You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by fi...@apache.org on 2013/05/24 01:41:22 UTC
[01/38] git commit: merged in testrunner work
Updated Branches:
refs/heads/master2 f7965d15a -> c65a9ced5
merged in testrunner work
Project: http://git-wip-us.apache.org/repos/asf/cordova-cli/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-cli/commit/d00f202f
Tree: http://git-wip-us.apache.org/repos/asf/cordova-cli/tree/d00f202f
Diff: http://git-wip-us.apache.org/repos/asf/cordova-cli/diff/d00f202f
Branch: refs/heads/master2
Commit: d00f202f39744ae759d4608e9d02480bdae7063c
Parents: f7965d1
Author: Fil Maj <ma...@gmail.com>
Authored: Wed May 22 11:40:27 2013 -0700
Committer: Fil Maj <ma...@gmail.com>
Committed: Thu May 23 15:17:27 2013 -0700
----------------------------------------------------------------------
.gitignore | 2 +-
package.json | 8 ++++----
src/compile.js | 2 --
test_runner.js | 37 +++++++++++++++++++++++++++++++++++++
4 files changed, 42 insertions(+), 7 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/d00f202f/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index 07b36d5..3e180c5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,6 +13,6 @@ lib/cordova-wp8/example
spec/fixtures/*
.gitcore
*.jar
-
+spec_tmp
# avoid npm pack issues
.gitignore
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/d00f202f/package.json
----------------------------------------------------------------------
diff --git a/package.json b/package.json
index 295f27c..24789be 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"cordova": "./bin/cordova"
},
"scripts": {
- "test": "./node_modules/jasmine-node/bin/jasmine-node --color spec/cordova-cli",
+ "test": "node test_runner.js",
"install": "node bootstrap.js"
},
"repository": {
@@ -23,8 +23,8 @@
"dependencies": {
"colors":">=0.6.0",
"elementtree":"0.1.3",
- "plugman":"0.6.1",
- "plist":"git+https://github.com/filmaj/node-plist.git",
+ "plugman":"0.7.7",
+ "plist":"0.4.x",
"xcode":"0.5.1",
"express":"3.0",
"shelljs":"0.1.2",
@@ -36,7 +36,7 @@
"open": "0.0.3"
},
"devDependencies": {
- "jasmine-node":"latest"
+ "jasmine-node":"1.3.x"
},
"author": "Anis Kadri",
"contributors": [
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/d00f202f/src/compile.js
----------------------------------------------------------------------
diff --git a/src/compile.js b/src/compile.js
index 1107fbc..2521811 100644
--- a/src/compile.js
+++ b/src/compile.js
@@ -82,5 +82,3 @@ module.exports = function compile(platforms, callback) {
shell_out_to_debug(projectRoot, platform, end);
});
};
-
-
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/d00f202f/test_runner.js
----------------------------------------------------------------------
diff --git a/test_runner.js b/test_runner.js
new file mode 100644
index 0000000..ba7e29d
--- /dev/null
+++ b/test_runner.js
@@ -0,0 +1,37 @@
+var platform = require('./src/platform'),
+ n = require('ncallbacks'),
+ path = require('path'),
+ shell = require('shelljs'),
+ platforms = require('./platforms');
+
+var specs = [];
+var supported = [];
+
+// stupid bs, jasmine-node cant accept multiple directories /facepalm
+var tmp = path.join(__dirname, 'spec_tmp');
+shell.rm('-rf', tmp);
+shell.mkdir('-p', path.join(tmp, 'platform-script'));
+shell.cp('-r', path.join(__dirname, 'spec', 'fixtures'), tmp);
+
+var end = n(platforms.length, function() {
+ console.log('Testing core cli and following platforms: ' + supported.join(', '));
+ var cmd = path.join(__dirname, 'node_modules', 'jasmine-node', 'bin', 'jasmine-node') + ' --color ' + tmp;
+ specs.forEach(function(s) {
+ var p = path.join(__dirname, s);
+ shell.cp('-r', p, path.join(tmp, 'platform-script'));
+ });
+ shell.cp('-r', path.join(__dirname, 'spec', 'cordova-cli'), tmp);
+ shell.exec(cmd, {async:true, silent:false}, function(code, output) {
+ });
+});
+console.log('Determining which platforms to run tests for...');
+platforms.forEach(function(p) {
+ platform.supports(p, function(e) {
+ if (e) {
+ } else {
+ specs.push('spec/platform-script/' + p);
+ supported.push(p);
+ }
+ end();
+ });
+});
[32/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyConnection.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyConnection.java
new file mode 100644
index 0000000..fccd14f
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyConnection.java
@@ -0,0 +1,579 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.spdy;
+
+import com.squareup.okhttp.internal.NamedRunnable;
+import com.squareup.okhttp.internal.Util;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.Executors.defaultThreadFactory;
+
+/**
+ * A socket connection to a remote peer. A connection hosts streams which can
+ * send and receive data.
+ *
+ * <p>Many methods in this API are <strong>synchronous:</strong> the call is
+ * completed before the method returns. This is typical for Java but atypical
+ * for SPDY. This is motivated by exception transparency: an IOException that
+ * was triggered by a certain caller can be caught and handled by that caller.
+ */
+public final class SpdyConnection implements Closeable {
+
+ // Internal state of this connection is guarded by 'this'. No blocking
+ // operations may be performed while holding this lock!
+ //
+ // Socket writes are guarded by spdyWriter.
+ //
+ // Socket reads are unguarded but are only made by the reader thread.
+ //
+ // Certain operations (like SYN_STREAM) need to synchronize on both the
+ // spdyWriter (to do blocking I/O) and this (to create streams). Such
+ // operations must synchronize on 'this' last. This ensures that we never
+ // wait for a blocking operation while holding 'this'.
+
+ static final int FLAG_FIN = 0x1;
+ static final int FLAG_UNIDIRECTIONAL = 0x2;
+
+ static final int TYPE_DATA = 0x0;
+ static final int TYPE_SYN_STREAM = 0x1;
+ static final int TYPE_SYN_REPLY = 0x2;
+ static final int TYPE_RST_STREAM = 0x3;
+ static final int TYPE_SETTINGS = 0x4;
+ static final int TYPE_NOOP = 0x5;
+ static final int TYPE_PING = 0x6;
+ static final int TYPE_GOAWAY = 0x7;
+ static final int TYPE_HEADERS = 0x8;
+ static final int TYPE_WINDOW_UPDATE = 0x9;
+ static final int TYPE_CREDENTIAL = 0x10;
+ static final int VERSION = 3;
+
+ static final int GOAWAY_OK = 0;
+ static final int GOAWAY_PROTOCOL_ERROR = 1;
+ static final int GOAWAY_INTERNAL_ERROR = 2;
+
+ private static final ExecutorService executor =
+ new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
+ new SynchronousQueue<Runnable>(), defaultThreadFactory());
+
+ /** True if this peer initiated the connection. */
+ final boolean client;
+
+ /**
+ * User code to run in response to an incoming stream. Callbacks must not be
+ * run on the callback executor.
+ */
+ private final IncomingStreamHandler handler;
+ private final SpdyReader spdyReader;
+ private final SpdyWriter spdyWriter;
+
+ private final Map<Integer, SpdyStream> streams = new HashMap<Integer, SpdyStream>();
+ private final String hostName;
+ private int lastGoodStreamId;
+ private int nextStreamId;
+ private boolean shutdown;
+ private long idleStartTimeNs = System.nanoTime();
+
+ /** Lazily-created map of in-flight pings awaiting a response. Guarded by this. */
+ private Map<Integer, Ping> pings;
+ private int nextPingId;
+
+ /** Lazily-created settings for this connection. */
+ Settings settings;
+
+ private SpdyConnection(Builder builder) {
+ client = builder.client;
+ handler = builder.handler;
+ spdyReader = new SpdyReader(builder.in);
+ spdyWriter = new SpdyWriter(builder.out);
+ nextStreamId = builder.client ? 1 : 2;
+ nextPingId = builder.client ? 1 : 2;
+
+ hostName = builder.hostName;
+
+ new Thread(new Reader(), "Spdy Reader " + hostName).start();
+ }
+
+ /**
+ * Returns the number of {@link SpdyStream#isOpen() open streams} on this
+ * connection.
+ */
+ public synchronized int openStreamCount() {
+ return streams.size();
+ }
+
+ private synchronized SpdyStream getStream(int id) {
+ return streams.get(id);
+ }
+
+ synchronized SpdyStream removeStream(int streamId) {
+ SpdyStream stream = streams.remove(streamId);
+ if (stream != null && streams.isEmpty()) {
+ setIdle(true);
+ }
+ return stream;
+ }
+
+ private synchronized void setIdle(boolean value) {
+ idleStartTimeNs = value ? System.nanoTime() : 0L;
+ }
+
+ /** Returns true if this connection is idle. */
+ public synchronized boolean isIdle() {
+ return idleStartTimeNs != 0L;
+ }
+
+ /** Returns the time in ns when this connection became idle or 0L if connection is not idle. */
+ public synchronized long getIdleStartTimeNs() {
+ return idleStartTimeNs;
+ }
+
+ /**
+ * Returns a new locally-initiated stream.
+ *
+ * @param out true to create an output stream that we can use to send data
+ * to the remote peer. Corresponds to {@code FLAG_FIN}.
+ * @param in true to create an input stream that the remote peer can use to
+ * send data to us. Corresponds to {@code FLAG_UNIDIRECTIONAL}.
+ */
+ public SpdyStream newStream(List<String> requestHeaders, boolean out, boolean in)
+ throws IOException {
+ int flags = (out ? 0 : FLAG_FIN) | (in ? 0 : FLAG_UNIDIRECTIONAL);
+ int associatedStreamId = 0; // TODO: permit the caller to specify an associated stream?
+ int priority = 0; // TODO: permit the caller to specify a priority?
+ int slot = 0; // TODO: permit the caller to specify a slot?
+ SpdyStream stream;
+ int streamId;
+
+ synchronized (spdyWriter) {
+ synchronized (this) {
+ if (shutdown) {
+ throw new IOException("shutdown");
+ }
+ streamId = nextStreamId;
+ nextStreamId += 2;
+ stream = new SpdyStream(streamId, this, flags, priority, slot, requestHeaders, settings);
+ if (stream.isOpen()) {
+ streams.put(streamId, stream);
+ setIdle(false);
+ }
+ }
+
+ spdyWriter.synStream(flags, streamId, associatedStreamId, priority, slot, requestHeaders);
+ }
+
+ return stream;
+ }
+
+ void writeSynReply(int streamId, int flags, List<String> alternating) throws IOException {
+ spdyWriter.synReply(flags, streamId, alternating);
+ }
+
+ /** Writes a complete data frame. */
+ void writeFrame(byte[] bytes, int offset, int length) throws IOException {
+ synchronized (spdyWriter) {
+ spdyWriter.out.write(bytes, offset, length);
+ }
+ }
+
+ void writeSynResetLater(final int streamId, final int statusCode) {
+ executor.submit(
+ new NamedRunnable(String.format("Spdy Writer %s stream %d", hostName, streamId)) {
+ @Override public void execute() {
+ try {
+ writeSynReset(streamId, statusCode);
+ } catch (IOException ignored) {
+ }
+ }
+ });
+ }
+
+ void writeSynReset(int streamId, int statusCode) throws IOException {
+ spdyWriter.rstStream(streamId, statusCode);
+ }
+
+ void writeWindowUpdateLater(final int streamId, final int deltaWindowSize) {
+ executor.submit(
+ new NamedRunnable(String.format("Spdy Writer %s stream %d", hostName, streamId)) {
+ @Override public void execute() {
+ try {
+ writeWindowUpdate(streamId, deltaWindowSize);
+ } catch (IOException ignored) {
+ }
+ }
+ });
+ }
+
+ void writeWindowUpdate(int streamId, int deltaWindowSize) throws IOException {
+ spdyWriter.windowUpdate(streamId, deltaWindowSize);
+ }
+
+ /**
+ * Sends a ping frame to the peer. Use the returned object to await the
+ * ping's response and observe its round trip time.
+ */
+ public Ping ping() throws IOException {
+ Ping ping = new Ping();
+ int pingId;
+ synchronized (this) {
+ if (shutdown) {
+ throw new IOException("shutdown");
+ }
+ pingId = nextPingId;
+ nextPingId += 2;
+ if (pings == null) pings = new HashMap<Integer, Ping>();
+ pings.put(pingId, ping);
+ }
+ writePing(pingId, ping);
+ return ping;
+ }
+
+ private void writePingLater(final int streamId, final Ping ping) {
+ executor.submit(new NamedRunnable(String.format("Spdy Writer %s ping %d", hostName, streamId)) {
+ @Override public void execute() {
+ try {
+ writePing(streamId, ping);
+ } catch (IOException ignored) {
+ }
+ }
+ });
+ }
+
+ private void writePing(int id, Ping ping) throws IOException {
+ synchronized (spdyWriter) {
+ // Observe the sent time immediately before performing I/O.
+ if (ping != null) ping.send();
+ spdyWriter.ping(0, id);
+ }
+ }
+
+ private synchronized Ping removePing(int id) {
+ return pings != null ? pings.remove(id) : null;
+ }
+
+ /** Sends a noop frame to the peer. */
+ public void noop() throws IOException {
+ spdyWriter.noop();
+ }
+
+ public void flush() throws IOException {
+ synchronized (spdyWriter) {
+ spdyWriter.out.flush();
+ }
+ }
+
+ /**
+ * Degrades this connection such that new streams can neither be created
+ * locally, nor accepted from the remote peer. Existing streams are not
+ * impacted. This is intended to permit an endpoint to gracefully stop
+ * accepting new requests without harming previously established streams.
+ *
+ * @param statusCode one of {@link #GOAWAY_OK}, {@link
+ * #GOAWAY_INTERNAL_ERROR} or {@link #GOAWAY_PROTOCOL_ERROR}.
+ */
+ public void shutdown(int statusCode) throws IOException {
+ synchronized (spdyWriter) {
+ int lastGoodStreamId;
+ synchronized (this) {
+ if (shutdown) {
+ return;
+ }
+ shutdown = true;
+ lastGoodStreamId = this.lastGoodStreamId;
+ }
+ spdyWriter.goAway(0, lastGoodStreamId, statusCode);
+ }
+ }
+
+ /**
+ * Closes this connection. This cancels all open streams and unanswered
+ * pings. It closes the underlying input and output streams and shuts down
+ * internal executor services.
+ */
+ @Override public void close() throws IOException {
+ close(GOAWAY_OK, SpdyStream.RST_CANCEL);
+ }
+
+ private void close(int shutdownStatusCode, int rstStatusCode) throws IOException {
+ assert (!Thread.holdsLock(this));
+ IOException thrown = null;
+ try {
+ shutdown(shutdownStatusCode);
+ } catch (IOException e) {
+ thrown = e;
+ }
+
+ SpdyStream[] streamsToClose = null;
+ Ping[] pingsToCancel = null;
+ synchronized (this) {
+ if (!streams.isEmpty()) {
+ streamsToClose = streams.values().toArray(new SpdyStream[streams.size()]);
+ streams.clear();
+ setIdle(false);
+ }
+ if (pings != null) {
+ pingsToCancel = pings.values().toArray(new Ping[pings.size()]);
+ pings = null;
+ }
+ }
+
+ if (streamsToClose != null) {
+ for (SpdyStream stream : streamsToClose) {
+ try {
+ stream.close(rstStatusCode);
+ } catch (IOException e) {
+ if (thrown != null) thrown = e;
+ }
+ }
+ }
+
+ if (pingsToCancel != null) {
+ for (Ping ping : pingsToCancel) {
+ ping.cancel();
+ }
+ }
+
+ try {
+ spdyReader.close();
+ } catch (IOException e) {
+ thrown = e;
+ }
+ try {
+ spdyWriter.close();
+ } catch (IOException e) {
+ if (thrown == null) thrown = e;
+ }
+
+ if (thrown != null) throw thrown;
+ }
+
+ public static class Builder {
+ private String hostName;
+ private InputStream in;
+ private OutputStream out;
+ private IncomingStreamHandler handler = IncomingStreamHandler.REFUSE_INCOMING_STREAMS;
+ public boolean client;
+
+ public Builder(boolean client, Socket socket) throws IOException {
+ this("", client, socket.getInputStream(), socket.getOutputStream());
+ }
+
+ public Builder(boolean client, InputStream in, OutputStream out) {
+ this("", client, in, out);
+ }
+
+ /**
+ * @param client true if this peer initiated the connection; false if
+ * this peer accepted the connection.
+ */
+ public Builder(String hostName, boolean client, Socket socket) throws IOException {
+ this(hostName, client, socket.getInputStream(), socket.getOutputStream());
+ }
+
+ /**
+ * @param client true if this peer initiated the connection; false if this
+ * peer accepted the connection.
+ */
+ public Builder(String hostName, boolean client, InputStream in, OutputStream out) {
+ this.hostName = hostName;
+ this.client = client;
+ this.in = in;
+ this.out = out;
+ }
+
+ public Builder handler(IncomingStreamHandler handler) {
+ this.handler = handler;
+ return this;
+ }
+
+ public SpdyConnection build() {
+ return new SpdyConnection(this);
+ }
+ }
+
+ private class Reader implements Runnable, SpdyReader.Handler {
+ @Override public void run() {
+ int shutdownStatusCode = GOAWAY_INTERNAL_ERROR;
+ int rstStatusCode = SpdyStream.RST_INTERNAL_ERROR;
+ try {
+ while (spdyReader.nextFrame(this)) {
+ }
+ shutdownStatusCode = GOAWAY_OK;
+ rstStatusCode = SpdyStream.RST_CANCEL;
+ } catch (IOException e) {
+ shutdownStatusCode = GOAWAY_PROTOCOL_ERROR;
+ rstStatusCode = SpdyStream.RST_PROTOCOL_ERROR;
+ } finally {
+ try {
+ close(shutdownStatusCode, rstStatusCode);
+ } catch (IOException ignored) {
+ }
+ }
+ }
+
+ @Override public void data(int flags, int streamId, InputStream in, int length)
+ throws IOException {
+ SpdyStream dataStream = getStream(streamId);
+ if (dataStream == null) {
+ writeSynResetLater(streamId, SpdyStream.RST_INVALID_STREAM);
+ Util.skipByReading(in, length);
+ return;
+ }
+ dataStream.receiveData(in, length);
+ if ((flags & SpdyConnection.FLAG_FIN) != 0) {
+ dataStream.receiveFin();
+ }
+ }
+
+ @Override
+ public void synStream(int flags, int streamId, int associatedStreamId, int priority, int slot,
+ List<String> nameValueBlock) {
+ final SpdyStream synStream;
+ final SpdyStream previous;
+ synchronized (SpdyConnection.this) {
+ synStream =
+ new SpdyStream(streamId, SpdyConnection.this, flags, priority, slot, nameValueBlock,
+ settings);
+ if (shutdown) {
+ return;
+ }
+ lastGoodStreamId = streamId;
+ previous = streams.put(streamId, synStream);
+ }
+ if (previous != null) {
+ previous.closeLater(SpdyStream.RST_PROTOCOL_ERROR);
+ removeStream(streamId);
+ return;
+ }
+
+ executor.submit(
+ new NamedRunnable(String.format("Callback %s stream %d", hostName, streamId)) {
+ @Override public void execute() {
+ try {
+ handler.receive(synStream);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ }
+
+ @Override public void synReply(int flags, int streamId, List<String> nameValueBlock)
+ throws IOException {
+ SpdyStream replyStream = getStream(streamId);
+ if (replyStream == null) {
+ writeSynResetLater(streamId, SpdyStream.RST_INVALID_STREAM);
+ return;
+ }
+ replyStream.receiveReply(nameValueBlock);
+ if ((flags & SpdyConnection.FLAG_FIN) != 0) {
+ replyStream.receiveFin();
+ }
+ }
+
+ @Override public void headers(int flags, int streamId, List<String> nameValueBlock)
+ throws IOException {
+ SpdyStream replyStream = getStream(streamId);
+ if (replyStream != null) {
+ replyStream.receiveHeaders(nameValueBlock);
+ }
+ }
+
+ @Override public void rstStream(int flags, int streamId, int statusCode) {
+ SpdyStream rstStream = removeStream(streamId);
+ if (rstStream != null) {
+ rstStream.receiveRstStream(statusCode);
+ }
+ }
+
+ @Override public void settings(int flags, Settings newSettings) {
+ SpdyStream[] streamsToNotify = null;
+ synchronized (SpdyConnection.this) {
+ if (settings == null || (flags & Settings.FLAG_CLEAR_PREVIOUSLY_PERSISTED_SETTINGS) != 0) {
+ settings = newSettings;
+ } else {
+ settings.merge(newSettings);
+ }
+ if (!streams.isEmpty()) {
+ streamsToNotify = streams.values().toArray(new SpdyStream[streams.size()]);
+ }
+ }
+ if (streamsToNotify != null) {
+ for (SpdyStream stream : streamsToNotify) {
+ // The synchronization here is ugly. We need to synchronize on 'this' to guard
+ // reads to 'settings'. We synchronize on 'stream' to guard the state change.
+ // And we need to acquire the 'stream' lock first, since that may block.
+ synchronized (stream) {
+ synchronized (this) {
+ stream.receiveSettings(settings);
+ }
+ }
+ }
+ }
+ }
+
+ @Override public void noop() {
+ }
+
+ @Override public void ping(int flags, int streamId) {
+ if (client != (streamId % 2 == 1)) {
+ // Respond to a client ping if this is a server and vice versa.
+ writePingLater(streamId, null);
+ } else {
+ Ping ping = removePing(streamId);
+ if (ping != null) {
+ ping.receive();
+ }
+ }
+ }
+
+ @Override public void goAway(int flags, int lastGoodStreamId, int statusCode) {
+ synchronized (SpdyConnection.this) {
+ shutdown = true;
+
+ // Fail all streams created after the last good stream ID.
+ for (Iterator<Map.Entry<Integer, SpdyStream>> i = streams.entrySet().iterator();
+ i.hasNext(); ) {
+ Map.Entry<Integer, SpdyStream> entry = i.next();
+ int streamId = entry.getKey();
+ if (streamId > lastGoodStreamId && entry.getValue().isLocallyInitiated()) {
+ entry.getValue().receiveRstStream(SpdyStream.RST_REFUSED_STREAM);
+ i.remove();
+ }
+ }
+ }
+ }
+
+ @Override public void windowUpdate(int flags, int streamId, int deltaWindowSize) {
+ SpdyStream stream = getStream(streamId);
+ if (stream != null) {
+ stream.receiveWindowUpdate(deltaWindowSize);
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyReader.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyReader.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyReader.java
new file mode 100644
index 0000000..7d3f2bd
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyReader.java
@@ -0,0 +1,326 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.spdy;
+
+import com.squareup.okhttp.internal.Util;
+import java.io.Closeable;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.ProtocolException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Logger;
+import java.util.zip.DataFormatException;
+import java.util.zip.Inflater;
+import java.util.zip.InflaterInputStream;
+
+/** Read spdy/3 frames. */
+final class SpdyReader implements Closeable {
+ static final byte[] DICTIONARY;
+ static {
+ try {
+ DICTIONARY = ("\u0000\u0000\u0000\u0007options\u0000\u0000\u0000\u0004hea"
+ + "d\u0000\u0000\u0000\u0004post\u0000\u0000\u0000\u0003put\u0000\u0000\u0000\u0006dele"
+ + "te\u0000\u0000\u0000\u0005trace\u0000\u0000\u0000\u0006accept\u0000\u0000\u0000"
+ + "\u000Eaccept-charset\u0000\u0000\u0000\u000Faccept-encoding\u0000\u0000\u0000\u000Fa"
+ + "ccept-language\u0000\u0000\u0000\raccept-ranges\u0000\u0000\u0000\u0003age\u0000"
+ + "\u0000\u0000\u0005allow\u0000\u0000\u0000\rauthorization\u0000\u0000\u0000\rcache-co"
+ + "ntrol\u0000\u0000\u0000\nconnection\u0000\u0000\u0000\fcontent-base\u0000\u0000"
+ + "\u0000\u0010content-encoding\u0000\u0000\u0000\u0010content-language\u0000\u0000"
+ + "\u0000\u000Econtent-length\u0000\u0000\u0000\u0010content-location\u0000\u0000\u0000"
+ + "\u000Bcontent-md5\u0000\u0000\u0000\rcontent-range\u0000\u0000\u0000\fcontent-type"
+ + "\u0000\u0000\u0000\u0004date\u0000\u0000\u0000\u0004etag\u0000\u0000\u0000\u0006expe"
+ + "ct\u0000\u0000\u0000\u0007expires\u0000\u0000\u0000\u0004from\u0000\u0000\u0000"
+ + "\u0004host\u0000\u0000\u0000\bif-match\u0000\u0000\u0000\u0011if-modified-since"
+ + "\u0000\u0000\u0000\rif-none-match\u0000\u0000\u0000\bif-range\u0000\u0000\u0000"
+ + "\u0013if-unmodified-since\u0000\u0000\u0000\rlast-modified\u0000\u0000\u0000\blocati"
+ + "on\u0000\u0000\u0000\fmax-forwards\u0000\u0000\u0000\u0006pragma\u0000\u0000\u0000"
+ + "\u0012proxy-authenticate\u0000\u0000\u0000\u0013proxy-authorization\u0000\u0000"
+ + "\u0000\u0005range\u0000\u0000\u0000\u0007referer\u0000\u0000\u0000\u000Bretry-after"
+ + "\u0000\u0000\u0000\u0006server\u0000\u0000\u0000\u0002te\u0000\u0000\u0000\u0007trai"
+ + "ler\u0000\u0000\u0000\u0011transfer-encoding\u0000\u0000\u0000\u0007upgrade\u0000"
+ + "\u0000\u0000\nuser-agent\u0000\u0000\u0000\u0004vary\u0000\u0000\u0000\u0003via"
+ + "\u0000\u0000\u0000\u0007warning\u0000\u0000\u0000\u0010www-authenticate\u0000\u0000"
+ + "\u0000\u0006method\u0000\u0000\u0000\u0003get\u0000\u0000\u0000\u0006status\u0000"
+ + "\u0000\u0000\u0006200 OK\u0000\u0000\u0000\u0007version\u0000\u0000\u0000\bHTTP/1.1"
+ + "\u0000\u0000\u0000\u0003url\u0000\u0000\u0000\u0006public\u0000\u0000\u0000\nset-coo"
+ + "kie\u0000\u0000\u0000\nkeep-alive\u0000\u0000\u0000\u0006origin100101201202205206300"
+ + "302303304305306307402405406407408409410411412413414415416417502504505203 Non-Authori"
+ + "tative Information204 No Content301 Moved Permanently400 Bad Request401 Unauthorized"
+ + "403 Forbidden404 Not Found500 Internal Server Error501 Not Implemented503 Service Un"
+ + "availableJan Feb Mar Apr May Jun Jul Aug Sept Oct Nov Dec 00:00:00 Mon, Tue, Wed, Th"
+ + "u, Fri, Sat, Sun, GMTchunked,text/html,image/png,image/jpg,image/gif,application/xml"
+ + ",application/xhtml+xml,text/plain,text/javascript,publicprivatemax-age=gzip,deflate,"
+ + "sdchcharset=utf-8charset=iso-8859-1,utf-,*,enq=0.").getBytes(Util.UTF_8.name());
+ } catch (UnsupportedEncodingException e) {
+ throw new AssertionError();
+ }
+ }
+
+ private final DataInputStream in;
+ private final DataInputStream nameValueBlockIn;
+ private int compressedLimit;
+
+ SpdyReader(InputStream in) {
+ this.in = new DataInputStream(in);
+ this.nameValueBlockIn = newNameValueBlockStream();
+ }
+
+ /**
+ * Send the next frame to {@code handler}. Returns true unless there are no
+ * more frames on the stream.
+ */
+ public boolean nextFrame(Handler handler) throws IOException {
+ int w1;
+ try {
+ w1 = in.readInt();
+ } catch (IOException e) {
+ return false; // This might be a normal socket close.
+ }
+ int w2 = in.readInt();
+
+ boolean control = (w1 & 0x80000000) != 0;
+ int flags = (w2 & 0xff000000) >>> 24;
+ int length = (w2 & 0xffffff);
+
+ if (control) {
+ int version = (w1 & 0x7fff0000) >>> 16;
+ int type = (w1 & 0xffff);
+
+ if (version != 3) {
+ throw new ProtocolException("version != 3: " + version);
+ }
+
+ switch (type) {
+ case SpdyConnection.TYPE_SYN_STREAM:
+ readSynStream(handler, flags, length);
+ return true;
+
+ case SpdyConnection.TYPE_SYN_REPLY:
+ readSynReply(handler, flags, length);
+ return true;
+
+ case SpdyConnection.TYPE_RST_STREAM:
+ readRstStream(handler, flags, length);
+ return true;
+
+ case SpdyConnection.TYPE_SETTINGS:
+ readSettings(handler, flags, length);
+ return true;
+
+ case SpdyConnection.TYPE_NOOP:
+ if (length != 0) throw ioException("TYPE_NOOP length: %d != 0", length);
+ handler.noop();
+ return true;
+
+ case SpdyConnection.TYPE_PING:
+ readPing(handler, flags, length);
+ return true;
+
+ case SpdyConnection.TYPE_GOAWAY:
+ readGoAway(handler, flags, length);
+ return true;
+
+ case SpdyConnection.TYPE_HEADERS:
+ readHeaders(handler, flags, length);
+ return true;
+
+ case SpdyConnection.TYPE_WINDOW_UPDATE:
+ readWindowUpdate(handler, flags, length);
+ return true;
+
+ case SpdyConnection.TYPE_CREDENTIAL:
+ Util.skipByReading(in, length);
+ throw new UnsupportedOperationException("TODO"); // TODO: implement
+
+ default:
+ throw new IOException("Unexpected frame");
+ }
+ } else {
+ int streamId = w1 & 0x7fffffff;
+ handler.data(flags, streamId, in, length);
+ return true;
+ }
+ }
+
+ private void readSynStream(Handler handler, int flags, int length) throws IOException {
+ int w1 = in.readInt();
+ int w2 = in.readInt();
+ int s3 = in.readShort();
+ int streamId = w1 & 0x7fffffff;
+ int associatedStreamId = w2 & 0x7fffffff;
+ int priority = (s3 & 0xe000) >>> 13;
+ int slot = s3 & 0xff;
+ List<String> nameValueBlock = readNameValueBlock(length - 10);
+ handler.synStream(flags, streamId, associatedStreamId, priority, slot, nameValueBlock);
+ }
+
+ private void readSynReply(Handler handler, int flags, int length) throws IOException {
+ int w1 = in.readInt();
+ int streamId = w1 & 0x7fffffff;
+ List<String> nameValueBlock = readNameValueBlock(length - 4);
+ handler.synReply(flags, streamId, nameValueBlock);
+ }
+
+ private void readRstStream(Handler handler, int flags, int length) throws IOException {
+ if (length != 8) throw ioException("TYPE_RST_STREAM length: %d != 8", length);
+ int streamId = in.readInt() & 0x7fffffff;
+ int statusCode = in.readInt();
+ handler.rstStream(flags, streamId, statusCode);
+ }
+
+ private void readHeaders(Handler handler, int flags, int length) throws IOException {
+ int w1 = in.readInt();
+ int streamId = w1 & 0x7fffffff;
+ List<String> nameValueBlock = readNameValueBlock(length - 4);
+ handler.headers(flags, streamId, nameValueBlock);
+ }
+
+ private void readWindowUpdate(Handler handler, int flags, int length) throws IOException {
+ if (length != 8) throw ioException("TYPE_WINDOW_UPDATE length: %d != 8", length);
+ int w1 = in.readInt();
+ int w2 = in.readInt();
+ int streamId = w1 & 0x7fffffff;
+ int deltaWindowSize = w2 & 0x7fffffff;
+ handler.windowUpdate(flags, streamId, deltaWindowSize);
+ }
+
+ private DataInputStream newNameValueBlockStream() {
+ // Limit the inflater input stream to only those bytes in the Name/Value block.
+ final InputStream throttleStream = new InputStream() {
+ @Override public int read() throws IOException {
+ return Util.readSingleByte(this);
+ }
+
+ @Override public int read(byte[] buffer, int offset, int byteCount) throws IOException {
+ byteCount = Math.min(byteCount, compressedLimit);
+ int consumed = in.read(buffer, offset, byteCount);
+ compressedLimit -= consumed;
+ return consumed;
+ }
+
+ @Override public void close() throws IOException {
+ in.close();
+ }
+ };
+
+ // Subclass inflater to install a dictionary when it's needed.
+ Inflater inflater = new Inflater() {
+ @Override
+ public int inflate(byte[] buffer, int offset, int count) throws DataFormatException {
+ int result = super.inflate(buffer, offset, count);
+ if (result == 0 && needsDictionary()) {
+ setDictionary(DICTIONARY);
+ result = super.inflate(buffer, offset, count);
+ }
+ return result;
+ }
+ };
+
+ return new DataInputStream(new InflaterInputStream(throttleStream, inflater));
+ }
+
+ private List<String> readNameValueBlock(int length) throws IOException {
+ this.compressedLimit += length;
+ try {
+ int numberOfPairs = nameValueBlockIn.readInt();
+ if (numberOfPairs < 0) {
+ Logger.getLogger(getClass().getName()).warning("numberOfPairs < 0: " + numberOfPairs);
+ throw ioException("numberOfPairs < 0");
+ }
+ List<String> entries = new ArrayList<String>(numberOfPairs * 2);
+ for (int i = 0; i < numberOfPairs; i++) {
+ String name = readString();
+ String values = readString();
+ if (name.length() == 0) throw ioException("name.length == 0");
+ if (values.length() == 0) throw ioException("values.length == 0");
+ entries.add(name);
+ entries.add(values);
+ }
+
+ if (compressedLimit != 0) {
+ Logger.getLogger(getClass().getName()).warning("compressedLimit > 0: " + compressedLimit);
+ }
+
+ return entries;
+ } catch (DataFormatException e) {
+ throw new IOException(e.getMessage());
+ }
+ }
+
+ private String readString() throws DataFormatException, IOException {
+ int length = nameValueBlockIn.readInt();
+ byte[] bytes = new byte[length];
+ Util.readFully(nameValueBlockIn, bytes);
+ return new String(bytes, 0, length, "UTF-8");
+ }
+
+ private void readPing(Handler handler, int flags, int length) throws IOException {
+ if (length != 4) throw ioException("TYPE_PING length: %d != 4", length);
+ int id = in.readInt();
+ handler.ping(flags, id);
+ }
+
+ private void readGoAway(Handler handler, int flags, int length) throws IOException {
+ if (length != 8) throw ioException("TYPE_GOAWAY length: %d != 8", length);
+ int lastGoodStreamId = in.readInt() & 0x7fffffff;
+ int statusCode = in.readInt();
+ handler.goAway(flags, lastGoodStreamId, statusCode);
+ }
+
+ private void readSettings(Handler handler, int flags, int length) throws IOException {
+ int numberOfEntries = in.readInt();
+ if (length != 4 + 8 * numberOfEntries) {
+ throw ioException("TYPE_SETTINGS length: %d != 4 + 8 * %d", length, numberOfEntries);
+ }
+ Settings settings = new Settings();
+ for (int i = 0; i < numberOfEntries; i++) {
+ int w1 = in.readInt();
+ int value = in.readInt();
+ int idFlags = (w1 & 0xff000000) >>> 24;
+ int id = w1 & 0xffffff;
+ settings.set(id, idFlags, value);
+ }
+ handler.settings(flags, settings);
+ }
+
+ private static IOException ioException(String message, Object... args) throws IOException {
+ throw new IOException(String.format(message, args));
+ }
+
+ @Override public void close() throws IOException {
+ Util.closeAll(in, nameValueBlockIn);
+ }
+
+ public interface Handler {
+ void data(int flags, int streamId, InputStream in, int length) throws IOException;
+
+ void synStream(int flags, int streamId, int associatedStreamId, int priority, int slot,
+ List<String> nameValueBlock);
+
+ void synReply(int flags, int streamId, List<String> nameValueBlock) throws IOException;
+ void headers(int flags, int streamId, List<String> nameValueBlock) throws IOException;
+ void rstStream(int flags, int streamId, int statusCode);
+ void settings(int flags, Settings settings);
+ void noop();
+ void ping(int flags, int streamId);
+ void goAway(int flags, int lastGoodStreamId, int statusCode);
+ void windowUpdate(int flags, int streamId, int deltaWindowSize);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyStream.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyStream.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyStream.java
new file mode 100644
index 0000000..744a04e
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyStream.java
@@ -0,0 +1,733 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.spdy;
+
+import com.squareup.okhttp.internal.Util;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.io.OutputStream;
+import java.net.SocketTimeoutException;
+import java.util.ArrayList;
+import java.util.List;
+
+import static com.squareup.okhttp.internal.Util.checkOffsetAndCount;
+import static com.squareup.okhttp.internal.Util.pokeInt;
+import static java.nio.ByteOrder.BIG_ENDIAN;
+
+/** A logical bidirectional stream. */
+public final class SpdyStream {
+
+ // Internal state is guarded by this. No long-running or potentially
+ // blocking operations are performed while the lock is held.
+
+ private static final int DATA_FRAME_HEADER_LENGTH = 8;
+
+ private static final String[] STATUS_CODE_NAMES = {
+ null,
+ "PROTOCOL_ERROR",
+ "INVALID_STREAM",
+ "REFUSED_STREAM",
+ "UNSUPPORTED_VERSION",
+ "CANCEL",
+ "INTERNAL_ERROR",
+ "FLOW_CONTROL_ERROR",
+ "STREAM_IN_USE",
+ "STREAM_ALREADY_CLOSED",
+ "INVALID_CREDENTIALS",
+ "FRAME_TOO_LARGE"
+ };
+
+ public static final int RST_PROTOCOL_ERROR = 1;
+ public static final int RST_INVALID_STREAM = 2;
+ public static final int RST_REFUSED_STREAM = 3;
+ public static final int RST_UNSUPPORTED_VERSION = 4;
+ public static final int RST_CANCEL = 5;
+ public static final int RST_INTERNAL_ERROR = 6;
+ public static final int RST_FLOW_CONTROL_ERROR = 7;
+ public static final int RST_STREAM_IN_USE = 8;
+ public static final int RST_STREAM_ALREADY_CLOSED = 9;
+ public static final int RST_INVALID_CREDENTIALS = 10;
+ public static final int RST_FRAME_TOO_LARGE = 11;
+
+ /**
+ * The number of unacknowledged bytes at which the input stream will send
+ * the peer a {@code WINDOW_UPDATE} frame. Must be less than this client's
+ * window size, otherwise the remote peer will stop sending data on this
+ * stream. (Chrome 25 uses 5 MiB.)
+ */
+ public static final int WINDOW_UPDATE_THRESHOLD = Settings.DEFAULT_INITIAL_WINDOW_SIZE / 2;
+
+ private final int id;
+ private final SpdyConnection connection;
+ private final int priority;
+ private final int slot;
+ private long readTimeoutMillis = 0;
+ private int writeWindowSize;
+
+ /** Headers sent by the stream initiator. Immutable and non null. */
+ private final List<String> requestHeaders;
+
+ /** Headers sent in the stream reply. Null if reply is either not sent or not sent yet. */
+ private List<String> responseHeaders;
+
+ private final SpdyDataInputStream in = new SpdyDataInputStream();
+ private final SpdyDataOutputStream out = new SpdyDataOutputStream();
+
+ /**
+ * The reason why this stream was abnormally closed. If there are multiple
+ * reasons to abnormally close this stream (such as both peers closing it
+ * near-simultaneously) then this is the first reason known to this peer.
+ */
+ private int rstStatusCode = -1;
+
+ SpdyStream(int id, SpdyConnection connection, int flags, int priority, int slot,
+ List<String> requestHeaders, Settings settings) {
+ if (connection == null) throw new NullPointerException("connection == null");
+ if (requestHeaders == null) throw new NullPointerException("requestHeaders == null");
+ this.id = id;
+ this.connection = connection;
+ this.priority = priority;
+ this.slot = slot;
+ this.requestHeaders = requestHeaders;
+
+ if (isLocallyInitiated()) {
+ // I am the sender
+ in.finished = (flags & SpdyConnection.FLAG_UNIDIRECTIONAL) != 0;
+ out.finished = (flags & SpdyConnection.FLAG_FIN) != 0;
+ } else {
+ // I am the receiver
+ in.finished = (flags & SpdyConnection.FLAG_FIN) != 0;
+ out.finished = (flags & SpdyConnection.FLAG_UNIDIRECTIONAL) != 0;
+ }
+
+ setSettings(settings);
+ }
+
+ /**
+ * Returns true if this stream is open. A stream is open until either:
+ * <ul>
+ * <li>A {@code SYN_RESET} frame abnormally terminates the stream.
+ * <li>Both input and output streams have transmitted all data and
+ * headers.
+ * </ul>
+ * Note that the input stream may continue to yield data even after a stream
+ * reports itself as not open. This is because input data is buffered.
+ */
+ public synchronized boolean isOpen() {
+ if (rstStatusCode != -1) {
+ return false;
+ }
+ if ((in.finished || in.closed) && (out.finished || out.closed) && responseHeaders != null) {
+ return false;
+ }
+ return true;
+ }
+
+ /** Returns true if this stream was created by this peer. */
+ public boolean isLocallyInitiated() {
+ boolean streamIsClient = (id % 2 == 1);
+ return connection.client == streamIsClient;
+ }
+
+ public SpdyConnection getConnection() {
+ return connection;
+ }
+
+ public List<String> getRequestHeaders() {
+ return requestHeaders;
+ }
+
+ /**
+ * Returns the stream's response headers, blocking if necessary if they
+ * have not been received yet.
+ */
+ public synchronized List<String> getResponseHeaders() throws IOException {
+ try {
+ while (responseHeaders == null && rstStatusCode == -1) {
+ wait();
+ }
+ if (responseHeaders != null) {
+ return responseHeaders;
+ }
+ throw new IOException("stream was reset: " + rstStatusString());
+ } catch (InterruptedException e) {
+ InterruptedIOException rethrow = new InterruptedIOException();
+ rethrow.initCause(e);
+ throw rethrow;
+ }
+ }
+
+ /**
+ * Returns the reason why this stream was closed, or -1 if it closed
+ * normally or has not yet been closed. Valid reasons are {@link
+ * #RST_PROTOCOL_ERROR}, {@link #RST_INVALID_STREAM}, {@link
+ * #RST_REFUSED_STREAM}, {@link #RST_UNSUPPORTED_VERSION}, {@link
+ * #RST_CANCEL}, {@link #RST_INTERNAL_ERROR} and {@link
+ * #RST_FLOW_CONTROL_ERROR}.
+ */
+ public synchronized int getRstStatusCode() {
+ return rstStatusCode;
+ }
+
+ /**
+ * Sends a reply to an incoming stream.
+ *
+ * @param out true to create an output stream that we can use to send data
+ * to the remote peer. Corresponds to {@code FLAG_FIN}.
+ */
+ public void reply(List<String> responseHeaders, boolean out) throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+ int flags = 0;
+ synchronized (this) {
+ if (responseHeaders == null) {
+ throw new NullPointerException("responseHeaders == null");
+ }
+ if (isLocallyInitiated()) {
+ throw new IllegalStateException("cannot reply to a locally initiated stream");
+ }
+ if (this.responseHeaders != null) {
+ throw new IllegalStateException("reply already sent");
+ }
+ this.responseHeaders = responseHeaders;
+ if (!out) {
+ this.out.finished = true;
+ flags |= SpdyConnection.FLAG_FIN;
+ }
+ }
+ connection.writeSynReply(id, flags, responseHeaders);
+ }
+
+ /**
+ * Sets the maximum time to wait on input stream reads before failing with a
+ * {@code SocketTimeoutException}, or {@code 0} to wait indefinitely.
+ */
+ public void setReadTimeout(long readTimeoutMillis) {
+ this.readTimeoutMillis = readTimeoutMillis;
+ }
+
+ public long getReadTimeoutMillis() {
+ return readTimeoutMillis;
+ }
+
+ /** Returns an input stream that can be used to read data from the peer. */
+ public InputStream getInputStream() {
+ return in;
+ }
+
+ /**
+ * Returns an output stream that can be used to write data to the peer.
+ *
+ * @throws IllegalStateException if this stream was initiated by the peer
+ * and a {@link #reply} has not yet been sent.
+ */
+ public OutputStream getOutputStream() {
+ synchronized (this) {
+ if (responseHeaders == null && !isLocallyInitiated()) {
+ throw new IllegalStateException("reply before requesting the output stream");
+ }
+ }
+ return out;
+ }
+
+ /**
+ * Abnormally terminate this stream. This blocks until the {@code RST_STREAM}
+ * frame has been transmitted.
+ */
+ public void close(int rstStatusCode) throws IOException {
+ if (!closeInternal(rstStatusCode)) {
+ return; // Already closed.
+ }
+ connection.writeSynReset(id, rstStatusCode);
+ }
+
+ /**
+ * Abnormally terminate this stream. This enqueues a {@code RST_STREAM}
+ * frame and returns immediately.
+ */
+ public void closeLater(int rstStatusCode) {
+ if (!closeInternal(rstStatusCode)) {
+ return; // Already closed.
+ }
+ connection.writeSynResetLater(id, rstStatusCode);
+ }
+
+ /** Returns true if this stream was closed. */
+ private boolean closeInternal(int rstStatusCode) {
+ assert (!Thread.holdsLock(this));
+ synchronized (this) {
+ if (this.rstStatusCode != -1) {
+ return false;
+ }
+ if (in.finished && out.finished) {
+ return false;
+ }
+ this.rstStatusCode = rstStatusCode;
+ notifyAll();
+ }
+ connection.removeStream(id);
+ return true;
+ }
+
+ void receiveReply(List<String> strings) throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+ boolean streamInUseError = false;
+ boolean open = true;
+ synchronized (this) {
+ if (isLocallyInitiated() && responseHeaders == null) {
+ responseHeaders = strings;
+ open = isOpen();
+ notifyAll();
+ } else {
+ streamInUseError = true;
+ }
+ }
+ if (streamInUseError) {
+ closeLater(SpdyStream.RST_STREAM_IN_USE);
+ } else if (!open) {
+ connection.removeStream(id);
+ }
+ }
+
+ void receiveHeaders(List<String> headers) throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+ boolean protocolError = false;
+ synchronized (this) {
+ if (responseHeaders != null) {
+ List<String> newHeaders = new ArrayList<String>();
+ newHeaders.addAll(responseHeaders);
+ newHeaders.addAll(headers);
+ this.responseHeaders = newHeaders;
+ } else {
+ protocolError = true;
+ }
+ }
+ if (protocolError) {
+ closeLater(SpdyStream.RST_PROTOCOL_ERROR);
+ }
+ }
+
+ void receiveData(InputStream in, int length) throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+ this.in.receive(in, length);
+ }
+
+ void receiveFin() {
+ assert (!Thread.holdsLock(SpdyStream.this));
+ boolean open;
+ synchronized (this) {
+ this.in.finished = true;
+ open = isOpen();
+ notifyAll();
+ }
+ if (!open) {
+ connection.removeStream(id);
+ }
+ }
+
+ synchronized void receiveRstStream(int statusCode) {
+ if (rstStatusCode == -1) {
+ rstStatusCode = statusCode;
+ notifyAll();
+ }
+ }
+
+ private void setSettings(Settings settings) {
+ assert (Thread.holdsLock(connection)); // Because 'settings' is guarded by 'connection'.
+ this.writeWindowSize =
+ settings != null ? settings.getInitialWindowSize(Settings.DEFAULT_INITIAL_WINDOW_SIZE)
+ : Settings.DEFAULT_INITIAL_WINDOW_SIZE;
+ }
+
+ void receiveSettings(Settings settings) {
+ assert (Thread.holdsLock(this));
+ setSettings(settings);
+ notifyAll();
+ }
+
+ synchronized void receiveWindowUpdate(int deltaWindowSize) {
+ out.unacknowledgedBytes -= deltaWindowSize;
+ notifyAll();
+ }
+
+ private String rstStatusString() {
+ return rstStatusCode > 0 && rstStatusCode < STATUS_CODE_NAMES.length
+ ? STATUS_CODE_NAMES[rstStatusCode] : Integer.toString(rstStatusCode);
+ }
+
+ int getPriority() {
+ return priority;
+ }
+
+ int getSlot() {
+ return slot;
+ }
+
+ /**
+ * An input stream that reads the incoming data frames of a stream. Although
+ * this class uses synchronization to safely receive incoming data frames,
+ * it is not intended for use by multiple readers.
+ */
+ private final class SpdyDataInputStream extends InputStream {
+ // Store incoming data bytes in a circular buffer. When the buffer is
+ // empty, pos == -1. Otherwise pos is the first byte to read and limit
+ // is the first byte to write.
+ //
+ // { - - - X X X X - - - }
+ // ^ ^
+ // pos limit
+ //
+ // { X X X - - - - X X X }
+ // ^ ^
+ // limit pos
+
+ private final byte[] buffer = new byte[Settings.DEFAULT_INITIAL_WINDOW_SIZE];
+
+ /** the next byte to be read, or -1 if the buffer is empty. Never buffer.length */
+ private int pos = -1;
+
+ /** the last byte to be read. Never buffer.length */
+ private int limit;
+
+ /** True if the caller has closed this stream. */
+ private boolean closed;
+
+ /**
+ * True if either side has cleanly shut down this stream. We will
+ * receive no more bytes beyond those already in the buffer.
+ */
+ private boolean finished;
+
+ /**
+ * The total number of bytes consumed by the application (with {@link
+ * #read}), but not yet acknowledged by sending a {@code WINDOW_UPDATE}
+ * frame.
+ */
+ private int unacknowledgedBytes = 0;
+
+ @Override public int available() throws IOException {
+ synchronized (SpdyStream.this) {
+ checkNotClosed();
+ if (pos == -1) {
+ return 0;
+ } else if (limit > pos) {
+ return limit - pos;
+ } else {
+ return limit + (buffer.length - pos);
+ }
+ }
+ }
+
+ @Override public int read() throws IOException {
+ return Util.readSingleByte(this);
+ }
+
+ @Override public int read(byte[] b, int offset, int count) throws IOException {
+ synchronized (SpdyStream.this) {
+ checkOffsetAndCount(b.length, offset, count);
+ waitUntilReadable();
+ checkNotClosed();
+
+ if (pos == -1) {
+ return -1;
+ }
+
+ int copied = 0;
+
+ // drain from [pos..buffer.length)
+ if (limit <= pos) {
+ int bytesToCopy = Math.min(count, buffer.length - pos);
+ System.arraycopy(buffer, pos, b, offset, bytesToCopy);
+ pos += bytesToCopy;
+ copied += bytesToCopy;
+ if (pos == buffer.length) {
+ pos = 0;
+ }
+ }
+
+ // drain from [pos..limit)
+ if (copied < count) {
+ int bytesToCopy = Math.min(limit - pos, count - copied);
+ System.arraycopy(buffer, pos, b, offset + copied, bytesToCopy);
+ pos += bytesToCopy;
+ copied += bytesToCopy;
+ }
+
+ // Flow control: notify the peer that we're ready for more data!
+ unacknowledgedBytes += copied;
+ if (unacknowledgedBytes >= WINDOW_UPDATE_THRESHOLD) {
+ connection.writeWindowUpdateLater(id, unacknowledgedBytes);
+ unacknowledgedBytes = 0;
+ }
+
+ if (pos == limit) {
+ pos = -1;
+ limit = 0;
+ }
+
+ return copied;
+ }
+ }
+
+ /**
+ * Returns once the input stream is either readable or finished. Throws
+ * a {@link SocketTimeoutException} if the read timeout elapses before
+ * that happens.
+ */
+ private void waitUntilReadable() throws IOException {
+ long start = 0;
+ long remaining = 0;
+ if (readTimeoutMillis != 0) {
+ start = (System.nanoTime() / 1000000);
+ remaining = readTimeoutMillis;
+ }
+ try {
+ while (pos == -1 && !finished && !closed && rstStatusCode == -1) {
+ if (readTimeoutMillis == 0) {
+ SpdyStream.this.wait();
+ } else if (remaining > 0) {
+ SpdyStream.this.wait(remaining);
+ remaining = start + readTimeoutMillis - (System.nanoTime() / 1000000);
+ } else {
+ throw new SocketTimeoutException();
+ }
+ }
+ } catch (InterruptedException e) {
+ throw new InterruptedIOException();
+ }
+ }
+
+ void receive(InputStream in, int byteCount) throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+
+ if (byteCount == 0) {
+ return;
+ }
+
+ int pos;
+ int limit;
+ int firstNewByte;
+ boolean finished;
+ boolean flowControlError;
+ synchronized (SpdyStream.this) {
+ finished = this.finished;
+ pos = this.pos;
+ firstNewByte = this.limit;
+ limit = this.limit;
+ flowControlError = byteCount > buffer.length - available();
+ }
+
+ // If the peer sends more data than we can handle, discard it and close the connection.
+ if (flowControlError) {
+ Util.skipByReading(in, byteCount);
+ closeLater(SpdyStream.RST_FLOW_CONTROL_ERROR);
+ return;
+ }
+
+ // Discard data received after the stream is finished. It's probably a benign race.
+ if (finished) {
+ Util.skipByReading(in, byteCount);
+ return;
+ }
+
+ // Fill the buffer without holding any locks. First fill [limit..buffer.length) if that
+ // won't overwrite unread data. Then fill [limit..pos). We can't hold a lock, otherwise
+ // writes will be blocked until reads complete.
+ if (pos < limit) {
+ int firstCopyCount = Math.min(byteCount, buffer.length - limit);
+ Util.readFully(in, buffer, limit, firstCopyCount);
+ limit += firstCopyCount;
+ byteCount -= firstCopyCount;
+ if (limit == buffer.length) {
+ limit = 0;
+ }
+ }
+ if (byteCount > 0) {
+ Util.readFully(in, buffer, limit, byteCount);
+ limit += byteCount;
+ }
+
+ synchronized (SpdyStream.this) {
+ // Update the new limit, and mark the position as readable if necessary.
+ this.limit = limit;
+ if (this.pos == -1) {
+ this.pos = firstNewByte;
+ SpdyStream.this.notifyAll();
+ }
+ }
+ }
+
+ @Override public void close() throws IOException {
+ synchronized (SpdyStream.this) {
+ closed = true;
+ SpdyStream.this.notifyAll();
+ }
+ cancelStreamIfNecessary();
+ }
+
+ private void checkNotClosed() throws IOException {
+ if (closed) {
+ throw new IOException("stream closed");
+ }
+ if (rstStatusCode != -1) {
+ throw new IOException("stream was reset: " + rstStatusString());
+ }
+ }
+ }
+
+ private void cancelStreamIfNecessary() throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+ boolean open;
+ boolean cancel;
+ synchronized (this) {
+ cancel = !in.finished && in.closed && (out.finished || out.closed);
+ open = isOpen();
+ }
+ if (cancel) {
+ // RST this stream to prevent additional data from being sent. This
+ // is safe because the input stream is closed (we won't use any
+ // further bytes) and the output stream is either finished or closed
+ // (so RSTing both streams doesn't cause harm).
+ SpdyStream.this.close(RST_CANCEL);
+ } else if (!open) {
+ connection.removeStream(id);
+ }
+ }
+
+ /**
+ * An output stream that writes outgoing data frames of a stream. This class
+ * is not thread safe.
+ */
+ private final class SpdyDataOutputStream extends OutputStream {
+ private final byte[] buffer = new byte[8192];
+ private int pos = DATA_FRAME_HEADER_LENGTH;
+
+ /** True if the caller has closed this stream. */
+ private boolean closed;
+
+ /**
+ * True if either side has cleanly shut down this stream. We shall send
+ * no more bytes.
+ */
+ private boolean finished;
+
+ /**
+ * The total number of bytes written out to the peer, but not yet
+ * acknowledged with an incoming {@code WINDOW_UPDATE} frame. Writes
+ * block if they cause this to exceed the {@code WINDOW_SIZE}.
+ */
+ private int unacknowledgedBytes = 0;
+
+ @Override public void write(int b) throws IOException {
+ Util.writeSingleByte(this, b);
+ }
+
+ @Override public void write(byte[] bytes, int offset, int count) throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+ checkOffsetAndCount(bytes.length, offset, count);
+ checkNotClosed();
+
+ while (count > 0) {
+ if (pos == buffer.length) {
+ writeFrame(false);
+ }
+ int bytesToCopy = Math.min(count, buffer.length - pos);
+ System.arraycopy(bytes, offset, buffer, pos, bytesToCopy);
+ pos += bytesToCopy;
+ offset += bytesToCopy;
+ count -= bytesToCopy;
+ }
+ }
+
+ @Override public void flush() throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+ checkNotClosed();
+ if (pos > DATA_FRAME_HEADER_LENGTH) {
+ writeFrame(false);
+ connection.flush();
+ }
+ }
+
+ @Override public void close() throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+ synchronized (SpdyStream.this) {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ }
+ writeFrame(true);
+ connection.flush();
+ cancelStreamIfNecessary();
+ }
+
+ private void writeFrame(boolean last) throws IOException {
+ assert (!Thread.holdsLock(SpdyStream.this));
+
+ int length = pos - DATA_FRAME_HEADER_LENGTH;
+ synchronized (SpdyStream.this) {
+ waitUntilWritable(length, last);
+ unacknowledgedBytes += length;
+ }
+ int flags = 0;
+ if (last) {
+ flags |= SpdyConnection.FLAG_FIN;
+ }
+ pokeInt(buffer, 0, id & 0x7fffffff, BIG_ENDIAN);
+ pokeInt(buffer, 4, (flags & 0xff) << 24 | length & 0xffffff, BIG_ENDIAN);
+ connection.writeFrame(buffer, 0, pos);
+ pos = DATA_FRAME_HEADER_LENGTH;
+ }
+
+ /**
+ * Returns once the peer is ready to receive {@code count} bytes.
+ *
+ * @throws IOException if the stream was finished or closed, or the
+ * thread was interrupted.
+ */
+ private void waitUntilWritable(int count, boolean last) throws IOException {
+ try {
+ while (unacknowledgedBytes + count >= writeWindowSize) {
+ SpdyStream.this.wait(); // Wait until we receive a WINDOW_UPDATE.
+
+ // The stream may have been closed or reset while we were waiting!
+ if (!last && closed) {
+ throw new IOException("stream closed");
+ } else if (finished) {
+ throw new IOException("stream finished");
+ } else if (rstStatusCode != -1) {
+ throw new IOException("stream was reset: " + rstStatusString());
+ }
+ }
+ } catch (InterruptedException e) {
+ throw new InterruptedIOException();
+ }
+ }
+
+ private void checkNotClosed() throws IOException {
+ synchronized (SpdyStream.this) {
+ if (closed) {
+ throw new IOException("stream closed");
+ } else if (finished) {
+ throw new IOException("stream finished");
+ } else if (rstStatusCode != -1) {
+ throw new IOException("stream was reset: " + rstStatusString());
+ }
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyWriter.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyWriter.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyWriter.java
new file mode 100644
index 0000000..b3d1d1f
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/SpdyWriter.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.spdy;
+
+import com.squareup.okhttp.internal.Platform;
+import com.squareup.okhttp.internal.Util;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.zip.Deflater;
+
+/** Write spdy/3 frames. */
+final class SpdyWriter implements Closeable {
+ final DataOutputStream out;
+ private final ByteArrayOutputStream nameValueBlockBuffer;
+ private final DataOutputStream nameValueBlockOut;
+
+ SpdyWriter(OutputStream out) {
+ this.out = new DataOutputStream(out);
+
+ Deflater deflater = new Deflater();
+ deflater.setDictionary(SpdyReader.DICTIONARY);
+ nameValueBlockBuffer = new ByteArrayOutputStream();
+ nameValueBlockOut = new DataOutputStream(
+ Platform.get().newDeflaterOutputStream(nameValueBlockBuffer, deflater, true));
+ }
+
+ public synchronized void synStream(int flags, int streamId, int associatedStreamId, int priority,
+ int slot, List<String> nameValueBlock) throws IOException {
+ writeNameValueBlockToBuffer(nameValueBlock);
+ int length = 10 + nameValueBlockBuffer.size();
+ int type = SpdyConnection.TYPE_SYN_STREAM;
+
+ int unused = 0;
+ out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.writeInt(streamId & 0x7fffffff);
+ out.writeInt(associatedStreamId & 0x7fffffff);
+ out.writeShort((priority & 0x7) << 13 | (unused & 0x1f) << 8 | (slot & 0xff));
+ nameValueBlockBuffer.writeTo(out);
+ out.flush();
+ }
+
+ public synchronized void synReply(int flags, int streamId, List<String> nameValueBlock)
+ throws IOException {
+ writeNameValueBlockToBuffer(nameValueBlock);
+ int type = SpdyConnection.TYPE_SYN_REPLY;
+ int length = nameValueBlockBuffer.size() + 4;
+
+ out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.writeInt(streamId & 0x7fffffff);
+ nameValueBlockBuffer.writeTo(out);
+ out.flush();
+ }
+
+ public synchronized void headers(int flags, int streamId, List<String> nameValueBlock)
+ throws IOException {
+ writeNameValueBlockToBuffer(nameValueBlock);
+ int type = SpdyConnection.TYPE_HEADERS;
+ int length = nameValueBlockBuffer.size() + 4;
+
+ out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.writeInt(streamId & 0x7fffffff);
+ nameValueBlockBuffer.writeTo(out);
+ out.flush();
+ }
+
+ public synchronized void rstStream(int streamId, int statusCode) throws IOException {
+ int flags = 0;
+ int type = SpdyConnection.TYPE_RST_STREAM;
+ int length = 8;
+ out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.writeInt(streamId & 0x7fffffff);
+ out.writeInt(statusCode);
+ out.flush();
+ }
+
+ public synchronized void data(int flags, int streamId, byte[] data) throws IOException {
+ int length = data.length;
+ out.writeInt(streamId & 0x7fffffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.write(data);
+ out.flush();
+ }
+
+ private void writeNameValueBlockToBuffer(List<String> nameValueBlock) throws IOException {
+ nameValueBlockBuffer.reset();
+ int numberOfPairs = nameValueBlock.size() / 2;
+ nameValueBlockOut.writeInt(numberOfPairs);
+ for (String s : nameValueBlock) {
+ nameValueBlockOut.writeInt(s.length());
+ nameValueBlockOut.write(s.getBytes("UTF-8"));
+ }
+ nameValueBlockOut.flush();
+ }
+
+ public synchronized void settings(int flags, Settings settings) throws IOException {
+ int type = SpdyConnection.TYPE_SETTINGS;
+ int size = settings.size();
+ int length = 4 + size * 8;
+ out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.writeInt(size);
+ for (int i = 0; i <= Settings.COUNT; i++) {
+ if (!settings.isSet(i)) continue;
+ int settingsFlags = settings.flags(i);
+ out.writeInt((settingsFlags & 0xff) << 24 | (i & 0xffffff));
+ out.writeInt(settings.get(i));
+ }
+ out.flush();
+ }
+
+ public synchronized void noop() throws IOException {
+ int type = SpdyConnection.TYPE_NOOP;
+ int length = 0;
+ int flags = 0;
+ out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.flush();
+ }
+
+ public synchronized void ping(int flags, int id) throws IOException {
+ int type = SpdyConnection.TYPE_PING;
+ int length = 4;
+ out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.writeInt(id);
+ out.flush();
+ }
+
+ public synchronized void goAway(int flags, int lastGoodStreamId, int statusCode)
+ throws IOException {
+ int type = SpdyConnection.TYPE_GOAWAY;
+ int length = 8;
+ out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.writeInt(lastGoodStreamId);
+ out.writeInt(statusCode);
+ out.flush();
+ }
+
+ public synchronized void windowUpdate(int streamId, int deltaWindowSize) throws IOException {
+ int type = SpdyConnection.TYPE_WINDOW_UPDATE;
+ int flags = 0;
+ int length = 8;
+ out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff);
+ out.writeInt((flags & 0xff) << 24 | length & 0xffffff);
+ out.writeInt(streamId);
+ out.writeInt(deltaWindowSize);
+ out.flush();
+ }
+
+ @Override public void close() throws IOException {
+ Util.closeAll(out, nameValueBlockOut);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/AudioHandler.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/AudioHandler.java b/lib/cordova-android/framework/src/org/apache/cordova/AudioHandler.java
index fd8c9df..20c3c4e 100644
--- a/lib/cordova-android/framework/src/org/apache/cordova/AudioHandler.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/AudioHandler.java
@@ -20,7 +20,7 @@ package org.apache.cordova;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
-
+import org.apache.cordova.api.DataResource;
import android.content.Context;
import android.media.AudioManager;
@@ -56,6 +56,11 @@ public class AudioHandler extends CordovaPlugin {
this.pausedForPhone = new ArrayList<AudioPlayer>();
}
+ public String getFilePath(String url, String source){
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(url, this.webView.pluginManager, cordova, source);
+ return dataResource.getRealFile().getPath();
+ }
+
/**
* Executes the request and returns PluginResult.
* @param action The action to execute.
@@ -68,13 +73,13 @@ public class AudioHandler extends CordovaPlugin {
String result = "";
if (action.equals("startRecordingAudio")) {
- this.startRecordingAudio(args.getString(0), FileHelper.stripFileProtocol(args.getString(1)));
+ this.startRecordingAudio(args.getString(0), getFilePath(args.getString(1), "AudioHandler.startRecordingAudio"));
}
else if (action.equals("stopRecordingAudio")) {
this.stopRecordingAudio(args.getString(0));
}
else if (action.equals("startPlayingAudio")) {
- this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(args.getString(1)));
+ this.startPlayingAudio(args.getString(0), getFilePath(args.getString(1), "AudioHandler.startPlayingAudio"));
}
else if (action.equals("seekToAudio")) {
this.seekToAudio(args.getString(0), args.getInt(1));
@@ -102,7 +107,7 @@ public class AudioHandler extends CordovaPlugin {
}
else if (action.equals("create")) {
String id = args.getString(0);
- String src = FileHelper.stripFileProtocol(args.getString(1));
+ String src = getFilePath(args.getString(1), "AudioHandler.create");
AudioPlayer audio = new AudioPlayer(this, id, src);
this.players.put(id, audio);
}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/CameraLauncher.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/CameraLauncher.java b/lib/cordova-android/framework/src/org/apache/cordova/CameraLauncher.java
index 426d250..1974dd7 100755
--- a/lib/cordova-android/framework/src/org/apache/cordova/CameraLauncher.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/CameraLauncher.java
@@ -20,15 +20,16 @@ package org.apache.cordova;
import java.io.ByteArrayOutputStream;
import java.io.File;
-import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
+import org.apache.cordova.api.DataResource;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
@@ -42,7 +43,6 @@ import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
-import android.graphics.Rect;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
@@ -290,7 +290,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
// If sending base64 image back
if (destType == DATA_URL) {
- bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
+ bitmap = getScaledBitmap(imageUri.toString());
if (bitmap == null) {
// Try to get the bitmap from intent.
bitmap = (Bitmap)intent.getExtras().get("data");
@@ -316,7 +316,9 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
if (this.saveToPhotoAlbum) {
Uri inputUri = getUriFromMediaStore();
//Just because we have a media URI doesn't mean we have a real file, we need to make it
- uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(inputUri, webView.pluginManager, cordova, "CameraLauncher.CameraExitIntent");
+ File file = dataResource.getRealFile();
+ uri = Uri.fromFile(file);
} else {
uri = Uri.fromFile(new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), System.currentTimeMillis() + ".jpg"));
}
@@ -332,14 +334,15 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
this.callbackContext.success(uri.toString());
} else {
- bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
+ bitmap = getScaledBitmap(imageUri.toString());
if (rotate != 0 && this.correctOrientation) {
bitmap = getRotatedBitmap(rotate, bitmap, exif);
}
// Add compressed version of captured image to returned media store Uri
- OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(uri, webView.pluginManager, cordova, "CameraLauncher.CameraExitIntent");
+ OutputStream os = dataResource.getOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
@@ -347,7 +350,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
if (this.encodingType == JPEG) {
String exifPath;
if (this.saveToPhotoAlbum) {
- exifPath = FileHelper.getRealPath(uri, this.cordova);
+ exifPath = dataResource.getRealFile().getPath();
} else {
exifPath = uri.getPath();
}
@@ -398,8 +401,9 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
this.callbackContext.success(uri.toString());
} else {
String uriString = uri.toString();
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(uri, webView.pluginManager, cordova, "CameraLauncher.CameraExitIntent");
// Get the path to the image. Makes loading so much easier.
- String mimeType = FileHelper.getMimeType(uriString, this.cordova);
+ String mimeType = dataResource.getMimeType();
// If we don't have a valid image so quit.
if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) {
Log.d(LOG_TAG, "I either have a null image path or bitmap");
@@ -440,7 +444,8 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
// Create an ExifHelper to save the exif data that is lost during compression
String resizePath = DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
// Some content: URIs do not map to file paths (e.g. picasa).
- String realPath = FileHelper.getRealPath(uri, this.cordova);
+ File realFile = DataResource.initiateNewDataRequestForUri(uri, webView.pluginManager, cordova, "CameraLauncher.CameraExitIntent").getRealFile();
+ String realPath = realFile != null? realFile.getPath() : null;
ExifHelper exif = new ExifHelper();
if (realPath != null && this.encodingType == JPEG) {
try {
@@ -534,8 +539,15 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
*/
private void writeUncompressedImage(Uri uri) throws FileNotFoundException,
IOException {
- FileInputStream fis = new FileInputStream(FileHelper.stripFileProtocol(imageUri.toString()));
- OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
+ DataResource inputDataResource = DataResource.initiateNewDataRequestForUri(imageUri, webView.pluginManager, cordova, "CameraLauncher.writeUncompressedImage");
+ InputStream fis = inputDataResource.getInputStream();
+ DataResource outDataResource = DataResource.initiateNewDataRequestForUri(uri, webView.pluginManager, cordova, "CameraLauncher.writeUncompressedImage");
+ OutputStream os = outDataResource.getOutputStream();
+ if(fis == null) {
+ throw new FileNotFoundException("Could not get the input file");
+ } else if(os == null) {
+ throw new FileNotFoundException("Could not get the output file");
+ }
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) {
@@ -578,14 +590,15 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
*/
private Bitmap getScaledBitmap(String imageUrl) throws IOException {
// If no new width or height were specified return the original bitmap
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(imageUrl, webView.pluginManager, cordova, "CameraLauncher.getScaledBitmap");
if (this.targetWidth <= 0 && this.targetHeight <= 0) {
- return BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova));
+ return BitmapFactory.decodeStream(dataResource.getInputStream());
}
// figure out the original width and height of the image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
- BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova), null, options);
+ BitmapFactory.decodeStream(dataResource.getInputStream(), null, options);
//CB-2292: WTF? Why is the width null?
if(options.outWidth == 0 || options.outHeight == 0)
@@ -599,7 +612,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
// Load in the smallest bitmap possible that is closest to the size we want
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth, this.targetHeight);
- Bitmap unscaledBitmap = BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova), null, options);
+ Bitmap unscaledBitmap = BitmapFactory.decodeStream(dataResource.getInputStream(), null, options);
if (unscaledBitmap == null) {
return null;
}
@@ -698,16 +711,20 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
bitmap.recycle();
}
- // Clean up initial camera-written image file.
- (new File(FileHelper.stripFileProtocol(oldImage.toString()))).delete();
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(oldImage, webView.pluginManager, cordova, "CameraLauncher.cleanup");
+ File file = dataResource.getRealFile();
+ if(file != null) {
+ // Clean up initial camera-written image file.
+ file.delete();
- checkForDuplicateImage(imageType);
- // Scan for the gallery to update pic refs in gallery
- if (this.saveToPhotoAlbum && newImage != null) {
- this.scanForGallery(newImage);
- }
+ checkForDuplicateImage(imageType);
+ // Scan for the gallery to update pic refs in gallery
+ if (this.saveToPhotoAlbum && newImage != null) {
+ this.scanForGallery(newImage);
+ }
- System.gc();
+ System.gc();
+ }
}
/**
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/Capture.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/Capture.java b/lib/cordova-android/framework/src/org/apache/cordova/Capture.java
index 5f737ca..d7ad419 100644
--- a/lib/cordova-android/framework/src/org/apache/cordova/Capture.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/Capture.java
@@ -26,6 +26,7 @@ import java.io.OutputStream;
import android.os.Build;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
+import org.apache.cordova.api.DataResource;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
@@ -129,7 +130,8 @@ public class Capture extends CordovaPlugin {
// If the mimeType isn't set the rest will fail
// so let's see if we can determine it.
if (mimeType == null || mimeType.equals("") || "null".equals(mimeType)) {
- mimeType = FileHelper.getMimeType(filePath, cordova);
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "Capture.dataResource");
+ mimeType = dataResource.getMimeType();
}
Log.d(LOG_TAG, "Mime type = " + mimeType);
@@ -156,7 +158,8 @@ public class Capture extends CordovaPlugin {
private JSONObject getImageData(String filePath, JSONObject obj) throws JSONException {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(FileHelper.stripFileProtocol(filePath), options);
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "Capture.getImageData");
+ BitmapFactory.decodeFile(dataResource.getRealFile().getPath(), options);
obj.put("height", options.outHeight);
obj.put("width", options.outWidth);
return obj;
@@ -348,7 +351,8 @@ public class Capture extends CordovaPlugin {
* @throws IOException
*/
private JSONObject createMediaFile(Uri data) {
- File fp = new File(FileHelper.getRealPath(data, this.cordova));
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(data, webView.pluginManager, cordova, "Capture.createMediaFile");
+ File fp = dataResource.getRealFile();
JSONObject obj = new JSONObject();
try {
@@ -358,6 +362,7 @@ public class Capture extends CordovaPlugin {
// Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files
// are reported as video/3gpp. I'm doing this hacky check of the URI to see if it
// is stored in the audio or video content store.
+
if (fp.getAbsoluteFile().toString().endsWith(".3gp") || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
if (data.toString().contains("/audio/")) {
obj.put("type", AUDIO_3GPP);
@@ -365,7 +370,7 @@ public class Capture extends CordovaPlugin {
obj.put("type", VIDEO_3GPP);
}
} else {
- obj.put("type", FileHelper.getMimeType(fp.getAbsolutePath(), cordova));
+ obj.put("type", dataResource.getMimeType());
}
obj.put("lastModifiedDate", fp.lastModified());
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/Config.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/Config.java b/lib/cordova-android/framework/src/org/apache/cordova/Config.java
index 594c2b2..c2ced34 100644
--- a/lib/cordova-android/framework/src/org/apache/cordova/Config.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/Config.java
@@ -50,9 +50,8 @@ public class Config {
private static Config self = null;
public static void init(Activity action) {
- if (self == null) {
- self = new Config(action);
- }
+ //Just re-initialize this! Seriously, we lose this all the time
+ self = new Config(action);
}
// Intended to be used for testing only; creates an empty configuration.
@@ -97,7 +96,7 @@ public class Config {
}
else if (strNode.equals("log")) {
String level = xml.getAttributeValue(null, "level");
- LOG.i("CordovaLog", "Found log level %s", level);
+ Log.d(TAG, "The <log> tags is deprecated. Use <preference name=\"loglevel\" value=\"" + level + "\"/> instead.");
if (level != null) {
LOG.setLogLevel(level);
}
@@ -113,30 +112,27 @@ public class Config {
Note: We should probably pass in the classname for the variable splash on splashscreen!
*/
- if(name.equals("splashscreen")) {
+ if (name.equals("loglevel")) {
+ String level = xml.getAttributeValue(null, "value");
+ LOG.setLogLevel(level);
+ } else if (name.equals("splashscreen")) {
String value = xml.getAttributeValue(null, "value");
int resource = 0;
- if (value != null)
+ if (value == null)
{
value = "splash";
}
resource = action.getResources().getIdentifier(value, "drawable", action.getPackageName());
action.getIntent().putExtra(name, resource);
- LOG.i("CordovaLog", "Found preference for %s=%s", name, value);
- Log.d("CordovaLog", "Found preference for " + name + "=" + value);
}
else if(name.equals("backgroundColor")) {
int value = xml.getAttributeIntValue(null, "value", Color.BLACK);
action.getIntent().putExtra(name, value);
- LOG.i("CordovaLog", "Found preference for %s=%d", name, value);
- Log.d("CordovaLog", "Found preference for " + name + "=" + Integer.toString(value));
}
else if(name.equals("loadUrlTimeoutValue")) {
int value = xml.getAttributeIntValue(null, "value", 20000);
action.getIntent().putExtra(name, value);
- LOG.i("CordovaLog", "Found preference for %s=%d", name, value);
- Log.d("CordovaLog", "Found preference for " + name + "=" + Integer.toString(value));
}
else if(name.equals("keepRunning"))
{
@@ -157,12 +153,9 @@ public class Config {
{
String value = xml.getAttributeValue(null, "value");
action.getIntent().putExtra(name, value);
- LOG.i("CordovaLog", "Found preference for %s=%s", name, value);
- Log.d("CordovaLog", "Found preference for " + name + "=" + value);
}
/*
LOG.i("CordovaLog", "Found preference for %s=%s", name, value);
- Log.d("CordovaLog", "Found preference for " + name + "=" + value);
*/
}
else if (strNode.equals("content")) {
[12/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/webview.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/webview.js b/lib/cordova-blackberry/framework/lib/webview.js
new file mode 100644
index 0000000..495dfbe
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/webview.js
@@ -0,0 +1,271 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var networkResourceRequested = require('./webkitHandlers/networkResourceRequested'),
+ utils = require('./utils'),
+ config = require('./config'),
+ webkitOriginAccess = require("./policy/webkitOriginAccess"),
+ CHROME_HEIGHT = 0,
+ OUT_OF_PROCESS = 1,
+ webview,
+ _webviewObj;
+
+webview =
+ {
+ create: function (ready) {
+ _webviewObj = window.qnx.webplatform.createWebView({processId: OUT_OF_PROCESS, defaultSendEventHandlers: ['onChooseFile', 'onOpenWindow'], defaultWebEventHandlers: ['InvokeRequestEvent']}, function () {
+ //Create webkit event handlers
+ var requestObj = networkResourceRequested.createHandler(_webviewObj);
+
+ //Bind networkResourceRequested event so that everything works
+ _webviewObj.onNetworkResourceRequested = requestObj.networkResourceRequestedHandler;
+
+ webkitOriginAccess.addWebView(_webviewObj);
+
+ _webviewObj.visible = true;
+ _webviewObj.active = true;
+ _webviewObj.zOrder = 0;
+ _webviewObj.setGeometry(0, CHROME_HEIGHT, screen.width, screen.height - CHROME_HEIGHT);
+
+ if (typeof config.backgroundColor !== 'undefined') {
+ _webviewObj.backgroundColor = config.backgroundColor;
+ }
+
+ if (typeof config.customHeaders !== 'undefined') {
+ _webviewObj.extraHttpHeaders = config.customHeaders;
+ }
+
+ if (typeof config.userAgent !== 'undefined') {
+ _webviewObj.userAgent = config.userAgent;
+ }
+
+ _webviewObj.autoDeferNetworkingAndJavaScript = config.autoDeferNetworkingAndJavaScript;
+
+ /* Catch and trigger our custom HTML dialog */
+ _webviewObj.allowWebEvent("DialogRequested");
+
+ _webviewObj.addEventListener("DocumentLoadFinished", function () {
+ // show app window if auto hide splash screen is true, OR splash screen is not specified
+ // if auto hide is set to false explicitly but no splash screen is specified, should still show app window
+ // otherwise the app cannot be launched
+ if (config.autoHideSplashScreen || !config["rim:splash"]) {
+ window.qnx.webplatform.getApplication().windowVisible = true;
+ }
+ });
+
+
+ if (ready && typeof ready === 'function') {
+ ready();
+ }
+
+ window.qnx.webplatform.getController().dispatchEvent("webview.initialized", [_webviewObj]);
+
+ // If content is not loaded, too bad open the visibility up.
+ setTimeout(function () {
+ if (config.autoHideSplashScreen || !config["rim:splash"]) {
+ window.qnx.webplatform.getApplication().windowVisible = true;
+ }
+ }, 2500);
+ });
+
+ },
+
+ destroy: function () {
+ _webviewObj.destroy();
+ },
+
+ setURL: function (url) {
+ _webviewObj.url = url;
+ },
+
+ reload: function () {
+ _webviewObj.reload();
+ },
+
+ executeJavascript: function (js) {
+ _webviewObj.executeJavaScript(js);
+ },
+
+ addEventListener: function (eventName, callback) {
+ _webviewObj.addEventListener(eventName, callback);
+ },
+
+ removeEventListener: function (eventName, callback) {
+ _webviewObj.removeEventListener(eventName, callback);
+ },
+
+ windowGroup: function () {
+ return _webviewObj.windowGroup;
+ },
+
+ getGeometry: function () {
+ return this.geometry;
+ },
+
+ setGeometry: function (x, y, width, height) {
+ this.geometry = {x: x, y: y, w: width, h: height};
+ _webviewObj.setGeometry(x, y, width, height);
+ },
+
+ setApplicationOrientation: function (angle) {
+ _webviewObj.setApplicationOrientation(angle);
+ },
+
+ setExtraPluginDirectory: function (directory) {
+ _webviewObj.setExtraPluginDirectory(directory);
+ },
+
+ setEnablePlugins: function (enablePlugins) {
+ _webviewObj.pluginsEnabled = enablePlugins;
+ },
+
+ getEnablePlugins: function () {
+ return _webviewObj.pluginsEnabled;
+ },
+
+ notifyApplicationOrientationDone: function () {
+ _webviewObj.notifyApplicationOrientationDone();
+ },
+
+ setSandbox: function (sandbox) {
+ _webviewObj.setFileSystemSandbox = sandbox;
+ },
+
+ getSandbox: function () {
+ return _webviewObj.setFileSystemSandbox;
+ },
+
+ downloadURL: function (url) {
+ _webviewObj.downloadURL(url);
+ },
+
+ handleContextMenuResponse: function (action) {
+ _webviewObj.handleContextMenuResponse(action);
+ },
+
+ allowGeolocation : function (url) {
+ _webviewObj.allowGeolocation(url);
+ },
+
+ disallowGeolocation : function (url) {
+ _webviewObj.disallowGeolocation(url);
+
+ },
+
+ addKnownSSLCertificate: function (url, certificateInfo) {
+ _webviewObj.addKnownSSLCertificate(url, certificateInfo);
+ },
+
+ continueSSLHandshaking: function (streamId, SSLAction) {
+ _webviewObj.continueSSLHandshaking(streamId, SSLAction);
+ },
+
+ getSensitivity: function () {
+ return _webviewObj.getSensitivity();
+ },
+
+ setSensitivity: function (sensitivity) {
+ return _webviewObj.setSensitivity(sensitivity);
+ },
+
+ getBackgroundColor: function () {
+ return _webviewObj.getBackgroundColor();
+ },
+
+ setBackgroundColor: function (backgroundColor) {
+ return _webviewObj.setBackgroundColor(backgroundColor);
+ },
+
+ getWebViewObj: function (webview) {
+ return _webviewObj;
+ },
+
+ setUIWebViewObj: function (webviewObj) {
+ _webviewObj.uiWebView = webviewObj;
+ },
+
+ allowUserMedia: function (evtId, cameraName) {
+ _webviewObj.allowUserMedia(evtId, cameraName);
+ },
+
+ disallowUserMedia: function (evtId) {
+ _webviewObj.disallowUserMedia(evtId);
+ }
+};
+
+webview.__defineGetter__('id', function () {
+ if (_webviewObj) {
+ return _webviewObj.id;
+ }
+});
+
+webview.__defineGetter__('enableCrossSiteXHR', function () {
+ return _webviewObj.enableCrossSiteXHR;
+});
+
+webview.__defineSetter__('enableCrossSiteXHR', function (shouldEnable) {
+ _webviewObj.enableCrossSiteXHR = !!shouldEnable;
+});
+
+webview.__defineGetter__('processId', function () {
+ return _webviewObj.processId;
+});
+
+webview.__defineSetter__('onOpenWindow', function (input) {
+ _webviewObj.onOpenWindow = input;
+});
+
+webview.__defineSetter__('onCloseWindow', function (input) {
+ _webviewObj.onCloseWindow = input;
+});
+
+webview.__defineSetter__('onDestroyWindow', function (input) {
+ _webviewObj.onDestroyWindow = input;
+});
+
+webview.__defineSetter__('onDialogRequested', function (input) {
+ _webviewObj.onDialogRequested = input;
+});
+
+webview.__defineSetter__('onGeolocationPermissionRequest', function (input) {
+ _webviewObj.onGeolocationPermissionRequest = input;
+});
+
+webview.__defineSetter__('onSSLHandshakingFailed', function (input) {
+ _webviewObj.onSSLHandshakingFailed = input;
+});
+
+webview.__defineSetter__('onPropertyCurrentContextEvent', function (input) {
+ _webviewObj.onPropertyCurrentContextEvent = input;
+});
+
+webview.__defineSetter__('onContextMenuRequestEvent', function (input) {
+ _webviewObj.onContextMenuRequestEvent = input;
+});
+
+webview.__defineSetter__('onContextMenuCancelEvent', function (input) {
+ _webviewObj.onContextMenuCancelEvent = input;
+});
+
+webview.__defineSetter__('onUserMediaRequest', function (input) {
+ _webviewObj.onUserMediaRequest = input;
+});
+
+webview.__defineSetter__('onChildWindowOpen', function (input) {
+ _webviewObj.onChildWindowOpen = input;
+});
+
+module.exports = webview;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/config.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/config.js b/lib/cordova-blackberry/framework/test/unit/lib/config.js
new file mode 100644
index 0000000..64e8f7e
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/config.js
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var srcPath = __dirname + '/../../../lib/';
+
+describe("Config", function () {
+ var config = require(srcPath + 'config.js');
+
+ it("verify user value is correctly mixed", function () {
+ expect(config.copyright).toEqual("@Rebecca");
+ });
+
+ it("verify default value is correctly mixed", function () {
+ expect(config.widgetExtensions).toEqual(null);
+ });
+
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/controllerWebView.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/controllerWebView.js b/lib/cordova-blackberry/framework/test/unit/lib/controllerWebView.js
new file mode 100644
index 0000000..003d276
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/controllerWebView.js
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2010-2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+describe("controllerWebView", function () {
+ var controllerWebView = require('./../../../lib/controllerWebView'),
+ mockedController,
+ mockedInvocation,
+ mockedApplication;
+
+ beforeEach(function () {
+ mockedController = {
+ id: 42,
+ enableWebInspector: null,
+ enableCrossSiteXHR: null,
+ visible: null,
+ active: null,
+ setGeometry: jasmine.createSpy(),
+ setApplicationOrientation: jasmine.createSpy(),
+ notifyApplicationOrientationDone: jasmine.createSpy(),
+ publishRemoteFunction: jasmine.createSpy(),
+ dispatchEvent : jasmine.createSpy()
+ };
+ mockedInvocation = {
+ queryTargets: function (request, callback) {
+ callback("error", "results");
+ }
+ };
+ mockedApplication = {
+ invocation: mockedInvocation
+ };
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ getController: function () {
+ return mockedController;
+ },
+ getApplication: function () {
+ return mockedApplication;
+ }
+ }
+ }
+ };
+ GLOBAL.screen = {
+ width : 1024,
+ height: 768
+ };
+ });
+
+ describe("init", function () {
+ it("sets up the controllerWebview", function () {
+ controllerWebView.init({debugEnabled: true});
+ expect(mockedController.enableWebInspector).toEqual(true);
+ expect(mockedController.enableCrossSiteXHR).toEqual(true);
+ expect(mockedController.visible).toEqual(false);
+ expect(mockedController.active).toEqual(false);
+ expect(mockedController.setGeometry).toHaveBeenCalledWith(0, 0, screen.width, screen.height);
+ });
+
+ it("tests that the dispatch function is called properly", function () {
+ controllerWebView.init({debugEnabled: true});
+ controllerWebView.dispatchEvent('Awesome Event', ['these are agruments', 'another argument']);
+ expect(mockedController.dispatchEvent).toHaveBeenCalledWith('Awesome Event', ['these are agruments', 'another argument']);
+ });
+ });
+
+ describe("id", function () {
+ it("can get the id for the webiew", function () {
+ controllerWebView.init({debugEnabled: true});
+ expect(controllerWebView.id).toEqual(mockedController.id);
+ });
+ });
+
+ describe("geometry", function () {
+ it("can set geometry", function () {
+ controllerWebView.init({debugEnabled: true});
+ controllerWebView.setGeometry(0, 0, 100, 200);
+ expect(mockedController.setGeometry).toHaveBeenCalledWith(0, 0, 100, 200);
+ });
+ });
+
+ describe("application orientation", function () {
+ it("can set application orientation", function () {
+ controllerWebView.init({debugEnabled: true});
+ controllerWebView.setApplicationOrientation(90);
+ expect(mockedController.setApplicationOrientation).toHaveBeenCalledWith(90);
+ });
+
+ it("can notifyApplicationOrientationDone", function () {
+ controllerWebView.init({debugEnabled: true});
+ controllerWebView.notifyApplicationOrientationDone();
+ expect(mockedController.notifyApplicationOrientationDone).toHaveBeenCalled();
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/event.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/event.js b/lib/cordova-blackberry/framework/test/unit/lib/event.js
new file mode 100644
index 0000000..3d3e7fe
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/event.js
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var libRoot = __dirname + "/../../../lib/";
+
+describe("lib/event", function () {
+ var event = require(libRoot + "event"),
+ webview = require(libRoot + "webview"),
+ mockedWebview;
+
+ beforeEach(function () {
+ spyOn(webview, "executeJavascript");
+ mockedWebview = {
+ executeJavaScript: jasmine.createSpy(),
+ id: (new Date()).getTime()
+ };
+ });
+
+ describe("trigger", function () {
+
+
+ it("will trigger on the content webview when no webview is registered (for backwards compatability)", function () {
+ event.trigger("foo", {"id": 123});
+ expect(mockedWebview.executeJavaScript).not.toHaveBeenCalled();
+ expect(webview.executeJavascript).toHaveBeenCalled();
+ });
+
+ it("can invoke the webview execute javascript", function () {
+ var data = {"id": 123};
+ event.add({event: "foo", context: {addEventListener: jasmine.createSpy()}}, mockedWebview);
+ event.trigger("foo", data);
+ expect(mockedWebview.executeJavaScript).toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify([data]))) + "')");
+ expect(webview.executeJavascript).not.toHaveBeenCalled();
+ this.after(function () {
+ event.remove({event: "foo", context: {removeEventListener: jasmine.createSpy()}}, mockedWebview);
+ });
+ });
+
+ it("sends multiple arguments passed in across as a JSONified array", function () {
+ var args = [{"id": 123, "foo": "hello world", list: [1, 2, 3]}, "Grrrrrrr", "Arrrrg"];
+ event.add({event: "foo", context: {addEventListener: jasmine.createSpy()}}, mockedWebview);
+ event.trigger.apply(null, ["foo"].concat(args));
+ expect(mockedWebview.executeJavaScript).toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify(args))) + "')");
+ expect(webview.executeJavascript).not.toHaveBeenCalled();
+ this.after(function () {
+ event.remove({event: "foo", context: {removeEventListener: jasmine.createSpy()}}, mockedWebview);
+ });
+ });
+
+ it("invokes on all webviews that have registered, but not those removed", function () {
+ var mockedWebview2 = {
+ executeJavaScript: jasmine.createSpy(),
+ id: mockedWebview.id - 42
+ },
+ mockedWebview3 = {
+ executeJavaScript: jasmine.createSpy(),
+ id: mockedWebview.id + 42
+ },
+ mockedWebview4 = {
+ executeJavaScript: jasmine.createSpy(),
+ id: mockedWebview.id * 42
+ };
+ event.add({event: "foo", context: {addEventListener: jasmine.createSpy()}}, mockedWebview);
+ event.add({event: "foo", context: {addEventListener: jasmine.createSpy()}}, mockedWebview2);
+ event.add({event: "foo", context: {addEventListener: jasmine.createSpy()}}, mockedWebview3);
+ event.trigger("foo", {"id": 123});
+ expect(mockedWebview.executeJavaScript).toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify([{"id": 123}]))) + "')");
+ expect(mockedWebview2.executeJavaScript).toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify([{"id": 123}]))) + "')");
+ expect(mockedWebview3.executeJavaScript).toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify([{"id": 123}]))) + "')");
+ expect(mockedWebview4.executeJavaScript).not.toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify([{"id": 123}]))) + "')");
+ expect(webview.executeJavascript).not.toHaveBeenCalled();
+
+
+ event.remove({event: "foo", context: {removeEventListener: jasmine.createSpy()}}, mockedWebview3);
+ mockedWebview.executeJavaScript.reset();
+ mockedWebview2.executeJavaScript.reset();
+ mockedWebview3.executeJavaScript.reset();
+ mockedWebview4.executeJavaScript.reset();
+ event.trigger("foo", {"id": 123});
+ expect(mockedWebview.executeJavaScript).toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify([{"id": 123}]))) + "')");
+ expect(mockedWebview2.executeJavaScript).toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify([{"id": 123}]))) + "')");
+ expect(mockedWebview3.executeJavaScript).not.toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify([{"id": 123}]))) + "')");
+ expect(mockedWebview4.executeJavaScript).not.toHaveBeenCalledWith("webworks.event.trigger('foo', '" + escape(encodeURIComponent(JSON.stringify([{"id": 123}]))) + "')");
+ expect(webview.executeJavascript).not.toHaveBeenCalled();
+ this.after(function () {
+ event.remove({event: "foo", context: {removeEventListener: jasmine.createSpy()}}, mockedWebview);
+ event.remove({event: "foo", context: {removeEventListener: jasmine.createSpy()}}, mockedWebview2);
+ });
+ });
+
+ });
+
+ describe("add/remove would invoke action context", function () {
+ var action = {
+ context: {
+ addEventListener: jasmine.createSpy(),
+ removeEventListener: jasmine.createSpy()
+ },
+ event: "HELLO",
+ trigger: function () {}
+ };
+
+ beforeEach(function () {
+ action.context.addEventListener.reset();
+ action.context.removeEventListener.reset();
+ });
+
+ it("can invoke action context add listener", function () {
+ event.add(action, mockedWebview);
+ expect(action.context.addEventListener).toHaveBeenCalledWith(action.event, action.trigger);
+ });
+
+ it("will not invoke action context add listener when the action has a once field", function () {
+ action.once = true;
+ event.add(action, mockedWebview);
+ expect(action.context.addEventListener).not.toHaveBeenCalledWith(action.event, action.trigger);
+ this.after(function () {
+ delete action.once;
+ });
+ });
+
+ it("can invoke action context remove listener", function () {
+ event.remove(action, mockedWebview);
+ expect(action.context.removeEventListener).toHaveBeenCalledWith(action.event, action.trigger);
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/events/applicationEvents.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/events/applicationEvents.js b/lib/cordova-blackberry/framework/test/unit/lib/events/applicationEvents.js
new file mode 100644
index 0000000..81fa2e1
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/events/applicationEvents.js
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var _libDir = __dirname + "./../../../../lib/",
+ appEventPrefix = "application.",
+ appEvents,
+ mockedApplication;
+
+describe("lib/events/applicationEvents", function () {
+ beforeEach(function () {
+ mockedApplication = {
+ addEventListener: jasmine.createSpy("application addEventListener"),
+ removeEventListener: jasmine.createSpy("application removeEventListener")
+ };
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ getApplication: function () {
+ return mockedApplication;
+ }
+ }
+ }
+ };
+ appEvents = require(_libDir + "events/applicationEvents");
+ });
+
+ afterEach(function () {
+ mockedApplication = null;
+ delete GLOBAL.window;
+ appEvents = null;
+ delete require.cache[require.resolve(_libDir + "events/applicationEvents")];
+ });
+
+ describe("addEventListener", function () {
+ it("adds event name with application prepended", function () {
+ var eventName = "MostAwesomeEventEver",
+ trigger = function () {};
+ appEvents.addEventListener(eventName, trigger);
+ expect(mockedApplication.addEventListener).toHaveBeenCalledWith(appEventPrefix + eventName, trigger);
+ });
+
+ it("warns in the console if the eventName is falsey", function () {
+ var eventName = false,
+ trigger = function () {};
+ spyOn(console, "warn");
+ appEvents.addEventListener(eventName, trigger);
+ expect(mockedApplication.addEventListener).not.toHaveBeenCalledWith(appEventPrefix + eventName, trigger);
+ expect(console.warn).toHaveBeenCalledWith(jasmine.any(String));
+ });
+ });
+
+ describe("removeEventListener", function () {
+ it("adds event name with application prepended", function () {
+ var eventName = "MostAwesomeEventEver",
+ trigger = function () {};
+ appEvents.removeEventListener(eventName, trigger);
+ expect(mockedApplication.removeEventListener).toHaveBeenCalledWith(appEventPrefix + eventName, trigger);
+ });
+
+ it("warns in the console if the eventName is falsey", function () {
+ var eventName = false,
+ trigger = function () {};
+ spyOn(console, "warn");
+ appEvents.removeEventListener(eventName, trigger);
+ expect(mockedApplication.removeEventListener).not.toHaveBeenCalledWith(appEventPrefix + eventName, trigger);
+ expect(console.warn).toHaveBeenCalledWith(jasmine.any(String));
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/events/deviceEvents.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/events/deviceEvents.js b/lib/cordova-blackberry/framework/test/unit/lib/events/deviceEvents.js
new file mode 100644
index 0000000..2e55455
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/events/deviceEvents.js
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var _libDir = __dirname + "./../../../../lib/",
+ deviceEventPrefix = "device.",
+ deviceEvents;
+
+describe("lib/events/deviceEvents", function () {
+ beforeEach(function () {
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ device: {
+ addEventListener: jasmine.createSpy(),
+ removeEventListener: jasmine.createSpy()
+ }
+ }
+ }
+ };
+ deviceEvents = require(_libDir + "events/deviceEvents");
+ });
+
+ afterEach(function () {
+ delete GLOBAL.window;
+ deviceEvents = null;
+ delete require.cache[require.resolve(_libDir + "events/deviceEvents")];
+ });
+
+ describe("addEventListener", function () {
+ it("adds event name with application prepended", function () {
+ var eventName = "MostAwesomeEventEver",
+ trigger = function () {};
+ deviceEvents.addEventListener(eventName, trigger);
+ expect(window.qnx.webplatform.device.addEventListener).toHaveBeenCalledWith(deviceEventPrefix + eventName, trigger);
+ });
+
+ it("warns in the console if the eventName is falsey", function () {
+ var eventName = false,
+ trigger = function () {};
+ spyOn(console, "warn");
+ deviceEvents.addEventListener(eventName, trigger);
+ expect(window.qnx.webplatform.device.addEventListener).not.toHaveBeenCalledWith(deviceEventPrefix + eventName, trigger);
+ expect(console.warn).toHaveBeenCalledWith(jasmine.any(String));
+ });
+ });
+
+ describe("removeEventListener", function () {
+ it("adds event name with application prepended", function () {
+ var eventName = "MostAwesomeEventEver",
+ trigger = function () {};
+ deviceEvents.removeEventListener(eventName, trigger);
+ expect(window.qnx.webplatform.device.removeEventListener).toHaveBeenCalledWith(deviceEventPrefix + eventName, trigger);
+ });
+
+ it("warns in the console if the eventName is falsey", function () {
+ var eventName = false,
+ trigger = function () {};
+ spyOn(console, "warn");
+ deviceEvents.removeEventListener(eventName, trigger);
+ expect(window.qnx.webplatform.device.removeEventListener).not.toHaveBeenCalledWith(deviceEventPrefix + eventName, trigger);
+ expect(console.warn).toHaveBeenCalledWith(jasmine.any(String));
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/framework.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/framework.js b/lib/cordova-blackberry/framework/test/unit/lib/framework.js
new file mode 100644
index 0000000..312dd8b
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/framework.js
@@ -0,0 +1,429 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var srcPath = __dirname + '/../../../lib/',
+ config = require(srcPath + "config"),
+ framework,
+ webview,
+ overlayWebView,
+ overlayWebViewObj,
+ controllerWebView,
+ Whitelist = require(srcPath + 'policy/whitelist').Whitelist,
+ mockedController,
+ mockedApplicationWindow,
+ mockedApplication,
+ mockedDevice,
+ mockedQnx,
+ mock_request = {
+ url: "http://www.dummy.com",
+ allow: jasmine.createSpy(),
+ deny: jasmine.createSpy()
+ };
+
+describe("framework", function () {
+ beforeEach(function () {
+ mockedController = {
+ id: 42,
+ enableCrossSiteXHR: undefined,
+ visible: undefined,
+ active: undefined,
+ zOrder: undefined,
+ url: undefined,
+ setGeometry: jasmine.createSpy(),
+ onNetworkResourceRequested: undefined,
+ destroy: jasmine.createSpy(),
+ executeJavaScript: jasmine.createSpy(),
+ windowGroup: undefined,
+ addEventListener: jasmine.createSpy(),
+ uiWebView: undefined,
+ onChildWindowOpen: undefined
+ };
+ mockedApplicationWindow = {
+ visible: undefined
+ };
+ mockedApplication = {
+ addEventListener: jasmine.createSpy(),
+ webInspectorPort : "1337",
+ invocation: {
+ invoke: jasmine.createSpy()
+ }
+ };
+ mockedDevice = {
+ getNetworkInterfaces : jasmine.createSpy()
+ };
+ mockedQnx = {
+ callExtensionMethod : function () {
+ return 42;
+ },
+ webplatform : {
+ getController : function () {
+ return mockedController;
+ },
+ getApplication : function () {
+ return mockedApplication;
+ },
+ getApplicationWindow : function () {
+ return mockedApplicationWindow;
+ },
+ device : mockedDevice,
+ nativeCall: jasmine.createSpy("qnx.webplatform.nativeCall")
+ }
+ };
+ GLOBAL.window = {
+ qnx: mockedQnx
+ };
+ GLOBAL.qnx = mockedQnx;
+ GLOBAL.NamedNodeMap = function () {};
+
+ delete require.cache[require.resolve(srcPath + "webview")];
+ webview = require(srcPath + "webview");
+ delete require.cache[require.resolve(srcPath + "overlayWebView")];
+ overlayWebView = require(srcPath + "overlayWebView");
+ delete require.cache[require.resolve(srcPath + "controllerWebView")];
+ controllerWebView = require(srcPath + "controllerWebView");
+
+ spyOn(webview, "create").andCallFake(function (done) {
+ done();
+ });
+
+ spyOn(overlayWebView, "getWebViewObj").andCallFake(function () {
+ overlayWebViewObj = {
+ formcontrol: {
+ subscribeTo: jasmine.createSpy()
+ }
+ };
+ return overlayWebViewObj;
+ });
+
+ spyOn(overlayWebView, "create").andCallFake(function (done) {
+ done();
+ });
+
+ spyOn(controllerWebView, "init");
+ spyOn(controllerWebView, "dispatchEvent");
+ spyOn(webview, "destroy");
+ spyOn(webview, "executeJavascript");
+ spyOn(webview, "setURL");
+ spyOn(webview, "setUIWebViewObj");
+ spyOn(webview, "addEventListener").andCallFake(function (eventName, callback) {
+ callback();
+ });
+ spyOn(webview, "removeEventListener");
+
+ spyOn(overlayWebView, "setURL");
+ spyOn(overlayWebView, "renderContextMenuFor");
+ spyOn(overlayWebView, "handleDialogFor");
+ spyOn(overlayWebView, "addEventListener").andCallFake(function (eventName, callback) {
+ callback();
+ });
+ spyOn(overlayWebView, "removeEventListener");
+ spyOn(overlayWebView, "bindAppWebViewToChildWebViewControls");
+
+ delete require.cache[require.resolve(srcPath + "framework")];
+ framework = require(srcPath + 'framework');
+ });
+
+ afterEach(function () {
+ delete GLOBAL.blackberry;
+ delete GLOBAL.window;
+ delete GLOBAL.qnx;
+ delete GLOBAL.NamedNodeMap;
+ });
+
+ it("can start a webview instance", function () {
+ framework.start();
+ expect(controllerWebView.init).toHaveBeenCalled();
+ expect(webview.create).toHaveBeenCalled();
+ });
+
+ it("on start passing callback and setting object parameters to create method of webview", function () {
+ framework.start();
+ expect(webview.create).toHaveBeenCalledWith(jasmine.any(Function), jasmine.any(Object));
+ });
+
+ it("setting object should have debugEnabled to be defined", function () {
+ framework.start();
+ expect((webview.create.mostRecentCall.args)[1].debugEnabled).toBeDefined();
+ });
+
+ it("can start a webview instance with a url", function () {
+ var url = "http://www.google.com";
+ framework.start(url);
+ expect(webview.setURL).toHaveBeenCalledWith(url);
+ });
+
+ it("can stop a webview instance", function () {
+ framework.start();
+ framework.stop();
+ expect(webview.destroy).toHaveBeenCalled();
+ });
+
+ describe('creating the overlay webview', function () {
+ beforeEach(function () {
+ framework.start();
+ });
+ it('calls overlayWebView.create', function () {
+ expect(overlayWebView.create).toHaveBeenCalled();
+ });
+
+ it('sets the overlayWebView URL', function () {
+ expect(overlayWebView.setURL).toHaveBeenCalledWith("local:///chrome/ui.html");
+ });
+
+ it('calls renderContextMenuFor passing the webview', function () {
+ expect(overlayWebView.renderContextMenuFor).toHaveBeenCalledWith(webview);
+ });
+
+ it('calls handleDialogFor passing the webview', function () {
+ expect(overlayWebView.handleDialogFor).toHaveBeenCalledWith(webview);
+ });
+
+ it('dispatches the ui.init event on the controllerWebView', function () {
+ expect(controllerWebView.dispatchEvent).toHaveBeenCalledWith('ui.init', null);
+ });
+ });
+
+ describe('configuring webSecurity', function () {
+ var enableCrossSiteXHRSetter;
+
+ beforeEach(function () {
+ enableCrossSiteXHRSetter = jasmine.createSpy();
+ Object.defineProperty(webview, "enableCrossSiteXHR", {set: enableCrossSiteXHRSetter, configurable: true});
+ });
+
+ afterEach(function () {
+ delete webview.enableCrossSiteXHR;
+ delete require.cache[require.resolve(srcPath + "webview")];
+ webview = require(srcPath + "webview");
+ });
+
+ it('does not call enableCrossSiteXHR by default', function () {
+ expect(config.enableWebSecurity).toBe(true);
+ framework.start();
+
+ expect(enableCrossSiteXHRSetter).not.toHaveBeenCalledWith(true);
+ });
+
+ it('does enable crossSiteXHR when the config says too', function () {
+ delete require.cache[require.resolve(srcPath + "config")];
+ config = require(srcPath + 'config');
+ config.enableWebSecurity = false;
+
+ //reload config in framework
+ delete require.cache[require.resolve(srcPath + "framework")];
+ framework = require(srcPath + 'framework');
+
+ this.after(function () {
+ delete require.cache[require.resolve(srcPath + "config")];
+ config = require(srcPath + 'config');
+
+ delete require.cache[require.resolve(srcPath + "framework")];
+ framework = require(srcPath + 'framework');
+ });
+
+ expect(config.enableWebSecurity).toBe(false);
+ framework.start();
+
+ expect(enableCrossSiteXHRSetter).toHaveBeenCalledWith(true);
+ });
+ });
+
+ describe('configuring OpenChildWindow events', function () {
+ var onChildWindowOpenHandler;
+
+ beforeEach(function () {
+ Object.defineProperty(webview, "onChildWindowOpen", {set: function (input) {
+ onChildWindowOpenHandler = input;
+ }, configurable: true});
+ });
+
+ afterEach(function () {
+ delete webview.onChildWindowOpen;
+ delete require.cache[require.resolve(srcPath + "webview")];
+ webview = require(srcPath + "webview");
+ });
+
+ it('delegates to childWebViewControls on the overlay webview', function () {
+ config.enableChildWebView = true;
+
+ //reload config in framework
+ delete require.cache[require.resolve(srcPath + "framework")];
+ framework = require(srcPath + 'framework');
+
+ this.after(function () {
+ delete require.cache[require.resolve(srcPath + "config")];
+ config = require(srcPath + 'config');
+ });
+
+ framework.start();
+ expect(overlayWebView.bindAppWebViewToChildWebViewControls).toHaveBeenCalledWith(webview);
+ expect(webview.onChildWindowOpen).not.toBeDefined();
+ });
+
+ it('binds to OpenChildWindow and invokes the browser', function () {
+ config.enableChildWebView = false;
+
+ //reload config in framework
+ delete require.cache[require.resolve(srcPath + "framework")];
+ framework = require(srcPath + 'framework');
+
+ this.after(function () {
+ delete require.cache[require.resolve(srcPath + "config")];
+ config = require(srcPath + 'config');
+ });
+
+ framework.start();
+ expect(overlayWebView.bindAppWebViewToChildWebViewControls).not.toHaveBeenCalledWith(webview);
+ expect(onChildWindowOpenHandler).toEqual(jasmine.any(Function));
+ onChildWindowOpenHandler(JSON.stringify({url: 'http://www.google.com'}));
+ expect(mockedApplication.invocation.invoke).toHaveBeenCalledWith(
+ {uri: 'http://www.google.com', target: "sys.browser" }
+ );
+ });
+ });
+
+ describe('shows the webinspector dialog', function () {
+ it('show the webinspector dialog', function () {
+ var flag = false;
+ spyOn(overlayWebView, "showDialog");
+
+ window.qnx.webplatform.device.getNetworkInterfaces = function (callback) {
+ callback();
+ flag = true;
+ };
+ config.debugEnabled = true;
+ framework.start();
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ expect(overlayWebView.showDialog).toHaveBeenCalled();
+ });
+ });
+
+ it('show the webinspector dialog with the correct IP address', function () {
+ var flag = false,
+ messageObj;
+ spyOn(overlayWebView, "showDialog");
+
+ window.qnx.webplatform.device.getNetworkInterfaces = function (callback) {
+ var dummyData = {
+ asix0i : null,
+ bb0 : null,
+ bptp0 : null,
+ cellular0 : null,
+ cellular1 : null,
+ cellular2 : null,
+ cellular3 : null,
+ cellular4 : null,
+ ecm0 : {
+ connected : true,
+ ipv4Address : "169.254.0.1",
+ ipv6Address : "fe80::70aa:b2ff:fef9:b374",
+ type : "usb"
+ },
+ ipsec0 : null,
+ ipsec1 : null,
+ lo0 : null,
+ lo2 : null,
+ nap0 : null,
+ pan0 : null,
+ pflog0 : null,
+ ppp0 : null,
+ rndis0 : null,
+ smsc0 : null,
+ tiw_drv0 : null,
+ tiw_ibss0 : null,
+ tiw_p2pdev0 : null,
+ tiw_p2pgrp0 : null,
+ tiw_sta0 : {
+ connected : true,
+ ipv4Address : "192.168.2.2",
+ ipv6Address : "fe80::72aa:b2ff:fef9:b374",
+ type : "wifi"
+ },
+ vlan0 : null,
+ vpn0 : null
+ };
+ callback(dummyData);
+ flag = true;
+ };
+ config.debugEnabled = true;
+ framework.start();
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ messageObj = {
+ title : "Web Inspector Enabled",
+ htmlmessage : "\n ip4: 169.254.0.1:1337<br/> ip6: fe80::70aa:b2ff:fef9:b374:1337",
+ dialogType : "JavaScriptAlert"
+ };
+ expect(overlayWebView.showDialog).toHaveBeenCalledWith(messageObj);
+ });
+ });
+
+ });
+
+ describe('enabling form control', function () {
+ var originalConfigVal;
+
+ beforeEach(function () {
+ originalConfigVal = config.enableFormControl;
+ });
+
+ afterEach(function () {
+ config.enableFormControl = originalConfigVal;
+ });
+
+ it('subscribes webview to formcontrol', function () {
+ config.enableFormControl = true;
+ framework.start();
+ expect(overlayWebViewObj.formcontrol.subscribeTo).toHaveBeenCalledWith(webview);
+ });
+
+ it('does not subscribe webview to formcontrol is enableFormControl is false', function () {
+ config.enableFormControl = false;
+ framework.start();
+ expect(overlayWebViewObj.formcontrol.subscribeTo).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('enabling popup blocker', function () {
+ var originalConfigVal;
+
+ beforeEach(function () {
+ originalConfigVal = config.enablePopupBlocker;
+ });
+
+ afterEach(function () {
+ config.enablePopupBlocker = originalConfigVal;
+ });
+
+ it('does nothing when enablePopupBlocker is true', function () {
+ config.enablePopupBlocker = true;
+ framework.start();
+ expect(mockedQnx.webplatform.nativeCall).not.toHaveBeenCalledWith('webview.setBlockPopups', webview.id, false);
+ });
+
+ it('Disables popupblocker when enablePopupBlocker is false', function () {
+ config.enablePopupBlocker = false;
+ framework.start();
+ expect(mockedQnx.webplatform.nativeCall).toHaveBeenCalledWith('webview.setBlockPopups', webview.id, false);
+ });
+ });
+
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/overlayWebView.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/overlayWebView.js b/lib/cordova-blackberry/framework/test/unit/lib/overlayWebView.js
new file mode 100644
index 0000000..21150a9
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/overlayWebView.js
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+describe("Overlay Webview", function () {
+ var webview,
+ libPath = "./../../../",
+ mockedController,
+ mockedWebview,
+ mockedApplication;
+
+ beforeEach(function () {
+ webview = require(libPath + "lib/overlayWebView");
+ mockedWebview = {
+ id: 42,
+ enableCrossSiteXHR: undefined,
+ visible: undefined,
+ active: undefined,
+ zOrder: undefined,
+ url: undefined,
+ setGeometry: jasmine.createSpy(),
+ setApplicationOrientation: jasmine.createSpy(),
+ notifyApplicationOrientationDone: jasmine.createSpy(),
+ onContextMenuRequestEvent: undefined,
+ onNetworkResourceRequested: undefined,
+ destroy: jasmine.createSpy(),
+ executeJavaScript: jasmine.createSpy(),
+ windowGroup: undefined,
+ addEventListener: jasmine.createSpy(),
+ enableWebEventRedirect: jasmine.createSpy(),
+ notifyContextMenuCancelled: jasmine.createSpy(),
+ allowQnxObject: undefined,
+ allowRpc: undefined,
+ contextMenu: {
+ subscribeTo: jasmine.createSpy()
+ },
+ invocationlist: {
+ show: jasmine.createSpy()
+ }
+ };
+ mockedController = {
+ dispatchEvent : jasmine.createSpy(),
+ addEventListener : jasmine.createSpy()
+ };
+
+ mockedApplication = {
+ windowVisible: undefined
+ };
+ GLOBAL.qnx = {
+ callExtensionMethod: jasmine.createSpy(),
+ webplatform: {
+ getController: function () {
+ return mockedController;
+ },
+ createUIWebView: function (createFunction) {
+ runs(createFunction);
+ return mockedWebview;
+ },
+ getApplication: function () {
+ return mockedApplication;
+ }
+ }
+ };
+ GLOBAL.window = {
+ qnx: qnx
+ };
+ GLOBAL.screen = {
+ width : 1024,
+ height: 768
+ };
+ });
+
+ describe("create", function () {
+ it("sets up the visible webview", function () {
+ webview.create();
+ waits(1);
+ runs(function () {
+ expect(mockedWebview.visible).toEqual(true);
+ expect(mockedWebview.active).toEqual(true);
+ expect(mockedWebview.zOrder).toEqual(2);
+ expect(mockedWebview.setGeometry).toHaveBeenCalledWith(0, 0, screen.width, screen.height);
+ expect(mockedWebview.backgroundColor).toEqual(0x00FFFFFF);
+ expect(mockedWebview.sensitivity).toEqual("SensitivityTest");
+ expect(mockedWebview.allowQnxObject).toEqual(true);
+ expect(mockedWebview.allowRpc).toEqual(true);
+ expect(mockedController.dispatchEvent).toHaveBeenCalledWith("overlayWebView.initialized", jasmine.any(Array));
+ });
+ });
+
+ it("calls the ready function", function () {
+ var chuck = jasmine.createSpy();
+ webview.create(chuck);
+ waits(1);
+ runs(function () {
+ expect(chuck).toHaveBeenCalled();
+ });
+ });
+
+ });
+
+ describe("methods other than create", function () {
+
+ it("calls the underlying destroy", function () {
+ webview.create(mockedWebview);
+ webview.destroy();
+ expect(mockedWebview.destroy).toHaveBeenCalled();
+ });
+
+ it("sets the url property", function () {
+ var url = "http://AWESOMESAUCE.com";
+ webview.create(mockedWebview);
+ webview.setURL(url);
+ expect(mockedWebview.url).toEqual(url);
+ });
+
+ it("calls the underlying executeJavascript", function () {
+ var js = "var awesome='Jasmine BDD'";
+ webview.create(mockedWebview);
+ webview.executeJavascript(js);
+ expect(mockedWebview.executeJavaScript).toHaveBeenCalledWith(js);
+ });
+ it("calls the underlying windowGroup property", function () {
+ webview.create(mockedWebview);
+ expect(webview.windowGroup()).toEqual(mockedWebview.windowGroup);
+ });
+
+ it("can get the id for the webiew", function () {
+ webview.create();
+ expect(webview.id).toEqual(mockedWebview.id);
+ });
+
+ it("can set geometry", function () {
+ webview.create();
+ webview.setGeometry(0, 0, 100, 200);
+ expect(mockedWebview.setGeometry).toHaveBeenCalledWith(0, 0, 100, 200);
+ });
+
+ it("can set application orientation", function () {
+ webview.create();
+ webview.setApplicationOrientation(90);
+ expect(mockedWebview.setApplicationOrientation).toHaveBeenCalledWith(90);
+ });
+
+ it("can notifyApplicationOrientationDone", function () {
+ webview.create();
+ webview.notifyApplicationOrientationDone();
+ expect(mockedWebview.notifyApplicationOrientationDone).toHaveBeenCalled();
+ });
+
+ it("can notifyContextMenuCancelled", function () {
+ webview.create();
+ webview.notifyContextMenuCancelled();
+ expect(mockedWebview.notifyContextMenuCancelled).toHaveBeenCalled();
+ });
+
+ it("can render the ccm for another webview ", function () {
+ webview.create();
+ webview.renderContextMenuFor(webview);
+ expect(mockedWebview.contextMenu.subscribeTo).toHaveBeenCalledWith(webview);
+ });
+
+ it("It has a zOrder propety ", function () {
+ expect(webview.zOrder).toBeDefined();
+ });
+
+ it('proxies calls to invocationlist.show()', function () {
+ var request = {},
+ title = {},
+ success = function () {},
+ error = function () {};
+ webview.create();
+ webview.showInvocationList(request, title, success, error);
+ expect(mockedWebview.invocationlist.show).toHaveBeenCalledWith(request, title, success, error);
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/plugins/default.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/plugins/default.js b/lib/cordova-blackberry/framework/test/unit/lib/plugins/default.js
new file mode 100644
index 0000000..349bfea
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/plugins/default.js
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ROOT = "../../../../";
+
+describe("default plugin", function () {
+
+ var defaultPlugin = require(ROOT + 'lib/plugins/default'),
+ testExtension,
+ utils,
+ mockController,
+ mockApplication;
+
+ describe("when handling requests", function () {
+ var req, res, succ, fail, args;
+
+ beforeEach(function () {
+ req = {
+ origin: "http://www.origin.com",
+ params: {}
+ };
+ res = {
+ send: jasmine.createSpy()
+ };
+ succ = jasmine.createSpy("lib/plugin/default success");
+ fail = jasmine.createSpy("lib/plugin/default fail");
+ args = {};
+
+ GLOBAL.frameworkModules = ["plugin/blackberry.app/index.js"];
+
+ //All of this mocking is required for modules to load, DO NOT REMOVE
+ mockController = {
+ dispatchEvent: jasmine.createSpy()
+ };
+ mockApplication = {
+ };
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ getController: jasmine.createSpy().andReturn(mockController),
+ getApplication: jasmine.createSpy().andReturn(mockApplication)
+ }
+ }
+ };
+
+ testExtension = {
+ getReadOnlyFields: function () {}
+ };
+
+ delete require.cache[require.resolve(ROOT + "lib/utils")];
+ utils = require(ROOT + "lib/utils");
+ spyOn(utils, "loadModule").andCallFake(function (module) {
+ // on device, "plugin/blackberry.app/index.js" would exist since packager would
+ // name the extension folder with feature id in compilation time
+ if (module.indexOf("/plugin") !== -1) {
+ return testExtension;
+ } else {
+ return undefined;
+ }
+ });
+ });
+
+ afterEach(function () {
+ delete GLOBAL.frameworkModules;
+ delete GLOBAL.window;
+ });
+
+ it("returns 404 if the extension is not found", function () {
+ var ext = "NotAnExt",
+ errMsg = "Extension " + ext + " not found";
+
+ req.params.ext = ext;
+ spyOn(console, "warn");
+
+ defaultPlugin.exec(req, succ, fail, args);
+
+ expect(fail).toHaveBeenCalledWith(-1, errMsg, 404);
+ expect(console.warn).toHaveBeenCalledWith(errMsg);
+ });
+
+ it("returns 404 if the method is not found", function () {
+ req.params.ext = "blackberry.app";
+ req.params.method = "NotAMethod";
+ spyOn(console, "warn");
+
+ defaultPlugin.exec(req, succ, fail, args);
+
+ expect(fail).toHaveBeenCalledWith(-1, jasmine.any(String), 404);
+ expect(console.warn).toHaveBeenCalledWith("Method " + req.params.method + " for " + req.params.ext + " not found");
+ });
+
+ it("calls the method of the extension", function () {
+ var env = {"request": req, "response": res};
+
+ spyOn(testExtension, "getReadOnlyFields");
+
+ req.params.ext = "blackberry.app";
+ req.params.method = "getReadOnlyFields";
+
+ defaultPlugin.exec(req, succ, fail, args, env);
+
+ expect(testExtension.getReadOnlyFields).toHaveBeenCalledWith(succ, fail, args, env);
+ });
+
+ it("calls a multi-level method of the extension", function () {
+ var env = {"request": req, "response": res};
+
+ spyOn(testExtension, "getReadOnlyFields");
+ testExtension.getReadOnlyFields.a = {
+ b : {
+ c : jasmine.createSpy()
+ }
+ };
+
+ req.params.ext = "blackberry.app";
+ req.params.method = "getReadOnlyFields/a/b/c";
+
+ defaultPlugin.exec(req, succ, fail, args, env);
+
+ expect(fail).wasNotCalled();
+ expect(testExtension.getReadOnlyFields.a.b.c).toHaveBeenCalledWith(succ, fail, args, env);
+ });
+
+ it("throws a 404 is a multi-level method is not found", function () {
+ var env = {"request": req, "response": res};
+
+ spyOn(console, "warn");
+ spyOn(testExtension, "getReadOnlyFields");
+ testExtension.getReadOnlyFields.a = {
+ };
+
+ req.params.ext = "blackberry.app";
+ req.params.method = "getReadOnlyFields/a/b/c";
+
+ defaultPlugin.exec(req, succ, fail, args, env);
+
+ expect(fail).toHaveBeenCalledWith(-1, jasmine.any(String), 404);
+ expect(console.warn).toHaveBeenCalledWith("Method " + req.params.method + " for " + req.params.ext + " not found");
+ });
+ });
+
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/plugins/event.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/plugins/event.js b/lib/cordova-blackberry/framework/test/unit/lib/plugins/event.js
new file mode 100644
index 0000000..ea92f1d
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/plugins/event.js
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+describe("event plugin", function () {
+
+ var ROOT = "./../../../../",
+ eventLib = require(ROOT + "lib/event"),
+ eventPlugin;
+
+ describe("once function", function () {
+ var args = {
+ eventName: encodeURIComponent(JSON.stringify("GRRRRR"))
+ };
+
+ it("calls success if no error", function () {
+ var success = jasmine.createSpy(),
+ fail = jasmine.createSpy(),
+ webview = {};
+
+ spyOn(eventLib, "add");
+ delete require.cache[require.resolve(ROOT + "lib/plugins/event")];
+ eventPlugin = require(ROOT + "lib/plugins/event");
+ this.after(function () {
+ delete require.cache[require.resolve(ROOT + "lib/plugins/event")];
+ });
+
+ eventPlugin.once(undefined, success, fail, args, {webview: webview});
+
+ expect(eventLib.add).toHaveBeenCalledWith(
+ {
+ event: "GRRRRR",
+ once: true
+ },
+ webview
+ );
+ expect(success).toHaveBeenCalled();
+ expect(fail).not.toHaveBeenCalledWith(-1, jasmine.any(String));
+ });
+
+ it("calls fail if there is an error", function () {
+ var success = jasmine.createSpy(),
+ fail = jasmine.createSpy(),
+ webview = {};
+
+ spyOn(eventLib, "add").andThrow("ERRRORZ");
+ delete require.cache[require.resolve(ROOT + "lib/plugins/event")];
+ eventPlugin = require(ROOT + "lib/plugins/event");
+ this.after(function () {
+ delete require.cache[require.resolve(ROOT + "lib/plugins/event")];
+ });
+
+ eventPlugin.once(undefined, success, fail, args, {webview: webview});
+
+ expect(eventLib.add).toHaveBeenCalledWith(
+ {
+ event: "GRRRRR",
+ once: true
+ },
+ webview
+ );
+ expect(success).not.toHaveBeenCalled();
+ expect(fail).toHaveBeenCalledWith(-1, jasmine.any(String));
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/policy/webkitOriginAccess.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/policy/webkitOriginAccess.js b/lib/cordova-blackberry/framework/test/unit/lib/policy/webkitOriginAccess.js
new file mode 100644
index 0000000..4a5ac8e
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/policy/webkitOriginAccess.js
@@ -0,0 +1,194 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var LIB_PATH = __dirname + "/../../../../lib/",
+ utils = require(LIB_PATH + 'utils'),
+ webkitOriginAccess = require(LIB_PATH + "policy/webkitOriginAccess"),
+ LOCAL_URI = "local://",
+ FILE_URI = "file://",
+ WW_URI = utils.getURIPrefix(),
+ mockWebView;
+
+describe("lib/policy/webkitOriginAccess", function () {
+ beforeEach(function () {
+ mockWebView = {
+ addOriginAccessWhitelistEntry: jasmine.createSpy()
+ };
+ });
+
+ afterEach(function () {
+ mockWebView = undefined;
+ delete require.cache[require.resolve(LIB_PATH + "config")];
+ delete require.cache[require.resolve(LIB_PATH + "policy/webkitOriginAccess")];
+ webkitOriginAccess = require(LIB_PATH + "policy/webkitOriginAccess");
+ });
+
+ function mockConfig(mockAccessList, hasMultiAccess) {
+ delete require.cache[require.resolve(LIB_PATH + "config")];
+ delete require.cache[require.resolve(LIB_PATH + "policy/webkitOriginAccess")];
+ var config = require(LIB_PATH + "config");
+ config.accessList = mockAccessList;
+ config.hasMultiAccess = !!hasMultiAccess;
+ webkitOriginAccess = require(LIB_PATH + "policy/webkitOriginAccess");
+ }
+
+ describe("addWebview function", function () {
+
+ it("exists", function () {
+ expect(webkitOriginAccess.addWebView).toBeDefined();
+ });
+
+ it("sets up one time whitelisting", function () {
+ webkitOriginAccess.addWebView(mockWebView);
+
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(LOCAL_URI, FILE_URI, true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(FILE_URI, LOCAL_URI, true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(LOCAL_URI, WW_URI, true);
+ });
+
+ it("initializes the webview with whitelisting based on the config", function () {
+ var mockAccessList = [
+ {
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : null
+ }
+ ];
+ mockConfig(mockAccessList);
+
+ webkitOriginAccess.addWebView(mockWebView);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(LOCAL_URI, "http://google.com", true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith("http://google.com", LOCAL_URI, true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith("http://google.com", WW_URI, true);
+ });
+
+ it("initializes the webview with whitelisting based on what domains have been added", function () {
+ var mockAccessList = [{
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : null
+ }],
+ url = "http://www.rim.com";
+
+ mockConfig(mockAccessList, true);
+
+ webkitOriginAccess.addOriginAccess(url, true);
+
+ webkitOriginAccess.addWebView(mockWebView);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(LOCAL_URI, url, true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(url, LOCAL_URI, true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(url, "http://google.com", true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith("http://google.com", url, true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(url, WW_URI, true);
+ });
+
+ it("will not initialize twice", function () {
+ var origCallCount;
+
+ webkitOriginAccess.addWebView(mockWebView);
+ origCallCount = mockWebView.addOriginAccessWhitelistEntry.callCount;
+ webkitOriginAccess.addWebView(mockWebView);
+
+ expect(mockWebView.addOriginAccessWhitelistEntry.callCount).toEqual(origCallCount);
+ });
+
+ });
+
+ describe("addOriginAccess function", function () {
+ it("exists", function () {
+ expect(webkitOriginAccess.addOriginAccess).toBeDefined();
+ });
+
+ it("Treats falsey values as false", function () {
+ var url = "http://www.rim.com";
+
+ webkitOriginAccess.addWebView(mockWebView);
+ webkitOriginAccess.addOriginAccess(url);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(LOCAL_URI, url, false);
+ });
+
+ it("Adds access for any non-local and non-file url", function () {
+ var url = "http://www.rim.com/grrr/arrg/blah.htm";
+
+ webkitOriginAccess.addWebView(mockWebView);
+ webkitOriginAccess.addOriginAccess(url);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(LOCAL_URI, url, false);
+ });
+
+ //Because local:// is already a domain, the spy should not have no new calls
+ it("Local uris are treated as local://", function () {
+ var url = "local:///buy/local/beef/mmmmmmmmmmmmm/Steak.yum",
+ origCallCount;
+
+ webkitOriginAccess.addWebView(mockWebView);
+ webkitOriginAccess.addOriginAccess(url);
+ origCallCount = mockWebView.addOriginAccessWhitelistEntry.callCount;
+ webkitOriginAccess.addOriginAccess(url);
+ expect(mockWebView.addOriginAccessWhitelistEntry.callCount).toEqual(origCallCount);
+ });
+
+ it("File uris are treated as file://", function () {
+ var url = "file:///buy/local/beef/mmmmmmmmmmmmm/Steak.yum",
+ authority = "file://";
+
+ webkitOriginAccess.addWebView(mockWebView);
+ webkitOriginAccess.addOriginAccess(url);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(LOCAL_URI, authority, false);
+ });
+
+ it("updates all managed webviews of the new domain access", function () {
+ var mockWebView2 = {
+ addOriginAccessWhitelistEntry: jasmine.createSpy()
+ },
+ url = "http://www.rim.com";
+
+ webkitOriginAccess.addWebView(mockWebView);
+ webkitOriginAccess.addWebView(mockWebView2);
+
+ webkitOriginAccess.addOriginAccess(url, true);
+
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(LOCAL_URI, url, true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(url, LOCAL_URI, true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(url, WW_URI, true);
+ expect(mockWebView2.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(LOCAL_URI, url, true);
+ expect(mockWebView2.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(url, LOCAL_URI, true);
+ expect(mockWebView2.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(url, WW_URI, true);
+ });
+
+ it("updates all managed webviews when a new domain is added", function () {
+ var mockAccessList = [{
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : null
+ }],
+ url = "http://www.rim.com";
+
+ mockConfig(mockAccessList, true);
+
+ webkitOriginAccess.addWebView(mockWebView);
+
+ expect(mockWebView.addOriginAccessWhitelistEntry).not.toHaveBeenCalledWith(url, "http://google.com", true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).not.toHaveBeenCalledWith("http://google.com", url, true);
+
+ webkitOriginAccess.addOriginAccess(url, true);
+
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith(url, "http://google.com", true);
+ expect(mockWebView.addOriginAccessWhitelistEntry).toHaveBeenCalledWith("http://google.com", url, true);
+ });
+
+ });
+
+});
[13/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/event.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/event.js b/lib/cordova-blackberry/framework/lib/event.js
new file mode 100644
index 0000000..880e6c4
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/event.js
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var _handlers = {},
+ _webview = require("./webview");
+
+module.exports = {
+ trigger: function (actionEvent) {
+ var args = Array.prototype.slice.call(arguments),
+ executeString = "webworks.event.trigger('" + actionEvent + "', '" + escape(encodeURIComponent(JSON.stringify(args.slice(1)))) + "')";
+
+ if (_handlers.hasOwnProperty(actionEvent)) {
+ _handlers[actionEvent].forEach(function (webview) {
+ webview.executeJavaScript(executeString);
+ });
+ } else {
+ //Just dump it in the content webview for consistency
+ _webview.executeJavascript(executeString);
+ }
+ },
+
+ add: function (action, webview) {
+ var triggerEvent;
+
+ if (action) {
+ //Use action.event for old extensions that may not have triggerEvent defined
+ triggerEvent = action.triggerEvent || action.event;
+
+ if (!action.once) {
+ action.context.addEventListener(action.event, action.trigger || this.trigger);
+ }
+
+ //If there are no registered listeners for this event, create an array to hold them
+ if (!_handlers.hasOwnProperty(triggerEvent)) {
+ _handlers[triggerEvent] = [];
+ }
+ //If the webview is not in the list of webviews listening to this action then add it
+ if (!_handlers[triggerEvent].some(function (handlerWebView) {
+ return handlerWebView.id === webview.id;
+ })) {
+ _handlers[triggerEvent].push(webview);
+ }
+
+ } else {
+ throw "Action is null or undefined";
+ }
+ },
+
+ remove: function (action, webview) {
+ if (action) {
+ action.context.removeEventListener(action.event, action.trigger || this.trigger);
+
+ //Remove the webview from the _handlers
+ if (_handlers.hasOwnProperty(action.event)) {
+
+ _handlers[action.event] = _handlers[action.event].filter(function (sourceWebview) {
+ return sourceWebview.id !== webview.id;
+ });
+
+ //If the array is empty delete it
+ if (_handlers[action.event].length === 0) {
+ delete _handlers[action.event];
+ }
+ }
+
+ } else {
+ throw "Action is null or undefined";
+ }
+
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/events/applicationEvents.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/events/applicationEvents.js b/lib/cordova-blackberry/framework/lib/events/applicationEvents.js
new file mode 100644
index 0000000..14a8f9e
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/events/applicationEvents.js
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+module.exports = {
+ addEventListener: function (event, trigger) {
+ if (event) {
+ event = "application." + event;
+ window.qnx.webplatform.getApplication().addEventListener(event, trigger);
+ } else {
+ console.warn("Attempting to register for 'falsey' event: " + event);
+ }
+ },
+ removeEventListener: function (event, trigger) {
+ if (event) {
+ event = "application." + event;
+ window.qnx.webplatform.getApplication().removeEventListener(event, trigger);
+ } else {
+ console.warn("Attempting to un-register for 'falsey' event: " + event);
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/events/deviceEvents.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/events/deviceEvents.js b/lib/cordova-blackberry/framework/lib/events/deviceEvents.js
new file mode 100644
index 0000000..939357b
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/events/deviceEvents.js
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+module.exports = {
+ addEventListener: function (event, trigger) {
+ if (event) {
+ event = "device." + event;
+ window.qnx.webplatform.device.addEventListener(event, trigger);
+ } else {
+ console.warn("Attempting to register for 'falsey' event: " + event);
+ }
+ },
+ removeEventListener: function (event, trigger) {
+ if (event) {
+ event = "device." + event;
+ window.qnx.webplatform.device.removeEventListener(event, trigger);
+ } else {
+ console.warn("Attempting to un-register for 'falsey' event: " + event);
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/exception.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/exception.js b/lib/cordova-blackberry/framework/lib/exception.js
new file mode 100644
index 0000000..f0a8467
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/exception.js
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+module.exports = {
+
+ types: {
+ Application: "Application",
+ ArgumentLength: "ArgumentLength",
+ ArgumentType: "ArgumentType",
+ Argument: "Argument",
+ NotificationType: "NotificationType",
+ NotificationStateType: "NotificationStateType",
+ DomObjectNotFound: "DomObjectNotFound",
+ MethodNotImplemented: "MethodNotImplemented",
+ InvalidState: "InvalidState",
+ ApplicationState: "ApplicationState"
+ },
+
+ handle: function handle(exception, reThrow) {
+ reThrow = reThrow || false;
+
+ var eMsg = exception.message || "exception caught!",
+ msg = eMsg + "\n\n" + (exception.stack || "*no stack provided*") + "\n\n";
+
+ console.error(msg);
+
+ if (reThrow) {
+ throw exception;
+ }
+ },
+
+ raise: function raise(exceptionType, message, customExceptionObject) {
+ var obj = customExceptionObject || {
+ type: "",
+ message: "",
+
+ toString: function () {
+ var result = this.name + ': "' + this.message + '"';
+
+ if (this.stack) {
+ result += "\n" + this.stack;
+ }
+ return result;
+ }
+ };
+
+ message = message || "";
+
+ obj.name = exceptionType;
+ obj.type = exceptionType;
+ // TODO: include the exception objects original message if exists
+ obj.message = message;
+
+ throw obj;
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/framework.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/framework.js b/lib/cordova-blackberry/framework/lib/framework.js
new file mode 100644
index 0000000..5de045c
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/framework.js
@@ -0,0 +1,172 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var utils = require('./utils'),
+ controllerWebView = require('./controllerWebView'),
+ webview = require('./webview'),
+ overlayWebView = require('./overlayWebView'),
+ config = require("./config"),
+ appEvents = require("./events/applicationEvents"),
+ actionMap = {
+ pause: {
+ event: "inactive",
+ trigger: function () {
+ webview.executeJavascript("cordova.fireDocumentEvent('pause')");
+ }
+ },
+ resume: {
+ event: "active",
+ trigger: function () {
+ webview.executeJavascript("cordova.fireDocumentEvent('resume')");
+ }
+ }
+ };
+
+function addEvents() {
+ for (var action in actionMap) {
+ if (actionMap.hasOwnProperty(action)) {
+ appEvents.addEventListener(actionMap[action].event, actionMap[action].trigger);
+ }
+ }
+}
+
+function removeEvents() {
+ for (var action in actionMap) {
+ if (actionMap.hasOwnProperty(action)) {
+ appEvents.removeEventListener(actionMap[action].event, actionMap[action].trigger);
+ }
+ }
+}
+
+function showWebInspectorInfo() {
+ var port = window.qnx.webplatform.getApplication().webInspectorPort,
+ messageObj = {};
+
+ qnx.webplatform.device.getNetworkInterfaces(function (networkInfo) {
+ var connectedInterface;
+
+ utils.forEach(networkInfo, function (info) {
+ if (info && !connectedInterface) {
+ connectedInterface = info;
+ }
+ }, this);
+
+ messageObj.title = "Web Inspector Enabled";
+ if (connectedInterface) {
+ messageObj.htmlmessage = "\n ip4: " + connectedInterface.ipv4Address + ":" + port + "<br/> ip6: " + connectedInterface.ipv6Address + ":" + port;
+ } else {
+ messageObj.message = "";
+ }
+ messageObj.dialogType = 'JavaScriptAlert';
+ overlayWebView.showDialog(messageObj);
+ });
+}
+
+var _self = {
+ start: function (url) {
+ var callback,
+ showUrlCallback;
+
+ // Set up the controller WebView
+ controllerWebView.init(config);
+
+ webview.create(function () {
+ if (config.enableFlash) {
+ //Set webview plugin directory [required for flash]
+ webview.setExtraPluginDirectory('/usr/lib/browser/plugins');
+
+ //Enable plugins for the webview [required for flash]
+ webview.setEnablePlugins(true);
+
+ //Enable flash for the childWebViews
+ controllerWebView.onChildWebViewCreated = function (child) {
+ //Set webview plugin directory [required for flash]
+ child.setExtraPluginDirectory('/usr/lib/browser/plugins');
+
+ //Enable plugins for the webview [required for flash]
+ child.pluginsEnabled = true;
+ };
+ }
+
+ if (!config.enableWebSecurity) {
+ webview.enableCrossSiteXHR = true;
+ }
+
+ if (!config.enablePopupBlocker) {
+ qnx.webplatform.nativeCall('webview.setBlockPopups', webview.id, false);
+ }
+ // Workaround for executeJavascript doing nothing for the first time
+
+ webview.executeJavascript("1 + 1");
+
+ url = url || config.content;
+
+ showUrlCallback = function () {
+ overlayWebView.removeEventListener("DocumentLoadFinished", showUrlCallback);
+ showUrlCallback = null;
+
+ // Start page
+ if (url) {
+ webview.setURL(url);
+ }
+ };
+
+ overlayWebView.create(function () {
+ overlayWebView.addEventListener("DocumentLoadFinished", showUrlCallback);
+
+ overlayWebView.setURL("local:///chrome/ui.html");
+ overlayWebView.renderContextMenuFor(webview);
+ overlayWebView.handleDialogFor(webview);
+ controllerWebView.dispatchEvent('ui.init', null);
+ webview.setUIWebViewObj(overlayWebView.getWebViewObj());
+ if (config.enableChildWebView) {
+ overlayWebView.bindAppWebViewToChildWebViewControls(webview);
+ } else {
+ webview.onChildWindowOpen = function (data) {
+ var parsedData = JSON.parse(data);
+ utils.invokeInBrowser(parsedData.url);
+ };
+ }
+ if (config.enableFormControl) {
+ overlayWebView.getWebViewObj().formcontrol.subscribeTo(webview);
+ }
+ });
+ },
+ {
+ debugEnabled : config.debugEnabled
+ });
+
+ addEvents();
+
+ //if debugging is enabled, show the IP and port for webinspector
+ if (config.debugEnabled) {
+ callback = function () {
+ showWebInspectorInfo();
+
+ //Remove listener. Alert should only be shown once.
+ webview.removeEventListener("DocumentLoadFinished", callback);
+ };
+
+ webview.addEventListener("DocumentLoadFinished", callback);
+ }
+ },
+ stop: function () {
+ removeEvents();
+ webview.destroy();
+ }
+};
+
+module.exports = _self;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/jnext.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/jnext.js b/lib/cordova-blackberry/framework/lib/jnext.js
new file mode 100755
index 0000000..d0e4d79
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/jnext.js
@@ -0,0 +1,185 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*global objJSExt */
+
+function JNEXT_() {
+ var self = this;
+ var m_bFirstRequire = true;
+
+ self.m_arEvents = {};
+
+ self.onPageLoad = function() {
+ };
+
+ self.attachToDOM = function() {
+ // Make sure JNEXT onPageLoad is called when page load
+ // completes without damaging existing onLoad handlers
+ var prevOnLoad = window.onload;
+ if( typeof window.onload != 'function') {
+ window.onload = self.onPageLoad;
+ } else {
+ window.onload = function() {
+ if(prevOnLoad) {
+ prevOnLoad();
+ }
+
+ self.onPageLoad();
+ };
+ }
+
+ // Unobtrusively add the JNEXT plugin or ActiveX to the DOM
+ var objBody = document.getElementsByTagName("body")[0];
+ var objDiv = document.createElement('div');
+ var strHTML;
+
+ if(window.ActiveXObject) {
+ strHTML = '<object id="objJSExt" width="0" height="0" classid="CLSID:C802F39D-BF85-427a-A334-77E501DB62E9" codebase="jnext.ocx"></object>';
+ strHTML += '<script language="JavaScript" for="objJSExt" EVENT="Js2nEvent( strEvent )">JNEXT.processEvent(strEvent)</script>';
+ } else {
+ var strAddSrc = "";
+ if(navigator.userAgent.indexOf("Safari") != -1 && navigator.userAgent.indexOf("Windows") != -1) {
+ // This hack required on Safari for Windows
+ strAddSrc = 'src="./jnext/safari.foo"';
+ }
+ strHTML = '<embed id="objJSExt" ' + strAddSrc + ' type="application/jnext-scriptable-plugin" width="0" height="0">';
+ }
+
+ objDiv.innerHTML = strHTML;
+ objBody.appendChild(objDiv);
+ };
+
+ self.getosname = function() {
+ return objJSExt.sendCmd("osname");
+ };
+
+ self.require = function(strLibrary) {
+ // Load a required JNEXT plugin
+ var strCmd;
+ var strVal;
+ var arParams;
+
+ if(m_bFirstRequire) {
+ strCmd = "userAgent " + navigator.userAgent;
+ strVal = objJSExt.sendCmd(strCmd);
+ arParams = strVal.split(" ");
+ if(arParams[0] != "Ok") {
+ alert("userAgent " + strVal);
+ return false;
+ }
+ self.m_bFirstRequire = false;
+ }
+ strCmd = "Require " + strLibrary;
+ strVal = objJSExt.sendCmd(strCmd);
+ arParams = strVal.split(" ");
+ if(arParams[0] != "Ok") {
+ alert("Require " + strVal);
+ return false;
+ }
+
+ return true;
+ };
+
+ self.createObject = function(strObjName) {
+ // Create an instance of a native object
+ var strCmd;
+ var strVal;
+ var arParams;
+ strVal = objJSExt.sendCmd("CreateObject " + strObjName);
+ arParams = strVal.split(" ");
+ if(arParams[0] != "Ok") {
+ alert("CreateObject: " + strVal);
+ return "";
+ }
+ return arParams[1];
+ };
+
+ self.invoke = function(strObjId, strMethod, strParams) {
+ // Invoke a method of a given instance of a native object
+ var strCmd = "InvokeMethod " + strObjId + " " + strMethod;
+
+ if( typeof (strParams) != "undefined") {
+ strCmd += " " + strParams;
+ }
+
+ return objJSExt.sendCmd(strCmd);
+ };
+
+ self.registerEvents = function(objNotify) {
+ var strId = objNotify.getId();
+ self.m_arEvents[strId] = objNotify;
+ };
+
+ self.unregisterEvents = function(objNotify) {
+ var strId = objNotify.getId();
+ delete self.m_arEvents[strId];
+ };
+
+ self.processEvent = function(strNativeEvt) {
+ // Process an event received from native code. The event
+ // containes the target JavaScript object id and the
+ // relevant parameters.
+
+ var arParams = strNativeEvt.split(" ");
+ var strObjId = arParams[0];
+ var strEvent = strNativeEvt.substring(strObjId.length + 1);
+
+ var objNotify = self.m_arEvents[strObjId];
+ if( typeof (objNotify) == 'undefined') {
+ alert("Warning: No object with Id " + strId + " found for event " + strEvent);
+ return;
+ }
+
+ // This will now be handled by the appropriate JavaScript
+ // JNEXT extension object
+ objNotify.onEvent(strEvent);
+ };
+
+ self.ajaxGet = function(strUrl, id) {
+ var req = false;
+ if(window.ActiveXObject) {
+ try {
+ req = new ActiveXObject("Msxml2.XMLHTTP");
+ } catch (e) {
+ try {
+ req = new ActiveXObject("Microsoft.XMLHTTP");
+ } catch (ex) {
+ }
+ }
+ } else if(window.XMLHttpRequest) {
+ req = new XMLHttpRequest();
+ } else {
+ return false;
+ }
+
+ req.onreadystatechange = function() {
+ if(req.readyState == 4 && (req.status == 200 || window.location.href.indexOf("http") == -1)) {
+ self.onAjaxRecv(req.responseText);
+ }
+ };
+
+ req.open('GET', strUrl, true);
+ req.send(null);
+ };
+
+ self.onAjaxRecv = function(strContent) {
+ alert(strContent);
+ };
+
+ self.attachToDOM();
+}
+
+window.JNEXT = new JNEXT_();
+module.exports = JNEXT;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/overlayWebView.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/overlayWebView.js b/lib/cordova-blackberry/framework/lib/overlayWebView.js
new file mode 100644
index 0000000..a2bba69
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/overlayWebView.js
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var CHROME_HEIGHT = 0,
+ webview,
+ _webviewObj;
+
+webview =
+ {
+
+ create: function (ready, configSettings) {
+ _webviewObj = window.qnx.webplatform.createUIWebView(function () {
+
+ _webviewObj.visible = true;
+ _webviewObj.active = true;
+ _webviewObj.zOrder = 2;
+ _webviewObj.enableCrossSiteXHR = true;
+ _webviewObj.setGeometry(0, 0, screen.width, screen.height);
+ _webviewObj.addEventListener("DocumentLoadFinished", function () {
+ _webviewObj.default.setDefaultFont();
+ _webviewObj.visible = true;
+ });
+
+ _webviewObj.allowRpc = true;
+ _webviewObj.backgroundColor = 0x00FFFFFF;
+ _webviewObj.sensitivity = "SensitivityTest";
+ _webviewObj.devicePixelRatio = 1;
+ _webviewObj.allowQnxObject = true;
+
+ if (ready && typeof ready === 'function') {
+ ready();
+ }
+
+ window.qnx.webplatform.getController().dispatchEvent("overlayWebView.initialized", [_webviewObj]);
+
+ });
+ },
+
+ destroy: function () {
+ _webviewObj.destroy();
+ },
+
+ setURL: function (url) {
+ _webviewObj.url = url;
+ },
+
+ setGeometry: function (x, y, width, height) {
+ _webviewObj.setGeometry(x, y, width, height);
+ },
+
+ setSensitivity : function (sensitivity) {
+ _webviewObj.sensitivity = sensitivity;
+ },
+
+ setApplicationOrientation: function (angle) {
+ _webviewObj.setApplicationOrientation(angle);
+ },
+
+ notifyApplicationOrientationDone: function () {
+ _webviewObj.notifyApplicationOrientationDone();
+ },
+
+ executeJavascript: function (js) {
+ _webviewObj.executeJavaScript(js);
+ },
+
+ windowGroup: function () {
+ return _webviewObj.windowGroup;
+ },
+
+ notifyContextMenuCancelled: function () {
+ _webviewObj.notifyContextMenuCancelled();
+ },
+
+ bindAppWebViewToChildWebViewControls: function (appWebView) {
+ if (_webviewObj && _webviewObj.childwebviewcontrols) {
+ _webviewObj.childwebviewcontrols.subscribeTo(appWebView);
+ }
+ },
+
+ renderContextMenuFor: function (targetWebView) {
+ return _webviewObj.contextMenu.subscribeTo(targetWebView);
+ },
+
+ handleDialogFor: function (targetWebView) {
+ return _webviewObj.dialog.subscribeTo(targetWebView);
+ },
+
+ showDialog: function (description, callback) {
+ return _webviewObj.dialog.show(description, callback);
+ },
+
+ getWebViewObj: function (webview) {
+ return _webviewObj;
+ },
+
+ addEventListener: function (eventName, callback) {
+ _webviewObj.addEventListener(eventName, callback);
+ },
+
+ removeEventListener: function (eventName, callback) {
+ _webviewObj.removeEventListener(eventName, callback);
+ },
+
+ showToast : function (message, options) {
+ return _webviewObj.toast.show(message, options);
+ },
+
+ showInvocationList: function (request, title, success, error) {
+ _webviewObj.invocationlist.show(request, title, success, error);
+ }
+};
+
+webview.__defineGetter__('id', function () {
+ if (_webviewObj) {
+ return _webviewObj.id;
+ }
+});
+
+webview.__defineGetter__('zOrder', function () {
+ return _webviewObj.zOrder;
+});
+
+webview.__defineGetter__('contextMenu', function () {
+ if (_webviewObj) {
+ return _webviewObj.contextMenu;
+ }
+});
+
+module.exports = webview;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/plugins/default.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/plugins/default.js b/lib/cordova-blackberry/framework/lib/plugins/default.js
new file mode 100644
index 0000000..8347917
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/plugins/default.js
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2010-2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var Whitelist = require("../policy/whitelist").Whitelist,
+ whitelist = new Whitelist();
+
+module.exports = {
+
+ exec: function (request, succ, fail, args, env) {
+ var extPath = "plugin/" + request.params.ext + "/index",
+ requestObj = {
+ extension: null,
+ method: null,
+ getExtension: function () {
+ if (frameworkModules.indexOf(extPath + ".js") !== -1) {
+ this.extension = require("../utils").loadModule("../" + extPath);
+ return requestObj;
+ } else {
+ throw {code: 404, msg: "Extension " + request.params.ext + " not found"};
+ }
+ },
+ getMethod: function () {
+ var methodParts = request.params.method ? request.params.method.split('/') : [request.params.method],
+ extMethod;
+
+ try {
+ extMethod = this.extension[methodParts.shift()];
+ extMethod = methodParts.reduce(function (previous, current) {
+ if (previous[current]) {
+ return previous[current];
+ } else {
+ throw {code: 404, msg: "Method " + request.params.method + " for " + request.params.ext + " not found"};
+ }
+ }, extMethod);
+
+ if (extMethod && typeof extMethod === "function") {
+ this.method = extMethod;
+ return requestObj;
+ } else {
+ throw {code: 404, msg: "Method " + request.params.method + " for " + request.params.ext + " not found"};
+ }
+ } catch (e) {
+ throw {code: 404, msg: "Method " + request.params.method + " for " + request.params.ext + " not found"};
+ }
+ },
+ exec: function () {
+ this.method(succ, fail, args, env);
+ }
+ };
+
+ try {
+ requestObj.getExtension().getMethod().exec();
+ } catch (e) {
+ console.warn(e.msg);
+ fail(-1, e.msg, e.code);
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/plugins/event.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/plugins/event.js b/lib/cordova-blackberry/framework/lib/plugins/event.js
new file mode 100644
index 0000000..441bc70
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/plugins/event.js
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var _event = require("../../lib/event"),
+ ONCE_EVENT_ERROR = "Error occured while adding once event listener.",
+ ERROR_ID = -1;
+
+module.exports = {
+ once: function (request, success, fail, args, env) {
+ try {
+ var eventName = decodeURIComponent(args.eventName).replace(/\"/g, ""),
+ action = {
+ once: true,
+ event: eventName
+ };
+
+ _event.add(action, env.webview);
+
+ if (success) {
+ success();
+ }
+ }
+ catch (e) {
+ if (fail) {
+ fail(ERROR_ID, ONCE_EVENT_ERROR);
+ }
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/policy/folderAccess.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/policy/folderAccess.js b/lib/cordova-blackberry/framework/lib/policy/folderAccess.js
new file mode 100644
index 0000000..5cd5690
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/policy/folderAccess.js
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var util = require("../utils");
+
+// Removes the start and end slashes from the path
+function _trimSurroundingSlashes(path) {
+ // Trim starting slash
+ if (util.startsWith(path, "/")) {
+ path = path.substr(1);
+ }
+
+ // Trim ending slash
+ if (util.endsWith(path, "/")) {
+ path = path.substr(0, path.length - 1);
+ }
+
+ return path;
+}
+
+// Determines the depth of the given path
+// Folder path must not include the scheme or the host
+function _determineDepth(folderPath) {
+ var depthCount = 0;
+
+ // Replace all backslashes with forward slash
+ folderPath = folderPath.replace("\\", "/");
+
+ // Special case: "/" is the given path
+ if (folderPath === "/") {
+ return 0;
+ }
+
+ folderPath = _trimSurroundingSlashes(folderPath);
+
+ // Count slashes remaining
+ while (folderPath.indexOf("/") !== -1) {
+ depthCount = depthCount + 1;
+
+ // Add 1 to skip the slash
+ folderPath = folderPath.substring(folderPath.indexOf("/") + 1);
+ }
+
+ // Add one more for the remaining folder
+ depthCount += 1;
+
+ return depthCount;
+}
+
+// Parse a folder path up to the desired depth
+function _getPath(folderPath, desiredDepth) {
+ var depthCount = 0, builtPath = "";
+
+ // Special case: Desired depth is 0
+ if (desiredDepth === 0) {
+ return "/";
+ }
+
+ // Replace all backslashes with forward slash
+ folderPath = folderPath.replace("\\", "/");
+
+ folderPath = _trimSurroundingSlashes(folderPath);
+
+ // Count slashes remaining
+ while (depthCount < desiredDepth) {
+ depthCount += 1;
+
+ // Add 1 to skip the slash
+ builtPath += "/" + folderPath.substring(0, folderPath.indexOf('/'));
+ folderPath = folderPath.substring(folderPath.indexOf('/') + 1);
+ }
+
+ return builtPath;
+}
+
+function WebFolderAccessManager() {
+ this._pathCollection = {};
+ this._maxPathLength = 0;
+}
+
+WebFolderAccessManager.prototype.addAccess = function (folderPath, access) {
+ if (!folderPath) {
+ folderPath = "/";
+ }
+
+ // Trim surrounding slashes for consistency
+ // The root "/" is a special case that does not need this trimming
+ if (folderPath !== "/") {
+ folderPath = "/" + _trimSurroundingSlashes(folderPath);
+ }
+
+ folderPath = folderPath.toLowerCase();
+
+ this._pathCollection[folderPath] = access;
+
+ // Determine the depth of the path
+ this._maxPathLength = Math.max(this._maxPathLength, _determineDepth(folderPath));
+};
+
+WebFolderAccessManager.prototype.getAccess = function (folderPath) {
+ var depth = _determineDepth(folderPath);
+ return this.getAccessRecursively(folderPath, depth);
+};
+
+WebFolderAccessManager.prototype.fetchAccess = function (folderPath) {
+ var queryIndex, folderPathWildcard;
+
+ if (!this._pathCollection.hasOwnProperty(folderPath)) {
+ // If there isn't an exact match and folderPath contains query string,
+ // check if the path collection contains an access with the same folderPath
+ // but with wildcard query
+ if ((queryIndex = folderPath.indexOf("?")) > -1) {
+ folderPathWildcard = folderPath.slice(0, queryIndex + 1) + "*";
+
+ if (this._pathCollection.hasOwnProperty(folderPathWildcard)) {
+ return this._pathCollection[folderPathWildcard];
+ }
+ }
+
+ return null;
+ } else {
+ return this._pathCollection[folderPath];
+ }
+};
+
+WebFolderAccessManager.prototype.getAccessRecursively = function (folderPath, pathLength) {
+ var fetchedAccess,
+ newPathLength,
+ newPath;
+
+ if (!folderPath) {
+ return null;
+ }
+
+ folderPath = folderPath.toLowerCase();
+
+ if (!!(fetchedAccess = this.fetchAccess(folderPath))) {
+ return fetchedAccess;
+ } else {
+ // Truncate the end portion of the path and try again
+ newPathLength = Math.min(this._maxPathLength, pathLength - 1);
+ newPath = _getPath(folderPath, newPathLength);
+
+ return this.getAccessRecursively(newPath, newPathLength);
+ }
+};
+
+function WebFolderAccess() {
+ this._mgr = new WebFolderAccessManager();
+}
+
+// folderPath - folder path must not include the scheme or the host
+WebFolderAccess.prototype.addAccess = function (folderPath, access) {
+ this._mgr.addAccess(folderPath, access);
+};
+
+// folderPath - folder path must not include the scheme or the host
+WebFolderAccess.prototype.getAccess = function (folderPath) {
+ return this._mgr.getAccess(folderPath);
+};
+
+exports.WebFolderAccess = WebFolderAccess;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/policy/webkitOriginAccess.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/policy/webkitOriginAccess.js b/lib/cordova-blackberry/framework/lib/policy/webkitOriginAccess.js
new file mode 100644
index 0000000..84adb49
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/policy/webkitOriginAccess.js
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var config = require('./../config'),
+ utils = require('./../utils'),
+ Whitelist = require('./whitelist').Whitelist,
+ LOCAL_URI = "local://",
+ FILE_URI = "file://",
+ WW_URI = utils.getURIPrefix(),
+ _domains = [
+ {
+ url: LOCAL_URI,
+ allowSubDomains: true
+ }
+ ],
+ _webviews = [],
+ _isInitialized = false,
+ _whitelist = new Whitelist();
+
+function addOriginAccessWhitelistEntry(webview, source, destination, allowSubDomains) {
+ webview.addOriginAccessWhitelistEntry(source, destination, !!allowSubDomains);
+}
+
+function addDomain(url, allowSubDomains) {
+ var parsedUri = utils.parseUri(url);
+
+ allowSubDomains = !!allowSubDomains;
+
+ if (utils.isLocalURI(parsedUri)) {
+ url = LOCAL_URI;
+ } else if (utils.isFileURI(parsedUri)) {
+ url = FILE_URI;
+ } else {
+ url = parsedUri.source;
+ }
+
+ if (_whitelist.isAccessAllowed(url) && !_domains.some(function (domain) {
+ return domain.url === url;
+ })) {
+ _webviews.forEach(function (webview) {
+ addOriginAccessWhitelistEntry(webview, url, WW_URI, true);
+
+ _domains.forEach(function (domain) {
+ addOriginAccessWhitelistEntry(webview, domain.url, url, allowSubDomains);
+ addOriginAccessWhitelistEntry(webview, url, domain.url, domain.allowSubDomains);
+ });
+
+ });
+
+ _domains.push({
+ url: url,
+ allowSubDomains: allowSubDomains
+ });
+ }
+}
+
+function initializeDomains() {
+ var accessElements = config.accessList;
+
+ accessElements.forEach(function (element, index, array) {
+ var uri = (element.uri === 'WIDGET_LOCAL' ? LOCAL_URI : element.uri);
+ addDomain(uri, !!element.allowSubDomain);
+ });
+}
+
+function initializaWebview(webview) {
+ //Always allow file access from local and let the OS deal with permissions
+ addOriginAccessWhitelistEntry(webview, LOCAL_URI, FILE_URI, true);
+ addOriginAccessWhitelistEntry(webview, FILE_URI, LOCAL_URI, true);
+ //Always allow LOCAL access to URIs
+ addOriginAccessWhitelistEntry(webview, LOCAL_URI, WW_URI, true);
+
+ _domains.forEach(function (domain, domainIndex, domainArray) {
+ var i,
+ nextDomain;
+
+ if (domain.uri !== LOCAL_URI) {
+ addOriginAccessWhitelistEntry(webview, domain.url, WW_URI, true);
+ }
+
+ for (i = domainIndex + 1; i < domainArray.length; i++) {
+ nextDomain = domainArray[i];
+ addOriginAccessWhitelistEntry(webview, domain.url, nextDomain.url, nextDomain.allowSubDomains);
+ addOriginAccessWhitelistEntry(webview, nextDomain.url, domain.url, domain.allowSubDomains);
+ }
+ });
+
+}
+
+module.exports = {
+
+ addWebView: function (webview) {
+ if (_webviews.indexOf(webview) === -1) {
+ _webviews.push(webview);
+ initializaWebview(webview);
+ if (!_isInitialized) {
+ initializeDomains();
+ _isInitialized = true;
+ }
+ }
+ },
+
+ addOriginAccess: function (origin, allowSubDomains) {
+ if (!_isInitialized) {
+ initializeDomains();
+ _isInitialized = true;
+ }
+ addDomain(origin, allowSubDomains);
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/policy/whitelist.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/policy/whitelist.js b/lib/cordova-blackberry/framework/lib/policy/whitelist.js
new file mode 100644
index 0000000..dcfbc3c
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/policy/whitelist.js
@@ -0,0 +1,317 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var WebFolderAccess = require("./folderAccess").WebFolderAccess,
+ util = require("../utils");
+
+function _isLocalAccess(access) {
+ return access && access.uri === "WIDGET_LOCAL";
+}
+
+function _isMatch(access, requestURI) {
+ // Look for local first
+ if (_isLocalAccess(access)) {
+ // Local access always allowed
+ //THIS USED TO RETURN TRUE FOR FILE ACCESS
+ //I HAVE TURNED IT OFF BECAUSE IT MAKES NO SENSE THAT LOCAL ACCESS ALWAYS MATCHES FILE ACCESS
+ return (util.isLocalURI(requestURI));
+ } else if (util.isDataURI(requestURI)) {
+ // Check for data url
+ // data urls are allowed
+ return true;
+ }
+
+ // Based on widgets 1.0 (access control)
+ // http://www.w3.org/TR/2009/WD-widgets-access-20090618/#rfc3987
+ var refURI = util.parseUri(access.uri),
+ allowSub = access.allowSubDomain;
+
+ if (!requestURI.path) {
+ requestURI.path = "/";
+ }
+
+ // Start comparison based on widget spec.
+ // 1. Compare scheme
+ if (refURI.scheme.toLowerCase() !== requestURI.scheme.toLowerCase()) {
+ return false;
+ }
+
+ // 2. Compare host - if subdoman is false, host must match exactly
+ // (referenceURI MUST HAVE host specified - not null.)
+ // Special Case: Ignore this condition if we are dealing with file://
+ if (!requestURI.authority && !util.isFileURI(requestURI)) {
+ return false;
+ }
+
+ if (!allowSub && refURI.host.toLowerCase() !== requestURI.host.toLowerCase()) {
+ return false;
+ }
+
+ // 3. Compare host - if subdomain is true, check for subdomain or match
+ if (allowSub && !util.endsWith(requestURI.host.toLowerCase(), "." + refURI.host.toLowerCase()) &&
+ requestURI.host.toLowerCase() !== refURI.host.toLowerCase()) {
+ return false;
+ }
+
+ // 4. Compare port
+ if (refURI.port && refURI.port !== requestURI.port) {
+ return false;
+ }
+
+ // 5. Compare path+query
+ if (!util.startsWith(requestURI.path.toLowerCase(), refURI.path.toLowerCase()) && refURI.query !== "*") {
+ return false;
+ }
+
+ return true;
+}
+
+function _getAccessForPathAndQuery(folderAccess, path, query) {
+ if (folderAccess) {
+ if (!query) {
+ return folderAccess.getAccess(path);
+ } else {
+ return folderAccess.getAccess(path + "?" + query);
+ }
+ }
+
+ return null;
+}
+
+function AccessManager(config) {
+ config = config || require("../config");
+
+ this._accessList = config.accessList;
+ this._hasGlobalAccess = config.hasMultiAccess;
+ this._authorityCollection = null;
+ this._localAccess = null;
+}
+
+AccessManager.prototype.getFolderAccess = function (scheme, authority) {
+ var key = scheme + "://" + authority;
+ key = key.toLowerCase();
+
+ if (this._authorityCollection.hasOwnProperty(key)) {
+ return this._authorityCollection[key];
+ }
+
+ return null;
+};
+
+AccessManager.prototype.putFolderAccess = function (scheme, authority, folderAccess) {
+ var key = scheme + "://" + authority;
+ key = key.toLowerCase();
+ this._authorityCollection[key] = folderAccess;
+};
+
+AccessManager.prototype.initializeAuthCollection = function () {
+ var folderAccess, currentURI, that = this;
+
+ if (!this._authorityCollection) {
+ this._authorityCollection = {};
+
+ if (this._accessList) {
+ this._accessList.forEach(function (access) {
+ if (_isLocalAccess(access)) {
+ that._localAccess = access;
+ } else {
+ currentURI = util.parseUri(access.uri);
+
+ // Check the authority collection to see if the authority item
+ // we want already exists
+ folderAccess = that.getFolderAccess(currentURI.scheme, currentURI.authority) || new WebFolderAccess();
+
+ // Add folder path access to the authority item
+ if (!currentURI.query) {
+ folderAccess.addAccess(currentURI.path, access);
+ } else {
+ folderAccess.addAccess(currentURI.path + "?" + currentURI.query, access);
+ }
+
+ that.putFolderAccess(currentURI.scheme, currentURI.authority, folderAccess);
+ }
+ });
+ }
+ }
+};
+
+AccessManager.prototype.authorityCheck = function (port, scheme, authority) {
+ var originalAuthority = authority;
+
+ if (port) {
+ // If authority has a specific port, and the collection does not have an access matches
+ // the exact authority, strip port from authority to see if there is a match
+ if (!this.getFolderAccess(scheme, authority)) {
+ authority = authority.slice(0, authority.lastIndexOf(":"));
+ authority = this.authorityCheck("", scheme, authority);
+ }
+
+ //If no successful match was found without the port, reset the authority and try with it
+ if (!this.getFolderAccess(scheme, authority)) {
+ authority = originalAuthority;
+ }
+ }
+
+ if (authority.indexOf(".") === -1) {
+ // If authority is computer name, must have exact match in collection
+ if (!this.getFolderAccess(scheme, authority)) {
+ return "";
+ }
+
+ return authority;
+ }
+
+ while (authority && !this.getFolderAccess(scheme, authority)) {
+ if (authority.indexOf(".") === -1) {
+ return "";
+ }
+ authority = authority.substring(authority.indexOf(".") + 1);
+ }
+
+ return authority;
+};
+
+AccessManager.prototype.getFromFolderAccess = function (folderAccess, requestURI) {
+ var fetchedAccess = null,
+ scheme = requestURI.scheme,
+ authority = requestURI.authority,
+ path = requestURI.path,
+ query = requestURI.query,
+ prevAuthority;
+
+ if (!path) {
+ fetchedAccess = folderAccess.getAccess("/");
+ } else {
+ fetchedAccess = _getAccessForPathAndQuery(folderAccess, path, query);
+ }
+
+ // Make sure we've got the right one
+ while (!fetchedAccess || !_isMatch(fetchedAccess, requestURI)) {
+ // There was an auth url that matched, but didnt match the folder structure
+ // Try the next level up
+ prevAuthority = authority;
+ authority = authority.substring(authority.indexOf(".") + 1);
+ //If authority hasn't changed, then this loop will continue endlessly because nothing else has changed
+ //This will happen when an element has the same authority but no folder access.
+ if (prevAuthority === authority) {
+ return null;
+ }
+
+ // Check for an authority string that has an existing key
+ authority = this.authorityCheck(requestURI.port, scheme, authority);
+ if (!authority) {
+ return null;
+ }
+
+ // Retrieve access set for the specified authority
+ folderAccess = this.getFolderAccess(scheme, authority);
+
+ // Special case: no access element was found for a file protocol request.
+ // This is added since file protocol was allowed through the above check
+ if (scheme === "file" && !folderAccess) {
+ return null;
+ }
+
+ fetchedAccess = _getAccessForPathAndQuery(folderAccess, path, query);
+ }
+
+ return fetchedAccess;
+};
+
+AccessManager.prototype.getAccessByUrl = function (url) {
+ var requestURI = util.parseUri(url),
+ authority = requestURI.authority,
+ scheme = requestURI.scheme,
+ folderAccess,
+ fetchedAccess;
+
+ if (util.isAbsoluteURI(requestURI)) {
+ // Initialize authority collection if it does not yet exist
+ this.initializeAuthCollection();
+
+ // Start with the full authority path and check if an access exists for that path
+ // If it does not exist, remove the first section of the authority path and try again
+
+ // Check for an authority string that has an existing key
+ // Special case: Allow file, and local protocol to proceed without an authority
+ authority = this.authorityCheck(requestURI.port, scheme, authority);
+ if (!authority && !(scheme === "file" || scheme === "local" || scheme === "data")) {
+ return null;
+ }
+ // Retrieve access set for the specified authority
+ folderAccess = this.getFolderAccess(scheme, authority);
+
+ // Special case: no access was found for a file protocol request
+ // This is added since file protocol was allowed through the above check
+ if (scheme === "file" && !folderAccess) {
+ return null;
+ } else if (scheme === "local" && !folderAccess) {
+ // If no access element is found with local URI, use local access for this request
+ return this._localAccess;
+ } else if (scheme === "data") {
+ // Always allow data-uris
+ return true;
+ }
+
+ fetchedAccess = this.getFromFolderAccess(folderAccess, requestURI);
+
+ if (fetchedAccess) {
+ return fetchedAccess;
+ } else if (this._localAccess && _isMatch(this._localAccess, requestURI)) {
+ // If we cannot find a more specific access for this local URI, use local access
+ return this._localAccess;
+ } else if (folderAccess && _isMatch(folderAccess, requestURI)) {
+ return folderAccess;
+ }
+ }
+
+ return null;
+};
+
+AccessManager.prototype.hasGlobalAccess = function () {
+ return this._hasGlobalAccess;
+};
+
+function Whitelist(config) {
+ this._mgr = new AccessManager(config);
+}
+
+Whitelist.prototype.getFeaturesForUrl = function (url) {
+ var access = this._mgr.getAccessByUrl(url),
+ featureIds = [];
+
+ if (access && access.features) {
+ access.features.forEach(function (elem) {
+ featureIds.push(elem.id);
+ });
+ }
+
+ return featureIds;
+};
+
+Whitelist.prototype.isFeatureAllowed = function (url, feature) {
+ var features = this.getFeaturesForUrl(url);
+
+ return !!features && features.reduce(function (found, current) {
+ return found || current === feature;
+ }, false);
+};
+
+Whitelist.prototype.isAccessAllowed = function (url, isXHR) {
+ return (this._mgr.hasGlobalAccess() && !isXHR) || !!this._mgr.getAccessByUrl(url);
+};
+
+exports.Whitelist = Whitelist;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/server.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/server.js b/lib/cordova-blackberry/framework/lib/server.js
new file mode 100644
index 0000000..15b95b0
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/server.js
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var DEFAULT_SERVICE = "default",
+ DEFAULT_ACTION = "exec";
+
+function rebuildRequest(req) {
+ var originalURL = req.params.service + "/" +
+ req.params.action +
+ (req.params.ext ? "/" + req.params.ext : "") +
+ (req.params.method ? "/" + req.params.method : "") +
+ (req.params.args ? "?" + req.params.args : ""),
+ tokens = originalURL.split('/'),
+ //Handle the case where the method is multi-level
+ finalToken = (tokens[1] && tokens.length > 2) ? tokens.slice(1).join('/') : tokens[1],
+ args = null;
+
+ // set args
+ if (finalToken && finalToken.indexOf("?") >= 0) {
+ // Re-split args
+ args = finalToken.split("?")[1];
+ }
+
+ return {
+ params : {
+ service : DEFAULT_SERVICE,
+ action : DEFAULT_ACTION,
+ ext : tokens[0],
+ method : (finalToken && finalToken.indexOf("?") >= 0) ? finalToken.split("?")[0] : finalToken,
+ args : args
+ },
+ body : req.body,
+ origin : req.origin
+ };
+}
+
+function parseArgs(req) {
+ var args = null,
+ params;
+ // set args
+ if (req.params.args && typeof req.params.args === "string") {
+ // GET querystring to json
+ params = req.params.args.split("&");
+ if (params) {
+ args = {};
+ params.forEach(function (param) {
+ var parts = param.split("=");
+ args[parts[0]] = parts[1];
+ });
+ }
+ } else {
+ // POST body to json
+ if (req.body) {
+ args = JSON.parse(req.body);
+ }
+ }
+ req.params.args = args;
+}
+
+module.exports = {
+ handle: function (req, res, sourceWebview, config) {
+ try {
+ var pluginName = "lib/plugins/" + req.params.service,
+ plugin;
+
+ if (frameworkModules.indexOf(pluginName + ".js") === -1) {
+ pluginName = "lib/plugins/" + DEFAULT_SERVICE;
+ req = rebuildRequest(req);
+ }
+
+ parseArgs(req);
+
+ //Updating because some versions of node only work with relative paths
+ pluginName = pluginName.replace('lib', '.');
+
+ plugin = require("./utils").loadModule(pluginName);
+
+ plugin[req.params.action](req,
+ function (result) {
+ res.send(200, encodeURIComponent(JSON.stringify({
+ code: 42,
+ data: result
+ })));
+ },
+ function (code, error, httpCode) {
+ if (!httpCode) {
+ httpCode = 200;
+ }
+
+ res.send(httpCode, encodeURIComponent(JSON.stringify({
+ code: Math.abs(code) * -1 || -1,
+ data: null,
+ msg: error
+ })));
+ },
+ req.params.args,
+ {
+ "request": req,
+ "response": res,
+ "webview": sourceWebview,
+ "config": config
+ });
+ } catch (e) {
+ console.error(e);
+ res.send(404, "can't find the stuff");
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/utils.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/utils.js b/lib/cordova-blackberry/framework/lib/utils.js
new file mode 100644
index 0000000..4ab008a
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/utils.js
@@ -0,0 +1,549 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var self,
+ exception = require('./exception');
+
+function S4() {
+ return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
+}
+
+self = module.exports = {
+ validateNumberOfArguments: function (lowerBound, upperBound, numberOfArguments, customExceptionType, customExceptionMessage, customExceptionObject) {
+
+ customExceptionMessage = customExceptionMessage || "";
+
+ if (arguments.length < 3 || arguments.length > 6) {
+ exception.raise(exception.types.Argument, "Wrong number of arguments when calling: validateNumberOfArguments()");
+ }
+
+ if (isNaN(lowerBound) && isNaN(upperBound) && isNaN(numberOfArguments)) {
+ exception.raise(exception.types.ArgumentType, "(validateNumberOfArguments) Arguments are not numbers");
+ }
+
+ lowerBound = parseInt(lowerBound, 10);
+ upperBound = parseInt(upperBound, 10);
+ numberOfArguments = parseInt(numberOfArguments, 10);
+
+ if (numberOfArguments < lowerBound || numberOfArguments > upperBound) {
+ exception.raise((customExceptionType || exception.types.ArgumentLength), (customExceptionMessage + "\n\nWrong number of arguments"), customExceptionObject);
+ }
+
+ },
+
+ validateArgumentType: function (arg, argType, customExceptionType, customExceptionMessage, customExceptionObject) {
+ var invalidArg = false,
+ msg;
+
+ switch (argType) {
+ case "array":
+ if (!arg instanceof Array) {
+ invalidArg = true;
+ }
+ break;
+ case "date":
+ if (!arg instanceof Date) {
+ invalidArg = true;
+ }
+ break;
+ case "integer":
+ if (typeof arg === "number") {
+ if (arg !== Math.floor(arg)) {
+ invalidArg = true;
+ }
+ }
+ else {
+ invalidArg = true;
+ }
+ break;
+ default:
+ if (typeof arg !== argType) {
+ invalidArg = true;
+ }
+ break;
+ }
+
+ if (invalidArg) {
+ msg = customExceptionMessage + ("\n\nInvalid Argument type. argument: " + arg + " ==> was expected to be of type: " + argType);
+ exception.raise((customExceptionType || exception.types.ArgumentType), msg, customExceptionObject);
+ }
+ },
+
+ validateMultipleArgumentTypes: function (argArray, argTypeArray, customExceptionType, customExceptionMessage, customExceptionObject) {
+ for (var i = 0; i < argArray.length; i++) {
+ this.validateArgumentType(argArray[i], argTypeArray[i], customExceptionType, customExceptionMessage, customExceptionObject);
+ }
+ },
+
+ arrayContains: function (array, obj) {
+ var i = array.length;
+ while (i--) {
+ if (array[i] === obj) {
+ return true;
+ }
+ }
+ return false;
+ },
+
+ some: function (obj, predicate, scope) {
+ if (obj instanceof Array) {
+ return obj.some(predicate, scope);
+ }
+ else {
+ var values = self.map(obj, predicate, scope);
+
+ return self.reduce(values, function (some, value) {
+ return value ? value : some;
+ }, false);
+ }
+ },
+
+ count: function (obj) {
+ return self.sum(obj, function (total) {
+ return 1;
+ });
+ },
+
+ sum: function (obj, selector, scope) {
+ var values = self.map(obj, selector, scope);
+ return self.reduce(values, function (total, value) {
+ return total + value;
+ });
+ },
+
+ max: function (obj, selector, scope) {
+ var values = self.map(obj, selector, scope);
+ return self.reduce(values, function (max, value) {
+ return max < value ? value : max;
+ }, Number.MIN_VALUE);
+ },
+
+ min: function (obj, selector, scope) {
+ var values = self.map(obj, selector, scope);
+ return self.reduce(values, function (min, value) {
+ return min > value ? value : min;
+ }, Number.MAX_VALUE);
+ },
+
+ forEach: function (obj, action, scope) {
+ if (obj instanceof Array) {
+ return obj.forEach(action, scope);
+ }
+ else {
+ self.map(obj, action, scope);
+ }
+ },
+
+ filter: function (obj, predicate, scope) {
+ if (obj instanceof Array) {
+ return obj.filter(predicate, scope);
+ }
+ else {
+ var result = [];
+ self.forEach(obj, function (value, index) {
+ if (predicate.apply(scope, [value, index])) {
+ result.push(value);
+ }
+
+ }, scope);
+
+ return result;
+ }
+ },
+
+ reduce: function (obj, func, init, scope) {
+ var i,
+ initial = init === undefined ? 0 : init,
+ result = initial;
+
+
+ if (obj instanceof Array) {
+ return obj.reduce(func, initial);
+ }
+ else if (obj instanceof NamedNodeMap) {
+ for (i = 0; i < obj.length; i++) {
+ result = func.apply(scope, [result, obj[i], i]);
+ }
+ }
+ else {
+ for (i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ result = func.apply(scope, [result, obj[i], i]);
+ }
+ }
+ }
+
+ return result;
+
+ },
+
+ map: function (obj, func, scope) {
+ var i,
+ returnVal = null,
+ result = [];
+
+ if (obj instanceof Array) {
+ return obj.map(func, scope);
+ }
+ else if (obj instanceof NamedNodeMap) {
+ for (i = 0; i < obj.length; i++) {
+ returnVal = func.apply(scope, [obj[i], i]);
+ result.push(returnVal);
+ }
+ }
+ else {
+ for (i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ returnVal = func.apply(scope, [obj[i], i]);
+ result.push(returnVal);
+ }
+ }
+ }
+
+ return result;
+ },
+
+ series: function (tasks, callback) {
+
+ var execute = function () {
+ var args = [],
+ task;
+
+ if (tasks.length) {
+ task = tasks.shift();
+ args = args.concat(task.args).concat(execute);
+ task.func.apply(this, args);
+ }
+ else {
+ callback.func.apply(this, callback.args);
+ }
+ };
+
+ execute();
+ },
+
+ regexSanitize: function (regexString) {
+ return regexString.replace("^", "\\^")
+ .replace("$", "\\$")
+ .replace("(", "\\(")
+ .replace(")", "\\)")
+ .replace("<", "\\<")
+ .replace("[", "\\[")
+ .replace("{", "\\{")
+ .replace(/\\/, "\\\\")
+ .replace("|", "\\|")
+ .replace(">", "\\>")
+ .replace(".", "\\.")
+ .replace("*", "\\*")
+ .replace("+", "\\+")
+ .replace("?", "\\?");
+ },
+
+ find: function (comparison, collection, startInx, endInx, callback) {
+ var results = [],
+ compare = function (s, pattern) {
+
+ if (typeof(s) !== "string" || pattern === null) {
+ return s === pattern;
+ }
+
+ var regex = pattern.replace(/\./g, "\\.")
+ .replace(/\^/g, "\\^")
+ .replace(/\*/g, ".*")
+ .replace(/\\\.\*/g, "\\*");
+
+ regex = "^".concat(regex, "$");
+
+ return !!s.match(new RegExp(regex, "i"));
+ };
+
+ self.forEach(collection, function (c) {
+ var match,
+ fail = false;
+
+ self.forEach(comparison, function (value, key) {
+ if (!fail && value !== undefined) {
+
+ if (compare(c[key], value)) {
+ match = c;
+ }
+ else {
+ fail = true;
+ match = null;
+ }
+ }
+ });
+
+ if (match) {
+ results.push(match);
+ }
+ });
+
+ if (callback) {
+ if (startInx === undefined) {
+ startInx = 0;
+ }
+ if (endInx === undefined) {
+ endInx = results.length;
+ }
+ if (startInx === endInx) {
+ endInx = startInx + 1;
+ }
+
+ callback.apply(null, [results.slice(startInx, endInx)]);
+ }
+ },
+
+ mixin: function (mixin, to) {
+ Object.getOwnPropertyNames(mixin).forEach(function (prop) {
+ if (Object.hasOwnProperty.call(mixin, prop)) {
+ Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(mixin, prop));
+ }
+ });
+ return to;
+ },
+
+ copy: function (obj) {
+ var i,
+ newObj = (obj === null ? false : global.toString.call(obj) === "[object Array]") ? [] : {};
+
+ if (typeof obj === 'number' ||
+ typeof obj === 'string' ||
+ typeof obj === 'boolean' ||
+ obj === null ||
+ obj === undefined) {
+ return obj;
+ }
+
+ if (obj instanceof Date) {
+ return new Date(obj);
+ }
+
+ if (obj instanceof RegExp) {
+ return new RegExp(obj);
+ }
+
+ for (i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ if (obj[i] && typeof obj[i] === "object") {
+ if (obj[i] instanceof Date) {
+ newObj[i] = obj[i];
+ }
+ else {
+ newObj[i] = self.copy(obj[i]);
+ }
+ }
+ else {
+ newObj[i] = obj[i];
+ }
+ }
+ }
+
+ return newObj;
+ },
+
+ startsWith : function (str, substr) {
+ return str.indexOf(substr) === 0;
+ },
+
+ endsWith : function (str, substr) {
+ return str.indexOf(substr, str.length - substr.length) !== -1;
+ },
+
+ parseUri : function (str) {
+ var i, uri = {},
+ key = [ "source", "scheme", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor" ],
+ matcher = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(str);
+
+ for (i = key.length - 1; i >= 0; i--) {
+ uri[key[i]] = matcher[i] || "";
+ }
+
+ return uri;
+ },
+
+ // uri - output from parseUri
+ isAbsoluteURI : function (uri) {
+ if (uri && uri.source) {
+ return uri.relative !== uri.source;
+ }
+
+ return false;
+ },
+
+ fileNameToImageMIME : function (fileName) {
+
+ var extensionsToMIME = {},
+ ext;
+
+ extensionsToMIME.png = 'image/png';
+ extensionsToMIME.jpg = 'image/jpeg';
+ extensionsToMIME.jpe = 'image/jpeg';
+ extensionsToMIME.jpeg = 'image/jpeg';
+ extensionsToMIME.gif = 'image/gif';
+ extensionsToMIME.bmp = 'image/bmp';
+ extensionsToMIME.bm = 'image/bmp';
+ extensionsToMIME.svg = 'image/svg+xml';
+ extensionsToMIME.tif = 'image/tiff';
+ extensionsToMIME.tiff = 'image/tiff';
+
+ ext = fileName.split('.').pop();
+ return extensionsToMIME[ext];
+ },
+
+ isLocalURI : function (uri) {
+ return uri && uri.scheme && "local:///".indexOf(uri.scheme.toLowerCase()) !== -1;
+ },
+
+ isFileURI : function (uri) {
+ return uri && uri.scheme && "file://".indexOf(uri.scheme.toLowerCase()) !== -1;
+ },
+
+ isHttpURI : function (uri) {
+ return uri && uri.scheme && "http://".indexOf(uri.scheme.toLowerCase()) !== -1;
+ },
+
+ isHttpsURI : function (uri) {
+ return uri && uri.scheme && "https://".indexOf(uri.scheme.toLowerCase()) !== -1;
+ },
+
+ // Checks if the specified uri starts with 'data:'
+ isDataURI : function (uri) {
+ return uri && uri.scheme && "data:".indexOf(uri.scheme.toLowerCase()) !== -1;
+ },
+
+ performExec : function (featureId, property, args) {
+ var result;
+
+ window.webworks.exec(function (data, response) {
+ result = data;
+ }, function (data, response) {
+ throw data;
+ }, featureId, property, args, true);
+
+ return result;
+ },
+
+ inNode : function () {
+ return !!require.resolve;
+ },
+
+ requireWebview : function () {
+ return require("./webview");
+ },
+ convertDataToBinary : function (data, dataEncoding) {
+ var rawData,
+ uint8Array,
+ i;
+
+ if (data) {
+ if (dataEncoding.toLowerCase() === "base64") {
+ rawData = window.atob(data);
+ }
+ else {
+ rawData = data;
+ }
+
+ uint8Array = new Uint8Array(new ArrayBuffer(rawData.length));
+
+ for (i = 0; i < uint8Array.length; i++) {
+ uint8Array[i] = rawData.charCodeAt(i);
+ }
+
+ return uint8Array.buffer;
+ }
+ },
+ getBlobWithArrayBufferAsData : function (data, dataEncoding) {
+ var rawData,
+ blobBuilderObj = new window.WebKitBlobBuilder();
+ rawData = this.convertDataToBinary(data, dataEncoding);
+ blobBuilderObj.append(rawData);
+
+ return blobBuilderObj.getBlob("arraybuffer");
+ },
+ loadModule: function (module) {
+ return require(module);
+ },
+ loadExtensionModule: function (plugin, path) {
+ if (plugin && path) {
+ return require("../plugin/" + plugin + "/" + path);
+ } else {
+ return null;
+ }
+ },
+ hasPermission: function (config, permission) {
+ if (config && config.permissions && config.permissions.length) {
+ return config.permissions.indexOf(permission) >= 0;
+ }
+
+ return false;
+ },
+ guid: function () {
+ return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
+ },
+ getURIPrefix: function () {
+ return "http://localhost:8472/";
+ },
+ translatePath: function (path) {
+ if (path.indexOf("local:///") === 0) {
+ var sourceDir = window.qnx.webplatform.getApplication().getEnv("HOME"); //leading slashes need to be removed
+ path = "file:///" + sourceDir.replace(/^\/*/, '') + "/../app/native/" + path.replace(/local:\/\/\//, '');
+ }
+ return path;
+ },
+ invokeInBrowser: function (url) {
+ var request = {
+ uri: url,
+ target: "sys.browser"
+ };
+ window.qnx.webplatform.getApplication().invocation.invoke(request);
+ },
+ isPersonal: function () {
+ return window.qnx.webplatform.getApplication().getEnv("PERIMETER") === "personal";
+ },
+ deepclone: function (obj) {
+ var newObj = obj instanceof Array ? [] : {},
+ key;
+
+ if (typeof obj === 'number' ||
+ typeof obj === 'string' ||
+ typeof obj === 'boolean' ||
+ obj === null ||
+ obj === undefined) {
+ return obj;
+ }
+
+ if (obj instanceof Date) {
+ return new Date(obj);
+ }
+
+ if (obj instanceof RegExp) {
+ return new RegExp(obj);
+ }
+
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ if (obj[key] && typeof obj[key] === "object") {
+ newObj[key] = self.deepclone(obj[key]);
+ } else {
+ newObj[key] = obj[key];
+ }
+ }
+ }
+
+ return newObj;
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/webkitEvent.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/webkitEvent.js b/lib/cordova-blackberry/framework/lib/webkitEvent.js
new file mode 100644
index 0000000..0f4bef7
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/webkitEvent.js
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var utils = require('./utils'),
+ exception = require('./exception'),
+ _listeners = {};
+
+function _on(eventType, listener, scope, once) {
+ if (!eventType) {
+ throw "eventType must be truthy";
+ }
+ _listeners[eventType] = _listeners[eventType] || [];
+ _listeners[eventType].push({
+ func: listener,
+ scope: scope,
+ once: !!once
+ });
+}
+
+function _trigger(listener, args, sync) {
+ try {
+ if (sync) {
+ listener.func.apply(listener.scope, args);
+ }
+ else {
+ setTimeout(function () {
+ listener.func.apply(listener.scope, args);
+ }, 1);
+ }
+ }
+ catch (e) {
+ exception.handle(e);
+ }
+}
+
+module.exports = {
+ on: function (eventType, listener, scope) {
+ _on(eventType, listener, scope, false);
+ },
+
+ once: function (eventType, listener, scope) {
+ _on(eventType, listener, scope, true);
+ },
+
+ trigger: function (eventType, args, sync) {
+ args = args || [];
+ sync = sync || false;
+
+ var listeners = _listeners[eventType];
+
+ if (listeners) {
+ listeners.forEach(function (listener) {
+ _trigger(listener, args, sync);
+ });
+
+ _listeners[eventType] = listeners.filter(function (listener) {
+ return !listener.once;
+ });
+ }
+ },
+
+ eventHasSubscriber: function (eventType) {
+ return !!_listeners[eventType];
+ },
+
+ getEventSubscribers: function (eventType) {
+ return utils.copy(_listeners[eventType]) || [];
+ },
+
+ clear: function (eventType) {
+ if (eventType) {
+ delete _listeners[eventType];
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/webkitHandlers/networkResourceRequested.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/webkitHandlers/networkResourceRequested.js b/lib/cordova-blackberry/framework/lib/webkitHandlers/networkResourceRequested.js
new file mode 100644
index 0000000..759c8bd
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/webkitHandlers/networkResourceRequested.js
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var Whitelist = require('../policy/whitelist').Whitelist,
+ ACCEPT_RESPONSE = {setAction: "ACCEPT"},
+ DENY_RESPONSE = {setAction: "DENY"},
+ SUBSTITUTE_RESPONSE = {setAction: "SUBSTITUTE"},
+ utils = require('../utils');
+
+function _formMessage(url, origin, sid, body, securityOrigin, webview) {
+ var tokens = url.split(utils.getURIPrefix())[1].split("/"),
+ //Handle the case where the method is multi-level
+ finalToken = (tokens[3] && tokens.length > 4) ? tokens.slice(3).join('/') : tokens[3];
+
+ return {
+ request : {
+ params : {
+ service : tokens[0],
+ action : tokens[1],
+ ext : tokens[2],
+ method : (finalToken && finalToken.indexOf("?") >= 0) ? finalToken.split("?")[0] : finalToken,
+ args : (finalToken && finalToken.indexOf("?") >= 0) ? finalToken.split("?")[1] : null
+ },
+ body : body,
+ origin : origin,
+ securityOrigin: securityOrigin
+
+ },
+ response : {
+ send : function (code, data) {
+ var responseText;
+ if (typeof(data) === 'string') {
+ responseText = data;
+ } else {
+ responseText = JSON.stringify(data);
+ }
+
+ webview.notifyOpen(sid, code, "OK");
+ webview.notifyHeaderReceived(sid, "Access-Control-Allow-Origin", "*");
+ webview.notifyHeaderReceived(sid, "Access-Control-Allow-Origin", securityOrigin);
+ webview.notifyHeaderReceived(sid, "Access-Control-Allow-Headers", "Content-Type");
+ webview.notifyDataReceived(sid, responseText, responseText.length);
+ webview.notifyDone(sid);
+ }
+ }
+ };
+}
+
+function networkResourceRequestedHandler(value) {
+ var config = require("./../config"),
+ obj = JSON.parse(value),
+ response,
+ url = obj.url,
+ body = obj.body,
+ whitelist = new Whitelist(),
+ server,
+ message,
+ sid = obj.streamId,
+ origin = obj.referrer,
+ securityOrigin = obj.securityOrigin,
+ isXHR = obj.targetType === "TargetIsXMLHTTPRequest",
+ //Assumes its a navigation request if the target is the main frame
+ isNav = obj.targetType === "TargetIsMainFrame",
+ hasAccess = whitelist.isAccessAllowed(url, isXHR),
+ deniedMsg;
+
+ //If the URL starts with the prefix then its a request from an API
+ //In this case we will hijack and give our own response
+ //Otherwise follow whitelisting rules
+ if (url.match("^" + utils.getURIPrefix())) {
+ server = require("../server");
+ message = _formMessage(url, origin, sid, body, securityOrigin, this.webview, config);
+ response = SUBSTITUTE_RESPONSE;
+ server.handle(message.request, message.response, this.webview);
+ } else {
+ //Whitelisting will not prevent navigation, ONLY we will
+ //Except when they've disabled web security
+ if (hasAccess || !config.enableWebSecurity) {
+ response = ACCEPT_RESPONSE;
+ } else {
+ response = DENY_RESPONSE;
+ url = utils.parseUri(url);
+ deniedMsg = "Access to \"" + url.source + "\" not allowed";
+
+ console.warn(deniedMsg);
+
+ //Denied navigation requests are sent to the inApp browser rather than an alert
+ if (isNav) {
+ if (config.enableChildWebView) {
+ this.webview.uiWebView.childwebviewcontrols.open(url.source);
+ } else {
+ utils.invokeInBrowser(url.source);
+ }
+ } else {
+ this.webview.executeJavaScript("alert('" + deniedMsg + "')");
+ }
+ }
+ }
+
+ if (response) {
+ return JSON.stringify(response);
+ }
+}
+
+function NetworkResourceRequestHandler(webview) {
+ this.webview = webview;
+ this.networkResourceRequestedHandler = networkResourceRequestedHandler.bind(this);
+}
+
+module.exports = {
+ createHandler: function (webview) {
+ return new NetworkResourceRequestHandler(webview);
+ }
+};
[26/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/functional/debugtoken-helper.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/functional/debugtoken-helper.js b/lib/cordova-blackberry/bin/test/cordova/functional/debugtoken-helper.js
new file mode 100644
index 0000000..cbf28d9
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/functional/debugtoken-helper.js
@@ -0,0 +1,377 @@
+/**
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+*/
+
+var childProcess = require('child_process'),
+ debugTokenHelper = require("../../templates/project/cordova/lib/debugtoken-helper"),
+ wrench = require('wrench'),
+ fs = require('fs'),
+ properties,
+ flag;
+
+function testCreateDebugtoken(target) {
+ debugTokenHelper.createToken(properties, target, function (code) {
+ if (code === 0) {
+ console.log("Debug token is created successfully!");
+ } else {
+ console.log("Debug token is not created successfully!");
+ }
+
+ flag = true;
+ });
+}
+
+function testDeployDebugtoken() {
+ debugTokenHelper.deployToken(properties, "", function () {
+ console.log("Deploy callback is invoked!");
+ flag = true;
+ });
+}
+
+function testDeployDebugtokenAll() {
+ debugTokenHelper.deployToken(properties, "all", function () {
+ console.log("Deploy callback is invoked!");
+ flag = true;
+ });
+}
+
+function testDeployDebugtokenSingle() {
+ debugTokenHelper.deployToken(properties, "d1", function () {
+ console.log("Deploy callback is invoked!");
+ flag = true;
+ });
+}
+
+describe("cordova/lib/debugtoken-helper tests", function () {
+ beforeEach(function () {
+ flag = false;
+ });
+
+ it("should create a debugtoken for target all", function () {
+ testCreateDebugtoken("all");
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ "keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ "pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ expect(fs.existsSync("debugtoken.bar"));
+ });
+ });
+
+ it("should create a debugtoken for single target", function () {
+ testCreateDebugtoken("d1");
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ "keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ "pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ expect(fs.existsSync("debugtoken.bar"));
+ });
+ });
+
+ it("should create a debugtoken for default target", function () {
+ testCreateDebugtoken("");
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ "keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ "pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ expect(fs.existsSync("debugtoken.bar"));
+ });
+ });
+
+ it("cannot create a debugtoken without keystorepass", function () {
+ testCreateDebugtoken("all");
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ //"keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ "pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ expect(!fs.existsSync("debugtoken.bar"));
+ });
+ });
+
+ it("cannot create a debugtoken without any device PINs", function () {
+ testCreateDebugtoken("all");
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ "keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ //"pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ expect(!fs.existsSync("debugtoken.bar"));
+ });
+ });
+
+ it("should deploy a debugtoken to default target", function () {
+ debugTokenHelper.createToken(properties, "", testDeployDebugtoken);
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ "keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ "pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+
+ window.alert("Make sure you connect the device " + "2A54F454" + " to " + "169.254.0.1");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ var confirm = window.confirm("Was the debug token deployed to device?");
+ expect(confirm).toEqual(true);
+ });
+ });
+
+ it("should deploy a debugtoken to all targets", function () {
+ debugTokenHelper.createToken(properties, "all", testDeployDebugtokenAll);
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ "keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ "pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+
+ window.alert("Make sure you connect the device " + "2A54F454" + " to " + "169.254.0.1");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ var confirm = window.confirm("Was the debug token deployed to device?");
+ expect(confirm).toEqual(true);
+ });
+ });
+
+ it("should deploy a debugtoken to a single target", function () {
+ debugTokenHelper.createToken(properties, "d1", testDeployDebugtokenSingle);
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ "keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ "pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+
+ window.alert("Make sure you connect the device " + "2A54F454" + " to " + "169.254.0.1");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ var confirm = window.confirm("Was the debug token deployed to device?");
+ expect(confirm).toEqual(true);
+ });
+ });
+
+ it("cannot deploy a debugtoken when the target is not connected", function () {
+ debugTokenHelper.createToken(properties, "all", testDeployDebugtoken);
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ "keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ "pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+
+ window.alert("Disconnect the target from 169.254.0.1");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ var confirm = window.confirm("Was the debug token deployed to device?");
+ expect(confirm).toEqual(false);
+ });
+ });
+
+ it("cannot deploy a debugtoken if no debugtoken", function () {
+ testDeployDebugtoken();
+
+ beforeEach(function () {
+ properties = {
+ "barName": "cordova-BB10-app",
+ "keystorepass": "qaqa1234",
+ "defaultTarget": "d1",
+ "targets": {
+ "d1": {
+ "ip": "169.254.0.1",
+ "type": "device",
+ "pin": "2A54F454",
+ "password" : "qaqa123"
+ }
+ }
+ };
+
+ fs.unlinkSync("debugtoken.bar");
+ });
+
+ waitsFor(function () {
+ return flag;
+ });
+
+ runs(function () {
+ var confirm = window.confirm("Was the debug token deployed to device?");
+ expect(confirm).toEqual(false);
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/integration/create.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/integration/create.js b/lib/cordova-blackberry/bin/test/cordova/integration/create.js
new file mode 100644
index 0000000..9879ef0
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/integration/create.js
@@ -0,0 +1,158 @@
+/**
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+*/
+
+var childProcess = require('child_process'),
+ tempFolder = '.tmp/',
+ appFolder = tempFolder + 'tempCordovaApp/',
+ projectFile = 'project.json',
+ wrench = require('wrench'),
+ fs = require('fs'),
+ flag = false,
+ _stdout = "",
+ _stderr = "";
+
+function executeScript(shellCommand, shouldError) {
+ childProcess.exec(shellCommand, function (error, stdout, stderr) {
+ if (error && !shouldError) {
+ console.log("Error executing command: " + error);
+ }
+ _stdout = stdout.toString().trim();
+ _stderr = stderr.toString().trim();
+ flag = true;
+ });
+}
+
+describe("create tests", function () {
+ it("creates project", function () {
+ var project,
+ appIdRegExp = /id="default\.app\.id"/g;
+ executeScript("bin/create " + appFolder);
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ project = JSON.parse(fs.readFileSync(appFolder + projectFile, "utf-8"));
+ expect(appIdRegExp.test(fs.readFileSync(appFolder + "www/config.xml", "utf-8"))).toEqual(true);
+ expect(fs.existsSync(appFolder)).toEqual(true);
+ expect(fs.existsSync(appFolder + "/plugins")).toEqual(true);
+ expect(fs.existsSync(appFolder + "/cordova")).toEqual(true);
+ expect(fs.existsSync(appFolder + "/cordova/node_modules")).toEqual(true);
+ expect(fs.existsSync(appFolder + "/cordova/lib")).toEqual(true);
+ expect(fs.existsSync(appFolder + "/cordova/third_party")).toEqual(true);
+ expect(fs.existsSync(appFolder + "/www")).toEqual(true);
+ expect(project.barName).toEqual("cordova-BB10-app");
+ expect(project.keystorepass).toEqual("password");
+ expect(project.defaultTarget).toEqual("");
+ expect(project.targets).toEqual({});
+ expect(fs.existsSync("./build")).toEqual(false);
+ expect(_stdout).toEqual("");
+ expect(_stderr).toEqual("");
+ });
+ this.after(function () {
+ wrench.rmdirSyncRecursive(tempFolder);
+ });
+ });
+
+ it("sets appId", function () {
+ var configEt,
+ appIdRegExp = /id="com\.example\.bb10app"/g;
+ executeScript("bin/create " + appFolder + " com.example.bb10app");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(appIdRegExp.test(fs.readFileSync(appFolder + "www/config.xml", "utf-8"))).toEqual(true);
+ expect(_stdout).toEqual("");
+ expect(_stderr).toEqual("");
+ });
+ this.after(function () {
+ wrench.rmdirSyncRecursive(tempFolder);
+ });
+ });
+
+ it("sets appId and barName", function () {
+ var project,
+ appIdRegExp = /id="com\.example\.bb10app"/g;
+ executeScript("bin/create " + appFolder + " com.example.bb10app bb10appV1");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ project = JSON.parse(fs.readFileSync(appFolder + projectFile, "utf-8"));
+ expect(appIdRegExp.test(fs.readFileSync(appFolder + "www/config.xml", "utf-8"))).toEqual(true);
+ expect(project.barName).toEqual("bb10appV1");
+ expect(_stdout).toEqual("");
+ expect(_stderr).toEqual("");
+ });
+ this.after(function () {
+ wrench.rmdirSyncRecursive(tempFolder);
+ });
+ });
+
+ it("No args", function () {
+ executeScript("bin/create", true);
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("Project creation failed!\nError: You must give a project PATH");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("Empty dir error", function () {
+ executeScript("bin/create ./", true);
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("Project creation failed!\nError: The project path must be an empty directory");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("Invalid appId error", function () {
+ executeScript("bin/create " + appFolder + " 23.21#$", true);
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("Project creation failed!\nError: App ID must be sequence of alpha-numeric (optionally seperated by '.') characters, no longer than 50 characters");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("Invalid barName error", function () {
+ executeScript("bin/create " + appFolder + " com.example.app %bad@bar^name", true);
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("Project creation failed!\nError: BAR filename can only contain alpha-numeric, '.', '-' and '_' characters");
+ expect(_stderr).toEqual("");
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/integration/target.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/integration/target.js b/lib/cordova-blackberry/bin/test/cordova/integration/target.js
new file mode 100644
index 0000000..e948a87
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/integration/target.js
@@ -0,0 +1,237 @@
+/**
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+*/
+
+var childProcess = require('child_process'),
+ tempFolder = '.tmp/',
+ appFolder = tempFolder + 'tempCordovaApp/',
+ projectFile = 'project.json',
+ wrench = require('wrench'),
+ fs = require('fs'),
+ flag = false,
+ _stdout = "",
+ _stderr = "";
+
+function executeScript(shellCommand) {
+ childProcess.exec(shellCommand, function (error, stdout, stderr) {
+ if (error) {
+ console.log("Error executing command: " + error);
+ }
+ _stdout = stdout.toString().trim();
+ _stderr = stderr.toString().trim();
+ flag = true;
+ });
+}
+
+describe("cordova/target tests", function () {
+ beforeEach(function () {
+ executeScript("bin/create " + appFolder);
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ });
+ });
+
+ afterEach(function () {
+ wrench.rmdirSyncRecursive(tempFolder);
+ });
+
+ it("should add a target", function () {
+ var project,
+ target;
+ executeScript(appFolder + "cordova/target add z10 169.254.0.1 device -p pass --pin DEADBEEF");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ project = JSON.parse(fs.readFileSync(appFolder + projectFile, 'utf-8'));
+ expect(project.defaultTarget).toEqual("z10");
+ expect(Object.keys(project.targets).length).toEqual(1);
+ target = project.targets.z10;
+ expect(target.ip).toEqual("169.254.0.1");
+ expect(target.type).toEqual("device");
+ expect(target.password).toEqual("pass");
+ expect(target.pin).toEqual("DEADBEEF");
+ expect(_stdout).toEqual("");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("should remove a target", function () {
+ var project;
+ executeScript(appFolder + "cordova/target add z10 169.254.0.1 device -p pass --pin DEADBEEF");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ executeScript(appFolder + "cordova/target remove z10");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ project = JSON.parse(fs.readFileSync(appFolder + projectFile, 'utf-8'));
+ expect(project.defaultTarget).toEqual("");
+ expect(Object.keys(project.targets).length).toEqual(0);
+ expect(_stdout).toEqual("Deleting default target, please set a new default target");
+ expect(_stderr).toEqual("");
+ });
+ });
+ });
+
+ it("should set default target", function () {
+ var project;
+ executeScript(appFolder + "cordova/target add z10 169.254.0.1 device -p pass --pin DEADBEEF");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ executeScript(appFolder + "cordova/target add q10 169.254.0.2 device -p p455w02D --pin FACEFACE");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ executeScript(appFolder + "cordova/target default q10");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ project = JSON.parse(fs.readFileSync(appFolder + projectFile, 'utf-8'));
+ expect(project.defaultTarget).toEqual("q10");
+ });
+ });
+ });
+ });
+
+ it("should list targets", function () {
+ executeScript(appFolder + "cordova/target add z10 169.254.0.1 device -p pass --pin DEADBEEF");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ executeScript(appFolder + "cordova/target add q10 169.254.0.2 device -p p455w02D --pin FACEFACE");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ executeScript(appFolder + "cordova/target");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("* z10\n q10");
+ expect(_stderr).toEqual("");
+ });
+ });
+ });
+ });
+
+ it("should require name for add/remove", function () {
+ executeScript(appFolder + "cordova/target add");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("Target details not specified");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("should require ip for add", function () {
+ executeScript(appFolder + "cordova/target add z10");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("IP is required");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("should require type for add ", function () {
+ executeScript(appFolder + "cordova/target add z10 169.254.0.1");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("target type is required");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("should warn unregonized command", function () {
+ executeScript(appFolder + "cordova/target bleh");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("Unrecognized command");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("should warn invalid ip", function () {
+ executeScript(appFolder + "cordova/target add z10 256.254.0.1");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("Invalid IP: 256.254.0.1");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("should warn invalid type", function () {
+ executeScript(appFolder + "cordova/target add z10 169.254.0.1 bleh");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("Invalid target type: bleh");
+ expect(_stderr).toEqual("");
+ });
+ });
+
+ it("should warn invalid pin", function () {
+ executeScript(appFolder + "cordova/target add z10 169.254.0.1 device --pin NOTAPIN!");
+ waitsFor(function () {
+ return flag;
+ });
+ runs(function () {
+ flag = false;
+ expect(_stdout).toEqual("Invalid PIN: NOTAPIN!");
+ expect(_stderr).toEqual("");
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/config-bare-minimum.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/config-bare-minimum.xml b/lib/cordova-blackberry/bin/test/cordova/unit/config-bare-minimum.xml
new file mode 100644
index 0000000..90572f4
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/config-bare-minimum.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<widget xmlns=" http://www.w3.org/ns/widgets"
+ xmlns:rim="http://www.blackberry.com/ns/widgets"
+ version="1.0.0"
+ id="myID">
+ <name>Demo</name>
+ <content src="local:///startPage.html"/>
+ <author>Research In Motion Ltd.</author>
+ <license href="http://www.apache.org/licenses/LICENSE-2.0">
+ Licensed under the Apache License, Version 2.0 (the "License");
+ #you may not use this file except in compliance with the License.
+ #You may obtain a copy of the License at
+ #
+ #http://www.apache.org/licenses/LICENSE-2.0
+ #
+ #Unless required by applicable law or agreed to in writing, software
+ #distributed under the License is distributed on an "AS IS" BASIS,
+ #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ #See the License for the specific language governing permissions and limitations under the License.
+ </license>
+</widget>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/config-license.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/config-license.xml b/lib/cordova-blackberry/bin/test/cordova/unit/config-license.xml
new file mode 100644
index 0000000..ac4ffe9
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/config-license.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<widget xmlns=" http://www.w3.org/ns/widgets"
+ xmlns:rim="http://www.blackberry.com/ns/widgets"
+ version="1.0.0"
+ id="myID">
+ <name>Demo</name>
+ <content src="local:///startPage.html"/>
+ <author>Research In Motion Ltd.</author>
+ <license href="http://www.apache.org/licenses/LICENSE-2.0"></license>
+</widget>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/config.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/config.xml b/lib/cordova-blackberry/bin/test/cordova/unit/config.xml
new file mode 100644
index 0000000..8650a90
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/config.xml
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="utf-8"?>
+<widget xmlns=" http://www.w3.org/ns/widgets"
+ xmlns:rim="http://www.blackberry.com/ns/widgets"
+ version="1.0.0"
+ id="My WidgetId"
+ rim:header="RIM-Widget:rim/widget"
+ rim:userAgent="A Test-User-Agent/(Blackberry-Agent)">
+ <name>Demo</name>
+ <content src="local:///startPage.html"/>
+ <author rim:copyright="No Copyright"
+ href="http://www.rim.com/"
+ email = "author@rim.com">Research In Motion Ltd.</author>
+ <description>This app does everything.</description>
+ <license href="http://www.apache.org/licenses/LICENSE-2.0">My License</license>
+ <icon src="test.png" />
+ <rim:permissions>
+ <rim:permit>access_shared</rim:permit>
+ <rim:permit>read_geolocation</rim:permit>
+ <rim:permit>use_camera</rim:permit>
+ </rim:permissions>
+ <feature id="blackberry.app.orientation">
+ <param name="mode" value="portrait" />
+ <param name="other" value="portrait" />
+ </feature>
+ <feature id="blackberry.app" required="true" version="1.0.0.0">
+ <param name="childBrowser" value="disable" />
+ <param name="websecurity" value="disable" />
+ <param name="popupBlocker" value="enable" />
+ </feature>
+ <feature id="blackberry.system" required="true" version="1.0.0.3"/>
+ <access uri="http://www.somedomain1.com" subdomains="true">
+ <feature id="blackberry.app" required="true" version="1.0.0.0"/>
+ <feature id="blackberry.app.event" required="false" version="2.0.0.0"/>
+ </access>
+ <rim:invoke-target id="com.domain.subdomain.appname.app1">
+ <type>APPLICATION</type>
+ <require-source-permissions>invoke_accross_perimeters,access_shared</require-source-permissions>
+ <filter>
+ <action>bb.action.OPEN</action>
+ <action>bb.action.SET</action>
+ <action>bb.action.VIEW</action>
+ <mime-type>image/*</mime-type>
+ <mime-type>text/*</mime-type>
+ <property var="uris" value="ftp://" />
+ <property var="uris" value="http://" />
+ <property var="uris" value="https://" />
+ <property var="exts" value="jpg" />
+ <property var="exts" value="png" />
+ <property var="exts" value="txt" />
+ <property var="exts" value="doc" />
+ </filter>
+ </rim:invoke-target>
+</widget>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/data/ascii_text.txt
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/data/ascii_text.txt b/lib/cordova-blackberry/bin/test/cordova/unit/data/ascii_text.txt
new file mode 100644
index 0000000..5e1c309
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/data/ascii_text.txt
@@ -0,0 +1 @@
+Hello World
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/data/ucs2be_text.txt
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/data/ucs2be_text.txt b/lib/cordova-blackberry/bin/test/cordova/unit/data/ucs2be_text.txt
new file mode 100644
index 0000000..f999e5f
Binary files /dev/null and b/lib/cordova-blackberry/bin/test/cordova/unit/data/ucs2be_text.txt differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/data/ucs2le_text.txt
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/data/ucs2le_text.txt b/lib/cordova-blackberry/bin/test/cordova/unit/data/ucs2le_text.txt
new file mode 100644
index 0000000..088fa80
Binary files /dev/null and b/lib/cordova-blackberry/bin/test/cordova/unit/data/ucs2le_text.txt differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/data/utf8_text.txt
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/data/utf8_text.txt b/lib/cordova-blackberry/bin/test/cordova/unit/data/utf8_text.txt
new file mode 100644
index 0000000..05eac02
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/data/utf8_text.txt
@@ -0,0 +1 @@
+Hello World
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/params-bad.json
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/params-bad.json b/lib/cordova-blackberry/bin/test/cordova/unit/params-bad.json
new file mode 100644
index 0000000..16c75eb
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/params-bad.json
@@ -0,0 +1,10 @@
+{
+EVIL!
+ "blackberry-signer": {
+ "-proxyhost": "abc.com",
+ "-proxyport": "80"
+ },
+ "blackberry-nativepackager": {
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/params.json
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/params.json b/lib/cordova-blackberry/bin/test/cordova/unit/params.json
new file mode 100644
index 0000000..6a3506f
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/params.json
@@ -0,0 +1,9 @@
+{
+ "blackberry-signer": {
+ "-proxyhost": "abc.com",
+ "-proxyport": "80"
+ },
+ "blackberry-nativepackager": {
+
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/bar-builder.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/bar-builder.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/bar-builder.js
new file mode 100644
index 0000000..02440cc
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/bar-builder.js
@@ -0,0 +1,34 @@
+var srcPath = __dirname + "/../../../../../templates/project/cordova/lib/",
+ path = require("path"),
+ wrench = require("wrench"),
+ barBuilder = require(srcPath + "bar-builder"),
+ fileMgr = require(srcPath + "file-manager"),
+ nativePkgr = require(srcPath + "native-packager"),
+ logger = require(srcPath + "logger"),
+ testData = require("./test-data"),
+ extManager = null;
+
+describe("BAR builder", function () {
+ it("build() create BAR for specified session", function () {
+ var callback = jasmine.createSpy(),
+ session = testData.session,
+ config = testData.config,
+ target = session.targets[0];
+
+ wrench.mkdirSyncRecursive(path.join(session.sourcePaths.LIB, "config"));
+
+ spyOn(wrench, "mkdirSyncRecursive");
+ spyOn(fileMgr, "copyWebworks");
+ spyOn(fileMgr, "generateFrameworkModulesJS");
+ spyOn(nativePkgr, "exec").andCallFake(function (session, target, config, callback) {
+ callback(0);
+ });
+
+ barBuilder.build(session, testData.config, callback);
+
+ expect(wrench.mkdirSyncRecursive).toHaveBeenCalledWith(session.outputDir + "/" + target);
+ expect(fileMgr.generateFrameworkModulesJS).toHaveBeenCalledWith(session);
+ expect(nativePkgr.exec).toHaveBeenCalledWith(session, target, config, jasmine.any(Function));
+ expect(callback).toHaveBeenCalledWith(0);
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/bbwpignore.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/bbwpignore.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/bbwpignore.js
new file mode 100644
index 0000000..7c68ee9
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/bbwpignore.js
@@ -0,0 +1,135 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var srcPath = __dirname + "/../../../../../templates/project/cordova/lib/",
+ BBWPignore = require(srcPath + "bbwpignore"),
+ fs = require('fs');
+
+describe("bbwpignore can match", function () {
+ it("a basic file set", function () {
+ var bbwpignore;
+ spyOn(fs, "readFileSync").andReturn("abc.js\n" +
+ "x/y/def.js");
+ bbwpignore = new BBWPignore("FileNameIgnoreForTests",
+ ["d/e/abc.js", "abc.js", "ted.js", ".DS_Store",
+ "x/y/def.js", "x/def.js", "a/b/x/y/def.js"]);
+ expect(bbwpignore.matchedFiles.length).toBe(4);
+ expect(bbwpignore.matchedFiles.indexOf("d/e/abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("x/y/def.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("a/b/x/y/def.js")).not.toBe(-1);
+ });
+
+ it("a basic file set with directories", function () {
+ var bbwpignore;
+ spyOn(fs, "readFileSync").andReturn("abc.js\n" +
+ "x/y/");
+ bbwpignore = new BBWPignore("FileNameIgnoreForTests",
+ ["d/e/abc.js", "abc.js", "ted.js", ".DS_Store",
+ "x/y/def.js", "x/def.js", "a/b/x/y/def.js"]);
+
+ expect(bbwpignore.matchedFiles.length).toBe(4);
+ expect(bbwpignore.matchedFiles.indexOf("d/e/abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("x/y/def.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("a/b/x/y/def.js")).not.toBe(-1);
+ });
+
+ it("a basic file set with directories that being with slash", function () {
+ var bbwpignore;
+ spyOn(fs, "readFileSync").andReturn("abc.js\n" +
+ "/x/y/");
+ bbwpignore = new BBWPignore("FileNameIgnoreForTests",
+ ["d/e/abc.js", "abc.js", "ted.js", ".DS_Store",
+ "x/y/def.js", "x/def.js", "a/b/x/y/def.js"]);
+ expect(bbwpignore.matchedFiles.length).toBe(4);
+ expect(bbwpignore.matchedFiles.indexOf("d/e/abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("/x/y")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("x/y/def.js")).not.toBe(-1);
+
+ });
+
+ it("a basic file set that begin with a slash on the directory", function () {
+ var bbwpignore;
+ spyOn(fs, "readFileSync").andReturn("abc.js\n" +
+ "/x/y/def.js");
+ bbwpignore = new BBWPignore("FileNameIgnoreForTests",
+ ["d/e/abc.js", "abc.js", "ted.js", ".DS_Store",
+ "x/y/def.js", "x/def.js", "a/b/x/y/def.js"]);
+
+ expect(bbwpignore.matchedFiles.length).toBe(3);
+ expect(bbwpignore.matchedFiles.indexOf("d/e/abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("x/y/def.js")).not.toBe(-1);
+
+ });
+
+ it("a basic file set that begin with a slash", function () {
+ var bbwpignore;
+ spyOn(fs, "readFileSync").andReturn("abc.js\n" +
+ "/def.js");
+ bbwpignore = new BBWPignore("FileNameIgnoreForTests",
+ ["d/e/abc.js", "abc.js", "ted.js", ".DS_Store",
+ "x/y/def.js", "x/def.js", "a/b/x/y/def.js"]);
+
+ expect(bbwpignore.matchedFiles.length).toBe(2);
+ expect(bbwpignore.matchedFiles.indexOf("d/e/abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("abc.js")).not.toBe(-1);
+
+ });
+
+ it("a basic file set that begin with a slash and has a wildcard", function () {
+ var bbwpignore;
+ spyOn(fs, "readFileSync").andReturn("abcd.js\n" +
+ "/*.js");
+ bbwpignore = new BBWPignore("FileNameIgnoreForTests",
+ ["d/e/abc.js", "abc.js", "ted.js", ".DS_Store",
+ "x/y/def.js", "x/def.js", "a/b/x/y/def.js"]);
+
+ expect(bbwpignore.matchedFiles.length).toBe(2);
+ expect(bbwpignore.matchedFiles.indexOf("abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("ted.js")).not.toBe(-1);
+
+ });
+
+ it("a basic file set that begin with a slash and has a wildcard", function () {
+ var bbwpignore;
+ spyOn(fs, "readFileSync").andReturn("abcd.js\n" +
+ "a*.js");
+ bbwpignore = new BBWPignore("FileNameIgnoreForTests",
+ ["d/e/abc.js", "abc.js", "ted.js", ".DS_Store",
+ "x/y/def.js", "x/def.js", "a/b/x/y/def.js"]);
+
+ expect(bbwpignore.matchedFiles.length).toBe(2);
+ expect(bbwpignore.matchedFiles.indexOf("d/e/abc.js")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("abc.js")).not.toBe(-1);
+
+ });
+
+ it("a basic directory set that begin with a slash", function () {
+ var bbwpignore;
+ spyOn(fs, "readFileSync").andReturn("/simulator/\n" +
+ "banana.js");
+ bbwpignore = new BBWPignore("FileNameIgnoreForTests",
+ ["simulator/a.js"]);
+
+ expect(bbwpignore.matchedFiles.length).toBe(2);
+ expect(bbwpignore.matchedFiles.indexOf("/simulator")).not.toBe(-1);
+ expect(bbwpignore.matchedFiles.indexOf("simulator/a.js")).not.toBe(-1);
+
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/cmdline.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/cmdline.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/cmdline.js
new file mode 100644
index 0000000..03eda58
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/cmdline.js
@@ -0,0 +1,77 @@
+var srcPath = __dirname + "/../../../../../templates/project/cordova/lib/",
+ localize = require(srcPath + "localize"),
+ cmdline = require(srcPath + "cmdline"),
+ cmd;
+
+describe("Command line", function () {
+ beforeEach(function () {
+ cmd = cmdline
+ .parse(process.argv)
+ .commander;
+ });
+
+ it("accepts -o with argument", function () {
+ cmd.parseOptions(["-o", "outdir"]);
+ expect(cmd.output).toEqual("outdir");
+ });
+
+ it("arg following -o is required", function () {
+ spyOn(process, "exit");
+ spyOn(console, "error");
+ cmd.parseOptions(["-o"]);
+ expect(console.error).toHaveBeenCalled();
+ expect(process.exit).toHaveBeenCalled();
+ });
+
+ it("accepts -s without argument", function () {
+ cmd.parseOptions(["-s"]);
+ expect(cmd.source).toBeTruthy();
+ });
+
+ it("accepts -s with argument", function () {
+ cmd.parseOptions(["-s", "mySourceDir"]);
+ expect(cmd.source).toEqual("mySourceDir");
+ });
+
+ it("accepts -d", function () {
+ cmd.parseOptions(["-d"]);
+ expect(cmd.debug).toBeTruthy();
+ });
+
+ it("accepts --loglevel with argument", function () {
+ cmd.parseOptions(["--loglevel", "warn"]);
+ expect(cmd.loglevel).toBe("warn");
+ });
+
+ it("accepts -ll", function () {
+ cmd.parseOptions(["-ll", "error"]);
+ expect(cmd.loglevel).toBe("error");
+ });
+
+ it("accepts -g with argument", function () {
+ cmd.parseOptions(["-g", "myPassword"]);
+ expect(cmd.password).toEqual("myPassword");
+ });
+
+ it("accepts --buildId with argument", function () {
+ cmd.parseOptions(["--buildId", "100"]);
+ expect(cmd.buildId).toEqual("100");
+ });
+
+ it("accepts -buildId with argument", function () {
+ cmd.parseOptions(["-buildId", "100"]);
+ expect(cmd.buildId).toEqual("100");
+ });
+
+ it("accepts --appdesc with argument", function () {
+ cmd.parseOptions(["--appdesc", "bardescriptor"]);
+ expect(cmd.appdesc).toEqual("bardescriptor");
+ });
+
+ it("throws an error for invalid multi-word arguments", function () {
+ expect(function () {
+ require(srcPath + "cmdline").parse(["--src"]);
+ }).toThrow(localize.translate("EXCEPTION_CMDLINE_ARG_INVALID", "--src"));
+ });
+
+});
[05/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVCamera.h
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVCamera.h b/lib/cordova-ios/CordovaLib/Classes/CDVCamera.h
index 65eac77..2932e3b 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVCamera.h
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVCamera.h
@@ -18,6 +18,8 @@
*/
#import <Foundation/Foundation.h>
+#import <CoreLocation/CoreLocation.h>
+#import <CoreLocation/CLLocationManager.h>
#import "CDVPlugin.h"
enum CDVDestinationType {
@@ -62,10 +64,14 @@ typedef NSUInteger CDVMediaType;
@interface CDVCamera : CDVPlugin <UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
- UIPopoverControllerDelegate>
+ UIPopoverControllerDelegate,
+ CLLocationManagerDelegate>
{}
@property (strong) CDVCameraPicker* pickerController;
+@property (strong) NSMutableDictionary *metadata;
+@property (strong, nonatomic) CLLocationManager *locationManager;
+@property (strong) NSData* data;
/*
* getPicture
@@ -85,8 +91,12 @@ typedef NSUInteger CDVMediaType;
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info;
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary*)editingInfo;
- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker;
+- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (UIImage*)imageByScalingAndCroppingForSize:(UIImage*)anImage toSize:(CGSize)targetSize;
- (UIImage*)imageByScalingNotCroppingForSize:(UIImage*)anImage toSize:(CGSize)frameSize;
- (UIImage*)imageCorrectedForCaptureOrientation:(UIImage*)anImage;
+- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation;
+- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
+
@end
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVCamera.m
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVCamera.m b/lib/cordova-ios/CordovaLib/Classes/CDVCamera.m
index 823fde9..1ee641c 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVCamera.m
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVCamera.m
@@ -22,6 +22,11 @@
#import "NSArray+Comparisons.h"
#import "NSData+Base64.h"
#import "NSDictionary+Extensions.h"
+#import <ImageIO/CGImageProperties.h>
+#import <AssetsLibrary/ALAssetRepresentation.h>
+#import <ImageIO/CGImageSource.h>
+#import <ImageIO/CGImageProperties.h>
+#import <ImageIO/CGImageDestination.h>
#import <MobileCoreServices/UTCoreTypes.h>
#define CDV_PHOTO_PREFIX @"cdv_photo_"
@@ -41,7 +46,7 @@ static NSSet* org_apache_cordova_validArrowDirections;
org_apache_cordova_validArrowDirections = [[NSSet alloc] initWithObjects:[NSNumber numberWithInt:UIPopoverArrowDirectionUp], [NSNumber numberWithInt:UIPopoverArrowDirectionDown], [NSNumber numberWithInt:UIPopoverArrowDirectionLeft], [NSNumber numberWithInt:UIPopoverArrowDirectionRight], [NSNumber numberWithInt:UIPopoverArrowDirectionAny], nil];
}
-@synthesize hasPendingOperation, pickerController;
+@synthesize hasPendingOperation, pickerController, locationManager;
- (BOOL)popoverSupported
{
@@ -187,6 +192,17 @@ static NSSet* org_apache_cordova_validArrowDirections;
animated:YES];
}
+- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
+{
+ if([navigationController isKindOfClass:[UIImagePickerController class]]){
+ UIImagePickerController * cameraPicker = (UIImagePickerController*)navigationController;
+
+ if(![cameraPicker.mediaTypes containsObject:(NSString*) kUTTypeImage]){
+ [viewController.navigationItem setTitle:NSLocalizedString(@"Videos title", nil)];
+ }
+ }
+}
+
- (void)cleanup:(CDVInvokedUrlCommand*)command
{
// empty the tmp directory
@@ -271,10 +287,6 @@ static NSSet* org_apache_cordova_validArrowDirections;
image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
- if (cameraPicker.saveToPhotoAlbum) {
- UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
- }
-
if (cameraPicker.correctOrientation) {
image = [self imageCorrectedForCaptureOrientation:image];
}
@@ -295,12 +307,22 @@ static NSSet* org_apache_cordova_validArrowDirections;
if (cameraPicker.encodingType == EncodingTypePNG) {
data = UIImagePNGRepresentation(scaledImage == nil ? image : scaledImage);
} else {
- data = UIImageJPEGRepresentation(scaledImage == nil ? image : scaledImage, cameraPicker.quality / 100.0f);
-
- /* splice loc */
- CDVJpegHeaderWriter* exifWriter = [[CDVJpegHeaderWriter alloc] init];
- NSString* headerstring = [exifWriter createExifAPP1:[info objectForKey:@"UIImagePickerControllerMediaMetadata"]];
- data = [exifWriter spliceExifBlockIntoJpeg:data withExifBlock:headerstring];
+ self.data = UIImageJPEGRepresentation(scaledImage == nil ? image : scaledImage, cameraPicker.quality / 100.0f);
+
+ NSDictionary *controllerMetadata = [info objectForKey:@"UIImagePickerControllerMediaMetadata"];
+ if (controllerMetadata) {
+ self.metadata = [[NSMutableDictionary alloc] init];
+
+ NSMutableDictionary *EXIFDictionary = [[controllerMetadata objectForKey:(NSString *)kCGImagePropertyExifDictionary]mutableCopy];
+ if (EXIFDictionary) [self.metadata setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
+
+ [[self locationManager] startUpdatingLocation];
+ return;
+ }
+ }
+
+ if (cameraPicker.saveToPhotoAlbum) {
+ UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:data], nil, nil, nil);
}
if (cameraPicker.returnType == DestinationTypeFileUri) {
@@ -551,6 +573,143 @@ static NSSet* org_apache_cordova_validArrowDirections;
self.hasPendingOperation = NO;
}
+
+- (CLLocationManager *)locationManager {
+
+ if (locationManager != nil) {
+ return locationManager;
+ }
+
+ locationManager = [[CLLocationManager alloc] init];
+ [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
+ [locationManager setDelegate:self];
+
+ return locationManager;
+}
+
+- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation
+{
+ if (locationManager != nil) {
+ [self.locationManager stopUpdatingLocation];
+ self.locationManager = nil;
+
+ NSMutableDictionary *GPSDictionary = [[NSMutableDictionary dictionary] init];
+
+ CLLocationDegrees latitude = newLocation.coordinate.latitude;
+ CLLocationDegrees longitude = newLocation.coordinate.longitude;
+
+ // latitude
+ if (latitude < 0.0) {
+ latitude = latitude * -1.0f;
+ [GPSDictionary setObject:@"S" forKey:(NSString*)kCGImagePropertyGPSLatitudeRef];
+ } else {
+ [GPSDictionary setObject:@"N" forKey:(NSString*)kCGImagePropertyGPSLatitudeRef];
+ }
+ [GPSDictionary setObject:[NSNumber numberWithFloat:latitude] forKey:(NSString*)kCGImagePropertyGPSLatitude];
+
+ // longitude
+ if (longitude < 0.0) {
+ longitude = longitude * -1.0f;
+ [GPSDictionary setObject:@"W" forKey:(NSString*)kCGImagePropertyGPSLongitudeRef];
+ }
+ else {
+ [GPSDictionary setObject:@"E" forKey:(NSString*)kCGImagePropertyGPSLongitudeRef];
+ }
+ [GPSDictionary setObject:[NSNumber numberWithFloat:longitude] forKey:(NSString*)kCGImagePropertyGPSLongitude];
+
+ // altitude
+ CGFloat altitude = newLocation.altitude;
+ if (!isnan(altitude)){
+ if (altitude < 0) {
+ altitude = -altitude;
+ [GPSDictionary setObject:@"1" forKey:(NSString *)kCGImagePropertyGPSAltitudeRef];
+ } else {
+ [GPSDictionary setObject:@"0" forKey:(NSString *)kCGImagePropertyGPSAltitudeRef];
+ }
+ [GPSDictionary setObject:[NSNumber numberWithFloat:altitude] forKey:(NSString *)kCGImagePropertyGPSAltitude];
+ }
+
+ // Time and date
+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
+ [formatter setDateFormat:@"HH:mm:ss.SSSSSS"];
+ [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
+ [GPSDictionary setObject:[formatter stringFromDate:newLocation.timestamp] forKey:(NSString *)kCGImagePropertyGPSTimeStamp];
+ [formatter setDateFormat:@"yyyy:MM:dd"];
+ [GPSDictionary setObject:[formatter stringFromDate:newLocation.timestamp] forKey:(NSString *)kCGImagePropertyGPSDateStamp];
+
+ [self.metadata setObject:GPSDictionary forKey:(NSString *)kCGImagePropertyGPSDictionary];
+ [self imagePickerControllerReturnImageResult];
+ }
+}
+
+- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
+ if (locationManager != nil) {
+ [self.locationManager stopUpdatingLocation];
+ self.locationManager = nil;
+
+ [self imagePickerControllerReturnImageResult];
+ }
+}
+
+- (void)imagePickerControllerReturnImageResult
+{
+ CDVPluginResult* result = nil;
+
+ if (self.metadata) {
+ CGImageSourceRef sourceImage = CGImageSourceCreateWithData((__bridge_retained CFDataRef)self.data, NULL);
+ CFStringRef sourceType = CGImageSourceGetType(sourceImage);
+
+ CGImageDestinationRef destinationImage = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)self.data, sourceType, 1, NULL);
+ CGImageDestinationAddImageFromSource(destinationImage, sourceImage, 0, (__bridge CFDictionaryRef)self.metadata);
+ CGImageDestinationFinalize(destinationImage);
+
+ CFRelease(sourceImage);
+ CFRelease(destinationImage);
+ }
+
+ if (self.pickerController.saveToPhotoAlbum) {
+ UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:[self data]], nil, nil, nil);
+ }
+
+ if (self.pickerController.returnType == DestinationTypeFileUri) {
+ // write to temp directory and return URI
+ // get the temp directory path
+ NSString* docsPath = [NSTemporaryDirectory()stringByStandardizingPath];
+ NSError* err = nil;
+ NSFileManager* fileMgr = [[NSFileManager alloc] init]; // recommended by apple (vs [NSFileManager defaultManager]) to be threadsafe
+ // generate unique file name
+ NSString* filePath;
+
+ int i = 1;
+ do {
+ filePath = [NSString stringWithFormat:@"%@/%@%03d.%@", docsPath, CDV_PHOTO_PREFIX, i++, self.pickerController.encodingType == EncodingTypePNG ? @"png":@"jpg"];
+ } while ([fileMgr fileExistsAtPath:filePath]);
+
+ // save file
+ if (![self.data writeToFile:filePath options:NSAtomicWrite error:&err]) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[err localizedDescription]];
+ }
+ else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[[NSURL fileURLWithPath:filePath] absoluteString]];
+ }
+ }
+ else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[self.data base64EncodedString]];
+ }
+ if (result) {
+ [self.commandDelegate sendPluginResult:result callbackId:self.pickerController.callbackId];
+ }
+
+ if (result) {
+ [self.commandDelegate sendPluginResult:result callbackId:self.pickerController.callbackId];
+ }
+
+ self.hasPendingOperation = NO;
+ self.pickerController = nil;
+ self.data = nil;
+ self.metadata = nil;
+}
+
@end
@implementation CDVCameraPicker
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVCapture.m
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVCapture.m b/lib/cordova-ios/CordovaLib/Classes/CDVCapture.m
index d89e3d3..6b7ed44 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVCapture.m
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVCapture.m
@@ -108,7 +108,6 @@
if ([options isKindOfClass:[NSNull class]]) {
options = [NSDictionary dictionary];
}
- NSString* mode = [options objectForKey:@"mode"];
// options could contain limit and mode neither of which are supported at this time
// taking more than one picture (limit) is only supported if provide own controls via cameraOverlayView property
@@ -139,7 +138,6 @@
}*/
// CDVImagePicker specific property
pickerController.callbackId = callbackId;
- pickerController.mimeType = mode;
if ([self.viewController respondsToSelector:@selector(presentViewController:::)]) {
[self.viewController presentViewController:pickerController animated:YES completion:nil];
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.h
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.h b/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.h
index 7392580..2e06c88 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.h
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.h
@@ -17,7 +17,10 @@
under the License.
*/
-@interface CDVConfigParser : NSObject <NSXMLParserDelegate>{}
+@interface CDVConfigParser : NSObject <NSXMLParserDelegate>
+{
+ NSString* featureName;
+}
@property (nonatomic, readonly, strong) NSMutableDictionary* pluginsDict;
@property (nonatomic, readonly, strong) NSMutableDictionary* settings;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.m
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.m b/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.m
index ffc8ede..23ae401 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.m
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVConfigParser.m
@@ -41,6 +41,7 @@
self.settings = [[NSMutableDictionary alloc] initWithCapacity:30];
self.whitelistHosts = [[NSMutableArray alloc] initWithCapacity:30];
self.startupPluginNames = [[NSMutableArray alloc] initWithCapacity:8];
+ featureName = nil;
}
return self;
}
@@ -55,6 +56,24 @@
if ([@"true" isEqualToString : attributeDict[@"onload"]]) {
[self.startupPluginNames addObject:name];
}
+ NSLog(@"\nUse of the <plugin> tag has been deprecated. Use a <feature> tag instead. Change:\n"
+ @" <plugin name=\"%@\" value=\"%@\" />\n"
+ @"To:\n"
+ @" <feature name=\"%@\">\n"
+ @" <param name=\"ios-package\" value=\"%@\">\n"
+ @" </feature>\n"
+ , attributeDict[@"name"], attributeDict[@"value"], attributeDict[@"name"], attributeDict[@"value"]);
+ } else if ([elementName isEqualToString:@"feature"]) { // store feature name to use with correct parameter set
+ featureName = [attributeDict[@"name"] lowercaseString];
+ } else if ((featureName != nil) && [elementName isEqualToString:@"param"]) {
+ NSString* paramName = [attributeDict[@"name"] lowercaseString];
+ id value = attributeDict[@"value"];
+ if ([paramName isEqualToString:@"ios-package"]) {
+ pluginsDict[featureName] = value;
+ }
+ if ([paramName isEqualToString:@"onload"] && [@"true" isEqualToString : value]) {
+ [self.startupPluginNames addObject:featureName];
+ }
} else if ([elementName isEqualToString:@"access"]) {
[whitelistHosts addObject:attributeDict[@"origin"]];
} else if ([elementName isEqualToString:@"content"]) {
@@ -62,6 +81,13 @@
}
}
+- (void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName
+{
+ if ([elementName isEqualToString:@"feature"]) { // no longer handling a feature so release
+ featureName = nil;
+ }
+}
+
- (void)parser:(NSXMLParser*)parser parseErrorOccurred:(NSError*)parseError
{
NSAssert(NO, @"config.xml parse error line %d col %d", [parser lineNumber], [parser columnNumber]);
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.h
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.h b/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.h
index 765326a..f87baff 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.h
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.h
@@ -60,6 +60,8 @@
- (void)close;
- (void)navigateTo:(NSURL*)url;
- (void)showLocationBar:(BOOL)show;
+- (void)showToolBar:(BOOL)show;
+- (void)setCloseButtonTitle:(NSString*)title;
- (id)initWithUserAgent:(NSString*)userAgent prevUserAgent:(NSString*)prevUserAgent;
@@ -68,6 +70,9 @@
@interface CDVInAppBrowserOptions : NSObject {}
@property (nonatomic, assign) BOOL location;
+@property (nonatomic, assign) BOOL toolbar;
+@property (nonatomic, copy) NSString* closebuttoncaption;
+
@property (nonatomic, copy) NSString* presentationstyle;
@property (nonatomic, copy) NSString* transitionstyle;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.m
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.m b/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.m
index b03d1fe..d5f06ec 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.m
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVInAppBrowser.m
@@ -103,13 +103,17 @@
CDVInAppBrowserOptions* browserOptions = [CDVInAppBrowserOptions parseOptions:options];
[self.inAppBrowserViewController showLocationBar:browserOptions.location];
+ [self.inAppBrowserViewController showToolBar:browserOptions.toolbar];
+ if (browserOptions.closebuttoncaption != nil) {
+ [self.inAppBrowserViewController setCloseButtonTitle:browserOptions.closebuttoncaption];
+ }
// Set Presentation Style
UIModalPresentationStyle presentationStyle = UIModalPresentationFullScreen; // default
if (browserOptions.presentationstyle != nil) {
- if ([browserOptions.presentationstyle isEqualToString:@"pagesheet"]) {
+ if ([[browserOptions.presentationstyle lowercaseString] isEqualToString:@"pagesheet"]) {
presentationStyle = UIModalPresentationPageSheet;
- } else if ([browserOptions.presentationstyle isEqualToString:@"formsheet"]) {
+ } else if ([[browserOptions.presentationstyle lowercaseString] isEqualToString:@"formsheet"]) {
presentationStyle = UIModalPresentationFormSheet;
}
}
@@ -118,9 +122,9 @@
// Set Transition Style
UIModalTransitionStyle transitionStyle = UIModalTransitionStyleCoverVertical; // default
if (browserOptions.transitionstyle != nil) {
- if ([browserOptions.transitionstyle isEqualToString:@"fliphorizontal"]) {
+ if ([[browserOptions.transitionstyle lowercaseString] isEqualToString:@"fliphorizontal"]) {
transitionStyle = UIModalTransitionStyleFlipHorizontal;
- } else if ([browserOptions.transitionstyle isEqualToString:@"crossdissolve"]) {
+ } else if ([[browserOptions.transitionstyle lowercaseString] isEqualToString:@"crossdissolve"]) {
transitionStyle = UIModalTransitionStyleCrossDissolve;
}
}
@@ -401,9 +405,6 @@
self.closeButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(close)];
self.closeButton.enabled = YES;
- self.closeButton.imageInsets = UIEdgeInsetsZero;
- self.closeButton.style = UIBarButtonItemStylePlain;
- self.closeButton.width = 32.000;
UIBarButtonItem* flexibleSpaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
@@ -467,32 +468,132 @@
[self.view addSubview:self.spinner];
}
+- (void)setCloseButtonTitle:(NSString*)title
+{
+ // the advantage of using UIBarButtonSystemItemDone is the system will localize it for you automatically
+ // but, if you want to set this yourself, knock yourself out (we can't set the title for a system Done button, so we have to create a new one)
+ self.closeButton = nil;
+ self.closeButton = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStyleBordered target:self action:@selector(close)];
+ self.closeButton.enabled = YES;
+ self.closeButton.tintColor = [UIColor colorWithRed:60.0 / 255.0 green:136.0 / 255.0 blue:230.0 / 255.0 alpha:1];
+
+ NSMutableArray* items = [self.toolbar.items mutableCopy];
+ [items replaceObjectAtIndex:0 withObject:self.closeButton];
+ [self.toolbar setItems:items];
+}
+
- (void)showLocationBar:(BOOL)show
{
- CGRect addressLabelFrame = self.addressLabel.frame;
- BOOL locationBarVisible = (addressLabelFrame.size.height > 0);
+ CGRect locationbarFrame = self.addressLabel.frame;
+
+ BOOL toolbarVisible = !self.toolbar.hidden;
// prevent double show/hide
- if (locationBarVisible == show) {
+ if (show == !(self.addressLabel.hidden)) {
return;
}
if (show) {
- CGRect webViewBounds = self.view.bounds;
- webViewBounds.size.height -= FOOTER_HEIGHT;
- self.webView.frame = webViewBounds;
+ self.addressLabel.hidden = NO;
+
+ if (toolbarVisible) {
+ // toolBar at the bottom, leave as is
+ // put locationBar on top of the toolBar
+
+ CGRect webViewBounds = self.view.bounds;
+ webViewBounds.size.height -= FOOTER_HEIGHT;
+ self.webView.frame = webViewBounds;
+
+ locationbarFrame.origin.y = webViewBounds.size.height;
+ self.addressLabel.frame = locationbarFrame;
+ } else {
+ // no toolBar, so put locationBar at the bottom
- CGRect addressLabelFrame = self.addressLabel.frame;
- addressLabelFrame.size.height = LOCATIONBAR_HEIGHT;
- self.addressLabel.frame = addressLabelFrame;
+ CGRect webViewBounds = self.view.bounds;
+ webViewBounds.size.height -= LOCATIONBAR_HEIGHT;
+ self.webView.frame = webViewBounds;
+
+ locationbarFrame.origin.y = webViewBounds.size.height;
+ self.addressLabel.frame = locationbarFrame;
+ }
} else {
- CGRect webViewBounds = self.view.bounds;
- webViewBounds.size.height -= TOOLBAR_HEIGHT;
- self.webView.frame = webViewBounds;
+ self.addressLabel.hidden = YES;
+
+ if (toolbarVisible) {
+ // locationBar is on top of toolBar, hide locationBar
+
+ // webView take up whole height less toolBar height
+ CGRect webViewBounds = self.view.bounds;
+ webViewBounds.size.height -= TOOLBAR_HEIGHT;
+ self.webView.frame = webViewBounds;
+ } else {
+ // no toolBar, expand webView to screen dimensions
+
+ CGRect webViewBounds = self.view.bounds;
+ self.webView.frame = webViewBounds;
+ }
+ }
+}
+
+- (void)showToolBar:(BOOL)show
+{
+ CGRect toolbarFrame = self.toolbar.frame;
+ CGRect locationbarFrame = self.addressLabel.frame;
- CGRect addressLabelFrame = self.addressLabel.frame;
- addressLabelFrame.size.height = 0;
- self.addressLabel.frame = addressLabelFrame;
+ BOOL locationbarVisible = !self.addressLabel.hidden;
+
+ // prevent double show/hide
+ if (show == !(self.toolbar.hidden)) {
+ return;
+ }
+
+ if (show) {
+ self.toolbar.hidden = NO;
+
+ if (locationbarVisible) {
+ // locationBar at the bottom, move locationBar up
+ // put toolBar at the bottom
+
+ CGRect webViewBounds = self.view.bounds;
+ webViewBounds.size.height -= FOOTER_HEIGHT;
+ self.webView.frame = webViewBounds;
+
+ locationbarFrame.origin.y = webViewBounds.size.height;
+ self.addressLabel.frame = locationbarFrame;
+
+ toolbarFrame.origin.y = (webViewBounds.size.height + LOCATIONBAR_HEIGHT);
+ self.toolbar.frame = toolbarFrame;
+ } else {
+ // no locationBar, so put toolBar at the bottom
+
+ CGRect webViewBounds = self.view.bounds;
+ webViewBounds.size.height -= TOOLBAR_HEIGHT;
+ self.webView.frame = webViewBounds;
+
+ toolbarFrame.origin.y = webViewBounds.size.height;
+ self.toolbar.frame = toolbarFrame;
+ }
+ } else {
+ self.toolbar.hidden = YES;
+
+ if (locationbarVisible) {
+ // locationBar is on top of toolBar, hide toolBar
+ // put locationBar at the bottom
+
+ // webView take up whole height less locationBar height
+ CGRect webViewBounds = self.view.bounds;
+ webViewBounds.size.height -= LOCATIONBAR_HEIGHT;
+ self.webView.frame = webViewBounds;
+
+ // move locationBar down
+ locationbarFrame.origin.y = webViewBounds.size.height;
+ self.addressLabel.frame = locationbarFrame;
+ } else {
+ // no locationBar, expand webView to screen dimensions
+
+ CGRect webViewBounds = self.view.bounds;
+ self.webView.frame = webViewBounds;
+ }
}
}
@@ -655,6 +756,8 @@
if (self = [super init]) {
// default values
self.location = YES;
+ self.toolbar = YES;
+ self.closebuttoncaption = nil;
self.enableviewportscale = NO;
self.mediaplaybackrequiresuseraction = NO;
@@ -679,19 +782,20 @@
if ([keyvalue count] == 2) {
NSString* key = [[keyvalue objectAtIndex:0] lowercaseString];
- NSString* value = [[keyvalue objectAtIndex:1] lowercaseString];
+ NSString* value = [keyvalue objectAtIndex:1];
+ NSString* value_lc = [value lowercaseString];
- BOOL isBoolean = [value isEqualToString:@"yes"] || [value isEqualToString:@"no"];
+ BOOL isBoolean = [value_lc isEqualToString:@"yes"] || [value_lc isEqualToString:@"no"];
NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setAllowsFloats:YES];
- BOOL isNumber = [numberFormatter numberFromString:value] != nil;
+ BOOL isNumber = [numberFormatter numberFromString:value_lc] != nil;
// set the property according to the key name
if ([obj respondsToSelector:NSSelectorFromString(key)]) {
if (isNumber) {
- [obj setValue:[numberFormatter numberFromString:value] forKey:key];
+ [obj setValue:[numberFormatter numberFromString:value_lc] forKey:key];
} else if (isBoolean) {
- [obj setValue:[NSNumber numberWithBool:[value isEqualToString:@"yes"]] forKey:key];
+ [obj setValue:[NSNumber numberWithBool:[value_lc isEqualToString:@"yes"]] forKey:key];
} else {
[obj setValue:value forKey:key];
}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVNotification.m
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVNotification.m b/lib/cordova-ios/CordovaLib/Classes/CDVNotification.m
index 821cb9f..464eb1f 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVNotification.m
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVNotification.m
@@ -31,10 +31,11 @@
* message The alert view message.
* title The alert view title.
* buttons The array of customized strings for the buttons.
+ * defaultText The input text for the textbox (if textbox exists).
* callbackId The commmand callback id.
* dialogType The type of alert view [alert | prompt].
*/
-- (void)showDialogWithMessage:(NSString*)message title:(NSString*)title buttons:(NSArray*)buttons callbackId:(NSString*)callbackId dialogType:(NSString*)dialogType
+- (void)showDialogWithMessage:(NSString*)message title:(NSString*)title buttons:(NSArray*)buttons defaultText:(NSString*)defaultText callbackId:(NSString*)callbackId dialogType:(NSString*)dialogType
{
CDVAlertView* alertView = [[CDVAlertView alloc]
initWithTitle:title
@@ -53,6 +54,8 @@
if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) {
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
+ UITextField* textField = [alertView textFieldAtIndex:0];
+ textField.text = defaultText;
}
[alertView show];
@@ -65,7 +68,7 @@
NSString* title = [command argumentAtIndex:1];
NSString* buttons = [command argumentAtIndex:2];
- [self showDialogWithMessage:message title:title buttons:@[buttons] callbackId:callbackId dialogType:DIALOG_TYPE_ALERT];
+ [self showDialogWithMessage:message title:title buttons:@[buttons] defaultText:nil callbackId:callbackId dialogType:DIALOG_TYPE_ALERT];
}
- (void)confirm:(CDVInvokedUrlCommand*)command
@@ -75,7 +78,7 @@
NSString* title = [command argumentAtIndex:1];
NSArray* buttons = [command argumentAtIndex:2];
- [self showDialogWithMessage:message title:title buttons:buttons callbackId:callbackId dialogType:DIALOG_TYPE_ALERT];
+ [self showDialogWithMessage:message title:title buttons:buttons defaultText:nil callbackId:callbackId dialogType:DIALOG_TYPE_ALERT];
}
- (void)prompt:(CDVInvokedUrlCommand*)command
@@ -84,8 +87,9 @@
NSString* message = [command argumentAtIndex:0];
NSString* title = [command argumentAtIndex:1];
NSArray* buttons = [command argumentAtIndex:2];
+ NSString* defaultText = [command argumentAtIndex:3];
- [self showDialogWithMessage:message title:title buttons:buttons callbackId:callbackId dialogType:DIALOG_TYPE_PROMPT];
+ [self showDialogWithMessage:message title:title buttons:buttons defaultText:defaultText callbackId:callbackId dialogType:DIALOG_TYPE_PROMPT];
}
/**
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVSplashScreen.m
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVSplashScreen.m b/lib/cordova-ios/CordovaLib/Classes/CDVSplashScreen.m
index 45889a0..fdb79fa 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVSplashScreen.m
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVSplashScreen.m
@@ -152,7 +152,12 @@
_curImageName = imageName;
}
- [self updateBounds];
+ // Check that splash screen's image exists before updating bounds
+ if (_imageView.image) {
+ [self updateBounds];
+ } else {
+ NSLog(@"WARNING: The splashscreen image named %@ was not found", imageName);
+ }
}
- (void)updateBounds
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.h
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.h b/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.h
index e339dd0..9165097 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.h
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.h
@@ -28,6 +28,7 @@ extern NSString* const kCDVDefaultWhitelistRejectionString;
- (id)initWithArray:(NSArray*)array;
- (BOOL)schemeIsAllowed:(NSString*)scheme;
- (BOOL)URLIsAllowed:(NSURL*)url;
+- (BOOL)URLIsAllowed:(NSURL*)url logFailure:(BOOL)logFailure;
- (NSString*)errorStringForURL:(NSURL*)url;
@end
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.m
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.m b/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.m
index db7aa32..e6807bd 100644
--- a/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.m
+++ b/lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.m
@@ -124,7 +124,7 @@ NSString* const kCDVDefaultSchemeName = @"cdv-default-scheme";
// check for single wildcard '*', if found set allowAll to YES
if ([host isEqualToString:@"*"]) {
- [_expandedWhitelists setObject:[NSArray arrayWithObject:host] forKey:scheme];
+ [_expandedWhitelists setObject:[NSMutableArray arrayWithObject:host] forKey:scheme];
continue;
}
@@ -170,19 +170,27 @@ NSString* const kCDVDefaultSchemeName = @"cdv-default-scheme";
- (BOOL)URLIsAllowed:(NSURL*)url
{
+ return [self URLIsAllowed:url logFailure:YES];
+}
+
+- (BOOL)URLIsAllowed:(NSURL*)url logFailure:(BOOL)logFailure
+{
NSString* scheme = [url scheme];
// http[s] and ftp[s] should also validate against the common set in the kCDVDefaultSchemeName list
if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"ftp"] || [scheme isEqualToString:@"ftps"]) {
NSURL* newUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@://%@", kCDVDefaultSchemeName, [url host]]];
// If it is allowed, we are done. If not, continue to check for the actual scheme-specific list
- if ([self URLIsAllowed:newUrl]) {
+ if ([self URLIsAllowed:newUrl logFailure:NO]) {
return YES;
}
}
// Check that the scheme is supported
if (![self schemeIsAllowed:scheme]) {
+ if (logFailure) {
+ NSLog(@"%@", [self errorStringForURL:url]);
+ }
return NO;
}
@@ -204,13 +212,20 @@ NSString* const kCDVDefaultSchemeName = @"cdv-default-scheme";
while (regex = [enumerator nextObject]) {
NSPredicate* regex_test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
+ // if wildcard, break out and allow
+ if ([regex isEqualToString:@"*"]) {
+ return YES;
+ }
+
if ([regex_test evaluateWithObject:urlHost] == YES) {
// if it matches at least one rule, return
return YES;
}
}
- NSLog(@"%@", [self errorStringForURL:url]);
+ if (logFailure) {
+ NSLog(@"%@", [self errorStringForURL:url]);
+ }
// if we got here, the url host is not in the white-list, do nothing
return NO;
}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/VERSION
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/VERSION b/lib/cordova-ios/CordovaLib/VERSION
index 24ba9a3..1277c83 100644
--- a/lib/cordova-ios/CordovaLib/VERSION
+++ b/lib/cordova-ios/CordovaLib/VERSION
@@ -1 +1 @@
-2.7.0
+2.8.0rc1
[02/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLibTests/CDVWhitelistTests.m
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLibTests/CDVWhitelistTests.m b/lib/cordova-ios/CordovaLibTests/CDVWhitelistTests.m
index 21576a3..b809972 100644
--- a/lib/cordova-ios/CordovaLibTests/CDVWhitelistTests.m
+++ b/lib/cordova-ios/CordovaLibTests/CDVWhitelistTests.m
@@ -290,4 +290,22 @@
STAssertFalse([whitelist URLIsAllowed:[NSURL URLWithString:@"http://www.google.com"]], nil);
}
+- (void)testWildcardPlusOtherUrls
+{
+ // test for https://issues.apache.org/jira/browse/CB-3394
+
+ NSArray* allowedHosts = [NSArray arrayWithObjects:
+ @"*",
+ @"cordova.apache.org",
+ nil];
+
+ CDVWhitelist* whitelist = [[CDVWhitelist alloc] initWithArray:allowedHosts];
+
+ STAssertTrue([whitelist URLIsAllowed:[NSURL URLWithString:@"http://*.apache.org"]], nil);
+ STAssertTrue([whitelist URLIsAllowed:[NSURL URLWithString:@"https://www.google.com"]], nil);
+ STAssertTrue([whitelist URLIsAllowed:[NSURL URLWithString:@"ftp://cordova.apache.org"]], nil);
+ STAssertTrue([whitelist URLIsAllowed:[NSURL URLWithString:@"http://cordova.apache.org"]], nil);
+ STAssertTrue([whitelist URLIsAllowed:[NSURL URLWithString:@"https://cordova.apache.org"]], nil);
+}
+
@end
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLibTests/CordovaLibApp/config.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLibTests/CordovaLibApp/config.xml b/lib/cordova-ios/CordovaLibTests/CordovaLibApp/config.xml
index f8a2fad..3e84967 100644
--- a/lib/cordova-ios/CordovaLibTests/CordovaLibApp/config.xml
+++ b/lib/cordova-ios/CordovaLibTests/CordovaLibApp/config.xml
@@ -1,40 +1,95 @@
<?xml version="1.0" encoding="UTF-8"?>
-<widget>
- <preference name="KeyboardDisplayRequiresUserAction" value="true" />
- <preference name="SuppressesIncrementalRendering" value="false" />
+<widget xmlns = "http://www.w3.org/ns/widgets"
+ id = "io.cordova.helloCordova"
+ version = "2.0.0">
+ <name>Hello Cordova</name>
+
+ <description>
+ A sample Apache Cordova application that responds to the deviceready event.
+ </description>
+
+ <author href="http://cordova.io" email="dev@cordova.apache.org">
+ Apache Cordova Team
+ </author>
+
+ <access origin="*"/>
+
+ <!-- <content src="http://mysite.com/myapp.html" /> for external pages -->
+ <content src="index.html" />
+
+ <!-- Preferences for iOS -->
+ <preference name="AllowInlineMediaPlayback" value="false" />
+ <preference name="AutoHideSplashScreen" value="true" />
+ <preference name="BackupWebStorage" value="cloud" />
<preference name="DisallowOverscroll" value="false" />
- <preference name="TopActivityIndicator" value="gray" />
<preference name="EnableLocation" value="false" /><!-- DEPRECATED -->
<preference name="EnableViewportScale" value="false" />
- <preference name="AutoHideSplashScreen" value="true" />
- <preference name="ShowSplashScreenSpinner" value="true" />
<preference name="FadeSplashScreen" value="true" />
- <preference name="FadeSplashScreenDuration" value="2" />
- <preference name="MediaPlaybackRequiresUserAction" value="false" />
- <preference name="AllowInlineMediaPlayback" value="false" />
- <preference name="BackupWebStorage" value="cloud" />
+ <preference name="FadeSplashScreenDuration" value=".25" />
<preference name="HideKeyboardFormAccessoryBar" value="false" />
+ <preference name="KeyboardDisplayRequiresUserAction" value="true" />
<preference name="KeyboardShrinksView" value="false" />
+ <preference name="MediaPlaybackRequiresUserAction" value="false" />
+ <preference name="ShowSplashScreenSpinner" value="true" />
+ <preference name="SuppressesIncrementalRendering" value="false" />
+ <preference name="TopActivityIndicator" value="gray" />
+
- <plugins>
- <plugin name="LocalStorage" value="CDVLocalStorage" />
- <plugin name="Device" value="CDVDevice" />
- <plugin name="Logger" value="CDVLogger" />
- <plugin name="Compass" value="CDVLocation" />
- <plugin name="Accelerometer" value="CDVAccelerometer" />
- <plugin name="Camera" value="CDVCamera" />
- <plugin name="NetworkStatus" value="CDVConnection" />
- <plugin name="Contacts" value="CDVContacts" />
- <plugin name="File" value="CDVFile" />
- <plugin name="FileTransfer" value="CDVFileTransfer" />
- <plugin name="Geolocation" value="CDVLocation" />
- <plugin name="Notification" value="CDVNotification" />
- <plugin name="Media" value="CDVSound" />
- <plugin name="Capture" value="CDVCapture" />
- <plugin name="SplashScreen" value="CDVSplashScreen" />
- <plugin name="Echo" value="CDVEcho" />
- <plugin name="Battery" value="CDVBattery" />
- <plugin name="Globalization" value="CDVGlobalization" />
- <plugin name="InAppBrowser" value="CDVInAppBrowser" />
- </plugins>
+ <feature name="Geolocation">
+ <param name="ios-package" value="CDVLocation"/>
+ </feature>
+ <feature name="Device">
+ <param name="ios-package" value="CDVDevice"/>
+ </feature>
+ <feature name="Accelerometer">
+ <param name="ios-package" value="CDVAccelerometer"/>
+ </feature>
+ <feature name="Compass">
+ <param name="ios-package" value="CDVLocation"/>
+ </feature>
+ <feature name="Media">
+ <param name="ios-package" value="CDVSound"/>
+ </feature>
+ <feature name="Camera">
+ <param name="ios-package" value="CDVCamera"/>
+ </feature>
+ <feature name="Contacts">
+ <param name="ios-package" value="CDVContacts"/>
+ </feature>
+ <feature name="File">
+ <param name="ios-package" value="CDVFile"/>
+ </feature>
+ <feature name="NetworkStatus">
+ <param name="ios-package" value="CDVConnection"/>
+ </feature>
+ <feature name="Notification">
+ <param name="ios-package" value="CDVNotification"/>
+ </feature>
+ <feature name="FileTransfer">
+ <param name="ios-package" value="CDVFileTransfer"/>
+ </feature>
+ <feature name="Capture">
+ <param name="ios-package" value="CDVCapture"/>
+ </feature>
+ <feature name="Battery">
+ <param name="ios-package" value="CDVBattery"/>
+ </feature>
+ <feature name="SplashScreen">
+ <param name="ios-package" value="CDVSplashScreen"/>
+ </feature>
+ <feature name="Echo">
+ <param name="ios-package" value="CDVEcho"/>
+ </feature>
+ <feature name="Globalization">
+ <param name="ios-package" value="CDVGlobalization"/>
+ </feature>
+ <feature name="InAppBrowser">
+ <param name="ios-package" value="CDVInAppBrowser"/>
+ </feature>
+ <feature name="Logger">
+ <param name="ios-package" value="CDVLogger"/>
+ </feature>
+ <feature name="LocalStorage">
+ <param name="ios-package" value="CDVLocalStorage"/>
+ </feature>
</widget>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLibTests/CordovaLibApp/www/index.html
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLibTests/CordovaLibApp/www/index.html b/lib/cordova-ios/CordovaLibTests/CordovaLibApp/www/index.html
index 1cac0a4..17f1319 100644
--- a/lib/cordova-ios/CordovaLibTests/CordovaLibApp/www/index.html
+++ b/lib/cordova-ios/CordovaLibTests/CordovaLibApp/www/index.html
@@ -32,7 +32,7 @@
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" type="text/css" />
-->
<!-- If your application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here -->
- <script type="text/javascript" charset="utf-8" src="cordova.ios.js"></script>
+ <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript">
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLibTests/CordovaTests.xcodeproj/project.pbxproj
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLibTests/CordovaTests.xcodeproj/project.pbxproj b/lib/cordova-ios/CordovaLibTests/CordovaTests.xcodeproj/project.pbxproj
index 219eb53..220d189 100644
--- a/lib/cordova-ios/CordovaLibTests/CordovaTests.xcodeproj/project.pbxproj
+++ b/lib/cordova-ios/CordovaLibTests/CordovaTests.xcodeproj/project.pbxproj
@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
+ 302193F91745430F00BC8D2B /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 302193F81745430F00BC8D2B /* ImageIO.framework */; };
3035621714104C34006C2D43 /* CDVWhitelistTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 30356213141049E1006C2D43 /* CDVWhitelistTests.m */; };
303A406A152124BB00182201 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 686357AA141002F100DF4CF2 /* UIKit.framework */; };
303A406B152124BB00182201 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 686357AC141002F100DF4CF2 /* Foundation.framework */; };
@@ -76,6 +77,7 @@
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
+ 302193F81745430F00BC8D2B /* ImageIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ImageIO.framework; path = System/Library/Frameworks/ImageIO.framework; sourceTree = SDKROOT; };
30356213141049E1006C2D43 /* CDVWhitelistTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVWhitelistTests.m; sourceTree = "<group>"; };
303A4068152124BB00182201 /* CordovaLibApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CordovaLibApp.app; sourceTree = BUILT_PRODUCTS_DIR; };
303A406F152124BB00182201 /* CordovaLibApp-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = "CordovaLibApp-Info.plist"; sourceTree = "<group>"; };
@@ -89,7 +91,6 @@
30AE4E8C1419532F005A9C9A /* CDVContactsTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVContactsTests.m; sourceTree = "<group>"; };
30B342F415224B360070E6A5 /* CDVWebViewTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVWebViewTest.m; sourceTree = "<group>"; };
30D1B08B15A2B36D0060C291 /* CDVBase64Tests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVBase64Tests.m; sourceTree = "<group>"; };
- 30F8AE12152127CE006625B3 /* Cordova.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Cordova.plist; sourceTree = "<group>"; };
30F8AE1C152129DA006625B3 /* www */ = {isa = PBXFileReference; lastKnownFileType = folder; path = www; sourceTree = "<group>"; };
686357A9141002F100DF4CF2 /* CordovaLibTests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CordovaLibTests.octest; sourceTree = BUILT_PRODUCTS_DIR; };
686357AA141002F100DF4CF2 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
@@ -122,6 +123,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
+ 302193F91745430F00BC8D2B /* ImageIO.framework in Frameworks */,
EB3B34E9161B5532003DBE7D /* libCordova.a in Frameworks */,
8220B5C216D541BD00EC3921 /* AssetsLibrary.framework in Frameworks */,
30F8AE0C152125B6006625B3 /* MobileCoreServices.framework in Frameworks */,
@@ -185,6 +187,7 @@
0867D69AFE84028FC02AAC07 /* Frameworks */ = {
isa = PBXGroup;
children = (
+ 302193F81745430F00BC8D2B /* ImageIO.framework */,
68A32D7414103017006B237C /* AddressBook.framework */,
8220B5C116D541BD00EC3921 /* AssetsLibrary.framework */,
686357DC14100B1600DF4CF2 /* CoreMedia.framework */,
@@ -217,7 +220,6 @@
303A406E152124BB00182201 /* Supporting Files */ = {
isa = PBXGroup;
children = (
- 30F8AE12152127CE006625B3 /* Cordova.plist */,
303A406F152124BB00182201 /* CordovaLibApp-Info.plist */,
303A4070152124BB00182201 /* InfoPlist.strings */,
303A4073152124BB00182201 /* main.m */,
@@ -272,7 +274,7 @@
303A4064152124BB00182201 /* Sources */,
303A4065152124BB00182201 /* Frameworks */,
303A4066152124BB00182201 /* Resources */,
- 30F8AE1615212883006625B3 /* Copy cordova.ios.js into www directory */,
+ 30F8AE1615212883006625B3 /* Copy cordova.js into www directory */,
);
buildRules = (
);
@@ -371,7 +373,7 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
- 30F8AE1615212883006625B3 /* Copy cordova.ios.js into www directory */ = {
+ 30F8AE1615212883006625B3 /* Copy cordova.js into www directory */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
@@ -379,12 +381,12 @@
inputPaths = (
"",
);
- name = "Copy cordova.ios.js into www directory";
+ name = "Copy cordova.js into www directory";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
- shellScript = "cp ../CordovaLib/cordova.ios.js \"$BUILT_PRODUCTS_DIR/$FULL_PRODUCT_NAME/www/cordova.ios.js\"";
+ shellScript = "cp ../CordovaLib/cordova.js \"$BUILT_PRODUCTS_DIR/$FULL_PRODUCT_NAME/www/cordova.js\"";
showEnvVarsInLog = 0;
};
686357A7141002F100DF4CF2 /* ShellScript */ = {
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/FirstRun.md
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/FirstRun.md b/lib/cordova-ios/FirstRun.md
index 5041249..58b79d7 100644
--- a/lib/cordova-ios/FirstRun.md
+++ b/lib/cordova-ios/FirstRun.md
@@ -43,7 +43,7 @@ Please see the **Cordova Plugin Upgrade Guide.md** document included in the **gu
## Project Upgrades
1. Please see the [**Upgrading Cordova iOS**](http://docs.cordova.io/en/edge/guide_upgrading_index.md.html) document on [http://docs.cordova.io](http://docs.cordova.io)
-2. See the FAQ in the README.md as well included in the source distribution
+2. See the **FAQ** in the README.md as well included in the source distribution
<br />
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/create
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/create b/lib/cordova-ios/bin/create
index d617f09..7f5a5d9 100755
--- a/lib/cordova-ios/bin/create
+++ b/lib/cordova-ios/bin/create
@@ -83,9 +83,7 @@ fi
cp -r "$BINDIR/templates/project/" "$PROJECT_PATH"
# Copy in the JS.
-cp "$CORDOVALIB_DIR/cordova.ios.js" "$PROJECT_PATH/www/cordova-$CDV_VER.js"
-# Change the filename reference in the html from cordova.ios.js -> cordova-VERSION.js.
-/usr/bin/sed -i "" "s/src[ ]*=[ ]*[\\'\"]cordova.ios.js[\\'\"]/src=\"cordova-${CDV_VER}.js\"/g" "$PROJECT_PATH/www/index.html"
+cp "$CORDOVALIB_DIR/cordova.js" "$PROJECT_PATH/www/cordova.js"
# I've tried to be thorough in my documentation of the manual actions below...
# on first brush it would seem that the right solution would be to brute force
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/__TESTING__.xcodeproj/project.pbxproj
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/__TESTING__.xcodeproj/project.pbxproj b/lib/cordova-ios/bin/templates/project/__TESTING__.xcodeproj/project.pbxproj
index 0af952e..6b81e10 100755
--- a/lib/cordova-ios/bin/templates/project/__TESTING__.xcodeproj/project.pbxproj
+++ b/lib/cordova-ios/bin/templates/project/__TESTING__.xcodeproj/project.pbxproj
@@ -41,6 +41,9 @@
30A0434914DC770100060A13 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 30A0434614DC770100060A13 /* Localizable.strings */; };
30E5649213A7FCAF007403D8 /* CoreMedia.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 30E5649113A7FCAF007403D8 /* CoreMedia.framework */; settings = {ATTRIBUTES = (Weak, ); }; };
30FC414916E50CA1004E6F35 /* icon-72@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 30FC414816E50CA1004E6F35 /* icon-72@2x.png */; };
+ 5AA0E66D1729F45B000DC89A /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5AA0E66C1729F45B000DC89A /* OpenAL.framework */; };
+ 5AA0E66F1729F460000DC89A /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5AA0E66E1729F460000DC89A /* ImageIO.framework */; };
+ 5AEE5B35173C68D80009041E /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5AEE5B34173C68D80009041E /* CoreLocation.framework */; };
5B1594DD16A7569C00FEF299 /* AssetsLibrary.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5B1594DC16A7569C00FEF299 /* AssetsLibrary.framework */; };
D4A0D8761607E02300AEF8BB /* Default-568h@2x~iphone.png in Resources */ = {isa = PBXBuildFile; fileRef = D4A0D8751607E02300AEF8BB /* Default-568h@2x~iphone.png */; };
F840E1F1165FE0F500CFE078 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = F840E1F0165FE0F500CFE078 /* config.xml */; };
@@ -103,6 +106,9 @@
30E5649113A7FCAF007403D8 /* CoreMedia.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMedia.framework; path = System/Library/Frameworks/CoreMedia.framework; sourceTree = SDKROOT; };
30FC414816E50CA1004E6F35 /* icon-72@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-72@2x.png"; sourceTree = "<group>"; };
32CA4F630368D1EE00C91783 /* __TESTING__-Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "__TESTING__-Prefix.pch"; sourceTree = "<group>"; };
+ 5AA0E66C1729F45B000DC89A /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; };
+ 5AA0E66E1729F460000DC89A /* ImageIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ImageIO.framework; path = System/Library/Frameworks/ImageIO.framework; sourceTree = SDKROOT; };
+ 5AEE5B34173C68D80009041E /* CoreLocation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = System/Library/Frameworks/CoreLocation.framework; sourceTree = SDKROOT; };
5B1594DC16A7569C00FEF299 /* AssetsLibrary.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AssetsLibrary.framework; path = System/Library/Frameworks/AssetsLibrary.framework; sourceTree = SDKROOT; };
8D1107310486CEB800E47090 /* __TESTING__-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "__TESTING__-Info.plist"; path = "../__TESTING__-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = "<group>"; };
D4A0D8751607E02300AEF8BB /* Default-568h@2x~iphone.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x~iphone.png"; sourceTree = "<group>"; };
@@ -114,6 +120,9 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
+ 301BF5BF109A6A2B0062928A /* CoreLocation.framework in Frameworks */,
+ 5AA0E66F1729F460000DC89A /* ImageIO.framework in Frameworks */,
+ 5AA0E66D1729F45B000DC89A /* OpenAL.framework in Frameworks */,
5B1594DD16A7569C00FEF299 /* AssetsLibrary.framework in Frameworks */,
301BF552109A68D80062928A /* libCordova.a in Frameworks */,
1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */,
@@ -124,12 +133,12 @@
301BF5B9109A6A2B0062928A /* AudioToolbox.framework in Frameworks */,
301BF5BB109A6A2B0062928A /* AVFoundation.framework in Frameworks */,
301BF5BD109A6A2B0062928A /* CFNetwork.framework in Frameworks */,
- 301BF5BF109A6A2B0062928A /* CoreLocation.framework in Frameworks */,
301BF5C1109A6A2B0062928A /* MediaPlayer.framework in Frameworks */,
301BF5C3109A6A2B0062928A /* QuartzCore.framework in Frameworks */,
301BF5C5109A6A2B0062928A /* SystemConfiguration.framework in Frameworks */,
305D5FD1115AB8F900A74A75 /* MobileCoreServices.framework in Frameworks */,
30E5649213A7FCAF007403D8 /* CoreMedia.framework in Frameworks */,
+ 5AEE5B35173C68D80009041E /* CoreLocation.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -218,6 +227,9 @@
29B97323FDCFA39411CA2CEA /* Frameworks */ = {
isa = PBXGroup;
children = (
+ 5AEE5B34173C68D80009041E /* CoreLocation.framework */,
+ 5AA0E66E1729F460000DC89A /* ImageIO.framework */,
+ 5AA0E66C1729F45B000DC89A /* OpenAL.framework */,
5B1594DC16A7569C00FEF299 /* AssetsLibrary.framework */,
1DF5F4DF0D08C38300B7A737 /* UIKit.framework */,
1D30AB110D05D00D00671497 /* Foundation.framework */,
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/__TESTING__/.gitignore
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/__TESTING__/.gitignore b/lib/cordova-ios/bin/templates/project/__TESTING__/.gitignore
deleted file mode 100644
index d30c0b0..0000000
--- a/lib/cordova-ios/bin/templates/project/__TESTING__/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-*.mode1v3
-*.perspectivev3
-*.pbxuser
-.DS_Store
-build
-www/phonegap.js
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/de.lproj/Localizable.strings
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/de.lproj/Localizable.strings b/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/de.lproj/Localizable.strings
index f1cdb42..3dbbf49 100644
--- a/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/de.lproj/Localizable.strings
+++ b/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/de.lproj/Localizable.strings
@@ -18,6 +18,8 @@
*/
+// controller title for Videos
+"Videos title" = "Videos";
// accessibility label for recording button
"toggle audio recording" = "starten/beenden der Tonaufnahme";
// notification spoken by VoiceOver when timed recording finishes
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/en.lproj/Localizable.strings
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/en.lproj/Localizable.strings b/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/en.lproj/Localizable.strings
index 8972684..860e13c 100644
--- a/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/en.lproj/Localizable.strings
+++ b/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/en.lproj/Localizable.strings
@@ -17,6 +17,8 @@
under the License.
*/
+// controller title for Videos
+"Videos title" = "Videos";
// accessibility label for recording button
"toggle audio recording" = "toggle audio recording";
// notification spoken by VoiceOver when timed recording finishes
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/es.lproj/Localizable.strings
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/es.lproj/Localizable.strings b/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/es.lproj/Localizable.strings
index 23831e6..ab39fce 100644
--- a/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/es.lproj/Localizable.strings
+++ b/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/es.lproj/Localizable.strings
@@ -17,6 +17,8 @@
under the License.
*/
+// controller title for Videos
+"Videos title" = "Videos";
// accessibility label for recording button
"toggle audio recording" = "grabación de audio cambiar";
// notification spoken by VoiceOver when timed recording finishes
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/se.lproj/Localizable.strings
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/se.lproj/Localizable.strings b/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/se.lproj/Localizable.strings
index 0af9646..4da165f 100644
--- a/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/se.lproj/Localizable.strings
+++ b/lib/cordova-ios/bin/templates/project/__TESTING__/Resources/se.lproj/Localizable.strings
@@ -18,6 +18,8 @@
*/
+// controller title for Videos
+"Videos title" = "Videor";
// accessibility label for recording button
"toggle audio recording" = "börja/avsluta inspelning";
// notification spoken by VoiceOver when timed recording finishes
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/__TESTING__/config.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/__TESTING__/config.xml b/lib/cordova-ios/bin/templates/project/__TESTING__/config.xml
index 537705d..ca292c8 100644
--- a/lib/cordova-ios/bin/templates/project/__TESTING__/config.xml
+++ b/lib/cordova-ios/bin/templates/project/__TESTING__/config.xml
@@ -1,25 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
-<!--
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
--->
-<widget>
+<widget xmlns = "http://www.w3.org/ns/widgets"
+ id = "io.cordova.helloCordova"
+ version = "2.0.0">
+ <name>Hello Cordova</name>
+
+ <description>
+ A sample Apache Cordova application that responds to the deviceready event.
+ </description>
+
+ <author href="http://cordova.io" email="dev@cordova.apache.org">
+ Apache Cordova Team
+ </author>
+
+ <access origin="*"/>
+
+ <!-- <content src="http://mysite.com/myapp.html" /> for external pages -->
+ <content src="index.html" />
+
+ <!-- Preferences for iOS -->
<preference name="AllowInlineMediaPlayback" value="false" />
<preference name="AutoHideSplashScreen" value="true" />
<preference name="BackupWebStorage" value="cloud" />
@@ -36,28 +34,65 @@
<preference name="SuppressesIncrementalRendering" value="false" />
<preference name="TopActivityIndicator" value="gray" />
- <content src="index.html" />
+ <feature name="Geolocation">
+ <param name="ios-package" value="CDVLocation"/>
+ </feature>
+ <feature name="Device">
+ <param name="ios-package" value="CDVDevice"/>
+ </feature>
+ <feature name="Accelerometer">
+ <param name="ios-package" value="CDVAccelerometer"/>
+ </feature>
+ <feature name="Compass">
+ <param name="ios-package" value="CDVLocation"/>
+ </feature>
+ <feature name="Media">
+ <param name="ios-package" value="CDVSound"/>
+ </feature>
+ <feature name="Camera">
+ <param name="ios-package" value="CDVCamera"/>
+ </feature>
+ <feature name="Contacts">
+ <param name="ios-package" value="CDVContacts"/>
+ </feature>
+ <feature name="File">
+ <param name="ios-package" value="CDVFile"/>
+ </feature>
+ <feature name="NetworkStatus">
+ <param name="ios-package" value="CDVConnection"/>
+ </feature>
+ <feature name="Notification">
+ <param name="ios-package" value="CDVNotification"/>
+ </feature>
+ <feature name="FileTransfer">
+ <param name="ios-package" value="CDVFileTransfer"/>
+ </feature>
+ <feature name="Capture">
+ <param name="ios-package" value="CDVCapture"/>
+ </feature>
+ <feature name="Battery">
+ <param name="ios-package" value="CDVBattery"/>
+ </feature>
+ <feature name="SplashScreen">
+ <param name="ios-package" value="CDVSplashScreen"/>
+ </feature>
+ <feature name="Echo">
+ <param name="ios-package" value="CDVEcho"/>
+ </feature>
+ <feature name="Globalization">
+ <param name="ios-package" value="CDVGlobalization"/>
+ </feature>
+ <feature name="InAppBrowser">
+ <param name="ios-package" value="CDVInAppBrowser"/>
+ </feature>
+ <feature name="Logger">
+ <param name="ios-package" value="CDVLogger"/>
+ </feature>
+ <feature name="LocalStorage">
+ <param name="ios-package" value="CDVLocalStorage"/>
+ </feature>
+ <!-- Deprecated plugins element. REmove in 3.0 -->
<plugins>
- <plugin name="Device" value="CDVDevice" />
- <plugin name="Logger" value="CDVLogger" />
- <plugin name="Compass" value="CDVLocation" />
- <plugin name="Accelerometer" value="CDVAccelerometer" />
- <plugin name="Camera" value="CDVCamera" />
- <plugin name="NetworkStatus" value="CDVConnection" />
- <plugin name="Contacts" value="CDVContacts" />
- <plugin name="Echo" value="CDVEcho" />
- <plugin name="File" value="CDVFile" />
- <plugin name="FileTransfer" value="CDVFileTransfer" />
- <plugin name="Geolocation" value="CDVLocation" />
- <plugin name="Notification" value="CDVNotification" />
- <plugin name="Media" value="CDVSound" />
- <plugin name="Capture" value="CDVCapture" />
- <plugin name="SplashScreen" value="CDVSplashScreen" />
- <plugin name="Battery" value="CDVBattery" />
- <plugin name="Globalization" value="CDVGlobalization" />
- <plugin name="InAppBrowser" value="CDVInAppBrowser" />
</plugins>
-
- <access origin="*" />
</widget>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/build
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/build b/lib/cordova-ios/bin/templates/project/cordova/build
deleted file mode 100755
index 1574c5e..0000000
--- a/lib/cordova-ios/bin/templates/project/cordova/build
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/bin/bash
-
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-#
-# compile and launch a Cordova/iOS project to the simulator
-#
-
-set -e
-
-XCODE_VER=$(xcodebuild -version | head -n 1 | sed -e 's/Xcode //')
-XCODE_MIN_VERSION="4.5"
-
-if [[ "$XCODE_VER" < "$XCODE_MIN_VERSION" ]]; then
- echo "Cordova can only run in Xcode version $XCODE_MIN_VERSION or greater."
- exit 1
-fi
-
-CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd -P)
-PROJECT_PATH="$(dirname "$CORDOVA_PATH")"
-XCODEPROJ=$( ls "$PROJECT_PATH" | grep .xcodeproj )
-PROJECT_NAME=$(basename "$XCODEPROJ" .xcodeproj)
-
-cd "$PROJECT_PATH"
-
-APP=build/$PROJECT_NAME.app
-SDK=`xcodebuild -showsdks | grep Sim | tail -1 | awk '{print $6}'`
-
-xcodebuild -project $PROJECT_NAME.xcodeproj -arch i386 -target $PROJECT_NAME -configuration Debug -sdk $SDK clean build VALID_ARCHS="i386" CONFIGURATION_BUILD_DIR="$PROJECT_PATH/build"
-
-
-
-
-
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/clean
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/clean b/lib/cordova-ios/bin/templates/project/cordova/clean
new file mode 100755
index 0000000..9a386fe
--- /dev/null
+++ b/lib/cordova-ios/bin/templates/project/cordova/clean
@@ -0,0 +1,44 @@
+#!/bin/bash
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+#
+# Clean a Cordova/iOS project
+#
+
+set -e
+
+XCODE_VER=$(xcodebuild -version | head -n 1 | sed -e 's/Xcode //')
+XCODE_MIN_VERSION="4.5"
+
+if [[ "$XCODE_VER" < "$XCODE_MIN_VERSION" ]]; then
+ echo "Cordova can only run in Xcode version $XCODE_MIN_VERSION or greater."
+ exit 1
+fi
+
+CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd -P)
+PROJECT_PATH="$(dirname "$CORDOVA_PATH")"
+XCODEPROJ=$( ls "$PROJECT_PATH" | grep .xcodeproj )
+PROJECT_NAME=$(basename "$XCODEPROJ" .xcodeproj)
+
+cd "$PROJECT_PATH"
+
+xcodebuild -project $PROJECT_NAME.xcodeproj -configuration Debug -alltargets clean
+xcodebuild -project $PROJECT_NAME.xcodeproj -configuration Release -alltargets clean
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/emulate
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/emulate b/lib/cordova-ios/bin/templates/project/cordova/emulate
index f26cb3a..e81c1bd 100755
--- a/lib/cordova-ios/bin/templates/project/cordova/emulate
+++ b/lib/cordova-ios/bin/templates/project/cordova/emulate
@@ -46,10 +46,20 @@ if [ ! -d "$APP_PATH" ]; then
exit 1
fi
-# launch using ios-sim
-if which ios-sim >/dev/null; then
- ios-sim launch "$APP_PATH" --family "$DEVICE_FAMILY" --stderr "$CORDOVA_PATH/console.log" --stdout "$CORDOVA_PATH/console.log" &
-else
- echo -e '\033[31mError: ios-sim was not found. Please download, build and install version 1.4 or greater from https://github.com/phonegap/ios-sim into your path. Or "brew install ios-sim" using homebrew: http://mxcl.github.com/homebrew/\033[m'; exit 1;
+IOS_SIM_MIN_VERSION="1.5"
+IOS_SIM_LOCATION=$(which ios-sim)
+if [ $? != 0 ]; then
+ echo -e "\033[31mError: ios-sim was not found. Please download, build and install version $IOS_SIM_MIN_VERSION or greater from https://github.com/phonegap/ios-sim into your path. Or 'brew install ios-sim' using homebrew: http://mxcl.github.com/homebrew/\033[m"; exit 1;
+ exit 1
+fi
+
+IOS_SIM_VERSION=$(ios-sim --version)
+
+if [[ "$IOS_SIM_VERSION" < "$IOS_SIM_MIN_VERSION" ]]; then
+ echo "Cordova needs ios-sim version $IOS_SIM_MIN_VERSION or greater, you have version $IOS_SIM_VERSION."
+ exit 1
fi
+# launch using ios-sim
+ios-sim launch "$APP_PATH" --family "$DEVICE_FAMILY" --stderr "$CORDOVA_PATH/console.log" --stdout "$CORDOVA_PATH/console.log" &
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/lib/install-device
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/lib/install-device b/lib/cordova-ios/bin/templates/project/cordova/lib/install-device
new file mode 100755
index 0000000..ad6993d
--- /dev/null
+++ b/lib/cordova-ios/bin/templates/project/cordova/lib/install-device
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# Valid values for "--target" (case insensitive):
+# "iPhone (Retina 3.5-inch)" (default)
+# "iPhone (Retina 4-inch)"
+# "iPhone"
+# "iPad"
+# "iPad (Retina)"
+
+set -e
+
+echo 'iOS: Not able to install to device through command-line at this time.'
+exit 1
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/lib/install-emulator
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/lib/install-emulator b/lib/cordova-ios/bin/templates/project/cordova/lib/install-emulator
new file mode 100755
index 0000000..a5485cf
--- /dev/null
+++ b/lib/cordova-ios/bin/templates/project/cordova/lib/install-emulator
@@ -0,0 +1,130 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# Valid values for "--target" (case insensitive):
+# "iPhone (Retina 3.5-inch)" (default)
+# "iPhone (Retina 4-inch)"
+# "iPhone"
+# "iPad"
+# "iPad (Retina)"
+
+set -e
+
+OPTION_RESULT=()
+TARGET="iPhone (Retina 3.5-inch)"
+TARGET_FLAG='--family iphone --retina'
+
+# separates "key=value", sets an array with 0th index as key, 1st index as value
+_parseOption()
+{
+ local ARG=$@
+ OIFS=$IFS
+ IFS='='
+
+ OPTION_RESULT=()
+ for i in ${ARG[@]}
+ do
+ OPTION_RESULT+=($i)
+ done
+
+ IFS=$OIFS
+}
+
+# parses key=value arguments
+_parseArgs()
+{
+ for arg in "$@"
+ do
+ _parseOption ${arg}
+ case "${OPTION_RESULT[0]}" in
+ "--target")
+ TARGET=${OPTION_RESULT[1]}
+ ;;
+ esac
+ done
+}
+
+_parseArgs "$@"
+
+# lowercase the target string
+TARGET_LC=`echo $TARGET | tr '[:upper:]' '[:lower:]'`
+
+# remember the comparison is lowercase
+case "$TARGET_LC" in
+ "iphone (retina 3.5-inch)")
+ TARGET_FLAG="--family iphone --retina"
+ ;;
+ "iphone (retina 4-inch)")
+ TARGET_FLAG="--family iphone --retina --tall"
+ ;;
+ "iphone")
+ TARGET_FLAG="--family iphone"
+ ;;
+ "ipad")
+ TARGET_FLAG="--family ipad"
+ ;;
+ "ipad (retina)")
+ TARGET_FLAG="--family ipad --retina"
+ ;;
+esac
+
+XCODE_VER=$(xcodebuild -version | head -n 1 | sed -e 's/Xcode //')
+XCODE_MIN_VERSION="4.5"
+
+if [[ "$XCODE_VER" < "$XCODE_MIN_VERSION" ]]; then
+ echo "Cordova can only run in Xcode version $XCODE_MIN_VERSION or greater."
+ exit 1
+fi
+
+LIB_PATH=$( cd "$( dirname "$0" )" && pwd -P)
+CORDOVA_PATH="$(dirname "$LIB_PATH")"
+PROJECT_PATH="$(dirname "$CORDOVA_PATH")"
+XCODEPROJ=$( ls "$PROJECT_PATH" | grep .xcodeproj )
+PROJECT_NAME=$(basename "$XCODEPROJ" .xcodeproj)
+
+APP_PATH="$PROJECT_PATH/build/$PROJECT_NAME.app"
+
+if [ ! -d "$APP_PATH" ]; then
+ echo "Project '$APP_PATH' is not built."
+ exit 1
+fi
+
+if [ ! -d "$APP_PATH" ]; then
+ echo "$APP_PATH not found to emulate."
+ exit 1
+fi
+
+IOS_SIM_MIN_VERSION="1.5"
+IOS_SIM_LOCATION=$(which xcodebuild)
+if [ $? != 0 ]; then
+ echo -e "\033[31mError: ios-sim was not found. Please download, build and install version $IOS_SIM_MIN_VERSION or greater from https://github.com/phonegap/ios-sim into your path. Or 'brew install ios-sim' using homebrew: http://mxcl.github.com/homebrew/\033[m"; exit 1;
+ exit 1
+fi
+
+IOS_SIM_VERSION=$(ios-sim --version)
+
+if [[ "$IOS_SIM_VERSION" < "$IOS_SIM_MIN_VERSION" ]]; then
+ echo "Cordova needs ios-sim version $IOS_SIM_MIN_VERSION or greater, you have version $IOS_SIM_VERSION."
+ exit 1
+fi
+
+# launch using ios-sim
+ios-sim launch "$APP_PATH" --stderr "$CORDOVA_PATH/console.log" --stdout "$CORDOVA_PATH/console.log" $TARGET_FLAG --exit
+
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/lib/list-devices
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/lib/list-devices b/lib/cordova-ios/bin/templates/project/cordova/lib/list-devices
new file mode 100755
index 0000000..80dd3b8
--- /dev/null
+++ b/lib/cordova-ios/bin/templates/project/cordova/lib/list-devices
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+system_profiler SPUSBDataType | sed -n -e '/iPad/,/Serial/p' | grep "Serial Number:" | awk -F ": " '{print $2 " iPad"}'
+system_profiler SPUSBDataType | sed -n -e '/iPhone/,/Serial/p' | grep "Serial Number:" | awk -F ": " '{print $2 " iPhone"}'
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/lib/list-emulator-images
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/lib/list-emulator-images b/lib/cordova-ios/bin/templates/project/cordova/lib/list-emulator-images
new file mode 100755
index 0000000..4df5315
--- /dev/null
+++ b/lib/cordova-ios/bin/templates/project/cordova/lib/list-emulator-images
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# Valid values for "--target" (case insensitive):
+# "iPhone (Retina 3.5-inch)" (default)
+# "iPhone (Retina 4-inch)"
+# "iPhone"
+# "iPad"
+# "iPad (Retina)"
+
+set -e
+
+echo \""iPhone (Retina 3.5-inch)"\"
+echo \""iPhone (Retina 4-inch)"\"
+echo \""iPhone"\"
+echo \""iPad"\"
+echo \""iPad (Retina)"\"
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/lib/list-started-emulators
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/lib/list-started-emulators b/lib/cordova-ios/bin/templates/project/cordova/lib/list-started-emulators
new file mode 100755
index 0000000..cfafe67
--- /dev/null
+++ b/lib/cordova-ios/bin/templates/project/cordova/lib/list-started-emulators
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# Valid values for "--target" (case insensitive):
+# "iPhone (Retina 3.5-inch)" (default)
+# "iPhone (Retina 4-inch)"
+# "iPhone"
+# "iPad"
+# "iPad (Retina)"
+
+set -e
+
+SIM_RUNNING=$(ps aux | grep -i "[i]Phone Simulator" | wc -l)
+if [ $SIM_RUNNING == 0 ]; then
+ echo "No emulators are running."
+ exit 1
+fi
+
+SIM_ID=`defaults read com.apple.iphonesimulator "SimulateDevice"`
+echo \"$SIM_ID\"
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/lib/sim.applescript
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/lib/sim.applescript b/lib/cordova-ios/bin/templates/project/cordova/lib/sim.applescript
new file mode 100755
index 0000000..5f6b152
--- /dev/null
+++ b/lib/cordova-ios/bin/templates/project/cordova/lib/sim.applescript
@@ -0,0 +1,14 @@
+tell application "System Events"
+ set UI elements enabled to true
+end tell
+
+tell application "iPhone Simulator"
+ activate
+end tell
+
+tell application "System Events"
+ tell process "iPhone Simulator"
+ click menu item "$DEVICE_NAME" of menu 1 of menu item "Device" of menu 1 of menu bar item "Hardware" of menu bar 1
+ click menu item "Home" of menu 1 of menu bar item "Hardware" of menu bar 1
+ end tell
+end tell
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/lib/start-emulator
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/lib/start-emulator b/lib/cordova-ios/bin/templates/project/cordova/lib/start-emulator
new file mode 100755
index 0000000..d7f6cb3
--- /dev/null
+++ b/lib/cordova-ios/bin/templates/project/cordova/lib/start-emulator
@@ -0,0 +1,35 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# Valid values for "--target" (case insensitive):
+# "iPhone (Retina 3.5-inch)" (default)
+# "iPhone (Retina 4-inch)"
+# "iPhone"
+# "iPad"
+# "iPad (Retina)"
+
+set -e
+
+
+DEFAULT_TARGET="iPhone (Retina 3.5-inch)"
+TARGET=${1:-$DEFAULT_TARGET}
+LIB_PATH=$( cd "$( dirname "$0" )" && pwd -P)
+
+SCPT=`sed -e "s/\\$DEVICE_NAME/$TARGET/g" $LIB_PATH/sim.applescript`
+osascript -e "$SCPT"
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/release
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/release b/lib/cordova-ios/bin/templates/project/cordova/release
deleted file mode 100755
index 7263934..0000000
--- a/lib/cordova-ios/bin/templates/project/cordova/release
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/bin/bash
-
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-#
-# compile and launch a Cordova/iOS project to the simulator
-#
-
-set -e
-
-XCODE_VER=$(xcodebuild -version | head -n 1 | sed -e 's/Xcode //')
-XCODE_MIN_VERSION="4.5"
-
-if [[ "$XCODE_VER" < "$XCODE_MIN_VERSION" ]]; then
- echo "Cordova can only run in Xcode version $XCODE_MIN_VERSION or greater."
- exit 1
-fi
-
-CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd -P)
-PROJECT_PATH="$(dirname "$CORDOVA_PATH")"
-XCODEPROJ=$( ls "$PROJECT_PATH" | grep .xcodeproj )
-PROJECT_NAME=$(basename "$XCODEPROJ" .xcodeproj)
-
-cd "$PROJECT_PATH"
-
-APP=build/$PROJECT_NAME.app
-SDK=`xcodebuild -showsdks | grep Sim | tail -1 | awk '{print $6}'`
-
-xcodebuild -project $PROJECT_NAME.xcodeproj -arch i386 -target $PROJECT_NAME -configuration Release -sdk $SDK clean build VALID_ARCHS="i386" CONFIGURATION_BUILD_DIR="$PROJECT_PATH/build"
-
-
-
-
-
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/run
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/run b/lib/cordova-ios/bin/templates/project/cordova/run
index ef7198e..da0916c 100755
--- a/lib/cordova-ios/bin/templates/project/cordova/run
+++ b/lib/cordova-ios/bin/templates/project/cordova/run
@@ -1,4 +1,4 @@
-#! /bin/sh
+#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
@@ -17,9 +17,79 @@
# specific language governing permissions and limitations
# under the License.
#
+# Valid values for "--target" (case insensitive):
+# "iPhone (Retina 3.5-inch)" (default)
+# "iPhone (Retina 4-inch)"
+# "iPhone"
+# "iPad"
+# "iPad (Retina)"
set -e
+OPTION_RESULT=()
+TARGET="iPhone (Retina 3.5-inch)"
+TARGET_FLAG='--family iphone --retina'
+
+# separates "key=value", sets an array with 0th index as key, 1st index as value
+_parseOption()
+{
+ local ARG=$@
+ OIFS=$IFS
+ IFS='='
+
+ OPTION_RESULT=()
+ for i in ${ARG[@]}
+ do
+ OPTION_RESULT+=($i)
+ done
+
+ IFS=$OIFS
+}
+
+# parses key=value arguments
+_parseArgs()
+{
+ for arg in "$@"
+ do
+ _parseOption ${arg}
+ case "${OPTION_RESULT[0]}" in
+ "--target")
+ TARGET=${OPTION_RESULT[1]}
+ ;;
+ esac
+ done
+}
+
+_parseArgs "$@"
+
+# "iPhone (Retina 3.5-inch)" -> --family iphone --retina
+# "iPhone (Retina 4-inch)" -> --family iphone --retina --tall
+# "iPhone" -> --family iphone
+# "iPad" -> --family ipad
+# "iPad (Retina)" -> --family ipad --retina
+
+# lowercase the target string
+TARGET_LC=`echo $TARGET | tr '[:upper:]' '[:lower:]'`
+
+# remember the comparison is lowercase
+case "$TARGET_LC" in
+ "iphone (retina 3.5-inch)")
+ TARGET_FLAG="--family iphone --retina"
+ ;;
+ "iphone (retina 4-inch)")
+ TARGET_FLAG="--family iphone --retina --tall"
+ ;;
+ "iphone")
+ TARGET_FLAG="--family iphone"
+ ;;
+ "ipad")
+ TARGET_FLAG="--family ipad"
+ ;;
+ "ipad (retina)")
+ TARGET_FLAG="--family ipad --retina"
+ ;;
+esac
+
XCODE_VER=$(xcodebuild -version | head -n 1 | sed -e 's/Xcode //')
XCODE_MIN_VERSION="4.5"
@@ -33,11 +103,7 @@ PROJECT_PATH="$(dirname "$CORDOVA_PATH")"
XCODEPROJ=$( ls "$PROJECT_PATH" | grep .xcodeproj )
PROJECT_NAME=$(basename "$XCODEPROJ" .xcodeproj)
-APP_PATH=$1
-
-if [ $# -lt 1 ]; then
- APP_PATH="$PROJECT_PATH/build/$PROJECT_NAME.app"
-fi
+APP_PATH="$PROJECT_PATH/build/$PROJECT_NAME.app"
if [ ! -d "$APP_PATH" ]; then
echo "Project '$APP_PATH' is not built. Building."
@@ -49,10 +115,19 @@ if [ ! -d "$APP_PATH" ]; then
exit 1
fi
-# launch using ios-sim
-if which ios-sim >/dev/null; then
- ios-sim launch "$APP_PATH" --stderr "$CORDOVA_PATH/console.log" --stdout "$CORDOVA_PATH/console.log" &
-else
- echo -e '\033[31mError: ios-sim was not found. Please download, build and install version 1.4 or greater from https://github.com/phonegap/ios-sim into your path. Or "brew install ios-sim" using homebrew: http://mxcl.github.com/homebrew/\033[m'; exit 1;
+IOS_SIM_MIN_VERSION="1.5"
+IOS_SIM_LOCATION=$(which ios-sim)
+if [ $? != 0 ]; then
+ echo -e "\033[31mError: ios-sim was not found. Please download, build and install version $IOS_SIM_MIN_VERSION or greater from https://github.com/phonegap/ios-sim into your path. Or 'brew install ios-sim' using homebrew: http://mxcl.github.com/homebrew/\033[m"; exit 1;
+ exit 1
fi
+IOS_SIM_VERSION=$(ios-sim --version)
+
+if [[ "$IOS_SIM_VERSION" < "$IOS_SIM_MIN_VERSION" ]]; then
+ echo "Cordova needs ios-sim version $IOS_SIM_MIN_VERSION or greater, you have version $IOS_SIM_VERSION."
+ exit 1
+fi
+
+# launch using ios-sim
+ios-sim launch "$APP_PATH" --stderr "$CORDOVA_PATH/console.log" --stdout "$CORDOVA_PATH/console.log" $TARGET_FLAG &
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/cordova/version
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/cordova/version b/lib/cordova-ios/bin/templates/project/cordova/version
new file mode 100755
index 0000000..f466559
--- /dev/null
+++ b/lib/cordova-ios/bin/templates/project/cordova/version
@@ -0,0 +1,40 @@
+#!/bin/bash
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+#
+# Returns the VERSION of CordovaLib used.
+# Note: it does not work if the --shared option was used to create the project.
+#
+
+set -e
+
+CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd -P)
+PROJECT_PATH="$(dirname "$CORDOVA_PATH")"
+
+VERSION_FILE_PATH="$PROJECT_PATH/CordovaLib/VERSION"
+VERSION=$(<$VERSION_FILE_PATH)
+
+if [ -f "$VERSION_FILE_PATH" ]; then
+ echo $VERSION
+else
+ echo "The file \"$VERSION_FILE_PATH\" does not exist."
+ exit 1
+fi
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/bin/templates/project/www/index.html
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/bin/templates/project/www/index.html b/lib/cordova-ios/bin/templates/project/www/index.html
index 8bc9055..e84fbd7 100644
--- a/lib/cordova-ios/bin/templates/project/www/index.html
+++ b/lib/cordova-ios/bin/templates/project/www/index.html
@@ -33,7 +33,7 @@
<p class="event received">Device is Ready</p>
</div>
</div>
- <script type="text/javascript" src="cordova.ios.js"></script>
+ <script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/platforms.js
----------------------------------------------------------------------
diff --git a/platforms.js b/platforms.js
index 542f734..c49c797 100644
--- a/platforms.js
+++ b/platforms.js
@@ -17,4 +17,4 @@
under the License.
*/
-module.exports = ['ios', 'android', 'blackberry', 'wp7', 'wp8'];
+module.exports = ['ios', 'android', /*'blackberry',*/ 'wp7', 'wp8'];
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/spec/cordova-cli/platform.spec.js
----------------------------------------------------------------------
diff --git a/spec/cordova-cli/platform.spec.js b/spec/cordova-cli/platform.spec.js
index b791bd9..ab76205 100644
--- a/spec/cordova-cli/platform.spec.js
+++ b/spec/cordova-cli/platform.spec.js
@@ -83,7 +83,8 @@ describe('platform command', function() {
expect(cordova.platform('list').length).toEqual(0);
});
- it('should list out added platforms in a project', function() {
+ // TODO: false test as environment where these tests are running may or may not have the specific platform's project built for it. if user does not have the appropriate sdk installed, this will fail.
+ xit('should list out added platforms in a project', function() {
process.chdir(tempDir);
cordova.create(tempDir);
shell.cp('-Rf', path.join(cordova_project, 'platforms', 'android'), path.join(tempDir, 'platforms'));
@@ -221,7 +222,9 @@ describe('platform command', function() {
cordova.platform('remove', 'android');
expect(cordova.platform('ls').length).toEqual(num_platforms - 1);
});
- it('should be able to remove multiple platforms', function() {
+ // TODO: fails if environemtn not configured for the specified paltforms.
+ // need to rethink this.
+ xit('should be able to remove multiple platforms', function() {
cordova.platform('remove', ['android','blackberry']);
expect(cordova.platform('ls').length).toEqual(num_platforms - 2);
});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/spec/cordova-cli/plugin.spec.js
----------------------------------------------------------------------
diff --git a/spec/cordova-cli/plugin.spec.js b/spec/cordova-cli/plugin.spec.js
index bf97b58..b24580c 100644
--- a/spec/cordova-cli/plugin.spec.js
+++ b/spec/cordova-cli/plugin.spec.js
@@ -113,24 +113,6 @@ describe('plugin command', function() {
process.chdir(cwd);
});
describe('failure', function() {
- it('should throw if plugin is already added to project', function() {
- process.chdir(cordova_project);
- var cb = jasmine.createSpy();
- this.after(function() {
- process.chdir(cordova_project);
- cordova.plugin('rm', "test");
- process.chdir(cwd);
- });
- runs(function() {
- cordova.plugin('add', testPlugin, cb);
- });
- waitsFor(function() { return cb.wasCalled; }, 'frst add plugin');
- runs(function(){
- expect(function() {
- cordova.plugin('add', testPlugin);
- }).toThrow();
- });
- });
it('should throw if plugin does not have a plugin.xml', function() {
process.chdir(cordova_project);
this.after(function() {
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/spec/platform-script/android/android_parser.spec.js
----------------------------------------------------------------------
diff --git a/spec/platform-script/android/android_parser.spec.js b/spec/platform-script/android/android_parser.spec.js
index 83b13dd..c0f77c1 100644
--- a/spec/platform-script/android/android_parser.spec.js
+++ b/spec/platform-script/android/android_parser.spec.js
@@ -185,7 +185,7 @@ describe('android project parser', function() {
});
it('should write out android js to cordova.js', function() {
parser.update_www();
- expect(fs.readFileSync(path.join(android_project_path, 'assets', 'www', 'cordova.js'),'utf-8')).toBe(fs.readFileSync(path.join(util.libDirectory, 'cordova-android', 'framework', 'assets', 'js', 'cordova.android.js'), 'utf-8'));
+ expect(fs.readFileSync(path.join(android_project_path, 'assets', 'www', 'cordova.js'),'utf-8')).toBe(fs.readFileSync(path.join(util.libDirectory, 'cordova-android', 'framework', 'assets', 'www', 'cordova.js'), 'utf-8'));
});
});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/spec/platform-script/ios/ios_parser.spec.js
----------------------------------------------------------------------
diff --git a/spec/platform-script/ios/ios_parser.spec.js b/spec/platform-script/ios/ios_parser.spec.js
index 9112929..8598c3f 100644
--- a/spec/platform-script/ios/ios_parser.spec.js
+++ b/spec/platform-script/ios/ios_parser.spec.js
@@ -158,7 +158,7 @@ describe('ios project parser', function () {
});
it('should write out ios js to cordova.js', function () {
parser.update_www();
- expect(fs.readFileSync(path.join(ios_project_path, 'www', 'cordova.js'), 'utf-8')).toBe(fs.readFileSync(path.join(util.libDirectory, 'cordova-ios', 'CordovaLib', 'cordova.ios.js'), 'utf-8'));
+ expect(fs.readFileSync(path.join(ios_project_path, 'www', 'cordova.js'), 'utf-8')).toBe(fs.readFileSync(path.join(util.libDirectory, 'cordova-ios', 'CordovaLib', 'cordova.js'), 'utf-8'));
});
});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/src/plugin.js
----------------------------------------------------------------------
diff --git a/src/plugin.js b/src/plugin.js
index c275a55..caeb82c 100644
--- a/src/plugin.js
+++ b/src/plugin.js
@@ -86,7 +86,8 @@ module.exports = function plugin(command, targets, callback) {
platforms.forEach(function(platform) {
var platformRoot = path.join(projectRoot, 'platforms', platform);
var parser = new parsers[platform](platformRoot);
- plugman.install(platform, platformRoot,
+ // TODO: unify use of blackberry in cli vs blackberry10 in plugman
+ plugman.install((platform=='blackberry'?'blackberry10':platform), platformRoot,
path.basename(dir), pluginsDir, undefined, {}, parser.staging_dir());
});
[33/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java
new file mode 100644
index 0000000..eba887e
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java
@@ -0,0 +1,424 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.internal.Util;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.ProtocolException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.TreeMap;
+
+/**
+ * The HTTP status and unparsed header fields of a single HTTP message. Values
+ * are represented as uninterpreted strings; use {@link RequestHeaders} and
+ * {@link ResponseHeaders} for interpreted headers. This class maintains the
+ * order of the header fields within the HTTP message.
+ *
+ * <p>This class tracks fields line-by-line. A field with multiple comma-
+ * separated values on the same line will be treated as a field with a single
+ * value by this class. It is the caller's responsibility to detect and split
+ * on commas if their field permits multiple values. This simplifies use of
+ * single-valued fields whose values routinely contain commas, such as cookies
+ * or dates.
+ *
+ * <p>This class trims whitespace from values. It never returns values with
+ * leading or trailing whitespace.
+ */
+public final class RawHeaders {
+ private static final Comparator<String> FIELD_NAME_COMPARATOR = new Comparator<String>() {
+ // @FindBugsSuppressWarnings("ES_COMPARING_PARAMETER_STRING_WITH_EQ")
+ @Override public int compare(String a, String b) {
+ if (a == b) {
+ return 0;
+ } else if (a == null) {
+ return -1;
+ } else if (b == null) {
+ return 1;
+ } else {
+ return String.CASE_INSENSITIVE_ORDER.compare(a, b);
+ }
+ }
+ };
+
+ private final List<String> namesAndValues = new ArrayList<String>(20);
+ private String requestLine;
+ private String statusLine;
+ private int httpMinorVersion = 1;
+ private int responseCode = -1;
+ private String responseMessage;
+
+ public RawHeaders() {
+ }
+
+ public RawHeaders(RawHeaders copyFrom) {
+ namesAndValues.addAll(copyFrom.namesAndValues);
+ requestLine = copyFrom.requestLine;
+ statusLine = copyFrom.statusLine;
+ httpMinorVersion = copyFrom.httpMinorVersion;
+ responseCode = copyFrom.responseCode;
+ responseMessage = copyFrom.responseMessage;
+ }
+
+ /** Sets the request line (like "GET / HTTP/1.1"). */
+ public void setRequestLine(String requestLine) {
+ requestLine = requestLine.trim();
+ this.requestLine = requestLine;
+ }
+
+ /** Sets the response status line (like "HTTP/1.0 200 OK"). */
+ public void setStatusLine(String statusLine) throws IOException {
+ // H T T P / 1 . 1 2 0 0 T e m p o r a r y R e d i r e c t
+ // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
+ if (this.responseMessage != null) {
+ throw new IllegalStateException("statusLine is already set");
+ }
+ // We allow empty message without leading white space since some servers
+ // do not send the white space when the message is empty.
+ boolean hasMessage = statusLine.length() > 13;
+ if (!statusLine.startsWith("HTTP/1.")
+ || statusLine.length() < 12
+ || statusLine.charAt(8) != ' '
+ || (hasMessage && statusLine.charAt(12) != ' ')) {
+ throw new ProtocolException("Unexpected status line: " + statusLine);
+ }
+ int httpMinorVersion = statusLine.charAt(7) - '0';
+ if (httpMinorVersion < 0 || httpMinorVersion > 9) {
+ throw new ProtocolException("Unexpected status line: " + statusLine);
+ }
+ int responseCode;
+ try {
+ responseCode = Integer.parseInt(statusLine.substring(9, 12));
+ } catch (NumberFormatException e) {
+ throw new ProtocolException("Unexpected status line: " + statusLine);
+ }
+ this.responseMessage = hasMessage ? statusLine.substring(13) : "";
+ this.responseCode = responseCode;
+ this.statusLine = statusLine;
+ this.httpMinorVersion = httpMinorVersion;
+ }
+
+ public void computeResponseStatusLineFromSpdyHeaders() throws IOException {
+ String status = null;
+ String version = null;
+ for (int i = 0; i < namesAndValues.size(); i += 2) {
+ String name = namesAndValues.get(i);
+ if (":status".equals(name)) {
+ status = namesAndValues.get(i + 1);
+ } else if (":version".equals(name)) {
+ version = namesAndValues.get(i + 1);
+ }
+ }
+ if (status == null || version == null) {
+ throw new ProtocolException("Expected ':status' and ':version' headers not present");
+ }
+ setStatusLine(version + " " + status);
+ }
+
+ /**
+ * @param method like "GET", "POST", "HEAD", etc.
+ * @param path like "/foo/bar.html"
+ * @param version like "HTTP/1.1"
+ * @param host like "www.android.com:1234"
+ * @param scheme like "https"
+ */
+ public void addSpdyRequestHeaders(String method, String path, String version, String host,
+ String scheme) {
+ // TODO: populate the statusLine for the client's benefit?
+ add(":method", method);
+ add(":scheme", scheme);
+ add(":path", path);
+ add(":version", version);
+ add(":host", host);
+ }
+
+ public String getStatusLine() {
+ return statusLine;
+ }
+
+ /**
+ * Returns the status line's HTTP minor version. This returns 0 for HTTP/1.0
+ * and 1 for HTTP/1.1. This returns 1 if the HTTP version is unknown.
+ */
+ public int getHttpMinorVersion() {
+ return httpMinorVersion != -1 ? httpMinorVersion : 1;
+ }
+
+ /** Returns the HTTP status code or -1 if it is unknown. */
+ public int getResponseCode() {
+ return responseCode;
+ }
+
+ /** Returns the HTTP status message or null if it is unknown. */
+ public String getResponseMessage() {
+ return responseMessage;
+ }
+
+ /**
+ * Add an HTTP header line containing a field name, a literal colon, and a
+ * value.
+ */
+ public void addLine(String line) {
+ int index = line.indexOf(":");
+ if (index == -1) {
+ addLenient("", line);
+ } else {
+ addLenient(line.substring(0, index), line.substring(index + 1));
+ }
+ }
+
+ /** Add a field with the specified value. */
+ public void add(String fieldName, String value) {
+ if (fieldName == null) throw new IllegalArgumentException("fieldname == null");
+ if (value == null) throw new IllegalArgumentException("value == null");
+ if (fieldName.length() == 0 || fieldName.indexOf('\0') != -1 || value.indexOf('\0') != -1) {
+ throw new IllegalArgumentException("Unexpected header: " + fieldName + ": " + value);
+ }
+ addLenient(fieldName, value);
+ }
+
+ /**
+ * Add a field with the specified value without any validation. Only
+ * appropriate for headers from the remote peer.
+ */
+ private void addLenient(String fieldName, String value) {
+ namesAndValues.add(fieldName);
+ namesAndValues.add(value.trim());
+ }
+
+ public void removeAll(String fieldName) {
+ for (int i = 0; i < namesAndValues.size(); i += 2) {
+ if (fieldName.equalsIgnoreCase(namesAndValues.get(i))) {
+ namesAndValues.remove(i); // field name
+ namesAndValues.remove(i); // value
+ }
+ }
+ }
+
+ public void addAll(String fieldName, List<String> headerFields) {
+ for (String value : headerFields) {
+ add(fieldName, value);
+ }
+ }
+
+ /**
+ * Set a field with the specified value. If the field is not found, it is
+ * added. If the field is found, the existing values are replaced.
+ */
+ public void set(String fieldName, String value) {
+ removeAll(fieldName);
+ add(fieldName, value);
+ }
+
+ /** Returns the number of field values. */
+ public int length() {
+ return namesAndValues.size() / 2;
+ }
+
+ /** Returns the field at {@code position} or null if that is out of range. */
+ public String getFieldName(int index) {
+ int fieldNameIndex = index * 2;
+ if (fieldNameIndex < 0 || fieldNameIndex >= namesAndValues.size()) {
+ return null;
+ }
+ return namesAndValues.get(fieldNameIndex);
+ }
+
+ /** Returns the value at {@code index} or null if that is out of range. */
+ public String getValue(int index) {
+ int valueIndex = index * 2 + 1;
+ if (valueIndex < 0 || valueIndex >= namesAndValues.size()) {
+ return null;
+ }
+ return namesAndValues.get(valueIndex);
+ }
+
+ /** Returns the last value corresponding to the specified field, or null. */
+ public String get(String fieldName) {
+ for (int i = namesAndValues.size() - 2; i >= 0; i -= 2) {
+ if (fieldName.equalsIgnoreCase(namesAndValues.get(i))) {
+ return namesAndValues.get(i + 1);
+ }
+ }
+ return null;
+ }
+
+ /** @param fieldNames a case-insensitive set of HTTP header field names. */
+ public RawHeaders getAll(Set<String> fieldNames) {
+ RawHeaders result = new RawHeaders();
+ for (int i = 0; i < namesAndValues.size(); i += 2) {
+ String fieldName = namesAndValues.get(i);
+ if (fieldNames.contains(fieldName)) {
+ result.add(fieldName, namesAndValues.get(i + 1));
+ }
+ }
+ return result;
+ }
+
+ /** Returns bytes of a request header for sending on an HTTP transport. */
+ public byte[] toBytes() throws UnsupportedEncodingException {
+ StringBuilder result = new StringBuilder(256);
+ result.append(requestLine).append("\r\n");
+ for (int i = 0; i < namesAndValues.size(); i += 2) {
+ result.append(namesAndValues.get(i))
+ .append(": ")
+ .append(namesAndValues.get(i + 1))
+ .append("\r\n");
+ }
+ result.append("\r\n");
+ return result.toString().getBytes("ISO-8859-1");
+ }
+
+ /** Parses bytes of a response header from an HTTP transport. */
+ public static RawHeaders fromBytes(InputStream in) throws IOException {
+ RawHeaders headers;
+ do {
+ headers = new RawHeaders();
+ headers.setStatusLine(Util.readAsciiLine(in));
+ readHeaders(in, headers);
+ } while (headers.getResponseCode() == HttpEngine.HTTP_CONTINUE);
+ return headers;
+ }
+
+ /** Reads headers or trailers into {@code out}. */
+ public static void readHeaders(InputStream in, RawHeaders out) throws IOException {
+ // parse the result headers until the first blank line
+ String line;
+ while ((line = Util.readAsciiLine(in)).length() != 0) {
+ out.addLine(line);
+ }
+ }
+
+ /**
+ * Returns an immutable map containing each field to its list of values. The
+ * status line is mapped to null.
+ */
+ public Map<String, List<String>> toMultimap(boolean response) {
+ Map<String, List<String>> result = new TreeMap<String, List<String>>(FIELD_NAME_COMPARATOR);
+ for (int i = 0; i < namesAndValues.size(); i += 2) {
+ String fieldName = namesAndValues.get(i);
+ String value = namesAndValues.get(i + 1);
+
+ List<String> allValues = new ArrayList<String>();
+ List<String> otherValues = result.get(fieldName);
+ if (otherValues != null) {
+ allValues.addAll(otherValues);
+ }
+ allValues.add(value);
+ result.put(fieldName, Collections.unmodifiableList(allValues));
+ }
+ if (response && statusLine != null) {
+ result.put(null, Collections.unmodifiableList(Collections.singletonList(statusLine)));
+ } else if (requestLine != null) {
+ result.put(null, Collections.unmodifiableList(Collections.singletonList(requestLine)));
+ }
+ return Collections.unmodifiableMap(result);
+ }
+
+ /**
+ * Creates a new instance from the given map of fields to values. If
+ * present, the null field's last element will be used to set the status
+ * line.
+ */
+ public static RawHeaders fromMultimap(Map<String, List<String>> map, boolean response)
+ throws IOException {
+ if (!response) throw new UnsupportedOperationException();
+ RawHeaders result = new RawHeaders();
+ for (Entry<String, List<String>> entry : map.entrySet()) {
+ String fieldName = entry.getKey();
+ List<String> values = entry.getValue();
+ if (fieldName != null) {
+ for (String value : values) {
+ result.addLenient(fieldName, value);
+ }
+ } else if (!values.isEmpty()) {
+ result.setStatusLine(values.get(values.size() - 1));
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Returns a list of alternating names and values. Names are all lower case.
+ * No names are repeated. If any name has multiple values, they are
+ * concatenated using "\0" as a delimiter.
+ */
+ public List<String> toNameValueBlock() {
+ Set<String> names = new HashSet<String>();
+ List<String> result = new ArrayList<String>();
+ for (int i = 0; i < namesAndValues.size(); i += 2) {
+ String name = namesAndValues.get(i).toLowerCase(Locale.US);
+ String value = namesAndValues.get(i + 1);
+
+ // Drop headers that are forbidden when layering HTTP over SPDY.
+ if (name.equals("connection")
+ || name.equals("host")
+ || name.equals("keep-alive")
+ || name.equals("proxy-connection")
+ || name.equals("transfer-encoding")) {
+ continue;
+ }
+
+ // If we haven't seen this name before, add the pair to the end of the list...
+ if (names.add(name)) {
+ result.add(name);
+ result.add(value);
+ continue;
+ }
+
+ // ...otherwise concatenate the existing values and this value.
+ for (int j = 0; j < result.size(); j += 2) {
+ if (name.equals(result.get(j))) {
+ result.set(j + 1, result.get(j + 1) + "\0" + value);
+ break;
+ }
+ }
+ }
+ return result;
+ }
+
+ public static RawHeaders fromNameValueBlock(List<String> nameValueBlock) {
+ if (nameValueBlock.size() % 2 != 0) {
+ throw new IllegalArgumentException("Unexpected name value block: " + nameValueBlock);
+ }
+ RawHeaders result = new RawHeaders();
+ for (int i = 0; i < nameValueBlock.size(); i += 2) {
+ String name = nameValueBlock.get(i);
+ String values = nameValueBlock.get(i + 1);
+ for (int start = 0; start < values.length(); ) {
+ int end = values.indexOf('\0', start);
+ if (end == -1) {
+ end = values.length();
+ }
+ result.namesAndValues.add(name);
+ result.namesAndValues.add(values.substring(start, end));
+ start = end + 1;
+ }
+ }
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java
new file mode 100644
index 0000000..5ec4fcc
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java
@@ -0,0 +1,290 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import java.net.URI;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+/** Parsed HTTP request headers. */
+public final class RequestHeaders {
+ private final URI uri;
+ private final RawHeaders headers;
+
+ /** Don't use a cache to satisfy this request. */
+ private boolean noCache;
+ private int maxAgeSeconds = -1;
+ private int maxStaleSeconds = -1;
+ private int minFreshSeconds = -1;
+
+ /**
+ * This field's name "only-if-cached" is misleading. It actually means "do
+ * not use the network". It is set by a client who only wants to make a
+ * request if it can be fully satisfied by the cache. Cached responses that
+ * would require validation (ie. conditional gets) are not permitted if this
+ * header is set.
+ */
+ private boolean onlyIfCached;
+
+ /**
+ * True if the request contains an authorization field. Although this isn't
+ * necessarily a shared cache, it follows the spec's strict requirements for
+ * shared caches.
+ */
+ private boolean hasAuthorization;
+
+ private int contentLength = -1;
+ private String transferEncoding;
+ private String userAgent;
+ private String host;
+ private String connection;
+ private String acceptEncoding;
+ private String contentType;
+ private String ifModifiedSince;
+ private String ifNoneMatch;
+ private String proxyAuthorization;
+
+ public RequestHeaders(URI uri, RawHeaders headers) {
+ this.uri = uri;
+ this.headers = headers;
+
+ HeaderParser.CacheControlHandler handler = new HeaderParser.CacheControlHandler() {
+ @Override public void handle(String directive, String parameter) {
+ if ("no-cache".equalsIgnoreCase(directive)) {
+ noCache = true;
+ } else if ("max-age".equalsIgnoreCase(directive)) {
+ maxAgeSeconds = HeaderParser.parseSeconds(parameter);
+ } else if ("max-stale".equalsIgnoreCase(directive)) {
+ maxStaleSeconds = HeaderParser.parseSeconds(parameter);
+ } else if ("min-fresh".equalsIgnoreCase(directive)) {
+ minFreshSeconds = HeaderParser.parseSeconds(parameter);
+ } else if ("only-if-cached".equalsIgnoreCase(directive)) {
+ onlyIfCached = true;
+ }
+ }
+ };
+
+ for (int i = 0; i < headers.length(); i++) {
+ String fieldName = headers.getFieldName(i);
+ String value = headers.getValue(i);
+ if ("Cache-Control".equalsIgnoreCase(fieldName)) {
+ HeaderParser.parseCacheControl(value, handler);
+ } else if ("Pragma".equalsIgnoreCase(fieldName)) {
+ if ("no-cache".equalsIgnoreCase(value)) {
+ noCache = true;
+ }
+ } else if ("If-None-Match".equalsIgnoreCase(fieldName)) {
+ ifNoneMatch = value;
+ } else if ("If-Modified-Since".equalsIgnoreCase(fieldName)) {
+ ifModifiedSince = value;
+ } else if ("Authorization".equalsIgnoreCase(fieldName)) {
+ hasAuthorization = true;
+ } else if ("Content-Length".equalsIgnoreCase(fieldName)) {
+ try {
+ contentLength = Integer.parseInt(value);
+ } catch (NumberFormatException ignored) {
+ }
+ } else if ("Transfer-Encoding".equalsIgnoreCase(fieldName)) {
+ transferEncoding = value;
+ } else if ("User-Agent".equalsIgnoreCase(fieldName)) {
+ userAgent = value;
+ } else if ("Host".equalsIgnoreCase(fieldName)) {
+ host = value;
+ } else if ("Connection".equalsIgnoreCase(fieldName)) {
+ connection = value;
+ } else if ("Accept-Encoding".equalsIgnoreCase(fieldName)) {
+ acceptEncoding = value;
+ } else if ("Content-Type".equalsIgnoreCase(fieldName)) {
+ contentType = value;
+ } else if ("Proxy-Authorization".equalsIgnoreCase(fieldName)) {
+ proxyAuthorization = value;
+ }
+ }
+ }
+
+ public boolean isChunked() {
+ return "chunked".equalsIgnoreCase(transferEncoding);
+ }
+
+ public boolean hasConnectionClose() {
+ return "close".equalsIgnoreCase(connection);
+ }
+
+ public URI getUri() {
+ return uri;
+ }
+
+ public RawHeaders getHeaders() {
+ return headers;
+ }
+
+ public boolean isNoCache() {
+ return noCache;
+ }
+
+ public int getMaxAgeSeconds() {
+ return maxAgeSeconds;
+ }
+
+ public int getMaxStaleSeconds() {
+ return maxStaleSeconds;
+ }
+
+ public int getMinFreshSeconds() {
+ return minFreshSeconds;
+ }
+
+ public boolean isOnlyIfCached() {
+ return onlyIfCached;
+ }
+
+ public boolean hasAuthorization() {
+ return hasAuthorization;
+ }
+
+ public int getContentLength() {
+ return contentLength;
+ }
+
+ public String getTransferEncoding() {
+ return transferEncoding;
+ }
+
+ public String getUserAgent() {
+ return userAgent;
+ }
+
+ public String getHost() {
+ return host;
+ }
+
+ public String getConnection() {
+ return connection;
+ }
+
+ public String getAcceptEncoding() {
+ return acceptEncoding;
+ }
+
+ public String getContentType() {
+ return contentType;
+ }
+
+ public String getIfModifiedSince() {
+ return ifModifiedSince;
+ }
+
+ public String getIfNoneMatch() {
+ return ifNoneMatch;
+ }
+
+ public String getProxyAuthorization() {
+ return proxyAuthorization;
+ }
+
+ public void setChunked() {
+ if (this.transferEncoding != null) {
+ headers.removeAll("Transfer-Encoding");
+ }
+ headers.add("Transfer-Encoding", "chunked");
+ this.transferEncoding = "chunked";
+ }
+
+ public void setContentLength(int contentLength) {
+ if (this.contentLength != -1) {
+ headers.removeAll("Content-Length");
+ }
+ headers.add("Content-Length", Integer.toString(contentLength));
+ this.contentLength = contentLength;
+ }
+
+ public void setUserAgent(String userAgent) {
+ if (this.userAgent != null) {
+ headers.removeAll("User-Agent");
+ }
+ headers.add("User-Agent", userAgent);
+ this.userAgent = userAgent;
+ }
+
+ public void setHost(String host) {
+ if (this.host != null) {
+ headers.removeAll("Host");
+ }
+ headers.add("Host", host);
+ this.host = host;
+ }
+
+ public void setConnection(String connection) {
+ if (this.connection != null) {
+ headers.removeAll("Connection");
+ }
+ headers.add("Connection", connection);
+ this.connection = connection;
+ }
+
+ public void setAcceptEncoding(String acceptEncoding) {
+ if (this.acceptEncoding != null) {
+ headers.removeAll("Accept-Encoding");
+ }
+ headers.add("Accept-Encoding", acceptEncoding);
+ this.acceptEncoding = acceptEncoding;
+ }
+
+ public void setContentType(String contentType) {
+ if (this.contentType != null) {
+ headers.removeAll("Content-Type");
+ }
+ headers.add("Content-Type", contentType);
+ this.contentType = contentType;
+ }
+
+ public void setIfModifiedSince(Date date) {
+ if (ifModifiedSince != null) {
+ headers.removeAll("If-Modified-Since");
+ }
+ String formattedDate = HttpDate.format(date);
+ headers.add("If-Modified-Since", formattedDate);
+ ifModifiedSince = formattedDate;
+ }
+
+ public void setIfNoneMatch(String ifNoneMatch) {
+ if (this.ifNoneMatch != null) {
+ headers.removeAll("If-None-Match");
+ }
+ headers.add("If-None-Match", ifNoneMatch);
+ this.ifNoneMatch = ifNoneMatch;
+ }
+
+ /**
+ * Returns true if the request contains conditions that save the server from
+ * sending a response that the client has locally. When the caller adds
+ * conditions, this cache won't participate in the request.
+ */
+ public boolean hasConditions() {
+ return ifModifiedSince != null || ifNoneMatch != null;
+ }
+
+ public void addCookies(Map<String, List<String>> allCookieHeaders) {
+ for (Map.Entry<String, List<String>> entry : allCookieHeaders.entrySet()) {
+ String key = entry.getKey();
+ if ("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key)) {
+ headers.addAll(key, entry.getValue());
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/ResponseHeaders.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/ResponseHeaders.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/ResponseHeaders.java
new file mode 100644
index 0000000..2ab564d
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/ResponseHeaders.java
@@ -0,0 +1,497 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.ResponseSource;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.TimeUnit;
+
+import static com.squareup.okhttp.internal.Util.equal;
+
+/** Parsed HTTP response headers. */
+public final class ResponseHeaders {
+
+ /** HTTP header name for the local time when the request was sent. */
+ private static final String SENT_MILLIS = "X-Android-Sent-Millis";
+
+ /** HTTP header name for the local time when the response was received. */
+ private static final String RECEIVED_MILLIS = "X-Android-Received-Millis";
+
+ /** HTTP synthetic header with the response source. */
+ static final String RESPONSE_SOURCE = "X-Android-Response-Source";
+
+ private final URI uri;
+ private final RawHeaders headers;
+
+ /** The server's time when this response was served, if known. */
+ private Date servedDate;
+
+ /** The last modified date of the response, if known. */
+ private Date lastModified;
+
+ /**
+ * The expiration date of the response, if known. If both this field and the
+ * max age are set, the max age is preferred.
+ */
+ private Date expires;
+
+ /**
+ * Extension header set by HttpURLConnectionImpl specifying the timestamp
+ * when the HTTP request was first initiated.
+ */
+ private long sentRequestMillis;
+
+ /**
+ * Extension header set by HttpURLConnectionImpl specifying the timestamp
+ * when the HTTP response was first received.
+ */
+ private long receivedResponseMillis;
+
+ /**
+ * In the response, this field's name "no-cache" is misleading. It doesn't
+ * prevent us from caching the response; it only means we have to validate
+ * the response with the origin server before returning it. We can do this
+ * with a conditional get.
+ */
+ private boolean noCache;
+
+ /** If true, this response should not be cached. */
+ private boolean noStore;
+
+ /**
+ * The duration past the response's served date that it can be served
+ * without validation.
+ */
+ private int maxAgeSeconds = -1;
+
+ /**
+ * The "s-maxage" directive is the max age for shared caches. Not to be
+ * confused with "max-age" for non-shared caches, As in Firefox and Chrome,
+ * this directive is not honored by this cache.
+ */
+ private int sMaxAgeSeconds = -1;
+
+ /**
+ * This request header field's name "only-if-cached" is misleading. It
+ * actually means "do not use the network". It is set by a client who only
+ * wants to make a request if it can be fully satisfied by the cache.
+ * Cached responses that would require validation (ie. conditional gets) are
+ * not permitted if this header is set.
+ */
+ private boolean isPublic;
+ private boolean mustRevalidate;
+ private String etag;
+ private int ageSeconds = -1;
+
+ /** Case-insensitive set of field names. */
+ private Set<String> varyFields = Collections.emptySet();
+
+ private String contentEncoding;
+ private String transferEncoding;
+ private int contentLength = -1;
+ private String connection;
+
+ public ResponseHeaders(URI uri, RawHeaders headers) {
+ this.uri = uri;
+ this.headers = headers;
+
+ HeaderParser.CacheControlHandler handler = new HeaderParser.CacheControlHandler() {
+ @Override public void handle(String directive, String parameter) {
+ if ("no-cache".equalsIgnoreCase(directive)) {
+ noCache = true;
+ } else if ("no-store".equalsIgnoreCase(directive)) {
+ noStore = true;
+ } else if ("max-age".equalsIgnoreCase(directive)) {
+ maxAgeSeconds = HeaderParser.parseSeconds(parameter);
+ } else if ("s-maxage".equalsIgnoreCase(directive)) {
+ sMaxAgeSeconds = HeaderParser.parseSeconds(parameter);
+ } else if ("public".equalsIgnoreCase(directive)) {
+ isPublic = true;
+ } else if ("must-revalidate".equalsIgnoreCase(directive)) {
+ mustRevalidate = true;
+ }
+ }
+ };
+
+ for (int i = 0; i < headers.length(); i++) {
+ String fieldName = headers.getFieldName(i);
+ String value = headers.getValue(i);
+ if ("Cache-Control".equalsIgnoreCase(fieldName)) {
+ HeaderParser.parseCacheControl(value, handler);
+ } else if ("Date".equalsIgnoreCase(fieldName)) {
+ servedDate = HttpDate.parse(value);
+ } else if ("Expires".equalsIgnoreCase(fieldName)) {
+ expires = HttpDate.parse(value);
+ } else if ("Last-Modified".equalsIgnoreCase(fieldName)) {
+ lastModified = HttpDate.parse(value);
+ } else if ("ETag".equalsIgnoreCase(fieldName)) {
+ etag = value;
+ } else if ("Pragma".equalsIgnoreCase(fieldName)) {
+ if ("no-cache".equalsIgnoreCase(value)) {
+ noCache = true;
+ }
+ } else if ("Age".equalsIgnoreCase(fieldName)) {
+ ageSeconds = HeaderParser.parseSeconds(value);
+ } else if ("Vary".equalsIgnoreCase(fieldName)) {
+ // Replace the immutable empty set with something we can mutate.
+ if (varyFields.isEmpty()) {
+ varyFields = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
+ }
+ for (String varyField : value.split(",")) {
+ varyFields.add(varyField.trim());
+ }
+ } else if ("Content-Encoding".equalsIgnoreCase(fieldName)) {
+ contentEncoding = value;
+ } else if ("Transfer-Encoding".equalsIgnoreCase(fieldName)) {
+ transferEncoding = value;
+ } else if ("Content-Length".equalsIgnoreCase(fieldName)) {
+ try {
+ contentLength = Integer.parseInt(value);
+ } catch (NumberFormatException ignored) {
+ }
+ } else if ("Connection".equalsIgnoreCase(fieldName)) {
+ connection = value;
+ } else if (SENT_MILLIS.equalsIgnoreCase(fieldName)) {
+ sentRequestMillis = Long.parseLong(value);
+ } else if (RECEIVED_MILLIS.equalsIgnoreCase(fieldName)) {
+ receivedResponseMillis = Long.parseLong(value);
+ }
+ }
+ }
+
+ public boolean isContentEncodingGzip() {
+ return "gzip".equalsIgnoreCase(contentEncoding);
+ }
+
+ public void stripContentEncoding() {
+ contentEncoding = null;
+ headers.removeAll("Content-Encoding");
+ }
+
+ public void stripContentLength() {
+ contentLength = -1;
+ headers.removeAll("Content-Length");
+ }
+
+ public boolean isChunked() {
+ return "chunked".equalsIgnoreCase(transferEncoding);
+ }
+
+ public boolean hasConnectionClose() {
+ return "close".equalsIgnoreCase(connection);
+ }
+
+ public URI getUri() {
+ return uri;
+ }
+
+ public RawHeaders getHeaders() {
+ return headers;
+ }
+
+ public Date getServedDate() {
+ return servedDate;
+ }
+
+ public Date getLastModified() {
+ return lastModified;
+ }
+
+ public Date getExpires() {
+ return expires;
+ }
+
+ public boolean isNoCache() {
+ return noCache;
+ }
+
+ public boolean isNoStore() {
+ return noStore;
+ }
+
+ public int getMaxAgeSeconds() {
+ return maxAgeSeconds;
+ }
+
+ public int getSMaxAgeSeconds() {
+ return sMaxAgeSeconds;
+ }
+
+ public boolean isPublic() {
+ return isPublic;
+ }
+
+ public boolean isMustRevalidate() {
+ return mustRevalidate;
+ }
+
+ public String getEtag() {
+ return etag;
+ }
+
+ public Set<String> getVaryFields() {
+ return varyFields;
+ }
+
+ public String getContentEncoding() {
+ return contentEncoding;
+ }
+
+ public int getContentLength() {
+ return contentLength;
+ }
+
+ public String getConnection() {
+ return connection;
+ }
+
+ public void setLocalTimestamps(long sentRequestMillis, long receivedResponseMillis) {
+ this.sentRequestMillis = sentRequestMillis;
+ headers.add(SENT_MILLIS, Long.toString(sentRequestMillis));
+ this.receivedResponseMillis = receivedResponseMillis;
+ headers.add(RECEIVED_MILLIS, Long.toString(receivedResponseMillis));
+ }
+
+ public void setResponseSource(ResponseSource responseSource) {
+ headers.set(RESPONSE_SOURCE, responseSource.toString() + " " + headers.getResponseCode());
+ }
+
+ /**
+ * Returns the current age of the response, in milliseconds. The calculation
+ * is specified by RFC 2616, 13.2.3 Age Calculations.
+ */
+ private long computeAge(long nowMillis) {
+ long apparentReceivedAge =
+ servedDate != null ? Math.max(0, receivedResponseMillis - servedDate.getTime()) : 0;
+ long receivedAge =
+ ageSeconds != -1 ? Math.max(apparentReceivedAge, TimeUnit.SECONDS.toMillis(ageSeconds))
+ : apparentReceivedAge;
+ long responseDuration = receivedResponseMillis - sentRequestMillis;
+ long residentDuration = nowMillis - receivedResponseMillis;
+ return receivedAge + responseDuration + residentDuration;
+ }
+
+ /**
+ * Returns the number of milliseconds that the response was fresh for,
+ * starting from the served date.
+ */
+ private long computeFreshnessLifetime() {
+ if (maxAgeSeconds != -1) {
+ return TimeUnit.SECONDS.toMillis(maxAgeSeconds);
+ } else if (expires != null) {
+ long servedMillis = servedDate != null ? servedDate.getTime() : receivedResponseMillis;
+ long delta = expires.getTime() - servedMillis;
+ return delta > 0 ? delta : 0;
+ } else if (lastModified != null && uri.getRawQuery() == null) {
+ // As recommended by the HTTP RFC and implemented in Firefox, the
+ // max age of a document should be defaulted to 10% of the
+ // document's age at the time it was served. Default expiration
+ // dates aren't used for URIs containing a query.
+ long servedMillis = servedDate != null ? servedDate.getTime() : sentRequestMillis;
+ long delta = servedMillis - lastModified.getTime();
+ return delta > 0 ? (delta / 10) : 0;
+ }
+ return 0;
+ }
+
+ /**
+ * Returns true if computeFreshnessLifetime used a heuristic. If we used a
+ * heuristic to serve a cached response older than 24 hours, we are required
+ * to attach a warning.
+ */
+ private boolean isFreshnessLifetimeHeuristic() {
+ return maxAgeSeconds == -1 && expires == null;
+ }
+
+ /**
+ * Returns true if this response can be stored to later serve another
+ * request.
+ */
+ public boolean isCacheable(RequestHeaders request) {
+ // Always go to network for uncacheable response codes (RFC 2616, 13.4),
+ // This implementation doesn't support caching partial content.
+ int responseCode = headers.getResponseCode();
+ if (responseCode != HttpURLConnection.HTTP_OK
+ && responseCode != HttpURLConnection.HTTP_NOT_AUTHORITATIVE
+ && responseCode != HttpURLConnection.HTTP_MULT_CHOICE
+ && responseCode != HttpURLConnection.HTTP_MOVED_PERM
+ && responseCode != HttpURLConnection.HTTP_GONE) {
+ return false;
+ }
+
+ // Responses to authorized requests aren't cacheable unless they include
+ // a 'public', 'must-revalidate' or 's-maxage' directive.
+ if (request.hasAuthorization() && !isPublic && !mustRevalidate && sMaxAgeSeconds == -1) {
+ return false;
+ }
+
+ if (noStore) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Returns true if a Vary header contains an asterisk. Such responses cannot
+ * be cached.
+ */
+ public boolean hasVaryAll() {
+ return varyFields.contains("*");
+ }
+
+ /**
+ * Returns true if none of the Vary headers on this response have changed
+ * between {@code cachedRequest} and {@code newRequest}.
+ */
+ public boolean varyMatches(Map<String, List<String>> cachedRequest,
+ Map<String, List<String>> newRequest) {
+ for (String field : varyFields) {
+ if (!equal(cachedRequest.get(field), newRequest.get(field))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /** Returns the source to satisfy {@code request} given this cached response. */
+ public ResponseSource chooseResponseSource(long nowMillis, RequestHeaders request) {
+ // If this response shouldn't have been stored, it should never be used
+ // as a response source. This check should be redundant as long as the
+ // persistence store is well-behaved and the rules are constant.
+ if (!isCacheable(request)) {
+ return ResponseSource.NETWORK;
+ }
+
+ if (request.isNoCache() || request.hasConditions()) {
+ return ResponseSource.NETWORK;
+ }
+
+ long ageMillis = computeAge(nowMillis);
+ long freshMillis = computeFreshnessLifetime();
+
+ if (request.getMaxAgeSeconds() != -1) {
+ freshMillis = Math.min(freshMillis, TimeUnit.SECONDS.toMillis(request.getMaxAgeSeconds()));
+ }
+
+ long minFreshMillis = 0;
+ if (request.getMinFreshSeconds() != -1) {
+ minFreshMillis = TimeUnit.SECONDS.toMillis(request.getMinFreshSeconds());
+ }
+
+ long maxStaleMillis = 0;
+ if (!mustRevalidate && request.getMaxStaleSeconds() != -1) {
+ maxStaleMillis = TimeUnit.SECONDS.toMillis(request.getMaxStaleSeconds());
+ }
+
+ if (!noCache && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
+ if (ageMillis + minFreshMillis >= freshMillis) {
+ headers.add("Warning", "110 HttpURLConnection \"Response is stale\"");
+ }
+ long oneDayMillis = 24 * 60 * 60 * 1000L;
+ if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
+ headers.add("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
+ }
+ return ResponseSource.CACHE;
+ }
+
+ if (lastModified != null) {
+ request.setIfModifiedSince(lastModified);
+ } else if (servedDate != null) {
+ request.setIfModifiedSince(servedDate);
+ }
+
+ if (etag != null) {
+ request.setIfNoneMatch(etag);
+ }
+
+ return request.hasConditions() ? ResponseSource.CONDITIONAL_CACHE : ResponseSource.NETWORK;
+ }
+
+ /**
+ * Returns true if this cached response should be used; false if the
+ * network response should be used.
+ */
+ public boolean validate(ResponseHeaders networkResponse) {
+ if (networkResponse.headers.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
+ return true;
+ }
+
+ // The HTTP spec says that if the network's response is older than our
+ // cached response, we may return the cache's response. Like Chrome (but
+ // unlike Firefox), this client prefers to return the newer response.
+ if (lastModified != null
+ && networkResponse.lastModified != null
+ && networkResponse.lastModified.getTime() < lastModified.getTime()) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Combines this cached header with a network header as defined by RFC 2616,
+ * 13.5.3.
+ */
+ public ResponseHeaders combine(ResponseHeaders network) throws IOException {
+ RawHeaders result = new RawHeaders();
+ result.setStatusLine(headers.getStatusLine());
+
+ for (int i = 0; i < headers.length(); i++) {
+ String fieldName = headers.getFieldName(i);
+ String value = headers.getValue(i);
+ if ("Warning".equals(fieldName) && value.startsWith("1")) {
+ continue; // drop 100-level freshness warnings
+ }
+ if (!isEndToEnd(fieldName) || network.headers.get(fieldName) == null) {
+ result.add(fieldName, value);
+ }
+ }
+
+ for (int i = 0; i < network.headers.length(); i++) {
+ String fieldName = network.headers.getFieldName(i);
+ if (isEndToEnd(fieldName)) {
+ result.add(fieldName, network.headers.getValue(i));
+ }
+ }
+
+ return new ResponseHeaders(uri, result);
+ }
+
+ /**
+ * Returns true if {@code fieldName} is an end-to-end HTTP header, as
+ * defined by RFC 2616, 13.5.1.
+ */
+ private static boolean isEndToEnd(String fieldName) {
+ return !"Connection".equalsIgnoreCase(fieldName)
+ && !"Keep-Alive".equalsIgnoreCase(fieldName)
+ && !"Proxy-Authenticate".equalsIgnoreCase(fieldName)
+ && !"Proxy-Authorization".equalsIgnoreCase(fieldName)
+ && !"TE".equalsIgnoreCase(fieldName)
+ && !"Trailers".equalsIgnoreCase(fieldName)
+ && !"Transfer-Encoding".equalsIgnoreCase(fieldName)
+ && !"Upgrade".equalsIgnoreCase(fieldName);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RetryableOutputStream.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RetryableOutputStream.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RetryableOutputStream.java
new file mode 100644
index 0000000..5eb6b76
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RetryableOutputStream.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.internal.AbstractOutputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.ProtocolException;
+
+import static com.squareup.okhttp.internal.Util.checkOffsetAndCount;
+
+/**
+ * An HTTP request body that's completely buffered in memory. This allows
+ * the post body to be transparently re-sent if the HTTP request must be
+ * sent multiple times.
+ */
+final class RetryableOutputStream extends AbstractOutputStream {
+ private final int limit;
+ private final ByteArrayOutputStream content;
+
+ public RetryableOutputStream(int limit) {
+ this.limit = limit;
+ this.content = new ByteArrayOutputStream(limit);
+ }
+
+ public RetryableOutputStream() {
+ this.limit = -1;
+ this.content = new ByteArrayOutputStream();
+ }
+
+ @Override public synchronized void close() throws IOException {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ if (content.size() < limit) {
+ throw new ProtocolException(
+ "content-length promised " + limit + " bytes, but received " + content.size());
+ }
+ }
+
+ @Override public synchronized void write(byte[] buffer, int offset, int count)
+ throws IOException {
+ checkNotClosed();
+ checkOffsetAndCount(buffer.length, offset, count);
+ if (limit != -1 && content.size() > limit - count) {
+ throw new ProtocolException("exceeded content-length limit of " + limit + " bytes");
+ }
+ content.write(buffer, offset, count);
+ }
+
+ public synchronized int contentLength() throws IOException {
+ close();
+ return content.size();
+ }
+
+ public void writeToSocket(OutputStream socketOut) throws IOException {
+ content.writeTo(socketOut);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RouteSelector.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RouteSelector.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RouteSelector.java
new file mode 100644
index 0000000..ce0a71d
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RouteSelector.java
@@ -0,0 +1,275 @@
+/*
+ * Copyright (C) 2012 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.Address;
+import com.squareup.okhttp.Connection;
+import com.squareup.okhttp.ConnectionPool;
+import com.squareup.okhttp.Route;
+import com.squareup.okhttp.internal.Dns;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.SocketAddress;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import javax.net.ssl.SSLHandshakeException;
+
+import static com.squareup.okhttp.internal.Util.getEffectivePort;
+
+/**
+ * Selects routes to connect to an origin server. Each connection requires a
+ * choice of proxy server, IP address, and TLS mode. Connections may also be
+ * recycled.
+ */
+public final class RouteSelector {
+ /** Uses {@link com.squareup.okhttp.internal.Platform#enableTlsExtensions}. */
+ private static final int TLS_MODE_MODERN = 1;
+ /** Uses {@link com.squareup.okhttp.internal.Platform#supportTlsIntolerantServer}. */
+ private static final int TLS_MODE_COMPATIBLE = 0;
+ /** No TLS mode. */
+ private static final int TLS_MODE_NULL = -1;
+
+ private final Address address;
+ private final URI uri;
+ private final ProxySelector proxySelector;
+ private final ConnectionPool pool;
+ private final Dns dns;
+ private final Set<Route> failedRoutes;
+
+ /* The most recently attempted route. */
+ private Proxy lastProxy;
+ private InetSocketAddress lastInetSocketAddress;
+
+ /* State for negotiating the next proxy to use. */
+ private boolean hasNextProxy;
+ private Proxy userSpecifiedProxy;
+ private Iterator<Proxy> proxySelectorProxies;
+
+ /* State for negotiating the next InetSocketAddress to use. */
+ private InetAddress[] socketAddresses;
+ private int nextSocketAddressIndex;
+ private int socketPort;
+
+ /* State for negotiating the next TLS configuration */
+ private int nextTlsMode = TLS_MODE_NULL;
+
+ /* State for negotiating failed routes */
+ private final List<Route> postponedRoutes;
+
+ public RouteSelector(Address address, URI uri, ProxySelector proxySelector, ConnectionPool pool,
+ Dns dns, Set<Route> failedRoutes) {
+ this.address = address;
+ this.uri = uri;
+ this.proxySelector = proxySelector;
+ this.pool = pool;
+ this.dns = dns;
+ this.failedRoutes = failedRoutes;
+ this.postponedRoutes = new LinkedList<Route>();
+
+ resetNextProxy(uri, address.getProxy());
+ }
+
+ /**
+ * Returns true if there's another route to attempt. Every address has at
+ * least one route.
+ */
+ public boolean hasNext() {
+ return hasNextTlsMode() || hasNextInetSocketAddress() || hasNextProxy() || hasNextPostponed();
+ }
+
+ /**
+ * Returns the next route address to attempt.
+ *
+ * @throws NoSuchElementException if there are no more routes to attempt.
+ */
+ public Connection next() throws IOException {
+ // Always prefer pooled connections over new connections.
+ Connection pooled = pool.get(address);
+ if (pooled != null) {
+ return pooled;
+ }
+
+ // Compute the next route to attempt.
+ if (!hasNextTlsMode()) {
+ if (!hasNextInetSocketAddress()) {
+ if (!hasNextProxy()) {
+ if (!hasNextPostponed()) {
+ throw new NoSuchElementException();
+ }
+ return new Connection(nextPostponed());
+ }
+ lastProxy = nextProxy();
+ resetNextInetSocketAddress(lastProxy);
+ }
+ lastInetSocketAddress = nextInetSocketAddress();
+ resetNextTlsMode();
+ }
+
+ boolean modernTls = nextTlsMode() == TLS_MODE_MODERN;
+ Route route = new Route(address, lastProxy, lastInetSocketAddress, modernTls);
+ if (failedRoutes.contains(route)) {
+ postponedRoutes.add(route);
+ // We will only recurse in order to skip previously failed routes. They will be
+ // tried last.
+ return next();
+ }
+
+ return new Connection(route);
+ }
+
+ /**
+ * Clients should invoke this method when they encounter a connectivity
+ * failure on a connection returned by this route selector.
+ */
+ public void connectFailed(Connection connection, IOException failure) {
+ Route failedRoute = connection.getRoute();
+ if (failedRoute.getProxy().type() != Proxy.Type.DIRECT && proxySelector != null) {
+ // Tell the proxy selector when we fail to connect on a fresh connection.
+ proxySelector.connectFailed(uri, failedRoute.getProxy().address(), failure);
+ }
+
+ failedRoutes.add(failedRoute);
+ if (!(failure instanceof SSLHandshakeException)) {
+ // If the problem was not related to SSL then it will also fail with
+ // a different Tls mode therefore we can be proactive about it.
+ failedRoutes.add(failedRoute.flipTlsMode());
+ }
+ }
+
+ /** Resets {@link #nextProxy} to the first option. */
+ private void resetNextProxy(URI uri, Proxy proxy) {
+ this.hasNextProxy = true; // This includes NO_PROXY!
+ if (proxy != null) {
+ this.userSpecifiedProxy = proxy;
+ } else {
+ List<Proxy> proxyList = proxySelector.select(uri);
+ if (proxyList != null) {
+ this.proxySelectorProxies = proxyList.iterator();
+ }
+ }
+ }
+
+ /** Returns true if there's another proxy to try. */
+ private boolean hasNextProxy() {
+ return hasNextProxy;
+ }
+
+ /** Returns the next proxy to try. May be PROXY.NO_PROXY but never null. */
+ private Proxy nextProxy() {
+ // If the user specifies a proxy, try that and only that.
+ if (userSpecifiedProxy != null) {
+ hasNextProxy = false;
+ return userSpecifiedProxy;
+ }
+
+ // Try each of the ProxySelector choices until one connection succeeds. If none succeed
+ // then we'll try a direct connection below.
+ if (proxySelectorProxies != null) {
+ while (proxySelectorProxies.hasNext()) {
+ Proxy candidate = proxySelectorProxies.next();
+ if (candidate.type() != Proxy.Type.DIRECT) {
+ return candidate;
+ }
+ }
+ }
+
+ // Finally try a direct connection.
+ hasNextProxy = false;
+ return Proxy.NO_PROXY;
+ }
+
+ /** Resets {@link #nextInetSocketAddress} to the first option. */
+ private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
+ socketAddresses = null; // Clear the addresses. Necessary if getAllByName() below throws!
+
+ String socketHost;
+ if (proxy.type() == Proxy.Type.DIRECT) {
+ socketHost = uri.getHost();
+ socketPort = getEffectivePort(uri);
+ } else {
+ SocketAddress proxyAddress = proxy.address();
+ if (!(proxyAddress instanceof InetSocketAddress)) {
+ throw new IllegalArgumentException(
+ "Proxy.address() is not an " + "InetSocketAddress: " + proxyAddress.getClass());
+ }
+ InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
+ socketHost = proxySocketAddress.getHostName();
+ socketPort = proxySocketAddress.getPort();
+ }
+
+ // Try each address for best behavior in mixed IPv4/IPv6 environments.
+ socketAddresses = dns.getAllByName(socketHost);
+ nextSocketAddressIndex = 0;
+ }
+
+ /** Returns true if there's another socket address to try. */
+ private boolean hasNextInetSocketAddress() {
+ return socketAddresses != null;
+ }
+
+ /** Returns the next socket address to try. */
+ private InetSocketAddress nextInetSocketAddress() throws UnknownHostException {
+ InetSocketAddress result =
+ new InetSocketAddress(socketAddresses[nextSocketAddressIndex++], socketPort);
+ if (nextSocketAddressIndex == socketAddresses.length) {
+ socketAddresses = null; // So that hasNextInetSocketAddress() returns false.
+ nextSocketAddressIndex = 0;
+ }
+
+ return result;
+ }
+
+ /** Resets {@link #nextTlsMode} to the first option. */
+ private void resetNextTlsMode() {
+ nextTlsMode = (address.getSslSocketFactory() != null) ? TLS_MODE_MODERN : TLS_MODE_COMPATIBLE;
+ }
+
+ /** Returns true if there's another TLS mode to try. */
+ private boolean hasNextTlsMode() {
+ return nextTlsMode != TLS_MODE_NULL;
+ }
+
+ /** Returns the next TLS mode to try. */
+ private int nextTlsMode() {
+ if (nextTlsMode == TLS_MODE_MODERN) {
+ nextTlsMode = TLS_MODE_COMPATIBLE;
+ return TLS_MODE_MODERN;
+ } else if (nextTlsMode == TLS_MODE_COMPATIBLE) {
+ nextTlsMode = TLS_MODE_NULL; // So that hasNextTlsMode() returns false.
+ return TLS_MODE_COMPATIBLE;
+ } else {
+ throw new AssertionError();
+ }
+ }
+
+ /** Returns true if there is another postponed route to try. */
+ private boolean hasNextPostponed() {
+ return !postponedRoutes.isEmpty();
+ }
+
+ /** Returns the next postponed route to try. */
+ private Route nextPostponed() {
+ return postponedRoutes.remove(0);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/SpdyTransport.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/SpdyTransport.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/SpdyTransport.java
new file mode 100644
index 0000000..18ab566
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/SpdyTransport.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.internal.spdy.SpdyConnection;
+import com.squareup.okhttp.internal.spdy.SpdyStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.CacheRequest;
+import java.net.URL;
+import java.util.List;
+
+public final class SpdyTransport implements Transport {
+ private final HttpEngine httpEngine;
+ private final SpdyConnection spdyConnection;
+ private SpdyStream stream;
+
+ public SpdyTransport(HttpEngine httpEngine, SpdyConnection spdyConnection) {
+ this.httpEngine = httpEngine;
+ this.spdyConnection = spdyConnection;
+ }
+
+ @Override public OutputStream createRequestBody() throws IOException {
+ // TODO: if we aren't streaming up to the server, we should buffer the whole request
+ writeRequestHeaders();
+ return stream.getOutputStream();
+ }
+
+ @Override public void writeRequestHeaders() throws IOException {
+ if (stream != null) {
+ return;
+ }
+ httpEngine.writingRequestHeaders();
+ RawHeaders requestHeaders = httpEngine.requestHeaders.getHeaders();
+ String version = httpEngine.connection.getHttpMinorVersion() == 1 ? "HTTP/1.1" : "HTTP/1.0";
+ URL url = httpEngine.policy.getURL();
+ requestHeaders.addSpdyRequestHeaders(httpEngine.method, HttpEngine.requestPath(url), version,
+ HttpEngine.getOriginAddress(url), httpEngine.uri.getScheme());
+ boolean hasRequestBody = httpEngine.hasRequestBody();
+ boolean hasResponseBody = true;
+ stream = spdyConnection.newStream(requestHeaders.toNameValueBlock(), hasRequestBody,
+ hasResponseBody);
+ stream.setReadTimeout(httpEngine.policy.getReadTimeout());
+ }
+
+ @Override public void writeRequestBody(RetryableOutputStream requestBody) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override public void flushRequest() throws IOException {
+ stream.getOutputStream().close();
+ }
+
+ @Override public ResponseHeaders readResponseHeaders() throws IOException {
+ List<String> nameValueBlock = stream.getResponseHeaders();
+ RawHeaders rawHeaders = RawHeaders.fromNameValueBlock(nameValueBlock);
+ rawHeaders.computeResponseStatusLineFromSpdyHeaders();
+ httpEngine.receiveHeaders(rawHeaders);
+ return new ResponseHeaders(httpEngine.uri, rawHeaders);
+ }
+
+ @Override public InputStream getTransferStream(CacheRequest cacheRequest) throws IOException {
+ return new UnknownLengthHttpInputStream(stream.getInputStream(), cacheRequest, httpEngine);
+ }
+
+ @Override public boolean makeReusable(boolean streamCancelled, OutputStream requestBodyOut,
+ InputStream responseBodyIn) {
+ if (streamCancelled) {
+ if (stream != null) {
+ stream.closeLater(SpdyStream.RST_CANCEL);
+ return true;
+ } else {
+ // If stream is null, it either means that writeRequestHeaders wasn't called
+ // or that SpdyConnection#newStream threw an IOEXception. In both cases there's
+ // nothing to do here and this stream can't be reused.
+ return false;
+ }
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/Transport.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/Transport.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/Transport.java
new file mode 100644
index 0000000..518827e
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/Transport.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.CacheRequest;
+
+interface Transport {
+ /**
+ * Returns an output stream where the request body can be written. The
+ * returned stream will of one of two types:
+ * <ul>
+ * <li><strong>Direct.</strong> Bytes are written to the socket and
+ * forgotten. This is most efficient, particularly for large request
+ * bodies. The returned stream may be buffered; the caller must call
+ * {@link #flushRequest} before reading the response.</li>
+ * <li><strong>Buffered.</strong> Bytes are written to an in memory
+ * buffer, and must be explicitly flushed with a call to {@link
+ * #writeRequestBody}. This allows HTTP authorization (401, 407)
+ * responses to be retransmitted transparently.</li>
+ * </ul>
+ */
+ // TODO: don't bother retransmitting the request body? It's quite a corner
+ // case and there's uncertainty whether Firefox or Chrome do this
+ OutputStream createRequestBody() throws IOException;
+
+ /** This should update the HTTP engine's sentRequestMillis field. */
+ void writeRequestHeaders() throws IOException;
+
+ /**
+ * Sends the request body returned by {@link #createRequestBody} to the
+ * remote peer.
+ */
+ void writeRequestBody(RetryableOutputStream requestBody) throws IOException;
+
+ /** Flush the request body to the underlying socket. */
+ void flushRequest() throws IOException;
+
+ /** Read response headers and update the cookie manager. */
+ ResponseHeaders readResponseHeaders() throws IOException;
+
+ // TODO: make this the content stream?
+ InputStream getTransferStream(CacheRequest cacheRequest) throws IOException;
+
+ /** Returns true if the underlying connection can be recycled. */
+ boolean makeReusable(boolean streamReusable, OutputStream requestBodyOut,
+ InputStream responseBodyIn);
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/UnknownLengthHttpInputStream.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/UnknownLengthHttpInputStream.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/UnknownLengthHttpInputStream.java
new file mode 100644
index 0000000..729e0b9
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/UnknownLengthHttpInputStream.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal.http;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.CacheRequest;
+
+import static com.squareup.okhttp.internal.Util.checkOffsetAndCount;
+
+/** An HTTP message body terminated by the end of the underlying stream. */
+final class UnknownLengthHttpInputStream extends AbstractHttpInputStream {
+ private boolean inputExhausted;
+
+ UnknownLengthHttpInputStream(InputStream is, CacheRequest cacheRequest, HttpEngine httpEngine)
+ throws IOException {
+ super(is, httpEngine, cacheRequest);
+ }
+
+ @Override public int read(byte[] buffer, int offset, int count) throws IOException {
+ checkOffsetAndCount(buffer.length, offset, count);
+ checkNotClosed();
+ if (in == null || inputExhausted) {
+ return -1;
+ }
+ int read = in.read(buffer, offset, count);
+ if (read == -1) {
+ inputExhausted = true;
+ endOfInput(false);
+ return -1;
+ }
+ cacheWrite(buffer, offset, read);
+ return read;
+ }
+
+ @Override public int available() throws IOException {
+ checkNotClosed();
+ return in == null ? 0 : in.available();
+ }
+
+ @Override public void close() throws IOException {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ if (!inputExhausted) {
+ unexpectedEndOfInput();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/IncomingStreamHandler.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/IncomingStreamHandler.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/IncomingStreamHandler.java
new file mode 100644
index 0000000..875fff0
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/IncomingStreamHandler.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.spdy;
+
+import java.io.IOException;
+
+/** Listener to be notified when a connected peer creates a new stream. */
+public interface IncomingStreamHandler {
+ IncomingStreamHandler REFUSE_INCOMING_STREAMS = new IncomingStreamHandler() {
+ @Override public void receive(SpdyStream stream) throws IOException {
+ stream.close(SpdyStream.RST_REFUSED_STREAM);
+ }
+ };
+
+ /**
+ * Handle a new stream from this connection's peer. Implementations should
+ * respond by either {@link SpdyStream#reply replying to the stream} or
+ * {@link SpdyStream#close closing it}. This response does not need to be
+ * synchronous.
+ */
+ void receive(SpdyStream stream) throws IOException;
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/Ping.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/Ping.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/Ping.java
new file mode 100644
index 0000000..c585255
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/Ping.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2012 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal.spdy;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * A locally-originated ping.
+ */
+public final class Ping {
+ private final CountDownLatch latch = new CountDownLatch(1);
+ private long sent = -1;
+ private long received = -1;
+
+ Ping() {
+ }
+
+ void send() {
+ if (sent != -1) throw new IllegalStateException();
+ sent = System.nanoTime();
+ }
+
+ void receive() {
+ if (received != -1 || sent == -1) throw new IllegalStateException();
+ received = System.nanoTime();
+ latch.countDown();
+ }
+
+ void cancel() {
+ if (received != -1 || sent == -1) throw new IllegalStateException();
+ received = sent - 1;
+ latch.countDown();
+ }
+
+ /**
+ * Returns the round trip time for this ping in nanoseconds, waiting for the
+ * response to arrive if necessary. Returns -1 if the response was
+ * cancelled.
+ */
+ public long roundTripTime() throws InterruptedException {
+ latch.await();
+ return received - sent;
+ }
+
+ /**
+ * Returns the round trip time for this ping in nanoseconds, or -1 if the
+ * response was cancelled, or -2 if the timeout elapsed before the round
+ * trip completed.
+ */
+ public long roundTripTime(long timeout, TimeUnit unit) throws InterruptedException {
+ if (latch.await(timeout, unit)) {
+ return received - sent;
+ } else {
+ return -2;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/Settings.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/Settings.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/Settings.java
new file mode 100644
index 0000000..774d791
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/spdy/Settings.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2012 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal.spdy;
+
+final class Settings {
+ /**
+ * From the spdy/3 spec, the default initial window size for all streams is
+ * 64 KiB. (Chrome 25 uses 10 MiB).
+ */
+ static final int DEFAULT_INITIAL_WINDOW_SIZE = 64 * 1024;
+
+ /** Peer request to clear durable settings. */
+ static final int FLAG_CLEAR_PREVIOUSLY_PERSISTED_SETTINGS = 0x1;
+
+ /** Sent by servers only. The peer requests this setting persisted for future connections. */
+ static final int PERSIST_VALUE = 0x1;
+ /** Sent by clients only. The client is reminding the server of a persisted value. */
+ static final int PERSISTED = 0x2;
+
+ /** Sender's estimate of max incoming kbps. */
+ static final int UPLOAD_BANDWIDTH = 0x1;
+ /** Sender's estimate of max outgoing kbps. */
+ static final int DOWNLOAD_BANDWIDTH = 0x2;
+ /** Sender's estimate of milliseconds between sending a request and receiving a response. */
+ static final int ROUND_TRIP_TIME = 0x3;
+ /** Sender's maximum number of concurrent streams. */
+ static final int MAX_CONCURRENT_STREAMS = 0x4;
+ /** Current CWND in Packets. */
+ static final int CURRENT_CWND = 0x5;
+ /** Retransmission rate. Percentage */
+ static final int DOWNLOAD_RETRANS_RATE = 0x6;
+ /** Window size in bytes. */
+ static final int INITIAL_WINDOW_SIZE = 0x7;
+ /** Window size in bytes. */
+ static final int CLIENT_CERTIFICATE_VECTOR_SIZE = 0x8;
+ /** Total number of settings. */
+ static final int COUNT = 0x9;
+
+ /** Bitfield of which flags that values. */
+ private int set;
+
+ /** Bitfield of flags that have {@link #PERSIST_VALUE}. */
+ private int persistValue;
+
+ /** Bitfield of flags that have {@link #PERSISTED}. */
+ private int persisted;
+
+ /** Flag values. */
+ private final int[] values = new int[COUNT];
+
+ void set(int id, int idFlags, int value) {
+ if (id >= values.length) {
+ return; // Discard unknown settings.
+ }
+
+ int bit = 1 << id;
+ set |= bit;
+ if ((idFlags & PERSIST_VALUE) != 0) {
+ persistValue |= bit;
+ } else {
+ persistValue &= ~bit;
+ }
+ if ((idFlags & PERSISTED) != 0) {
+ persisted |= bit;
+ } else {
+ persisted &= ~bit;
+ }
+
+ values[id] = value;
+ }
+
+ /** Returns true if a value has been assigned for the setting {@code id}. */
+ boolean isSet(int id) {
+ int bit = 1 << id;
+ return (set & bit) != 0;
+ }
+
+ /** Returns the value for the setting {@code id}, or 0 if unset. */
+ int get(int id) {
+ return values[id];
+ }
+
+ /** Returns the flags for the setting {@code id}, or 0 if unset. */
+ int flags(int id) {
+ int result = 0;
+ if (isPersisted(id)) result |= Settings.PERSISTED;
+ if (persistValue(id)) result |= Settings.PERSIST_VALUE;
+ return result;
+ }
+
+ /** Returns the number of settings that have values assigned. */
+ int size() {
+ return Integer.bitCount(set);
+ }
+
+ int getUploadBandwidth(int defaultValue) {
+ int bit = 1 << UPLOAD_BANDWIDTH;
+ return (bit & set) != 0 ? values[UPLOAD_BANDWIDTH] : defaultValue;
+ }
+
+ int getDownloadBandwidth(int defaultValue) {
+ int bit = 1 << DOWNLOAD_BANDWIDTH;
+ return (bit & set) != 0 ? values[DOWNLOAD_BANDWIDTH] : defaultValue;
+ }
+
+ int getRoundTripTime(int defaultValue) {
+ int bit = 1 << ROUND_TRIP_TIME;
+ return (bit & set) != 0 ? values[ROUND_TRIP_TIME] : defaultValue;
+ }
+
+ int getMaxConcurrentStreams(int defaultValue) {
+ int bit = 1 << MAX_CONCURRENT_STREAMS;
+ return (bit & set) != 0 ? values[MAX_CONCURRENT_STREAMS] : defaultValue;
+ }
+
+ int getCurrentCwnd(int defaultValue) {
+ int bit = 1 << CURRENT_CWND;
+ return (bit & set) != 0 ? values[CURRENT_CWND] : defaultValue;
+ }
+
+ int getDownloadRetransRate(int defaultValue) {
+ int bit = 1 << DOWNLOAD_RETRANS_RATE;
+ return (bit & set) != 0 ? values[DOWNLOAD_RETRANS_RATE] : defaultValue;
+ }
+
+ int getInitialWindowSize(int defaultValue) {
+ int bit = 1 << INITIAL_WINDOW_SIZE;
+ return (bit & set) != 0 ? values[INITIAL_WINDOW_SIZE] : defaultValue;
+ }
+
+ int getClientCertificateVectorSize(int defaultValue) {
+ int bit = 1 << CLIENT_CERTIFICATE_VECTOR_SIZE;
+ return (bit & set) != 0 ? values[CLIENT_CERTIFICATE_VECTOR_SIZE] : defaultValue;
+ }
+
+ /**
+ * Returns true if this user agent should use this setting in future SPDY
+ * connections to the same host.
+ */
+ boolean persistValue(int id) {
+ int bit = 1 << id;
+ return (persistValue & bit) != 0;
+ }
+
+ /** Returns true if this setting was persisted. */
+ boolean isPersisted(int id) {
+ int bit = 1 << id;
+ return (persisted & bit) != 0;
+ }
+
+ /**
+ * Writes {@code other} into this. If any setting is populated by this and
+ * {@code other}, the value and flags from {@code other} will be kept.
+ */
+ void merge(Settings other) {
+ for (int i = 0; i < COUNT; i++) {
+ if (!other.isSet(i)) continue;
+ set(i, other.flags(i), other.get(i));
+ }
+ }
+}
[25/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/config-parser.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/config-parser.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/config-parser.js
new file mode 100644
index 0000000..41775f4
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/config-parser.js
@@ -0,0 +1,1411 @@
+/*jshint sub:true*/
+
+var testData = require("./test-data"),
+ configParser = require(testData.libPath + "/config-parser"),
+ packagerUtils = require(testData.libPath + "/packager-utils"),
+ fileManager = require(testData.libPath + "/file-manager"),
+ logger = require(testData.libPath + "./logger"),
+ testUtilities = require("./test-utilities"),
+ xml2js = require('xml2js'),
+ localize = require(testData.libPath + "/localize"),
+ path = require("path"),
+ fs = require("fs"),
+ session = testData.session,
+ configPath = path.resolve("bin/test/cordova/unit/config.xml"),
+ configBadPath = path.resolve("test2/config.xml"),
+ configBareMinimumPath = path.resolve("bin/test/cordova/unit/config-bare-minimum.xml"),
+ mockParsing = testUtilities.mockParsing;
+
+describe("config parser", function () {
+ beforeEach(function () {
+ spyOn(logger, "warn");
+ spyOn(packagerUtils, "copyFile");
+ });
+
+ it("tries to open a config.xml file that doesn't exist", function () {
+ expect(function () {
+ configParser.parse(configBadPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_CONFIG_NOT_FOUND"));
+ });
+
+ it("parses standard elements in a config.xml", function () {
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.content).toEqual("local:///startPage.html");
+ expect(configObj.id).toEqual("My WidgetId");
+ expect(configObj.customHeaders).toEqual({ 'RIM-Widget' : 'rim/widget'});
+ expect(configObj.version).toEqual("1.0.0");
+ expect(configObj.license).toEqual("My License");
+ expect(configObj.licenseURL).toEqual("http://www.apache.org/licenses/LICENSE-2.0");
+ expect(configObj.icon).toEqual(["test.png"]);
+ expect(configObj.configXML).toEqual("config.xml");
+ expect(configObj.author).toEqual("Research In Motion Ltd.");
+ expect(configObj.authorURL).toEqual("http://www.rim.com/");
+ expect(configObj.copyright).toEqual("No Copyright");
+ expect(configObj.authorEmail).toEqual("author@rim.com");
+ expect(configObj.name).toEqual({ default : 'Demo' });
+ expect(configObj.description).toEqual({ default : 'This app does everything.' });
+ expect(configObj.permissions).toContain('access_shared');
+ expect(configObj.permissions).toContain('read_geolocation');
+ expect(configObj.permissions).toContain('use_camera');
+ expect(configObj.enableChildWebView).toBe(false);
+ expect(configObj.enableChildWebView).toBe(false);
+ });
+ });
+
+ it("parses Feature elements in a config.xml", function () {
+ var localAccessList,
+ accessListFeature;
+
+ configParser.parse(configPath, session, function (configObj) {
+ //validate WIDGET_LOCAL accessList
+ localAccessList = testUtilities.getAccessListForUri(configObj.accessList, "WIDGET_LOCAL");
+ expect(localAccessList).toBeDefined();
+ expect(localAccessList.uri).toEqual("WIDGET_LOCAL");
+ expect(localAccessList.allowSubDomain).toEqual(true);
+ });
+ });
+
+ it("parses Access elements a config.xml", function () {
+ var customAccessList,
+ accessListFeature;
+
+ configParser.parse(configPath, session, function (configObj) {
+ //validate http://www.somedomain1.com accessList
+ customAccessList = testUtilities.getAccessListForUri(configObj.accessList, "http://www.somedomain1.com");
+ expect(customAccessList).toBeDefined();
+ expect(customAccessList.uri).toEqual("http://www.somedomain1.com");
+ expect(customAccessList.allowSubDomain).toEqual(true);
+ });
+ });
+
+ it("parses a bare minimum config.xml without error", function () {
+ var bareMinimumConfigPath = path.resolve("bin/test/cordova/unit/config-bare-minimum.xml");
+
+ configParser.parse(bareMinimumConfigPath, session, function (configObj) {
+ expect(configObj.content).toEqual("local:///startPage.html");
+ expect(configObj.version).toEqual("1.0.0");
+ });
+ });
+
+ it("license url is set even if license body is empty", function () {
+ var licenseConfigPath = path.resolve("bin/test/cordova/unit/config-license.xml");
+
+ configParser.parse(licenseConfigPath, session, function (configObj) {
+ expect(configObj.license).toEqual("");
+ expect(configObj.licenseURL).toEqual("http://www.apache.org/licenses/LICENSE-2.0");
+ });
+ });
+
+ it("fails when id is undefined", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["@"].id = undefined;
+
+ mockParsing(data);
+
+ //Should throw an EXCEPTION_INVALID_ID error
+ expect(function () {
+ configParser.parse(configPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ID"));
+ });
+
+ it("fails when id is empty", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["@"].id = "";
+
+ mockParsing(data);
+
+ //Should throw an EXCEPTION_INVALID_ID error
+ expect(function () {
+ configParser.parse(configPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ID"));
+ });
+
+ it("Fails when no name was provided - single element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.name = "";
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_NAME"));
+ });
+
+ it("Fails when no name was provided - multiple elements", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.name = ["",
+ { '#': 'API Smoke Test-FR', '@': { 'xml:lang': 'fr' } },
+ ];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_NAME"));
+ });
+
+ it("Fails when localized name was provided but empty", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.name = ["API Smoke Test",
+ { '#': '', '@': { 'xml:lang': 'fr' } },
+ ];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_NAME"));
+ });
+
+ it("Parses a name element - single element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.name = "API Smoke Test";
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.name).toEqual({"default": "API Smoke Test"});
+ });
+ });
+
+ it("Parses a name element with xml:lang - single element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.name = { '#': 'EN VALUE', '@': { 'xml:lang': 'en' } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.name).toEqual({"en": "EN VALUE"});
+ });
+ });
+
+ it("Parses a name element that is not case sensitive", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.name = { '#': 'EN VALUE', '@': { 'xml:lang': 'eN' } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.name).toEqual({"en": "EN VALUE"});
+ });
+ });
+
+ it("Parses a name element with xml:lang - multi element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.name = ['API Smoke Test',
+ { '#': 'EN VALUE', '@': { 'xml:lang': 'en' } },
+ { '#': 'FR VALUE', '@': { 'xml:lang': 'fr' } }
+
+ ];
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.name).toEqual({"default": "API Smoke Test", "en": "EN VALUE", "fr": "FR VALUE"});
+ });
+ });
+
+ it("Fails when localized name was provided but empty", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.name = ['API Smoke Test',
+ { '#': '', '@': { 'xml:lang': 'fr' } },
+ ];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_NAME"));
+ });
+
+ it("Parses a description element - single element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.description = "This is my app";
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.description).toEqual({"default": "This is my app"});
+ });
+ });
+
+ it("Parses a description element with xml:lang - single element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.description = { '#': 'EN VALUE', '@': { 'xml:lang': 'en' } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.description).toEqual({"en": "EN VALUE"});
+ });
+ });
+
+ it("Parses a description element that is not case sensitive", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.description = { '#': 'EN VALUE', '@': { 'xml:lang': 'eN' } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.description).toEqual({"en": "EN VALUE"});
+ });
+ });
+
+ it("Parses a description element with xml:lang - multi element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.description = ['This is my app',
+ { '#': 'EN VALUE', '@': { 'xml:lang': 'en' } },
+ { '#': 'FR VALUE', '@': { 'xml:lang': 'fr' } }
+
+ ];
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.description).toEqual({"default": "This is my app", "en": "EN VALUE", "fr": "FR VALUE"});
+ });
+ });
+
+ it("Fails when missing content error is not shown", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.content = "";
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_CONTENT"));
+ });
+
+ it("adds local:/// protocol to urls", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.content["@"].src = "localFile.html";
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.content).toEqual("local:///localFile.html");
+ });
+ });
+
+ it("cleans source folder on error", function () {
+ mockParsing({}, "ERROR");
+
+ spyOn(logger, "error");
+ spyOn(fileManager, "cleanSource");
+
+ configParser.parse(configPath, session, function () {});
+
+ expect(fileManager.cleanSource).toHaveBeenCalled();
+ });
+
+ it("parses a single permission (comes in as string)", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['rim:permissions'] = {};
+ data['rim:permissions']['rim:permit'] = 'onePermissionNoAttribs';
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.permissions).toContain('onePermissionNoAttribs');
+ });
+ });
+
+ it("parses a single permission with attribs (comes in as object)", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['rim:permissions'] = {};
+ data['rim:permissions']['rim:permit'] = { '#': 'systemPerm', '@': { system: 'true' } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.permissions).toContain({ '#': 'systemPerm', '@': { system: 'true' } });
+ });
+ });
+
+ it("parses multiple permissions with no attribs (comes in as array)", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['rim:permissions'] = {};
+ data['rim:permissions']['rim:permit'] = [ 'access_shared', 'read_geolocation', 'use_camera' ];
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.permissions).toContain('access_shared');
+ expect(configObj.permissions).toContain('read_geolocation');
+ expect(configObj.permissions).toContain('use_camera');
+ });
+ });
+
+ it("parses multiple permissions with attribs (comes in as array)", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['rim:permissions'] = {};
+ data['rim:permissions']['rim:permit'] = [
+ { '#': 'systemPerm', '@': { system: 'true' } },
+ { '#': 'nonSystemPerm', '@': { system: 'false' } }
+ ];
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.permissions).toContain({ '#': 'systemPerm', '@': { system: 'true' } });
+ expect(configObj.permissions).toContain({ '#': 'nonSystemPerm', '@': { system: 'false' } });
+ });
+ });
+
+ it("parses a config with no permissions set", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ delete data['rim:permissions']; //No permissions set in config
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.permissions).toEqual([]);
+ });
+ });
+
+ it("enables the enable-flash feature when specified", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ //Add the enable-flash feature element
+ data['feature'] = {'@': {id: 'enable-flash'}};
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableFlash).toEqual(true);
+ });
+ });
+
+ it("does not enable the enable-flash feature when specified in an access element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ //Add the enable-flash to an access element
+ data['access'] = {"@" : {"uri" : "http://somewebsite.com"}, "feature" : {"@": {id: 'enable-flash'}}};
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableFlash).toEqual(false);
+ });
+ });
+
+ it("disables the enable-flash feature by default", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = undefined;//no features
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableFlash).toEqual(false);
+ });
+ });
+
+ it("sets autoDeferNetworkingAndJavaScript to false when the blackberry.push feature is specified", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ //Add the blackberry.push feature element
+ data["rim:permissions"] = {}; // ensure no run_when_backgrounded permission exists
+ data['feature'] = {'@': {id: 'blackberry.push'}};
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.autoDeferNetworkingAndJavaScript).toEqual(false);
+ });
+ });
+
+ it("sets autoDeferNetworkingAndJavaScript to false when the run_when_backgrounded permission is specified", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ //Add the run_when_backgrounded permission
+ data['feature'] = undefined; // no features
+ data["rim:permissions"] = {
+ "rim:permit" : [ 'read_geolocation', 'run_when_backgrounded', 'access_internet' ]
+ };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.permissions).toContain('run_when_backgrounded');
+ expect(configObj.autoDeferNetworkingAndJavaScript).toEqual(false);
+ });
+ });
+
+ it("sets autoDeferNetworkingAndJavaScript to true by default", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ data['feature'] = undefined; // no features
+ data["rim:permissions"] = {}; // ensure no run_when_backgrounded permission exists
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.autoDeferNetworkingAndJavaScript).toEqual(true);
+ });
+ });
+
+ it("does not throw an exception with empty permit tags", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['rim:permit'] = ['read_geolocation', {}, 'access_internet' ];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).not.toThrow();
+ });
+
+ it("multi access should be false if no access", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ //hasMultiAccess was set to false
+ expect(configObj.hasMultiAccess).toEqual(false);
+ expect(configObj.accessList).toEqual([ {
+ uri : 'WIDGET_LOCAL',
+ allowSubDomain : true
+ } ]);
+ });
+ });
+
+ it("multi access should be false if no uri is equal to *", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['access'] = {"@" : {"uri" : "http://www.somedomain1.com"}};
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ //hasMultiAccess was set to false
+ expect(configObj.hasMultiAccess).toEqual(false);
+ expect(configObj.accessList).toEqual([ {
+ uri : 'WIDGET_LOCAL',
+ allowSubDomain : true
+ }, {
+ "uri" : "http://www.somedomain1.com"
+ } ]);
+ });
+ });
+
+ it("multi access should be true with the uri being equal to *", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['access'] = {"@" : {"uri" : "*"}};
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ //hasMultiAccess was set to true
+ expect(configObj.hasMultiAccess).toEqual(true);
+ expect(configObj.accessList).toEqual([ {
+ uri : 'WIDGET_LOCAL',
+ allowSubDomain : true
+ } ]);
+ });
+ });
+
+ it("multi access should be true with one uri being equal to *", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['access'] = [{"@" : {"uri" : "*"}}, {"@" : {"uri" : "http://www.somedomain1.com"}}];
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ //hasMultiAccess was set to true
+ expect(configObj.hasMultiAccess).toEqual(true);
+ expect(configObj.accessList).toEqual([ {
+ uri : 'WIDGET_LOCAL',
+ allowSubDomain : true
+ }, {
+ "uri" : "http://www.somedomain1.com"
+ } ]);
+ });
+ });
+
+ it("should fail when feature is defined with the uri being equal to *", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['access'] = {"@" : {"uri" : "*"}, "feature" : {"@": {"id": "blackberry.app"}}};
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_FEATURE_DEFINED_WITH_WILDCARD_ACCESS_URI"));
+ });
+
+ it("should fail when multi features are defined with the uri being equal to *", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['access'] = {"@" : {"uri" : "*"}, "feature" : [{"@": {"id": "blackberry.app"}}, {"@": {"id": "blackberry.system"}}, {"@": {"id": "blackberry.invoke"}}]};
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_FEATURE_DEFINED_WITH_WILDCARD_ACCESS_URI"));
+ });
+
+ it("should fail when the access uri attribute does not specify a protocol", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ //Add an access element with one feature
+ data['access'] = {
+ '@': {
+ uri: 'rim.net',
+ subdomains: 'true'
+ },
+ feature: {
+ '@': { id: 'blackberry.system' }
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ACCESS_URI_NO_PROTOCOL", data['access']['@'].uri));
+ });
+
+ it("should fail when the access uri attribute does not specify a URN", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ //Add an access element with one feature
+ data['access'] = {
+ '@': {
+ uri: 'http://',
+ subdomains: 'true'
+ },
+ feature: {
+ '@': { id: 'blackberry.system' }
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ACCESS_URI_NO_URN", data['access']['@'].uri));
+ });
+
+ it("does not fail when there is a single feature element in the access list", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ //Add an access element with one feature
+ data['access'] = {
+ '@': {
+ uri: 'http://rim.net',
+ subdomains: 'true'
+ },
+ feature: {
+ '@': { id: 'blackberry.system' }
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).not.toThrow();
+ });
+
+ it("supports 4 digit version [build id]", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["@"].version = "1.0.0.50";
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.version).toEqual("1.0.0");
+ expect(configObj.buildId).toEqual("50");
+ });
+ });
+
+ it("uses --buildId when set", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ //--buildId 100
+ session.buildId = "100";
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.buildId).toEqual("100");
+ });
+ });
+
+ it("overides the build id specified in version with --buildId flag", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["@"].version = "1.0.0.50";
+
+ //--buildId 100
+ session.buildId = "100";
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.version).toEqual("1.0.0");
+ expect(configObj.buildId).toEqual("100");
+ });
+ });
+
+ it("throws a proper error when author tag is empty", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.author = {};
+
+ mockParsing(data);
+
+ //Should throw an EXCEPTION_INVALID_AUTHOR error
+ expect(function () {
+ configParser.parse(configPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_AUTHOR"));
+ });
+
+ it("can parse a standard rim:invoke-target element", function () {
+
+ configParser.parse(configPath, session, function (configObj) {
+ var invokeTarget = configObj["invoke-target"][0];
+
+ expect(invokeTarget).toBeDefined();
+ expect(invokeTarget["@"]).toBeDefined();
+ expect(invokeTarget["@"]["id"]).toBeDefined();
+ expect(invokeTarget["@"]["id"]).toEqual("com.domain.subdomain.appname.app1");
+ expect(invokeTarget.type).toBeDefined();
+ expect(invokeTarget.type).toEqual("APPLICATION");
+ expect(invokeTarget["require-source-permissions"]).toBeDefined();
+ expect(invokeTarget["require-source-permissions"]).toEqual("invoke_accross_perimeters,access_shared");
+ expect(invokeTarget.filter).toBeDefined();
+ expect(invokeTarget.filter[0].action).toBeDefined();
+ expect(invokeTarget.filter[0].action).toContain("bb.action.VIEW");
+ expect(invokeTarget.filter[0].action).toContain("bb.action.SET");
+ expect(invokeTarget.filter[0].action).toContain("bb.action.OPEN");
+ expect(invokeTarget.filter[0]["mime-type"]).toBeDefined();
+ expect(invokeTarget.filter[0]["mime-type"]).toContain("image/*");
+ expect(invokeTarget.filter[0]["mime-type"]).toContain("text/*");
+ expect(invokeTarget.filter[0].property).toBeDefined();
+
+ invokeTarget.filter[0].property.forEach(function (property) {
+ expect(property["@"]).toBeDefined();
+ expect(property["@"]["var"]).toBeDefined();
+ expect(property["@"]["var"]).toMatch("^(exts|uris)$");
+ if (property["@"]["var"] === "uris") {
+ expect(property["@"]["value"]).toMatch("^(ftp|http|https):\/\/$");
+ } else if (property["@"]["var"] === "exts") {
+ expect(property["@"]["value"]).toMatch("^(jpg|png|txt|doc)$");
+ }
+ });
+ });
+ });
+
+ it("can parse multiple filters in one element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:invoke-target"] = {
+ "@": {
+ "id": "com.domain.subdomain.appName.app"
+ },
+ "type": "application",
+ "filter": [{
+ "action": "bb.action.OPEN",
+ "mime-type": ["text/*", "image/*"]
+ }, {
+ "action": "bb.action.SET",
+ "mime-type": "image/*"
+ }]
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).not.toThrow();
+ });
+
+ it("can parse multiple invoke targets", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:invoke-target"] = [{
+ "@": {
+ "id": "com.domain.subdomain.appName.app"
+ },
+ "type": "application"
+ }, {
+ "@": {
+ "id": "com.domain.subdomain.appName.viewer"
+ },
+ "type": "viewer"
+ }];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).not.toThrow();
+
+ });
+
+ it("throws an error when an invoke target doesn't specify an invocation id", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:invoke-target"] = {
+ type: "APPLICATION"
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVOKE_TARGET_INVALID_ID"));
+ });
+
+ it("throws and error when an invoke target xml doesn't specify an invocation type", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:invoke-target"] = {
+ "@": {
+ "id": "com.domain.subdomain.appName.app"
+ },
+ type: {}
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVOKE_TARGET_INVALID_TYPE"));
+ });
+
+ it("throws an error when an invoke target doesn't specify an invocation type", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:invoke-target"] = {
+ "@": {
+ "id": "com.domain.subdomain.appName.app"
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVOKE_TARGET_INVALID_TYPE"));
+ });
+
+ it("throws an error when an invoke target filter doesn't contain an action", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:invoke-target"] = {
+ "@": {
+ "id": "com.domain.subdomain.appName.app"
+ },
+ "type": "APPLICATION",
+ "filter": {
+ "mime-type": "text/*",
+ "property": [{
+ "@": {
+ "var": "uris",
+ "value": "https://"
+ }
+ }, {
+ "@": {
+ "var": "exts",
+ "value": "html"
+ }
+ }, {
+ "@": {
+ "var": "exts",
+ "value": "htm"
+ }
+ }]
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVOKE_TARGET_ACTION_INVALID"));
+ });
+
+ it("throws an error when a filter doesn't contain a mime-type", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:invoke-target"] = {
+ "@": {
+ "id": "com.domain.subdomain.appName.app"
+ },
+ "type": "application",
+ "filter": {
+ "action": "bb.action.OPEN",
+ "property": [{
+ "@": {
+ "var": "uris",
+ "value": "https://"
+ }
+ }, {
+ "@": {
+ "var": "exts",
+ "value": "html"
+ }
+ }]
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVOKE_TARGET_MIME_TYPE_INVALID"));
+ });
+
+ describe("splash screen", function () {
+ it("throws error when rim:splash element does not contain src attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:splash"] = {};
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_SPLASH_SRC"));
+ });
+
+ it("throws error when rim:splash element contains empty src attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:splash"] = {
+ "@": {
+ "src": ""
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_SPLASH_SRC"));
+ });
+
+ it("throws error when one of many rim:splash elements does not contain attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:splash"] = [{
+ "@": {
+ "src": "a.jpg"
+ }
+ }, {
+ "#": "blah"
+ }];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_SPLASH_SRC"));
+ });
+
+ it("allow one rim:splash element that contains non-empty src attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:splash"] = {
+ "@": {
+ "src": "a.jpg"
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).not.toThrow();
+ });
+
+ it("allow multiple rim:splash elements that contain non-empty src attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:splash"] = [{
+ "@": {
+ "src": "a.jpg"
+ }
+ }, {
+ "@": {
+ "src": "b.jpg"
+ }
+ }];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).not.toThrow();
+ });
+
+ it("throws error when rim:splash src starts with 'locales' subfolder", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["rim:splash"] = [{
+ "@": {
+ "src": "a.jpg"
+ }
+ }, {
+ "@": {
+ "src": "locales/en/b.jpg"
+ }
+ }];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_SPLASH_SRC_LOCALES"));
+ });
+ });
+
+ describe("icon", function () {
+ it("throws error when icon element does not contain src attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["icon"] = {};
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ICON_SRC"));
+ });
+
+ it("throws error when icon element contains empty src attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["icon"] = {
+ "@": {
+ "src": ""
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ICON_SRC"));
+ });
+
+ it("throws error when one of many icon elements does not contain attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["icon"] = [{
+ "@": {
+ "src": "a.jpg"
+ }
+ }, {
+ "#": "blah"
+ }];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ICON_SRC"));
+ });
+
+ it("allow one icon element that contains non-empty src attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["icon"] = {
+ "@": {
+ "src": "a.jpg"
+ }
+ };
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).not.toThrow();
+ });
+
+ it("allow multiple icon elements that contain non-empty src attribute", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["icon"] = [{
+ "@": {
+ "src": "a.jpg"
+ }
+ }, {
+ "@": {
+ "src": "b.jpg"
+ }
+ }];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).not.toThrow();
+ });
+
+ it("throws error when icon src starts with 'locales' subfolder", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["icon"] = [{
+ "@": {
+ "src": "a.jpg"
+ }
+ }, {
+ "@": {
+ "src": "locales/en/b.jpg"
+ }
+ }];
+
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ICON_SRC_LOCALES"));
+ });
+
+ it("should copy the default icon to the src dir when no icon specified", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ mockParsing(data);
+
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).not.toThrow();
+
+ expect(packagerUtils.copyFile).toHaveBeenCalled();
+ });
+
+ it("should use the default icon config when no icon is specified", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ mockParsing(data);
+
+ configParser.parse(configBareMinimumPath, session, function (configObj) {
+ expect(configObj.icon).toEqual(["default-icon.png"]);
+ });
+ });
+
+ it("should not use the default icon config when icon is specified", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["icon"] = {
+ "@": {
+ "src": "test.png"
+ }
+ };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.icon).toEqual(["test.png"]);
+ expect(configObj.icon).not.toEqual(["default-icon.png"]);
+ expect(configObj.icon).not.toContain("default-icon.png");
+ });
+ });
+
+ it("sets orientation to landscape when specified", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app', required: true },
+ param: { '@': { name: 'orientation', value: 'landscape' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.orientation).toEqual("landscape");
+ expect(configObj.autoOrientation).toEqual(false);
+ });
+ });
+
+ it("sets orientation to portrait when specified", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app', required: true },
+ param: { '@': { name: 'orientation', value: 'portrait' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.orientation).toEqual("portrait");
+ expect(configObj.autoOrientation).toEqual(false);
+ });
+ });
+
+ it("sets auto orientation to true by default", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ delete data["feature"];//Remove any orientation data
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.autoOrientation).toEqual(true);
+ });
+ });
+
+ it("throws a warning when blackberry.app.orientation exists", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app.orientation', required: true },
+ param: { '@': { name: 'mode', value: 'portrait' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {});
+ expect(logger.warn).toHaveBeenCalled();
+ });
+
+ it("throws an error when blackberry.app orientation exists with an invalid mode param", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app', required: true },
+ param: { '@': { name: 'orientation', value: 'notAValidMode' } } };
+
+ mockParsing(data);
+
+ //Should throw an EXCEPTION_INVALID_ORIENTATION_MODE error
+ expect(function () {
+ configParser.parse(configPath, session, function (configObj) {});
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ORIENTATION_MODE", "notAValidMode"));
+ });
+
+ it("sets backgroundColor when specified via blackberry.app namespace", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app', required: true },
+ param: { '@': { name: 'backgroundColor', value: '0xffffff' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.backgroundColor).toEqual(16777215);//Decimal value of 0xffffff
+ });
+ });
+
+ it("throws an error when blackberry.app backgroundColor param is not a number", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app', required: true },
+ param: { '@': { name: 'backgroundColor', value: '$UI*@@$' } } };
+
+ mockParsing(data);
+
+ //Should throw an EXCEPTION_BGCOLOR_INVALID error
+ expect(function () {
+ configParser.parse(configPath, session, {});
+ }).toThrow(localize.translate("EXCEPTION_BGCOLOR_INVALID", "$UI*@@$"));
+ });
+
+ it("can properly parse the custom RIM-Wiget:rim/wiget element", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.customHeaders).toEqual({ 'RIM-Widget' : 'rim/widget'});
+ });
+ });
+
+ it("can properly parse the custom attributes but ignores improper headers", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["@"] = {
+ "xmlns": " http://www.w3.org/ns/widgets",
+ "xmlns:rim": "http://www.blackberry.com/ns/widgets",
+ "version": "1.0.0",
+ "id": "myID"
+ };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.id).toEqual("myID");
+ expect(configObj.customHeaders).toEqual(undefined);
+ });
+ });
+
+ it("can properly parse the custom attributes but ignores improper headers", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data["@"] = {
+ "xmlns": " http://www.w3.org/ns/widgets",
+ "xmlns:rim": "http://www.blackberry.com/ns/widgets",
+ "version": "1.0.0",
+ "id": "myID",
+ "rim:userAgent" : "A Test-User-Agent/(Blackberry-Agent)"
+ };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.id).toEqual("myID");
+ expect(configObj.userAgent).toEqual("A Test-User-Agent/(Blackberry-Agent)");
+ });
+ });
+
+ describe('disabling childBrowser (childWebView)', function () {
+
+ // { '@': { id: 'blackberry.app', required: true, version: '1.0.0.0' },
+ // param: { '@': { name: 'childBrowser', value: 'disable' } } }
+
+
+ it("sets enableChildWebView to true when childBrowser value is enable", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'childBrowser', value: 'enable' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableChildWebView).toBe(true);
+ });
+ });
+
+ it("sets enableChildWebView to false when value is disable", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'childBrowser', value: 'disable' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableChildWebView).toBe(false);
+ });
+ });
+ });
+
+ describe('disabling formcontrol', function () {
+
+ it("sets enableFormControl to true when formControl value is enable", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'formControl', value: 'enable' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableFormControl).toBe(true);
+ });
+ });
+
+ it("sets enableFormControl to false when value is disable", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data['feature'] = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'formControl', value: 'disable' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableFormControl).toBe(false);
+ });
+ });
+ });
+
+ describe('setting theme for some core ui elements', function () {
+ function testTheme(themeInConfig, themeParsed) {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+
+ if (themeInConfig) {
+ data['feature'] = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'theme', value: themeInConfig } } };
+
+ mockParsing(data);
+ }
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.theme).toBe(themeParsed);
+ });
+ }
+
+ it("sets theme to dark when config has theme with dark", function () {
+ testTheme("dark", "dark");
+ });
+
+ it("sets theme to bright when config has theme with bright", function () {
+ testTheme("bright", "bright");
+ });
+
+ it("sets theme to inherit when config has theme with inherit", function () {
+ testTheme("inherit", "inherit");
+ });
+
+ it("sets theme to default when config has theme with default", function () {
+ testTheme("default", "default");
+ });
+
+ it("sets theme to default when config has unsupported theme", function () {
+ testTheme("unsupportedthemename", "default");
+ });
+
+ it("sets theme to default when config has no theme provided", function () {
+ testTheme(undefined, "default");
+ });
+
+ it("sets theme to dark when config has theme with case insensitive dark", function () {
+ testTheme("dArK", "dark");
+ });
+
+ it("sets theme to bright when config has theme with case insensitive bright", function () {
+ testTheme("BriGht", "bright");
+ });
+
+ it("sets theme to inherit when config has theme with case insensitive inherit", function () {
+ testTheme("inHerIt", "inherit");
+ });
+
+ it("sets theme to inherit when config has theme with case insensitive inherit", function () {
+ testTheme("DefAulT", "default");
+ });
+
+ it("sets theme to default when config has NO theme tag provided", function () {
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.theme).toBe("default");
+ });
+ });
+ });
+
+ describe('disabling WebSecurity', function () {
+
+ // { '@': { id: 'blackberry.app', required: true, version: '1.0.0.0' },
+ // param: { '@': { name: 'childBrowser', value: 'disable' } } }
+
+
+ it("doesn't set enableWebSecurity to anything when param value is anything but disable", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.feature = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'websecurity', value: (new Date()).toString() } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableWebSecurity).toBe(undefined);
+ expect(logger.warn).not.toHaveBeenCalledWith(localize.translate("WARNING_WEBSECURITY_DISABLED"));
+ });
+ });
+
+ it("sets enableWebSecurity to false when value is disable", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.feature = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'websecurity', value: 'disable' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableWebSecurity).toBe(false);
+ expect(logger.warn).toHaveBeenCalledWith(localize.translate("WARNING_WEBSECURITY_DISABLED"));
+ });
+ });
+
+ it("sets enableWebSecurity to false when value is disable case insensitive", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.feature = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'websecurity', value: 'DisAble' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enableWebSecurity).toBe(false);
+ expect(logger.warn).toHaveBeenCalledWith(localize.translate("WARNING_WEBSECURITY_DISABLED"));
+ });
+ });
+ });
+
+ describe('enabling popupBlocker', function () {
+
+ // { '@': { id: 'blackberry.app', required: true, version: '1.0.0.0' },
+ // param: { '@': { name: 'childBrowser', value: 'disable' } } }
+
+ it("sets enableWebSecurity to false when value is disable", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.feature = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'popupBlocker', value: 'enable' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enablePopupBlocker).toBe(true);
+ });
+ });
+
+ it("sets enableWebSecurity to false when value is disable case insensitive", function () {
+ var data = testUtilities.cloneObj(testData.xml2jsConfig);
+ data.feature = { '@': { id: 'blackberry.app' },
+ param: { '@': { name: 'popupBlocker', value: 'EnAbLe' } } };
+
+ mockParsing(data);
+
+ configParser.parse(configPath, session, function (configObj) {
+ expect(configObj.enablePopupBlocker).toBe(true);
+ });
+ });
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/file-manager.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/file-manager.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/file-manager.js
new file mode 100644
index 0000000..1b1c6ff
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/file-manager.js
@@ -0,0 +1,67 @@
+var srcPath = __dirname + "/../../../../../templates/project/cordova/lib/",
+ barconf = require(srcPath + "bar-conf.js"),
+ fs = require("fs"),
+ path = require("path"),
+ util = require("util"),
+ packager_utils = require(srcPath + "packager-utils"),
+ localize = require(srcPath + "localize"),
+ wrench = require("wrench"),
+ logger = require(srcPath + "logger"),
+ conf = require(srcPath + "conf"),
+ fileMgr = require(srcPath + "file-manager"),
+ testData = require("./test-data"),
+ testUtilities = require("./test-utilities"),
+ session = testData.session,
+ extManager = {
+ getAllExtensionsToCopy: function (accessList) {
+ return ["app"];
+ },
+ getFeatureIdByExtensionBasename: function (extBasename) {
+ return "blackberry." + extBasename;
+ }
+ };
+
+describe("File manager", function () {
+
+ beforeEach(function () {
+ wrench.mkdirSyncRecursive(testData.session.outputDir);
+ });
+
+ afterEach(function () {
+ //cleanup packager-tests temp folder
+ wrench.rmdirSyncRecursive(testData.session.outputDir);
+ });
+
+ it("unzip() should extract 'from' zip file to 'to' directory", function () {
+ var from = session.archivePath,
+ to = session.sourceDir;
+
+ fileMgr.unzip(from, to);
+
+ expect(fs.statSync(session.sourceDir + "/a").isDirectory()).toBeTruthy();
+ expect(fs.statSync(session.sourceDir + "/a/dummy.txt").isFile()).toBeTruthy();
+ expect(fs.statSync(session.sourceDir + "/a/b").isDirectory()).toBeTruthy();
+ expect(fs.statSync(session.sourceDir + "/a/b/dummy2.txt").isFile()).toBeTruthy();
+ expect(fs.statSync(session.sourceDir + "/startPage.html").isFile()).toBeTruthy();
+ expect(fs.statSync(session.sourceDir + "/config.xml").isFile()).toBeTruthy();
+ expect(fs.statSync(session.sourceDir + "/test.png").isFile()).toBeTruthy();
+ });
+
+ it("cleanSource() should delete source folder", function () {
+ //Create packager-tests source folder
+ wrench.mkdirSyncRecursive(session.sourceDir);
+
+ fileMgr.cleanSource(session);
+ expect(fs.existsSync(session.sourceDir)).toBeFalsy();
+ });
+
+ it("prepareOutputFiles() should throw an error if the archive path doesn't exist", function () {
+ spyOn(wrench, "copyDirSyncRecursive");
+ var tempSession = testUtilities.cloneObj(session);
+ tempSession.archivePath = path.resolve("test/non-existant.zip");
+ expect(function () {
+ fileMgr.prepareOutputFiles(tempSession);
+ }).toThrow(localize.translate("EXCEPTION_INVALID_ARCHIVE_PATH", tempSession.archivePath));
+ });
+
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/i18n-manager.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/i18n-manager.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/i18n-manager.js
new file mode 100644
index 0000000..50d7225
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/i18n-manager.js
@@ -0,0 +1,298 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var testData = require("./test-data"),
+ i18nMgr = require(testData.libPath + "/i18n-manager"),
+ session = testData.session,
+ fs = require("fs"),
+ wrench = require("wrench"),
+ pkgrUtils = require(testData.libPath + "/packager-utils");
+
+function mockOSReturnFiles(files) {
+ if (pkgrUtils.isWindows()) {
+ var newFiles = [];
+ files.forEach(function (f) {
+ newFiles.push(session.sourceDir + "\\locales\\" + f.split("/").join("\\"));
+ });
+ return newFiles;
+ } else {
+ return files;
+ }
+}
+
+describe("i18n manager", function () {
+ it("generate correct metadata for icon", function () {
+ var config = {
+ icon: ["logo.png"]
+ },
+ xmlObject = {};
+
+ spyOn(fs, "existsSync").andReturn(true);
+ spyOn(wrench, "readdirSyncRecursive").andReturn(mockOSReturnFiles([
+ 'fr',
+ 'fr/logo.png'
+ ]));
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "icon");
+
+ expect(xmlObject.icon).toBeDefined();
+ expect(xmlObject.icon.image).toBeDefined();
+ expect(xmlObject.icon.image.length).toBe(2);
+ expect(xmlObject.icon.image).toContain({
+ _value: "logo.png"
+ });
+ expect(xmlObject.icon.image).toContain({
+ text: {
+ _attr: {
+ "xml:lang": "fr"
+ },
+ _value: "locales/fr/logo.png"
+ }
+ });
+ });
+
+ it("generate correct metadata for icon when locales folder does not exist", function () {
+ var config = {
+ icon: ["logo.png"]
+ },
+ xmlObject = {};
+
+ spyOn(fs, "existsSync").andReturn(false);
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "icon");
+
+ expect(xmlObject.icon).toBeDefined();
+ expect(xmlObject.icon.image).toBeDefined();
+ expect(xmlObject.icon.image.length).toBe(1);
+ expect(xmlObject.icon.image).toContain({
+ _value: "logo.png"
+ });
+ });
+
+ it("generate correct metadata for icon when locale folder does not contain matching image", function () {
+ var config = {
+ icon: ["logo.png"]
+ },
+ xmlObject = {};
+
+ spyOn(fs, "existsSync").andReturn(true);
+ spyOn(wrench, "readdirSyncRecursive").andReturn(mockOSReturnFiles([
+ 'fr',
+ 'fr/logo-mismatch.png'
+ ]));
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "icon");
+
+ expect(xmlObject.icon).toBeDefined();
+ expect(xmlObject.icon.image).toBeDefined();
+ expect(xmlObject.icon.image.length).toBe(1);
+ expect(xmlObject.icon.image).toContain({
+ _value: "logo.png"
+ });
+ });
+
+ it("generate correct metadata for icon when image is in subfolder", function () {
+ var config = {
+ icon: ["assets\\images\\logo.png"]
+ },
+ xmlObject = {};
+
+ spyOn(fs, "existsSync").andReturn(true);
+ spyOn(wrench, "readdirSyncRecursive").andReturn(mockOSReturnFiles([
+ 'fr',
+ 'fr/assets/images/logo.png'
+ ]));
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "icon");
+
+ expect(xmlObject.icon).toBeDefined();
+ expect(xmlObject.icon.image).toBeDefined();
+ expect(xmlObject.icon.image.length).toBe(2);
+ expect(xmlObject.icon.image).toContain({
+ _value: "assets/images/logo.png"
+ });
+ expect(xmlObject.icon.image).toContain({
+ text: {
+ _attr: {
+ "xml:lang": "fr"
+ },
+ _value: "locales/fr/assets/images/logo.png"
+ }
+ });
+ });
+
+ it("generate correct metadata for icon when image is in subfolder and OS is windows", function () {
+ var config = {
+ icon: ["assets\\images\\logo.png"]
+ },
+ xmlObject = {};
+
+ spyOn(pkgrUtils, 'isWindows').andReturn(true);
+ spyOn(fs, "existsSync").andReturn(true);
+ spyOn(wrench, "readdirSyncRecursive").andReturn(mockOSReturnFiles([
+ 'fr',
+ 'fr\\assets\\images\\logo.png'
+ ]));
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "icon");
+
+ expect(xmlObject.icon).toBeDefined();
+ expect(xmlObject.icon.image).toBeDefined();
+ expect(xmlObject.icon.image.length).toBe(1);
+ expect(xmlObject.icon.image).toContain({
+ _value: "assets/images/logo.png"
+ });
+ });
+
+ it("generate correct metadata for splash and OS is *nx", function () {
+ var config = {
+ "rim:splash": ["splash-1280x768.jpg", "splash-768x1280.jpg"]
+ },
+ xmlObject = {};
+
+ spyOn(pkgrUtils, 'isWindows').andReturn(false);
+ spyOn(fs, "existsSync").andReturn(true);
+ spyOn(wrench, "readdirSyncRecursive").andReturn(mockOSReturnFiles([
+ 'fr',
+ 'fr/splash-1280x768.jpg',
+ 'fr/splash-768x1280.jpg'
+ ]));
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "rim:splash");
+
+ expect(xmlObject.splashScreens).toBeDefined();
+ expect(xmlObject.splashScreens.image).toBeDefined();
+ expect(xmlObject.splashScreens.image.length).toBe(4);
+ expect(xmlObject.splashScreens.image).toContain({
+ _value: "splash-1280x768.jpg"
+ });
+ expect(xmlObject.splashScreens.image).toContain({
+ _value: "splash-768x1280.jpg"
+ });
+ expect(xmlObject.splashScreens.image).toContain({
+ text: {
+ _attr: {
+ "xml:lang": "fr"
+ },
+ _value: "locales/fr/splash-1280x768.jpg"
+ }
+ });
+ expect(xmlObject.splashScreens.image).toContain({
+ text: {
+ _attr: {
+ "xml:lang": "fr"
+ },
+ _value: "locales/fr/splash-768x1280.jpg"
+ }
+ });
+ });
+
+ it("generate correct metadata for splash when locales folder does not exist", function () {
+ var config = {
+ "rim:splash": ["splash-1280x768.jpg", "splash-768x1280.jpg"]
+ },
+ xmlObject = {};
+
+ spyOn(fs, "existsSync").andReturn(false);
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "rim:splash");
+
+ expect(xmlObject.splashScreens).toBeDefined();
+ expect(xmlObject.splashScreens.image).toBeDefined();
+ expect(xmlObject.splashScreens.image.length).toBe(2);
+ expect(xmlObject.splashScreens.image).toContain({
+ _value: "splash-1280x768.jpg"
+ });
+ expect(xmlObject.splashScreens.image).toContain({
+ _value: "splash-768x1280.jpg"
+ });
+ });
+
+ it("generate correct metadata for splash when locale folder does not contain matching image", function () {
+ var config = {
+ "rim:splash": ["splash-1280x768.jpg", "splash-768x1280.jpg"]
+ },
+ xmlObject = {};
+
+ spyOn(fs, "existsSync").andReturn(true);
+ spyOn(wrench, "readdirSyncRecursive").andReturn(mockOSReturnFiles([
+ 'fr',
+ 'fr/splash-1280x768-mismatch.jpg',
+ 'fr/splash-768x1280.jpg'
+ ]));
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "rim:splash");
+
+ expect(xmlObject.splashScreens).toBeDefined();
+ expect(xmlObject.splashScreens.image).toBeDefined();
+ expect(xmlObject.splashScreens.image.length).toBe(3);
+ expect(xmlObject.splashScreens.image).toContain({
+ _value: "splash-1280x768.jpg"
+ });
+ expect(xmlObject.splashScreens.image).toContain({
+ _value: "splash-768x1280.jpg"
+ });
+ expect(xmlObject.splashScreens.image).toContain({
+ text: {
+ _attr: {
+ "xml:lang": "fr"
+ },
+ _value: "locales/fr/splash-768x1280.jpg"
+ }
+ });
+ });
+
+ it("generate correct metadata for splash when image is in subfolder", function () {
+ var config = {
+ "rim:splash": ["assets\\images\\splash-1280x768.jpg", "assets\\images\\splash-768x1280.jpg"]
+ },
+ xmlObject = {};
+
+ spyOn(fs, "existsSync").andReturn(true);
+ spyOn(wrench, "readdirSyncRecursive").andReturn(mockOSReturnFiles([
+ 'fr',
+ 'fr/assets/images/splash-1280x768.jpg',
+ 'fr/assets/images/splash-768x1280.jpg'
+ ]));
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "rim:splash");
+
+ expect(xmlObject.splashScreens).toBeDefined();
+ expect(xmlObject.splashScreens.image).toBeDefined();
+ expect(xmlObject.splashScreens.image.length).toBe(4);
+ expect(xmlObject.splashScreens.image).toContain({
+ _value: "assets/images/splash-1280x768.jpg"
+ });
+ expect(xmlObject.splashScreens.image).toContain({
+ _value: "assets/images/splash-768x1280.jpg"
+ });
+ expect(xmlObject.splashScreens.image).toContain({
+ text: {
+ _attr: {
+ "xml:lang": "fr"
+ },
+ _value: "locales/fr/assets/images/splash-1280x768.jpg"
+ }
+ });
+ expect(xmlObject.splashScreens.image).toContain({
+ text: {
+ _attr: {
+ "xml:lang": "fr"
+ },
+ _value: "locales/fr/assets/images/splash-768x1280.jpg"
+ }
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/logger.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/logger.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/logger.js
new file mode 100644
index 0000000..c8aadb9
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/logger.js
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var srcPath = __dirname + "/../../../../../templates/project/cordova/lib/",
+ logger = require(srcPath + "logger");
+
+describe("logger", function () {
+ describe("when the log level is verbose", function () {
+ beforeEach(function () {
+ spyOn(console, "log");
+ logger.level('verbose');
+ });
+
+ it("logs info messages", function () {
+ logger.info("cheese is made from milk");
+ expect(console.log).toHaveBeenCalledWith("[INFO] cheese is made from milk");
+ });
+
+ it("logs error messages", function () {
+ logger.error("PC LOAD LETTER");
+ expect(console.log).toHaveBeenCalledWith("[ERROR] PC LOAD LETTER");
+ });
+
+ it("logs warning messages", function () {
+ logger.warn("beware the ides of march");
+ expect(console.log).toHaveBeenCalledWith("[WARN] beware the ides of march");
+ });
+
+ it("logs messages", function () {
+ logger.log("Hulk Smash!");
+ expect(console.log).toHaveBeenCalledWith("[BUILD] Hulk Smash!");
+ });
+ });
+
+ describe("when the log level is warn", function () {
+ beforeEach(function () {
+ spyOn(console, "log");
+ logger.level('warn');
+ });
+
+ it("doesn't log info messages", function () {
+ logger.info("cheese is made from milk");
+ expect(console.log).not.toHaveBeenCalledWith("[INFO] cheese is made from milk");
+ });
+
+ it("logs error messages", function () {
+ logger.error("PC LOAD LETTER");
+ expect(console.log).toHaveBeenCalledWith("[ERROR] PC LOAD LETTER");
+ });
+
+ it("logs warning messages", function () {
+ logger.warn("beware the ides of march");
+ expect(console.log).toHaveBeenCalledWith("[WARN] beware the ides of march");
+ });
+
+ it("logs messages", function () {
+ logger.log("Hulk Smash!");
+ expect(console.log).toHaveBeenCalledWith("[BUILD] Hulk Smash!");
+ });
+ });
+
+ describe("when the log level is error", function () {
+ beforeEach(function () {
+ spyOn(console, "log");
+ logger.level('error');
+ });
+
+ it("doesn't log info messages", function () {
+ logger.info("cheese is made from milk");
+ expect(console.log).not.toHaveBeenCalledWith("[INFO] cheese is made from milk");
+ });
+
+ it("logs error messages", function () {
+ logger.error("PC LOAD LETTER");
+ expect(console.log).toHaveBeenCalledWith("[ERROR] PC LOAD LETTER");
+ });
+
+ it("doesn't log warning messages", function () {
+ logger.warn("beware the ides of march");
+ expect(console.log).not.toHaveBeenCalledWith("[WARN] beware the ides of march");
+ });
+
+ it("logs messages", function () {
+ logger.log("Hulk Smash!");
+ expect(console.log).toHaveBeenCalledWith("[BUILD] Hulk Smash!");
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/native-packager.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/native-packager.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/native-packager.js
new file mode 100644
index 0000000..a4ab63e
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/native-packager.js
@@ -0,0 +1,347 @@
+var path = require("path"),
+ util = require("util"),
+ fs = require("fs"),
+ childProcess = require("child_process"),
+ wrench = require("wrench"),
+ srcPath = __dirname + "/../../../../../templates/project/cordova/lib/",
+ nativePkgr = require(srcPath + "/native-packager"),
+ pkgrUtils = require(srcPath + "/packager-utils"),
+ testUtils = require("./test-utilities"),
+ testData = require("./test-data"),
+ logger = require(srcPath + "logger"),
+ localize = require(srcPath + "/localize"),
+ conf = require(srcPath + "./conf"),
+ callback,
+ config,
+ session,
+ target,
+ result,
+ orgDebugEnabled,
+ orgDebugTokenPath,
+ NL = pkgrUtils.isWindows() ? "\r\n" : "\n";
+
+describe("Native packager", function () {
+ beforeEach(function () {
+ callback = jasmine.createSpy();
+ config = testData.config;
+ session = testData.session;
+ target = session.targets[0];
+ result = {
+ stdout: {
+ on: jasmine.createSpy()
+ },
+ stderr: {
+ on: jasmine.createSpy()
+ },
+ on: function (eventName, callback) {
+ callback(0);
+ }
+ };
+
+ // Store original debug token setting and later restore them in afterEach
+ // to be able to test positive and negative cases of each.
+ orgDebugEnabled = session.debug;
+ orgDebugTokenPath = session.conf.DEBUG_TOKEN;
+
+ spyOn(wrench, "readdirSyncRecursive").andReturn(["abc", "xyz"]);
+ spyOn(fs, "statSync").andReturn({
+ isDirectory: function () {
+ return false;
+ }
+ });
+ spyOn(fs, "writeFileSync");
+ spyOn(childProcess, "spawn").andReturn(result);
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ //Return true if this is the bbndk folder check
+ return path.indexOf("bbndk") !== -1;
+ });
+ });
+
+ afterEach(function () {
+ session.debug = orgDebugEnabled;
+ session.conf.DEBUG_TOKEN = orgDebugTokenPath;
+ });
+
+ it("should not display empty messages in logger", function () {
+ spyOn(pkgrUtils, "writeFile");
+ spyOn(logger, "warn");
+ spyOn(logger, "error");
+ spyOn(logger, "info");
+
+ nativePkgr.exec(session, target, testData.config, callback);
+
+ expect(logger.warn).not.toHaveBeenCalledWith("");
+ expect(logger.error).not.toHaveBeenCalledWith("");
+ expect(logger.info).not.toHaveBeenCalledWith("");
+ });
+
+ it("shows debug token warning when path to file is not valid", function () {
+ spyOn(pkgrUtils, "writeFile");
+ spyOn(logger, "warn");
+
+ session.debug = true;
+ //Current time will ensure that the file doesn't exist.
+ session.conf.DEBUG_TOKEN = new Date().getTime() + ".bar";
+
+ nativePkgr.exec(session, target, testData.config, callback);
+
+ expect(logger.warn).toHaveBeenCalledWith(localize.translate("EXCEPTION_DEBUG_TOKEN_NOT_FOUND"));
+ });
+
+ it("won't show debug token warning when -d options wasn't provided", function () {
+ spyOn(pkgrUtils, "writeFile");
+ spyOn(logger, "warn");
+
+ session.debug = false;
+ //Current time will ensure that the file doesn't exist.
+ session.conf.DEBUG_TOKEN = new Date().getTime() + ".bar";
+
+ nativePkgr.exec(session, target, testData.config, callback);
+
+ expect(logger.warn).not.toHaveBeenCalled();
+ });
+
+ it("shows debug token warning when debug token not a .bar file", function () {
+ spyOn(pkgrUtils, "writeFile");
+ spyOn(logger, "warn");
+
+ session.debug = true;
+ //Current time will ensure that the file doesn't exist.
+ session.conf.DEBUG_TOKEN = new Date().getTime() + ".xyz";
+
+ nativePkgr.exec(session, target, testData.config, callback);
+ expect(logger.warn).toHaveBeenCalledWith(localize.translate("EXCEPTION_DEBUG_TOKEN_WRONG_FILE_EXTENSION"));
+ });
+
+ it("exec blackberry-nativepackager", function () {
+ var bbTabletXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
+ "<qnx><id>" + config.id + "</id>" +
+ "<versionNumber>" + config.version + "</versionNumber>" +
+ "<author>" + config.author + "</author>" +
+ "<asset entry=\"true\" type=\"qnx/elf\">wwe</asset>" +
+ "<asset>abc</asset>" +
+ "<asset>xyz</asset>" +
+ "<entryPointType>Qnx/WebKit</entryPointType>" +
+ "<cascadesTheme>" + config.theme + "</cascadesTheme>" +
+ "<initialWindow><systemChrome>none</systemChrome><transparent>true</transparent><autoOrients>true</autoOrients></initialWindow>",
+ bbTabletXML2 = "<permission system=\"true\">run_native</permission>" +
+ "<permission system=\"false\">access_internet</permission>" +
+ "<name>" + config.name['default'] + "</name>" +
+ "<description>" + config.description['default'] + "</description></qnx>",
+ cmd = path.normalize(session.conf.DEPENDENCIES_TOOLS + "/bin/blackberry-nativepackager" + (pkgrUtils.isWindows() ? ".bat" : ""));
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (sourceDir, outputDir, data) {
+ expect(sourceDir).toEqual(session.sourceDir);
+ expect(outputDir).toEqual(conf.BAR_DESCRIPTOR);
+
+ //We have to validate the xml data in 2 chucks, because the WEBWORKS_VERSION env variable
+ //has a different value for SCM builds and we can't mock the webworks-info file
+ expect(data).toContain(bbTabletXML);
+ expect(data).toContain(bbTabletXML2);
+ });
+ nativePkgr.exec(session, target, testData.config, callback);
+
+ expect(fs.writeFileSync).toHaveBeenCalledWith(jasmine.any(String), jasmine.any(String));
+ expect(childProcess.spawn).toHaveBeenCalledWith(cmd, ["@options"], {"cwd": session.sourceDir, "env": process.env});
+ expect(callback).toHaveBeenCalledWith(0);
+ });
+
+ it("makes sure slog2 logging is enabled in debug mode", function () {
+ var tabletXMLEntry = "<env value=\"slog2\" var=\"CONSOLE_MODE\"></env>";
+
+ //Silence the logger during unit tests
+ spyOn(logger, "warn").andCallFake(function () { });
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (sourceDir, outputDir, data) {
+ expect(data).toContain(tabletXMLEntry);
+ });
+
+ session.debug = true;
+ nativePkgr.exec(session, target, testData.config, callback);
+ });
+
+ it("makes sure slog2 logging is not enabled when not in debug mode", function () {
+ var tabletXMLEntry = "<env value=\"slog2\" var=\"CONSOLE_MODE\"></env>";
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (sourceDir, outputDir, data) {
+ expect(data).not.toContain(tabletXMLEntry);
+ });
+
+ session.debug = false;
+ nativePkgr.exec(session, target, testData.config, callback);
+ });
+
+ it("can process application name", function () {
+ var config = testUtils.cloneObj(testData.config);
+ config.name = {"default": "API Smoke Test"};
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (fileLocation, fileName, fileData) {
+ expect(fileData).toContain("<name>API Smoke Test</name>");
+ });
+
+ nativePkgr.exec(session, target, config, callback);
+
+ });
+
+ it("can process localized application name", function () {
+ var config = testUtils.cloneObj(testData.config);
+ config.name = {"FR": "API Smoke Test - FR"};
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (fileLocation, fileName, fileData) {
+ expect(fileData).toContain('<name><text xml:lang="FR">API Smoke Test - FR</text></name>');
+ });
+
+ nativePkgr.exec(session, target, config, callback);
+ });
+
+ it("can process mutiple application names", function () {
+ var config = testUtils.cloneObj(testData.config);
+ config.name = {
+ "default": "API Smoke Test",
+ "EN": "API Smoke Test - EN",
+ "FR": "API Smoke Test - FR"
+ };
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (fileLocation, fileName, fileData) {
+ expect(fileData).toContain('<name>API Smoke Test<text xml:lang="EN">API Smoke Test - EN</text><text xml:lang="FR">API Smoke Test - FR</text></name>');
+ });
+
+ nativePkgr.exec(session, target, config, callback);
+ });
+
+ it("can process application description", function () {
+ var config = testUtils.cloneObj(testData.config);
+ config.description = {"default": "My app description"};
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (fileLocation, fileName, fileData) {
+ expect(fileData).toContain("<description>My app description</description>");
+ });
+
+ nativePkgr.exec(session, target, config, callback);
+
+ });
+
+ it("can process localized application description", function () {
+ var config = testUtils.cloneObj(testData.config);
+ config.description = {"FR": "My app description - FR"};
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (fileLocation, fileName, fileData) {
+ expect(fileData).toContain('<description><text xml:lang="FR">My app description - FR</text></description>');
+ });
+
+ nativePkgr.exec(session, target, config, callback);
+ });
+
+ it("can process mutiple application descriptions", function () {
+ var config = testUtils.cloneObj(testData.config);
+ config.description = {
+ "default": "My app description",
+ "EN": "My app description - EN",
+ "FR": "My app description - FR"
+ };
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (fileLocation, fileName, fileData) {
+ expect(fileData).toContain('<description>My app description<text xml:lang="EN">My app description - EN</text><text xml:lang="FR">My app description - FR</text></description>');
+ });
+
+ nativePkgr.exec(session, target, config, callback);
+ });
+
+ it("can process permissions with no attributes", function () {
+ var config = testUtils.cloneObj(testData.config);
+ config.permissions = ['read_device_identifying_information'];
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (fileLocation, fileName, fileData) {
+ expect(fileData).toContain("<permission>read_device_identifying_information</permission>");
+ });
+
+ nativePkgr.exec(session, target, config, callback);
+
+ });
+
+ it("can process permissions with attributes", function () {
+ var config = testUtils.cloneObj(testData.config);
+ config.permissions = [{ '#': 'systemPerm', '@': {"system": "true"}}];
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (fileLocation, fileName, fileData) {
+ expect(fileData).toContain("<permission system=\"true\">systemPerm</permission>");
+ });
+
+ nativePkgr.exec(session, target, config, callback);
+
+ });
+
+ it("adds the mandatory permissions for webworks", function () {
+ var config = testUtils.cloneObj(testData.config);
+ config.permissions = [];
+
+ spyOn(pkgrUtils, "writeFile").andCallFake(function (fileLocation, fileName, fileData) {
+ expect(fileData).toContain("<permission system=\"false\">access_internet</permission>");
+ expect(fileData).toContain("<permission system=\"true\">run_native</permission>");
+ });
+
+ nativePkgr.exec(session, target, config, callback);
+
+ });
+
+ it("omits -devMode when signing and specifying -d", function () {
+ testUtils.mockResolve(path);
+ spyOn(pkgrUtils, "writeFile");
+
+ var session = testUtils.cloneObj(testData.session),
+ config = testUtils.cloneObj(testData.config),
+ target = "device",
+ optionsFile = "-package" + NL +
+ "-buildId" + NL +
+ "100" + NL +
+ path.normalize("c:/device/Demo.bar") + NL +
+ "-barVersion" + NL +
+ "1.5" + NL +
+ "-C" + NL +
+ path.normalize("c:/src/") + NL +
+ conf.BAR_DESCRIPTOR + NL +
+ path.normalize("c:/src/abc") + NL +
+ path.normalize("c:/src/xyz") + NL;
+
+ //Set signing params [-g --buildId]
+ session.keystore = path.normalize("c:/author.p12");
+ session.storepass = "password";
+ config.buildId = "100";
+
+ session.barPath = path.normalize("c:/%s/" + "Demo.bar");
+ session.sourceDir = path.normalize("c:/src/");
+ session.isSigningRequired = function () {
+ return true;
+ };
+
+ //Set -d param
+ session.debug = "";
+
+ nativePkgr.exec(session, target, config, callback);
+
+ //options file should NOT contain -devMode
+ expect(fs.writeFileSync).toHaveBeenCalledWith(jasmine.any(String), optionsFile);
+ });
+
+ it("exec blackberry-nativepackager with additional params", function () {
+ var cmd = path.normalize(session.conf.DEPENDENCIES_TOOLS + "/bin/blackberry-nativepackager" + (pkgrUtils.isWindows() ? ".bat" : ""));
+ spyOn(pkgrUtils, "writeFile");
+
+ session.getParams = jasmine.createSpy("session getParams").andReturn({
+ "-installApp": "",
+ "-device": "192.168.1.114",
+ "-password": "abc"
+ });
+
+ nativePkgr.exec(session, "simulator", testData.config, callback);
+
+ expect(fs.writeFileSync.mostRecentCall.args[0]).toBe(path.resolve(session.sourceDir, "options"));
+ expect(fs.writeFileSync.mostRecentCall.args[1]).toContain("-package" + NL);
+ expect(fs.writeFileSync.mostRecentCall.args[1]).toContain("-password" + NL);
+ expect(fs.writeFileSync.mostRecentCall.args[1]).toContain("abc" + NL);
+ expect(fs.writeFileSync.mostRecentCall.args[1]).toContain("-device" + NL);
+ expect(fs.writeFileSync.mostRecentCall.args[1]).toContain("192.168.1.114" + NL);
+ expect(fs.writeFileSync.mostRecentCall.args[1]).toContain("-installApp" + NL);
+ expect(childProcess.spawn).toHaveBeenCalledWith(cmd, ["@options"], {"cwd": session.sourceDir, "env": process.env});
+ expect(callback).toHaveBeenCalledWith(0);
+ });
+});
[38/38] git commit: 2.8.0 npm version
Posted by fi...@apache.org.
2.8.0 npm version
Project: http://git-wip-us.apache.org/repos/asf/cordova-cli/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-cli/commit/c65a9ced
Tree: http://git-wip-us.apache.org/repos/asf/cordova-cli/tree/c65a9ced
Diff: http://git-wip-us.apache.org/repos/asf/cordova-cli/diff/c65a9ced
Branch: refs/heads/master2
Commit: c65a9ced5f38465a558fd3aa54f7bf57342dfa38
Parents: 88ad654
Author: Fil Maj <ma...@gmail.com>
Authored: Thu May 23 16:41:00 2013 -0700
Committer: Fil Maj <ma...@gmail.com>
Committed: Thu May 23 16:41:00 2013 -0700
----------------------------------------------------------------------
package.json | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/c65a9ced/package.json
----------------------------------------------------------------------
diff --git a/package.json b/package.json
index 24789be..7f807f8 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "cordova",
- "version": "2.7.4",
+ "version": "2.8.0",
"preferGlobal": "true",
"description": "Cordova command line interface tool",
"main": "cordova",
[23/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/plugins/SplashScreen/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/plugins/SplashScreen/index.js b/lib/cordova-blackberry/bin/test/plugins/SplashScreen/index.js
new file mode 100644
index 0000000..658ce3d
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/plugins/SplashScreen/index.js
@@ -0,0 +1,82 @@
+/*
+* Copyright 2013 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+describe("SplashScreen", function () {
+ var _apiDir = __dirname + "./../../../../plugins/SplashScreen/src/blackberry10/",
+ index,
+ mockedEnv = {
+ response: {
+ send: jasmine.createSpy()
+ }
+ },
+ mockedApplication = {
+ windowVisible: undefined
+ };
+
+ beforeEach(function () {
+ index = require(_apiDir + "index");
+ mockedEnv.response.send.reset();
+ });
+
+ afterEach(function () {
+ index = null;
+ delete require.cache[require.resolve(_apiDir + "index")];
+ });
+ describe("show", function () {
+ beforeEach(function () {
+ GLOBAL.PluginResult = function (args, env) {};
+ GLOBAL.PluginResult.prototype.error = jasmine.createSpy();
+ });
+
+ afterEach(function () {
+ delete GLOBAL.PluginResult;
+ });
+
+ it("calls PluginResult.error if show is called", function () {
+ index.show();
+
+ expect(PluginResult.prototype.error).toHaveBeenCalledWith("Not supported on platform", false);
+ });
+ });
+
+ describe("hide", function () {
+ beforeEach(function () {
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ getApplication: function () {
+ return mockedApplication;
+ }
+ }
+ }
+ };
+
+ GLOBAL.PluginResult = function (args, env) {};
+ GLOBAL.PluginResult.prototype.ok = jasmine.createSpy();
+ });
+
+ afterEach(function () {
+ delete GLOBAL.window;
+ delete GLOBAL.PluginResult;
+ });
+
+ it("calls PluginResult.ok if hide is called", function () {
+ index.hide();
+
+ expect(mockedApplication.windowVisible).toBeTruthy();
+ expect(PluginResult.prototype.ok).toHaveBeenCalledWith(undefined, false);
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/build.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/build.xml b/lib/cordova-blackberry/build.xml
deleted file mode 100644
index dcddbb6..0000000
--- a/lib/cordova-blackberry/build.xml
+++ /dev/null
@@ -1,342 +0,0 @@
-<project name="Create & Update a Cordova BlackBerry WebWorks Project" default="help">
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
- <!-- LOAD VERSION -->
-
- <loadfile property="version" srcFile="VERSION">
- <filterchain>
- <striplinebreaks/>
- </filterchain>
- </loadfile>
-
- <!-- LOAD PROPERTIES -->
-
- <property name="template.project.dir" location="bin/templates/project" />
- <property name="template.dist.dir" location="bin/templates/dist" />
-
- <property name="build.dir" location="build" />
- <property name="update.dir" value="lib/cordova.${version}" />
-
- <property name="dist.path" location="dist" />
- <property name="dist.www.path" location="${dist.path}/www" />
- <property name="dist.project.path" location="${dist.path}/sample" />
-
- <property name="jar.src" location="framework/ext/src" />
- <property name="jar.path" value="ext" />
- <property name="jar.basename" value="cordova.${version}.jar" />
- <property name="jar.file" value="${jar.path}/${jar.basename}" />
-
- <property name="playbook.js.path" value="javascript/playbook" />
- <property name="playbook.ext.src" location="framework/ext-air" />
- <property name="playbook.ext.path" value="ext-air" />
-
- <property name="qnx.js.path" value="javascript/qnx" />
- <property name="qnx.ext.src" location="framework/ext-qnx" />
- <property name="qnx.ext.path" value="ext-qnx" />
-
- <property name="js.src" location="javascript" />
- <property name="js.path" value="javascript" />
- <property name="js.basename" value="cordova-${version}.js" />
- <property name="js.file" value="${js.path}/${js.basename}" />
-
- <!-- BUILD JAVASCRIPT -->
-
- <target name="build-javascript">
- <!-- BB Javascript -->
- <mkdir dir="${build.dir}/${js.path}" />
- <copy file="${js.src}/cordova.blackberry.js" tofile="${build.dir}/${js.file}" />
- </target>
-
- <!-- BUILD BLACKBERRY EXTENSION -->
-
- <target name="build-bb-extension">
- <mkdir dir="${build.dir}/${jar.path}" />
-
- <zip destfile="${build.dir}/${jar.file}">
- <fileset dir="${jar.src}" includes="library.xml" />
- <fileset dir="${jar.src}" includes="**/*.java" />
- </zip>
- </target>
-
- <!-- BUILD PLAYBOOK EXTENSION -->
-
- <target name="build-pb-extension">
-
- <!-- Copy Ext -->
- <mkdir dir="${build.dir}/${playbook.ext.path}" />
- <copy todir="${build.dir}/${playbook.ext.path}">
- <fileset dir="${playbook.ext.src}" />
- </copy>
- </target>
-
- <!-- BUILD QNX EXTENSION -->
-
- <target name="build-qnx-extension">
-
- <!-- Copy Ext -->
- <mkdir dir="${build.dir}/${qnx.ext.path}" />
- <copy todir="${build.dir}/${qnx.ext.path}">
- <fileset dir="${qnx.ext.src}" />
- </copy>
- </target>
-
- <!-- CREATE A PROJECT -->
- <target name="create" depends="clean, build-javascript, build-bb-extension, build-pb-extension, build-qnx-extension">
- <fail unless="project.path" message="You must give a project PATH. Use the argument -Dproject.path="C:\dev\my_project"" />
-
- <available file="${project.path}" property="project.exists" />
- <fail if="project.exists" message="The project path must be an empty directory." />
-
- <!-- create project using template directory -->
- <mkdir dir="${project.path}" />
- <copy todir="${project.path}">
- <fileset dir="${template.project.dir}" />
- </copy>
-
- <!-- change file permission for cordova scripts because ant copy doesn't preserve file permissions -->
- <chmod dir="${project.path}/cordova" perm="700" includes="*"/>
-
- <!-- update project files to reference cordova.x.x.x.js -->
- <replaceregexp match="cordova\.js" replace="${js.basename}" byline="true">
- <fileset file="${project.path}/www/index.html" />
- <fileset file="${project.path}/build.xml" />
- </replaceregexp>
-
- <!-- copy cordova.js -->
- <copy todir="${project.path}/www">
- <fileset dir="${build.dir}/${js.path}" />
- </copy>
-
- <!-- copy ext/ -->
- <copy todir="${project.path}/www/ext">
- <fileset dir="${build.dir}/${jar.path}" />
- </copy>
-
- <!-- copy ext-air/ -->
- <copy todir="${project.path}/www/ext-air">
- <fileset dir="${build.dir}/${playbook.ext.path}" />
- </copy>
-
- <!-- copy ext-qnx/ -->
- <copy todir="${project.path}/www/ext-qnx">
- <fileset dir="${build.dir}/${qnx.ext.path}" />
- </copy>
-
- <!-- save release -->
- <mkdir dir="${project.path}/${update.dir}" />
- <copy todir="${project.path}/${update.dir}">
- <fileset dir="${build.dir}" />
- </copy>
-
- <echo>
-Project Creation Complete!
-==========================
-
-Getting Started:
-----------------
-
- cd ${project.path}
-
- ant help
- </echo>
- </target>
-
- <!-- DISTRIBUTION -->
- <target name="dist" depends="">
- <!-- create a sample project -->
- <antcall target="create">
- <param name="project.path" value="${dist.project.path}" />
- </antcall>
-
- <!-- copy dist template (README.md) -->
- <copy todir="${dist.path}">
- <fileset dir="${template.dist.dir}" />
- </copy>
-
- <!-- change file permission for cordova scripts because ant copy doesn't preserve file permissions -->
- <chmod dir="${dist.path}/sample/cordova" perm="700" includes="*" />
-
- <!-- copy cordova.jar -->
- <copy todir="${dist.www.path}/ext">
- <fileset dir="${build.dir}/${jar.path}" />
- </copy>
-
- <!-- copy ext-air/ -->
- <copy todir="${dist.www.path}/ext-air">
- <fileset dir="${build.dir}/${playbook.ext.path}" />
- </copy>
-
- <!-- copy ext-qnx/ -->
- <copy todir="${dist.www.path}/ext-qnx">
- <fileset dir="${build.dir}/${qnx.ext.path}" />
- </copy>
-
- <!-- copy cordova.js -->
- <copy todir="${dist.www.path}">
- <fileset dir="${build.dir}/${js.path}" />
- </copy>
-
- <!-- copy config.xml -->
- <copy todir="${dist.www.path}">
- <fileset file="${template.project.dir}/www/config.xml" />
- </copy>
-
- <!-- copy plugins.xml -->
- <copy todir="${dist.www.path}">
- <fileset file="${template.project.dir}/www/plugins.xml" />
- </copy>
-
- <!-- update config.xml to have a default name-->
- <replace file="${dist.project.path}/www/config.xml" token="__NAME__" value="cordovaExample"/>
- <replace file="${dist.project.path}/www/config.xml" token="__PACKAGE__" value="org.apache.cordova.example"/>
- <echo>
-Distribution Complete!
-======================
-
-Version:
---------
-
- ${version}
-
-Path:
------
-
- ${dist.path}
- </echo>
- </target>
-
- <target name="version">
- <replace dir="." token="${version}" value="${value}" />
-
- <echo>
-Version Update Complete!
-========================
-
-Version:
---------
-
- Previous: ${version}
- Current: ${value}
-
-Remember to:
-------------
-
- Review and commit the version update.
-
- $ git diff
- $ git commit -am "Update to version ${value}"
- $ git tag ${value}
- </echo>
- </target>
-
- <!-- UPDATE A PROJECT -->
-
- <target name="update" depends="clean, build-javascript, build-bb-extension, build-pb-extension, build-qnx-extension">
- <fail unless="project.path" message="You must give a project PATH. Use the argument -Dproject.path="C:\dev\my_project"" />
-
- <available file="${project.path}" property="project.exists" />
- <fail unless="project.exists" message="The project path cannot be empty." />
-
- <!-- save release -->
- <mkdir dir="${project.path}/${update.dir}" />
- <copy todir="${project.path}/${update.dir}">
- <fileset dir="${build.dir}" />
- </copy>
-
- <echo>
-Update complete!
-================
-
- Cordova ${version} has been created.
-
- Update does not alter your project files.
-
- See below for instructions to install Cordova ${version}.
-
-Where:
-------
-
- ${project.path}/${update.dir}
-
-Install:
---------
-
- 1. Install the Java Extension:
-
- - delete /www/${jar.path}/cordova.jar
-
- - copy /${update.dir}/${jar.file}
- to /www/${jar.file}
-
- 2. Install the JavaScript library:
-
- - delete /www/cordova.js
-
- - copy /${update.dir}/${js.file}
- to /www/${js.basename}
-
- 3. Update JavaScript references:
-
- - <script type="text/javascript" src="${js.basename}"></script>
- </echo>
- </target>
-
- <!-- CLEAN -->
-
- <target name="clean">
- <delete dir="${build.dir}" />
- <delete dir="${dist.path}" />
- </target>
-
- <!-- HELP -->
-
- <target name="help">
- <echo>
-NAME
- ${ant.project.name}
-
-SYNOPSIS
- ant COMMAND [-D<argument>=<value>]...
-
-DESCRIPTION
- This tool allows you to create and update Cordova-BlackBerry-WebWorks projects.
- You will want to run update after you have updated the framework source.
- In other words, when you <git pull origin master>.
-
-COMMANDS
- help ............ Show this help menu.
- ant, ant help
-
- create .......... Create a new project
- ant create PATH
- ant create -Dproject.path="C:\dev\my_project"
-
- update .......... Update an existing project
- ant update PATH
- ant update -Dproject.path="C:\dev\my_project"
-
- dist ............ Create a Cordova distribution build
- ant dist
-
- version ......... Update Cordova version
- ant version VERSION
- ant version -Dvalue="1.0.0"
- </echo>
- </target>
-</project>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/bootstrap/index.html
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/bootstrap/index.html b/lib/cordova-blackberry/framework/bootstrap/index.html
new file mode 100644
index 0000000..6e3b028
--- /dev/null
+++ b/lib/cordova-blackberry/framework/bootstrap/index.html
@@ -0,0 +1,23 @@
+<!DOCTYPE HTML>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="user-scalable=no, target-densitydpi=device-dpi, width=device-width">
+ <title>WebWorks For BB10 Bootstrap</title>
+ <script src="./require.js"></script>
+ <script src="platform:///webplatform.js"></script>
+ <script src="./frameworkModules.js"></script>
+ <script>
+ function start() {
+ //Must load jnext first, as there seemed to be a race condition for if it was defined before it was used
+ require("lib/jnext.js");
+ require(frameworkModules, function () {
+ require('lib/framework').start();
+ });
+ }
+ </script>
+ </head>
+ <body onload="start();">
+ I am the man behind the curtain.
+ </body>
+</html>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/bootstrap/require.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/bootstrap/require.js b/lib/cordova-blackberry/framework/bootstrap/require.js
new file mode 100644
index 0000000..a68bfcc
--- /dev/null
+++ b/lib/cordova-blackberry/framework/bootstrap/require.js
@@ -0,0 +1,251 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var define,
+ require;
+
+(function () {
+ var unpreparedModules = {},
+ readyModules = {},
+ ACCEPTABLE_EXTENSIONS = [".js", ".json"],
+ DEFAULT_EXTENSION = ".js";
+
+ function hasValidExtension(moduleName) {
+ return ACCEPTABLE_EXTENSIONS.some(function (element, index, array) {
+ return moduleName.match("\\" + element + "$");
+ });
+ }
+
+
+ function normalizeName(originalName, baseName) {
+ var nameParts,
+ name = originalName.slice(0);
+ //remove ^local:// (if it exists) and .js$
+ //This will not work for local:// without a trailing js
+ name = name.replace(/(?:^local:\/\/)/, "");
+ if (name.charAt(0) === '.' && baseName) {
+ //Split the baseName and remove the final part (the module name)
+ nameParts = baseName.split('/');
+ nameParts.pop();
+ nameParts = nameParts.concat(name.split('/'));
+
+ name = nameParts.reduce(function (previous, current, index, array) {
+ var returnValue,
+ slashIndex;
+
+ //If previous is a dot, ignore it
+ //If previous is ever just .. we're screwed anyway
+ if (previous !== '.') {
+ returnValue = previous;
+ }
+
+ //If we have a .. then remove a chunk of previous
+ if (current === "..") {
+ slashIndex = previous.lastIndexOf('/');
+ //If there's no slash we're either screwed or we remove the final token
+ if (slashIndex !== -1) {
+ returnValue = previous.slice(0, previous.lastIndexOf('/'));
+ } else {
+ returnValue = "";
+ }
+ } else if (current !== '.') {
+ //Otherwise simply append anything not a .
+ //Only append a slash if we're not empty
+ if (returnValue.length) {
+ returnValue += "/";
+ }
+ returnValue += current;
+ }
+
+ return returnValue;
+ });
+
+ }
+
+ //If there is no acceptable extension tack on a .js
+ if (!hasValidExtension(name)) {
+ name = name + DEFAULT_EXTENSION;
+ }
+
+ return name;
+ }
+
+ function buildModule(name, dependencies, factory) {
+ var module = {exports: {}},
+ localRequire = function (moduleName) {
+ return require(moduleName, name);
+ },
+ args = [];
+ localRequire.toUrl = function (moduleName, baseName) {
+ return require.toUrl(moduleName, baseName || name);
+ };
+ dependencies.forEach(function (dependency) {
+ if (dependency === 'require') {
+ args.push(localRequire);
+ } else if (dependency === 'exports') {
+ args.push(module.exports);
+ } else if (dependency === 'module') {
+ args.push(module);
+ } else {
+ //This is because jshint cannot handle out of order functions
+ /*global loadModule:false */
+ args.push(loadModule(dependency));
+ /*global loadModule:true */
+ }
+ });
+
+ //No need to process dependencies, webworks only has require, exports, module
+ factory.apply(this, args);
+
+ //For full AMD we would need logic to also check the return value
+ return module.exports;
+
+ }
+
+ function getDefineString(moduleName, body) {
+ var evalString = 'define("' + moduleName + '", function (require, exports, module) {',
+ isJson = /\.json$/.test(moduleName);
+
+ evalString += isJson ? ' module.exports = ' : '';
+ evalString += body.replace(/^\s+|\s+$/g, '');
+ evalString += isJson ? ' ;' : '';
+ evalString += '});';
+
+ return evalString;
+ }
+
+ function loadModule(name, baseName) {
+ var normalizedName = normalizeName(name, baseName),
+ url,
+ xhr,
+ loadResult;
+ //Always check undefined first, this allows the user to redefine modules
+ //(Not used in WebWorks, although it is used in our unit tests)
+ if (unpreparedModules[normalizedName]) {
+ readyModules[normalizedName] = buildModule(normalizedName, unpreparedModules[normalizedName].dependencies, unpreparedModules[normalizedName].factory);
+ delete unpreparedModules[normalizedName];
+ }
+
+ //If the module does not exist, load the module from external source
+ //Webworks currently only loads APIs from across bridge
+ if (!readyModules[normalizedName]) {
+ //If the module to be loaded ends in .js then we will define it
+ //Also if baseName exists than we have a local require situation
+ if (hasValidExtension(name) || baseName) {
+ xhr = new XMLHttpRequest();
+ url = name;
+ //If the module to be loaded starts with local:// go over the bridge
+ //Else If the module to be loaded is a relative load it may not have .js extension which is needed
+ if (/^local:\/\//.test(name)) {
+ url = "http://localhost:8472/extensions/load/" + normalizedName.replace(/(?:^ext\/)(.+)(?:\/client.js$)/, "$1");
+
+ xhr.open("GET", url, false);
+ xhr.send(null);
+ try {
+ loadResult = JSON.parse(xhr.responseText);
+
+ loadResult.dependencies.forEach(function (dep) {
+ /*jshint evil:true */
+ eval(getDefineString(dep.moduleName, dep.body));
+ /*jshint evil:false */
+ });
+
+ //Trimming responseText to remove EOF chars
+ /*jshint evil:true */
+ eval(getDefineString(normalizedName, loadResult.client));
+ /*jshint evil:false */
+ } catch (err1) {
+ err1.message += ' in ' + url;
+ throw err1;
+ }
+ } else {
+ if (baseName) {
+ url = normalizedName;
+ }
+
+ xhr.open("GET", url, false);
+ xhr.send(null);
+ try {
+ //Trimming responseText to remove EOF chars
+ /*jshint evil:true */
+ eval(getDefineString(normalizedName, xhr.responseText));
+ /*jshint evil:false */
+ } catch (err) {
+ err.message += ' in ' + url;
+ throw err;
+ }
+ }
+
+ if (unpreparedModules[normalizedName]) {
+ readyModules[normalizedName] = buildModule(normalizedName, unpreparedModules[normalizedName].dependencies, unpreparedModules[normalizedName].factory);
+ delete unpreparedModules[normalizedName];
+ }
+ } else {
+ throw "module " + name + " cannot be found";
+ }
+
+ }
+
+ return readyModules[normalizedName];
+
+ }
+
+ //Use the AMD signature incase we ever want to change.
+ //For now we will only be using (name, baseName)
+ require = function (dependencies, callback) {
+ if (typeof dependencies === "string") {
+ //dependencies is the module name and callback is the relName
+ //relName is not part of the AMDJS spec, but we use it from localRequire
+ return loadModule(dependencies, callback);
+ } else if (Array.isArray(dependencies) && typeof callback === 'function') {
+ //Call it Asynchronously
+ setTimeout(function () {
+ buildModule(undefined, dependencies, callback);
+ }, 0);
+ }
+ };
+
+ require.toUrl = function (originalName, baseName) {
+ return normalizeName(originalName, baseName);
+ };
+
+ //Use the AMD signature incase we ever want to change.
+ //For now webworks will only be using (name, factory) signature.
+ define = function (name, dependencies, factory) {
+ if (typeof name === "string" && typeof dependencies === 'function') {
+ factory = dependencies;
+ dependencies = ['require', 'exports', 'module'];
+ }
+
+ //According to the AMDJS spec we should parse out the require statments
+ //from factory.toString and add those to the list of dependencies
+
+ //Normalize the name. Remove local:// and .js
+ name = normalizeName(name);
+ unpreparedModules[name] = {
+ dependencies: dependencies,
+ factory: factory
+ };
+ };
+}());
+
+//Export for use in node for unit tests
+if (typeof module === "object" && typeof require === "function") {
+ module.exports = {
+ require: require,
+ define: define
+ };
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/bootstrap/ui.html
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/bootstrap/ui.html b/lib/cordova-blackberry/framework/bootstrap/ui.html
new file mode 100644
index 0000000..98c94a0
--- /dev/null
+++ b/lib/cordova-blackberry/framework/bootstrap/ui.html
@@ -0,0 +1,73 @@
+<!-- Copyright 2012 Research In Motion Limited.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ -->
+<!DOCTYPE HTML>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
+ <title>Overlay WebView</title>
+ <link rel="stylesheet" href="platform:///ui-resources/styles/styles.css" type="text/css" media="screen" charset="utf-8">
+
+ <script src="../chrome/require.js" type="text/javascript"></script>
+ <script src="platform:///webplatform.js" type="text/javascript"></script>
+ <script src="platform:///i18n.js" type="text/javascript"></script>
+ <script src="platform:///ui-resources/index.js" type="text/javascript"></script>
+ </head>
+ <body>
+
+ <div id="contextMenuModal" style="display:none;"></div>
+<div id="contextMenu" class="hideMenu">
+ <div id="contextMenuHeader">
+ <div id="contextMenuHeadText"></div>
+ <div id="contextMenuSubheadText"></div>
+ </div>
+ <div id="contextMenuContent"></div>
+ <div id="contextMenuHandle"></div>
+ <div id="contextMenuDelete"></div>
+</div>
+
+ <div id="dialog" class="hidden">
+ <div class="dialog-top-third">
+ <div id="dialog-panel">
+ </div>
+ </div>
+ <div class="dialog-bottom-two-thirds">
+ </div>
+</div>
+
+ <div id="invocationlist" class="screenInner screenSlide removed">
+ <div id="cancelTitlebar"></div>
+ <div id="invocationListContent" class="targetList"></div>
+ <div id="targetLoader">
+ <div id="targetLoaderActivity" class="activityIndicator"></div>
+ </div>
+</div>
+
+ <div id="toaster" class="toaster"></div>
+
+
+ <div id="childwebviewcontrols"></div>
+
+ <div id="formcontrolPanel">
+ <div id="formcontrol">
+ <button id="formcontrol_previous"/>
+ <button id="formcontrol_next"/>
+ <button id="formcontrol_submit"/>
+ </div>
+ </div>
+
+ </body>
+</html>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext-air/Cordova_Network/library.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext-air/Cordova_Network/library.xml b/lib/cordova-blackberry/framework/ext-air/Cordova_Network/library.xml
deleted file mode 100644
index c1835b4..0000000
--- a/lib/cordova-blackberry/framework/ext-air/Cordova_Network/library.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-<library isWhitelist="true">
- <extension>
- <entryClass>org.apache.cordova.network.Network</entryClass>
- </extension>
-
- <platforms>
- <platform value="AIR">
- <target version="default" config="AIR_XHR" />
- </platform>
- </platforms>
-
- <configurations>
- <configuration name="AIR_XHR" version="1.0" comment="For XHR architecture for Java implementation">
- <src type="text/actionscript" path="src" comment="ActionScript implementation" />
- </configuration>
- </configurations>
-
- <features>
- <feature id="org.apache.cordova" version="1.0.0" />
- </features>
-</library>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext-air/Cordova_Network/src/org/apache/cordova/network/Network.as
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext-air/Cordova_Network/src/org/apache/cordova/network/Network.as b/lib/cordova-blackberry/framework/ext-air/Cordova_Network/src/org/apache/cordova/network/Network.as
deleted file mode 100644
index d2ad030..0000000
--- a/lib/cordova-blackberry/framework/ext-air/Cordova_Network/src/org/apache/cordova/network/Network.as
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- * Copyright (c) 2011, Research In Motion Limited.
- */
-
-
-package org.apache.cordova.network {
- import flash.net.NetworkInfo;
- import flash.net.NetworkInterface;
- import flash.events.Event;
- import qnx.system.Device;
-
- import webworks.extension.DefaultExtension;
-
- public class Network extends DefaultExtension{
-
- private var _jsFunctionCallbackIDs:Array = [];
- private const FEATURE_ID:Array = [ "org.apache.cordova" ];
-
- public function Network() {
- //Attach event listener once only
- NetworkInfo.networkInfo.addEventListener(flash.events.Event.NETWORK_CHANGE, networkChange);
- }
-
- override public function getFeatureList():Array {
- return FEATURE_ID;
- }
-
- public function getConnectionInfo(param:String):void{
- if(_jsFunctionCallbackIDs.indexOf(param) < 0){
- _jsFunctionCallbackIDs.push(param);
- }
- }
-
- public function getDeviceInfo(id:String):void{
- evalJavaScriptEvent(id, [{
- "uuid" : Device.device.pin,
- "version": Device.device.scmBundle
- }]);
- }
-
- private function networkChange( event: Event ) : void {
-
- /**
- * Right now, we only care if there is a connection or not, since PlayBook only has WiFi
- * At the JS layer, we will map this from offline/online.
- * At some point in the future where there are more connection types on PlayBook,
- * we will want to attempt to map this to the real Cordova connection types...
- */
-
- var haveCoverage : Boolean = false;
- var networkStatus : String = "offline";
- var connectionType = "none";
-
- NetworkInfo.networkInfo.findInterfaces().some(
- function callback(item:NetworkInterface, index:int, vector:Vector.<NetworkInterface>):Boolean {
- this.webView.executeJavaScript("alert('Network Interface ' + item.name)");
- haveCoverage = item.active || haveCoverage;
- return haveCoverage;
- }, this);
-
- if (haveCoverage) {
- networkStatus = "online";
- connectionType = "wifi";
- }
-
- for (var i:Number=0; i<_jsFunctionCallbackIDs.length ; i++){
- evalJavaScriptEvent(_jsFunctionCallbackIDs[i], [{"type" : connectionType, "event" : networkStatus }] );
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/client.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/client.js b/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/client.js
deleted file mode 100644
index f8308b8..0000000
--- a/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/client.js
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- * Copyright 2010-2011 Research In Motion Limited.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/index.js b/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/index.js
deleted file mode 100644
index 4a60b93..0000000
--- a/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/index.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright 2010-2011 Research In Motion Limited.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-var Whitelist = require("../../lib/policy/whitelist").Whitelist,
- whitelist = new Whitelist(),
- noop = function () {};
-
-module.exports = {
- isWhitelisted: function (success, fail, args) {
- var url = JSON.parse(decodeURIComponent(args[0])),
- success = success || noop,
- fail = fail || noop;
-
- if (url) {
- success(whitelist.isAccessAllowed(url));
- }
- else {
- error("please provide an url");
- }
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/manifest.json
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/manifest.json b/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/manifest.json
deleted file mode 100644
index 9efdda2..0000000
--- a/lib/cordova-blackberry/framework/ext-qnx/org.apache.cordova/manifest.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "global": false,
- "namespace": "org.apache.cordova",
- "dependencies": []
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext-qnx/readme.md
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext-qnx/readme.md b/lib/cordova-blackberry/framework/ext-qnx/readme.md
deleted file mode 100644
index 6527192..0000000
--- a/lib/cordova-blackberry/framework/ext-qnx/readme.md
+++ /dev/null
@@ -1 +0,0 @@
-Placeholder for native extensions needed on qnx
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/.classpath
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/.classpath b/lib/cordova-blackberry/framework/ext/.classpath
deleted file mode 100644
index 8d3a567..0000000
--- a/lib/cordova-blackberry/framework/ext/.classpath
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="src" path="res"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/net.rim.ejde.BlackBerryVMInstallType/BlackBerry JRE 5.0.0"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/.project
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/.project b/lib/cordova-blackberry/framework/ext/.project
deleted file mode 100644
index ecbf8d5..0000000
--- a/lib/cordova-blackberry/framework/ext/.project
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>CordovaExtension</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>net.rim.ejde.internal.builder.BlackBerryPreprocessBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>net.rim.ejde.internal.builder.BlackBerryResourcesBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>net.rim.ejde.BlackBerryPreProcessNature</nature>
- <nature>net.rim.ejde.BlackBerryProjectCoreNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/.settings/net.rim.browser.tools.debug.widget.prefs
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/.settings/net.rim.browser.tools.debug.widget.prefs b/lib/cordova-blackberry/framework/ext/.settings/net.rim.browser.tools.debug.widget.prefs
deleted file mode 100644
index 524fddd..0000000
--- a/lib/cordova-blackberry/framework/ext/.settings/net.rim.browser.tools.debug.widget.prefs
+++ /dev/null
@@ -1,3 +0,0 @@
-#Sun May 23 23:01:24 PDT 2010
-eclipse.preferences.version=1
-outputfolder=build
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/.settings/org.eclipse.jdt.core.prefs
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/.settings/org.eclipse.jdt.core.prefs b/lib/cordova-blackberry/framework/ext/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index be7e57d..0000000
--- a/lib/cordova-blackberry/framework/ext/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,12 +0,0 @@
-#Sun May 23 23:00:44 PDT 2010
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.4
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=ignore
-org.eclipse.jdt.core.compiler.source=1.3
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/BlackBerry_App_Descriptor.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/BlackBerry_App_Descriptor.xml b/lib/cordova-blackberry/framework/ext/BlackBerry_App_Descriptor.xml
deleted file mode 100644
index bb973e8..0000000
--- a/lib/cordova-blackberry/framework/ext/BlackBerry_App_Descriptor.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<Properties ModelVersion="1.1.2">
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
- <General Title="" Version="1.0.0" Vendor="BlackBerry Developer" Description=""/>
- <Application Type="BlackBerry Application" MainMIDletName="" MainArgs="" HomeScreenPosition="0" StartupTier="7" IsSystemModule="false" IsAutostartup="false"/>
- <Resources hasTitleResource="false" TitleResourceBundleName="" TitleResourceBundleRelativePath="" TitleResourceBundleClassName="" TitleResourceBundleKey="" DescriptionId="">
- <Icons/>
- </Resources>
- <Compile OutputCompilerMessages="false" ConvertImages="false" CreateWarningForNoExportedRoutine="true" CompressResources="false" AliasList="">
- <PreprocessorDefines/>
- </Compile>
- <Packaging OutputFileName="Cordova" OutputFolder="deliverables" PreBuildStep="" PostBuildStep="" CleanStep="" GenerateALXFile="false">
- <AlxFiles/>
- </Packaging>
- <HiddenProperties>
- <ClassProtection/>
- <PackageProtection/>
- </HiddenProperties>
- <AlternateEntryPoints/>
-</Properties>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/library.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/library.xml b/lib/cordova-blackberry/framework/ext/src/library.xml
deleted file mode 100644
index d408e9f..0000000
--- a/lib/cordova-blackberry/framework/ext/src/library.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-<library>
- <extension>
- <entryClass>org.apache.cordova.CordovaExtension</entryClass>
- </extension>
- <features>
- <feature id="org.apache.cordova" version="1.0.0">Cordova JavaScript Extension</feature>
- <feature id="blackberry.connection" version="1.0.0">Stub in for backwards bb10 support</feature>
- <feature id="blackberry.io" version="1.0.0">Stub in for backwards bb10 support</feature>
- <feature id="blackberry.invoked" version="1.0.0">Stub in for backwards bb10 support</feature>
- <feature id="blackberry.invoke.card" version="1.0.0">Stub in for backwards bb10 support</feature>
- <feature id="blackberry.ui.contextmenu" version="1.0.0">Stub in for backwards bb10 support</feature>
- <feature id="blackberry.io.filetransfer" version="1.0.0">Stub in for backwards bb10 support</feature>
- <feature id="blackberry.pim.contacts" version="1.0.0">Stub in for backwards bb10 support</feature>
- <feature id="blackberry.bbm.platform" version="1.0.0">Stub in for backwards bb10 support</feature>
- </features>
-</library>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/CordovaExtension.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/CordovaExtension.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/CordovaExtension.java
deleted file mode 100644
index 62943b4..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/CordovaExtension.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- * Copyright (c) 2011, Research In Motion Limited.
- */
-package org.apache.cordova;
-
-import net.rim.device.api.browser.field2.BrowserField;
-import net.rim.device.api.script.ScriptEngine;
-import net.rim.device.api.system.Application;
-import net.rim.device.api.web.WidgetConfig;
-import net.rim.device.api.web.WidgetExtension;
-import net.rim.device.api.xml.parsers.DocumentBuilderFactory;
-
-import org.apache.cordova.api.PluginManager;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.notification.Notification;
-import org.apache.cordova.util.Log;
-import org.apache.cordova.util.Logger;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.lang.ref.WeakReference;
-
-/**
- * CordovaExtension is a BlackBerry WebWorks JavaScript extension. It
- * represents a single feature that can be used to access device capabilities.
- */
-public final class CordovaExtension implements WidgetExtension {
-
- // Weak reference encapsulating BrowserField object used to display the application
- // We use the weak reference because keeping a direct reference can
- // cause memory leak issues in WebWorks. Original solution described
- // and suggested by Tim Neil on the BlackBerry support forums.
- // Thanks Tim!
- protected static WeakReference browser = null;
-
- // Browser script engine
- //
- protected static ScriptEngine script;
-
- // Application name
- //
- protected static String appName;
-
- // Application GUID
- //
- protected static long appID;
-
- // Plugin Manager
- //
- protected PluginManager pluginManager;
-
- // Feature ID
- //
- private static final String FEATURE_ID ="org.apache.cordova";
-
- // Called when the BlackBerry Widget references this extension for the first time.
- // It provides a list of feature IDs exposed by this extension.
- //
- public String[] getFeatureList() {
- return new String[] {FEATURE_ID};
- }
-
- // Called whenever a widget loads a resource that requires a feature ID that is supplied
- // in the getFeatureList
- //
- public void loadFeature(String feature, String version, Document doc,
- ScriptEngine scriptEngine) throws Exception {
- script = scriptEngine;
- // Not sure why logger is not already enabled?
- Logger.enableLogging();
- if (feature.equals(FEATURE_ID)) {
- pluginManager = new PluginManager(this);
-
- // create and parse the plugins.xml
- Document c = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(Application.class.getResourceAsStream("/plugins.xml"));
-
- NodeList plugins = c.getElementsByTagName("plugin");
- if (plugins.getLength() == 0) {
- Logger.warn("If you are using any Cordova APIs you will need to "+
- "specify them in the config.xml using <gap:plugin name=\"MyPlugin\" "+
- "value=\"com.example.MyPlugin\"/>");
- }
- for(int i=0; i<plugins.getLength() ; i++){
- Node plugin = plugins.item(i);
- Logger.log("Found plugin " + plugin.getAttributes().getNamedItem("name").getNodeValue() + " = " +
- plugin.getAttributes().getNamedItem("value").getNodeValue());
- pluginManager.addService(plugin.getAttributes().getNamedItem("name").getNodeValue(),
- plugin.getAttributes().getNamedItem("value").getNodeValue());
- }
-
- scriptEngine.addExtension("org.apache.cordova.JavaPluginManager", pluginManager);
- scriptEngine.addExtension("org.apache.cordova.Logger", new Log());
-
- // let Cordova JavaScript know that extensions have been loaded
- // if this is premature, we at least set the _nativeReady flag to true
- // so that when the JS side is ready, it knows native side is too
- Logger.log(this.getClass().getName() + ": invoking Cordova.onNativeReady.fire()");
- scriptEngine.executeScript("try {cordova.require('cordova/channel').onNativeReady.fire();} catch(e) {_nativeReady = true;}", null);
- }
- }
-
- // Called so that the extension can get a reference to the configuration or browser field object
- //
- public void register(WidgetConfig widgetConfig, BrowserField browserField) {
- browser = new WeakReference(browserField);
-
- // grab widget application name and use it to generate a unique ID
- appName = widgetConfig.getName();
- appID = Long.parseLong(Math.abs(("org.apache.cordova."+appName).hashCode())+"",16);
-
- // create a notification profile for the application
- Notification.registerProfile();
- }
-
- /**
- * Called to clean up any features when the extension is unloaded. This is
- * invoked by the WebWorks Framework when another URL is loaded.
- *
- * @see net.rim.device.api.web.WidgetExtension#unloadFeatures(org.w3c.dom.Document)
- */
- public void unloadFeatures(Document doc) {
- // Cleanup plugin resources.
- if (pluginManager != null) {
- pluginManager.destroy();
- }
- }
-
- public static void invokeScript(final String js) {
- // Use a new thread so that JavaScript is invoked asynchronously.
- // Otherwise executeScript doesn't return until JavaScript call back
- // is finished.
- (new Thread() {
- public void run() {
- try {
- script.executeScript(js, null);
- } catch (Exception e) {
- // This is likely an IllegalStateException which is thrown
- // because the framework is in the process of being shutdown
- // so communication to JavaScript side is not allowed.
- Logger.log("Caught exception while executing script: "
- + e.getMessage());
- }
- }
- }).start();
- }
-
- /**
- * Invokes the Cordova success callback specified by callbackId.
- * @param callbackId unique callback ID
- * @param result Cordova PluginResult containing result
- */
- public static void invokeSuccessCallback(String callbackId, PluginResult result) {
- invokeScript(result.toSuccessCallbackString(callbackId));
- }
-
- /**
- * Invokes the Cordova error callback specified by callbackId.
- * @param callbackId unique callback ID
- * @param result Cordova PluginResult containing result
- */
- public static void invokeErrorCallback(String callbackId, PluginResult result) {
- invokeScript(result.toErrorCallbackString(callbackId));
- }
-
- /**
- * Provides access to the browser instance for the application.
- */
- public static BrowserField getBrowserField() {
- Object o = browser.get();
- if ( o instanceof BrowserField ) {
- return (BrowserField)o;
- } else {
- return null;
- }
- }
-
- /**
- * Returns the widget application name.
- */
- public static String getAppName() {
- return appName;
- }
-
- /**
- * Returns unique ID of the widget application.
- */
- public static long getAppID() {
- return appID;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
deleted file mode 100644
index 2088122..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.accelerometer;
-
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Vector;
-
-import net.rim.device.api.system.AccelerometerData;
-import net.rim.device.api.system.AccelerometerListener;
-import net.rim.device.api.system.AccelerometerSensor;
-import net.rim.device.api.system.Application;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.util.Logger;
-
-public class Accelerometer extends Plugin implements AccelerometerListener {
- private static final String LOG_TAG = "Accelerometer: ";
-
- private static final String ACTION_START = "start";
- private static final String ACTION_STOP = "stop";
-
- private static final int STOPPED = 0;
- private static final int STARTING = 1;
- private static final int RUNNING = 2;
- private static final int ERROR_FAILED_TO_START = 3;
-
- // BlackBerry uses a value of 1000 (AccelerometerSensor.G_FORCE_VALUE) to
- // represent g force constant. Spec uses m/s^2. This constant is used
- // to normalize BlackBerry values to the spec.
- private static final short G_FORCE_NORMALIZE = 981;
-
- // the single channel to the device sensor
- private static AccelerometerSensor.Channel _rawDataChannel = null;
-
- private int state = STOPPED; // state of this listener
- private long initTime = 0;
-
- /**
- * Reference to single start callbackid
- */
- private String callbackId;
-
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult result;
- if (!AccelerometerSensor.isSupported()) {
- result = new PluginResult(
- PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION,
- "Accelerometer sensor not supported");
- } else if (ACTION_START.equals(action)) {
- result = start(callbackId);
- } else if (ACTION_STOP.equals(action)) {
- result = stop();
- } else {
- result = new PluginResult(PluginResult.Status.INVALID_ACTION,
- "Accelerometer: Invalid action:" + action);
- }
-
- return result;
- }
-
- /**
- * Implements the AccelerometerListener method. We listen for the purpose of
- * closing the application's accelerometer sensor channel after timeout has
- * been exceeded.
- */
- public void onData(AccelerometerData accelData) {
- short x = accelData.getLastXAcceleration();
- short y = accelData.getLastYAcceleration();
- short z = accelData.getLastZAcceleration();
-
- // If any value is not zero, assume sensor is now active and set state.
- if (state == STARTING && (x != 0 || y != 0 || z != 0)) {
- state = RUNNING;
- }
-
- if (state == RUNNING) {
- // Send the new accelerometer data.
- JSONObject accel = new JSONObject();
- try {
- accel.put("x", normalize(x));
- accel.put("y", normalize(y));
- accel.put("z", normalize(z));
- accel.put("timestamp", accelData.getLastTimestamp());
- sendResult(true,
- new PluginResult(PluginResult.Status.OK, accel), true);
- } catch (JSONException e) {
- sendResult(false, new PluginResult(
- PluginResult.Status.JSON_EXCEPTION, "JSONException:"
- + e.getMessage()), false);
- }
- } else if ((System.currentTimeMillis() - initTime) > 2000) {
- // If the sensor does not become active within 2 seconds of
- // the request to start it, fail out.
- stop();
- state = ERROR_FAILED_TO_START;
- JSONObject errorObj = new JSONObject();
- try {
- errorObj.put("code", ERROR_FAILED_TO_START);
- errorObj.put("message", "Accelerometer could not be started.");
- } catch (JSONException e) {
- Logger.log(LOG_TAG
- + "Failed to build JSON object for ERROR_FAILED_TO_START.");
- }
- sendResult(false, new PluginResult(PluginResult.Status.ERROR,
- errorObj), false);
- }
- }
-
- /**
- * Called when Plugin is destroyed.
- */
- public void onDestroy() {
- stop();
- }
-
- /**
- * Adds a SystemListener to listen for changes to the battery state. The
- * listener is only registered if one has not already been added.
- */
- private PluginResult start(String callbackId) {
- this.callbackId = callbackId;
- if (_rawDataChannel == null || !_rawDataChannel.isOpen()) {
- _rawDataChannel = AccelerometerSensor
- .openRawDataChannel(Application.getApplication());
- Logger.log(LOG_TAG + "sensor channel opened");
-
- initTime = System.currentTimeMillis();
- state = STARTING;
- _rawDataChannel.setAccelerometerListener(this);
- Logger.log(LOG_TAG + "sensor listener added");
- }
-
- PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
- result.setKeepCallback(true);
- return result;
- }
-
- /**
- * Normalize the range of values returned by BlackBerry to the agreed upon
- * cross platform range.
- *
- * @param value
- * @return normalized value
- */
- private double normalize(short value) {
- // Integer multiplication is less troublesome then floating point.
- StringBuffer buf = new StringBuffer(String.valueOf(value
- * G_FORCE_NORMALIZE));
-
- // Manipulate the string to properly insert zeros and decimal point so
- // something like -708910 becomes -7.08910 and 764 becomes .00764.
- // Due to the values returned by BlackBerry there will always be 5
- // decimal precision in the normalized value.
- int idx = buf.charAt(0) == '-' ? 1 : 0;
- while (buf.length() < (5 + idx)) {
- buf.insert(idx, '0');
- }
- buf.insert(buf.length() - 5, '.');
-
- return Double.parseDouble(buf.toString());
- }
-
- /**
- * Helper function to send a PluginResult to the saved call back ID.
- *
- * @param issuccess
- * true if this is a successful result, false otherwise.
- * @param result
- * the PluginResult to return
- * @param keepCallback
- * Boolean value indicating whether to keep the call back id
- * active.
- */
- private synchronized void sendResult(boolean issuccess,
- PluginResult result, boolean keepCallback) {
-
- if (result != null) {
- // Must keep the call back active for future watch events.
- result.setKeepCallback(keepCallback);
-
- if (issuccess) {
- success(result, this.callbackId);
- } else {
- error(result, this.callbackId);
- }
- }
- }
-
- /**
- * Stops accelerometer listener and closes the sensor channel.
- */
- private synchronized PluginResult stop() {
- if (_rawDataChannel != null && _rawDataChannel.isOpen()) {
-
- // Remove the battery listener.
- _rawDataChannel.removeAccelerometerListener();
- _rawDataChannel.close();
- _rawDataChannel = null;
-
- Logger.log(LOG_TAG + "sensor channel closed");
- }
-
- state = STOPPED;
-
- return new PluginResult(PluginResult.Status.OK);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/IPlugin.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/IPlugin.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/IPlugin.java
deleted file mode 100644
index 7e09d31..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/IPlugin.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.api;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.json4j.JSONArray;
-
-/**
- * Plugin interface must be implemented by any plugin classes.
- *
- * The execute method is called by the PluginManager.
- */
-public interface IPlugin {
-
- /**
- * Executes the request and returns PluginResult.
- *
- * @param action The action to execute.
- * @param args JSONArry of arguments for the plugin.
- * @param callbackId The callback id used when calling back into JavaScript.
- * @return A PluginResult object with a status and message.
- */
- PluginResult execute(String action, JSONArray args, String callbackId);
-
- /**
- * Identifies if action to be executed returns a value and should be run synchronously.
- *
- * @param action The action to execute
- * @return T=returns value
- */
- public boolean isSynch(String action);
-
- /**
- * Sets the context of the Plugin. This can then be used to do things like
- * get file paths associated with the Activity.
- *
- * @param ctx The main application class.
- */
- void setContext(CordovaExtension ctx);
-
- /**
- * Called when the system is about to start resuming a previous activity.
- */
- void onPause();
-
- /**
- * Called when the activity will start interacting with the user.
- */
- void onResume();
-
- /**
- * The final call you receive before your activity is destroyed.
- */
- void onDestroy();
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/Plugin.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/Plugin.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/Plugin.java
deleted file mode 100644
index 6f70b85..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/Plugin.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.api;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.json4j.JSONArray;
-
-/**
- * Plugin interface must be implemented by any plugin classes.
- *
- * The execute method is called by the PluginManager.
- */
-public abstract class Plugin implements IPlugin {
-
- public CordovaExtension ctx; // Main application object
-
- /**
- * Executes the request and returns PluginResult.
- *
- * @param action The action to execute.
- * @param args JSONArry of arguments for the plugin.
- * @param callbackId The callback id used when calling back into JavaScript.
- * @return A PluginResult object with a status and message.
- */
- public abstract PluginResult execute(String action, JSONArray args, String callbackId);
-
- /**
- * Identifies if action to be executed returns a value and should be run synchronously.
- *
- * @param action The action to execute
- * @return T=returns value
- */
- public boolean isSynch(String action) {
- return false;
- }
-
- /**
- * Sets the context of the Plugin. This can then be used to do things like
- * get file paths associated with the Activity.
- *
- * @param ctx The context of the main Activity.
- */
- public void setContext(CordovaExtension ctx) {
- this.ctx = ctx;
- }
-
- /**
- * Called when Plugin is paused.
- */
- public void onPause() {
- }
-
- /**
- * Called when Plugin is resumed.
- */
- public void onResume() {
- }
-
- /**
- * Called when Plugin is destroyed.
- */
- public void onDestroy() {
- }
-
- /**
- * Send generic JavaScript statement back to JavaScript.
- * success(...) and error(...) should be used instead where possible.
- *
- * @param statement
- */
- public void invokeScript(String statement) {
- CordovaExtension.invokeScript(statement);
- }
-
- /**
- * Call the JavaScript success callback for this plugin.
- *
- * This can be used if the execute code for the plugin is asynchronous meaning
- * that execute should return null and the callback from the async operation can
- * call success(...) or error(...)
- *
- * @param pluginResult The result to return.
- * @param callbackId The callback id used when calling back into JavaScript.
- */
- public static void success(PluginResult pluginResult, String callbackId) {
- CordovaExtension.invokeSuccessCallback(callbackId, pluginResult);
- }
-
- /**
- * Call the JavaScript error callback for this plugin.
- *
- * @param pluginResult The result to return.
- * @param callbackId The callback id used when calling back into JavaScript.
- */
- public static void error(PluginResult pluginResult, String callbackId) {
- CordovaExtension.invokeErrorCallback(callbackId, pluginResult);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginManager.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginManager.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginManager.java
deleted file mode 100644
index a8e5e9b..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginManager.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.api;
-
-import java.util.Hashtable;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.util.FileUtils;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.script.Scriptable;
-import net.rim.device.api.script.ScriptableFunction;
-
-/**
- * PluginManager represents an object in the script engine. It can be accessed
- * from the script environment using <code>cordova.PluginManager</code>.
- *
- * PluginManager provides a function, <code>exec</code>, that can be invoked
- * from the script environment: <code>cordova.PluginManager.exec(...)</code>.
- * Invoking this function causes the script engine to load the appropriate
- * Cordova Plugin and perform the specified action.
- */
-public final class PluginManager extends Scriptable {
-
- /**
- * Field used to invoke Plugin actions.
- */
- public static String FIELD_EXEC = "exec";
-
- /**
- * Field used to cleanup Plugins.
- */
- public static String FIELD_DESTROY = "destroy";
-
- /**
- * Field used to indicate application has been brought to foreground.
- */
- public static String FIELD_RESUME = "resume";
-
- /**
- * Field used to indicate application has been sent to background
- */
- public static String FIELD_PAUSE = "pause";
-
- /**
- * Field used to register a Plugin.
- */
- public static String FIELD_ADD_PLUGIN = "addPlugin";
-
- /**
- * Loads the appropriate Cordova Plugins and invokes their actions.
- */
- private final PluginManagerFunction pluginManagerFunction;
-
- /**
- * Maps available services to Java class names.
- */
- private Hashtable services = new Hashtable();
-
- /**
- * Constructor. Adds available Cordova services.
- * @param ext The Cordova JavaScript Extension
- */
- public PluginManager(CordovaExtension ext) {
- this.pluginManagerFunction = new PluginManagerFunction(ext, this);
- }
-
- /**
- * The following fields are supported from the script environment:
- *
- * <code>cordova.pluginManager.exec</code> - Loads the appropriate
- * Plugin and invokes the specified action.
- *
- * <code>cordova.pluginManager.destroy</code> - Invokes the <code>onDestroy</code>
- * method on all Plugins to give them a chance to cleanup before exit.
- */
- public Object getField(String name) throws Exception {
- if (name.equals(FIELD_EXEC)) {
- return this.pluginManagerFunction;
- }
- else if (name.equals(FIELD_DESTROY)) {
- return new ScriptableFunction() {
- public Object invoke(Object obj, Object[] oargs) throws Exception {
- destroy();
- return null;
- }
- };
- }
- else if (name.equals(FIELD_RESUME)) {
- final PluginManagerFunction plugin_mgr = this.pluginManagerFunction;
- return new ScriptableFunction() {
- public Object invoke(Object obj, Object[] oargs) throws Exception {
- plugin_mgr.onResume();
- return null;
- }
- };
- }
- else if (name.equals(FIELD_PAUSE)) {
- final PluginManagerFunction plugin_mgr = this.pluginManagerFunction;
- return new ScriptableFunction() {
- public Object invoke(Object obj, Object[] oargs) throws Exception {
- plugin_mgr.onPause();
- return null;
- }
- };
- }
- else if (name.equals(FIELD_ADD_PLUGIN)) {
- Logger.log("Plugins are now added through the plugins.xml in the application root.");
- }
- return super.getField(name);
- }
-
- /**
- * Add a class that implements a service.
- *
- * @param serviceName The service name.
- * @param className The Java class name that implements the service.
- */
- public void addService(String serviceName, String className) {
- this.services.put(serviceName, className);
- }
-
- /**
- * Cleanup the plugin resources and delete temporary directory that may have
- * been created.
- */
- public void destroy() {
- // allow plugins to clean up
- pluginManagerFunction.onDestroy();
-
- // delete temporary application directory
- // NOTE: doing this on a background thread doesn't work because the app
- // is closing and the thread is killed before it completes.
- try {
- FileUtils.deleteApplicationTempDirectory();
- } catch (Exception e) {
- Logger.log(this.getClass().getName()
- + ": error deleting application temp directory: "
- + e.getMessage());
- }
- }
-
- /**
- * Get the class that implements a service.
- *
- * @param serviceName The service name.
- * @return The Java class name that implements the service.
- */
- public String getClassForService(String serviceName) {
- return (String)this.services.get(serviceName);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginManagerFunction.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginManagerFunction.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginManagerFunction.java
deleted file mode 100644
index 13a0e77..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginManagerFunction.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.api;
-
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import net.rim.device.api.script.ScriptableFunction;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.util.Logger;
-
-/**
- * PluginManagerFunction represents a function that can be invoked from the
- * script environment of the widget framework. It manages the plugins for
- * the Cordova JavaScript Extension.
- *
- * Calling <code>cordova.pluginManager.exec(...)</code> from JavaScript will
- * result in this class' <code>invoke()</code> method being called.
- */
-public class PluginManagerFunction extends ScriptableFunction {
-
- private final static int ARG_SERVICE = 0;
- private final static int ARG_ACTION = 1;
- private final static int ARG_CALLBACK_ID = 2;
- private final static int ARG_ARGS = 3;
- private final static int ARG_ASYNC = 4;
-
- private Hashtable plugins = new Hashtable();
-
- private final CordovaExtension ext;
- private final PluginManager pluginManager;
-
- /**
- * Constructor.
- * @param ext The Cordova JavaScript Extension
- * @param pluginManager The PluginManager that exposes the scriptable object.
- */
- public PluginManagerFunction(CordovaExtension ext, PluginManager pluginManager) {
- this.ext = ext;
- this.pluginManager = pluginManager;
- }
-
- /**
- * The invoke method is called when cordova.pluginManager.exec(...) is
- * used from the script environment. It instantiates the appropriate plugin
- * and invokes the specified action. JavaScript arguments are passed in
- * as an array of objects.
- *
- * @param service String containing the service to run
- * @param action String containing the action that the service is supposed to perform. This is
- * passed to the plugin execute method and it is up to the plugin developer
- * how to deal with it.
- * @param callbackId String containing the id of the callback that is executed in JavaScript if
- * this is an async plugin call.
- * @param args An Array literal string containing any arguments needed in the
- * plugin execute method.
- * @param async Boolean indicating whether the calling JavaScript code is expecting an
- * immediate return value. If true, either CordovaExtension.callbackSuccess(...) or
- * CordovaExtension.callbackError(...) is called once the plugin code has executed.
- *
- * @return JSON encoded string with a response message and status.
- *
- * @see net.rim.device.api.script.ScriptableFunction#invoke(java.lang.Object, java.lang.Object[])
- */
- public Object invoke(Object obj, Object[] oargs) throws Exception {
- final String service = (String)oargs[ARG_SERVICE];
- final String action = (String)oargs[ARG_ACTION];
- final String callbackId = (String)oargs[ARG_CALLBACK_ID];
- boolean async = (oargs[ARG_ASYNC].toString().equals("true") ? true : false);
- PluginResult pr = null;
-
- try {
- // action arguments
- final JSONArray args = new JSONArray((String)oargs[ARG_ARGS]);
-
- // get the class for the specified service
- String clazz = this.pluginManager.getClassForService(service);
- Class c = null;
- if (clazz != null) {
- c = getClassByName(clazz);
- }
-
- if (isCordovaPlugin(c)) {
- // Create a new instance of the plugin and set the context
- final Plugin plugin = this.loadPlugin(clazz, c);
- async = async && !plugin.isSynch(action);
- if (async) {
- // Run this async on a background thread so that JavaScript can continue on
- Thread thread = new Thread(new Runnable() {
- public void run() {
- // Call execute on the plugin so that it can do it's thing
- final PluginResult result = plugin.execute(action, args, callbackId);
-
- if (result != null) {
- int status = result.getStatus();
-
- // If plugin status is OK,
- // or plugin is not going to send an immediate result (NO_RESULT)
- if (status == PluginResult.Status.OK.ordinal() ||
- status == PluginResult.Status.NO_RESULT.ordinal()) {
- CordovaExtension.invokeSuccessCallback(callbackId, result);
- }
- // error
- else {
- CordovaExtension.invokeErrorCallback(callbackId, result);
- }
- }
- }
- });
- thread.start();
- return "";
- } else {
- // Call execute on the plugin so that it can do it's thing
- pr = plugin.execute(action, args, callbackId);
- }
- }
- } catch (ClassNotFoundException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- pr = new PluginResult(PluginResult.Status.CLASS_NOT_FOUND_EXCEPTION, "ClassNotFoundException: " + e.getMessage());
- } catch (IllegalAccessException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- pr = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION, "IllegalAccessException:" + e.getMessage());
- } catch (InstantiationException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- pr = new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION, "InstantiationException: " + e.getMessage());
- } catch (JSONException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- pr = new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSONException: " + e.getMessage());
- }
- // if async we have already returned at this point unless there was an error...
- if (async) {
- CordovaExtension.invokeErrorCallback(callbackId, pr);
- }
- return ( pr != null ? pr.getJSONString() : "{ status: 0, message: 'all good' }" );
- }
-
- /**
- * Get the class.
- *
- * @param clazz
- * @return
- * @throws ClassNotFoundException
- */
- private Class getClassByName(final String clazz) throws ClassNotFoundException {
- return Class.forName(clazz);
- }
-
- /**
- * Determines if the class implements org.apache.cordova.api.Plugin interface.
- *
- * @param c The class to check.
- * @return Boolean indicating if the class implements org.apache.cordova.api.Plugin
- */
- private boolean isCordovaPlugin(Class c) {
- if (c != null) {
- return org.apache.cordova.api.Plugin.class.isAssignableFrom(c) || org.apache.cordova.api.IPlugin.class.isAssignableFrom(c);
- }
- return false;
- }
-
- /**
- * Add plugin to be loaded and cached.
- * If plugin is already created, then just return it.
- *
- * @param className The class to load
- * @return The plugin
- */
- public Plugin loadPlugin(String className, Class clazz) throws IllegalAccessException, InstantiationException {
- if (this.plugins.containsKey(className)) {
- return this.getPlugin(className);
- }
- Logger.log(this.getClass().getName() + ": Loading plugin " + clazz);
- Plugin plugin = (Plugin)clazz.newInstance();
- this.plugins.put(className, plugin);
- plugin.setContext(this.ext);
- return plugin;
- }
-
- /**
- * Get the loaded plugin.
- *
- * @param className The class of the loaded plugin.
- * @return
- */
- public Plugin getPlugin(String className) {
- return (Plugin)this.plugins.get(className);
- }
-
- /**
- * Called when application is paused.
- */
- public void onPause() {
- Enumeration e = this.plugins.elements();
- while (e.hasMoreElements()) {
- Plugin plugin = (Plugin)e.nextElement();
- plugin.onPause();
- }
- }
-
- /**
- * Called when application is resumed.
- */
- public void onResume() {
- Enumeration e = this.plugins.elements();
- while (e.hasMoreElements()) {
- Plugin plugin = (Plugin)e.nextElement();
- plugin.onResume();
- }
- }
-
- /**
- * Called when application is destroyed.
- */
- public void onDestroy() {
- Enumeration e = this.plugins.elements();
- while (e.hasMoreElements()) {
- Plugin plugin = (Plugin)e.nextElement();
- plugin.onDestroy();
- }
- }
-}
[16/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JStringReader.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JStringReader.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JStringReader.java
deleted file mode 100644
index 5c3583a..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JStringReader.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-import java.io.IOException;
-import java.io.Reader;
-
-public class JSON4JStringReader extends Reader {
-
- private char[] _buf = null;
- private int _mark = 0;
- private int maxLength = 0;
-
- public JSON4JStringReader(String str) {
- _buf = str.toCharArray();
- maxLength = str.length();
- _mark = 0;
- }
-
- public void close() throws IOException {
- return;
- }
-
- public int read(char[] cbuf, int off, int len) throws IOException {
- if (_mark == (maxLength))
- return -1;
-
- int read = 0;
- for (int x=0; x<len; x++) {
- cbuf[x+off] = _buf[_mark];
- read++;
- _mark++;
- if (_mark == (maxLength))
- return read;
- }
- return read;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JStringWriter.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JStringWriter.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JStringWriter.java
deleted file mode 100644
index ce1d2cc..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JStringWriter.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-import java.io.IOException;
-import java.io.Writer;
-
-public class JSON4JStringWriter extends Writer {
-
- public static int BUF_SIZE = 10000;
-
- private char[] _buffer = null;
-
- private int _mark = 0;
-
- public JSON4JStringWriter() {
- _buffer = new char[BUF_SIZE];
- _mark = 0;
- }
-
- // Resizes an array; doubles up every time.
- public static char[] resizeArray(char[] expandMe) {
- int newSize = expandMe.length * 2;
- char[] newArray = new char[newSize];
- System.arraycopy(expandMe, 0, newArray, 0, expandMe.length);
- return newArray;
- }
-
-
- public void close() throws IOException {
- return;
- }
-
- public void flush() throws IOException {
- return;
- }
-
- public void write(char[] cbuf, int off, int len) throws IOException {
- if (((len - off) + _mark) >= _buffer.length) {
- // Resize the array first.
- _buffer = JSON4JStringWriter.resizeArray(_buffer);
- }
- for (int x=0; x < len; x++) {
- _buffer[_mark] = cbuf[off+x];
- _mark++;
- }
- }
-
- public String toString() {
- return new String(_buffer, 0, _mark);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/NumberUtil.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/NumberUtil.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/NumberUtil.java
deleted file mode 100644
index d63d4db..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/NumberUtil.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-public class NumberUtil {
-
- public static boolean isNumber(Class clazz) {
- if ( (clazz == Integer.class) || (clazz == Long.class) || (clazz == Double.class) || (clazz == Short.class) || (clazz == Float.class)) {
- return true;
- }
- return false;
- }
-
- public static double getDouble(Object val) {
- if (val instanceof Double) {
- return ((Double)val).doubleValue();
- }
- else if (val instanceof Long) {
- return ((Long)val).doubleValue();
- }
- else if (val instanceof Short) {
- Integer i = new Integer( ((Short)val).shortValue() );
- return i.doubleValue();
- }
- else if (val instanceof Float) {
- return ((Float)val).doubleValue();
- }
- else if (val instanceof Integer) {
- return ((Integer)val).doubleValue();
- }
- throw new IllegalArgumentException("Not a number");
- }
-
- public static short getShort(Object val) {
- if (val instanceof Double) {
- return ((Double)val).shortValue();
- }
- else if (val instanceof Long) {
- Double dg = new Double(((Long)val).longValue());
- return dg.shortValue();
- }
- else if (val instanceof Short) {
- return ((Short)val).shortValue();
- }
- else if (val instanceof Float) {
- return ((Float)val).shortValue();
- } else if (val instanceof Integer) {
- return ((Integer)val).shortValue();
- }
- throw new IllegalArgumentException("Not a number");
- }
-
- public static int getInt(Object val) {
- if (val instanceof Double) {
- return ((Double)val).intValue();
- }
- else if (val instanceof Long) {
- Double dg = new Double(((Long)val).longValue());
- return dg.intValue();
- }
- else if (val instanceof Short) {
- Double dg = new Double(((Short)val).shortValue());
- return dg.intValue();
- }
- else if (val instanceof Float) {
- return ((Float)val).intValue();
- }
- else if (val instanceof Integer) {
- return ((Integer)val).intValue();
- }
- throw new IllegalArgumentException("Not a number");
- }
-
- public static long getLong(Object val) {
- if (val instanceof Double) {
- return ((Double)val).longValue();
- }
- else if (val instanceof Long) {
- return ((Long)val).longValue();
- }
- else if (val instanceof Short) {
- Long lg = new Long(((Short)val).shortValue());
- return lg.longValue();
- }
- else if (val instanceof Float) {
- return ((Float)val).longValue();
- }
- else if (val instanceof Integer) {
- return ((Integer)val).longValue();
- }
- throw new IllegalArgumentException("Not a number");
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Parser.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Parser.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Parser.java
deleted file mode 100644
index 39ddf98..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Parser.java
+++ /dev/null
@@ -1,338 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-import java.io.IOException;
-import java.io.Reader;
-
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-
-/**
- * Private parser class which handles doing the parsing of the JSON string into tokens.
- */
-public class Parser {
-
- private Tokenizer tokenizer;
- private Token lastToken;
-
- /**
- * Contructor
- * @param reader The Reader to use when reading in the JSON stream/string.
- *
- * @throws JSONException Thrown if an error occurs in tokenizing the JSON string.
- */
- public Parser(Reader reader) throws JSONException {
- super();
- try {
- this.tokenizer = new Tokenizer(reader, false);
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- }
-
- /**
- * Contructor
- * @param reader The Reader to use when reading in the JSON stream/string.
- * @param strict Boolean indicating if the parser should parse in strict mode, meaning unqoted strings and comments are not allowed.
- *
- * @throws JSONException Thrown if an error occurs in tokenizing the JSON string.
- */
- public Parser(Reader reader, boolean strict) throws JSONException {
- super();
- try {
- this.tokenizer = new Tokenizer(reader, strict);
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- }
-
- /**
- * Method to initiate the parse of the toplevel JSON object, which will in turn parse all child JSON objects contained within.
- * Same as calling parse(false);
- *
- * @throws JSONException Thrown if an IO error occurd during parse of the JSON object(s).
- */
- public JSONObject parse() throws JSONException {
- return parse(false, (JSONObject)null);
- }
-
- /**
- * Method to initiate the parse of the toplevel JSON object, which will in turn parse all child JSON objects contained within.
- * Same as calling parse(false);
- *
- * @throws JSONException Thrown if an IO error occurd during parse of the JSON object(s).
- */
- public JSONObject parse(JSONObject jObj) throws JSONException {
- return parse(false, jObj);
- }
-
- /**
- * Method to initiate the parse of the toplevel JSON object, which will in turn parse all child JSON objects contained within.
- * @param ordered Flag to denote if the parse should contruct a JSON object which maintains serialization order of the attributes.
- *
- * @throws JSONException Thrown if an IO error occurd during parse of the JSON object(s).
- */
- public JSONObject parse(boolean ordered) throws JSONException {
- try {
- lastToken = tokenizer.next();
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- return parseObject(ordered, null);
- }
-
- /**
- * Method to initiate the parse of the toplevel JSON object, which will in turn parse all child JSON objects contained within.
- * @param ordered Flag to denote if the parse should contruct a JSON object which maintains serialization order of the attributes.
- * @param jObj The JSONObjetc to fill out from the parsing. If null, create a new one.
- *
- * @throws JSONException Thrown if an IO error occurd during parse of the JSON object(s).
- */
- public JSONObject parse(boolean ordered, JSONObject jObj) throws JSONException {
- try {
- lastToken = tokenizer.next();
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- return parseObject(ordered, jObj);
- }
-
- /**
- * Method to initiate the parse of the toplevel JSON object, which will in turn parse all child JSON objects contained within.
- * @param jObj The JSONArray to fill out from the parsing. If null, create a new one.
- *
- * @throws JSONException Thrown if an IO error occurd during parse of the JSON object(s).
- */
- public JSONArray parse(JSONArray jObj) throws JSONException {
- return parse(false, jObj);
- }
-
- /**
- * Method to initiate the parse of the toplevel JSON object, which will in turn parse all child JSON objects contained within.
- * @param ordered Flag to denote if the parse should contruct for all JSON objects encounted, a JSON object which maintains serialization order of the attributes.
- * @param jObj The JSONArray to fill out from the parsing. If null, create a new one.
- *
- * @throws JSONException Thrown if an IO error occurd during parse of the JSON object(s).
- */
- public JSONArray parse(boolean ordered, JSONArray jObj) throws JSONException {
- try {
- lastToken = tokenizer.next();
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- return parseArray(ordered, jObj);
- }
-
- /**
- * Method to parse a JSON object out of the current JSON string position.
- * @return JSONObject Returns the parsed out JSON object.
- *
- * @throws JSONException Thrown if an IO error occurs during parse, such as a malformed JSON object.
- */
- public JSONObject parseObject() throws JSONException {
- return parseObject(false, null);
- }
-
- /**
- * Method to parse a JSON object out of the current JSON string position.
- * @param ordered Flag to denote if the parse should contruct a JSON object which maintains serialization order of the attributes.
- * @return JSONObject Returns the parsed out JSON object.
- *
- * @throws JSONException Thrown if an IO error occurs during parse, such as a malformed JSON object.
- */
- public JSONObject parseObject(boolean ordered, JSONObject rootObject) throws JSONException {
-
- try {
- JSONObject result = null;
- if (rootObject != null) {
- result = rootObject;
- } else {
- if (!ordered) {
- result = new JSONObject();
- } else {
- //MSN NO ORDERED
- result = new JSONObject();
- }
- }
-
- if (lastToken != Token.TokenBraceL) throw new JSONException("Expecting '{' " + tokenizer.onLineCol() + " instead, obtained token: '" + lastToken + "'");
- lastToken = tokenizer.next();
-
- while (true) {
- if (lastToken == Token.TokenEOF) throw new JSONException("Unterminated object " + tokenizer.onLineCol());
-
- if (lastToken == Token.TokenBraceR) {
- lastToken = tokenizer.next();
- break;
- }
-
- if (!lastToken.isString()) throw new JSONException("Expecting string key " + tokenizer.onLineCol());
- String key = lastToken.getString();
-
- lastToken = tokenizer.next();
- if (lastToken != Token.TokenColon) throw new JSONException("Expecting colon " + tokenizer.onLineCol());
-
- lastToken = tokenizer.next();
- Object val = parseValue(ordered);
-
- result.put(key, val);
-
- if (lastToken == Token.TokenComma) {
- lastToken = tokenizer.next();
- }
-
- else if (lastToken != Token.TokenBraceR) {
- throw new JSONException("expecting either ',' or '}' " + tokenizer.onLineCol());
- }
- }
- return result;
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during object input read.");
- jex.setCause(iox);
- throw jex;
- }
- }
-
- /**
- * Method to parse out a JSON array from a JSON string
- * Same as calling parseArray(false, null)
- *
- * @throws JSONException Thrown if a parse error occurs, such as a malformed JSON array.
- */
- public JSONArray parseArray() throws JSONException {
- return parseArray(false, null);
- }
-
- /**
- * Method to parse out a JSON array from a JSON string
- * @param ordered Flag to denote if the parse should contruct JSON objects which maintain serialization order of the attributes for all JSONOjects in the array.
- * *param array An array instance to populate instead of creating a new one.
- *
- * @throws JSONException Thrown if a parse error occurs, such as a malformed JSON array.
- */
- public JSONArray parseArray(boolean ordered, JSONArray array) throws JSONException {
- JSONArray result = null;
- if(array != null){
- result = array;
- } else {
- result = new JSONArray();
- }
-
- try {
- if (lastToken != Token.TokenBrackL) throw new JSONException("Expecting '[' " + tokenizer.onLineCol());
- lastToken = tokenizer.next();
- while (true) {
- if (lastToken == Token.TokenEOF) throw new JSONException("Unterminated array " + tokenizer.onLineCol());
-
- /**
- * End of the array.
- */
- if (lastToken == Token.TokenBrackR) {
- lastToken = tokenizer.next();
- break;
- }
-
- Object val = parseValue(ordered);
- result.add(val);
-
- if (lastToken == Token.TokenComma) {
- lastToken = tokenizer.next();
- } else if (lastToken != Token.TokenBrackR) {
- throw new JSONException("expecting either ',' or ']' " + tokenizer.onLineCol());
- }
- }
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during array input read.");
- jex.setCause(iox);
- throw jex;
- }
- return result;
- }
-
- /**
- * Method to parse the current JSON property value from the last token.
- * @return The java object type that represents the JSON value.
- *
- * @throws JSONException Thrown if an IO error (read incomplete token) occurs.
- */
- public Object parseValue() throws JSONException {
- return parseValue(false);
- }
-
- /**
- * Method to parse the current JSON property value from the last token.
- * @return The java object type that represents the JSON value.
- * @param ordered Flag to denote if the parse should contruct JSON objects and arrays which maintain serialization order of the attributes.
- *
- * @throws JSONException Thrown if an IO error (read incomplete token) occurs.
- */
- public Object parseValue(boolean ordered) throws JSONException {
- if (lastToken == Token.TokenEOF) throw new JSONException("Expecting property value " + tokenizer.onLineCol());
-
- try {
- if (lastToken.isNumber()) {
- Object result = lastToken.getNumber();
- lastToken = tokenizer.next();
- return result;
- }
-
- if (lastToken.isString()) {
- Object result = lastToken.getString();
- lastToken = tokenizer.next();
- return result;
- }
-
- if (lastToken == Token.TokenFalse) {
- lastToken = tokenizer.next();
- return Boolean.FALSE;
- }
-
- if (lastToken == Token.TokenTrue) {
- lastToken = tokenizer.next();
- return Boolean.TRUE;
- }
-
- if (lastToken == Token.TokenNull) {
- lastToken = tokenizer.next();
- return JSONObject.NULL;
- }
-
- if (lastToken == Token.TokenBrackL) return parseArray(ordered, null);
- if (lastToken == Token.TokenBraceL) return parseObject(ordered, null);
-
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during value input read.");
- jex.setCause(iox);
- throw jex;
- }
- throw new JSONException("Invalid token " + tokenizer.onLineCol());
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Serializer.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Serializer.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Serializer.java
deleted file mode 100644
index 50f34d3..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Serializer.java
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.json4j.JSONString;
-
-/**
- * Class to handle serialization of a JSON object to a JSON string.
- */
-public class Serializer {
-
- /**
- * The writer to use when writing this JSON object.
- */
- private Writer writer;
-
- /**
- * Create a serializer on the specified output stream writer.
- */
- public Serializer(Writer writer) {
- super();
- this.writer = writer;
- }
-
- /**
- * Method to flush the current writer.
- * @throws IOException Thrown if an error occurs during writer flush.
- */
- public void flush() throws IOException {
- writer.flush();
- }
-
- /**
- * Method to close the current writer.
- * @throws IOException Thrown if an error occurs during writer close.
- */
- public void close() throws IOException {
- writer.close();
- }
-
- /**
- * Method to write a raw string to the writer.
- * @param s The String to write.
- * @throws IOException Thrown if an error occurs during write.
- */
- public Serializer writeRawString(String s) throws IOException {
- writer.write(s);
- return this;
- }
-
- /**
- * Method to write the text string 'null' to the output stream (null JSON object).
- * @throws IOException Thrown if an error occurs during write.
- */
- public Serializer writeNull() throws IOException {
- writeRawString("null");
- return this;
- }
-
- /**
- * Method to write a number to the current writer.
- * @param value The number to write to the JSON output string.
- * @throws IOException Thrown if an error occurs during write.
- */
- public Serializer writeNumber(Object value) throws IOException {
- if (null == value) return writeNull();
-
- if (value instanceof Float) {
- if (((Float)value).isNaN()) return writeNull();
- if (Float.NEGATIVE_INFINITY == ((Float)value).floatValue()) return writeNull();
- if (Float.POSITIVE_INFINITY == ((Float)value).floatValue()) return writeNull();
- }
-
- if (value instanceof Double) {
- if (((Double)value).isNaN()) return writeNull();
- if (Double.NEGATIVE_INFINITY == ((Double)value).doubleValue()) return writeNull();
- if (Double.POSITIVE_INFINITY == ((Double)value).doubleValue()) return writeNull();
- }
-
- writeRawString(value.toString());
-
- return this;
- }
-
- /**
- * Method to write a boolean value to the output stream.
- * @param value The Boolean object to write out as a JSON boolean.
- * @throws IOException Thrown if an error occurs during write.
- */
- public Serializer writeBoolean(Boolean value) throws IOException {
- if (null == value) return writeNull();
-
- writeRawString(value.toString());
-
- return this;
- }
-
- /**
- * Method to generate a string with a particular width. Alignment is done using zeroes if it does not meet the width requirements.
- * @param s The string to write
- * @param len The minimum length it should be, and to align with zeroes if length is smaller.
- * @return A string properly aligned/correct width.
- */
- private static String rightAlignedZero(String s, int len) {
- if (len == s.length()) return s;
-
- StringBuffer sb = new StringBuffer(s);
-
- while (sb.length() < len) {
- sb.insert(0, '0');
- }
-
- return sb.toString();
- }
-
- /**
- * Method to write a String out to the writer, encoding special characters and unicode characters properly.
- * @param value The string to write out.
- * @throws IOException Thrown if an error occurs during write.
- */
- public Serializer writeString(String value) throws IOException {
- if (null == value) return writeNull();
-
- writer.write('"');
-
- char[] chars = value.toCharArray();
-
- for (int i=0; i<chars.length; i++) {
- char c = chars[i];
- switch (c) {
- case '"': writer.write("\\\""); break;
- case '\\': writer.write("\\\\"); break;
- case 0: writer.write("\\0"); break;
- case '\b': writer.write("\\b"); break;
- case '\t': writer.write("\\t"); break;
- case '\n': writer.write("\\n"); break;
- case '\f': writer.write("\\f"); break;
- case '\r': writer.write("\\r"); break;
- case '/': writer.write("\\/"); break;
- default:
- if ((c >= 32) && (c <= 126)) {
- writer.write(c);
- } else {
- writer.write("\\u");
- writer.write(rightAlignedZero(Integer.toHexString(c),4));
- }
- }
- }
-
- writer.write('"');
-
- return this;
- }
-
- /**
- * Method to write out a generic JSON type.
- * @param object The JSON compatible object to serialize.
- * @throws IOException Thrown if an error occurs during write, or if a nonJSON compatible Java object is passed..
- */
- private Serializer write(Object object) throws IOException {
- if (null == object) return writeNull();
-
- // Serialize the various types!
- Class clazz = object.getClass();
- if (NumberUtil.isNumber(clazz)) return writeNumber(object);
- if (Boolean.class.isAssignableFrom(clazz)) return writeBoolean((Boolean) object);
- if (JSONObject.class.isAssignableFrom(clazz)) return writeObject((JSONObject) object);
- if (JSONArray.class.isAssignableFrom(clazz)) return writeArray((JSONArray) object);
- if (JSONString.class.isAssignableFrom(clazz)) return writeRawString(((JSONString) object).toJSONString());
- if (String.class.isAssignableFrom(clazz)) return writeString((String) object);
-
- throw new IOException("Attempting to serialize unserializable object: '" + object + "'");
- }
-
- /**
- * Method to write a complete JSON object to the stream.
- * @param object The JSON object to write out.
- * @throws IOException Thrown if an error occurs during write.
- */
- public Serializer writeObject(JSONObject object) throws IOException {
- if (null == object) return writeNull();
-
- // write header
- writeRawString("{");
- indentPush();
-
- Enumeration iter = getPropertyNames(object);
-
- while ( iter.hasMoreElements() ) {
- Object key = iter.nextElement();
- if (!(key instanceof String)) throw new IOException("attempting to serialize object with an invalid property name: '" + key + "'" );
-
- Object value = object.get(key);
- if (!JSONObject.isValidObject(value)) throw new IOException("attempting to serialize object with an invalid property value: '" + value + "'");
-
- newLine();
- indent();
- writeString((String)key);
- writeRawString(":");
- space();
- write(value);
-
- if (iter.hasMoreElements()) writeRawString(",");
- }
-
- // write trailer
- indentPop();
- newLine();
- indent();
- writeRawString("}");
-
- return this;
- }
-
- /**
- * Method to write a JSON array out to the stream.
- * @param value The JSON array to write out.
- * @throws IOException Thrown if an error occurs during write.
- */
- public Serializer writeArray(JSONArray value) throws IOException {
- if (null == value) return writeNull();
-
- // write header
- writeRawString("[");
- indentPush();
-
- for (Enumeration iter=value.elements(); iter.hasMoreElements(); ) {
- Object element = iter.nextElement();
- if (!JSONObject.isValidObject(element)) throw new IOException("attempting to serialize array with an invalid element: '" + value + "'");
-
- newLine();
- indent();
- write(element);
-
- if (iter.hasMoreElements()) writeRawString(",");
- }
-
- // write trailer
- indentPop();
- newLine();
- indent();
- writeRawString("]");
-
- return this;
- }
-
- //---------------------------------------------------------------
- // pretty printing overridables
- //---------------------------------------------------------------
-
- /**
- * Method to write a space to the output writer.
- * @throws IOException Thrown if an error occurs during write.
- */
- public void space() throws IOException {
- }
-
- /**
- * Method to write a newline to the output writer.
- * @throws IOException Thrown if an error occurs during write.
- */
- public void newLine() throws IOException {
- }
-
- /**
- * Method to write an indent to the output writer.
- * @throws IOException Thrown if an error occurs during write.
- */
- public void indent() throws IOException {
- }
-
- /**
- * Method to increase the indent depth of the output writer.
- * @throws IOException Thrown if an error occurs during write.
- */
- public void indentPush() {
- }
-
- /**
- * Method to reduce the indent depth of the output writer.
- */
- public void indentPop() {
- }
-
- /**
- * Method to get a list of all the property names stored in a map.
- */
- public Enumeration getPropertyNames(Hashtable map) {
- return map.keys();
- }
-
- /**
- * Method to write a String out to the writer, encoding special characters and unicode characters properly.
- * @param value The string to write out.
- */
- public static String quote(String value) {
- if (value == null || value.length() == 0) {
- return "\"\"";
- }
-
- StringBuffer buf = new StringBuffer();
- char[] chars = value.toCharArray();
-
- buf.append('"');
- for (int i=0; i<chars.length; i++) {
- char c = chars[i];
- switch (c) {
- case '"': buf.append("\\\""); break;
- case '\\': buf.append("\\\\"); break;
- case 0: buf.append("\\0"); break;
- case '\b': buf.append("\\b"); break;
- case '\t': buf.append("\\t"); break;
- case '\n': buf.append("\\n"); break;
- case '\f': buf.append("\\f"); break;
- case '\r': buf.append("\\r"); break;
- case '/': buf.append("\\/"); break;
- default:
- if ((c >= 32) && (c <= 126)) {
- buf.append(c);
- } else {
- buf.append("\\u");
- buf.append(rightAlignedZero(Integer.toHexString(c),4));
- }
- }
- }
- buf.append('"');
-
- return buf.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/SerializerVerbose.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/SerializerVerbose.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/SerializerVerbose.java
deleted file mode 100644
index 5132591..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/SerializerVerbose.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-import java.io.IOException;
-import java.io.Writer;
-
-/**
- * Internaql class for handling the serialization of JSON objects in a verbose
- * format, meaning newlines and indention.
- */
-public class SerializerVerbose extends Serializer {
-
- /**
- * Internal tracker keeping indent position.
- */
- private int indent = 0;
-
- /**
- * The indent string to use when serializing.
- */
- private String indentStr = "\t";
-
- /**
- * Constructor.
- */
- public SerializerVerbose(Writer writer) {
- super(writer);
- }
-
- /**
- * Constructor.
- * @param Writer The writer to serialize JSON to.
- * @param indentSpaces: How many spaces to indent by (0 to 8).
- * The default indent is the TAB character.
- */
- public SerializerVerbose(Writer writer, int indentSpaces) {
- super(writer);
- if(indentSpaces > 0 && indentSpaces < 8){
- this.indentStr = "";
- for(int i = 0; i < indentSpaces; i++){
- this.indentStr += " ";
- }
- }
- }
-
- /**
- * Method to write a space to the output writer.
- * @throws IOException Thrown if an error occurs during write.
- */
- public void space() throws IOException {
- writeRawString(" ");
- }
-
- /**
- * Method to write a newline to the output writer.
- * @throws IOException Thrown if an error occurs during write.
- */
- public void newLine() throws IOException {
- writeRawString("\n");
- }
-
- /**
- * Method to write an indent to the output writer.
- * @throws IOException Thrown if an error occurs during write.
- */
- public void indent() throws IOException {
- for (int i=0; i<indent; i++) writeRawString(this.indentStr);
- }
-
- /**
- * Method to increase the indent depth of the output writer.
- * @throws IOException Thrown if an error occurs during write.
- */
- public void indentPush() {
- indent++;
- }
-
- /**
- * Method to reduce the indent depth of the output writer.
- */
- public void indentPop() {
- indent--;
- if (indent < 0) throw new IllegalStateException();
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Token.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Token.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Token.java
deleted file mode 100644
index 1c635e9..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Token.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-/**
- * Class representing a JSON token.
- */
-public class Token {
-
- static final public Token TokenEOF = new Token();
- static final public Token TokenBraceL = new Token();
- static final public Token TokenBraceR = new Token();
- static final public Token TokenBrackL = new Token();
- static final public Token TokenBrackR = new Token();
- static final public Token TokenColon = new Token();
- static final public Token TokenComma = new Token();
- static final public Token TokenTrue = new Token();
- static final public Token TokenFalse = new Token();
- static final public Token TokenNull = new Token();
-
- private String valueString;
- private Object valueNumber;
- private boolean isConstant;
-
- /**
- * Constructor
- */
- public Token() {
- super();
- }
-
- /**
- * Constructor
- * @param value The value of the token as a string
- */
- public Token(String value) {
- super();
- valueString = value;
- }
-
- /**
- * Constructor
- * @param value The value of the token as a number
- */
- public Token(Object value) {
- super();
-
- valueNumber = value;
- }
-
- /**
- * Method to obtain the string value of this token
- */
- public String getString() {
- return valueString;
- }
-
- /**
- * Method to obtain the number value of this token
- */
- public Object getNumber() {
- return valueNumber;
- }
-
- /**
- * Method to indicate if this token is string based or not.
- */
- public boolean isString() {
- return (null != valueString) && !isConstant;
- }
-
- /**
- * Method to indicate if this token is number based or not.
- */
- public boolean isNumber() {
- return null != valueNumber;
- }
-
- /**
- * Method to convert the token to a string representation.
- */
- public String toString() {
- if (this == TokenEOF) return "Token: EOF";
- if (this == TokenBraceL) return "Token: {";
- if (this == TokenBraceR) return "Token: }";
- if (this == TokenBrackL) return "Token: [";
- if (this == TokenBrackR) return "Token: ]";
- if (this == TokenColon) return "Token: :";
- if (this == TokenComma) return "Token: ,";
- if (this == TokenTrue) return "Token: true";
- if (this == TokenFalse) return "Token: false";
- if (this == TokenNull) return "Token: null";
-
- if (this.isNumber()) return "Token: Number - " + getNumber();
- if (this.isString()) return "Token: String - '" + getString() + "'";
-
- return "Token: unknown.";
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Tokenizer.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Tokenizer.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Tokenizer.java
deleted file mode 100644
index 652106e..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/Tokenizer.java
+++ /dev/null
@@ -1,619 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-import java.io.IOException;
-import java.io.Reader;
-
-/**
- * Tokenizes a stream into JSON tokens.
- */
-public class Tokenizer {
-
- /**
- * The reader from which the JSON string is being read.
- */
- private Reader reader;
-
- /**
- * The current line position in the JSON string.
- */
- private int lineNo;
-
- /**
- * The current column position in the JSON string.
- */
- private int colNo;
-
- /**
- * The last character read from the JSON string.
- */
- private int lastChar;
-
- /**
- * Whether or not the parser should be spec strict, or allow unquoted strings and comments
- */
- private boolean strict = false;
-
- /**
- * Constructor.
- * @param reader The reader from which the JSON string is read. Same as Tokenizer(reader, false);
- *
- * @throws IOException Thrown on IOErrors such as invalid JSON or sudden reader closures.
- */
- public Tokenizer(Reader reader) throws IOException {
- super();
-
-// Class readerClass= reader.getClass();
- //In-memory readers don't need to be buffered. Also, skip PushbackReaders
- //because they probably already wrap a buffered stream. And lastly, anything
- //that extends from a BufferedReader also doesn't need buffering!
-// if (!StringReader.class.isAssignableFrom(readerClass) &&
-// !CharArrayReader.class.isAssignableFrom(readerClass) &&
-// !PushbackReader.class.isAssignableFrom(readerClass) &&
-// !BufferedReader.class.isAssignableFrom(readerClass)) {
-// reader = new BufferedReader(reader);
-// }
- this.reader = reader;
- this.lineNo = 0;
- this.colNo = 0;
- this.lastChar = '\n';
- readChar();
- }
-
- /**
- * Constructor.
- * @param reader The reader from which the JSON string is read.
- * @param strict Whether or not the parser should be spec strict, or allow unquoted strings and comments.
- *
- * @throws IOException Thrown on IOErrors such as invalid JSON or sudden reader closures.
- */
- public Tokenizer(Reader reader, boolean strict) throws IOException {
- super();
-
-// Class readerClass= reader.getClass();
- //In-memory readers don't need to be buffered. Also, skip PushbackReaders
- //because they probably already wrap a buffered stream. And lastly, anything
- //that extends from a BufferedReader also doesn't need buffering!
-// if (!StringReader.class.isAssignableFrom(readerClass) &&
-// !CharArrayReader.class.isAssignableFrom(readerClass) &&
-// !PushbackReader.class.isAssignableFrom(readerClass) &&
-// !BufferedReader.class.isAssignableFrom(readerClass)) {
-// reader = new BufferedReader(reader);
-// }
- this.reader = reader;
- this.lineNo = 0;
- this.colNo = 0;
- this.lastChar = '\n';
- this.strict = strict;
-
- readChar();
- }
-
- /**
- * Method to get the next JSON token from the JSON String
- * @return The next token in the stream, returning Token.TokenEOF when finished.
- *
- * @throws IOException Thrown if unexpected read error occurs or invalid character encountered in JSON string.
- */
- public Token next() throws IOException {
-
- // skip whitespace, use our own checker, it seems
- // a bit faster than Java's default.
- //while (Character.isWhitespace((char)lastChar)) {
- while (isWhitespace((char)lastChar)) {
- readChar();
- }
-
- // handle punctuation
- switch (lastChar) {
- case -1: readChar(); return Token.TokenEOF;
- case '{': readChar(); return Token.TokenBraceL;
- case '}': readChar(); return Token.TokenBraceR;
- case '[': readChar(); return Token.TokenBrackL;
- case ']': readChar(); return Token.TokenBrackR;
- case ':': readChar(); return Token.TokenColon;
- case ',': readChar(); return Token.TokenComma;
-
- case '"':
- case '\'':
- String stringValue = readString();
- return new Token(stringValue);
-
- case '-':
- case '.':
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- Object numberValue = readNumber();
- return new Token(numberValue);
-
- case 'n':
- case 't':
- case 'f':
- String ident = readIdentifier();
-
- if (ident.equals("null")) return Token.TokenNull;
- if (ident.equals("true")) return Token.TokenTrue;
- if (ident.equals("false")) return Token.TokenFalse;
-
- // Okay, this was some sort of unquoted string, may be okay
- if (!this.strict) {
- //Unquoted string. Non-strict mode allows this. It's still bad input
- //from a spec perspective, but allowable in non-strict mode.
- return new Token(ident);
- } else {
- throw new IOException("Unexpected unquoted string literal: [" + ident + "]. Unquoted strings are not allowed in strict mode");
- }
- case '/':
- if (!this.strict) {
- // Comment mode and not strict. Lets just devour the comment.
- readComment();
- return next();
- } else {
- throw new IOException("Unexpected character / encountered " + onLineCol() + ". Comments are not allowed in strict mode");
- }
-
- default:
- if (!this.strict && isValidUnquotedChar((char)lastChar)) {
- // Unquoted string. Bad form, but ... okay, lets accept it.
- // some other parsers do.
- String unquotedStr = readIdentifier();
- return new Token(unquotedStr);
- } else {
- if (this.strict) {
- throw new IOException("Unexpected character '" + (char)lastChar + "' " + onLineCol() + ". Unquoted strings are not allowed in strict mode.");
- } else {
- throw new IOException("Unexpected character '" + (char)lastChar + "' " + onLineCol());
- }
- }
- }
-
- }
-
- /**
- * Method to read out comments in the 'JSON'. JSON normally should not
- * have comments, but I guess we need to be more permissive to make some Crockford code
- * happy.
- */
- private void readComment() throws IOException {
- readChar();
- if ((char)lastChar == '/') {
- // Okay, // comment,so just read to \n or end of line
- while ((char)lastChar != '\n' && lastChar != -1) {
- readChar();
- }
- } else if ((char)lastChar == '*') {
- // /* comment, so read past it.
- char[] chars = new char[2];
- readChar();
- if (lastChar != -1) {
- chars[0] = (char)lastChar;
- } else {
- return;
- }
- readChar();
- if (lastChar != -1) {
- chars[1] = (char)lastChar;
- } else {
- return;
- }
-
- while (chars[0] != '*' || chars[1] != '/') {
- readChar();
- if (lastChar != -1) {
- chars[0] = chars[1];
- chars[1] = (char)lastChar;
-
- } else {
- return;
- }
- }
- }
- }
-
- /**
- * Method to read a string from the JSON string, converting escapes accordingly.
- * @return The parsed JSON string with all escapes properly converyed.
- *
- * @throws IOException Thrown on unterminated strings, invalid characters, bad escapes, and so on. Basically, invalid JSON.
- */
- private String readString() throws IOException {
- StringBuffer sb = new StringBuffer();
- int delim = lastChar;
- int l = lineNo;
- int c = colNo;
-
- readChar();
- while ((-1 != lastChar) && (delim != lastChar)) {
- StringBuffer digitBuffer;
-
- if (lastChar != '\\') {
- sb.append((char)lastChar);
- readChar();
- continue;
- }
-
- readChar();
-
- switch (lastChar) {
- case 'b': readChar(); sb.append('\b'); continue;
- case 'f': readChar(); sb.append('\f'); continue;
- case 'n': readChar(); sb.append('\n'); continue;
- case 'r': readChar(); sb.append('\r'); continue;
- case 't': readChar(); sb.append('\t'); continue;
- case '\'': readChar(); sb.append('\''); continue;
- case '"': readChar(); sb.append('"'); continue;
- case '\\': readChar(); sb.append('\\'); continue;
- case '/': readChar(); sb.append('/'); continue;
-
- // hex constant
- // unicode constant
- case 'x':
- case 'u':
- digitBuffer = new StringBuffer();
-
- int toRead = 2;
- if (lastChar == 'u') toRead = 4;
-
- for (int i=0; i<toRead; i++) {
- readChar();
- if (!isHexDigit(lastChar)) throw new IOException("non-hex digit " + onLineCol());
- digitBuffer.append((char) lastChar);
- }
- readChar();
-
- try {
- int digitValue = Integer.parseInt(digitBuffer.toString(), 16);
- sb.append((char) digitValue);
- } catch (NumberFormatException e) {
- throw new IOException("non-hex digit " + onLineCol());
- }
-
- break;
-
- // octal constant
- default:
- if (!isOctalDigit(lastChar)) throw new IOException("non-hex digit " + onLineCol());
-
- digitBuffer = new StringBuffer();
- digitBuffer.append((char) lastChar);
-
- for (int i=0; i<2; i++) {
- readChar();
- if (!isOctalDigit(lastChar)) break;
-
- digitBuffer.append((char) lastChar);
- }
-
- try {
- int digitValue = Integer.parseInt(digitBuffer.toString(), 8);
- sb.append((char) digitValue);
- } catch (NumberFormatException e) {
- throw new IOException("non-hex digit " + onLineCol());
- }
- }
- }
-
- if (-1 == lastChar) {
- throw new IOException("String not terminated " + onLineCol(l,c));
- }
-
- readChar();
-
- return sb.toString();
- }
-
- /**
- * Method to read a number from the JSON string.
- *
- * (-)(1-9)(0-9)* : decimal
- * (-)0(0-7)* : octal
- * (-)0(x|X)(0-9|a-f|A-F)* : hex
- * [digits][.digits][(E|e)[(+|-)]digits]
- *
- * @returns The number as the wrapper Java Number type.
- *
- * @throws IOException Thrown in invalid numbers or unexpected end of JSON string
- * */
- private Object readNumber() throws IOException {
- StringBuffer sb = new StringBuffer();
- int l = lineNo;
- int c = colNo;
-
- boolean isHex = false;
-
- if (lastChar == '-') {
- sb.append((char)lastChar);
- readChar();
- }
- if (lastChar == '0') {
- sb.append((char)lastChar);
- readChar();
- if (lastChar == 'x' || lastChar == 'X') {
- sb.append((char)lastChar);
- readChar();
- isHex = true;
- }
- }
-
- if (isHex) {
- while (isDigitChar(lastChar) || isHexDigit(lastChar)) {
- sb.append((char)lastChar);
- readChar();
- }
- }
- else {
- while (isDigitChar(lastChar)) {
- sb.append((char)lastChar);
- readChar();
- }
- }
-
- // convert it!
- String string = sb.toString();
-
- try {
- if (-1 != string.indexOf('.')) {
- return Double.valueOf(string);
- }
-
- String sign = "";
- if (string.startsWith("-")) {
- sign = "-";
- string = string.substring(1);
- }
-
-// if (isHex) {
-// Long value = Long.valueOf(sign + string.substring(2),16);
-// if (value.longValue() <= Integer.MAX_VALUE && (value.longValue() >= Integer.MIN_VALUE)) {
-// return new Integer(value.intValue());
-// }
-// else {
-// return value;
-// }
-// }
-
- if (string.equals("0")) {
- return new Integer(0);
-// } else if (string.startsWith("0") && string.length() > 1) {
-// Long value = Long.valueOf(sign + string.substring(1),8);
-// if (value.longValue() <= Integer.MAX_VALUE && (value.longValue() >= Integer.MIN_VALUE)) {
-// return new Integer(value.intValue());
-// }
-// else {
-// return value;
-// }
- }
-
- /**
- * We have to check for the exponential and treat appropriately
- * Exponentials should be treated as Doubles.
- */
- if (string.indexOf("e") != -1 || string.indexOf("E") != -1) {
- return Double.valueOf(sign + string);
- } else {
- Long value = new Long(Long.parseLong(sign+ string, 10));
- //Long value = Long.valueOf(sign + string);
- if (value.longValue() <= Integer.MAX_VALUE && (value.longValue() >= Integer.MIN_VALUE)) {
- return new Integer(Integer.parseInt(sign + string, 10));
- }
- else {
- return value;
- }
- }
- // else return new Integer(0); //MSN
- } catch (NumberFormatException e) {
- IOException iox = new IOException("Invalid number literal " + onLineCol(l,c));
- //MSNiox.setCause(e);
- throw iox;
- }
- }
-
- /**
- * Method to indicate if the character read is a HEX digit or not.
- * @param c The character to check for being a HEX digit.
- */
- private boolean isHexDigit(int c) {
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case 'A':
- case 'B':
- case 'C':
- case 'D':
- case 'E':
- case 'F':
- case 'a':
- case 'b':
- case 'c':
- case 'd':
- case 'e':
- case 'f':
- return true;
- }
-
- return false;
- }
-
- /**
- * Method to indicate if the character read is an OCTAL digit or not.
- * @param c The character to check for being a OCTAL digit.
- */
- private boolean isOctalDigit(int c) {
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- return true;
- }
-
- return false;
- }
-
- /**
- * Method to indicate if the character read is a digit or not.
- * @param c The character to check for being a digit.
- */
- private boolean isDigitChar(int c) {
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '.':
- case 'e':
- case 'E':
- case 'x':
- case 'X':
- case '+':
- case '-':
- return true;
- }
-
- return false;
- }
-
- /**
- * Method to read a partular character string.
- * only really need to handle 'null', 'true', and 'false'
- */
- private String readIdentifier() throws IOException {
- StringBuffer sb = new StringBuffer();
-
- if (this.strict) {
- while ((-1 != lastChar) && ( (Character.isUpperCase((char)lastChar)) || (Character.isLowerCase((char)lastChar)) ) ){
- sb.append((char)lastChar);
- readChar();
- }
- }
- else {
- while ((-1 != lastChar) && isValidUnquotedChar((char)lastChar)) {
- sb.append((char)lastChar);
- readChar();
- }
- }
-
- return sb.toString();
- }
-
- /**
- * Method to read the next character from the string, keeping track of line/column position.
- *
- * @throws IOEXception Thrown when underlying reader throws an error.
- */
- private void readChar() throws IOException {
- if ('\n' == lastChar) {
- this.colNo = 0;
- this.lineNo++;
- }
- lastChar = reader.read();
- if (-1 == lastChar) return ;
- colNo++;
- }
-
- /**
- * Method to generate a String indicationg the current line and column position in the JSON string.
- */
- private String onLineCol(int line, int col) {
- return "on line " + line + ", column " + col;
- }
-
- /**
- * Method to generate a String indicationg the current line and column position in the JSON string.
- */
- public String onLineCol() {
- return onLineCol(lineNo,colNo);
- }
-
- /**
- * High speed test for whitespace! Faster than the java one (from some testing).
- * @return if the indicated character is whitespace.
- */
- public boolean isWhitespace(char c) {
- switch (c) {
- case 9: //'unicode: 0009
- case 10: //'unicode: 000A'
- case 11: //'unicode: 000B'
- case 12: //'unicode: 000C'
- case 13: //'unicode: 000D'
- case 28: //'unicode: 001C'
- case 29: //'unicode: 001D'
- case 30: //'unicode: 001E'
- case 31: //'unicode: 001F'
- case ' ': // Space
- //case Character.SPACE_SEPARATOR:
- //case Character.LINE_SEPARATOR:
- //MSN case Character.PARAGRAPH_SEPARATOR:
- return true;
- }
- return false;
- }
-
- /**
- * For non strict mode, check if char is valid when not quoted.
- * @param c
- * @return if character is valid unquoted character.
- */
- public boolean isValidUnquotedChar(char c) {
-
- if ( (Character.isDigit(c)) || (Character.isLowerCase(c)) || (Character.isUpperCase(c)) ) {
- return true;
- }
-
- switch (c) {
- case '@':
- case '-':
- case '.':
- case '$':
- case '+':
- case '!':
- case '_':
- return true;
- }
- return false;
- }
-
-}
[17/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONObject.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONObject.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONObject.java
deleted file mode 100644
index 28c6216..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONObject.java
+++ /dev/null
@@ -1,1367 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-import java.io.UnsupportedEncodingException;
-import java.io.Writer;
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import org.apache.cordova.json4j.internal.JSON4JStringReader;
-import org.apache.cordova.json4j.internal.JSON4JStringWriter;
-import org.apache.cordova.json4j.internal.NumberUtil;
-import org.apache.cordova.json4j.internal.Parser;
-import org.apache.cordova.json4j.internal.Serializer;
-import org.apache.cordova.json4j.internal.SerializerVerbose;
-
-/**
- * Models a JSON Object.
- *
- * Extension of Hashtable that only allows String keys, and values which are JSON-able (such as a Java Bean).
- * <BR><BR>
- * JSON-able values are: null, and instances of String, Boolean, Number, JSONObject and JSONArray.
- * <BR><BR>
- * Instances of this class are not thread-safe.
- */
-public class JSONObject extends Hashtable implements JSONArtifact {
-
- private static final long serialVersionUID = -3269263069889337298L;
-
- /**
- * A constant definition reference to Java null.
- * Provided for API compatibility with other JSON parsers.
- */
- public static final Object NULL = new Null();
-
- /**
- * Return whether the object is a valid value for a property.
- * @param object The object to check for validity as a JSON property value.
- * @return boolean indicating if the provided object is directly convertable to JSON.
- */
- public static boolean isValidObject(Object object) {
- if (null == object) return true;
- return isValidType(object.getClass());
- }
-
- /**
- * Return whether the class is a valid type of value for a property.
- * @param clazz The class type to check for validity as a JSON object type.
- * @return boolean indicating if the provided class is directly convertable to JSON.
- */
- public static boolean isValidType(Class clazz) {
- if (null == clazz) throw new IllegalArgumentException();
-
- if (String.class == clazz) return true;
- if (Boolean.class == clazz) return true;
- if (JSONObject.class.isAssignableFrom(clazz)) return true;
- if (JSONArray.class == clazz) return true;
- if (NumberUtil.isNumber(clazz)) return true;
- if (JSONObject.NULL == clazz) return true;
- if (JSONString.class.isAssignableFrom(clazz)) return true;
-
- return false;
- }
-
- /**
- * Create a new instance of this class.
- */
- public JSONObject() {
- super();
- }
-
- /**
- * Create a new instance of this class taking selected values from the underlying one.
- * @param obj The JSONObject to extract values from.
- * @param keys The keys to take from the JSONObject and apply to this instance.
- * @throws JSONException Thrown if a key is duplicated in the string[] keys
- */
- public JSONObject(JSONObject obj, String[] keys) throws JSONException{
- super();
- if (keys != null && keys.length > 0) {
- for (int i = 0; i < keys.length; i++) {
- if (this.containsKey(keys[i])) {
- throw new JSONException("Duplicate key: " + keys[i]);
- }
- try {
- this.put(keys[i], obj.get(keys[i]));
- } catch (Exception ex) {
- JSONException jex = new JSONException("Error occurred during JSONObject creation");
- jex.setCause(ex);
- throw jex;
- }
- }
- }
- }
-
- /**
- * Create a new instance of this class from the provided JSON object string.
- * Note: This is the same as new JSONObject(str, false); Parsing in non-strict mode.
- * @param str The JSON string to parse.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONObject(String str) throws JSONException {
- super();
- JSON4JStringReader reader = new JSON4JStringReader(str);
- (new Parser(reader)).parse(this);
- }
-
- /**
- * Create a new instance of this class from the provided JSON object string.
- * @param str The JSON string to parse.
- * @param strict Whether or not to parse in 'strict' mode, meaning all strings must be quoted (including identifiers), and comments are not allowed.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONObject(String str, boolean strict) throws JSONException {
- super();
- JSON4JStringReader reader = new JSON4JStringReader(str);
- (new Parser(reader, strict)).parse(this);
- }
-
- /**
- * Create a new instance of this class from the data provided from the reader. The reader content must be a JSON object string.
- * Note: The reader will not be closed, that is left to the caller.
- * Note: This is the same as new JSONObject(rdr, false); Parsing in non-strict mode.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONObject(Reader rdr) throws JSONException {
- (new Parser(rdr)).parse(this);
- }
-
- /**
- * Create a new instance of this class from the data provided from the reader. The reader content must be a JSON object string.
- * Note: The reader will not be closed, that is left to the caller.
- * @param rdr The reader from which to read the JSON.
- * @param strict Whether or not to parse in 'strict' mode, meaning all strings must be quoted (including identifiers), and comments are not allowed.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONObject(Reader rdr, boolean strict) throws JSONException {
- (new Parser(rdr, strict)).parse(this);
- }
-
- /**
- * Create a new instance of this class from the data provided from the input stream. The stream content must be a JSON object string.
- * Note: The input stream content is assumed to be UTF-8 encoded.
- * Note: The InputStream will not be closed, that is left to the caller.
- * Note: This is the same as new JSONObject(is, false); Parsing in non-strict mode.
- * @param is The InputStream from which to read the JSON.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONObject (InputStream is) throws JSONException {
- InputStreamReader isr = null;
- if (is != null) {
- try {
- isr = new InputStreamReader(is, "UTF-8");
- } catch (Exception ex) {
- isr = new InputStreamReader(is);
- }
- } else {
- throw new JSONException("InputStream cannot be null");
- }
- (new Parser(isr)).parse(true, this);
- }
-
- /**
- * Create a new instance of this class from the data provided from the input stream. The stream content must be a JSON object string.
- * Note: The input stream content is assumed to be UTF-8 encoded.
- * Note: The InputStream will not be closed, that is left to the caller.
- * @param is The InputStream from which to read the JSON.
- * @param strict Whether or not to parse in 'strict' mode, meaning all strings must be quoted (including identifiers), and comments are not allowed.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONObject (InputStream is, boolean strict) throws JSONException {
- InputStreamReader isr = null;
- if (is != null) {
- try {
- isr = new InputStreamReader(is, "UTF-8");
- } catch (Exception ex) {
- isr = new InputStreamReader(is);
- }
- } else {
- throw new JSONException("InputStream cannot be null");
- }
- (new Parser(isr, strict)).parse(true, this);
- }
-
- /**
- * Write this object to the stream as JSON text in UTF-8 encoding. Same as calling write(os,false);
- * Note that encoding is always written as UTF-8, as per JSON spec.
- * @param os The output stream to write data to.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public OutputStream write(OutputStream os) throws JSONException {
- write(os,false);
- return os;
- }
-
- /**
- * Convert this object into a stream of JSON text. Same as calling write(writer,false);
- * Note that encoding is always written as UTF-8, as per JSON spec.
- * @param os The output stream to write data to.
- * @param verbose Whether or not to write the JSON text in a verbose format.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public OutputStream write(OutputStream os, boolean verbose) throws JSONException {
- Writer writer = null;
- try {
- //MSN BUFFERED
- writer = new OutputStreamWriter(os, "UTF-8");
- } catch (UnsupportedEncodingException uex) {
- JSONException jex = new JSONException(uex.toString());
- jex.setCause(uex);
- throw jex;
- }
- write(writer, verbose);
- try {
- writer.flush();
- } catch (Exception ex) {
- JSONException jex = new JSONException("Error during buffer flush");
- jex.setCause(ex);
- throw jex;
- }
- return os;
- }
-
- /**
- * Write this object to the stream as JSON text in UTF-8 encoding, specifying how many spaces should be used for each indent.
- * @param indentDepth How many spaces to use for each indent level. Should be one to eight.
- * Less than one means no intending, greater than 8 and it will just use tab.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public OutputStream write(OutputStream os, int indentDepth) throws JSONException {
- Writer writer = null;
- try {
- //MSN BUFFERED
- writer = new OutputStreamWriter(os, "UTF-8");
- } catch (UnsupportedEncodingException uex) {
- JSONException jex = new JSONException(uex.toString());
- jex.setCause(uex);
- throw jex;
- }
- write(writer, indentDepth);
- try {
- writer.flush();
- } catch (Exception ex) {
- JSONException jex = new JSONException("Error during buffer flush");
- jex.setCause(ex);
- throw jex;
- }
- return os;
- }
-
- /**
- * Write this object to the writer as JSON text. Same as calling write(writer,false);
- * @param writer The writer which to write the JSON text to.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public Writer write(Writer writer) throws JSONException {
- write(writer, false);
- return writer;
- }
-
- /**
- * Write this object to the writer as JSON text in UTF-8 encoding, specifying whether to use verbose (tab-indented) output or not.
- * @param writer The writer which to write the JSON text to.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public Writer write(Writer writer, boolean verbose) throws JSONException {
- Serializer serializer;
-
- //Try to avoid double-buffering or buffering in-memory
- //writers.
-// Class writerClass = writer.getClass();
- boolean flushIt = false;
-// if (!StringWriter.class.isAssignableFrom(writerClass) &&
-// !CharArrayWriter.class.isAssignableFrom(writerClass) &&
-// !BufferedWriter.class.isAssignableFrom(writerClass)) {
-// writer = new BufferedWriter(writer);
-// flushIt = true;
-// }
-
- if (verbose) {
- serializer = new SerializerVerbose(writer);
- } else {
- serializer = new Serializer(writer);
- }
-
- try {
- serializer.writeObject(this);
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- if (flushIt) {
- try {
- writer.flush();
- } catch (Exception ex) {
- JSONException jex = new JSONException("Error during buffer flush");
- jex.setCause(ex);
- throw jex;
- }
- }
- return writer;
- }
-
- /**
- * Write this object to the writer as JSON text, specifying how many spaces should be used for each indent.
- * This is an alternate indent style to using tabs.
- * @param writer The writer which to write the JSON text to.
- * @param indentDepth How many spaces to use for each indent. The value should be between one to eight.
- */
- public Writer write(Writer writer, int indentDepth) throws JSONException {
- Serializer serializer;
-
- if (indentDepth < 1) {
- indentDepth = 0;
- } else if (indentDepth > 8) {
- indentDepth = 9;
- }
-
- //Try to avoid double-buffering or buffering in-memory
- //writers.
-// Class writerClass = writer.getClass();
- boolean flushIt = false;
-// if (!StringWriter.class.isAssignableFrom(writerClass) &&
-// !CharArrayWriter.class.isAssignableFrom(writerClass) &&
-// !BufferedWriter.class.isAssignableFrom(writerClass)) {
-// writer = new BufferedWriter(writer);
-// flushIt = true;
-// }
-
- if (indentDepth > 0) {
- serializer = new SerializerVerbose(writer, indentDepth);
- } else {
- serializer = new Serializer(writer);
- }
- try {
- serializer.writeObject(this);
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- if (flushIt) {
- try {
- writer.flush();
- } catch (Exception ex) {
- JSONException jex = new JSONException("Error during buffer flush");
- jex.setCause(ex);
- throw jex;
- }
- }
- return writer;
- }
-
- /**
- * Convert this object into a String of JSON text, specifying how many spaces should be used for each indent.
- * This is an alternate indent style to using tabs.
- * @param indentDepth How many spaces to use for each indent. The value should be between one to eight.
- * Less than one means no indenting, greater than 8 and it will just use tab.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public String write(int indentDepth) throws JSONException {
- Serializer serializer;
- JSON4JStringWriter writer = new JSON4JStringWriter();
-
- if (indentDepth < 1) {
- indentDepth = 0;
- } else if (indentDepth > 8) {
- indentDepth = 9;
- }
-
- if (indentDepth > 0) {
- serializer = new SerializerVerbose(writer, indentDepth);
- } else {
- serializer = new Serializer(writer);
- }
- try {
- serializer.writeObject(this).flush();
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during write.");
- jex.setCause(iox);
- throw jex;
- }
- return writer.toString();
- }
-
- /**
- * Convert this object into a String of JSON text, specifying whether to use verbose (tab-indented) output or not.
- * @param verbose Whether or not to write in compressed format.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public String write(boolean verbose) throws JSONException {
- Serializer serializer;
- JSON4JStringWriter writer = new JSON4JStringWriter();
-
- if (verbose) {
- serializer = new SerializerVerbose(writer);
- } else {
- serializer = new Serializer(writer);
- }
- try {
- serializer.writeObject(this).flush();
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during write.");
- jex.setCause(iox);
- throw jex;
- }
- return writer.toString();
- }
-
- /**
- * Convert this object into a String of JSON text. Same as write(false);
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public String write() throws JSONException {
- return write(false);
- }
-
- /**
- * Method to obtain the object value for a key.
- * This string-based method is provided for API compatibility to other JSON models.
- * @param key The key (attribute) name to obtain the value for.
- * @throws JSONException Thrown if the noted key is not in the map of key/value pairs.
- */
- public Object get(String key) throws JSONException {
- Object val = this.get((Object)key);
- if (val == null) {
- if (!this.containsKey(key)) {
- throw new JSONException("The key [" + key + "] was not in the map");
- }
- }
- return val;
- }
-
- /**
- * Method to obtain the object value for a key. If the key is not in the map, null is returned.
- * This string-based method is provided for API compatibility to other JSON models.
- * @param key The key (attribute) name to obtain the value for.
- */
- public Object opt(String key) {
- return this.get((Object)key);
- }
-
- /**
- * (non-Javadoc)
- * @see java.util.HashMap#put(java.lang.Object, java.lang.Object)
- * @param key The key to put in the JSONObject
- * @param value The value to put in the JSONObject
- * @param includeSuperclass Boolean indicating that if the object is a JavaBean, include superclass getter properties.
- * @throws JSONException. Thrown if key is null, not a string, or the value could not be converted.
- */
- public Object put(Object key, Object value, boolean includeSuperclass) throws JSONException{
- if (null == key) throw new JSONException("key must not be null");
- if (!(key instanceof String)) throw new JSONException("key must be a String");
- if (!isValidObject(value)) {
- throw new JSONException("Invalid type of value. Could not convert type: [" + value.getClass().getName() + "]");
- }
- if (null == value) {
- value = NULL;
- }
- return super.put(key, value);
- }
-
- /**
- * (non-Javadoc)
- * @see java.util.HashMap#put(java.lang.Object, java.lang.Object)
- * This is the same as calling put(key, value, true);
- */
- public Object put(Object key, Object value) {
- try {
- return put(key, value, true);
- } catch (Exception e) {
- IllegalArgumentException iae = new IllegalArgumentException("Error occurred during JSON conversion");
- //MSN iae.setCause(e);
- throw iae;
- }
- }
-
- /**
- * Convenience functions, to help map from other JSON parsers.
- */
-
- /**
- * Similar to default HashMap put, except it returns JSONObject instead of Object.
- * @see java.util.HashMap#put(java.lang.Object, java.lang.Object)
- * @return A reference to this object instance.
- * @throws JSONException. Thrown if key is null, not a string, or the value could not be converted to JSON.
- */
- public JSONObject put(String key, Object value) throws JSONException{
- this.put((Object)key, value);
- return this;
- }
-
- /**
- * Method to add an atomic boolean to the JSONObject.
- * param key The key/attribute name to set the boolean at.
- * @param value The boolean value.
- * @throws JSONException. Thrown if key is null or not a string.
- * @return A reference to this object instance.
- */
- public JSONObject put(String key, boolean value) throws JSONException{
- this.put(key,new Boolean(value));
- return this;
- }
-
- /**
- * Method to add an atomic double to the JSONObject.
- * param key The key/attribute name to set the double at.
- * @param value The double value.
- * @throws JSONException. Thrown if key is null or not a string.
- * @return A reference to this object instance.
- */
- public JSONObject put(String key, double value) throws JSONException{
- this.put(key, new Double(value));
- return this;
- }
-
- /**
- * Method to add an atomic integer to the JSONObject.
- * param key The key/attribute name to set the integer at.
- * @param value The integer value.
- * @throws JSONException. Thrown if key is null or not a string.
- * @return A reference to this object instance.
- */
- public JSONObject put(String key, int value) throws JSONException{
- this.put(key, new Integer(value));
- return this;
- }
-
- /**
- * Method to add an atomic short to the JSONObject.
- * param key The key/attribute name to set the integer at.
- * @param value The integer value.
- * @throws JSONException. Thrown if key is null or not a string.
- * @return A reference to this object instance.
- */
- public JSONObject put(String key, short value) throws JSONException{
- this.put(key, new Short(value));
- return this;
- }
-
- /**
- * Method to add an atomic long to the JSONObject.
- * @param key The key/attribute name to set the long to.
- * @param value The long value.
- * @throws JSONException. Thrown if key is null or not a string.
- * @return A reference to this object instance.
- */
- public JSONObject put(String key, long value) throws JSONException{
- this.put(key, new Long(value));
- return this;
- }
-
- /**
- * Method to add an Object array as a new JSONArray contained in this JSONObject
- * @param key The key/attribute name to set the collection to.
- * @param value The Object array to convert to a JSONArray and store.
- * @throws JSONException Thrown when contents in the Collection cannot be converted to something JSONable.
- * @return A reference to this object instance.
- */
- public JSONObject put(String key, Object[] value) throws JSONException {
- return put (key, new JSONArray(value));
- }
-
- /**
- * Method to add an Object array as a new JSONArray contained in this JSONObject
- * @param key The key/attribute name to set the collection to.
- * @param value The Object array to convert to a JSONArray and store.
- * @param includeSuperclass For values of the Object array which are JavaBeans and are converted, include superclass getter properties.
- * @throws JSONException Thrown when contents in the Collection cannot be converted to something JSONable.
- * @return A reference to this object instance.
- *
- public JSONObject put(String key, Object[] value, boolean includeSuperclass) throws JSONException {
- return put (key, new JSONArray(value), includeSuperclass);
- } */
-
- /**
- * Utility method to obtain the specified key as a 'boolean' value
- * Only boolean true, false, and the String true and false will return. In this case null, the number 0, and empty string should be treated as false.
- * everything else is true.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * throws JSONException Thrown when the type returned by get(key) is not a boolean instance, or the strings 'true' or 'false'.
- * @return A boolean value (true or false), if the value stored for key is a Boolean, or the strings 'true' or 'false'.
- */
- public boolean getBoolean(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (val instanceof Boolean) {
- return((Boolean)val).booleanValue();
- } else if (NumberUtil.isNumber(val.getClass())) {
- throw new JSONException("Value at key: [" + key + "] was not a boolean or string value of 'true' or 'false'.");
- } else if (String.class.isAssignableFrom(val.getClass())) {
- String str = (String)val;
- if (str.equals("true")) {
- return true;
- } else if (str.equals("false")) {
- return false;
- } else {
- throw new JSONException("The value for key: [" + key + "]: [" + str + "] was not 'true' or 'false'");
- }
- } else {
- throw new JSONException("The value for key: [" + key + "] was not a type that can be converted to boolean");
- }
- } else {
- throw new JSONException("The value for key: [" + key + "] was null");
- }
- }
-
- /**
- * Utility method to obtain the specified key as a 'boolean' value
- * Only returns true if the value is boolean true or the string 'true'. All other values return false.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @return A boolean value (true or false), if the value stored for key is a Boolean, or the strings 'true' or 'false'.
- */
- public boolean optBoolean(String key) {
- Object val = this.opt(key);
- if (val != null) {
- if (val instanceof Boolean) {
- return((Boolean)val).booleanValue();
- } else if (NumberUtil.isNumber(val.getClass())) {
- return false;
- } else if (String.class.isAssignableFrom(val.getClass())) {
- String str = (String)val;
- if (str.equals("true")) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
-
- /**
- * Utility method to obtain the specified key as a 'boolean' value
- * Only returns true if the value is boolean true or the string 'true'. All other values return false.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @param defaultValue The default value to return.
- * @return A boolean value (true or false), if the value stored for key is a Boolean, or the strings 'true' or 'false'.
- */
- public boolean optBoolean(String key, boolean defaultValue) {
- Object val = this.opt(key);
- if (val != null) {
- if (val instanceof Boolean) {
- return((Boolean)val).booleanValue();
- } else if (NumberUtil.isNumber(val.getClass())) {
- return false;
- } else if (String.class.isAssignableFrom(val.getClass())) {
- String str = (String)val;
- if (str.equals("true")) {
- return true;
- } else if (str.equals("false")) {
- return false;
- } else {
- return defaultValue;
- }
- } else {
- return defaultValue;
- }
- } else {
- return defaultValue;
- }
- }
-
- /**
- * Utility method to obtain the specified key as a 'double' value
- * Only values of Number will be converted to double, all other types will generate an exception
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * throws JSONException Thrown when the type returned by get(key) is not a Double instance, or cannot be converted to a double.
- * @return A double value if the value stored for key is an instance of Number.
- */
- public double getDouble(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getDouble(val);
- }
- else {
- throw new JSONException("The value for key: [" + key + "] was not a type that can be converted to double");
- }
- } else {
- throw new JSONException("The value for key: [" + key + "] was null. Number required.");
- }
- }
-
- /**
- * Utility method to obtain the specified key as a 'double' value
- * Only values of Number will be converted to double. all other values will return Double.NaN.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @return A double value if the value stored for key is an instance of Number.
- */
- public double optDouble(String key) {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getDouble(val);
- }
- }
- return Double.NaN;
- }
-
- /**
- * Utility method to obtain the specified key as a 'double' value
- * Only values of Number will be converted to double. all other values will return Double.NaN.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @param defaultValue The default double value to return in case of NaN/null values in map.
- * @return A double value if the value stored for key is an instance of Number.
- */
- public double optDouble(String key, double defaultValue) {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getDouble(val);
- }
- }
- return defaultValue;
- }
-
- /**
- * Utility method to obtain the specified key as a 'short' value
- * Only values of Number will be converted to short, all other types will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * throws JSONException Thrown when the type returned by get(key) is not a Short instance, or cannot be converted to a short.
- * @return A short value if the value stored for key is an instance of Number.
- */
- public short getShort(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getShort(val);
- } else {
- throw new JSONException("The value for key: [" + key + "] was not a type that can be converted to short");
- }
- } else {
- throw new JSONException("The value for key: [" + key + "] was null. Number required.");
- }
- }
-
- /**
- * Utility method to obtain the specified key as a 'short' value
- * Only values of Number will be converted to short. All other types return 0.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @return A short value if the value stored for key is an instance of Number. 0 otherwise.
- */
- public short optShort(String key) {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getShort(val);
- }
- }
- return(short)0;
- }
-
- /**
- * Utility method to obtain the specified key as a 'short' value
- * Only values of Number will be converted to short.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @param defaultValue The default value to return in the case of null/nonNumber values in the map.
- * @return A short value if the value stored for key is an instance of Number. 0 otherwise.
- */
- public short optShort(String key, short defaultValue) {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getShort(val);
- }
- }
- return defaultValue;
- }
-
- /**
- * Utility method to obtain the specified key as a 'int' value
- * Only values of Number will be converted to integer, all other types will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * throws JSONException Thrown when the type returned by get(key) is not a Double instance, or cannot be converted to a double.
- * @return A int value if the value stored for key is an instance of Number.
- */
- public int getInt(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getInt(val);
- } else {
- throw new JSONException("The value for key: [" + key + "] was not a type that can be converted to integer");
- }
- } else {
- throw new JSONException("The value for key: [" + key + "] was null. Number required.");
- }
- }
-
- /**
- * Utility method to obtain the specified key as a 'int' value
- * Provided for compatibility to other JSON models.
- * Only values of Number will be converted to integer, all other types will return 0.
- * @param key The key to look up.
- * @return A int value if the value stored for key is an instance of Number. 0 otherwise.
- */
- public int optInt(String key) {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getInt(val);
- }
- }
- return 0;
- }
-
- /**
- * Utility method to obtain the specified key as a 'int' value
- * Provided for compatibility to other JSON models.
- * Only values of Number will be converted to integer
- * @param key The key to look up.
- * @param defaultValue The default int value to return in case of null/non-number values in the map.
- * @return A int value if the value stored for key is an instance of Number.
- */
- public int optInt(String key, int defaultValue) {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getInt(val);
- }
- }
- return defaultValue;
- }
-
- /**
- * Utility method to obtain the specified key as a 'long' value
- * Only values of Number will be converted to long, all other types will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * throws JSONException Thrown when the type returned by get(key) is not a Long instance, or cannot be converted to a long..
- * @return A long value if the value stored for key is an instance of Number.
- */
- public long getLong(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getLong(val);
- } else {
- throw new JSONException("The value for key: [" + key + "] was not a type that can be converted to long");
- }
- } else {
- throw new JSONException("The value for key: [" + key + "] was null. Number required.");
- }
- }
-
- /**
- * Utility method to obtain the specified key as a 'long' value
- * Only values of Number will be converted to long. all other types return 0.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @return A long value if the value stored for key is an instance of Number, 0 otherwise.
- */
- public long optLong(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getLong(val);
- }
- }
- return(long)0;
- }
-
- /**
- * Utility method to obtain the specified key as a 'long' value
- * Only values of Number will be converted to long. all other types return 0.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @param defaultValue The default long value to return in case of null/non Number values in the map.
- * @return A long value if the value stored for key is an instance of Number, defaultValue otherwise.
- */
- public long optLong(String key, long defaultValue) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getLong(val);
- }
- }
- return defaultValue;
- }
-
- /**
- * Utility method to obtain the specified key as a 'string' value
- * Only values that can be easily converted to string will be returned. A null will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * throws JSONException Thrown when the type returned by get(key) is null.
- * @return A string value if the value if the value stored for key is not null.
- */
- public String getString(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- return val.toString();
- } else {
- throw new JSONException("The value for key: [" + key + "] was null. Object required.");
- }
- }
-
- /**
- * Utility method to obtain the specified key as a 'string' value
- * Only values that can be easily converted to string will be returned. A null will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * throws JSONException Thrown when the type returned by get(key) is null.
- * @return A string value if the value if the value stored for key is not null.
- */
- public String optString(String key) {
- Object val = this.opt(key);
- if (val != null) {
- return val.toString();
- }
- return null;
- }
-
- /**
- * Utility method to obtain the specified key as a 'string' value
- * Only values that can be easily converted to string will be returned. A null will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @param defaultValue The default String value to return in the case of null values in the map.
- * @return A string value if the value if the value stored for key is not null, defaultValue otherwise.
- */
- public String optString(String key, String defaultValue) {
- Object val = this.opt(key);
- if (val != null) {
- return val.toString();
- }
- return defaultValue;
- }
-
- /**
- * Utility method to obtain the specified key as a JSONObject
- * Only values that are instances of JSONObject will be returned. A null will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * throws JSONException Thrown when the type returned by get(key) is not a JSONObject instance.
- * @return A JSONObject value if the value stored for key is an instance or subclass of JSONObject.
- */
- public JSONObject getJSONObject(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (JSONObject.class.isAssignableFrom(val.getClass())) {
- return(JSONObject)val;
- } else {
- throw new JSONException("The value for key: [" + key + "] was not a JSONObject");
- }
- } else {
- throw new JSONException("The value for key: [" + key + "] was null. Object required.");
- }
- }
-
- /**
- * Utility method to obtain the specified key as a JSONObject
- * Only values that are instances of JSONObject will be returned. A null will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @return A JSONObject value if the value stored for key is an instance or subclass of JSONObject, null otherwise.
- */
- public JSONObject optJSONObject(String key) {
- Object val = this.opt(key);
- if (val != null) {
- if (JSONObject.class.isAssignableFrom(val.getClass())) {
- return(JSONObject)val;
- }
- }
- return null;
- }
-
- /**
- * Utility method to obtain the specified key as a JSONObject
- * Only values that are instances of JSONObject will be returned. A null will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @param defaultValue The default JSONObject to return in the case of null/non JSONObject values in the map.
- * @return A JSONObject value if the value stored for key is an instance or subclass of JSONObject, defaultValue otherwise.
- */
- public JSONObject optJSONObject(String key, JSONObject defaultValue) {
- Object val = this.opt(key);
- if (val != null) {
- if (JSONObject.class.isAssignableFrom(val.getClass())) {
- return(JSONObject)val;
- }
- }
- return defaultValue;
- }
-
- /**
- * Utility method to obtain the specified key as a JSONArray
- * Only values that are instances of JSONArray will be returned. A null will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * throws JSONException Thrown when the type returned by get(key) is not a Long instance, or cannot be converted to a long..
- * @return A JSONArray value if the value stored for key is an instance or subclass of JSONArray.
- */
- public JSONArray getJSONArray(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (JSONArray.class.isAssignableFrom(val.getClass())) {
- return(JSONArray)val;
- } else {
- throw new JSONException("The value for key: [" + key + "] was not a JSONObject");
- }
- } else {
- throw new JSONException("The value for key: [" + key + "] was null. Object required.");
- }
- }
-
- /**
- * Utility method to obtain the specified key as a JSONArray
- * Only values that are instances of JSONArray will be returned. A null will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @return A JSONArray value if the value stored for key is an instance or subclass of JSONArray, null otherwise.
- */
- public JSONArray optJSONArray(String key) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (JSONArray.class.isAssignableFrom(val.getClass())) {
- return(JSONArray)val;
- }
- }
- return null;
- }
-
- /**
- * Utility method to obtain the specified key as a JSONArray
- * Only values that are instances of JSONArray will be returned. A null will generate an exception.
- * Provided for compatibility to other JSON models.
- * @param key The key to look up.
- * @param defaultValue The default value to return if the value in the map is null/not a JSONArray.
- * @return A JSONArray value if the value stored for key is an instance or subclass of JSONArray, defaultValue otherwise.
- */
- public JSONArray optJSONArray(String key, JSONArray defaultValue) throws JSONException {
- Object val = this.opt(key);
- if (val != null) {
- if (JSONArray.class.isAssignableFrom(val.getClass())) {
- return(JSONArray)val;
- }
- }
- return defaultValue;
- }
-
- /**
- * Put a key/value pair into the JSONObject, but only if key/value are both not null, and only if the key is not present already.
- * Provided for compatibility to existing models.
- * @param key The ket to place in the array
- * @param value The value to place in the array
- * @return Reference to the current JSONObject.
- * @throws JSONException - Thrown if the key already exists or if key or value is null
- */
- public JSONObject putOnce(String key, Object value) throws JSONException {
- if (key == null) {
- throw new JSONException("Key cannot be null");
- }
- if (value == null) {
- throw new JSONException("Value cannot be null");
- }
- if (this.containsKey(key)) {
- throw new JSONException("Key [" + key + "] already exists in the map");
- }
- this.put(key,value);
- return this;
- }
-
- /**
- * Put a key/value pair into the JSONObject, but only if the key and value are non-null.
- * @param key The keey (attribute) name to assign to the value.
- * @param value The value to put into the JSONObject.
- * @return Reference to the current JSONObject.
- * @throws JSONException - if the value is a non-finite number
- */
- public JSONObject putOpt(String key, Object value) throws JSONException {
- if (key == null) {
- throw new JSONException("Key cannot be null");
- }
- if (value == null) {
- throw new JSONException("Value cannot be null");
- }
- this.put(key,value);
- return this;
- }
-
- /**
- * Method to return the number of keys in this JSONObject.
- * This function merely maps to HashMap.size(). Provided for API compatibility.
- * @return returns the number of keys in the JSONObject.
- */
- public int length() {
- return this.size();
- }
-
- /**
- * Method to append the 'value' object to the element at entry 'key'.
- * If JSONObject.has(key) returns false, a new array is created and the value is appended to it.
- * If the object as position key is not an array, then a new JSONArray is created
- * and both current and new values are appended to it, then the value of the attribute is set to the new
- * array. If the current value is already an array, then 'value' is added to it.
- *
- * @param key The key/attribute name to append to.
- * @param value The value to append to it.
- *
- * @throws JSONException Thrown if the value to append is not JSONAble.
- * @return A reference to this object instance.
- */
- public JSONObject append(String key, Object value) throws JSONException {
- JSONArray array = null;
- if (!this.has(key)) {
- array = new JSONArray();
- }
- else {
- Object oldVal = this.get(key);
- array = new JSONArray();
- if (oldVal == null) {
- // Add a null if the key was actually there, but just
- // had value of null.
- array.add(null);
- }
- else if (JSONArray.class.isAssignableFrom(oldVal.getClass())) {
- array = (JSONArray)oldVal;
- } else {
- array = new JSONArray();
- array.add(oldVal);
- }
- }
- array.add(value);
- return put(key,array);
- }
-
- /**
- * Produce a JSONArray containing the values of the members of this JSONObject
- * @param names - A JSONArray containing the a list of key strings. This determines the sequence of values in the result.
- * @return A JSONArray of the values found for the names provided.
- * @throws JSONException - if errors occur during storing the values in a JSONArray
- */
- public JSONArray toJSONArray(JSONArray names) throws JSONException {
- Enumeration itr = names.elements();
- JSONArray array = new JSONArray();
- //MSN WAS IF, SHOULD BE WHILE?
- while (itr != null && itr.hasMoreElements()) {
- array.put(this.get(itr.nextElement()));
- }
- return array;
- }
-
-
- /**
- * Method to test if a key exists in the JSONObject.
- * @param key The key to test.
- * @return true if the key is defined in the JSONObject (regardless of value), or false if the key is not in the JSONObject
- */
- public boolean has(String key) {
- if (key != null) {
- return this.containsKey(key);
- }
- return false;
- }
-
- /**
- * Method to test if a key is mapped to null. This method will also return
- * true if the key has not been put in the JSONObject yet,
- *
- * @param key The key to test for null.
- * @return true if the key is not in the map or if the value referenced by the
- * key is null, or if the value is the JSONObject.NULL object.
- */
- public boolean isNull(String key) {
- Object obj = this.opt(key);
- return JSONObject.NULL.equals(obj);
- }
-
- /**
- * Utility function that returns an iterator of all the keys (attributes) of this JSONObject
- * @return An iterator of all keys in the object.
- *
- public Enumeration keys() {
- return this.keys();
-
- } */
-
- /**
- * Utility function that returns a JSONArray of all the names of the keys (attributes) of this JSONObject
- * @return All the keys in the JSONObject as a JSONArray.
- */
- public JSONArray names() {
- Enumeration itr = this.keys();
- if (itr != null) {
- JSONArray array = new JSONArray();
- while (itr.hasMoreElements()) {
- array.add(itr.nextElement());
- }
- return array;
- }
- return null;
- }
-
- /**
- * Utility function that returns a String[] of all the names of the keys (attributes) of this JSONObject
- * @return All the keys in the JSONObject as a String[].
- */
- public static String[] getNames(JSONObject obj) {
- String[] array = null;
- if (obj != null) {
- if (obj.size() > 0) {
- array = new String[obj.size()];
- int pos = 0;
- Enumeration itr = obj.keys();
- if (itr != null) {
- while (itr.hasMoreElements()) {
- array[pos] = (String)itr.nextElement();
- pos++;
- }
- }
- }
- }
- return array;
- }
-
-// /**
-// * Utility function that returns an iterator of all the keys (attributes) of this JSONObject sorted in lexicographic manner (String.compareTo).
-// * @return An iterator of all keys in the object in lexicographic (character code) sorted order.
-// */
-// public Enumeration sortedKeys() {
-// Enumeration itr = this.keys();
-// if (itr != null && itr.hasMoreElements()) {
-// Vector vect = new Vector();
-// while (itr.hasMoreElements()) {
-// vect.addElement(itr.nextElement());
-// }
-// String[] strs = new String[vect.size()];
-// vect.copyInto(strs);
-// // java.util.Arrays.sort(strs);
-// vect.clear();
-// for (int i = 0; i < strs.length; i++) {
-// vect.add(strs[i]);
-// }
-// return vect.iterator();
-// }
-// return null;
-// }
-
- /**
- * End of convenience methods.
- */
-
- /**
- * Over-ridden toString() method. Returns the same value as write(), which is a compact JSON String.
- * If an error occurs in the serialization, the return will be of format: JSON Generation Error: [<some error>]
- * @return A string of JSON text, if possible.
- */
- public String toString() {
- return toString(false);
- }
-
- /**
- * Verbose capable toString method.
- * If an error occurs in the serialization, the return will be of format: JSON Generation Error: [<some error>]
- * @param verbose Whether or not to tab-indent the output.
- * @return A string of JSON text, if possible.
- */
- public String toString(boolean verbose) {
- String str = null;
- try {
- str = write(verbose);
- } catch (JSONException jex) {
- str = "JSON Generation Error: [" + jex.toString() + "]";
- }
- return str;
- }
-
- /**
- * Function to return a string of JSON text with specified indention. Returns the same value as write(indentDepth).
- * If an error occurs in the serialization, a JSONException is thrown.
- * @return A string of JSON text, if possible.
- */
- public String toString(int indentDepth) throws JSONException {
- return write(indentDepth);
- }
-
- public static String quote(String string) {
- return Serializer.quote(string);
- }
-
- /**
- * An simple class provided for API compatibility to other JSON models that 'represents'
- * 'null' in an actual object.
- */
- private static class Null implements JSONString {
-
- /**
- * Equals function that returns true for comparisons to null.
- */
- public boolean equals(Object obj) {
- if (obj == null || obj == this) {
- return true;
- }
- else {
- return false;
- }
- }
-
- /**
- * Ensure only one Null object.
- */
- protected Object clone() {
- return this;
- }
-
- /**
- * toString method that just returns 'null' as the string.
- */
- public String toString() {
- return "null";
- }
-
- /**
- * Method to return a JSON compliant representation of this object.
- * @return a JSON formatted string.
- */
- public String toJSONString() {
- return this.toString();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONString.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONString.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONString.java
deleted file mode 100644
index b887adb..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONString.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j;
-
-/**
- * An interface that can be implemented to make a
- * particular object have an easy to use JSON representation. Objects that implement this
- * can be inserted into JSONObject and JSONArray and serialized.
- */
-public interface JSONString {
- /**
- * Method to return a JSON compliant representation of this object.
- * @return a JSON formatted string.
- */
- public String toJSONString();
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONStringer.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONStringer.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONStringer.java
deleted file mode 100644
index 10fb7a8..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONStringer.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j;
-
-import java.io.IOException;
-
-import org.apache.cordova.json4j.internal.JSON4JStringWriter;
-
-/**
- * This class implements a JSONSringer, a basic convenience subclass of JSONWriter to allow for
- * generating JSON strings quickly. This class exists for API compatibility to other popular
- * JSON parsers.
- */
-public class JSONStringer extends JSONWriter {
-
- public JSONStringer() {
- super(new JSON4JStringWriter());
- }
-
- /**
- * Return a string of the stringer contents. This also terminates the
- * Stringer and it cannot be used again. If any errors occur while trying to generate the JSON
- * it returns an empty string.
- */
- public String toString() {
- try {
- super.flush();
- super.close();
- return ((JSON4JStringWriter)writer).toString();
- } catch (Exception ex) {
- /* Squelch */
- return "";
- }
- }
-
- /**
- * Over-ride to do nothing for the stringer. Only toString() terminates the stringer object.
- */
- public void close() throws IOException, IllegalStateException {
- // Do nothing.
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONWriter.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONWriter.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONWriter.java
deleted file mode 100644
index 1914f58..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONWriter.java
+++ /dev/null
@@ -1,586 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Stack;
-
-import org.apache.cordova.json4j.internal.NumberUtil;
-
-/**
- * This class implements a JSONWrier, a convenience function for writing out JSON
- * to a writer or underlying stream.
- */
-public class JSONWriter {
-
- /**
- * The writer to use to output JSON in a semi-streaming fashion.
- */
- protected Writer writer = null;
-
- /**
- * Flag to denote that the writer is in an object.
- */
- private boolean inObject = false;
-
- /**
- * Flag to denote that the writer is in an array.
- */
- private boolean inArray = false;
-
- /**
- * Flag for state checking that a key was placed (if inside an object)
- * Required to be true for a value to be placed in that situation
- */
- private boolean keyPlaced = false;
-
- /**
- * Flag denoting if in an array or object, if the first entry has been placed or not.
- */
- private boolean firstEntry = false;
-
- /**
- * A stack to keep track of all the closures.
- */
- private Stack closures = null;
-
- /**
- * Flag used to check the state of this writer, if it has been closed, all
- * operations will throw an IllegalStateException.
- */
- private boolean closed = false;
-
- /**
- * Constructor.
- * @param writer The writer to use to do 'streaming' JSON writing.
- * @throws NullPointerException Thrown if writer is null.
- */
- public JSONWriter(Writer writer) throws NullPointerException {
- //Try to avoid double-buffering or buffering in-memory writers.
-// Class writerClass = writer.getClass();
-// if (!StringWriter.class.isAssignableFrom(writerClass) &&
-// !CharArrayWriter.class.isAssignableFrom(writerClass) &&
-// !BufferedWriter.class.isAssignableFrom(writerClass)) {
-// writer = new BufferedWriter(writer);
-// }
- this.writer = writer;
- this.closures = new Stack();
- }
-
- /**
- * Open a new JSON Array in the output stream.
- * @throws IOException Thrown if an error occurs on the underlying writer.
- * @throws IllegalstateException Thrown if the current writer position does not permit an array.
- * @return A reference to this writer.
- */
- public JSONWriter array() throws IOException, IllegalStateException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (inObject) {
- if (!keyPlaced) {
- throw new IllegalStateException("Current containment is a JSONObject, but a key has not been specified to contain a new array");
- }
- } else if (inArray) {
- if (!firstEntry) {
- writer.write(",");
- }
- }
- writer.write("[");
- inArray = true;
- inObject = false;
- keyPlaced = false;
- firstEntry = true;
- closures.push("]");
- return this;
- }
-
- /**
- * Method to close the current JSON Array in the stream.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws IllegalStateException Thrown if the writer position is not inside an array.
- * @return A reference to this writer.
- */
- public JSONWriter endArray() throws IOException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (!inArray) {
- throw new IllegalStateException("Current writer position is not within a JSON array");
- } else {
- writer.write(((String)closures.pop()));
- // Set our current positional/control state.
- if (!closures.isEmpty()) {
- String nextClosure = (String)closures.peek();
- if (nextClosure.equals("}")) {
- inObject = true;
- inArray = false;
- } else {
- inObject = false;
- inArray = true;
- }
- firstEntry = false;
- } else {
- inArray = false;
- inObject = false;
- firstEntry = true;
- }
- }
- return this;
- }
-
- /**
- * Method to close a current JSON object in the stream.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws IllegalStateException Thrown if the writer position is not inside an object, or if the object has a key placed, but no value.
- * @return A reference to this writer.
- */
- public JSONWriter endObject() throws IOException, IllegalStateException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (!inObject) {
- throw new IllegalStateException("Current writer position is not within a JSON object");
- } else {
- if (keyPlaced) {
- throw new IllegalStateException("Current writer position in an object and has a key placed, but no value has been assigned to the key. Cannot end.");
- } else {
- writer.write((String)closures.pop());
- // Set our current positional/control state.
- if (!closures.isEmpty()) {
- String nextClosure = (String)closures.peek();
- if (nextClosure.equals("}")) {
- inObject = true;
- inArray = false;
- } else {
- inObject = false;
- inArray = true;
- }
- firstEntry = false;
- } else {
- inArray = false;
- inObject = false;
- firstEntry = true;
- }
- }
- }
- return this;
- }
-
- /**
- * Place a key in the current JSON Object.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws IllegalStateException Thrown if the current writer position is not within an object.
- * @return A reference to this writer.
- */
- public JSONWriter key(String s) throws IOException, IllegalStateException, NullPointerException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (s == null) {
- throw new NullPointerException("Key cannot be null");
- } else {
- if (!inObject) {
- throw new IllegalStateException("Current writer position is not inside a JSON Object, a key cannot be placed.");
- } else {
- if (!keyPlaced) {
- if (firstEntry) {
- firstEntry = false;
- } else {
- writer.write(",");
- }
- keyPlaced = true;
- writeString(s);
- writer.write(":");
- } else {
- throw new IllegalStateException("Current writer position is inside a JSON Object an with an open key waiting for a value. Another key cannot be placed.");
- }
- }
- }
- return this;
- }
-
- /**
- * Open a new JSON Object in the output stream.
- * @throws IllegalStateException Thrown if an object cannot currently be created in the stream.
- * @throws IOException Thrown if an IO error occurs in the underlying writer.
- * @return A reference to this writer.
- */
- public JSONWriter object() throws IOException, IllegalStateException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (inObject) {
- if (!keyPlaced) {
- throw new IllegalStateException("Current containment is a JSONObject, but a key has not been specified to contain a new object");
- }
- } else if (inArray) {
- if (!firstEntry) {
- writer.write(",");
- }
- }
- writer.write("{");
- inObject = true;
- inArray = false;
- keyPlaced = false;
- firstEntry = true;
- closures.push("}");
- return this;
- }
-
- /**
- * Method to write a boolean to the current writer position.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws IllegalStateException Thrown if the current writer position will not accept a boolean value.
- * @return A reference to this writer.
- */
- public JSONWriter value(boolean b) throws IOException, IllegalStateException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (inArray) {
- if (firstEntry) {
- firstEntry = false;
- } else {
- writer.write(",");
- }
- if (b)
- writer.write("true");
- else
- writer.write("false");
-
- } else if (inObject) {
- if (keyPlaced) {
- if (b)
- writer.write("true");
- else
- writer.write("false");
- keyPlaced = false;
- } else {
- throw new IllegalStateException("Current containment is a JSONObject, but a key has not been specified for the boolean value.");
- }
- } else {
- throw new IllegalStateException("Writer is currently not in an array or object, cannot write value");
- }
- return this;
- }
-
- /**
- * Method to write a double to the current writer position.
- * @param d The Double to write.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws IllegalStateException Thrown if the current writer position will not accept a double value.
- * @return A reference to this writer.
- */
- public JSONWriter value(double d) throws IOException, IllegalStateException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (inArray) {
- if (firstEntry) {
- firstEntry = false;
- } else {
- writer.write(",");
- }
- writer.write(Double.toString(d));
- } else if (inObject) {
- if (keyPlaced) {
- writer.write(Double.toString(d));
- keyPlaced = false;
- } else {
- throw new IllegalStateException("Current containment is a JSONObject, but a key has not been specified for the double value.");
- }
- } else {
- throw new IllegalStateException("Writer is currently not in an array or object, cannot write value");
- }
- return this;
- }
-
- /**
- * Method to write a double to the current writer position.
- * @param l The long to write.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws IllegalStateException Thrown if the current writer position will not accept a double value.
- * @return A reference to this writer.
- */
- public JSONWriter value(long l) throws IOException, IllegalStateException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (inArray) {
- if (firstEntry) {
- firstEntry = false;
- } else {
- writer.write(",");
- }
- writer.write(Long.toString(l));
- } else if (inObject) {
- if (keyPlaced) {
- writer.write(Long.toString(l));
- keyPlaced = false;
- } else {
- throw new IllegalStateException("Current containment is a JSONObject, but a key has not been specified for the long value.");
- }
- } else {
- throw new IllegalStateException("Writer is currently not in an array or object, cannot write value");
- }
- return this;
- }
-
- /**
- * Method to write an int to the current writer position.
- * @param i The int to write.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws IllegalStateException Thrown if the current writer position will not accept a double value.
- * @return A reference to this writer.
- */
- public JSONWriter value(int i) throws IOException, IllegalStateException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (inArray) {
- if (firstEntry) {
- firstEntry = false;
- } else {
- writer.write(",");
- }
- writer.write(Integer.toString(i));
- } else if (inObject) {
- if (keyPlaced) {
- writer.write(Integer.toString(i));
- keyPlaced = false;
- } else {
- throw new IllegalStateException("Current containment is a JSONObject, but a key has not been specified for the int value.");
- }
- } else {
- throw new IllegalStateException("Writer is currently not in an array or object, cannot write value");
- }
- return this;
- }
-
- /**
- * Method to write a short to the current writer position.
- * @param s The short to write.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws IllegalStateException Thrown if the current writer position will not accept a double value.
- * @return A reference to this writer.
- */
- public JSONWriter value(short s) throws IOException, IllegalStateException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (inArray) {
- if (firstEntry) {
- firstEntry = false;
- } else {
- writer.write(",");
- }
- writer.write(Integer.toString(s));
- } else if (inObject) {
- if (keyPlaced) {
- writer.write(Integer.toString(s));
- keyPlaced = false;
- } else {
- throw new IllegalStateException("Current containment is a JSONObject, but a key has not been specified for the short value.");
- }
- } else {
- throw new IllegalStateException("Writer is currently not in an array or object, cannot write value");
- }
- return this;
- }
-
- /**
- * Method to write an Object to the current writer position.
- * @param o The object to write.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws JSONException Thrown if the object is not JSONAble.
- * @return A reference to this writer.
- */
- public JSONWriter value(Object o) throws IOException, IllegalStateException, JSONException {
- if (closed) {
- throw new IllegalStateException("The writer has been closed. No further operations allowed.");
- }
- if (inArray) {
- if (firstEntry) {
- firstEntry = false;
- } else {
- writer.write(",");
- }
- writeObject(o);
- } else if (inObject) {
- if (keyPlaced) {
- writeObject(o);
- keyPlaced = false;
- } else {
- throw new IllegalStateException("Current containment is a JSONObject, but a key has not been specified for the boolean value.");
- }
- } else {
- throw new IllegalStateException("Writer is currently not in an array or object, cannot write value");
- }
- return this;
- }
-
- /**
- * Method to close the JSON Writer. All current object depths will be closed out and the writer closed.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws IllegalStateException Thrown if the writer position is in an object and a key has been placed, but a value has not been assigned or if the writer was already closed.
- */
- public void close() throws IOException, IllegalStateException {
- if (!closed) {
- if (inObject && keyPlaced) {
- throw new IllegalStateException("Object has key without value. Cannot close.");
- } else {
- while (!closures.isEmpty()) {
- writer.write((String)closures.pop());
- }
- writer.flush();
- writer.close();
- closed = true;
- }
- }
- }
-
- /**
- * Method to flush the underlying writer so that all buffered content, if any, is written out.
- * @return A reference to this writer.
- */
- public JSONWriter flush() throws IOException {
- writer.flush();
- return this;
- }
-
- /**
- * Method to write a String out to the writer, encoding special characters and unicode characters properly.
- * @param value The string to write out.
- * @throws IOException Thrown if an error occurs during write.
- */
- private void writeString(String value) throws IOException {
- writer.write('"');
- char[] chars = value.toCharArray();
- for (int i=0; i<chars.length; i++) {
- char c = chars[i];
- switch (c) {
- case '"': writer.write("\\\""); break;
- case '\\': writer.write("\\\\"); break;
- case 0: writer.write("\\0"); break;
- case '\b': writer.write("\\b"); break;
- case '\t': writer.write("\\t"); break;
- case '\n': writer.write("\\n"); break;
- case '\f': writer.write("\\f"); break;
- case '\r': writer.write("\\r"); break;
- case '/': writer.write("\\/"); break;
- default:
- if ((c >= 32) && (c <= 126)) {
- writer.write(c);
- } else {
- writer.write("\\u");
- writer.write(rightAlignedZero(Integer.toHexString(c),4));
- }
- }
- }
- writer.write('"');
- }
-
- /**
- * Method to generate a string with a particular width. Alignment is done using zeroes if it does not meet the width requirements.
- * @param s The string to write
- * @param len The minimum length it should be, and to align with zeroes if length is smaller.
- * @return A string properly aligned/correct width.
- */
- private String rightAlignedZero(String s, int len) {
- if (len == s.length()) return s;
- StringBuffer sb = new StringBuffer(s);
- while (sb.length() < len) {
- sb.insert(0, '0');
- }
- return sb.toString();
- }
-
- /**
- * Method to write a number to the current writer.
- * @param value The number to write to the JSON output string.
- * @throws IOException Thrown if an error occurs during write.
- */
- private void writeNumber(Object value) throws IOException {
- if (null == value) {
- writeNull();
- }
- if (value instanceof Float) {
- if (((Float)value).isNaN()) {
- writeNull();
- }
- if (Float.NEGATIVE_INFINITY == ((Float)value).floatValue()) {
- writeNull();
- }
- if (Float.POSITIVE_INFINITY == ((Float)value).floatValue()) {
- writeNull();
- }
- }
- if (value instanceof Double) {
- if (((Double)value).isNaN()) {
- writeNull();
- }
- if (Double.NEGATIVE_INFINITY == ((Double)value).doubleValue()) {
- writeNull();
- }
- if (Double.POSITIVE_INFINITY == ((Double)value).doubleValue()) {
- writeNull();
- }
- }
- writer.write(value.toString());
- }
-
- /**
- * Method to write an object to the current writer.
- * @param o The object to write.
- * @throws IOException Thrown if an IO error occurs on the underlying writer.
- * @throws JSONException Thrown if the specified object is not JSONAble.
- */
- private void writeObject(Object o) throws IOException, JSONException {
- // Handle the object!
- if (o == null) {
- writeNull();
- } else {
- Class clazz = o.getClass();
- if (JSONArtifact.class.isAssignableFrom(clazz)) {
- writer.write(((JSONArtifact)o).toString());
- } else if (NumberUtil.isNumber(clazz)) {
- writeNumber(o);
- } else if (Boolean.class.isAssignableFrom(clazz)) {
- writer.write(((Boolean)o).toString());
- } else if (String.class.isAssignableFrom(clazz)) {
- writeString((String)o);
- } else if (JSONString.class.isAssignableFrom(clazz)) {
- writer.write(((JSONString)o).toJSONString());
- }// else {
- // // Unknown type, we'll just try to serialize it like a Java Bean.
- // writer.write(BeanSerializer.toJson(o, true).write());
- // }
- }
- }
-
- /**
- * Method to write the text string 'null' to the output stream (null JSON object).
- * @throws IOException Thrown if an error occurs during write.
- */
- private void writeNull() throws IOException {
- writer.write("null");
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JNumber.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JNumber.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JNumber.java
deleted file mode 100644
index 99d244c..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JNumber.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-public class JSON4JNumber {
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JPBackReader.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JPBackReader.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JPBackReader.java
deleted file mode 100644
index a2ed87b..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/internal/JSON4JPBackReader.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j.internal;
-
-import java.io.IOException;
-import java.io.Reader;
-
-public class JSON4JPBackReader extends Reader {
-
- private Reader _reader = null;
-
- private int _lastChar = 0;
-
- public JSON4JPBackReader(Reader reader) {
- _reader = reader;
- }
-
- public void close() throws IOException {
- _reader.close();
- }
-
- public void unread(int c) {
- }
-
- public int read(char[] cbuf, int off, int len) throws IOException {
- cbuf[off] = (char)_lastChar;
- _reader.read(cbuf, off + 1, len -1);
- _lastChar = cbuf[off + len];
- return 0;
- }
-}
[35/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/FaultRecoveringOutputStream.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/FaultRecoveringOutputStream.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/FaultRecoveringOutputStream.java
new file mode 100644
index 0000000..c32b27a
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/FaultRecoveringOutputStream.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2013 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import static com.squareup.okhttp.internal.Util.checkOffsetAndCount;
+
+/**
+ * An output stream wrapper that recovers from failures in the underlying stream
+ * by replacing it with another stream. This class buffers a fixed amount of
+ * data under the assumption that failures occur early in a stream's life.
+ * If a failure occurs after the buffer has been exhausted, no recovery is
+ * attempted.
+ *
+ * <p>Subclasses must override {@link #replacementStream} which will request a
+ * replacement stream each time an {@link IOException} is encountered on the
+ * current stream.
+ */
+public abstract class FaultRecoveringOutputStream extends AbstractOutputStream {
+ private final int maxReplayBufferLength;
+
+ /** Bytes to transmit on the replacement stream, or null if no recovery is possible. */
+ private ByteArrayOutputStream replayBuffer;
+ private OutputStream out;
+
+ /**
+ * @param maxReplayBufferLength the maximum number of successfully written
+ * bytes to buffer so they can be replayed in the event of an error.
+ * Failure recoveries are not possible once this limit has been exceeded.
+ */
+ public FaultRecoveringOutputStream(int maxReplayBufferLength, OutputStream out) {
+ if (maxReplayBufferLength < 0) throw new IllegalArgumentException();
+ this.maxReplayBufferLength = maxReplayBufferLength;
+ this.replayBuffer = new ByteArrayOutputStream(maxReplayBufferLength);
+ this.out = out;
+ }
+
+ @Override public final void write(byte[] buffer, int offset, int count) throws IOException {
+ if (closed) throw new IOException("stream closed");
+ checkOffsetAndCount(buffer.length, offset, count);
+
+ while (true) {
+ try {
+ out.write(buffer, offset, count);
+
+ if (replayBuffer != null) {
+ if (count + replayBuffer.size() > maxReplayBufferLength) {
+ // Failure recovery is no longer possible once we overflow the replay buffer.
+ replayBuffer = null;
+ } else {
+ // Remember the written bytes to the replay buffer.
+ replayBuffer.write(buffer, offset, count);
+ }
+ }
+ return;
+ } catch (IOException e) {
+ if (!recover(e)) throw e;
+ }
+ }
+ }
+
+ @Override public final void flush() throws IOException {
+ if (closed) {
+ return; // don't throw; this stream might have been closed on the caller's behalf
+ }
+ while (true) {
+ try {
+ out.flush();
+ return;
+ } catch (IOException e) {
+ if (!recover(e)) throw e;
+ }
+ }
+ }
+
+ @Override public final void close() throws IOException {
+ if (closed) {
+ return;
+ }
+ while (true) {
+ try {
+ out.close();
+ closed = true;
+ return;
+ } catch (IOException e) {
+ if (!recover(e)) throw e;
+ }
+ }
+ }
+
+ /**
+ * Attempt to replace {@code out} with another equivalent stream. Returns true
+ * if a suitable replacement stream was found.
+ */
+ private boolean recover(IOException e) {
+ if (replayBuffer == null) {
+ return false; // Can't recover because we've dropped data that we would need to replay.
+ }
+
+ while (true) {
+ OutputStream replacementStream = null;
+ try {
+ replacementStream = replacementStream(e);
+ if (replacementStream == null) {
+ return false;
+ }
+ replaceStream(replacementStream);
+ return true;
+ } catch (IOException replacementStreamFailure) {
+ // The replacement was also broken. Loop to ask for another replacement.
+ Util.closeQuietly(replacementStream);
+ e = replacementStreamFailure;
+ }
+ }
+ }
+
+ /**
+ * Returns true if errors in the underlying stream can currently be recovered.
+ */
+ public boolean isRecoverable() {
+ return replayBuffer != null;
+ }
+
+ /**
+ * Replaces the current output stream with {@code replacementStream}, writing
+ * any replay bytes to it if they exist. The current output stream is closed.
+ */
+ public final void replaceStream(OutputStream replacementStream) throws IOException {
+ if (!isRecoverable()) {
+ throw new IllegalStateException();
+ }
+ if (this.out == replacementStream) {
+ return; // Don't replace a stream with itself.
+ }
+ replayBuffer.writeTo(replacementStream);
+ Util.closeQuietly(out);
+ out = replacementStream;
+ }
+
+ /**
+ * Returns a replacement output stream to recover from {@code e} thrown by the
+ * previous stream. Returns a new OutputStream if recovery was successful, in
+ * which case all previously-written data will be replayed. Returns null if
+ * the failure cannot be recovered.
+ */
+ protected abstract OutputStream replacementStream(IOException e) throws IOException;
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/NamedRunnable.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/NamedRunnable.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/NamedRunnable.java
new file mode 100644
index 0000000..ce430b2
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/NamedRunnable.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2013 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal;
+
+/**
+ * Runnable implementation which always sets its thread name.
+ */
+public abstract class NamedRunnable implements Runnable {
+ private String name;
+
+ public NamedRunnable(String name) {
+ this.name = name;
+ }
+
+ @Override public final void run() {
+ String oldName = Thread.currentThread().getName();
+ Thread.currentThread().setName(name);
+ try {
+ execute();
+ } finally {
+ Thread.currentThread().setName(oldName);
+ }
+ }
+
+ protected abstract void execute();
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Platform.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Platform.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Platform.java
new file mode 100644
index 0000000..6b4ac34
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Platform.java
@@ -0,0 +1,389 @@
+/*
+ * Copyright (C) 2012 Square, Inc.
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal;
+
+import com.squareup.okhttp.OkHttpClient;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.NetworkInterface;
+import java.net.Socket;
+import java.net.SocketException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.zip.Deflater;
+import java.util.zip.DeflaterOutputStream;
+import javax.net.ssl.SSLSocket;
+
+/**
+ * Access to Platform-specific features necessary for SPDY and advanced TLS.
+ *
+ * <h3>SPDY</h3>
+ * SPDY requires a TLS extension called NPN (Next Protocol Negotiation) that's
+ * available in Android 4.1+ and OpenJDK 7+ (with the npn-boot extension). It
+ * also requires a recent version of {@code DeflaterOutputStream} that is
+ * public API in Java 7 and callable via reflection in Android 4.1+.
+ */
+public class Platform {
+ private static final Platform PLATFORM = findPlatform();
+
+ private Constructor<DeflaterOutputStream> deflaterConstructor;
+
+ public static Platform get() {
+ return PLATFORM;
+ }
+
+ public void logW(String warning) {
+ System.out.println(warning);
+ }
+
+ public void tagSocket(Socket socket) throws SocketException {
+ }
+
+ public void untagSocket(Socket socket) throws SocketException {
+ }
+
+ public URI toUriLenient(URL url) throws URISyntaxException {
+ return url.toURI(); // this isn't as good as the built-in toUriLenient
+ }
+
+ /**
+ * Attempt a TLS connection with useful extensions enabled. This mode
+ * supports more features, but is less likely to be compatible with older
+ * HTTPS servers.
+ */
+ public void enableTlsExtensions(SSLSocket socket, String uriHost) {
+ }
+
+ /**
+ * Attempt a secure connection with basic functionality to maximize
+ * compatibility. Currently this uses SSL 3.0.
+ */
+ public void supportTlsIntolerantServer(SSLSocket socket) {
+ socket.setEnabledProtocols(new String[] {"SSLv3"});
+ }
+
+ /** Returns the negotiated protocol, or null if no protocol was negotiated. */
+ public byte[] getNpnSelectedProtocol(SSLSocket socket) {
+ return null;
+ }
+
+ /**
+ * Sets client-supported protocols on a socket to send to a server. The
+ * protocols are only sent if the socket implementation supports NPN.
+ */
+ public void setNpnProtocols(SSLSocket socket, byte[] npnProtocols) {
+ }
+
+ /**
+ * Returns a deflater output stream that supports SYNC_FLUSH for SPDY name
+ * value blocks. This throws an {@link UnsupportedOperationException} on
+ * Java 6 and earlier where there is no built-in API to do SYNC_FLUSH.
+ */
+ public OutputStream newDeflaterOutputStream(OutputStream out, Deflater deflater,
+ boolean syncFlush) {
+ try {
+ Constructor<DeflaterOutputStream> constructor = deflaterConstructor;
+ if (constructor == null) {
+ constructor = deflaterConstructor = DeflaterOutputStream.class.getConstructor(
+ OutputStream.class, Deflater.class, boolean.class);
+ }
+ return constructor.newInstance(out, deflater, syncFlush);
+ } catch (NoSuchMethodException e) {
+ throw new UnsupportedOperationException("Cannot SPDY; no SYNC_FLUSH available");
+ } catch (InvocationTargetException e) {
+ throw e.getCause() instanceof RuntimeException ? (RuntimeException) e.getCause()
+ : new RuntimeException(e.getCause());
+ } catch (InstantiationException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException e) {
+ throw new AssertionError();
+ }
+ }
+
+ /**
+ * Returns the maximum transmission unit of the network interface used by
+ * {@code socket}, or a reasonable default if this platform doesn't expose the
+ * MTU to the application layer.
+ *
+ * <p>The returned value should only be used as an optimization; such as to
+ * size buffers efficiently.
+ */
+ public int getMtu(Socket socket) throws IOException {
+ return 1400; // Smaller than 1500 to leave room for headers on interfaces like PPPoE.
+ }
+
+ /** Attempt to match the host runtime to a capable Platform implementation. */
+ private static Platform findPlatform() {
+ Method getMtu;
+ try {
+ getMtu = NetworkInterface.class.getMethod("getMTU");
+ } catch (NoSuchMethodException e) {
+ return new Platform(); // No Java 1.6 APIs. It's either Java 1.5, Android 2.2 or earlier.
+ }
+
+ // Attempt to find Android 2.3+ APIs.
+ Class<?> openSslSocketClass;
+ Method setUseSessionTickets;
+ Method setHostname;
+ try {
+ openSslSocketClass = Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl");
+ setUseSessionTickets = openSslSocketClass.getMethod("setUseSessionTickets", boolean.class);
+ setHostname = openSslSocketClass.getMethod("setHostname", String.class);
+
+ // Attempt to find Android 4.1+ APIs.
+ try {
+ Method setNpnProtocols = openSslSocketClass.getMethod("setNpnProtocols", byte[].class);
+ Method getNpnSelectedProtocol = openSslSocketClass.getMethod("getNpnSelectedProtocol");
+ return new Android41(getMtu, openSslSocketClass, setUseSessionTickets, setHostname,
+ setNpnProtocols, getNpnSelectedProtocol);
+ } catch (NoSuchMethodException ignored) {
+ return new Android23(getMtu, openSslSocketClass, setUseSessionTickets, setHostname);
+ }
+ } catch (ClassNotFoundException ignored) {
+ // This isn't an Android runtime.
+ } catch (NoSuchMethodException ignored) {
+ // This isn't Android 2.3 or better.
+ }
+
+ // Attempt to find the Jetty's NPN extension for OpenJDK.
+ try {
+ String npnClassName = "org.eclipse.jetty.npn.NextProtoNego";
+ Class<?> nextProtoNegoClass = Class.forName(npnClassName);
+ Class<?> providerClass = Class.forName(npnClassName + "$Provider");
+ Class<?> clientProviderClass = Class.forName(npnClassName + "$ClientProvider");
+ Class<?> serverProviderClass = Class.forName(npnClassName + "$ServerProvider");
+ Method putMethod = nextProtoNegoClass.getMethod("put", SSLSocket.class, providerClass);
+ Method getMethod = nextProtoNegoClass.getMethod("get", SSLSocket.class);
+ return new JdkWithJettyNpnPlatform(getMtu, putMethod, getMethod, clientProviderClass,
+ serverProviderClass);
+ } catch (ClassNotFoundException ignored) {
+ // NPN isn't on the classpath.
+ } catch (NoSuchMethodException ignored) {
+ // The NPN version isn't what we expect.
+ }
+
+ return getMtu != null ? new Java5(getMtu) : new Platform();
+ }
+
+ private static class Java5 extends Platform {
+ private final Method getMtu;
+
+ private Java5(Method getMtu) {
+ this.getMtu = getMtu;
+ }
+
+ @Override public int getMtu(Socket socket) throws IOException {
+ try {
+ NetworkInterface networkInterface = NetworkInterface.getByInetAddress(
+ socket.getLocalAddress());
+ return (Integer) getMtu.invoke(networkInterface);
+ } catch (IllegalAccessException e) {
+ throw new AssertionError(e);
+ } catch (InvocationTargetException e) {
+ if (e.getCause() instanceof IOException) throw (IOException) e.getCause();
+ throw new RuntimeException(e.getCause());
+ }
+ }
+ }
+
+ /**
+ * Android version 2.3 and newer support TLS session tickets and server name
+ * indication (SNI).
+ */
+ private static class Android23 extends Java5 {
+ protected final Class<?> openSslSocketClass;
+ private final Method setUseSessionTickets;
+ private final Method setHostname;
+
+ private Android23(Method getMtu, Class<?> openSslSocketClass, Method setUseSessionTickets,
+ Method setHostname) {
+ super(getMtu);
+ this.openSslSocketClass = openSslSocketClass;
+ this.setUseSessionTickets = setUseSessionTickets;
+ this.setHostname = setHostname;
+ }
+
+ @Override public void enableTlsExtensions(SSLSocket socket, String uriHost) {
+ super.enableTlsExtensions(socket, uriHost);
+ if (openSslSocketClass.isInstance(socket)) {
+ // This is Android: use reflection on OpenSslSocketImpl.
+ try {
+ setUseSessionTickets.invoke(socket, true);
+ setHostname.invoke(socket, uriHost);
+ } catch (InvocationTargetException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException e) {
+ throw new AssertionError(e);
+ }
+ }
+ }
+ }
+
+ /** Android version 4.1 and newer support NPN. */
+ private static class Android41 extends Android23 {
+ private final Method setNpnProtocols;
+ private final Method getNpnSelectedProtocol;
+
+ private Android41(Method getMtu, Class<?> openSslSocketClass, Method setUseSessionTickets,
+ Method setHostname, Method setNpnProtocols, Method getNpnSelectedProtocol) {
+ super(getMtu, openSslSocketClass, setUseSessionTickets, setHostname);
+ this.setNpnProtocols = setNpnProtocols;
+ this.getNpnSelectedProtocol = getNpnSelectedProtocol;
+ }
+
+ @Override public void setNpnProtocols(SSLSocket socket, byte[] npnProtocols) {
+ if (!openSslSocketClass.isInstance(socket)) {
+ return;
+ }
+ try {
+ setNpnProtocols.invoke(socket, new Object[] {npnProtocols});
+ } catch (IllegalAccessException e) {
+ throw new AssertionError(e);
+ } catch (InvocationTargetException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override public byte[] getNpnSelectedProtocol(SSLSocket socket) {
+ if (!openSslSocketClass.isInstance(socket)) {
+ return null;
+ }
+ try {
+ return (byte[]) getNpnSelectedProtocol.invoke(socket);
+ } catch (InvocationTargetException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException e) {
+ throw new AssertionError(e);
+ }
+ }
+ }
+
+ /**
+ * OpenJDK 7 plus {@code org.mortbay.jetty.npn/npn-boot} on the boot class
+ * path.
+ */
+ private static class JdkWithJettyNpnPlatform extends Java5 {
+ private final Method getMethod;
+ private final Method putMethod;
+ private final Class<?> clientProviderClass;
+ private final Class<?> serverProviderClass;
+
+ public JdkWithJettyNpnPlatform(Method getMtu, Method putMethod, Method getMethod,
+ Class<?> clientProviderClass, Class<?> serverProviderClass) {
+ super(getMtu);
+ this.putMethod = putMethod;
+ this.getMethod = getMethod;
+ this.clientProviderClass = clientProviderClass;
+ this.serverProviderClass = serverProviderClass;
+ }
+
+ @Override public void setNpnProtocols(SSLSocket socket, byte[] npnProtocols) {
+ try {
+ List<String> strings = new ArrayList<String>();
+ for (int i = 0; i < npnProtocols.length; ) {
+ int length = npnProtocols[i++];
+ strings.add(new String(npnProtocols, i, length, "US-ASCII"));
+ i += length;
+ }
+ Object provider = Proxy.newProxyInstance(Platform.class.getClassLoader(),
+ new Class[] {clientProviderClass, serverProviderClass},
+ new JettyNpnProvider(strings));
+ putMethod.invoke(null, socket, provider);
+ } catch (UnsupportedEncodingException e) {
+ throw new AssertionError(e);
+ } catch (InvocationTargetException e) {
+ throw new AssertionError(e);
+ } catch (IllegalAccessException e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ @Override public byte[] getNpnSelectedProtocol(SSLSocket socket) {
+ try {
+ JettyNpnProvider provider =
+ (JettyNpnProvider) Proxy.getInvocationHandler(getMethod.invoke(null, socket));
+ if (!provider.unsupported && provider.selected == null) {
+ Logger logger = Logger.getLogger(OkHttpClient.class.getName());
+ logger.log(Level.INFO,
+ "NPN callback dropped so SPDY is disabled. " + "Is npn-boot on the boot class path?");
+ return null;
+ }
+ return provider.unsupported ? null : provider.selected.getBytes("US-ASCII");
+ } catch (UnsupportedEncodingException e) {
+ throw new AssertionError();
+ } catch (InvocationTargetException e) {
+ throw new AssertionError();
+ } catch (IllegalAccessException e) {
+ throw new AssertionError();
+ }
+ }
+ }
+
+ /**
+ * Handle the methods of NextProtoNego's ClientProvider and ServerProvider
+ * without a compile-time dependency on those interfaces.
+ */
+ private static class JettyNpnProvider implements InvocationHandler {
+ private final List<String> protocols;
+ private boolean unsupported;
+ private String selected;
+
+ public JettyNpnProvider(List<String> protocols) {
+ this.protocols = protocols;
+ }
+
+ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ String methodName = method.getName();
+ Class<?> returnType = method.getReturnType();
+ if (args == null) {
+ args = Util.EMPTY_STRING_ARRAY;
+ }
+ if (methodName.equals("supports") && boolean.class == returnType) {
+ return true;
+ } else if (methodName.equals("unsupported") && void.class == returnType) {
+ this.unsupported = true;
+ return null;
+ } else if (methodName.equals("protocols") && args.length == 0) {
+ return protocols;
+ } else if (methodName.equals("selectProtocol")
+ && String.class == returnType
+ && args.length == 1
+ && (args[0] == null || args[0] instanceof List)) {
+ // TODO: use OpenSSL's algorithm which uses both lists
+ List<?> serverProtocols = (List) args[0];
+ this.selected = protocols.get(0);
+ return selected;
+ } else if (methodName.equals("protocolSelected") && args.length == 1) {
+ this.selected = (String) args[0];
+ return null;
+ } else {
+ return method.invoke(this, args);
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/StrictLineReader.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/StrictLineReader.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/StrictLineReader.java
new file mode 100644
index 0000000..3ddc693
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/StrictLineReader.java
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal;
+
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+
+/**
+ * Buffers input from an {@link InputStream} for reading lines.
+ *
+ * <p>This class is used for buffered reading of lines. For purposes of this class, a line ends with
+ * "\n" or "\r\n". End of input is reported by throwing {@code EOFException}. Unterminated line at
+ * end of input is invalid and will be ignored, the caller may use {@code hasUnterminatedLine()}
+ * to detect it after catching the {@code EOFException}.
+ *
+ * <p>This class is intended for reading input that strictly consists of lines, such as line-based
+ * cache entries or cache journal. Unlike the {@link java.io.BufferedReader} which in conjunction
+ * with {@link java.io.InputStreamReader} provides similar functionality, this class uses different
+ * end-of-input reporting and a more restrictive definition of a line.
+ *
+ * <p>This class supports only charsets that encode '\r' and '\n' as a single byte with value 13
+ * and 10, respectively, and the representation of no other character contains these values.
+ * We currently check in constructor that the charset is one of US-ASCII, UTF-8 and ISO-8859-1.
+ * The default charset is US_ASCII.
+ */
+public class StrictLineReader implements Closeable {
+ private static final byte CR = (byte) '\r';
+ private static final byte LF = (byte) '\n';
+
+ private final InputStream in;
+ private final Charset charset;
+
+ /*
+ * Buffered data is stored in {@code buf}. As long as no exception occurs, 0 <= pos <= end
+ * and the data in the range [pos, end) is buffered for reading. At end of input, if there is
+ * an unterminated line, we set end == -1, otherwise end == pos. If the underlying
+ * {@code InputStream} throws an {@code IOException}, end may remain as either pos or -1.
+ */
+ private byte[] buf;
+ private int pos;
+ private int end;
+
+ /**
+ * Constructs a new {@code LineReader} with the specified charset and the default capacity.
+ *
+ * @param in the {@code InputStream} to read data from.
+ * @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
+ * supported.
+ * @throws NullPointerException if {@code in} or {@code charset} is null.
+ * @throws IllegalArgumentException if the specified charset is not supported.
+ */
+ public StrictLineReader(InputStream in, Charset charset) {
+ this(in, 8192, charset);
+ }
+
+ /**
+ * Constructs a new {@code LineReader} with the specified capacity and charset.
+ *
+ * @param in the {@code InputStream} to read data from.
+ * @param capacity the capacity of the buffer.
+ * @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
+ * supported.
+ * @throws NullPointerException if {@code in} or {@code charset} is null.
+ * @throws IllegalArgumentException if {@code capacity} is negative or zero
+ * or the specified charset is not supported.
+ */
+ public StrictLineReader(InputStream in, int capacity, Charset charset) {
+ if (in == null || charset == null) {
+ throw new NullPointerException();
+ }
+ if (capacity < 0) {
+ throw new IllegalArgumentException("capacity <= 0");
+ }
+ if (!(charset.equals(Util.US_ASCII))) {
+ throw new IllegalArgumentException("Unsupported encoding");
+ }
+
+ this.in = in;
+ this.charset = charset;
+ buf = new byte[capacity];
+ }
+
+ /**
+ * Closes the reader by closing the underlying {@code InputStream} and
+ * marking this reader as closed.
+ *
+ * @throws IOException for errors when closing the underlying {@code InputStream}.
+ */
+ public void close() throws IOException {
+ synchronized (in) {
+ if (buf != null) {
+ buf = null;
+ in.close();
+ }
+ }
+ }
+
+ /**
+ * Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"},
+ * this end of line marker is not included in the result.
+ *
+ * @return the next line from the input.
+ * @throws IOException for underlying {@code InputStream} errors.
+ * @throws EOFException for the end of source stream.
+ */
+ public String readLine() throws IOException {
+ synchronized (in) {
+ if (buf == null) {
+ throw new IOException("LineReader is closed");
+ }
+
+ // Read more data if we are at the end of the buffered data.
+ // Though it's an error to read after an exception, we will let {@code fillBuf()}
+ // throw again if that happens; thus we need to handle end == -1 as well as end == pos.
+ if (pos >= end) {
+ fillBuf();
+ }
+ // Try to find LF in the buffered data and return the line if successful.
+ for (int i = pos; i != end; ++i) {
+ if (buf[i] == LF) {
+ int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i;
+ String res = new String(buf, pos, lineEnd - pos, charset.name());
+ pos = i + 1;
+ return res;
+ }
+ }
+
+ // Let's anticipate up to 80 characters on top of those already read.
+ ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) {
+ @Override
+ public String toString() {
+ int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count;
+ try {
+ return new String(buf, 0, length, charset.name());
+ } catch (UnsupportedEncodingException e) {
+ throw new AssertionError(e); // Since we control the charset this will never happen.
+ }
+ }
+ };
+
+ while (true) {
+ out.write(buf, pos, end - pos);
+ // Mark unterminated line in case fillBuf throws EOFException or IOException.
+ end = -1;
+ fillBuf();
+ // Try to find LF in the buffered data and return the line if successful.
+ for (int i = pos; i != end; ++i) {
+ if (buf[i] == LF) {
+ if (i != pos) {
+ out.write(buf, pos, i - pos);
+ }
+ pos = i + 1;
+ return out.toString();
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Read an {@code int} from a line containing its decimal representation.
+ *
+ * @return the value of the {@code int} from the next line.
+ * @throws IOException for underlying {@code InputStream} errors or conversion error.
+ * @throws EOFException for the end of source stream.
+ */
+ public int readInt() throws IOException {
+ String intString = readLine();
+ try {
+ return Integer.parseInt(intString);
+ } catch (NumberFormatException e) {
+ throw new IOException("expected an int but was \"" + intString + "\"");
+ }
+ }
+
+ /**
+ * Reads new input data into the buffer. Call only with pos == end or end == -1,
+ * depending on the desired outcome if the function throws.
+ */
+ private void fillBuf() throws IOException {
+ int result = in.read(buf, 0, buf.length);
+ if (result == -1) {
+ throw new EOFException();
+ }
+ pos = 0;
+ end = result;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Util.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Util.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Util.java
new file mode 100644
index 0000000..290e5ea
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Util.java
@@ -0,0 +1,327 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal;
+
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.net.Socket;
+import java.net.URI;
+import java.net.URL;
+import java.nio.ByteOrder;
+import java.nio.charset.Charset;
+import java.util.concurrent.atomic.AtomicReference;
+
+/** Junk drawer of utility methods. */
+public final class Util {
+ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
+ public static final String[] EMPTY_STRING_ARRAY = new String[0];
+
+ /** A cheap and type-safe constant for the ISO-8859-1 Charset. */
+ public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
+
+ /** A cheap and type-safe constant for the US-ASCII Charset. */
+ public static final Charset US_ASCII = Charset.forName("US-ASCII");
+
+ /** A cheap and type-safe constant for the UTF-8 Charset. */
+ public static final Charset UTF_8 = Charset.forName("UTF-8");
+ private static AtomicReference<byte[]> skipBuffer = new AtomicReference<byte[]>();
+
+ private Util() {
+ }
+
+ public static int getEffectivePort(URI uri) {
+ return getEffectivePort(uri.getScheme(), uri.getPort());
+ }
+
+ public static int getEffectivePort(URL url) {
+ return getEffectivePort(url.getProtocol(), url.getPort());
+ }
+
+ private static int getEffectivePort(String scheme, int specifiedPort) {
+ return specifiedPort != -1 ? specifiedPort : getDefaultPort(scheme);
+ }
+
+ public static int getDefaultPort(String scheme) {
+ if ("http".equalsIgnoreCase(scheme)) {
+ return 80;
+ } else if ("https".equalsIgnoreCase(scheme)) {
+ return 443;
+ } else {
+ return -1;
+ }
+ }
+
+ public static void checkOffsetAndCount(int arrayLength, int offset, int count) {
+ if ((offset | count) < 0 || offset > arrayLength || arrayLength - offset < count) {
+ throw new ArrayIndexOutOfBoundsException();
+ }
+ }
+
+ public static void pokeInt(byte[] dst, int offset, int value, ByteOrder order) {
+ if (order == ByteOrder.BIG_ENDIAN) {
+ dst[offset++] = (byte) ((value >> 24) & 0xff);
+ dst[offset++] = (byte) ((value >> 16) & 0xff);
+ dst[offset++] = (byte) ((value >> 8) & 0xff);
+ dst[offset] = (byte) ((value >> 0) & 0xff);
+ } else {
+ dst[offset++] = (byte) ((value >> 0) & 0xff);
+ dst[offset++] = (byte) ((value >> 8) & 0xff);
+ dst[offset++] = (byte) ((value >> 16) & 0xff);
+ dst[offset] = (byte) ((value >> 24) & 0xff);
+ }
+ }
+
+ /** Returns true if two possibly-null objects are equal. */
+ public static boolean equal(Object a, Object b) {
+ return a == b || (a != null && a.equals(b));
+ }
+
+ /**
+ * Closes {@code closeable}, ignoring any checked exceptions. Does nothing
+ * if {@code closeable} is null.
+ */
+ public static void closeQuietly(Closeable closeable) {
+ if (closeable != null) {
+ try {
+ closeable.close();
+ } catch (RuntimeException rethrown) {
+ throw rethrown;
+ } catch (Exception ignored) {
+ }
+ }
+ }
+
+ /**
+ * Closes {@code socket}, ignoring any checked exceptions. Does nothing if
+ * {@code socket} is null.
+ */
+ public static void closeQuietly(Socket socket) {
+ if (socket != null) {
+ try {
+ socket.close();
+ } catch (RuntimeException rethrown) {
+ throw rethrown;
+ } catch (Exception ignored) {
+ }
+ }
+ }
+
+ /**
+ * Closes {@code a} and {@code b}. If either close fails, this completes
+ * the other close and rethrows the first encountered exception.
+ */
+ public static void closeAll(Closeable a, Closeable b) throws IOException {
+ Throwable thrown = null;
+ try {
+ a.close();
+ } catch (Throwable e) {
+ thrown = e;
+ }
+ try {
+ b.close();
+ } catch (Throwable e) {
+ if (thrown == null) thrown = e;
+ }
+ if (thrown == null) return;
+ if (thrown instanceof IOException) throw (IOException) thrown;
+ if (thrown instanceof RuntimeException) throw (RuntimeException) thrown;
+ if (thrown instanceof Error) throw (Error) thrown;
+ throw new AssertionError(thrown);
+ }
+
+ /**
+ * Deletes the contents of {@code dir}. Throws an IOException if any file
+ * could not be deleted, or if {@code dir} is not a readable directory.
+ */
+ public static void deleteContents(File dir) throws IOException {
+ File[] files = dir.listFiles();
+ if (files == null) {
+ throw new IOException("not a readable directory: " + dir);
+ }
+ for (File file : files) {
+ if (file.isDirectory()) {
+ deleteContents(file);
+ }
+ if (!file.delete()) {
+ throw new IOException("failed to delete file: " + file);
+ }
+ }
+ }
+
+ /**
+ * Implements InputStream.read(int) in terms of InputStream.read(byte[], int, int).
+ * InputStream assumes that you implement InputStream.read(int) and provides default
+ * implementations of the others, but often the opposite is more efficient.
+ */
+ public static int readSingleByte(InputStream in) throws IOException {
+ byte[] buffer = new byte[1];
+ int result = in.read(buffer, 0, 1);
+ return (result != -1) ? buffer[0] & 0xff : -1;
+ }
+
+ /**
+ * Implements OutputStream.write(int) in terms of OutputStream.write(byte[], int, int).
+ * OutputStream assumes that you implement OutputStream.write(int) and provides default
+ * implementations of the others, but often the opposite is more efficient.
+ */
+ public static void writeSingleByte(OutputStream out, int b) throws IOException {
+ byte[] buffer = new byte[1];
+ buffer[0] = (byte) (b & 0xff);
+ out.write(buffer);
+ }
+
+ /**
+ * Fills 'dst' with bytes from 'in', throwing EOFException if insufficient bytes are available.
+ */
+ public static void readFully(InputStream in, byte[] dst) throws IOException {
+ readFully(in, dst, 0, dst.length);
+ }
+
+ /**
+ * Reads exactly 'byteCount' bytes from 'in' (into 'dst' at offset 'offset'), and throws
+ * EOFException if insufficient bytes are available.
+ *
+ * Used to implement {@link java.io.DataInputStream#readFully(byte[], int, int)}.
+ */
+ public static void readFully(InputStream in, byte[] dst, int offset, int byteCount)
+ throws IOException {
+ if (byteCount == 0) {
+ return;
+ }
+ if (in == null) {
+ throw new NullPointerException("in == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ checkOffsetAndCount(dst.length, offset, byteCount);
+ while (byteCount > 0) {
+ int bytesRead = in.read(dst, offset, byteCount);
+ if (bytesRead < 0) {
+ throw new EOFException();
+ }
+ offset += bytesRead;
+ byteCount -= bytesRead;
+ }
+ }
+
+ /** Returns the remainder of 'reader' as a string, closing it when done. */
+ public static String readFully(Reader reader) throws IOException {
+ try {
+ StringWriter writer = new StringWriter();
+ char[] buffer = new char[1024];
+ int count;
+ while ((count = reader.read(buffer)) != -1) {
+ writer.write(buffer, 0, count);
+ }
+ return writer.toString();
+ } finally {
+ reader.close();
+ }
+ }
+
+ public static void skipAll(InputStream in) throws IOException {
+ do {
+ in.skip(Long.MAX_VALUE);
+ } while (in.read() != -1);
+ }
+
+ /**
+ * Call {@code in.read()} repeatedly until either the stream is exhausted or
+ * {@code byteCount} bytes have been read.
+ *
+ * <p>This method reuses the skip buffer but is careful to never use it at
+ * the same time that another stream is using it. Otherwise streams that use
+ * the caller's buffer for consistency checks like CRC could be clobbered by
+ * other threads. A thread-local buffer is also insufficient because some
+ * streams may call other streams in their skip() method, also clobbering the
+ * buffer.
+ */
+ public static long skipByReading(InputStream in, long byteCount) throws IOException {
+ // acquire the shared skip buffer.
+ byte[] buffer = skipBuffer.getAndSet(null);
+ if (buffer == null) {
+ buffer = new byte[4096];
+ }
+
+ long skipped = 0;
+ while (skipped < byteCount) {
+ int toRead = (int) Math.min(byteCount - skipped, buffer.length);
+ int read = in.read(buffer, 0, toRead);
+ if (read == -1) {
+ break;
+ }
+ skipped += read;
+ if (read < toRead) {
+ break;
+ }
+ }
+
+ // release the shared skip buffer.
+ skipBuffer.set(buffer);
+
+ return skipped;
+ }
+
+ /**
+ * Copies all of the bytes from {@code in} to {@code out}. Neither stream is closed.
+ * Returns the total number of bytes transferred.
+ */
+ public static int copy(InputStream in, OutputStream out) throws IOException {
+ int total = 0;
+ byte[] buffer = new byte[8192];
+ int c;
+ while ((c = in.read(buffer)) != -1) {
+ total += c;
+ out.write(buffer, 0, c);
+ }
+ return total;
+ }
+
+ /**
+ * Returns the ASCII characters up to but not including the next "\r\n", or
+ * "\n".
+ *
+ * @throws java.io.EOFException if the stream is exhausted before the next newline
+ * character.
+ */
+ public static String readAsciiLine(InputStream in) throws IOException {
+ // TODO: support UTF-8 here instead
+ StringBuilder result = new StringBuilder(80);
+ while (true) {
+ int c = in.read();
+ if (c == -1) {
+ throw new EOFException();
+ } else if (c == '\n') {
+ break;
+ }
+
+ result.append((char) c);
+ }
+ int length = result.length();
+ if (length > 0 && result.charAt(length - 1) == '\r') {
+ result.setLength(length - 1);
+ }
+ return result.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/AbstractHttpInputStream.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/AbstractHttpInputStream.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/AbstractHttpInputStream.java
new file mode 100644
index 0000000..187f3b6
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/AbstractHttpInputStream.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.internal.Util;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.CacheRequest;
+
+/**
+ * An input stream for the body of an HTTP response.
+ *
+ * <p>Since a single socket's input stream may be used to read multiple HTTP
+ * responses from the same server, subclasses shouldn't close the socket stream.
+ *
+ * <p>A side effect of reading an HTTP response is that the response cache
+ * is populated. If the stream is closed early, that cache entry will be
+ * invalidated.
+ */
+abstract class AbstractHttpInputStream extends InputStream {
+ protected final InputStream in;
+ protected final HttpEngine httpEngine;
+ private final CacheRequest cacheRequest;
+ private final OutputStream cacheBody;
+ protected boolean closed;
+
+ AbstractHttpInputStream(InputStream in, HttpEngine httpEngine, CacheRequest cacheRequest)
+ throws IOException {
+ this.in = in;
+ this.httpEngine = httpEngine;
+
+ OutputStream cacheBody = cacheRequest != null ? cacheRequest.getBody() : null;
+
+ // some apps return a null body; for compatibility we treat that like a null cache request
+ if (cacheBody == null) {
+ cacheRequest = null;
+ }
+
+ this.cacheBody = cacheBody;
+ this.cacheRequest = cacheRequest;
+ }
+
+ /**
+ * read() is implemented using read(byte[], int, int) so subclasses only
+ * need to override the latter.
+ */
+ @Override public final int read() throws IOException {
+ return Util.readSingleByte(this);
+ }
+
+ protected final void checkNotClosed() throws IOException {
+ if (closed) {
+ throw new IOException("stream closed");
+ }
+ }
+
+ protected final void cacheWrite(byte[] buffer, int offset, int count) throws IOException {
+ if (cacheBody != null) {
+ cacheBody.write(buffer, offset, count);
+ }
+ }
+
+ /**
+ * Closes the cache entry and makes the socket available for reuse. This
+ * should be invoked when the end of the body has been reached.
+ */
+ protected final void endOfInput(boolean streamCancelled) throws IOException {
+ if (cacheRequest != null) {
+ cacheBody.close();
+ }
+ httpEngine.release(streamCancelled);
+ }
+
+ /**
+ * Calls abort on the cache entry and disconnects the socket. This
+ * should be invoked when the connection is closed unexpectedly to
+ * invalidate the cache entry and to prevent the HTTP connection from
+ * being reused. HTTP messages are sent in serial so whenever a message
+ * cannot be read to completion, subsequent messages cannot be read
+ * either and the connection must be discarded.
+ *
+ * <p>An earlier implementation skipped the remaining bytes, but this
+ * requires that the entire transfer be completed. If the intention was
+ * to cancel the transfer, closing the connection is the only solution.
+ */
+ protected final void unexpectedEndOfInput() {
+ if (cacheRequest != null) {
+ cacheRequest.abort();
+ }
+ httpEngine.release(true);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/AbstractHttpOutputStream.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/AbstractHttpOutputStream.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/AbstractHttpOutputStream.java
new file mode 100644
index 0000000..90675b0
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/AbstractHttpOutputStream.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * An output stream for the body of an HTTP request.
+ *
+ * <p>Since a single socket's output stream may be used to write multiple HTTP
+ * requests to the same server, subclasses should not close the socket stream.
+ */
+abstract class AbstractHttpOutputStream extends OutputStream {
+ protected boolean closed;
+
+ @Override public final void write(int data) throws IOException {
+ write(new byte[] { (byte) data });
+ }
+
+ protected final void checkNotClosed() throws IOException {
+ if (closed) {
+ throw new IOException("stream closed");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HeaderParser.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HeaderParser.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HeaderParser.java
new file mode 100644
index 0000000..12e6409
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HeaderParser.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+final class HeaderParser {
+
+ public interface CacheControlHandler {
+ void handle(String directive, String parameter);
+ }
+
+ /** Parse a comma-separated list of cache control header values. */
+ public static void parseCacheControl(String value, CacheControlHandler handler) {
+ int pos = 0;
+ while (pos < value.length()) {
+ int tokenStart = pos;
+ pos = skipUntil(value, pos, "=,");
+ String directive = value.substring(tokenStart, pos).trim();
+
+ if (pos == value.length() || value.charAt(pos) == ',') {
+ pos++; // consume ',' (if necessary)
+ handler.handle(directive, null);
+ continue;
+ }
+
+ pos++; // consume '='
+ pos = skipWhitespace(value, pos);
+
+ String parameter;
+
+ // quoted string
+ if (pos < value.length() && value.charAt(pos) == '\"') {
+ pos++; // consume '"' open quote
+ int parameterStart = pos;
+ pos = skipUntil(value, pos, "\"");
+ parameter = value.substring(parameterStart, pos);
+ pos++; // consume '"' close quote (if necessary)
+
+ // unquoted string
+ } else {
+ int parameterStart = pos;
+ pos = skipUntil(value, pos, ",");
+ parameter = value.substring(parameterStart, pos).trim();
+ }
+
+ handler.handle(directive, parameter);
+ }
+ }
+
+ /**
+ * Returns the next index in {@code input} at or after {@code pos} that
+ * contains a character from {@code characters}. Returns the input length if
+ * none of the requested characters can be found.
+ */
+ public static int skipUntil(String input, int pos, String characters) {
+ for (; pos < input.length(); pos++) {
+ if (characters.indexOf(input.charAt(pos)) != -1) {
+ break;
+ }
+ }
+ return pos;
+ }
+
+ /**
+ * Returns the next non-whitespace character in {@code input} that is white
+ * space. Result is undefined if input contains newline characters.
+ */
+ public static int skipWhitespace(String input, int pos) {
+ for (; pos < input.length(); pos++) {
+ char c = input.charAt(pos);
+ if (c != ' ' && c != '\t') {
+ break;
+ }
+ }
+ return pos;
+ }
+
+ /**
+ * Returns {@code value} as a positive integer, or 0 if it is negative, or
+ * -1 if it cannot be parsed.
+ */
+ public static int parseSeconds(String value) {
+ try {
+ long seconds = Long.parseLong(value);
+ if (seconds > Integer.MAX_VALUE) {
+ return Integer.MAX_VALUE;
+ } else if (seconds < 0) {
+ return 0;
+ } else {
+ return (int) seconds;
+ }
+ } catch (NumberFormatException e) {
+ return -1;
+ }
+ }
+
+ private HeaderParser() {
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpAuthenticator.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpAuthenticator.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpAuthenticator.java
new file mode 100644
index 0000000..4ccd12a
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpAuthenticator.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright (C) 2012 Square, Inc.
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.internal.Base64;
+import java.io.IOException;
+import java.net.Authenticator;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.net.Proxy;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+import static java.net.HttpURLConnection.HTTP_PROXY_AUTH;
+import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
+
+/** Handles HTTP authentication headers from origin and proxy servers. */
+public final class HttpAuthenticator {
+ private HttpAuthenticator() {
+ }
+
+ /**
+ * React to a failed authorization response by looking up new credentials.
+ *
+ * @return true if credentials have been added to successorRequestHeaders
+ * and another request should be attempted.
+ */
+ public static boolean processAuthHeader(int responseCode, RawHeaders responseHeaders,
+ RawHeaders successorRequestHeaders, Proxy proxy, URL url) throws IOException {
+ if (responseCode != HTTP_PROXY_AUTH && responseCode != HTTP_UNAUTHORIZED) {
+ throw new IllegalArgumentException();
+ }
+
+ // Keep asking for username/password until authorized.
+ String challengeHeader =
+ responseCode == HTTP_PROXY_AUTH ? "Proxy-Authenticate" : "WWW-Authenticate";
+ String credentials = getCredentials(responseHeaders, challengeHeader, proxy, url);
+ if (credentials == null) {
+ return false; // Could not find credentials so end the request cycle.
+ }
+
+ // Add authorization credentials, bypassing the already-connected check.
+ String fieldName = responseCode == HTTP_PROXY_AUTH ? "Proxy-Authorization" : "Authorization";
+ successorRequestHeaders.set(fieldName, credentials);
+ return true;
+ }
+
+ /**
+ * Returns the authorization credentials that may satisfy the challenge.
+ * Returns null if a challenge header was not provided or if credentials
+ * were not available.
+ */
+ private static String getCredentials(RawHeaders responseHeaders, String challengeHeader,
+ Proxy proxy, URL url) throws IOException {
+ List<Challenge> challenges = parseChallenges(responseHeaders, challengeHeader);
+ if (challenges.isEmpty()) {
+ return null;
+ }
+
+ for (Challenge challenge : challenges) {
+ // Use the global authenticator to get the password.
+ PasswordAuthentication auth;
+ if (responseHeaders.getResponseCode() == HTTP_PROXY_AUTH) {
+ InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
+ auth = Authenticator.requestPasswordAuthentication(proxyAddress.getHostName(),
+ getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url.getProtocol(),
+ challenge.realm, challenge.scheme, url, Authenticator.RequestorType.PROXY);
+ } else {
+ auth = Authenticator.requestPasswordAuthentication(url.getHost(),
+ getConnectToInetAddress(proxy, url), url.getPort(), url.getProtocol(), challenge.realm,
+ challenge.scheme, url, Authenticator.RequestorType.SERVER);
+ }
+ if (auth == null) {
+ continue;
+ }
+
+ // Use base64 to encode the username and password.
+ String usernameAndPassword = auth.getUserName() + ":" + new String(auth.getPassword());
+ byte[] bytes = usernameAndPassword.getBytes("ISO-8859-1");
+ String encoded = Base64.encode(bytes);
+ return challenge.scheme + " " + encoded;
+ }
+
+ return null;
+ }
+
+ private static InetAddress getConnectToInetAddress(Proxy proxy, URL url) throws IOException {
+ return (proxy != null && proxy.type() != Proxy.Type.DIRECT)
+ ? ((InetSocketAddress) proxy.address()).getAddress() : InetAddress.getByName(url.getHost());
+ }
+
+ /**
+ * Parse RFC 2617 challenges. This API is only interested in the scheme
+ * name and realm.
+ */
+ private static List<Challenge> parseChallenges(RawHeaders responseHeaders,
+ String challengeHeader) {
+ // auth-scheme = token
+ // auth-param = token "=" ( token | quoted-string )
+ // challenge = auth-scheme 1*SP 1#auth-param
+ // realm = "realm" "=" realm-value
+ // realm-value = quoted-string
+ List<Challenge> result = new ArrayList<Challenge>();
+ for (int h = 0; h < responseHeaders.length(); h++) {
+ if (!challengeHeader.equalsIgnoreCase(responseHeaders.getFieldName(h))) {
+ continue;
+ }
+ String value = responseHeaders.getValue(h);
+ int pos = 0;
+ while (pos < value.length()) {
+ int tokenStart = pos;
+ pos = HeaderParser.skipUntil(value, pos, " ");
+
+ String scheme = value.substring(tokenStart, pos).trim();
+ pos = HeaderParser.skipWhitespace(value, pos);
+
+ // TODO: This currently only handles schemes with a 'realm' parameter;
+ // It needs to be fixed to handle any scheme and any parameters
+ // http://code.google.com/p/android/issues/detail?id=11140
+
+ if (!value.regionMatches(pos, "realm=\"", 0, "realm=\"".length())) {
+ break; // Unexpected challenge parameter; give up!
+ }
+
+ pos += "realm=\"".length();
+ int realmStart = pos;
+ pos = HeaderParser.skipUntil(value, pos, "\"");
+ String realm = value.substring(realmStart, pos);
+ pos++; // Consume '"' close quote.
+ pos = HeaderParser.skipUntil(value, pos, ",");
+ pos++; // Consume ',' comma.
+ pos = HeaderParser.skipWhitespace(value, pos);
+ result.add(new Challenge(scheme, realm));
+ }
+ }
+ return result;
+ }
+
+ /** An RFC 2617 challenge. */
+ private static final class Challenge {
+ final String scheme;
+ final String realm;
+
+ Challenge(String scheme, String realm) {
+ this.scheme = scheme;
+ this.realm = realm;
+ }
+
+ @Override public boolean equals(Object o) {
+ return o instanceof Challenge
+ && ((Challenge) o).scheme.equals(scheme)
+ && ((Challenge) o).realm.equals(realm);
+ }
+
+ @Override public int hashCode() {
+ return scheme.hashCode() + 31 * realm.hashCode();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpDate.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpDate.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpDate.java
new file mode 100644
index 0000000..acb5fda
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpDate.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
+
+/**
+ * Best-effort parser for HTTP dates.
+ */
+final class HttpDate {
+
+ /**
+ * Most websites serve cookies in the blessed format. Eagerly create the parser to ensure such
+ * cookies are on the fast path.
+ */
+ private static final ThreadLocal<DateFormat> STANDARD_DATE_FORMAT =
+ new ThreadLocal<DateFormat>() {
+ @Override protected DateFormat initialValue() {
+ DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
+ rfc1123.setTimeZone(TimeZone.getTimeZone("UTC"));
+ return rfc1123;
+ }
+ };
+
+ /** If we fail to parse a date in a non-standard format, try each of these formats in sequence. */
+ private static final String[] BROWSER_COMPATIBLE_DATE_FORMATS = new String[] {
+ /* This list comes from {@code org.apache.http.impl.cookie.BrowserCompatSpec}. */
+ "EEEE, dd-MMM-yy HH:mm:ss zzz", // RFC 1036
+ "EEE MMM d HH:mm:ss yyyy", // ANSI C asctime()
+ "EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd-MMM-yyyy HH-mm-ss z", "EEE, dd MMM yy HH:mm:ss z",
+ "EEE dd-MMM-yyyy HH:mm:ss z", "EEE dd MMM yyyy HH:mm:ss z", "EEE dd-MMM-yyyy HH-mm-ss z",
+ "EEE dd-MMM-yy HH:mm:ss z", "EEE dd MMM yy HH:mm:ss z", "EEE,dd-MMM-yy HH:mm:ss z",
+ "EEE,dd-MMM-yyyy HH:mm:ss z", "EEE, dd-MM-yyyy HH:mm:ss z",
+
+ /* RI bug 6641315 claims a cookie of this format was once served by www.yahoo.com */
+ "EEE MMM d yyyy HH:mm:ss z", };
+
+ /**
+ * Returns the date for {@code value}. Returns null if the value couldn't be
+ * parsed.
+ */
+ public static Date parse(String value) {
+ try {
+ return STANDARD_DATE_FORMAT.get().parse(value);
+ } catch (ParseException ignore) {
+ }
+ for (String formatString : BROWSER_COMPATIBLE_DATE_FORMATS) {
+ try {
+ return new SimpleDateFormat(formatString, Locale.US).parse(value);
+ } catch (ParseException ignore) {
+ }
+ }
+ return null;
+ }
+
+ /** Returns the string for {@code value}. */
+ public static String format(Date value) {
+ return STANDARD_DATE_FORMAT.get().format(value);
+ }
+
+ private HttpDate() {
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpEngine.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpEngine.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpEngine.java
new file mode 100644
index 0000000..7a06dca
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpEngine.java
@@ -0,0 +1,664 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.Address;
+import com.squareup.okhttp.Connection;
+import com.squareup.okhttp.ResponseSource;
+import com.squareup.okhttp.TunnelRequest;
+import com.squareup.okhttp.internal.Dns;
+import com.squareup.okhttp.internal.Platform;
+import com.squareup.okhttp.internal.Util;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.CacheRequest;
+import java.net.CacheResponse;
+import java.net.CookieHandler;
+import java.net.Proxy;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.GZIPInputStream;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.SSLSocketFactory;
+
+import static com.squareup.okhttp.internal.Util.EMPTY_BYTE_ARRAY;
+import static com.squareup.okhttp.internal.Util.getDefaultPort;
+import static com.squareup.okhttp.internal.Util.getEffectivePort;
+
+/**
+ * Handles a single HTTP request/response pair. Each HTTP engine follows this
+ * lifecycle:
+ * <ol>
+ * <li>It is created.
+ * <li>The HTTP request message is sent with sendRequest(). Once the request
+ * is sent it is an error to modify the request headers. After
+ * sendRequest() has been called the request body can be written to if
+ * it exists.
+ * <li>The HTTP response message is read with readResponse(). After the
+ * response has been read the response headers and body can be read.
+ * All responses have a response body input stream, though in some
+ * instances this stream is empty.
+ * </ol>
+ *
+ * <p>The request and response may be served by the HTTP response cache, by the
+ * network, or by both in the event of a conditional GET.
+ *
+ * <p>This class may hold a socket connection that needs to be released or
+ * recycled. By default, this socket connection is held when the last byte of
+ * the response is consumed. To release the connection when it is no longer
+ * required, use {@link #automaticallyReleaseConnectionToPool()}.
+ */
+public class HttpEngine {
+ private static final CacheResponse GATEWAY_TIMEOUT_RESPONSE = new CacheResponse() {
+ @Override public Map<String, List<String>> getHeaders() throws IOException {
+ Map<String, List<String>> result = new HashMap<String, List<String>>();
+ result.put(null, Collections.singletonList("HTTP/1.1 504 Gateway Timeout"));
+ return result;
+ }
+ @Override public InputStream getBody() throws IOException {
+ return new ByteArrayInputStream(EMPTY_BYTE_ARRAY);
+ }
+ };
+ public static final int HTTP_CONTINUE = 100;
+
+ protected final HttpURLConnectionImpl policy;
+
+ protected final String method;
+
+ private ResponseSource responseSource;
+
+ protected Connection connection;
+ protected RouteSelector routeSelector;
+ private OutputStream requestBodyOut;
+
+ private Transport transport;
+
+ private InputStream responseTransferIn;
+ private InputStream responseBodyIn;
+
+ private CacheResponse cacheResponse;
+ private CacheRequest cacheRequest;
+
+ /** The time when the request headers were written, or -1 if they haven't been written yet. */
+ long sentRequestMillis = -1;
+
+ /**
+ * True if this client added an "Accept-Encoding: gzip" header field and is
+ * therefore responsible for also decompressing the transfer stream.
+ */
+ private boolean transparentGzip;
+
+ final URI uri;
+
+ final RequestHeaders requestHeaders;
+
+ /** Null until a response is received from the network or the cache. */
+ ResponseHeaders responseHeaders;
+
+ // The cache response currently being validated on a conditional get. Null
+ // if the cached response doesn't exist or doesn't need validation. If the
+ // conditional get succeeds, these will be used for the response headers and
+ // body. If it fails, these be closed and set to null.
+ private ResponseHeaders cachedResponseHeaders;
+ private InputStream cachedResponseBody;
+
+ /**
+ * True if the socket connection should be released to the connection pool
+ * when the response has been fully read.
+ */
+ private boolean automaticallyReleaseConnectionToPool;
+
+ /** True if the socket connection is no longer needed by this engine. */
+ private boolean connectionReleased;
+
+ /**
+ * @param requestHeaders the client's supplied request headers. This class
+ * creates a private copy that it can mutate.
+ * @param connection the connection used for an intermediate response
+ * immediately prior to this request/response pair, such as a same-host
+ * redirect. This engine assumes ownership of the connection and must
+ * release it when it is unneeded.
+ */
+ public HttpEngine(HttpURLConnectionImpl policy, String method, RawHeaders requestHeaders,
+ Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
+ this.policy = policy;
+ this.method = method;
+ this.connection = connection;
+ this.requestBodyOut = requestBodyOut;
+
+ try {
+ uri = Platform.get().toUriLenient(policy.getURL());
+ } catch (URISyntaxException e) {
+ throw new IOException(e.getMessage());
+ }
+
+ this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
+ }
+
+ public URI getUri() {
+ return uri;
+ }
+
+ /**
+ * Figures out what the response source will be, and opens a socket to that
+ * source if necessary. Prepares the request headers and gets ready to start
+ * writing the request body if it exists.
+ */
+ public final void sendRequest() throws IOException {
+ if (responseSource != null) {
+ return;
+ }
+
+ prepareRawRequestHeaders();
+ initResponseSource();
+ if (policy.responseCache != null) {
+ policy.responseCache.trackResponse(responseSource);
+ }
+
+ // The raw response source may require the network, but the request
+ // headers may forbid network use. In that case, dispose of the network
+ // response and use a GATEWAY_TIMEOUT response instead, as specified
+ // by http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4.
+ if (requestHeaders.isOnlyIfCached() && responseSource.requiresConnection()) {
+ if (responseSource == ResponseSource.CONDITIONAL_CACHE) {
+ Util.closeQuietly(cachedResponseBody);
+ }
+ this.responseSource = ResponseSource.CACHE;
+ this.cacheResponse = GATEWAY_TIMEOUT_RESPONSE;
+ RawHeaders rawResponseHeaders = RawHeaders.fromMultimap(cacheResponse.getHeaders(), true);
+ setResponse(new ResponseHeaders(uri, rawResponseHeaders), cacheResponse.getBody());
+ }
+
+ if (responseSource.requiresConnection()) {
+ sendSocketRequest();
+ } else if (connection != null) {
+ policy.connectionPool.recycle(connection);
+ policy.getFailedRoutes().remove(connection.getRoute());
+ connection = null;
+ }
+ }
+
+ /**
+ * Initialize the source for this response. It may be corrected later if the
+ * request headers forbids network use.
+ */
+ private void initResponseSource() throws IOException {
+ responseSource = ResponseSource.NETWORK;
+ if (!policy.getUseCaches() || policy.responseCache == null) {
+ return;
+ }
+
+ CacheResponse candidate =
+ policy.responseCache.get(uri, method, requestHeaders.getHeaders().toMultimap(false));
+ if (candidate == null) {
+ return;
+ }
+
+ Map<String, List<String>> responseHeadersMap = candidate.getHeaders();
+ cachedResponseBody = candidate.getBody();
+ if (!acceptCacheResponseType(candidate)
+ || responseHeadersMap == null
+ || cachedResponseBody == null) {
+ Util.closeQuietly(cachedResponseBody);
+ return;
+ }
+
+ RawHeaders rawResponseHeaders = RawHeaders.fromMultimap(responseHeadersMap, true);
+ cachedResponseHeaders = new ResponseHeaders(uri, rawResponseHeaders);
+ long now = System.currentTimeMillis();
+ this.responseSource = cachedResponseHeaders.chooseResponseSource(now, requestHeaders);
+ if (responseSource == ResponseSource.CACHE) {
+ this.cacheResponse = candidate;
+ setResponse(cachedResponseHeaders, cachedResponseBody);
+ } else if (responseSource == ResponseSource.CONDITIONAL_CACHE) {
+ this.cacheResponse = candidate;
+ } else if (responseSource == ResponseSource.NETWORK) {
+ Util.closeQuietly(cachedResponseBody);
+ } else {
+ throw new AssertionError();
+ }
+ }
+
+ private void sendSocketRequest() throws IOException {
+ if (connection == null) {
+ connect();
+ }
+
+ if (transport != null) {
+ throw new IllegalStateException();
+ }
+
+ transport = (Transport) connection.newTransport(this);
+
+ if (hasRequestBody() && requestBodyOut == null) {
+ // Create a request body if we don't have one already. We'll already
+ // have one if we're retrying a failed POST.
+ requestBodyOut = transport.createRequestBody();
+ }
+ }
+
+ /** Connect to the origin server either directly or via a proxy. */
+ protected final void connect() throws IOException {
+ if (connection != null) {
+ return;
+ }
+ if (routeSelector == null) {
+ String uriHost = uri.getHost();
+ if (uriHost == null) {
+ throw new UnknownHostException(uri.toString());
+ }
+ SSLSocketFactory sslSocketFactory = null;
+ HostnameVerifier hostnameVerifier = null;
+ if (uri.getScheme().equalsIgnoreCase("https")) {
+ sslSocketFactory = policy.sslSocketFactory;
+ hostnameVerifier = policy.hostnameVerifier;
+ }
+ Address address = new Address(uriHost, getEffectivePort(uri), sslSocketFactory,
+ hostnameVerifier, policy.requestedProxy);
+ routeSelector = new RouteSelector(address, uri, policy.proxySelector, policy.connectionPool,
+ Dns.DEFAULT, policy.getFailedRoutes());
+ }
+ connection = routeSelector.next();
+ if (!connection.isConnected()) {
+ connection.connect(policy.getConnectTimeout(), policy.getReadTimeout(), getTunnelConfig());
+ policy.connectionPool.maybeShare(connection);
+ policy.getFailedRoutes().remove(connection.getRoute());
+ }
+ connected(connection);
+ if (connection.getRoute().getProxy() != policy.requestedProxy) {
+ // Update the request line if the proxy changed; it may need a host name.
+ requestHeaders.getHeaders().setRequestLine(getRequestLine());
+ }
+ }
+
+ /**
+ * Called after a socket connection has been created or retrieved from the
+ * pool. Subclasses use this hook to get a reference to the TLS data.
+ */
+ protected void connected(Connection connection) {
+ }
+
+ /**
+ * Called immediately before the transport transmits HTTP request headers.
+ * This is used to observe the sent time should the request be cached.
+ */
+ public void writingRequestHeaders() {
+ if (sentRequestMillis != -1) {
+ throw new IllegalStateException();
+ }
+ sentRequestMillis = System.currentTimeMillis();
+ }
+
+ /**
+ * @param body the response body, or null if it doesn't exist or isn't
+ * available.
+ */
+ private void setResponse(ResponseHeaders headers, InputStream body) throws IOException {
+ if (this.responseBodyIn != null) {
+ throw new IllegalStateException();
+ }
+ this.responseHeaders = headers;
+ if (body != null) {
+ initContentStream(body);
+ }
+ }
+
+ boolean hasRequestBody() {
+ return method.equals("POST") || method.equals("PUT");
+ }
+
+ /** Returns the request body or null if this request doesn't have a body. */
+ public final OutputStream getRequestBody() {
+ if (responseSource == null) {
+ throw new IllegalStateException();
+ }
+ return requestBodyOut;
+ }
+
+ public final boolean hasResponse() {
+ return responseHeaders != null;
+ }
+
+ public final RequestHeaders getRequestHeaders() {
+ return requestHeaders;
+ }
+
+ public final ResponseHeaders getResponseHeaders() {
+ if (responseHeaders == null) {
+ throw new IllegalStateException();
+ }
+ return responseHeaders;
+ }
+
+ public final int getResponseCode() {
+ if (responseHeaders == null) {
+ throw new IllegalStateException();
+ }
+ return responseHeaders.getHeaders().getResponseCode();
+ }
+
+ public final InputStream getResponseBody() {
+ if (responseHeaders == null) {
+ throw new IllegalStateException();
+ }
+ return responseBodyIn;
+ }
+
+ public final CacheResponse getCacheResponse() {
+ return cacheResponse;
+ }
+
+ public final Connection getConnection() {
+ return connection;
+ }
+
+ /**
+ * Returns true if {@code cacheResponse} is of the right type. This
+ * condition is necessary but not sufficient for the cached response to
+ * be used.
+ */
+ protected boolean acceptCacheResponseType(CacheResponse cacheResponse) {
+ return true;
+ }
+
+ private void maybeCache() throws IOException {
+ // Are we caching at all?
+ if (!policy.getUseCaches() || policy.responseCache == null) {
+ return;
+ }
+
+ // Should we cache this response for this request?
+ if (!responseHeaders.isCacheable(requestHeaders)) {
+ return;
+ }
+
+ // Offer this request to the cache.
+ cacheRequest = policy.responseCache.put(uri, policy.getHttpConnectionToCache());
+ }
+
+ /**
+ * Cause the socket connection to be released to the connection pool when
+ * it is no longer needed. If it is already unneeded, it will be pooled
+ * immediately. Otherwise the connection is held so that redirects can be
+ * handled by the same connection.
+ */
+ public final void automaticallyReleaseConnectionToPool() {
+ automaticallyReleaseConnectionToPool = true;
+ if (connection != null && connectionReleased) {
+ policy.connectionPool.recycle(connection);
+ connection = null;
+ }
+ }
+
+ /**
+ * Releases this engine so that its resources may be either reused or
+ * closed. Also call {@link #automaticallyReleaseConnectionToPool} unless
+ * the connection will be used to follow a redirect.
+ */
+ public final void release(boolean streamCancelled) {
+ // If the response body comes from the cache, close it.
+ if (responseBodyIn == cachedResponseBody) {
+ Util.closeQuietly(responseBodyIn);
+ }
+
+ if (!connectionReleased && connection != null) {
+ connectionReleased = true;
+
+ if (transport == null || !transport.makeReusable(streamCancelled, requestBodyOut,
+ responseTransferIn)) {
+ Util.closeQuietly(connection);
+ connection = null;
+ } else if (automaticallyReleaseConnectionToPool) {
+ policy.connectionPool.recycle(connection);
+ connection = null;
+ }
+ }
+ }
+
+ private void initContentStream(InputStream transferStream) throws IOException {
+ responseTransferIn = transferStream;
+ if (transparentGzip && responseHeaders.isContentEncodingGzip()) {
+ // If the response was transparently gzipped, remove the gzip header field
+ // so clients don't double decompress. http://b/3009828
+ //
+ // Also remove the Content-Length in this case because it contains the
+ // length 528 of the gzipped response. This isn't terribly useful and is
+ // dangerous because 529 clients can query the content length, but not
+ // the content encoding.
+ responseHeaders.stripContentEncoding();
+ responseHeaders.stripContentLength();
+ responseBodyIn = new GZIPInputStream(transferStream);
+ } else {
+ responseBodyIn = transferStream;
+ }
+ }
+
+ /**
+ * Returns true if the response must have a (possibly 0-length) body.
+ * See RFC 2616 section 4.3.
+ */
+ public final boolean hasResponseBody() {
+ int responseCode = responseHeaders.getHeaders().getResponseCode();
+
+ // HEAD requests never yield a body regardless of the response headers.
+ if (method.equals("HEAD")) {
+ return false;
+ }
+
+ if ((responseCode < HTTP_CONTINUE || responseCode >= 200)
+ && responseCode != HttpURLConnectionImpl.HTTP_NO_CONTENT
+ && responseCode != HttpURLConnectionImpl.HTTP_NOT_MODIFIED) {
+ return true;
+ }
+
+ // If the Content-Length or Transfer-Encoding headers disagree with the
+ // response code, the response is malformed. For best compatibility, we
+ // honor the headers.
+ if (responseHeaders.getContentLength() != -1 || responseHeaders.isChunked()) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Populates requestHeaders with defaults and cookies.
+ *
+ * <p>This client doesn't specify a default {@code Accept} header because it
+ * doesn't know what content types the application is interested in.
+ */
+ private void prepareRawRequestHeaders() throws IOException {
+ requestHeaders.getHeaders().setRequestLine(getRequestLine());
+
+ if (requestHeaders.getUserAgent() == null) {
+ requestHeaders.setUserAgent(getDefaultUserAgent());
+ }
+
+ if (requestHeaders.getHost() == null) {
+ requestHeaders.setHost(getOriginAddress(policy.getURL()));
+ }
+
+ if ((connection == null || connection.getHttpMinorVersion() != 0)
+ && requestHeaders.getConnection() == null) {
+ requestHeaders.setConnection("Keep-Alive");
+ }
+
+ if (requestHeaders.getAcceptEncoding() == null) {
+ transparentGzip = true;
+ requestHeaders.setAcceptEncoding("gzip");
+ }
+
+ if (hasRequestBody() && requestHeaders.getContentType() == null) {
+ requestHeaders.setContentType("application/x-www-form-urlencoded");
+ }
+
+ long ifModifiedSince = policy.getIfModifiedSince();
+ if (ifModifiedSince != 0) {
+ requestHeaders.setIfModifiedSince(new Date(ifModifiedSince));
+ }
+
+ CookieHandler cookieHandler = policy.cookieHandler;
+ if (cookieHandler != null) {
+ requestHeaders.addCookies(
+ cookieHandler.get(uri, requestHeaders.getHeaders().toMultimap(false)));
+ }
+ }
+
+ /**
+ * Returns the request status line, like "GET / HTTP/1.1". This is exposed
+ * to the application by {@link HttpURLConnectionImpl#getHeaderFields}, so
+ * it needs to be set even if the transport is SPDY.
+ */
+ String getRequestLine() {
+ String protocol =
+ (connection == null || connection.getHttpMinorVersion() != 0) ? "HTTP/1.1" : "HTTP/1.0";
+ return method + " " + requestString() + " " + protocol;
+ }
+
+ private String requestString() {
+ URL url = policy.getURL();
+ if (includeAuthorityInRequestLine()) {
+ return url.toString();
+ } else {
+ return requestPath(url);
+ }
+ }
+
+ /**
+ * Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never
+ * empty, even if the request URL is. Includes the query component if it
+ * exists.
+ */
+ public static String requestPath(URL url) {
+ String fileOnly = url.getFile();
+ if (fileOnly == null) {
+ return "/";
+ } else if (!fileOnly.startsWith("/")) {
+ return "/" + fileOnly;
+ } else {
+ return fileOnly;
+ }
+ }
+
+ /**
+ * Returns true if the request line should contain the full URL with host
+ * and port (like "GET http://android.com/foo HTTP/1.1") or only the path
+ * (like "GET /foo HTTP/1.1").
+ *
+ * <p>This is non-final because for HTTPS it's never necessary to supply the
+ * full URL, even if a proxy is in use.
+ */
+ protected boolean includeAuthorityInRequestLine() {
+ return connection == null
+ ? policy.usingProxy() // A proxy was requested.
+ : connection.getRoute().getProxy().type() == Proxy.Type.HTTP; // A proxy was selected.
+ }
+
+ public static String getDefaultUserAgent() {
+ String agent = System.getProperty("http.agent");
+ return agent != null ? agent : ("Java" + System.getProperty("java.version"));
+ }
+
+ public static String getOriginAddress(URL url) {
+ int port = url.getPort();
+ String result = url.getHost();
+ if (port > 0 && port != getDefaultPort(url.getProtocol())) {
+ result = result + ":" + port;
+ }
+ return result;
+ }
+
+ /**
+ * Flushes the remaining request header and body, parses the HTTP response
+ * headers and starts reading the HTTP response body if it exists.
+ */
+ public final void readResponse() throws IOException {
+ if (hasResponse()) {
+ responseHeaders.setResponseSource(responseSource);
+ return;
+ }
+
+ if (responseSource == null) {
+ throw new IllegalStateException("readResponse() without sendRequest()");
+ }
+
+ if (!responseSource.requiresConnection()) {
+ return;
+ }
+
+ if (sentRequestMillis == -1) {
+ if (requestBodyOut instanceof RetryableOutputStream) {
+ int contentLength = ((RetryableOutputStream) requestBodyOut).contentLength();
+ requestHeaders.setContentLength(contentLength);
+ }
+ transport.writeRequestHeaders();
+ }
+
+ if (requestBodyOut != null) {
+ requestBodyOut.close();
+ if (requestBodyOut instanceof RetryableOutputStream) {
+ transport.writeRequestBody((RetryableOutputStream) requestBodyOut);
+ }
+ }
+
+ transport.flushRequest();
+
+ responseHeaders = transport.readResponseHeaders();
+ responseHeaders.setLocalTimestamps(sentRequestMillis, System.currentTimeMillis());
+ responseHeaders.setResponseSource(responseSource);
+
+ if (responseSource == ResponseSource.CONDITIONAL_CACHE) {
+ if (cachedResponseHeaders.validate(responseHeaders)) {
+ release(false);
+ ResponseHeaders combinedHeaders = cachedResponseHeaders.combine(responseHeaders);
+ setResponse(combinedHeaders, cachedResponseBody);
+ policy.responseCache.trackConditionalCacheHit();
+ policy.responseCache.update(cacheResponse, policy.getHttpConnectionToCache());
+ return;
+ } else {
+ Util.closeQuietly(cachedResponseBody);
+ }
+ }
+
+ if (hasResponseBody()) {
+ maybeCache(); // reentrant. this calls into user code which may call back into this!
+ }
+
+ initContentStream(transport.getTransferStream(cacheRequest));
+ }
+
+ protected TunnelRequest getTunnelConfig() {
+ return null;
+ }
+
+ public void receiveHeaders(RawHeaders headers) throws IOException {
+ CookieHandler cookieHandler = policy.cookieHandler;
+ if (cookieHandler != null) {
+ cookieHandler.put(uri, headers.toMultimap(true));
+ }
+ }
+}
[20/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/Geolocation.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/Geolocation.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/Geolocation.java
deleted file mode 100644
index 1226f48..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/Geolocation.java
+++ /dev/null
@@ -1,372 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.geolocation;
-
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import javax.microedition.location.Criteria;
-import javax.microedition.location.Location;
-import javax.microedition.location.LocationException;
-import javax.microedition.location.LocationProvider;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.gps.BlackBerryCriteria;
-import net.rim.device.api.gps.BlackBerryLocationProvider;
-import net.rim.device.api.gps.GPSInfo;
-
-public class Geolocation extends Plugin {
-
- /**
- * Possible actions.
- */
- protected static final int ACTION_WATCH = 0;
- protected static final int ACTION_CLEAR_WATCH = 1;
- protected static final int ACTION_GET_POSITION = 2;
- protected static final int ACTION_SHUTDOWN = 3;
-
- /**
- * Callback ID argument index.
- */
- protected static final int ARG_CALLBACK_ID = 0;
-
- /**
- * Minimum GPS accuracy (meters).
- */
- protected static final float MIN_GPS_ACCURACY = 10F; // meters
-
- /**
- * Hash of all the listeners created, keyed on callback ids.
- */
- protected final Hashtable geoListeners;
-
- /**
- * Constructor.
- */
- public Geolocation() {
- this.geoListeners = new Hashtable();
- }
-
- /**
- * Executes the specified geolocation action.
- *
- * @param action
- * "getCurrentPosition" - Retrieves current location.
- * "watchPosition" - Establishes a location provider that is keyed on specified position options
- * and attaches a listener that notifies registered callbacks of location updates.
- * "stop" - Clears the watch identified by the watch ID that must be specified in args.
- * "shutdown" - Stops all listeners and resets all location providers.
- * @param callbackId callback managed by the plugin manager (ignored)
- * @param args contains the callback id and position options
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
-
- /*
- * The geolocation plugin bypasses the plugin callback framework for
- * success callbacks because the current implementation of the framework
- * deletes the callbacks after they have been called. The geolocation
- * listener callbacks need to continue listening for location changes,
- * and are therefore managed separately from the plugin framework.
- *
- * This means the invoking script must pass the listener callback ID in
- * the args parameter (along with the position options). The callbackId
- * parameter (used by the plugin framework) is ignored.
- *
- * The invoking script should still provide a failure callback so the
- * plugin framework can handle general error reporting.
- */
- String listenerCallbackId;
- try {
- listenerCallbackId = args.getString(ARG_CALLBACK_ID);
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Callback ID argument is not valid.");
- }
-
- if (!GPSInfo.isGPSModeAvailable(GPSInfo.GPS_DEVICE_INTERNAL)){
- return new PluginResult(GeolocationStatus.GPS_NOT_AVAILABLE);
- }
-
- PositionOptions options;
- switch (getAction(action)) {
- case ACTION_CLEAR_WATCH:
- clearWatch(listenerCallbackId);
- return null;
-
- case ACTION_WATCH:
-
- try {
- options = PositionOptions.fromJSONArray(args);
- } catch (NumberFormatException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "One of the position options is not a valid number.");
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "One of the position options is not valid JSON.");
- }
-
- this.watchPosition(listenerCallbackId, options);
- return null;
-
- case ACTION_GET_POSITION:
-
- try {
- options = PositionOptions.fromJSONArray(args);
- } catch (NumberFormatException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "One of the position options is not a valid number.");
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "One of the position options is not valid JSON.");
- }
-
- this.getCurrentPosition(listenerCallbackId, options);
- return null;
-
- case ACTION_SHUTDOWN:
- this.shutdown();
- return null;
- }
-
- return new PluginResult(PluginResult.Status.INVALID_ACTION, "Geolocation: invalid action " + action);
- }
-
- /**
- * Checks if the provided location is valid.
- * @param location
- * @return true if the location is valid
- */
- protected boolean isLocationValid(Location location) {
- return location != null && location.isValid();
- }
-
- /**
- * Checks if the provided location is fresh or not.
- * @param po position options containing maximum location age allowed
- * @param location location object
- * @return true if the location is newer than maximum age allowed
- */
- protected boolean isLocationFresh(PositionOptions po, Location location) {
- return new Date().getTime() - location.getTimestamp() < po.maxAge;
- }
-
- /**
- * Checks if the accuracy of the location is high enough.
- * @param po position options containing high accuracy flag
- * @param location location object
- * @return true if the location accuracy is lower than MIN_GPS_ACCURACY
- */
- protected boolean isLocationAccurate(PositionOptions po, Location location) {
- return po.enableHighAccuracy && location.getQualifiedCoordinates().getHorizontalAccuracy() < MIN_GPS_ACCURACY;
- }
-
- /**
- * Retrieves a location provider with some criteria.
- * @param po position options
- */
- protected static LocationProvider getLocationProvider(PositionOptions po) {
- // configure criteria for location provider
- // Note: being too restrictive will make it less likely that one will be returned
- BlackBerryCriteria criteria = new BlackBerryCriteria();
-
- // can we get GPS info from the wifi network?
- if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST))
- criteria.setMode(GPSInfo.GPS_MODE_ASSIST);
- // relies on device GPS receiver - not good indoors or if obstructed
- else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS))
- criteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS);
-
- criteria.setAltitudeRequired(true);
-
- // enable full power usage to increase location accuracy
- if (po.enableHighAccuracy) {
- criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
- }
-
- // Attempt to get a location provider
- BlackBerryLocationProvider provider;
- try {
- // Note: this could return an existing provider that meets above criteria
- provider = (BlackBerryLocationProvider) LocationProvider.getInstance(criteria);
- } catch (LocationException e) {
- // all LocationProviders are currently permanently unavailable :(
- provider = null;
- }
-
- return provider;
- }
-
- /**
- * Gets the current location, then creates a location listener to receive
- * updates. Registers the specified callback with the listener.
- * @param callbackId callback to receive location updates
- * @param options position options
- */
- protected void watchPosition(String callbackId, PositionOptions options) {
-
- // attempt to retrieve a location provider
- LocationProvider provider = getLocationProvider(options);
- if (provider == null) {
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(GeolocationStatus.GPS_NOT_AVAILABLE));
- return;
- }
-
- // create a listener for location updates
- GeolocationListener listener;
- try {
- listener = new GeolocationListener(provider, callbackId, options);
- } catch (IllegalArgumentException e) {
- // if interval < -1, or
- // if (interval != -1) and
- // (timeout > interval or maxAge > interval or
- // (timeout < 1 and timeout != -1) or
- // (maxAge < 1 and maxAge != -1)
- // )
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(GeolocationStatus.GPS_JSON_EXCEPTION, e.getMessage()));
- return;
- }
-
- // store the listener
- addListener(callbackId, listener);
- }
-
- /**
- * Shuts down all location listeners.
- */
- protected synchronized void shutdown() {
- for (Enumeration listeners = this.geoListeners.elements(); listeners.hasMoreElements(); ) {
- GeolocationListener listener = (GeolocationListener) listeners.nextElement();
- listener.shutdown();
- }
- this.geoListeners.clear();
- }
-
- /**
- * Clears the watch for the specified callback id.
- * If no more watches exist for the location provider, it is shut down.
- * @param callbackId identifer of the listener to shutdown
- */
- protected void clearWatch(String callbackId) {
- synchronized(this.geoListeners) {
- GeolocationListener listener = (GeolocationListener) this.geoListeners.get(callbackId);
- listener.shutdown();
- this.geoListeners.remove(callbackId);
- }
- }
-
- /**
- * Returns a PluginResult with status OK and a JSON object representing the coords
- * @param callbackId callback to receive the the result
- * @param po position options
- */
- protected void getCurrentPosition(String callbackId, PositionOptions options) {
-
- // Check the device for its last known location (may have come from
- // another app on the device that has already requested a location).
- // If it is invalid, old, or inaccurate, attempt to get a new one.
- Location location = LocationProvider.getLastKnownLocation();
- if (!isLocationValid(location) || !isLocationFresh(options, location) || !isLocationAccurate(options, location)) {
- // attempt to retrieve a location provider
- LocationProvider provider = getLocationProvider(options);
- if (provider == null) {
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(GeolocationStatus.GPS_NOT_AVAILABLE));
- return;
- }
-
- try {
- // convert timeout from millis
- int timeout = (options.timeout > 0) ? options.timeout/1000 : -1;
- Logger.log(this.getClass().getName() + ": retrieving location with timeout=" + timeout);
- location = provider.getLocation(timeout);
- } catch(LocationException e) {
- Logger.log(this.getClass().getName() + ": " + e.getMessage());
- provider.reset();
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(GeolocationStatus.GPS_TIMEOUT));
- return;
- } catch (InterruptedException e) {
- Logger.log(this.getClass().getName() + ": " + e.getMessage());
- provider.reset();
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(GeolocationStatus.GPS_INTERUPTED_EXCEPTION));
- return;
- }
- }
-
- // send the location back
- sendLocation(callbackId, location);
- }
-
- /**
- * Converts the location to a geo position and sends result to JavaScript.
- * @param callbackId callback to receive position
- * @param location location to send
- */
- protected void sendLocation(String callbackId, Location location) {
- // convert the location to a JSON object and return it in the PluginResult
- JSONObject position = null;
- try {
- position = Position.fromLocation(location).toJSONObject();
- } catch (JSONException e) {
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(PluginResult.Status.JSON_EXCEPTION,
- "Converting the location to a JSON object failed"));
- return;
- }
-
- // invoke the geolocation callback
- CordovaExtension.invokeSuccessCallback(callbackId,
- new GeolocationResult(GeolocationResult.Status.OK, position));
- }
-
- /**
- * Returns action to perform.
- * @param action
- * @return action to perform
- */
- protected static int getAction(String action) {
- if ("watchPosition".equals(action)) return ACTION_WATCH;
- if ("stop".equals(action)) return ACTION_CLEAR_WATCH;
- if ("getCurrentPosition".equals(action)) return ACTION_GET_POSITION;
- if ("shutdown".endsWith(action)) return ACTION_SHUTDOWN;
- return -1;
- }
-
- /**
- * Adds a location listener.
- * @param callbackId callback to receive listener updates
- * @param listener location listener
- */
- protected synchronized void addListener(String callbackId, GeolocationListener listener) {
- this.geoListeners.put(callbackId, listener);
- }
-
- /**
- * Called when Plugin is destroyed.
- */
- public void onDestroy() {
- this.shutdown();
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationListener.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationListener.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationListener.java
deleted file mode 100644
index 58ef4f0..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationListener.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.geolocation;
-
-import javax.microedition.location.Location;
-import javax.microedition.location.LocationListener;
-import javax.microedition.location.LocationProvider;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.util.Logger;
-
-/**
- * GeolocationListener listens for update notifications from a LocationProvider.
- * Provides location update notifications to registered callback.
- */
-public final class GeolocationListener implements LocationListener {
-
- private LocationProvider locationProvider; // location provider the listener listens to
- private String callbackId; // callback that is to be notified on location updates
-
- /**
- * Creates a new listener that attaches itself to the specified LocationProvider.
- * @param locationProvider location provider that listener will attach to
- * @param callbackId callback to receive location updates
- * @param options position options
- */
- public GeolocationListener(LocationProvider locationProvider, String callbackId, PositionOptions options) {
- this.locationProvider = locationProvider;
- this.callbackId = callbackId;
-
- // Add this as a location listener to the provider. Updates are received
- // at the specified interval. This is where it gets confusing:
- // the setLocationListener method takes three parameters: interval, timeout,
- // and maxAge. The listener only seems to work if all three are the same
- // value, which is probably best, since neither timeout nor maxAge can be
- // larger than interval. Also, the actual timeout to wait for a valid
- // location is [interval + timeout]. (I told you it was confusing).
- // So, we do the only thing we can do, which is to divide the user timeout
- // in half, and set it to the interval and timeout values. This will give
- // us the correct timeout value. BTW, this is exactly what RIM does in
- // their HTML5 implementation in the 6.0 browser. Try it :)
- int seconds = (options.timeout > 0) ? options.timeout/2000 : 1; // half and convert to millis
- this.locationProvider.setLocationListener(this,
- seconds, // interval - seconds between location updates
- seconds, // timeout - additional time to wait for update
- seconds); // maxage - maximum age of location
- }
-
- /**
- * Updated when location changes.
- */
- public void locationUpdated(LocationProvider provider, Location location) {
- if (location.isValid()) {
- Logger.log(this.getClass().getName() + ": updated with valid location");
- this.updateLocation(location);
- } else {
- // This just means we couldn't get a valid location within the listener interval.
- Logger.log(this.getClass().getName() + ": updated with invalid location");
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(GeolocationStatus.GPS_TIMEOUT));
- }
- }
-
- /**
- * Updated when provider state changes.
- */
- public void providerStateChanged(LocationProvider provider, int newState) {
- switch (newState) {
- case LocationProvider.AVAILABLE:
- Logger.log(this.getClass().getName() + ": provider state changed to AVAILABLE");
- break;
- case LocationProvider.OUT_OF_SERVICE:
- Logger.log(this.getClass().getName() + ": provider state changed to OUT_OF_SERVICE");
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(GeolocationStatus.GPS_OUT_OF_SERVICE));
- this.shutdown();
- break;
- case LocationProvider.TEMPORARILY_UNAVAILABLE:
- Logger.log(this.getClass().getName() + ": provider state changed to TEMPORARILY_UNAVAILABLE");
- // This is what happens when you are inside
- // TODO: explore possible ways to recover
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(GeolocationStatus.GPS_TEMPORARILY_UNAVAILABLE));
- this.shutdown();
- break;
- }
- }
-
- /**
- * Shuts down the listener by resetting the location provider.
- */
- public void shutdown() {
- Logger.log(this.getClass().getName() + ": resetting location provider for callback '" + callbackId + "'");
- this.locationProvider.setLocationListener(null, 0, 0, 0);
- this.locationProvider.reset();
- }
-
- /**
- * Notifies callbacks of location updates.
- * @param location updated location
- */
- protected void updateLocation(Location location) {
- JSONObject position = null;
- try {
- position = Position.fromLocation(location).toJSONObject();
- } catch (JSONException e) {
- CordovaExtension.invokeErrorCallback(callbackId,
- new GeolocationResult(PluginResult.Status.JSON_EXCEPTION, "Converting the location to a JSON object failed"));
- }
-
- CordovaExtension.invokeSuccessCallback(callbackId,
- new GeolocationResult(GeolocationStatus.OK, position));
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationResult.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationResult.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationResult.java
deleted file mode 100644
index 9969701..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationResult.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.geolocation;
-
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.util.Logger;
-
-/**
- * Extends PluginResult for the purposes of overriding the success and error
- * callback invocations.
- */
-public class GeolocationResult extends PluginResult {
-
- /**
- * Constructor.
- * @param status
- */
- public GeolocationResult(Status status) {
- super(status);
- }
-
- /**
- * Constructor.
- * @param status
- * @param message
- */
- public GeolocationResult(Status status, String message) {
- super(status, message);
- }
-
- /**
- * Constructor.
- * @param status
- * @param message
- */
- public GeolocationResult(Status status, JSONObject message) {
- super(status, message);
- }
-
- /**
- * Produces the invocation string for the specified geolocation success callback.
- * @param callbackId callback identifier
- */
- public String toSuccessCallbackString(String callbackId) {
- Logger.log(this.getClass().getName() + ": invoking success callback: " + callbackId + ", with args: " + this.getJSONString());
- return "try { navigator.geolocation.success('"+callbackId+"', " + this.getJSONString() + "); } catch(e) { alert('error in success callback:' + e.message); }";
- }
-
- /**
- * Produces the invocation string for the specified geolocation error callback.
- * @param callbackId callback identifier
- */
- public String toErrorCallbackString(String callbackId) {
- return "try { navigator.geolocation.fail('"+callbackId+"', " + this.getJSONString() + "); } catch(e) { alert('error in error callback:' + e.message); }";
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationStatus.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationStatus.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationStatus.java
deleted file mode 100644
index 4c70a10..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/GeolocationStatus.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.geolocation;
-
-import org.apache.cordova.api.PluginResult;
-
-public class GeolocationStatus extends PluginResult.Status {
-
- protected GeolocationStatus(int status, String message) {
- super(status, message);
- }
-
- public static final GeolocationStatus GPS_NOT_AVAILABLE = new GeolocationStatus(101, "GPS not available");
- public static final GeolocationStatus GPS_OUT_OF_SERVICE = new GeolocationStatus(102, "GPS out of service");
- public static final GeolocationStatus GPS_TEMPORARILY_UNAVAILABLE = new GeolocationStatus(103, "GPS temporarily unavailable");
- public static final GeolocationStatus GPS_TIMEOUT = new GeolocationStatus(104, "GPS location acquisition timed out");
- public static final GeolocationStatus GPS_INTERUPTED_EXCEPTION = new GeolocationStatus(105, "GPS location acquisition interrupted");
- public static final GeolocationStatus GPS_INVALID_LOCATION = new GeolocationStatus(106, "GPS returned an invalid location");
- public static final GeolocationStatus GPS_JSON_EXCEPTION = new GeolocationStatus(107, "An illegal argument was passed to the location listener");
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/Position.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/Position.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/Position.java
deleted file mode 100644
index 6ce490e..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/Position.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.geolocation;
-
-import javax.microedition.location.Location;
-
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-
-/**
- * Stores geo location variables.
- */
-public class Position {
-
- private double _lat = 0;
- private double _lng = 0;
- private float altitude = 0;
- private float accuracy = 0;
- private float alt_accuracy = 0;
- private float heading = 0;
- private float velocity = 0;
- private long timestamp = 0;
-
- public Position(double lat, double lng, float altitude, float accuracy, float alt_accuracy,
- float heading, float speed, long timestamp) {
- this._lat = lat;
- this._lng = lng;
- this.altitude = altitude;
- this.accuracy = accuracy;
- this.alt_accuracy = alt_accuracy;
- this.heading = heading;
- this.velocity = speed;
- this.timestamp = timestamp;
- }
-
- public static Position fromLocation(Location location) {
- double latitude = location.getQualifiedCoordinates().getLatitude();
- double longitude = location.getQualifiedCoordinates().getLongitude();
- float altitude = location.getQualifiedCoordinates().getAltitude();
- float accuracy = location.getQualifiedCoordinates().getHorizontalAccuracy();
- float alt_accuracy = location.getQualifiedCoordinates().getVerticalAccuracy();
- float heading = location.getCourse();
- float speed = location.getSpeed();
- long time = location.getTimestamp();
-
- return new Position(latitude, longitude, altitude, accuracy, alt_accuracy, heading, speed, time);
- }
-
- public double getLatitude() {
- return _lat;
- }
-
- public void setLatitude(double _lat) {
- this._lat = _lat;
- }
-
- public double getLongitude() {
- return _lng;
- }
-
- public void setLongitude(double _lng) {
- this._lng = _lng;
- }
-
- public float getAltitude() {
- return altitude;
- }
-
- public void setAltitude(float altitude) {
- this.altitude = altitude;
- }
-
- public float getAccuracy() {
- return accuracy;
- }
-
- public void setAccuracy(float accuracy) {
- this.accuracy = accuracy;
- }
-
- public float getAltitudeAccuracy() {
- return alt_accuracy;
- }
-
- public void setAltitudeAccuracy(float alt_accuracy) {
- this.alt_accuracy = alt_accuracy;
- }
-
- public float getHeading() {
- return heading;
- }
-
- public void setHeading(float heading) {
- this.heading = heading;
- }
-
- public float getVelocity() {
- return velocity;
- }
-
- public void setVelocity(float velocity) {
- this.velocity = velocity;
- }
-
- public long getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(long timestamp) {
- this.timestamp = timestamp;
- }
-
- public JSONObject toJSONObject() throws JSONException {
- return new JSONObject("{latitude:" + String.valueOf(_lat) + ", longitude:" + String.valueOf(_lng) + ", altitude:" + altitude + ", accuracy:" + accuracy + ", heading:" + heading + ", speed:" + velocity + ", alt_accuracy:" + alt_accuracy + ", timestamp:" + timestamp + "}");
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/PositionOptions.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/PositionOptions.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/PositionOptions.java
deleted file mode 100644
index 85d5853..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/geolocation/PositionOptions.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.geolocation;
-
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-
-public class PositionOptions {
- private static final int START_ARG_MAX_AGE = 1;
- private static final int START_ARG_TIMEOUT = 2;
- private static final int START_ARG_HIGH_ACCURACY = 3;
-
- public int maxAge;
- public int timeout;
- public boolean enableHighAccuracy;
-
- public static PositionOptions fromJSONArray(JSONArray args) throws NumberFormatException, JSONException {
- PositionOptions po = new PositionOptions();
-
- po.maxAge = Integer.parseInt(args.getString(START_ARG_MAX_AGE));
- po.timeout = Integer.parseInt(args.getString(START_ARG_TIMEOUT));
- po.enableHighAccuracy = args.getBoolean(START_ARG_HIGH_ACCURACY);
-
- return po;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Globalization.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Globalization.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Globalization.java
deleted file mode 100644
index e6aaae5..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Globalization.java
+++ /dev/null
@@ -1,558 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.globalization;
-
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONObject;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-
-import net.rim.device.api.i18n.Locale;
-import net.rim.device.api.i18n.SimpleDateFormat;
-import net.rim.device.api.util.TimeZoneUtilities;
-import javax.microedition.global.Formatter;
-
-import java.util.Date;
-import java.util.Calendar;
-import java.util.TimeZone;
-import java.lang.Long;
-
-public class Globalization extends Plugin {
-
- /**
- * Executes the requested action and returns a PluginResult.
- *
- * @param action
- * The action to execute.
- * @param data
- * JSONArry of arguments for the action.
- * @param callbackId
- * The callback ID to be invoked upon action completion
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray data, String callbackId) {
- JSONObject obj = new JSONObject();
-
- try {
- if (action.equals(Resources.GETLOCALENAME)) {
- obj = getLocaleName();
- } else if (action.equals(Resources.GETPREFERREDLANGUAGE)) {
- obj = getPreferredLanguage();
- } else if (action.equalsIgnoreCase(Resources.DATETOSTRING)) {
- obj = getDateToString(data);
- } else if (action.equalsIgnoreCase(Resources.STRINGTODATE)) {
- obj = getStringToDate(data);
- } else if (action.equalsIgnoreCase(Resources.GETDATEPATTERN)) {
- obj = getDatePattern(data);
- } else if (action.equalsIgnoreCase(Resources.GETDATENAMES)) {
- obj = getDateNames(data);
- } else if (action.equalsIgnoreCase(Resources.ISDAYLIGHTSAVINGSTIME)) {
- obj = getIsDayLightSavingsTime(data);
- } else if (action.equalsIgnoreCase(Resources.GETFIRSTDAYOFWEEK)) {
- obj = getFirstDayOfWeek(data);
- } else if (action.equalsIgnoreCase(Resources.NUMBERTOSTRING)) {
- obj = getNumberToString(data);
- } else if (action.equalsIgnoreCase(Resources.STRINGTONUMBER)) {
- obj = getStringToNumber(data);
- } else if (action.equalsIgnoreCase(Resources.GETNUMBERPATTERN)) {
- obj = getNumberPattern(data);
- } else if (action.equalsIgnoreCase(Resources.GETCURRENCYPATTERN)) {
- obj = getCurrencyPattern(data);
- } else {
- return new PluginResult(PluginResult.Status.INVALID_ACTION);
- }
- } catch (GlobalizationError ge) {
- return new PluginResult(PluginResult.Status.ERROR, ge.toJson());
- } catch (Exception e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
- }
-
- return new PluginResult(PluginResult.Status.OK, obj);
- }
-
- /**
- * Returns the string identifier for the client's current locale setting.
- *
- * @return JSONObject Object.value {String}: The locale identifier
- *
- * @throws GlobalizationError.UNKNOWN_ERROR
- */
- private JSONObject getLocaleName() throws GlobalizationError {
- JSONObject obj = new JSONObject();
- try {
- return obj.put("value", Locale.getDefault().toString());
- } catch (Exception e) {
- throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
- }
- }
-
- /**
- * Returns the string identifier for the client's current language
- *
- * @return JSONObject Object.value {String}: The language identifier
- *
- * @throws GlobalizationError.UNKNOWN_ERROR
- */
- private JSONObject getPreferredLanguage() throws GlobalizationError {
- JSONObject obj = new JSONObject();
- try {
- return obj.put("value", Locale.getDefault().getDisplayLanguage()
- .toString());
- } catch (Exception e) {
- throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
- }
- }
-
- /**
- * Returns a date formatted as a string according to the client's user
- * preferences and calendar using the time zone of the client.
- *
- * @return JSONObject Object.value {String}: The localized date string
- *
- * @throws GlobalizationError.FORMATTING_ERROR
- */
- private JSONObject getDateToString(JSONArray options)
- throws GlobalizationError {
- JSONObject obj = new JSONObject();
- try {
- Date date = new Date(Long.parseLong(options.getJSONObject(0)
- .get(Resources.DATE).toString()));
- // get formatting pattern from BB device
- SimpleDateFormat fmt = new SimpleDateFormat(
- Util.getBlackBerryDatePattern(options));
-
- // return formatted date
- return obj.put("value", fmt.format(date));
- } catch (Exception ge) {
- throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR);
- }
- }
-
- /**
- * Parses a date formatted as a string according to the client's user
- * preferences and calendar using the time zone of the client and returns
- * the corresponding date object
- *
- * @return JSONObject
- * Object.year {Number}: The four digit year
- * Object.month {Number}: The month from (0 - 11)
- * Object.day {Number}: The day from (1 - 31)
- * Object.hour {Number}: The hour from (0 - 23)
- * Object.minute {Number}: The minute from (0 - 59)
- * Object.second {Number}: The second from (0 - 59)
- * Object.millisecond {Number}: The milliseconds (from 0 - 999),
- * not available on all platforms
- *
- * @throws GlobalizationError.PARSING_ERROR
- */
- private JSONObject getStringToDate(JSONArray options)
- throws GlobalizationError {
- JSONObject obj = new JSONObject();
- try {
- // get formatting pattern from BB device
- SimpleDateFormat fmt = new SimpleDateFormat(
- Util.getBlackBerryDatePattern(options));
-
- // Manually parse string based on user preferences or Locale default
- String userDate = options.getJSONObject(0)
- .get(Resources.DATESTRING).toString().trim();
-
- Calendar date = Util.dateParserBB(userDate, fmt.toPattern());
- if (date == null) { // date was unparsable
- throw new Exception();
- }
-
- // return properties;
- obj.put("year", date.get(Calendar.YEAR));
- obj.put("month", date.get(Calendar.MONTH)); // returns 0-11
- obj.put("day", date.get(Calendar.DAY_OF_MONTH));
- obj.put("hour", date.get(Calendar.HOUR));
- obj.put("minute", date.get(Calendar.MINUTE));
- obj.put("second", date.get(Calendar.SECOND));
- obj.put("millisecond", date.get(Calendar.MILLISECOND));
- return obj;
- } catch (Exception ge) {
- throw new GlobalizationError(GlobalizationError.PARSING_ERROR);
- }
- }
-
- /**
- * Returns a pattern string for formatting and parsing dates according to
- * the client's user preferences.
- *
- * @return JSONObject
- * Object.pattern {String}: The date and time pattern for
- * formatting and parsing dates. The patterns follow
- * Unicode Technical Standard #35
- * http://unicode.org/reports/tr35/tr35-4.html
- * Object.timezone {String}: The abbreviated name of the time
- * zone on the client
- * Object.utc_offset {Number}: The current difference in seconds
- * between the client's time zon and coordinated universal
- * time.
- * Object.dst_offset {Number}: The current daylight saving time
- * offset in seconds between the client's non-daylight
- * saving's time zone and the client's daylight saving's
- * time zone.
- *
- * @throws GlobalizationError.PATTERN_ERROR
- */
- private JSONObject getDatePattern(JSONArray options)
- throws GlobalizationError {
- JSONObject obj = new JSONObject();
- try {
- // TimeZone from users device
- TimeZone tz = Calendar.getInstance().getTimeZone();
-
- // Daylight
- boolean daylight = tz.useDaylightTime();
-
- // set dst_offset
- int dst_offset = 0; // defaulted to zero
- if (daylight) {
- Calendar c = Calendar.getInstance();
- dst_offset = (tz.getOffset(1, c.get(Calendar.YEAR),
- c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH),
- c.get(Calendar.DAY_OF_WEEK),
- c.get(Calendar.MILLISECOND))) / 1000;
- }
-
- obj.put("pattern", Util.getBlackBerryDatePattern(options));
- obj.put("timezone", TimeZoneUtilities.getDisplayName(tz,
- TimeZoneUtilities.SHORT));
- obj.put("utc_offset", tz.getRawOffset() / 1000);
- obj.put("dst_offset", dst_offset);
- return obj;
- } catch (Exception ge) {
- throw new GlobalizationError(GlobalizationError.PATTERN_ERROR);
- }
- }
-
- /**
- * Returns an array of either the names of the months or days of the week
- * according to the client's user preferences and calendar
- *
- * @return JSONObject
- * Object.value {Array{String}}: The array of names starting from
- * either the first month in the year or the first day
- * of the week.
- *
- * @throws GlobalizationError.UNKNOWN_ERROR
- */
- private JSONObject getDateNames(JSONArray options)
- throws GlobalizationError {
- JSONObject obj = new JSONObject();
- JSONArray value = new JSONArray();
- try {
- int type = 0; // default wide
- int item = 0; // default months
-
- // get options if available
- if (options.getJSONObject(0).length() > 0) {
- // get type if available
- if (!((JSONObject) options.getJSONObject(0).get(
- Resources.OPTIONS)).isNull(Resources.TYPE)) {
- String t = (String) ((JSONObject) options.getJSONObject(0)
- .get(Resources.OPTIONS)).get(Resources.TYPE);
- if (t.equalsIgnoreCase(Resources.NARROW)) {
- type++;
- } // DateUtils.LENGTH_MEDIUM
- }
- // get item if available
- if (!((JSONObject) options.getJSONObject(0).get(
- Resources.OPTIONS)).isNull(Resources.ITEM)) {
- String t = (String) ((JSONObject) options.getJSONObject(0)
- .get(Resources.OPTIONS)).get(Resources.ITEM);
- if (t.equalsIgnoreCase(Resources.DAYS)) {
- item += 10;
- } // Days of week start at 1
- }
- }
- // determine return value
-
- int method = item + type;
- if (method == 1) {
- value = Util.getDateNameString(Resources.MONTHS, "MMM");
- }// months and narrow
- else if (method == 10) {
- value = Util.getDateNameString(Resources.DAYS, "EEEE");
- }// days and wide
- else if (method == 11) {
- value = Util.getDateNameString(Resources.DAYS, "EEE");
- }// days and narrow
- else {
- value = Util.getDateNameString(Resources.MONTHS, "MMMM");
- }// default: months and wide
-
- if (value == null) {
- throw new Exception();
- }
-
- // return array of names
- return obj.put("value", value);
- } catch (Exception ge) {
- throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
- }
- }
-
- /**
- * Returns whether daylight savings time is in effect for a given date using
- * the client's time zone and calendar.
- *
- * @return JSONObject
- * Object.dst {Boolean}: The value "true" indicates that daylight
- * savings time is in effect for the given date and
- * "false" indicates that it is not.
- *
- * @throws GlobalizationError.UNKNOWN_ERROR
- *
- * Note: Functionality to determine if date is within day light
- * savings time is not available in this API version
- */
- private JSONObject getIsDayLightSavingsTime(JSONArray options)
- throws GlobalizationError {
- throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
- }
-
- /**
- * Returns the first day of the week according to the client's user
- * preferences and calendar. The days of the week are numbered starting from
- * 1 where 1 is considered to be Sunday.
- *
- * @return JSONObject
- * Object.value {Number}: The number of the first day of the week.
- *
- * @throws GlobalizationError.UNKNOWN_ERROR
- */
- private JSONObject getFirstDayOfWeek(JSONArray options)
- throws GlobalizationError {
- JSONObject obj = new JSONObject();
- try {
- JSONObject result = Util.getLocaleData(Locale.getDefault()
- .toString());
-
- if (result == null || result.length() <= 0) {
- throw new Exception();
- }
- return obj.put("value", Integer.valueOf(result
- .getString(Resources.JSON_FIRISTDAYOFWEEK)));
- } catch (Exception e) {
- throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
- }
- }
-
- /**
- * Returns a number formatted as a string according to the client's user
- * preferences.
- *
- * @return JSONObject
- * Object.value {String}: The formatted number string.
- *
- * @throws GlobalizationError.FORMATTING_ERROR
- */
- private JSONObject getNumberToString(JSONArray options)
- throws GlobalizationError {
- JSONObject obj = new JSONObject();
- String value;
- try {
- // Initialize formatter
- Formatter fmt = new Formatter(Locale.getDefault().toString());
-
- // obtain user supplied number
- double num = Double.parseDouble(options.getJSONObject(0)
- .get(Resources.NUMBER).toString());
- // format based on options if available
- value = fmt.formatNumber(num);
- if (options.getJSONObject(0).length() > 1) {
- // options were included
- if (!((JSONObject) options.getJSONObject(0).get(
- Resources.OPTIONS)).isNull(Resources.TYPE)) {
- String fmtOpt = (String) ((JSONObject) options
- .getJSONObject(0).get(Resources.OPTIONS))
- .get(Resources.TYPE);
- if (fmtOpt.equalsIgnoreCase(Resources.CURRENCY)) {
- value = fmt.formatCurrency(num);
- } else if (fmtOpt.equalsIgnoreCase(Resources.PERCENT)) {
- // convert double to long
- // used 1 decimal places as a default
- value = fmt.formatPercentage((float) num, 1);
- }
- }
- }
- return obj.put("value", value);
- } catch (Exception ge) {
- throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR);
- }
-
- }
-
- /**
- * Parses a number formatted as a string according to the client's user
- * preferences and returns the corresponding number.
- *
- * @return JSONObject
- * Object.value {Number}: The parsed number.
- *
- * @throws GlobalizationError.PARSING_ERROR
- */
- private JSONObject getStringToNumber(JSONArray options)
- throws GlobalizationError {
- JSONObject obj = new JSONObject();
- double value = 0;
- try {
- // format based on options if available
- String num = options.getJSONObject(0).get(Resources.NUMBERSTRING)
- .toString().trim();
- if (options.getJSONObject(0).length() > 1) {
- // options were included
- if (!((JSONObject) options.getJSONObject(0).get(
- Resources.OPTIONS)).isNull(Resources.TYPE)) {
- String fmtOpt = (String) ((JSONObject) options
- .getJSONObject(0).get(Resources.OPTIONS))
- .get(Resources.TYPE);
- // remove unwanted symbols
- if (fmtOpt.equalsIgnoreCase(Resources.CURRENCY)) {
- value = (Double.parseDouble(Util.removeSymbols(num)));
- } else if (fmtOpt.equalsIgnoreCase(Resources.PERCENT)) {
- value = (Double.parseDouble(Util.removeSymbols(num)) / 100);
- }
- }
- } else {
- value = Double.parseDouble(num); // decimal default
- }
-
- return obj.put("value", value);
- } catch (Exception ge) {
- throw new GlobalizationError(GlobalizationError.PARSING_ERROR);
- }
- }
-
- /**
- * Returns a pattern string for formatting and parsing numbers according to
- * the client's user preferences.
- *
- * @return JSONObject
- * Object.pattern {String}: The number pattern for formatting and
- * parsing numbers. The patterns follow Unicode
- * Technical Standard #35.
- * http://unicode.org/reports/tr35/tr35-4.html
- * Object.symbol {String}: The symbol to be used when formatting
- * and parsing e.g., percent or currency symbol.
- * Object.fraction {Number}: The number of fractional digits to use
- * when parsing and formatting numbers.
- * Object.rounding {Number}: The rounding increment to use when
- * parsing and formatting.
- * Object.positive {String}: The symbol to use for positive numbers
- * when parsing and formatting.
- * Object.negative: {String}: The symbol to use for negative
- * numbers when parsing and formatting.
- * Object.decimal: {String}: The decimal symbol to use for parsing
- * and formatting.
- * Object.grouping: {String}: The grouping symbol to use for
- * parsing and formatting.
- *
- * @throws GlobalizationError.PATTERN_ERROR
- */
- private JSONObject getNumberPattern(JSONArray options)
- throws GlobalizationError {
- JSONObject obj = new JSONObject();
- try {
- JSONObject result = Util.getLocaleData(Locale.getDefault()
- .toString());
-
- String symbol = Resources.JSON_DECIMALSYMBOL;
- // get Date value + options (if available)
- if (options.getJSONObject(0).length() > 0) {
- // options were included
- if (!((JSONObject) options.getJSONObject(0).get(
- Resources.OPTIONS)).isNull(Resources.TYPE)) {
- String fmtOpt = (String) ((JSONObject) options
- .getJSONObject(0).get(Resources.OPTIONS))
- .get(Resources.TYPE);
- if (fmtOpt.equalsIgnoreCase(Resources.CURRENCY)) {
- symbol = Resources.JSON_CURRENCYSYMBOL;
- } else if (fmtOpt.equalsIgnoreCase(Resources.PERCENT)) {
- symbol = Resources.JSON_PERCENTSYMBOL;
- }
- }
- }
-
- // return properties
- obj.put("pattern", result.getString(Resources.JSON_PATTERN));
- obj.put("symbol", result.getString(symbol));
- obj.put("fraction",
- Integer.valueOf(result.getString(Resources.JSON_FRACTION)));
- obj.put("rounding",
- Integer.valueOf(result.getString(Resources.JSON_ROUNDING)));
- obj.put("positive", result.getString(Resources.JSON_POSITIVE));
- obj.put("negative", result.getString(Resources.JSON_NEGATIVE));
- obj.put("decimal", result.getString(Resources.JSON_DECIMALSYMBOL));
- obj.put("grouping", result.getString(Resources.JSON_GROUPING));
- return obj;
- } catch (Exception ge) {
- throw new GlobalizationError(GlobalizationError.PATTERN_ERROR);
- }
- }
-
- /**
- * Returns a pattern string for formatting and parsing currency values
- * according to the client's user preferences and ISO 4217 currency code.
- *
- * @return JSONObject =
- * Object.pattern {String}: The currency pattern for formatting and
- * parsing currency values. The patterns follow
- * Unicode Technical Standard #35
- * http://unicode.org/reports/tr35/tr35-4.html
- * Object.code {String}: The ISO 4217 currency code for the pattern.
- * Object.fraction {Number}: The number of fractional digits to use
- * when parsing and formatting currency.
- * Object.rounding {Number}: The rounding increment to use when
- * parsing and formatting.
- * Object.decimal: {String}: The decimal symbol to use for parsing
- * and formatting.
- * Object.grouping: {String}: The grouping symbol to use for
- * parsing and formatting.
- *
- * @throws GlobalizationError.FORMATTING_ERROR
- */
- private JSONObject getCurrencyPattern(JSONArray options)
- throws GlobalizationError {
- JSONObject obj = new JSONObject();
- try {
- JSONObject result = Util.getCurrencyData(Locale.getDefault()
- .toString(),
- options.getJSONObject(0).getString(Resources.CURRENCYCODE));
-
- // return properties
- obj.put("pattern", result.getString(Resources.JSON_CURRENCYPATTERN));
- obj.put("code", result.getString(Resources.JSON_CURRENCYCODE));
- obj.put("fraction", Integer.valueOf(result
- .getString(Resources.JSON_CURRENCYFRACTION)));
- obj.put("rounding", Integer.valueOf(result
- .getString(Resources.JSON_CURRENCYROUNDING)));
- obj.put("decimal", result.getString(Resources.JSON_CURRENCYDECIMAL));
- obj.put("grouping",
- result.getString(Resources.JSON_CURRENCYGROUPING));
- return obj;
- } catch (Exception ge) {
- throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/GlobalizationError.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/GlobalizationError.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/GlobalizationError.java
deleted file mode 100644
index b2a9388..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/GlobalizationError.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.globalization;
-
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-
-/**
- * User initiated exception. Exception class representing defined Globalization
- * error codes.
- *
- * Globalization error codes:
- * GlobalizationError.UNKNOWN_ERROR = 0;
- * GlobalizationError.FORMATTING_ERROR = 1;
- * GlobalizationError.PARSING_ERROR = 2;
- * GlobalizationError.PATTERN_ERROR = 3;
- */
-public class GlobalizationError extends Exception {
-
- private static final long serialVersionUID = 1L;
- public static final String UNKNOWN_ERROR = "UNKNOWN_ERROR";
- public static final String FORMATTING_ERROR = "FORMATTING_ERROR";
- public static final String PARSING_ERROR = "PARSING_ERROR";
- public static final String PATTERN_ERROR = "PATTERN_ERROR";
-
- int error = 0; // default unknown error thrown
-
- /**
- * Default constructor
- */
- public GlobalizationError() {
- }
-
- /**
- * Create an exception returning an error code
- *
- * @param s
- */
- public GlobalizationError(String s) {
- if (s.equalsIgnoreCase(FORMATTING_ERROR)) {
- error = 1;
- } else if (s.equalsIgnoreCase(PARSING_ERROR)) {
- error = 2;
- } else if (s.equalsIgnoreCase(PATTERN_ERROR)) {
- error = 3;
- }
- }
-
- /**
- * get error string based on error code
- *
- * @param String
- * msg
- */
- public String getErrorString() {
- String msg = "";
- switch (error) {
- case 0:
- msg = UNKNOWN_ERROR;
- break;
- case 1:
- msg = FORMATTING_ERROR;
- break;
- case 2:
- msg = PARSING_ERROR;
- break;
- case 3:
- msg = PATTERN_ERROR;
- break;
- }
- return msg;
- }
-
- /**
- * get error code
- *
- * @param String
- * msg
- */
- public int getErrorCode() {
- return error;
- }
-
- /**
- * get the json version of this object to return to javascript
- *
- * @return
- */
- public JSONObject toJson() {
- JSONObject obj = new JSONObject();
- try {
- obj.put("code", getErrorCode());
- obj.put("message", getErrorString());
- } catch (JSONException e) {
- // never happens
- }
- return obj;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Resources.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Resources.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Resources.java
deleted file mode 100644
index 02cbc8a..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Resources.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.globalization;
-
-public class Resources {
- // Globalization Plugin Actions
- public static final String GETLOCALENAME = "getLocaleName";
- public static final String DATETOSTRING = "dateToString";
- public static final String STRINGTODATE = "stringToDate";
- public static final String GETDATEPATTERN = "getDatePattern";
- public static final String GETDATENAMES = "getDateNames";
- public static final String ISDAYLIGHTSAVINGSTIME = "isDayLightSavingsTime";
- public static final String GETFIRSTDAYOFWEEK = "getFirstDayOfWeek";
- public static final String NUMBERTOSTRING = "numberToString";
- public static final String STRINGTONUMBER = "stringToNumber";
- public static final String GETNUMBERPATTERN = "getNumberPattern";
- public static final String GETCURRENCYPATTERN = "getCurrencyPattern";
- public static final String GETPREFERREDLANGUAGE = "getPreferredLanguage";
-
- // Globalization Option Parameters
- public static final String OPTIONS = "options";
- public static final String FORMATLENGTH = "formatLength";
- public static final String MEDIUM = "medium";
- public static final String LONG = "long";
- public static final String FULL = "full";
- public static final String SELECTOR = "selector";
- public static final String DATE = "date";
- public static final String TIME = "time";
- public static final String DATESTRING = "dateString";
- public static final String TYPE = "type";
- public static final String ITEM = "item";
- public static final String NARROW = "narrow";
- public static final String WIDE = "wide";
- public static final String MONTHS = "months";
- public static final String DAYS = "days";
- public static final String SPACE = " ";
- public static final String DATEDELIMITER = "-";
- public static final String TIMEDELIMITER = ":";
- public static final String[] AM_PMFORMATS = { "a", "aa" };
- public static final String NUMBER = "number";
- public static final String NUMBERSTRING = "numberString";
- public static final String PERCENT = "percent";
- public static final String CURRENCY = "currency";
- public static final String CURRENCYCODE = "currencyCode";
-
- // JSON File: JSONObject
- public static final String JSON_CURRENCY = "currency";
- public static final String JSON_LOCALE = "locale";
- public static final String JSON_NAME = "name";
-
- // JSON File: parameters
- // locale:
- public static final String JSON_PATTERN = "pattern";
- public static final String JSON_DECIMAL = "decimal";
- public static final String JSON_FRACTION = "fraction";
- public static final String JSON_ROUNDING = "rounding";
- public static final String JSON_GROUPING = "grouping";
- public static final String JSON_NEGATIVE = "negative";
- public static final String JSON_FIRISTDAYOFWEEK = "firstDayOfWeek";
- public static final String JSON_POSITIVE = "positive";
- public static final String JSON_PERCENTSYMBOL = "percentSymbol";
- public static final String JSON_CURRENCYSYMBOL = "currencySymbol";
- public static final String JSON_DECIMALSYMBOL = "decimalSymbol";
- public static final String JSON_DISPLAYNAME = "displayName";
-
- // currency
- public static final String JSON_CURRENCYCODE = "currencyCode";
- public static final String JSON_CURRENCYPATTERN = "currencyPattern";
- public static final String JSON_CURRENCYDECIMAL = "currencyDecimal";
- public static final String JSON_CURRENCYFRACTION = "currencyFraction";
- public static final String JSON_CURRENCYGROUPING = "currencyGrouping";
- public static final String JSON_CURRENCYROUNDING = "currencyRounding";
-
- // class paths:
- public static final String LOCALEINFOPATH = "/res/resourceBundles/";
- public static final String LOCALEINFOPATHEND = ".js.gz";
-
- // locale resource key identifiers
- public static final int LOCALENAME = 0;
-
- // Persistent Store ID:
- public static final long PERSISTENTSTORE_ID = 0x10001;
-}
[30/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/FileTransfer.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/FileTransfer.java b/lib/cordova-android/framework/src/org/apache/cordova/FileTransfer.java
index c1ca15c..784c34c 100644
--- a/lib/cordova-android/framework/src/org/apache/cordova/FileTransfer.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/FileTransfer.java
@@ -64,6 +64,8 @@ import android.os.Build;
import android.util.Log;
import android.webkit.CookieManager;
+import com.squareup.okhttp.OkHttpClient;
+
public class FileTransfer extends CordovaPlugin {
private static final String LOG_TAG = "FileTransfer";
@@ -79,6 +81,8 @@ public class FileTransfer extends CordovaPlugin {
private static HashMap<String, RequestContext> activeRequests = new HashMap<String, RequestContext>();
private static final int MAX_BUFFER_SIZE = 16 * 1024;
+ private static OkHttpClient httpClient = new OkHttpClient();
+
private static final class RequestContext {
String source;
String target;
@@ -174,39 +178,6 @@ public class FileTransfer extends CordovaPlugin {
}
}
- /**
- * Works around a bug on Android 2.3.
- * http://code.google.com/p/android/issues/detail?id=14562
- */
- private static final class DoneHandlerInputStream extends TrackingHTTPInputStream {
- private boolean done;
-
- public DoneHandlerInputStream(InputStream stream) {
- super(stream);
- }
-
- @Override
- public int read() throws IOException {
- int result = done ? -1 : super.read();
- done = (result == -1);
- return result;
- }
-
- @Override
- public int read(byte[] buffer) throws IOException {
- int result = done ? -1 : super.read(buffer);
- done = (result == -1);
- return result;
- }
-
- @Override
- public int read(byte[] bytes, int offset, int count) throws IOException {
- int result = done ? -1 : super.read(bytes, offset, count);
- done = (result == -1);
- return result;
- }
- }
-
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("upload") || action.equals("download")) {
@@ -327,13 +298,13 @@ public class FileTransfer extends CordovaPlugin {
if (useHttps) {
// Using standard HTTPS connection. Will not allow self signed certificate
if (!trustEveryone) {
- conn = (HttpsURLConnection) url.openConnection();
+ conn = (HttpsURLConnection) httpClient.open(url);
}
// Use our HTTPS connection that blindly trusts everyone.
// This should only be used in debug environments
else {
// Setup the HTTPS connection class to trust everyone
- HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
+ HttpsURLConnection https = (HttpsURLConnection) httpClient.open(url);
oldSocketFactory = trustAllHosts(https);
// Save the current hostnameVerifier
oldHostnameVerifier = https.getHostnameVerifier();
@@ -344,7 +315,7 @@ public class FileTransfer extends CordovaPlugin {
}
// Return a standard HTTP connection
else {
- conn = (HttpURLConnection) url.openConnection();
+ conn = httpClient.open(url);
}
// Allow Inputs
@@ -561,9 +532,6 @@ public class FileTransfer extends CordovaPlugin {
}
private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
- return new DoneHandlerInputStream(conn.getInputStream());
- }
String encoding = conn.getContentEncoding();
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));
@@ -681,7 +649,7 @@ public class FileTransfer extends CordovaPlugin {
*/
private static String getArgument(JSONArray args, int position, String defaultString) {
String arg = defaultString;
- if (args.length() >= position) {
+ if (args.length() > position) {
arg = args.optString(position);
if (arg == null || "null".equals(arg)) {
arg = defaultString;
@@ -749,13 +717,13 @@ public class FileTransfer extends CordovaPlugin {
if (useHttps) {
// Using standard HTTPS connection. Will not allow self signed certificate
if (!trustEveryone) {
- connection = (HttpsURLConnection) url.openConnection();
+ connection = (HttpsURLConnection) httpClient.open(url);
}
// Use our HTTPS connection that blindly trusts everyone.
// This should only be used in debug environments
else {
// Setup the HTTPS connection class to trust everyone
- HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
+ HttpsURLConnection https = (HttpsURLConnection) httpClient.open(url);
oldSocketFactory = trustAllHosts(https);
// Save the current hostnameVerifier
oldHostnameVerifier = https.getHostnameVerifier();
@@ -766,7 +734,8 @@ public class FileTransfer extends CordovaPlugin {
}
// Return a standard HTTP connection
else {
- connection = url.openConnection();
+ connection = httpClient.open(url);
+
}
if (connection instanceof HttpURLConnection) {
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/FileUtils.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/FileUtils.java b/lib/cordova-android/framework/src/org/apache/cordova/FileUtils.java
index 2135be9..e62fc4a 100755
--- a/lib/cordova-android/framework/src/org/apache/cordova/FileUtils.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/FileUtils.java
@@ -18,8 +18,6 @@
*/
package org.apache.cordova;
-import android.database.Cursor;
-import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
@@ -27,6 +25,7 @@ import android.util.Log;
import org.apache.commons.codec.binary.Base64;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
+import org.apache.cordova.api.DataResource;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.file.EncodingException;
import org.apache.cordova.file.FileExistsException;
@@ -46,8 +45,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLDecoder;
import java.nio.channels.FileChannel;
/**
@@ -234,7 +231,7 @@ public class FileUtils extends CordovaPlugin {
* @param filePath the path to check
*/
private void notifyDelete(String filePath) {
- String newFilePath = FileHelper.getRealPath(filePath, cordova);
+ String newFilePath = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.notifyDelete").getRealFile().getPath();
try {
this.cordova.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.Media.DATA + " = ?",
@@ -256,37 +253,10 @@ public class FileUtils extends CordovaPlugin {
* @throws IOException if the user can't read the file
* @throws JSONException
*/
- @SuppressWarnings("deprecation")
private JSONObject resolveLocalFileSystemURI(String url) throws IOException, JSONException {
- String decoded = URLDecoder.decode(url, "UTF-8");
+ File fp = DataResource.initiateNewDataRequestForUri(url, webView.pluginManager, cordova, "FileUtils.resolveLocalFileSystemURI").getRealFile();
- File fp = null;
-
- // Handle the special case where you get an Android content:// uri.
- if (decoded.startsWith("content:")) {
- Cursor cursor = this.cordova.getActivity().managedQuery(Uri.parse(decoded), new String[] { MediaStore.Images.Media.DATA }, null, null, null);
- // Note: MediaStore.Images/Audio/Video.Media.DATA is always "_data"
- int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
- cursor.moveToFirst();
- fp = new File(cursor.getString(column_index));
- } else {
- // Test to see if this is a valid URL first
- @SuppressWarnings("unused")
- URL testUrl = new URL(decoded);
-
- if (decoded.startsWith("file://")) {
- int questionMark = decoded.indexOf("?");
- if (questionMark < 0) {
- fp = new File(decoded.substring(7, decoded.length()));
- } else {
- fp = new File(decoded.substring(7, questionMark));
- }
- } else {
- fp = new File(decoded);
- }
- }
-
- if (!fp.exists()) {
+ if (fp == null || !fp.exists()) {
throw new FileNotFoundException();
}
if (!fp.canRead()) {
@@ -304,9 +274,9 @@ public class FileUtils extends CordovaPlugin {
* @throws JSONException
*/
private JSONArray readEntries(String fileName) throws FileNotFoundException, JSONException {
- File fp = createFileObject(fileName);
+ File fp = DataResource.initiateNewDataRequestForUri(fileName, webView.pluginManager, cordova, "FileUtils.readEntries").getRealFile();
- if (!fp.exists()) {
+ if (fp == null || !fp.exists()) {
// The directory we are listing doesn't exist so we should fail.
throw new FileNotFoundException();
}
@@ -341,8 +311,10 @@ public class FileUtils extends CordovaPlugin {
* @throws FileExistsException
*/
private JSONObject transferTo(String fileName, String newParent, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
- String newFileName = FileHelper.getRealPath(fileName, cordova);
- newParent = FileHelper.getRealPath(newParent, cordova);
+ DataResource dataResourceFrom = DataResource.initiateNewDataRequestForUri(fileName, webView.pluginManager, cordova, "FileUtils.transferTo");
+ String newFileName = dataResourceFrom.getRealFile().getPath();
+ DataResource dataResourceTo = DataResource.initiateNewDataRequestForUri(newParent, webView.pluginManager, cordova, "FileUtils.transferTo");
+ newParent = dataResourceTo.getRealFile().getPath();
// Check for invalid file name
if (newName != null && newName.contains(":")) {
@@ -613,7 +585,7 @@ public class FileUtils extends CordovaPlugin {
* @throws FileExistsException
*/
private boolean removeRecursively(String filePath) throws FileExistsException {
- File fp = createFileObject(filePath);
+ File fp = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.readEntries").getRealFile();
// You can't delete the root directory.
if (atRootDirectory(filePath)) {
@@ -654,7 +626,7 @@ public class FileUtils extends CordovaPlugin {
* @throws InvalidModificationException
*/
private boolean remove(String filePath) throws NoModificationAllowedException, InvalidModificationException {
- File fp = createFileObject(filePath);
+ File fp = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.readEntries").getRealFile();
// You can't delete the root directory.
if (atRootDirectory(filePath)) {
@@ -698,7 +670,8 @@ public class FileUtils extends CordovaPlugin {
throw new EncodingException("This file has a : in it's name");
}
- File fp = createFileObject(dirPath, fileName);
+ String filePath = getFullFilePath(dirPath, fileName);
+ File fp = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.getFile").getRealFile();
if (create) {
if (exclusive && fp.exists()) {
@@ -740,15 +713,14 @@ public class FileUtils extends CordovaPlugin {
* @param fileName new file name
* @return
*/
- private File createFileObject(String dirPath, String fileName) {
- File fp = null;
+ private String getFullFilePath(String dirPath, String fileName) {
if (fileName.startsWith("/")) {
- fp = new File(fileName);
+ return fileName;
} else {
- dirPath = FileHelper.getRealPath(dirPath, cordova);
- fp = new File(dirPath + File.separator + fileName);
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(dirPath, webView.pluginManager, cordova, "FileUtils.getFullFilePath");
+ dirPath = dataResource.getRealFile().getPath();
+ return dirPath + File.separator + fileName;
}
- return fp;
}
/**
@@ -760,12 +732,13 @@ public class FileUtils extends CordovaPlugin {
* @throws JSONException
*/
private JSONObject getParent(String filePath) throws JSONException {
- filePath = FileHelper.getRealPath(filePath, cordova);
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.getParent");
+ filePath = dataResource.getRealFile().getPath();
if (atRootDirectory(filePath)) {
return getEntry(filePath);
}
- return getEntry(new File(filePath).getParent());
+ return getEntry(dataResource.getRealFile().getParent());
}
/**
@@ -776,7 +749,7 @@ public class FileUtils extends CordovaPlugin {
* @return true if we are at the root, false otherwise.
*/
private boolean atRootDirectory(String filePath) {
- filePath = FileHelper.getRealPath(filePath, cordova);
+ filePath = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.atRootDirectory").getRealFile().getPath();
if (filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + cordova.getActivity().getPackageName() + "/cache") ||
filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()) ||
@@ -787,19 +760,6 @@ public class FileUtils extends CordovaPlugin {
}
/**
- * Create a File object from the passed in path
- *
- * @param filePath
- * @return
- */
- private File createFileObject(String filePath) {
- filePath = FileHelper.getRealPath(filePath, cordova);
-
- File file = new File(filePath);
- return file;
- }
-
- /**
* Look up metadata about this entry.
*
* @param filePath to entry
@@ -807,9 +767,9 @@ public class FileUtils extends CordovaPlugin {
* @throws FileNotFoundException
*/
private long getMetadata(String filePath) throws FileNotFoundException {
- File file = createFileObject(filePath);
+ File file = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.getMetadata").getRealFile();
- if (!file.exists()) {
+ if (file == null || !file.exists()) {
throw new FileNotFoundException("Failed to find file in getMetadata");
}
@@ -825,15 +785,16 @@ public class FileUtils extends CordovaPlugin {
* @throws JSONException
*/
private JSONObject getFileMetadata(String filePath) throws FileNotFoundException, JSONException {
- File file = createFileObject(filePath);
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.getMetadata");
+ File file = dataResource.getRealFile();
- if (!file.exists()) {
+ if (file == null || !file.exists()) {
throw new FileNotFoundException("File: " + filePath + " does not exist.");
}
JSONObject metadata = new JSONObject();
metadata.put("size", file.length());
- metadata.put("type", FileHelper.getMimeType(filePath, cordova));
+ metadata.put("type", dataResource.getMimeType());
metadata.put("name", file.getName());
metadata.put("fullPath", filePath);
metadata.put("lastModifiedDate", file.lastModified());
@@ -935,7 +896,8 @@ public class FileUtils extends CordovaPlugin {
this.cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
- byte[] bytes = readAsBinaryHelper(filename, start, end);
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(filename, webView.pluginManager, cordova, "FileUtils.readFileAs");
+ byte[] bytes = readAsBinaryHelper(dataResource.getInputStream(), start, end);
PluginResult result;
switch (resultType) {
@@ -949,7 +911,7 @@ public class FileUtils extends CordovaPlugin {
result = new PluginResult(PluginResult.Status.OK, bytes, true);
break;
default: // Base64.
- String contentType = FileHelper.getMimeType(filename, cordova);
+ String contentType = dataResource.getMimeType();
byte[] base64 = Base64.encodeBase64(bytes);
String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
result = new PluginResult(PluginResult.Status.OK, s);
@@ -976,10 +938,9 @@ public class FileUtils extends CordovaPlugin {
* @return Contents of the file as a byte[].
* @throws IOException
*/
- private byte[] readAsBinaryHelper(String filename, int start, int end) throws IOException {
+ private byte[] readAsBinaryHelper(InputStream inputStream, int start, int end) throws IOException {
int numBytesToRead = end - start;
byte[] bytes = new byte[numBytesToRead];
- InputStream inputStream = FileHelper.getInputStreamFromUriString(filename, cordova);
int numBytesRead = 0;
if (start > 0) {
@@ -1008,7 +969,8 @@ public class FileUtils extends CordovaPlugin {
throw new NoModificationAllowedException("Couldn't write to file given its content URI");
}
- filename = FileHelper.getRealPath(filename, cordova);
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(filename, webView.pluginManager, cordova, "FileUtils.write");
+ filename = dataResource.getRealFile().getPath();
boolean append = false;
if (offset > 0) {
@@ -1037,13 +999,16 @@ public class FileUtils extends CordovaPlugin {
* @throws NoModificationAllowedException
*/
private long truncateFile(String filename, long size) throws FileNotFoundException, IOException, NoModificationAllowedException {
- if (filename.startsWith("content://")) {
- throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(filename, webView.pluginManager, cordova, "FileUtils.truncateFile");
+ if(!dataResource.isWritable()) {
+ throw new NoModificationAllowedException("Couldn't truncate file as it is not writable");
+ }
+ File file = dataResource.getRealFile();
+ if(file == null) {
+ throw new FileNotFoundException("Couldn't get the file");
}
- filename = FileHelper.getRealPath(filename, cordova);
-
- RandomAccessFile raf = new RandomAccessFile(filename, "rw");
+ RandomAccessFile raf = new RandomAccessFile(file, "rw");
try {
if (raf.length() >= size) {
FileChannel channel = raf.getChannel();
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/IceCreamCordovaWebViewClient.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/IceCreamCordovaWebViewClient.java b/lib/cordova-android/framework/src/org/apache/cordova/IceCreamCordovaWebViewClient.java
index 847972e..14c7603 100644
--- a/lib/cordova-android/framework/src/org/apache/cordova/IceCreamCordovaWebViewClient.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/IceCreamCordovaWebViewClient.java
@@ -22,6 +22,8 @@ import java.io.IOException;
import java.io.InputStream;
import org.apache.cordova.api.CordovaInterface;
+import org.apache.cordova.api.DataResource;
+import org.apache.cordova.api.DataResourceContext;
import org.apache.cordova.api.LOG;
import android.annotation.TargetApi;
@@ -43,41 +45,27 @@ public class IceCreamCordovaWebViewClient extends CordovaWebViewClient {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
+ // We need to support the new DataResource intercepts without breaking the shouldInterceptRequest mechanism.
+ DataResource dataResource = DataResource.initiateNewDataRequestForUri(url, this.appView.pluginManager, cordova,
+ "WebViewClient.shouldInterceptRequest");
+ url = dataResource.getUri().toString();
+
+ // This mechanism is no longer needed due to the dataResource mechanism. It would be awesome to just get rid of it.
//Check if plugins intercept the request
WebResourceResponse ret = super.shouldInterceptRequest(view, url);
- if(ret == null && (url.contains("?") || url.contains("#") || needsIceCreamSpaceInAssetUrlFix(url))){
- ret = generateWebResourceResponse(url);
- }
- return ret;
- }
-
- private WebResourceResponse generateWebResourceResponse(String url) {
- if (url.startsWith("file:///android_asset/")) {
- String mimetype = FileHelper.getMimeType(url, cordova);
+ if(ret == null) {
try {
- InputStream stream = FileHelper.getInputStreamFromUriString(url, cordova);
- WebResourceResponse response = new WebResourceResponse(mimetype, "UTF-8", stream);
- return response;
- } catch (IOException e) {
- LOG.e("generateWebResourceResponse", e.getMessage(), e);
+ InputStream is;
+ String mimeType;
+ if((is = dataResource.getInputStream()) != null && (mimeType = dataResource.getMimeType()) != null) {
+ // If we don't know how to open this file, let the browser continue loading
+ ret = new WebResourceResponse(mimeType, "UTF-8", is);
+ }
+ } catch(IOException e) {
+ LOG.e("IceCreamCordovaWebViewClient", "Error occurred while loading a file.", e);
}
}
- return null;
- }
-
- private static boolean needsIceCreamSpaceInAssetUrlFix(String url) {
- if (!url.contains("%20")){
- return false;
- }
-
- switch(android.os.Build.VERSION.SDK_INT){
- case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH:
- case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1:
- return true;
- default:
- return false;
- }
+ return ret;
}
-
}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/LinearLayoutSoftKeyboardDetect.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/LinearLayoutSoftKeyboardDetect.java b/lib/cordova-android/framework/src/org/apache/cordova/LinearLayoutSoftKeyboardDetect.java
index 280269b..52712ac 100755
--- a/lib/cordova-android/framework/src/org/apache/cordova/LinearLayoutSoftKeyboardDetect.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/LinearLayoutSoftKeyboardDetect.java
@@ -35,13 +35,13 @@ public class LinearLayoutSoftKeyboardDetect extends LinearLayout {
private int oldWidth = 0; // Need to save old width for orientation change
private int screenWidth = 0;
private int screenHeight = 0;
- private DroidGap app = null;
+ private CordovaActivity app = null;
public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) {
super(context);
screenWidth = width;
screenHeight = height;
- app = (DroidGap) context;
+ app = (CordovaActivity) context;
}
@Override
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/Notification.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/Notification.java b/lib/cordova-android/framework/src/org/apache/cordova/Notification.java
index 9d96062..cf2e95f 100755
--- a/lib/cordova-android/framework/src/org/apache/cordova/Notification.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/Notification.java
@@ -74,7 +74,7 @@ public class Notification extends CordovaPlugin {
return true;
}
else if (action.equals("prompt")) {
- this.prompt(args.getString(0), args.getString(1), args.getJSONArray(2), callbackContext);
+ this.prompt(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), callbackContext);
return true;
}
else if (action.equals("activityStart")) {
@@ -208,41 +208,40 @@ public class Notification extends CordovaPlugin {
// First button
if (buttonLabels.length() > 0) {
try {
- dlg.setNegativeButton(buttonLabels.getString(0),
- new AlertDialog.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
- }
- });
- } catch (JSONException e) { }
+ dlg.setNegativeButton(buttonLabels.getString(0),
+ new AlertDialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.dismiss();
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
+ }
+ });
+ } catch (JSONException e) { }
}
// Second button
if (buttonLabels.length() > 1) {
try {
- dlg.setNeutralButton(buttonLabels.getString(1),
- new AlertDialog.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
- }
- });
- } catch (JSONException e) { }
+ dlg.setNeutralButton(buttonLabels.getString(1),
+ new AlertDialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.dismiss();
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
+ }
+ });
+ } catch (JSONException e) { }
}
// Third button
if (buttonLabels.length() > 2) {
try {
- dlg.setPositiveButton(buttonLabels.getString(2),
- new AlertDialog.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
- }
- }
- );
- } catch (JSONException e) { }
+ dlg.setPositiveButton(buttonLabels.getString(2),
+ new AlertDialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.dismiss();
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
+ }
+ });
+ } catch (JSONException e) { }
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
@@ -271,11 +270,12 @@ public class Notification extends CordovaPlugin {
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
- public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels, final CallbackContext callbackContext) {
+ public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels, final String defaultText, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
final EditText promptInput = new EditText(cordova.getActivity());
-
+ promptInput.setHint(defaultText);
+
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(cordova.getActivity());
@@ -290,73 +290,72 @@ public class Notification extends CordovaPlugin {
// First button
if (buttonLabels.length() > 0) {
try {
- dlg.setNegativeButton(buttonLabels.getString(0),
- new AlertDialog.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- try {
- result.put("buttonIndex",1);
- result.put("input1", promptInput.getText());
- } catch (JSONException e) { e.printStackTrace(); }
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
- }
- });
- } catch (JSONException e) { }
+ dlg.setNegativeButton(buttonLabels.getString(0),
+ new AlertDialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.dismiss();
+ try {
+ result.put("buttonIndex",1);
+ result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
+ } catch (JSONException e) { e.printStackTrace(); }
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
+ }
+ });
+ } catch (JSONException e) { }
}
// Second button
if (buttonLabels.length() > 1) {
try {
- dlg.setNeutralButton(buttonLabels.getString(1),
- new AlertDialog.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- try {
- result.put("buttonIndex",2);
- result.put("input1", promptInput.getText());
- } catch (JSONException e) { e.printStackTrace(); }
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
- }
- });
- } catch (JSONException e) { }
+ dlg.setNeutralButton(buttonLabels.getString(1),
+ new AlertDialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.dismiss();
+ try {
+ result.put("buttonIndex",2);
+ result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
+ } catch (JSONException e) { e.printStackTrace(); }
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
+ }
+ });
+ } catch (JSONException e) { }
}
// Third button
if (buttonLabels.length() > 2) {
try {
- dlg.setPositiveButton(buttonLabels.getString(2),
- new AlertDialog.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- try {
- result.put("buttonIndex",3);
- result.put("input1", promptInput.getText());
- } catch (JSONException e) { e.printStackTrace(); }
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
- }
- }
- );
- } catch (JSONException e) { }
+ dlg.setPositiveButton(buttonLabels.getString(2),
+ new AlertDialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.dismiss();
+ try {
+ result.put("buttonIndex",3);
+ result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
+ } catch (JSONException e) { e.printStackTrace(); }
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
+ }
+ });
+ } catch (JSONException e) { }
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
- public void onCancel(DialogInterface dialog)
- {
+ public void onCancel(DialogInterface dialog){
dialog.dismiss();
- try {
- result.put("buttonIndex",0);
- result.put("input1", promptInput.getText());
- } catch (JSONException e) { e.printStackTrace(); }
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
+ try {
+ result.put("buttonIndex",0);
+ result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
+ } catch (JSONException e) { e.printStackTrace(); }
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
dlg.create();
dlg.show();
-
+
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
+
/**
* Show the spinner.
*
@@ -446,5 +445,4 @@ public class Notification extends CordovaPlugin {
this.progressDialog = null;
}
}
-
}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/StandAlone.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/StandAlone.java b/lib/cordova-android/framework/src/org/apache/cordova/StandAlone.java
deleted file mode 100644
index a199dda..0000000
--- a/lib/cordova-android/framework/src/org/apache/cordova/StandAlone.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-package org.apache.cordova;
-
-import android.os.Bundle;
-
-public class StandAlone extends DroidGap {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- super.loadUrl("file:///android_asset/www/index.html");
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/api/CordovaPlugin.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/api/CordovaPlugin.java b/lib/cordova-android/framework/src/org/apache/cordova/api/CordovaPlugin.java
index 2b225e6..866677c 100644
--- a/lib/cordova-android/framework/src/org/apache/cordova/api/CordovaPlugin.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/api/CordovaPlugin.java
@@ -176,6 +176,20 @@ public class CordovaPlugin {
}
/**
+ * All plugins can now choose if they want to modify any uri requests. This includes all webview requests, opening of files, content uri's etc.
+ * This mechanism allows several plugins to modify the same request
+ * @param requestSource The source of the incoming request
+ *
+ * @param dataResource The resource to be loaded.
+ * @param dataResourceContext Context associated with the resource load
+ * @return Return a new DataResource if the plugin wants to assist in loading the request or null if it doesn't.
+ */
+ @TargetApi(Build.VERSION_CODES.HONEYCOMB)
+ public DataResource handleDataResourceRequest(DataResource dataResource, DataResourceContext dataResourceContext) {
+ return null;
+ }
+
+ /**
* Called when the WebView does a top-level navigation or refreshes.
*
* Plugins should stop any long-running processes and clean up internal state.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/api/DataResource.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/api/DataResource.java b/lib/cordova-android/framework/src/org/apache/cordova/api/DataResource.java
new file mode 100644
index 0000000..3e6ead8
--- /dev/null
+++ b/lib/cordova-android/framework/src/org/apache/cordova/api/DataResource.java
@@ -0,0 +1,141 @@
+package org.apache.cordova.api;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.cordova.FileHelper;
+
+import android.net.Uri;
+
+/*
+ * All requests to access files, browser network requests etc have to go through this class.
+ */
+public class DataResource {
+ private CordovaInterface cordova;
+
+ // Uri of the request. Always required.
+ private Uri uri;
+ // Remaining fields may or may not be null
+ private InputStream is;
+ private OutputStream os;
+ private String mimeType;
+ private Boolean writable;
+ private File realFile;
+ private boolean retryIsLoad = true;
+ private boolean retryOsLoad = true;
+ private boolean retryMimeTypeLoad = true;
+ private boolean retryWritableLoad = true;
+ private boolean retryRealFileLoad = true;
+
+ public DataResource(CordovaInterface cordova, Uri uri) {
+ this.cordova = cordova;
+ this.uri = uri;
+ }
+ public DataResource(CordovaInterface cordova, Uri uri, InputStream is,
+ OutputStream os, String mimeType, boolean writable, File realFile) {
+ this(cordova, uri);
+ this.is = is;
+ this.mimeType = mimeType;
+ this.writable = Boolean.valueOf(writable);
+ this.realFile = realFile;
+ }
+ public Uri getUri() {
+ // Uri is always provided
+ return uri;
+ }
+ public InputStream getInputStream() throws IOException {
+ if(is == null && retryIsLoad) {
+ try {
+ is = FileHelper.getInputStreamFromUriString(uri.toString(), cordova);
+ } finally {
+ // We failed loading once, don't try loading anymore
+ if(is == null) {
+ retryIsLoad = false;
+ }
+ }
+ }
+ return is;
+ }
+ public OutputStream getOutputStream() throws FileNotFoundException {
+ if(os == null && retryOsLoad) {
+ try {
+ os = FileHelper.getOutputStreamFromUriString(uri.toString(), cordova);
+ } finally {
+ // We failed loading once, don't try loading anymore
+ if(os == null) {
+ retryOsLoad = false;
+ }
+ }
+ }
+ return os;
+ }
+ public String getMimeType() {
+ if(mimeType == null && retryMimeTypeLoad) {
+ try {
+ mimeType = FileHelper.getMimeType(uri.toString(), cordova);
+ } finally {
+ // We failed loading once, don't try loading anymore
+ if(mimeType == null) {
+ retryMimeTypeLoad = false;
+ }
+ }
+ }
+ return mimeType;
+ }
+ public boolean isWritable() {
+ if(writable == null && retryWritableLoad) {
+ try {
+ writable = FileHelper.isUriWritable(uri.toString());
+ } finally {
+ // We failed loading once, don't try loading anymore
+ if(writable == null) {
+ retryWritableLoad = false;
+ }
+ }
+ }
+ // default to false
+ return writable != null && writable.booleanValue();
+ }
+ public File getRealFile() {
+ if(realFile == null && retryRealFileLoad) {
+ try {
+ String realPath = FileHelper.getRealPath(uri, cordova);
+ if(realPath != null) {
+ realFile = new File(realPath);
+ }
+ } finally {
+ // We failed loading once, don't try loading anymore
+ if(realFile == null) {
+ retryRealFileLoad = false;
+ }
+ }
+ }
+ return realFile;
+ }
+
+ // static instantiation methods
+ public static DataResource initiateNewDataRequestForUri(String uriString, PluginManager pluginManager, CordovaInterface cordova, String requestSourceTag){
+ // if no protocol is specified, assume its file:
+ uriString = FileHelper.insertFileProtocol(uriString);
+ return initiateNewDataRequestForUri(Uri.parse(uriString), pluginManager, cordova, requestSourceTag);
+ }
+ public static DataResource initiateNewDataRequestForUri(Uri uri, PluginManager pluginManager, CordovaInterface cordova, String requestSourceTag){
+ return initiateNewDataRequestForUri(uri, pluginManager, cordova, new DataResourceContext(requestSourceTag));
+ }
+ public static DataResource initiateNewDataRequestForUri(String uriString, PluginManager pluginManager, CordovaInterface cordova, DataResourceContext dataResourceContext){
+ // if no protocol is specified, assume its file:
+ uriString = FileHelper.insertFileProtocol(uriString);
+ return initiateNewDataRequestForUri(Uri.parse(uriString), pluginManager, cordova, dataResourceContext);
+ }
+ public static DataResource initiateNewDataRequestForUri(Uri uri, PluginManager pluginManager, CordovaInterface cordova, DataResourceContext dataResourceContext){
+ DataResource dataResource = new DataResource(cordova, uri);
+ if (pluginManager != null) {
+ // get the resource as returned by plugins
+ dataResource = pluginManager.handleDataResourceRequestWithPlugins(dataResource, dataResourceContext);
+ }
+ return dataResource;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/api/DataResourceContext.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/api/DataResourceContext.java b/lib/cordova-android/framework/src/org/apache/cordova/api/DataResourceContext.java
new file mode 100644
index 0000000..310586b
--- /dev/null
+++ b/lib/cordova-android/framework/src/org/apache/cordova/api/DataResourceContext.java
@@ -0,0 +1,31 @@
+package org.apache.cordova.api;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+/*
+ * Some context information associated with a DataRequest.
+ */
+public class DataResourceContext {
+ // A random id that is unique for a particular request.
+ private int requestId;
+ // A tag associated with the source of this dataResourceContext
+ private String source;
+ // If needed, any data associated with core plugins can be a part of the context object
+ // If needed, any data associated with non core plugins should store data in a Map so as to not clutter the context object
+ private Map<String, Object> dataMap;
+ public DataResourceContext(String source) {
+ this.requestId = new Random().nextInt();
+ this.source = source;
+ this.dataMap = new HashMap<String, Object>();
+ }
+ public int getRequestId() {
+ return requestId;
+ }
+ public String getSource() {
+ return source;
+ }
+ public Map<String, Object> getDataMap() {
+ return dataMap;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/api/PluginManager.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/api/PluginManager.java b/lib/cordova-android/framework/src/org/apache/cordova/api/PluginManager.java
index 774b21c..e0ceabf 100755
--- a/lib/cordova-android/framework/src/org/apache/cordova/api/PluginManager.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/api/PluginManager.java
@@ -54,6 +54,7 @@ public class PluginManager {
// Map URL schemes like foo: to plugins that want to handle those schemes
// This would allow how all URLs are handled to be offloaded to a plugin
protected HashMap<String, String> urlMap = new HashMap<String, String>();
+ private int MAX_REPITIONS = 1000;
/**
* Constructor.
@@ -109,7 +110,6 @@ public class PluginManager {
int eventType = -1;
String service = "", pluginClass = "", paramType = "";
boolean onload = false;
- PluginEntry entry = null;
boolean insideFeature = false;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
@@ -118,45 +118,37 @@ public class PluginManager {
if (strNode.equals("plugin")) {
service = xml.getAttributeValue(null, "name");
pluginClass = xml.getAttributeValue(null, "value");
- // System.out.println("Plugin: "+name+" => "+value);
+ Log.d(TAG, "<plugin> tags are deprecated, please use <features> instead. <plugin> will no longer work as of Cordova 3.0");
onload = "true".equals(xml.getAttributeValue(null, "onload"));
- entry = new PluginEntry(service, pluginClass, onload);
- this.addService(entry);
}
//What is this?
else if (strNode.equals("url-filter")) {
this.urlMap.put(xml.getAttributeValue(null, "value"), service);
}
else if (strNode.equals("feature")) {
- insideFeature = true;
- //Check for supported feature sets (Accelerometer, Geolocation, etc)
+ //Check for supported feature sets aka. plugins (Accelerometer, Geolocation, etc)
//Set the bit for reading params
- String uri = xml.getAttributeValue(null,"name");
+ insideFeature = true;
+ service = xml.getAttributeValue(null, "name");
}
- else if(strNode.equals("param")) {
- if(insideFeature)
- {
- paramType = xml.getAttributeValue(null, "name");
- if(paramType.equals("service"))
- service = xml.getAttributeValue(null, "value");
- else if(paramType.equals("package"))
- pluginClass = xml.getAttributeValue(null, "value");
- if(service.length() > 0 && pluginClass.length() > 0)
- {
- onload = "true".equals(xml.getAttributeValue(null, "onload"));
- entry = new PluginEntry(service, pluginClass, onload);
- this.addService(entry);
- service = "";
- pluginClass = "";
- }
- }
+ else if (insideFeature && strNode.equals("param")) {
+ paramType = xml.getAttributeValue(null, "name");
+ if (paramType.equals("service")) // check if it is using the older service param
+ service = xml.getAttributeValue(null, "value");
+ else if (paramType.equals("package") || paramType.equals("android-package"))
+ pluginClass = xml.getAttributeValue(null,"value");
+ else if (paramType.equals("onload"))
+ onload = "true".equals(xml.getAttributeValue(null, "value"));
}
}
else if (eventType == XmlResourceParser.END_TAG)
{
String strNode = xml.getName();
- if(strNode.equals("feature"))
+ if (strNode.equals("feature") || strNode.equals("plugin"))
{
+ PluginEntry entry = new PluginEntry(service, pluginClass, onload);
+ this.addService(entry);
+
//Empty the strings to prevent plugin loading bugs
service = "";
pluginClass = "";
@@ -409,4 +401,32 @@ public class PluginManager {
LOG.e(TAG, "https://git-wip-us.apache.org/repos/asf?p=incubator-cordova-android.git;a=blob;f=framework/res/xml/plugins.xml");
LOG.e(TAG, "=====================================================================================");
}
+
+ /**
+ * Called when the any resource is going to be loaded - either from the webview, files or any other resource
+ *
+ *
+ * @param dataResource The resource request to be loaded.
+ * @param dataResourceContext The context of the dataResource request
+ * @return Return the resource request that will be loaded. The returned request may be modified or unchanged.
+ */
+ public DataResource handleDataResourceRequestWithPlugins(DataResource dataResource, DataResourceContext dataResourceContext){
+ int repetitions = 0;
+ boolean requestModified = true;
+ while(requestModified && repetitions < MAX_REPITIONS) {
+ requestModified = false;
+ repetitions ++;
+ for (PluginEntry entry : this.entries.values()) {
+ if (entry.plugin != null) {
+ DataResource ret = entry.plugin.handleDataResourceRequest(dataResource, dataResourceContext);
+ if(ret != null) {
+ dataResource = ret;
+ requestModified = true;
+ break;
+ }
+ }
+ }
+ }
+ return dataResource;
+ }
}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/test/proguard.cfg
----------------------------------------------------------------------
diff --git a/lib/cordova-android/test/proguard.cfg b/lib/cordova-android/test/proguard.cfg
deleted file mode 100644
index b1cdf17..0000000
--- a/lib/cordova-android/test/proguard.cfg
+++ /dev/null
@@ -1,40 +0,0 @@
--optimizationpasses 5
--dontusemixedcaseclassnames
--dontskipnonpubliclibraryclasses
--dontpreverify
--verbose
--optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-
--keep public class * extends android.app.Activity
--keep public class * extends android.app.Application
--keep public class * extends android.app.Service
--keep public class * extends android.content.BroadcastReceiver
--keep public class * extends android.content.ContentProvider
--keep public class * extends android.app.backup.BackupAgentHelper
--keep public class * extends android.preference.Preference
--keep public class com.android.vending.licensing.ILicensingService
-
--keepclasseswithmembernames class * {
- native <methods>;
-}
-
--keepclasseswithmembers class * {
- public <init>(android.content.Context, android.util.AttributeSet);
-}
-
--keepclasseswithmembers class * {
- public <init>(android.content.Context, android.util.AttributeSet, int);
-}
-
--keepclassmembers class * extends android.app.Activity {
- public void *(android.view.View);
-}
-
--keepclassmembers enum * {
- public static **[] values();
- public static ** valueOf(java.lang.String);
-}
-
--keep class * implements android.os.Parcelable {
- public static final android.os.Parcelable$Creator *;
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/test/res/xml/config.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-android/test/res/xml/config.xml b/lib/cordova-android/test/res/xml/config.xml
index 675aeb5..d3ea4d8 100644
--- a/lib/cordova-android/test/res/xml/config.xml
+++ b/lib/cordova-android/test/res/xml/config.xml
@@ -1,57 +1,86 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-<cordova>
- <!--
- access elements control the Android whitelist.
- Domains are assumed blocked unless set otherwise
- -->
-
- <access origin="http://127.0.0.1*"/> <!-- allow local pages -->
-
- <!-- <access origin="https://example.com" /> allow any secure requests to example.com -->
- <!-- <access origin="https://example.com" subdomains="true" /> such as above, but including subdomains, such as www -->
- <access origin=".*"/>
+<?xml version="1.0" encoding="UTF-8"?>
+<widget xmlns = "http://www.w3.org/ns/widgets"
+ id = "io.cordova.helloCordova"
+ version = "2.0.0">
+ <name>Hello Cordova</name>
+
+ <description>
+ A sample Apache Cordova application that responds to the deviceready event.
+ </description>
+
+ <author href="http://cordova.io" email="callback-dev@incubator.apache.org">
+ Apache Cordova Team
+ </author>
+
+ <access origin="*"/>
+
+
+ <!-- <content src="http://mysite.com/myapp.html" /> for external pages -->
+ <content src="index.html" />
<log level="DEBUG"/>
+
+ <!-- Preferences for Android -->
<preference name="useBrowserHistory" value="true" />
-<plugins>
- <plugin name="App" value="org.apache.cordova.App"/>
- <plugin name="Activity" value="org.apache.cordova.test.ActivityPlugin"/>
- <plugin name="Geolocation" value="org.apache.cordova.GeoBroker"/>
- <plugin name="Device" value="org.apache.cordova.Device"/>
- <plugin name="Accelerometer" value="org.apache.cordova.AccelListener"/>
- <plugin name="Compass" value="org.apache.cordova.CompassListener"/>
- <plugin name="Media" value="org.apache.cordova.AudioHandler"/>
- <plugin name="Camera" value="org.apache.cordova.CameraLauncher"/>
- <plugin name="Contacts" value="org.apache.cordova.ContactManager"/>
- <plugin name="File" value="org.apache.cordova.FileUtils"/>
- <plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager"/>
- <plugin name="Notification" value="org.apache.cordova.Notification"/>
- <plugin name="Storage" value="org.apache.cordova.Storage"/>
- <plugin name="FileTransfer" value="org.apache.cordova.FileTransfer"/>
- <plugin name="Capture" value="org.apache.cordova.Capture"/>
- <plugin name="Battery" value="org.apache.cordova.BatteryListener"/>
- <plugin name="SplashScreen" value="org.apache.cordova.SplashScreen"/>
- <plugin name="Echo" value="org.apache.cordova.Echo" />
- <plugin name="Globalization" value="org.apache.cordova.Globalization"/>
- <plugin name="InAppBrowser" value="org.apache.cordova.InAppBrowser"/>
-</plugins>
-</cordova>
+ <preference name="exit-on-suspend" value="false" />
+
+ <feature name="App">
+ <param name="android-package" value="org.apache.cordova.App"/>
+ </feature>
+ <feature name="Geolocation">
+ <param name="android-package" value="org.apache.cordova.GeoBroker"/>
+ </feature>
+ <feature name="Device">
+ <param name="android-package" value="org.apache.cordova.Device"/>
+ </feature>
+ <feature name="Accelerometer">
+ <param name="android-package" value="org.apache.cordova.AccelListener"/>
+ </feature>
+ <feature name="Compass">
+ <param name="android-package" value="org.apache.cordova.CompassListener"/>
+ </feature>
+ <feature name="Media">
+ <param name="android-package" value="org.apache.cordova.AudioHandler"/>
+ </feature>
+ <feature name="Camera">
+ <param name="android-package" value="org.apache.cordova.CameraLauncher"/>
+ </feature>
+ <feature name="Contacts">
+ <param name="android-package" value="org.apache.cordova.ContactManager"/>
+ </feature>
+ <feature name="File">
+ <param name="android-package" value="org.apache.cordova.FileUtils"/>
+ </feature>
+ <feature name="NetworkStatus">
+ <param name="android-package" value="org.apache.cordova.NetworkManager"/>
+ </feature>
+ <feature name="Notification">
+ <param name="android-package" value="org.apache.cordova.Notification"/>
+ </feature>
+ <feature name="Storage">
+ <param name="android-package" value="org.apache.cordova.Storage"/>
+ </feature>
+ <feature name="FileTransfer">
+ <param name="android-package" value="org.apache.cordova.FileTransfer"/>
+ </feature>
+ <feature name="Capture">
+ <param name="android-package" value="org.apache.cordova.Capture"/>
+ </feature>
+ <feature name="Battery">
+ <param name="android-package" value="org.apache.cordova.BatteryListener"/>
+ </feature>
+ <feature name="SplashScreen">
+ <param name="android-package" value="org.apache.cordova.SplashScreen"/>
+ </feature>
+ <feature name="Echo">
+ <param name="android-package" value="org.apache.cordova.Echo"/>
+ </feature>
+ <feature name="Globalization">
+ <param name="android-package" value="org.apache.cordova.Globalization"/>
+ </feature>
+ <feature name="InAppBrowser">
+ <param name="android-package" value="org.apache.cordova.InAppBrowser"/>
+ </feature>
+
+</widget>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/.jshint
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/.jshint b/lib/cordova-blackberry/.jshint
new file mode 100644
index 0000000..9f5611b
--- /dev/null
+++ b/lib/cordova-blackberry/.jshint
@@ -0,0 +1,3 @@
+{
+ "es5" : true
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/.jshintignore
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/.jshintignore b/lib/cordova-blackberry/.jshintignore
new file mode 100644
index 0000000..6bb2b92
--- /dev/null
+++ b/lib/cordova-blackberry/.jshintignore
@@ -0,0 +1 @@
+bin/test/cordova/unit/params-bad.json
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/.npmignore
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/.npmignore b/lib/cordova-blackberry/.npmignore
new file mode 100644
index 0000000..db4145c
--- /dev/null
+++ b/lib/cordova-blackberry/.npmignore
@@ -0,0 +1,2 @@
+.gitignore
+.gitkeep
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/Jakefile
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/Jakefile b/lib/cordova-blackberry/Jakefile
new file mode 100644
index 0000000..81b2f6f
--- /dev/null
+++ b/lib/cordova-blackberry/Jakefile
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF
+ * or more contributor license agreements. See th
+ * distributed with this work for additional infor
+ * regarding copyright ownership. The ASF license
+ * to you under the Apache License, Version 2.0 (t
+ * "License"); you may not use this file except in
+ * with the License. You may obtain a copy of the
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to
+ * software distributed under the License is distr
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
+ * KIND, either express or implied. See the Licen
+ * specific language governing permissions and lim
+ * under the License.
+ */
+
+var DESC_NEW_LINE = "\n\t\t #";
+
+var util = require('util'),
+ fs = require('fs'),
+ childProcess = require('child_process'),
+ path = require("path"),
+ rexp_minified = new RegExp("\\.min\\.js$"),
+ rexp_src = new RegExp('\\.js$');
+
+// HELPERS
+// Iterates over a directory
+function forEachFile(root, cbFile, cbDone) {
+ var count = 0;
+
+ function scan(name) {
+ ++count;
+
+ fs.stat(name, function (err, stats) {
+ if (err) cbFile(err);
+
+ if (stats.isDirectory()) {
+ fs.readdir(name, function (err, files) {
+ if (err) cbFile(err);
+
+ files.forEach(function (file) {
+ scan(path.join(name, file));
+ });
+ done();
+ });
+ } else if (stats.isFile()) {
+ cbFile(null, name, stats, done);
+ } else {
+ done();
+ }
+ });
+ }
+
+ function done() {
+ --count;
+ if (count === 0 && cbDone) cbDone();
+ }
+
+ scan(root);
+}
+
+desc("runs test");
+task('default', ['hint','test'], function () {});
+
+desc("run all tests in node - jake test [path]");
+task('test', [], function () {
+ require('./scripts/test')(null, process.argv.length >= 4 ? process.argv[3] : null);
+});
+
+desc('check sources with JSHint');
+task('hint', ['complainwhitespace'], function () {
+ var knownWarnings = [
+ "Redefinition of 'FileReader'",
+ "Redefinition of 'require'",
+ "Read only",
+ "Redefinition of 'console'"
+ ];
+ var filterKnownWarnings = function(el, index, array) {
+ var wut = true;
+ // filter out the known warnings listed out above
+ knownWarnings.forEach(function(e) {
+ wut = wut && (el.indexOf(e) == -1);
+ });
+ wut = wut && (!el.match(/\d+ errors/));
+ return wut;
+ };
+
+ childProcess.exec("jshint framework/lib bin/lib bin/test bin/templates/project/cordova bin/templates/project/project.json --config .jshint --extra-ext .json",function(err,stdout,stderr) {
+ var exs = stdout.split('\n');
+ console.log(exs.filter(filterKnownWarnings).join('\n'));
+ complete();
+ });
+}, true);
+
+var complainedAboutWhitespace = false
+
+desc('complain about what fixwhitespace would fix');
+task('complainwhitespace', function() {
+ processWhiteSpace(function(file, newSource) {
+ if (!complainedAboutWhitespace) {
+ console.log("files with whitespace issues: (to fix: `jake fixwhitespace`)")
+ complainedAboutWhitespace = true
+ }
+
+ console.log(" " + file)
+ })
+}, true);
+
+desc('converts tabs to four spaces, eliminates trailing white space, converts newlines to proper form - enforcing style guide ftw!');
+task('fixwhitespace', function() {
+ processWhiteSpace(function(file, newSource) {
+ if (!complainedAboutWhitespace) {
+ console.log("fixed whitespace issues in:")
+ complainedAboutWhitespace = true
+ }
+
+ fs.writeFileSync(file, newSource, 'utf8');
+ console.log(" " + file)
+ })
+}, true);
+
+function processWhiteSpace(processor) {
+ forEachFile('framework', function(err, file, stats, cbDone) {
+ //if (err) throw err;
+ if (rexp_minified.test(file) || !rexp_src.test(file)) {
+ cbDone();
+ } else {
+ var origsrc = src = fs.readFileSync(file, 'utf8');
+
+ // tabs -> four spaces
+ if (src.indexOf('\t') >= 0) {
+ src = src.split('\t').join(' ');
+ }
+
+ // eliminate trailing white space
+ src = src.replace(/ +\n/g, '\n');
+
+ if (origsrc !== src) {
+ // write it out yo
+ processor(file, src);
+ }
+ cbDone();
+ }
+ }, complete);
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/README.md
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/README.md b/lib/cordova-blackberry/README.md
index e2f9896..a19b87a 100644
--- a/lib/cordova-blackberry/README.md
+++ b/lib/cordova-blackberry/README.md
@@ -1,183 +1,96 @@
-Cordova BlackBerry WebWorks
-============================
+# Apache Cordova for BlackBerry 10
-[Cordova framework](http://incubator.apache.org/cordova/) for __BlackBerry Tablet OS, Smartphones and BlackBerry 10 devices__. The framework is implemented using the [BlackBerry WebWorks SDK](http://us.blackberry.com/developers/tablet/webworks.jsp).
+Apache Cordova is an application development platform which allows mobile applications to be written with web technology: HTML, CSS and JavaScript. Access to device APIs is provided by native plugins.
-Directory Structure
--------------------
+This implementation for BlackBerry 10 packages web assets into a BAR file which may be deployed to devices and simulators.
- framework/ ... BlackBerry WebWorks JavaScript Extension (Cordova native code)
- javascript/ .. Cordova JavaScript (concatenated, non-minified)
- bin/ ......... Scripts for project creation
+## Pre-requisites
-Introduction
-------------
+Install the latest BlackBerry 10 NDK:
-BlackBerry WebWorks is a framework for developing web-based applications for BlackBerry SmartPhones (BlackBerry OS 5.0 and higher) and the TabletOS. Creating a web application is one of the easiest ways to have an application that runs on both platforms.
+[https://developer.blackberry.com/native/download/](https://developer.blackberry.com/native/download)
-The WebWorks framework allows developers to create applications using web content and resources (HTML/CSS/JavaScript) that are able to access device features through the [BlackBerry WebWorks API](http://www.blackberry.com/developers/docs/widgetapi/). In addition, the framework allows developers to create their own WebWorks JavaScript Extensions to expose additional device capabilities through JavaScript APIs. These extensions are written using either the BlackBerry Java API for SmartPhones, or Adobe AIR for the Tablet OS.
+Setup environment variables:
+- [Linux/Mac] `source [BBNDK directory]/bbndk-env.sh`
+- [Windows] `[BBNDK directory]\bbndk-env.bat`
-The cordova-blackberry-webworks platform allows web developers to develop applications targeting BlackBerry 5.0 and higher devices using the common [Cordova API](http://docs.cordova.io). When possible, Cordova makes use of the WebWorks JavaScript API; however, most Cordova features are implemented in the native Java or AIR environment as a WebWorks JavaScript Extension.
+Install code signing keys:
+[https://developer.blackberry.com/html5/documentation/signing_setup_bb10_apps_2008396_11.html](https://developer.blackberry.com/html5/documentation/signing_setup_bb10_apps_2008396_11.html)
-Getting Started
-===============
+Install node.js:
-Several guides are available on the [Cordova Documentation site](http://docs.cordova.io/) (Getting Started Guides - on the left side near the bottom) to help you get started developing for the cordova-blackberry-webworks platform. This guide will help you install and configure the BlackBerry WebWorks development environment, and the cordova-blackberry-webworks platform. It will also step you through the process of creating a Cordova project.
+[http://nodejs.org/](http://nodejs.org/)
-[Getting Started with Cordova BlackBerry WebWorks](http://docs.cordova.io/guide_getting-started_blackberry_index.md.html)
+## Getting Started
-This guide is for advanced developers who wish to develop their own cordova-blackberry-webworks plugin.
+Create a new project:
-[How To Create a Cordova Plugin for Cordova BlackBerry WebWorks](http://docs.cordova.io/guide_plugin-development_blackberry_index.md.html)
+`bin/create <path to project>`
+## Managing Targets
-Installing the cordova-blackberry-webworks Framework
-=====================================================
+A target is a device or simulator which will run the app.
-Cloning the cordova-blackberry-webworks repository always provides you with the latest (EDGE) version of the Cordova code. To clone the repository, do the following:
+This command will add a new target:
- $ cd C:\some\path\
- $ git clone git://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks.git
+`<path to project>/cordova/target add <name> <ip> <device | simulator> [-p | --password <password>] [--pin <devicepin>]`
-Cordova BlackBerry Developer Tools
----
+To remove a target:
-The Cordova developer tooling is split between general tooling and project level tooling. If you are on Windows, please run the equivalent .bat files instead of the shell scripts :)
+`<path to project>/cordova/target remove <name>`
-### General Commands
+To set a target as default:
- ./bin/create [path appname packagename] ............ creates a sample app with the specified application name, to the specified path
+`<path to project>/cordova/target default <name>`
-Please note that once you `create` a Cordova BlackBerry project, you
-will need to edit the `project.properties` file that resides inside your
-generated application directory to set up your environment properly. You
-will need to specify things like the location of the BlackBerry Widget
-Packager(s), device and signing key passwords, simulator executables,
-and device IPs (if applicable).
+## Building
-The ./bin/create command is also required to be called in order to automatically download
-the bin/template/project/lib/ant-contrib.jar file. Please be aware that without running
-this command first, your project will not have this important file! Once that ant-contrib.jar
-file is downloaded, there is no need to update that file or download again.
+`<path to project>/cordova/build`
-#### Running the Example Project
+A project can be built in debug or release mode.
-Create the example project and build it to the first device:
+To run an application in debug mode, a debug token must first be installed on the device. The build script will automatically attempt to generate a token and install it. This requires code signing keys to be installed on the development machine. Debug mode will also enable WebInspector. A prompt will appear with the URL to access WebInspector from a remote machine.
- ./bin/create
- cd example
- ./cordova/run blackberry
+If building in release mode, a unique buildId must be provided, either via command line or by setting it in config.xml.
-#### Creating a new Cordova BlackBerry Project
+Here is the build script syntax:
- ./bin/create ~/Desktop/myapp MyAppName MyAppPackageName
+`build command [<target>] [-k | --keystorepass] [-b | --buildId <number>] [-p | --params <json>] [-ll | --loglevel <level>]`
-### Project Commands
+Commands:
-These commands live in a generated Cordova BlackBerry project. As per
-the note above, please make sure you edit the `project.properties` file
-inside your application directory appropriately otherwise these commands
-will not work!
+ release [options]
+ Build in release mode. This will sign the resulting bar.
+
+ debug [options]
+ Build in debug mode.
- ./cordova/run ............................ install to a connected device or simulator
- ./cordova/build .......................... build project, but do not deploy to simulator or device
+ Options:
+ -h, --help output usage information
+ -k, --keystorepass <password> Signing key password
+ -b, --buildId <num> Specifies the build number for signing (typically incremented from previous signing).
+ -p, --params <params JSON file> Specifies additional parameters to pass to downstream tools.
+ -ll, --loglevel <loglevel> set the logging level (error, warn, verbose)`
-(Legacy) Creating a New Cordova Project
--------------------------------
+## Deploying
-The (legacy) Cordova ant build scripts enable you to create multiple, independent Cordova projects.
+To deploy the project to a target, use the run command:
-(Note: The Cordova build script requires Apache ANT 1.8 or higher. Also, these scripts won't work without
-the bin/template/project/lib/ant-contrib.jar file so please run the ./bin/create command to automatically
-download that file or manually download it and place it in the bin/template/lib/ directory.
+`<path to project>/cordova/run <target>`
-The build script packages the Cordova source code and resources into each project you create. This allows you to easily distribute the project to other BlackBerry WebWorks developers. To create a Cordova project:
+## Plugin Management
- $ cd cordova-blackberry-webworks
- $ ant help
+To add a plugin from a local path, you will first need to run fetch:
- $ ant create -Dproject.path="C:\development\my_new_project"
+`<path to project>/cordova/plugin fetch <path to plugin>`
- $ cd C:\development\my_new_project
- $ ant help
+Now the plugin can be installed by name:
-For each project, you need to tell ANT where you installed the BlackBerry WebWorks SDK, which packages and compiles your code into a deployable application. You can specify the location of the BlackBerry WebWorks Packager (BBWP) by editing __project.properties__ in the project directory.
+`<path to project>/cordova/plugin install <name>`
- [edit project.properties]
+Plugins hosted remotely can be installed by name without using fetch. To see a list of available remote plugins use:
-Building and Deploying a Project
---------------------------------
+`<path to project>/cordova/plugin list`
-The Cordova build scripts automate common tasks, such as compiling your project, and deploying it to simulators or devices. To see what options are available, use:
-
- $ cd C:\development\my_new_project
- $ ant help
-
-Every command is in the form `ant TARGET COMMAND [options]`, where
-target is either `blackberry`, `playbook` or `qnx`.
-
-To build your project into a deployable application (.cod/.jad) file:
-
- $ ant TARGET build
-
-To build your project and load it in a BlackBerry simulator:
-
- $ ant TARGET load-simulator
-
-To build your project and load it onto a USB-attached device:
-
- $ ant TARGET load-device
-
-Updating the Cordova Framework
--------------------------------
-
-As you develop your application, there may be updates made to the Cordova source code. To incorporate Cordova changes into your project, use the build script as follows:
-
- $ cd cordova-blackberry-webworks
- $ git pull origin master
-
- $ ant update -Dproject.path="C:\development\my_new_project"
-
-Customizing Cordova
---------------------
-
-By default, Cordova gives access to all the core Cordova APIs as detailed at docs.cordova.io.
-If you want to remove some of those APIs you can do so by editing the plugins.xml document in your
-application root. You need to edit the plugins.xml file to add third-party plugins to your application
-as well.
-
-Creating a Distribution
------------------------
-
-### Update Version
-
- $ ant version -Dvalue="1.0.0"
-
- $ git diff
- $ git commit -am "Update to version 1.0.0"
- $ git tag 1.0.0
-
-### Create distribution
-
- $ ant dist
-
-Troubleshooting
-===============
-
-__Q: I uploaded my application to the BlackBerry device, but it will not open or run.__
-
-__A:__ Try hard resetting the device by pressing and hold ALT + CAPS LOCK + DEL. You must press and hold each key in sequence and not all at once. Some devices require _either_ the right or left CAPS LOCK key to be pressed. Some devices also require this combination to be pressed twice.
-
-__Q: My simulator screen is not refreshing and I see blocks on a clicked position.__
-
-__A:__ Windows 7 and the simulator's graphics acceleration do not mix. On the simulator, set View -> Graphics Acceleration to Off.
-
-__Q: When I use the Cordova [Camera.getPicture API](http://docs.cordova.io/cordova_camera_camera.md.html#camera.getPicture) on my device, the camera never returns to my application. Why does this happen?__
-
-__A:__ Cordova uses a JavaScript Extension to invoke the native camera application so the user can take a picture. When the picture is taken, Cordova will close the native camera application by emulating a key injection (pressing the back/escape button). On a physical device, users will have to set permissions to allow the application to simulate key injections. Setting application permissions is device-specific. On a Storm2 (9550), for example, select the BlackBerry button from the Home screen to get to All Applications screen, then Options > Applications > Your Application. Then select Edit Default Permissions > Interactions > Input Simulation and set it to 'Allow'. Save your changes.
-
-__Q: None of the Cordova APIs are working, why is that?__
-
-__A:__ You probably need to update your plugins.xml file in the root of your application.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/VERSION
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/VERSION b/lib/cordova-blackberry/VERSION
index 24ba9a3..38f8e88 100644
--- a/lib/cordova-blackberry/VERSION
+++ b/lib/cordova-blackberry/VERSION
@@ -1 +1 @@
-2.7.0
+dev
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/check_reqs
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/check_reqs b/lib/cordova-blackberry/bin/check_reqs
new file mode 100755
index 0000000..9a8e9ee
--- /dev/null
+++ b/lib/cordova-blackberry/bin/check_reqs
@@ -0,0 +1,28 @@
+#!/usr/bin/env node
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+var qnxHost = process.env.QNX_HOST;
+
+if (typeof qnxHost !== "undefined" && typeof process.env.QNX_TARGET !== "undefined" && process.env.PATH.indexOf(qnxHost) !== -1) {
+ process.exit(0);
+} else {
+ process.exit(-1);
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/check_reqs.bat
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/check_reqs.bat b/lib/cordova-blackberry/bin/check_reqs.bat
new file mode 100755
index 0000000..ed05fac
--- /dev/null
+++ b/lib/cordova-blackberry/bin/check_reqs.bat
@@ -0,0 +1,21 @@
+@ECHO OFF
+goto comment
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+:comment
+
+@node.exe %~dp0\check_reqs %*
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/create
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/create b/lib/cordova-blackberry/bin/create
index ca84dc8..87ce4c3 100755
--- a/lib/cordova-blackberry/bin/create
+++ b/lib/cordova-blackberry/bin/create
@@ -17,92 +17,9 @@
# under the License.
#
# create a cordova/blackberry project
-#
+#
# USAGE
# ./create [path package appname]
#
-set -e
-
-if [ -n "$1" ] && [ "$1" == "-h" ]
-then
- echo "Usage: $0 <path_to_new_project> <package_name> <project_name>"
- echo " <path_to_new_project>: Path to your new Cordova iOS project"
- echo " <package_name>: Package name, following reverse-domain style convention (ignored on BlackBerry platforms)"
- echo " <project_name>: Project name"
- echo 'After you have created your application, make sure to customize the project.properties file inside your app directory with your environment specifics!'
- exit 0;
-fi
-
-
-BUILD_PATH="$( cd "$( dirname "$0" )/.." && pwd )"
-VERSION=$(cat "$BUILD_PATH/VERSION")
-
-PROJECT_PATH="${1:-"./example"}"
-PACKAGE=${2:-"org.apache.cordova.example"}
-NAME=${3:-"cordovaExample"}
-
-# clobber any existing example
-if [ -d "$PROJECT_PATH" ]
-then
- echo "Project already exists! Delete and recreate"
- exit 1
-fi
-
-# cleanup after exit and/or on error
-function on_exit {
- echo "Cleaning up ..."
- [ -d "$BUILD_PATH/build" ] && rm -rf "$BUILD_PATH/build"
- echo "Remember to update the project.properties file inside your application directory!"
-}
-
-function on_error {
- echo "An error occured. Deleting project..."
- [ -d "$PROJECT_PATH" ] && rm -rf "$PROJECT_PATH"
-}
-
-function replace {
- local pattern=$1
- local filename=$2
- # Mac OS X requires -i argument
- if [[ "$OSTYPE" =~ "darwin" ]]
- then
- /usr/bin/sed -i '' -e $pattern "$filename"
- elif [[ "$OSTYPE" =~ "linux" ]]
- then
- /bin/sed -i -e $pattern "$filename"
- fi
-}
-
-# we do not want the script to silently fail
-trap on_error ERR
-trap on_exit EXIT
-
-ANT="$(which ant)"
-
-MANIFEST_PATH="$PROJECT_PATH/www/config.xml"
-
-# compile cordova.js and cordova.jar if in source, ignore if in distribution
-if [ ! -e "$BUILD_PATH/www/ext/cordova-$VERSION.jar" ] && [ -d "$BUILD_PATH/framework" ]
-then
- if [ ! -e "$BUILD_PATH"/bin/templates/project/lib/ant-contrib/ant-contrib-1.0b3.jar ]; then
- echo "Downloading ant-contrib"
- # Use curl to get the jar
- curl -OL http://central.maven.org/maven2/ant-contrib/ant-contrib/1.0b3/ant-contrib-1.0b3.jar &> /dev/null
- mkdir -p "$BUILD_PATH"/bin/templates/project/lib/ant-contrib
- mv ant-contrib-1.0b3.jar "$BUILD_PATH"/bin/templates/project/lib/ant-contrib
- fi
-
- echo "Creating BlackBerry project..."
- ("$ANT" create -Dproject.path="$PROJECT_PATH" -f "$BUILD_PATH/build.xml" &> /dev/null)
- # interpolate the activity and package into config.xml
- echo "Updating config.xml ..."
- replace "s/__NAME__/${NAME}/g" "$MANIFEST_PATH"
- replace "s/__PACKAGE__/${PACKAGE}/g" "$MANIFEST_PATH"
-else
- # copy project template if in distribution
- echo "Copying assets and resources ..."
- cp -r "$BUILD_PATH/sample/." "$PROJECT_PATH"
- echo "Updating config.xml ..."
- replace "s/cordovaExample/${NAME}/g" "$MANIFEST_PATH"
- replace "s/org.apache.cordova.example/${PACKAGE}/g" "$MANIFEST_PATH"
-fi
+#!/bin/sh
+node $( dirname "$0" )"/create.js" "$@"
[15/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/media/AudioPlayer.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/media/AudioPlayer.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/media/AudioPlayer.java
deleted file mode 100644
index 9958cf0..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/media/AudioPlayer.java
+++ /dev/null
@@ -1,654 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.media;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.file.FileConnection;
-import javax.microedition.media.Manager;
-import javax.microedition.media.MediaException;
-import javax.microedition.media.Player;
-import javax.microedition.media.PlayerListener;
-import javax.microedition.media.control.RecordControl;
-import javax.microedition.media.control.VolumeControl;
-import javax.microedition.media.protocol.DataSource;
-
-import net.rim.device.api.media.protocol.ByteArrayInputStreamDataSource;
-
-import org.apache.cordova.util.FileUtils;
-import org.apache.cordova.util.Logger;
-
-/**
- * This class implements the audio playback and recording capabilities used by
- * Cordova. It is called by the Media Cordova class. Only one file can be played
- * or recorded per class instance.
- *
- * Supports playing audio locally and remotely. Files located within the
- * application package must be prefixed with "local:///". If no URI prefix
- * (file, http, local) is found, file is assumed to be on device and "file:///"
- * prefix added.
- */
-public class AudioPlayer implements PlayerListener {
-
- private static final String LOG_TAG = "AudioPlayer: ";
-
- // Media states
- public static final int MEDIA_NONE = 0;
- public static final int MEDIA_STARTING = 1;
- public static final int MEDIA_RUNNING = 2;
- public static final int MEDIA_PAUSED = 3;
- public static final int MEDIA_STOPPED = 4;
-
- // Media message ids
- private static final int MEDIA_STATE = 1;
- private static final int MEDIA_DURATION = 2;
- private static final int MEDIA_POSITION = 3;
- private static final int MEDIA_ERROR = 9;
-
- // Media error codes
- private static final int MEDIA_ERR_NONE_ACTIVE = 0;
- private static final int MEDIA_ERR_ABORTED = 1;
- private static final int MEDIA_ERR_NETWORK = 2;
- private static final int MEDIA_ERR_DECODE = 3;
- private static final int MEDIA_ERR_NONE_SUPPORTED = 4;
-
- private final Media handler;
- private final String id;
- private int state = MEDIA_NONE; // State of recording or playback
- private String audioFile = null; // File name to play or record to
- private float duration = -1; // Duration of audio
-
- private Player recorder = null; // Audio recording object
- private RecordControl recorderControl = null;
- private ByteArrayOutputStream recorderOutput = null;
-
- private Player player = null; // Audio player object
- private boolean prepareOnly = false;
-
- private long prevPos = 0;
- private long adjustTime = 0;
- private long previousTime = 0;
-
- private long lastPlay = System.currentTimeMillis();
-
- private boolean buffering = false;
-
- /**
- * Constructor.
- *
- * @param handler
- * The audio handler object
- * @param id
- * The id of this audio player
- */
- public AudioPlayer(Media handler, String id) {
- this.handler = handler;
- this.id = id;
- }
-
- /**
- * Destroy stop audio playing or recording and free resources.
- */
- public synchronized void destroy() {
- // Stop any play or record
- destroyPlayer();
- if (recorder != null) {
- stopRecording();
- }
- }
-
- /**
- * Stop and free the player.
- */
- private void destroyPlayer() {
- if (player != null) {
- if (state == MEDIA_RUNNING || state == MEDIA_PAUSED) {
- stopPlaying();
- }
- player.removePlayerListener(this);
- player.close();
- player = null;
- }
- }
-
- /**
- * Get current position of playback.
- *
- * @return position as a floating point number indicating number of seconds
- * or -1 if not playing
- */
- public synchronized float getCurrentPosition() {
- // Current position is only valid when running, paused or buffering.
- if (state == MEDIA_RUNNING || state == MEDIA_PAUSED || buffering) {
- // The time returned by getMediaTime() is only updated every second.
- // Keep track of time between updates in order to provide
- // millisecond granularity.
- long curPos = player.getMediaTime();
-
- // Media time is within the 1 second granularity window so add time
- // since last update.
- if (curPos == prevPos && state == MEDIA_RUNNING) {
- if (previousTime == 0) {
- previousTime = System.currentTimeMillis();
- } else {
- long newTime = System.currentTimeMillis();
- // Convert from milliseconds to microseconds.
- adjustTime += ((newTime - previousTime) * 1000);
- previousTime = newTime;
- curPos += adjustTime;
- }
- } else {
- prevPos = curPos;
- previousTime = System.currentTimeMillis();
- adjustTime = 0;
- }
-
- // Convert from microseconds to floating point seconds.
- float time = curPos / 1000000.0f;
- sendStatus(MEDIA_POSITION, time);
- return time;
- } else {
- return -1;
- }
- }
-
- /**
- * Get the duration of the audio file.
- *
- * @param file
- * The name of the audio file.
- * @return duration as a floating point number indicating number of seconds
- * or -1 = can't be determined or -2 = not allowed
- */
- public synchronized float getDuration(String file) {
- // Can't get duration of recording
- if (recorder != null) {
- return (-2); // not allowed
- }
-
- // If audio file already loaded and started, then return duration
- if (player != null) {
- return duration;
- }
-
- // If no player yet, then create one
- else {
- prepareOnly = true;
- startPlaying(file);
- // This will only return value for local, since streaming
- // file hasn't been read yet.
- return duration;
- }
- }
-
- /**
- * Get the audio state.
- *
- * @return int
- */
- public synchronized int getState() {
- return state;
- }
-
- /**
- * Pause playing.
- */
- public synchronized void pausePlaying() {
- // If playing, then pause
- if (state == MEDIA_RUNNING) {
- try {
- player.stop();
- setState(MEDIA_PAUSED);
- } catch (MediaException e) {
- Logger.log(LOG_TAG + "pausePlaying() Error: " + e.getMessage());
- sendError(MEDIA_ERR_ABORTED);
- }
- } else {
- Logger.log(LOG_TAG
- + "pausePlaying() Error: called during invalid state: "
- + state);
- sendError(MEDIA_ERR_NONE_ACTIVE);
- }
- }
-
- /**
- * PlayerListener interface callback when an event occurs in the player.
- *
- * @see javax.microedition.media.PlayerListener#playerUpdate(javax.microedition.media.Player,
- * java.lang.String, java.lang.Object)
- */
- public void playerUpdate(Player player, String event, Object eventData) {
- if (BUFFERING_STARTED.equals(event)) {
- buffering = true;
- } else if (BUFFERING_STOPPED.equals(event)) {
- buffering = false;
- setState(MEDIA_RUNNING);
- } else if (DURATION_UPDATED.equals(event)) {
- if (eventData != null && eventData instanceof Long) {
- // Convert duration from microseconds to seconds.
- duration = ((Long) eventData).longValue() / 1000000.0f;
- sendStatus(MEDIA_DURATION, duration);
- }
- } else if (END_OF_MEDIA.equals(event)) {
- // Update the final position before stopping the player.
- if (eventData != null && eventData instanceof Long) {
- sendStatus(MEDIA_POSITION,
- ((Long) eventData).longValue() / 1000000.0f);
- }
- stopPlaying();
- } else if (ERROR.equals(event)) {
- // Send error notification to JavaScript
- if (eventData != null && eventData instanceof String) {
- try {
- int code = Integer.parseInt((String) eventData);
- sendError(code);
- } catch (NumberFormatException ne) {
- Logger.log(LOG_TAG + "playerUpdate(): Player id(" + id + ") received error: "
- + eventData);
- }
- } else {
- Logger.log(LOG_TAG + "playerUpdate(): Player id(" + id + ") received error: " + eventData);
- }
- destroy();
- }
- }
-
- /**
- * Seek or jump to a new time in the track.
- *
- * @throws MediaException
- */
- public synchronized void seekToPlaying(int milliseconds) {
- if (player != null) {
- try {
- // Convert milliseconds to microseconds.
- player.setMediaTime(milliseconds > 0 ? milliseconds * 1000
- : milliseconds);
- sendStatus(MEDIA_POSITION, milliseconds / 1000.0f);
- } catch (MediaException e) {
- Logger.log(LOG_TAG + "seekToPlaying() Error: " + e.getMessage());
- sendError(MEDIA_ERR_ABORTED);
- }
- }
- }
-
- /**
- * Set the volume for audio player
- *
- * @param volume
- * volume level 0.0-1.0
- */
- public synchronized void setVolume(float volume) {
- if (player != null) {
- if (player.getState() >= Player.REALIZED) {
- VolumeControl vc = (VolumeControl) player
- .getControl("VolumeControl");
- // Native volume level range is 0-100
- vc.setLevel((int) (volume * 100));
- }
- }
- }
-
- /**
- * Start or resume playing audio file.
- *
- * @param file
- * The name of the audio file.
- */
- public synchronized void startPlaying(String file) {
- try {
- if (recorder != null) {
- Logger.log(LOG_TAG
- + "startPlaying() Error: Can't play in record mode.");
- sendError(MEDIA_ERR_ABORTED);
- }
-
- // If this is a new request to play audio, or stopped
- else if (player == null || state == MEDIA_STOPPED) {
- setState(MEDIA_STARTING);
-
- if (file == null || file.length() == 0) {
- Logger.log(LOG_TAG
- + "startPlaying(): Input file not specified.");
- sendError(MEDIA_ERR_ABORTED);
- setState(MEDIA_NONE);
- destroy();
- return;
- }
-
- // If the player was previously used, need to check if it needs
- // recreated to pick up file changes. Cases when the player
- // needs recreated:
- // 1. New source file was specified.
- // 2. File is local and has been modified since last play.
- if (player != null) {
- if (!file.equals(audioFile)) {
- destroyPlayer();
- } else if (!isStreaming(file)) {
- // File needs to follow the local or file URI protocol
- // so if neither prefix exists assume a file URI and add
- // the "file:///" prefix.
- file = FileUtils.prefixFileURI(file);
- FileConnection fconn = null;
- try {
- fconn = (FileConnection) Connector.open(file,
- Connector.READ);
- if (fconn.exists()) {
- if (fconn.lastModified() > lastPlay) {
- destroyPlayer();
- }
- }
- } catch (Exception e) {
- // Ignore
- } finally {
- try {
- if (fconn != null) {
- fconn.close();
- }
- } catch (IOException ignored) {
- }
- }
- }
- }
-
- // At this point if player is not null then the file previously
- // played is still valid so just reset the current position.
- if (player != null) {
- player.setMediaTime(0);
- }
- // Otherwise, create a new one
- else {
- // If streaming file
- if (isStreaming(file)) {
- player = Manager.createPlayer(file);
- } else {
- // File needs to follow the local or file URI protocol
- // so if neither prefix exists assume a file URI and add
- // the "file:///" prefix.
- file = FileUtils.prefixFileURI(file);
-
- String contentType = "audio/mp3";
- if (file.endsWith(".amr")) {
- contentType = "audio/amr";
- } else if (file.endsWith(".wav")) {
- contentType = "audio/wav";
- }
-
- DataSource dataSource = new ByteArrayInputStreamDataSource(
- new ByteArrayInputStream(FileUtils.readFile(
- file, Connector.READ)), contentType);
- player = Manager.createPlayer(dataSource);
- }
- audioFile = file;
- player.addPlayerListener(this);
- }
-
- lastPlay = System.currentTimeMillis();
- player.realize();
- player.prefetch();
-
- // Get duration as floating point seconds.
- duration = player.getDuration() == Player.TIME_UNKNOWN ? Player.TIME_UNKNOWN
- : player.getDuration() / 1000000.0f;
-
- sendStatus(MEDIA_DURATION, duration);
-
- if (!prepareOnly) {
- player.start();
- }
- prepareOnly = false;
- }
-
- // If previously existing player is still valid.
- else {
- // If player has been paused, then resume playback
- if (state == MEDIA_PAUSED || state == MEDIA_STARTING) {
- player.start();
- setState(MEDIA_RUNNING);
- } else {
- Logger.log(LOG_TAG
- + "Error: startPlaying() called during invalid state: "
- + state);
- sendError(MEDIA_ERR_ABORTED);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- Logger.log(LOG_TAG + "startPlaying() Error: " + e.getMessage());
- sendError(MEDIA_ERR_ABORTED);
- }
- }
-
- /**
- * Start recording the specified file.
- *
- * @param file
- * The name of the file
- */
- public synchronized void startRecording(String file) {
- try {
- if (player != null) {
- Logger.log(LOG_TAG
- + "startRecording() Error: Can't record in play mode.");
- sendError(MEDIA_ERR_ABORTED);
- } else if (recorder == null) {
-
- if (file == null || file.length() == 0) {
- Logger.log(LOG_TAG
- + "startRecording() Error: Output file not specified.");
- sendError(MEDIA_ERR_ABORTED);
- return;
- }
- setState(MEDIA_STARTING);
- file = FileUtils.prefixFileURI(file);
-
- recorder = Manager.createPlayer("capture://audio");
- recorder.addPlayerListener(this);
- recorder.realize();
- recorderControl = (RecordControl) recorder
- .getControl("RecordControl");
- recorderOutput = new ByteArrayOutputStream();
- recorderControl.setRecordStream(recorderOutput);
- recorderControl.startRecord();
- recorder.start();
- audioFile = file;
- setState(MEDIA_RUNNING);
-
- } else {
- Logger.log(LOG_TAG
- + "startRecording() Error: Already recording.");
- sendError(MEDIA_ERR_ABORTED);
- }
- } catch (Exception e) {
- Logger.log(LOG_TAG
- + "startRecording() Error: Failed to start recording. "
- + e.getMessage());
- if (recorder != null) {
- recorder.removePlayerListener(this);
- recorder.close();
- recorder = null;
- }
- if (recorderControl != null) {
- try {
- recorderControl.reset();
- } catch (IOException e1) {
- // Ignore
- }
- recorderControl = null;
- }
- if (recorderOutput != null) {
- try {
- recorderOutput.close();
- } catch (IOException e1) {
- // Ignore
- }
- recorderOutput = null;
- }
-
- setState(MEDIA_NONE);
- }
- }
-
- /**
- * Stop playing the audio file.
- */
- public synchronized void stopPlaying() {
- if (state == MEDIA_RUNNING || state == MEDIA_PAUSED) {
- try {
- player.stop();
- player.setMediaTime(0);
- } catch (MediaException e) {
- Logger.log(LOG_TAG + "stopPlaying() Error: " + e.getMessage());
- sendError(MEDIA_ERR_ABORTED);
- }
- setState(MEDIA_STOPPED);
- } else {
- Logger.log(LOG_TAG + "stopPlaying() called during invalid state: "
- + state);
- sendError(MEDIA_ERR_NONE_ACTIVE);
- }
- }
-
- /**
- * Stop recording and save to the file specified when recording started.
- */
- public synchronized void stopRecording() {
- DataOutputStream output = null;
- FileConnection conn = null;
-
- try {
- if (recorder != null) {
- if (state == MEDIA_RUNNING) {
- recorderControl.commit();
- byte data[] = recorderOutput.toByteArray();
-
- conn = (FileConnection) Connector.open(audioFile,
- Connector.READ_WRITE);
- if (conn.exists()) {
- conn.delete();
- conn.close();
- conn = (FileConnection) Connector.open(audioFile,
- Connector.READ_WRITE);
- }
- conn.create();
- output = conn.openDataOutputStream();
- output.write(data);
- output.flush();
- }
- }
- } catch (IOException e) {
- // Ignore
- Logger.log(LOG_TAG + "stopRecording() Error: " + e.getMessage());
- } finally {
- if (recorderOutput != null) {
- try {
- recorderOutput.close();
- } catch (IOException e) {
- // Ignore
- Logger.log(LOG_TAG
- + "stopRecording() Failed to close recorder output. "
- + e.getMessage());
- }
- recorderOutput = null;
- }
- if (recorder != null) {
- recorder.removePlayerListener(this);
- recorder.close();
- recorder = null;
- }
-
- if (recorderControl != null) {
- recorderControl.stopRecord();
- recorderControl = null;
- }
-
- if (output != null) {
- try {
- output.close();
- } catch (IOException e) {
- // Ignore
- Logger.log(LOG_TAG
- + "stopRecording() Failed to close output file. "
- + e.getMessage());
- }
- output = null;
- }
-
- if (conn != null) {
- try {
- conn.close();
- } catch (IOException e) {
- // Ignore
- Logger.log(LOG_TAG
- + "stopRecording() Failed to close connection. "
- + e.getMessage());
- }
- }
- setState(MEDIA_STOPPED);
- }
- }
-
- /**
- * Determine if playback file is streaming or local. It is streaming if file
- * name starts with "http://"
- *
- * @param file
- * The file name
- * @return T=streaming, F=local
- */
- private boolean isStreaming(String file) {
- if (file.startsWith("http://") || file.startsWith("https://")) {
- return true;
- }
- return false;
- }
-
- private void sendError(int code) {
- handler.invokeScript("cordova.require('cordova/plugin/Media').onStatus('"
- + id + "', " + MEDIA_ERROR + ", { \"code\":" + code + "});");
- }
-
- private void sendStatus(int msg, float value) {
- handler.invokeScript("cordova.require('cordova/plugin/Media').onStatus('"
- + id + "', " + msg + ", " + value + ");");
- }
-
- private void sendStatus(int msg, int value) {
- handler.invokeScript("cordova.require('cordova/plugin/Media').onStatus('"
- + id + "', " + msg + ", " + value + ");");
- }
-
- /**
- * Set the state and send it to JavaScript.
- *
- * @param state
- */
- private synchronized void setState(int state) {
- // Only send state back to JavaScript if it has changed.
- if (this.state != state) {
- sendStatus(MEDIA_STATE, state);
- }
-
- this.state = state;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/media/Media.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/media/Media.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/media/Media.java
deleted file mode 100644
index f1e2b27..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/media/Media.java
+++ /dev/null
@@ -1,344 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.media;
-
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.util.Logger;
-
-/**
- * This plugin provides the ability to play and record audio. The file can be
- * local or over a network using http.
- *
- * Audio formats supported (tested): .mp3, .wav, .amr
- *
- * Supports playing audio locally and remotely. Files located within the
- * application package must be prefixed with "local:///". If no URI prefix
- * (file, http, local) is found, file is assumed to be on device and "file:///"
- * prefix added.
- */
-public class Media extends Plugin {
-
- private static final String LOG_TAG = "Media: ";
- private final Hashtable players = new Hashtable();
-
- // Cross-platform defined actions
- private static final String CREATE = "create";
- private static final String START_RECORDING = "startRecordingAudio";
- private static final String STOP_RECORDING = "stopRecordingAudio";
- private static final String START_PLAYING = "startPlayingAudio";
- private static final String STOP_PLAYING = "stopPlayingAudio";
- private static final String SEEK_TO = "seekToAudio";
- private static final String PAUSE_PLAYING = "pausePlayingAudio";
- private static final String SET_VOLUME = "setVolume";
- private static final String GET_POSITION = "getCurrentPositionAudio";
- private static final String GET_DURATION = "getDurationAudio";
- private static final String RELEASE = "release";
-
- /**
- * Executes the request and returns PluginResult.
- *
- * @param action
- * The action to execute.
- * @param args
- * JSONArry of arguments for the plugin.
- * @param callbackId
- * The callback id used when calling back into JavaScript.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult.Status status = PluginResult.Status.NO_RESULT;
-
- try {
- if (CREATE.equals(action)) {
- createMedia(args.getString(0), args.getString(1));
- return new PluginResult(PluginResult.Status.OK, "");
- } else if (START_RECORDING.equals(action)) {
- startRecordingAudio(args.getString(0), args.getString(1));
- } else if (STOP_RECORDING.equals(action)) {
- stopRecordingAudio(args.getString(0));
- } else if (START_PLAYING.equals(action)) {
- startPlayingAudio(args.getString(0), args.getString(1));
- } else if (SEEK_TO.equals(action)) {
- seekToAudio(args.getString(0), args.getInt(1));
- } else if (PAUSE_PLAYING.equals(action)) {
- pausePlayingAudio(args.getString(0));
- } else if (STOP_PLAYING.equals(action)) {
- stopPlayingAudio(args.getString(0));
- } else if (SET_VOLUME.equals(action)) {
- try {
- float level = Float.parseFloat(args.getString(1));
- setVolume(args.getString(0), level);
- } catch (NumberFormatException nfe) {
- Logger.log(LOG_TAG + "execute(): Failed to convert volume level: "
- + args.getString(1) + " " + nfe.getMessage());
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
- }
- } else if (GET_POSITION.equals(action)) {
- float f = getCurrentPositionAudio(args.getString(0));
- return new PluginResult(PluginResult.Status.OK, f);
- } else if (GET_DURATION.equals(action)) {
- float f = getDurationAudio(args.getString(0), args.getString(1));
- return new PluginResult(PluginResult.Status.OK, f);
- } else if (RELEASE.equals(action)) {
- boolean b = release(args.getString(0));
- return new PluginResult(PluginResult.Status.OK, b);
- } else {
- Logger.log(LOG_TAG + "execute(): Invalid action: " + action);
- return new PluginResult(PluginResult.Status.INVALID_ACTION,
- "Invalid action: " + action);
- }
- return new PluginResult(status, "");
- } catch (JSONException e) {
- Logger.log(LOG_TAG + "execute() Error: " + e.getMessage());
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
- }
- }
-
- /**
- * Identifies if action to be executed returns a value and should be run
- * synchronously.
- *
- * @param action
- * The action to execute
- * @return T=returns value
- */
- public boolean isSynch(String action) {
- if (CREATE.equals(action) || GET_POSITION.equals(action)
- || GET_DURATION.equals(action) || RELEASE.equals(action)) {
- return true;
- }
- return false;
- }
-
- /**
- * Stop all audio players and recorders.
- */
- public void onDestroy() {
- Enumeration keys = players.keys();
- while (keys.hasMoreElements()) {
- AudioPlayer audio = (AudioPlayer) players.get(keys.nextElement());
- if (audio != null) {
- audio.destroy();
- }
- }
-
- players.clear();
- }
-
- /**
- * Start or resume playing audio file.
- *
- * @param id
- * The id of the audio player
- * @param file
- * The name of the audio file.
- */
- private void createMedia(String id, String file) {
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio == null) {
- audio = new AudioPlayer(this, id);
- players.put(id, audio);
- }
- }
-
- /**
- * Get current position of playback.
- *
- * @param id
- * The id of the audio player
- * @return position in msec
- */
- private float getCurrentPositionAudio(String id) {
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio != null) {
- return (audio.getCurrentPosition());
- }
- return -1;
- }
-
- /**
- * Get the duration of the audio file.
- *
- * @param id
- * The id of the audio player
- * @param file
- * The name of the audio file.
- * @return The duration in msec.
- */
- private float getDurationAudio(String id, String file) {
- // Get audio file
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio != null) {
- return (audio.getDuration(file));
- }
-
- // If not already open, then open the file
- audio = new AudioPlayer(this, id);
- players.put(id, audio);
- return (audio.getDuration(file));
- }
-
- /**
- * Pause playing.
- *
- * @param id
- * The id of the audio player
- */
- private void pausePlayingAudio(String id) {
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio != null) {
- audio.pausePlaying();
- } else {
- Logger.log(LOG_TAG
- + "pausePlayingAudio() Error: Unknown Audio Player " + id);
- }
- }
-
- /**
- * Release the audio player instance to save memory.
- *
- * @param id
- * The id of the audio player
- */
- private boolean release(String id) {
- if (!players.containsKey(id)) {
- Logger.log(LOG_TAG + "release() Error: Unknown Audio Player " + id);
- return false;
- }
-
- AudioPlayer audio = (AudioPlayer) players.get(id);
- players.remove(id);
- audio.destroy();
- return true;
- }
-
- /**
- * Seek to a location.
- *
- * @param id
- * The id of the audio player
- * @param miliseconds
- * int: number of milliseconds to skip 1000 = 1 second
- */
- private void seekToAudio(String id, int milliseconds) {
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio != null) {
- audio.seekToPlaying(milliseconds);
- } else {
- Logger.log(LOG_TAG + "seekToAudio() Error: Unknown Audio Player "
- + id);
- }
- }
-
- /**
- * Set the volume for an audio device
- *
- * @param id
- * The id of the audio player
- * @param volume
- * Volume to adjust to 0 - 1
- */
- private void setVolume(String id, float volume) {
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio != null) {
- audio.setVolume(volume);
- } else {
- Logger.log(LOG_TAG + "setVolume() Error: Unknown Audio Player "
- + id);
- }
- }
-
- /**
- * Start or resume playing audio file.
- *
- * @param id
- * The id of the audio player
- * @param file
- * The name of the audio file.
- */
- private void startPlayingAudio(String id, String file) {
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio == null) {
- audio = new AudioPlayer(this, id);
- players.put(id, audio);
- }
- audio.startPlaying(file);
- }
-
- /**
- * Start recording and save the specified file.
- *
- * @param id
- * The id of the audio player
- * @param file
- * The name of the file
- */
- private void startRecordingAudio(String id, String file) {
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio == null) {
- audio = new AudioPlayer(this, id);
- players.put(id, audio);
- }
-
- int state = audio.getState();
- if (state == AudioPlayer.MEDIA_NONE
- || state == AudioPlayer.MEDIA_STOPPED) {
- audio.startRecording(file);
- }
- }
-
- /**
- * Stop playing the audio file.
- *
- * @param id
- * The id of the audio player
- */
- private void stopPlayingAudio(String id) {
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio != null) {
- audio.stopPlaying();
- } else {
- Logger.log(LOG_TAG
- + "stopPlayingAudio() Error: Unknown Audio Player " + id);
- }
- }
-
- /**
- * Stop recording and save to the file specified when recording started.
- *
- * @param id
- * The id of the audio player
- */
- private void stopRecordingAudio(String id) {
- AudioPlayer audio = (AudioPlayer) players.get(id);
- if (audio != null) {
- audio.stopRecording();
- players.remove(id);
- } else {
- Logger.log(LOG_TAG
- + "stopRecordingAudio() Error: Unknown Audio Player " + id);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/network/ConnectionInfoAction.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/network/ConnectionInfoAction.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/network/ConnectionInfoAction.java
deleted file mode 100644
index 2a280e6..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/network/ConnectionInfoAction.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.network;
-
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.system.Application;
-import net.rim.device.api.system.CoverageInfo;
-import net.rim.device.api.system.CoverageStatusListener;
-import net.rim.device.api.system.RadioInfo;
-import net.rim.device.api.system.RadioStatusListener;
-import net.rim.device.api.system.WLANConnectionListener;
-import net.rim.device.api.system.WLANInfo;
-
-/**
- * Determines the current network data connection type and listens for changes
- * to network coverage. This class is intended for use through the Network
- * plug-in.
- */
-public class ConnectionInfoAction {
- // Return types
- private static final String TYPE_UNKNOWN = "unknown";
- private static final String TYPE_ETHERNET = "ethernet";
- private static final String TYPE_WIFI = "wifi";
- private static final String TYPE_2G = "2g";
- private static final String TYPE_3G = "3g";
- private static final String TYPE_4G = "4g";
- private static final String TYPE_NONE = "none";
-
- // Network status event values
- private static final String OFFLINE = "offline";
- private static final String ONLINE = "online";
-
- // Network service support constants
- private static final int DATA = RadioInfo.NETWORK_SERVICE_DATA;
- private static final int TWO_G = RadioInfo.NETWORK_SERVICE_DATA
- | RadioInfo.NETWORK_SERVICE_EDGE;
- private static final int THREE_G = RadioInfo.NETWORK_SERVICE_EVDO_REV0
- | RadioInfo.NETWORK_SERVICE_EVDO_REV0_ONLY
- | RadioInfo.NETWORK_SERVICE_EVDO_REVA
- | RadioInfo.NETWORK_SERVICE_EVDO_REVA_ONLY
- | RadioInfo.NETWORK_SERVICE_UMTS;
-
- // Listeners used to detect network changes
- private RadioStatusListener radioListener = null;
- private WLANConnectionListener wlanListener = null;
- private CoverageStatusListener coverageListener = null;
-
- // Variable indicating whether the user has disabled mobile data
- private Boolean dataDisabled = Boolean.FALSE;
-
- // The set of call back IDs to send results to. Using Hashtable because
- // BlackBerry does not support Collections. There should only ever be one
- // call back ID, but this allows multiple.
- private Hashtable callbackIds = new Hashtable();
-
- private String prevType = TYPE_NONE;
- private String prevEvent = OFFLINE;
-
- /**
- * Determines the current network data connection type. Listeners are
- * registered to return additional results when network state changes.
- *
- * @param callbackId
- * The success call back ID to receive network type results.
- * @return A PluginResult object with the success or failure result of the
- * operation. A success result includes information about the
- * currently active network type.
- */
- protected PluginResult getConnectionInfo(String callbackId) {
-
- // Ensure that the dataDisabled variable is initialized.
- setDataDisabled(CoverageInfo.getCoverageStatus(), false);
-
- // Add the network change listeners if they have not been added.
- addListeners(callbackId);
-
- // Retrieve the current active connection type and build the return
- // result.
- PluginResult result = new PluginResult(PluginResult.Status.OK,
- getConnectionType(true, true));
-
- // Need to keep the call back since listeners have been registered to
- // fire events on the specified call back ID.
- result.setKeepCallback(true);
-
- return result;
- }
-
- /**
- * Removes all coverage listeners and clears the list of call back IDs. This
- * method should be invoked when the Network plug-in's onDestroy is called.
- */
- protected synchronized void shutdown() {
- if (radioListener != null) {
- Application.getApplication().removeRadioListener(radioListener);
- radioListener = null;
- }
-
- if (wlanListener != null) {
- WLANInfo.removeListener(wlanListener);
- wlanListener = null;
- }
-
- if (coverageListener != null) {
- CoverageInfo.removeListener(coverageListener);
- coverageListener = null;
- }
-
- callbackIds.clear();
- }
-
- /**
- * Adds a RadioStatusListener, WLANConnectionListener and
- * CoverageStatusListener to listen for various network change events. The
- * listeners are only registered if they have not already been added. Each
- * listener is used to detect different types of network change events.
- *
- * RadioStatusListener - Detects changes in cellular data coverage.
- * WLANConnectionListener - Detects changes in wifi coverage.
- * CoverageStatusListener - Used to detect changes in the mobile data config
- *
- * @param callbackId
- * The reference point to call back when a listener event occurs.
- */
- private synchronized void addListeners(String callbackId) {
- callbackIds.put(callbackId, callbackId);
-
- if (radioListener == null) {
- radioListener = new RadioStatusListener() {
- public void baseStationChange() {}
- public void networkScanComplete(boolean success) {}
-
- public void networkServiceChange(int networkId, int service) {
- // Cellular data change detected. If the user hasn't
- // disabled mobile data and wifi is not currently in use
- // return a result indicating the cellular data coverage
- // change.
- if (dataDisabled == Boolean.FALSE
- && WLANInfo.getWLANState() != WLANInfo.WLAN_STATE_CONNECTED) {
- if ((service & DATA) == 0) {
- sendResult(TYPE_NONE, OFFLINE);
- } else {
- // In the case where cell data and wifi was turned
- // off and then the user disabled mobile data
- // configuration, the mobile data config disablement
- // by the user isn't detected by the coverage status
- // listener so dataDisabled may not be accurate.
- // When service data is activated, have to make sure
- // that dataDisabled is properly set.
- setDataDisabled(CoverageInfo.getCoverageStatus(),
- false);
- if (dataDisabled == Boolean.FALSE) {
- sendResult(getConnectionType(false, true),
- ONLINE);
- }
- }
- }
- }
-
- public void networkStarted(int networkId, int service) {}
- public void networkStateChange(int state) {}
- public void pdpStateChange(int apn, int state, int cause) {}
- public void radioTurnedOff() {}
- public void signalLevel(int level) {}
- };
- Application.getApplication().addRadioListener(radioListener);
- }
-
- if (wlanListener == null) {
- wlanListener = new WLANConnectionListener() {
- public void networkConnected() {
- if (dataDisabled == Boolean.FALSE) {
- sendResult(TYPE_WIFI, ONLINE);
- }
- }
-
- public void networkDisconnected(int reason) {
- // Wifi was disconnected, if the user hasn't disabled mobile
- // data, check if cellular data coverage exists.
- if (dataDisabled == Boolean.FALSE) {
- String type = getConnectionType(false, true);
- String event = OFFLINE;
- if (!TYPE_NONE.equals(type)) {
- event = ONLINE;
- }
- sendResult(type, event);
- }
- }
- };
- WLANInfo.addListener(wlanListener);
- }
-
- if (coverageListener == null) {
- coverageListener = new CoverageStatusListener() {
- public void coverageStatusChanged(int newCoverage) {
- // When coverage changes, check to determine if it is due
- // to the user disabling mobile data through configuration
- // flag.
- setDataDisabled(newCoverage, true);
- }
- };
- CoverageInfo.addListener(coverageListener);
- }
- }
-
- /**
- * Determine the type of connection currently being used for data
- * transmission on the device. If the user has disabled mobile data then
- * TYPE_NONE is returned regardless of cellular or wifi radio state as this
- * is the way the browser behaves. Otherwise, wifi and/or cellular radios
- * are queried for state based on the passed in parameters.
- *
- * @param checkWLAN
- * Determines whether wifi radio state is queried or not.
- * @param checkCell
- * Determines whether cellular radio state is queried or not.
- * @return A string indicating one of the defined network connections types.
- */
- private String getConnectionType(boolean checkWLAN, boolean checkCell) {
- String networkType = TYPE_NONE;
-
- if (dataDisabled == Boolean.FALSE) {
- // Detect if wifi is active and connected. If wifi is active it
- // takes precedence over cellular data transmission.
- if (checkWLAN
- && WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
- networkType = TYPE_WIFI;
- }
-
- if (checkCell && TYPE_NONE.equals(networkType)
- && RadioInfo.isDataServiceOperational()) {
-
- int activeServices = RadioInfo.getNetworkService();
- networkType = TYPE_UNKNOWN;
- if ((activeServices & THREE_G) != 0) {
- networkType = TYPE_3G;
- } else if ((activeServices & TWO_G) != 0) {
- networkType = TYPE_2G;
- }
- }
- }
-
- return networkType;
- }
-
- /**
- * Helper function to build and send the PluginResult to the saved call back
- * IDs.
- *
- * @param type
- * The network connection type. This value should be null if the
- * specified event is "offline".
- * @param event
- * The network event.
- */
- private void sendResult(String type, String event) {
-
- // Only send the event if it is different then the last sent event.
- synchronized (prevType) {
- if (prevType != null && prevEvent != null && prevType.equals(type)
- && prevEvent.equals(event)) {
- return;
- } else {
- prevType = type;
- prevEvent = event;
- }
- }
-
- PluginResult result = new PluginResult(PluginResult.Status.OK,
- type);
-
- // Must keep the call back active for future events.
- result.setKeepCallback(true);
-
- // Iterate through the saved call back IDs. Really should only ever be
- // one.
- for (Enumeration callbacks = this.callbackIds.elements(); callbacks
- .hasMoreElements();) {
- String callbackId = (String) callbacks.nextElement();
- CordovaExtension.invokeSuccessCallback(callbackId, result);
- }
-
- }
-
- /**
- * Determines if the user has disabled mobile data through the user level
- * configuration panels and optionally returns an "online" or "offline"
- * result.
- *
- * @param newCoverage
- * A bit mask of CoverageInfo.COVERAGE_* flags indicating the
- * current coverage.
- * @param returnResult
- * If true, return a result based on the value of the mobile data
- * configuration.
- */
- private void setDataDisabled(int newCoverage, boolean returnResult) {
-
- boolean isRadioData = (RadioInfo.getNetworkService() & DATA) != 0;
- boolean wlanConnected = WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED;
- boolean eventDetected = false;
- String event = OFFLINE;
-
- // Note: To detect that mobile data has been disabled through
- // configuration, determine if the current coverage is
- // CoverageInfo.COVERAGE_NONE AND that either cellular or wifi radios
- // are currently connected. This is because the low level radio routines
- // will return a connected state even when mobile data is disabled
- // through configuration.
- synchronized (dataDisabled) {
- if (newCoverage == CoverageInfo.COVERAGE_NONE
- && (isRadioData || wlanConnected)) {
- if (dataDisabled == Boolean.FALSE) {
- Logger.log("Mobile data was disabled by the user through configuration.");
- dataDisabled = Boolean.TRUE;
- eventDetected = true;
- }
- } else if (dataDisabled == Boolean.TRUE) {
- Logger.log("Mobile data was enabled by the user.");
- dataDisabled = Boolean.FALSE;
- event = ONLINE;
- eventDetected = true;
- }
- }
-
- if (returnResult && eventDetected) {
- // The user has enabled/disabled mobile data. Return a result
- // indicating the current network state.
- String type = getConnectionType(true, true);
- sendResult(type, event);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/network/Network.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/network/Network.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/network/Network.java
deleted file mode 100644
index 86e5ac6..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/network/Network.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.network;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-
-/**
- * The Network command interface.
- *
- * The Network class can invoke the following actions:
- *
- * - getConnectionInfo(callback)
- *
- */
-public class Network extends Plugin {
- // Supported actions
- public static final String ACTION_CONNECTION_INFO = "getConnectionInfo";
-
- private ConnectionInfoAction connectionInfo = new ConnectionInfoAction();
-
- /**
- * Executes the request and returns CommandResult.
- *
- * @param action The command to execute.
- * @param callbackId The callback ID to be invoked upon action completion
- * @param args JSONArry of arguments for the command.
- * @return A CommandResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult result = null;
-
- if (action.equals(ACTION_CONNECTION_INFO)) {
- result = connectionInfo.getConnectionInfo(callbackId);
- }
- else {
- result = new PluginResult(PluginResult.Status.INVALID_ACTION, "Network: Invalid action: " + action);
- }
-
- return result;
- }
-
- /**
- * Called when Plugin is destroyed.
- */
- public void onDestroy() {
- connectionInfo.shutdown();
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ActivityDialog.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ActivityDialog.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ActivityDialog.java
deleted file mode 100644
index 710f61e..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ActivityDialog.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.notification;
-
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.ui.SpacerField;
-
-import net.rim.device.api.system.Bitmap;
-import net.rim.device.api.system.Characters;
-import net.rim.device.api.ui.UiApplication;
-import net.rim.device.api.ui.component.BitmapField;
-import net.rim.device.api.ui.component.LabelField;
-import net.rim.device.api.ui.component.SeparatorField;
-import net.rim.device.api.ui.container.HorizontalFieldManager;
-import net.rim.device.api.ui.container.PopupScreen;
-import net.rim.device.api.ui.container.VerticalFieldManager;
-
-/**
- * A Popup activity dialog box with an optional title and message.
- */
-public final class ActivityDialog extends PopupScreen {
- private static ActivityDialog dialog = null;
-
- /**
- * Construct an activity dialog, with customizable title and message.
- *
- * @param title
- * Title of the activity dialog
- * @param message
- * Message to print in the body of the dialog
- */
- private ActivityDialog(String title, String message) {
- super(new VerticalFieldManager());
-
- if (title != null && title.length() > 0) {
- add(new LabelField(title));
- add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
- }
- add(new SpacerField(0, 20));
-
- HorizontalFieldManager hfm = new HorizontalFieldManager();
-
- Bitmap hourglass = Bitmap.getPredefinedBitmap(Bitmap.HOURGLASS);
-
- BitmapField bitmap = new BitmapField(hourglass);
- hfm.add(bitmap);
-
- if (message != null && message.length() > 0) {
- hfm.add(new LabelField(message, FIELD_HCENTER | FIELD_VCENTER));
- }
-
- add(hfm);
- add(new SpacerField(0, 20));
- }
-
- /**
- * Creates and displays the activity dialog.
- *
- * @param args
- * JSONArray of arguments.
- * @return a PluginResult indicating success or error.
- */
- static synchronized PluginResult start(JSONArray args) {
- if (dialog == null) {
- String message = null;
- String title = null;
-
- // Title and message are optional, grab the strings from the args
- // if they are there.
- if (args != null && args.length() > 0) {
- try {
- if (!args.isNull(0)) {
- title = args.getString(0);
- }
- if (args.length() > 1 && !args.isNull(1)) {
- message = args.getString(1);
- }
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "JSONException: " + e.getMessage());
- }
- }
-
- dialog = new ActivityDialog(title, message);
- final UiApplication uiApp = UiApplication.getUiApplication();
- uiApp.invokeLater(new Runnable() {
- public void run() {
- uiApp.pushModalScreen(dialog);
- }
- });
- }
-
- return new PluginResult(PluginResult.Status.OK, "");
- }
-
- /**
- * Closes the activity dialog.
- *
- * @return a PluginResult indicating success or error.
- */
- static synchronized PluginResult stop() {
- if (dialog != null) {
- final UiApplication uiApp = UiApplication.getUiApplication();
- final ActivityDialog tmpDialog = dialog;
- uiApp.invokeLater(new Runnable() {
- public void run() {
- uiApp.popScreen(tmpDialog);
- }
- });
- dialog = null;
- }
-
- return new PluginResult(PluginResult.Status.OK, "");
- }
-
- /**
- * @see net.rim.device.api.ui.Screen#keyChar(char, int, int)
- */
- protected boolean keyChar(char key, int status, int time) {
- // If the user clicks back key while progress dialog is displayed, close
- // the progress dialog.
- if (key == Characters.ESCAPE) {
- stop();
- }
-
- return super.keyChar(key, status, time);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/AlertAction.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/AlertAction.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/AlertAction.java
deleted file mode 100644
index c04a3cb..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/AlertAction.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.notification;
-
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-
-import net.rim.device.api.ui.UiApplication;
-
-/**
- * Alert Action
- *
- * Displays and interacts with a dialog box.
- *
- */
-public class AlertAction {
-
- private static final String DEFAULT_MESSAGE = "";
- private static final String DEFAULT_TITLE = "Alert";
- private static final String DEFAULT_BUTTON = "OK";
-
- /**
- * Displays a custom alert.
- *
- * @param args JSONArray formatted as [ message, title, buttonLabel ]
- * message: the message to display in the dialog body (default: "").
- * title: the title to display at the top of the dialog (default: "Alert").
- * buttonLabel: the button text (default: "OK").
- * @return A PluginResult object with the success or failure state for displaying the dialog box.
- */
- public static PluginResult execute(JSONArray args) {
-
- PluginResult result = null;
-
- try {
- String message = DEFAULT_MESSAGE;
- String title = DEFAULT_TITLE;
- String buttonLabel = DEFAULT_BUTTON;
- if (args.length() > 0 && !args.isNull(0))
- message = args.getString(0);
- if (args.length() > 1 && !args.isNull(1))
- title = args.getString(1);
- if (args.length() > 2 && !args.isNull(2))
- buttonLabel = args.getString(2);
-
- // construct the dialog
- final AlertDialog dialog = new AlertDialog(message, title, buttonLabel);
-
- // ask the event dispatch thread to show dialog
- Runnable runnable = new Runnable() {
- public void run() {
- UiApplication ui = UiApplication.getUiApplication();
- ui.pushModalScreen(dialog);
- }
- };
- UiApplication.getUiApplication().invokeAndWait(runnable);
-
- result = new PluginResult(PluginResult.Status.OK);
- }
- catch (JSONException e) {
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSONException: " + e.getMessage());
- }
-
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/AlertDialog.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/AlertDialog.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/AlertDialog.java
deleted file mode 100644
index a32666b..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/AlertDialog.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.notification;
-
-import org.apache.cordova.ui.SpacerField;
-
-import net.rim.device.api.ui.Field;
-import net.rim.device.api.ui.FieldChangeListener;
-import net.rim.device.api.ui.component.ButtonField;
-import net.rim.device.api.ui.component.LabelField;
-import net.rim.device.api.ui.component.SeparatorField;
-import net.rim.device.api.ui.container.PopupScreen;
-import net.rim.device.api.ui.container.VerticalFieldManager;
-
-public final class AlertDialog extends PopupScreen implements FieldChangeListener {
-
- private ButtonField button;
-
- /**
- * Open a custom alert dialog, with a customizable title and button text.
- *
- * @param {String} message Message to print in the body of the alert
- * @param {String} title Title of the alert dialog (default: 'Alert')
- * @param {String} buttonLabel Label of the close button (default: 'OK')
- */
- public AlertDialog(String message, String title, String buttonLabel) {
-
- super(new VerticalFieldManager());
-
- // title
- add(new LabelField(title));
-
- // separator
- add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
-
- // message
- add(new SpacerField(0, 20));
- add(new LabelField(message, FIELD_HCENTER | FIELD_VCENTER));
- add(new SpacerField(0, 20));
-
- // button
- button = new ButtonField(buttonLabel, ButtonField.CONSUME_CLICK | FIELD_HCENTER);
- button.setChangeListener(this);
- add(button);
- }
-
- public void fieldChanged(Field field, int context) {
- if (button == field) {
- close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/BeepAction.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/BeepAction.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/BeepAction.java
deleted file mode 100644
index b1c3658..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/BeepAction.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.notification;
-
-import java.io.IOException;
-
-import javax.microedition.media.Control;
-import javax.microedition.media.Manager;
-import javax.microedition.media.MediaException;
-import javax.microedition.media.Player;
-import javax.microedition.media.control.ToneControl;
-import javax.microedition.media.control.VolumeControl;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.media.control.AudioPathControl;
-import net.rim.device.api.notification.NotificationsManager;
-import net.rim.device.api.system.Alert;
-
-/**
- * Beep Action plays a device tone.
- */
-public class BeepAction {
-
- private static final int BEEP_VOLUME = 100;
- private static final byte NOTE = 76; // E5
- private static final byte D = 16; // quarter note
- private static final byte tempo = 30; // 120 bpm
-
- private static final byte[] TONE_SEQUENCE_START = {
- ToneControl.VERSION, 1,
- ToneControl.TEMPO, tempo
- };
-
- private static final byte[] TONE = {
- NOTE,D, ToneControl.SILENCE,D/2
- };
-
- /**
- * Beeps the device for a given number of times. By default, it will beep
- * once. If the user explicitly sets the beep count to zero, it will play
- * the applications notification profile. The application profile playback
- * sequence is controlled by the user.
- *
- * @param args JSONArray formatted as [ count ]
- * count: specifies the number of times to beep the device (default: 1).
- * @return A CommandResult object with the success or failure
- * state for beeping the device.
- */
- public static PluginResult execute(JSONArray args) {
- PluginResult result = null;
-
- if (Alert.isAudioSupported()) {
-
- try {
- int repeatCount = 1;
- if (args.length() > 0 && !args.isNull(0)) {
- repeatCount = args.getInt(0);
- }
-
- // play tone n times
- if (repeatCount > 0) {
- playTone(repeatCount);
- }
- // FIXME: unsupported on other platforms
- // send notification event to application profile
- else {
- NotificationsManager.triggerImmediateEvent(
- CordovaExtension.getAppID(), 0, null, null);
- }
- }
- catch (JSONException e) {
- Logger.log(BeepAction.class.getName() + ": " + e);
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
- }
- catch (Exception e) {
- Logger.log(BeepAction.class.getName() + ": " + e);
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION, e.getMessage());
- }
-
- result = new PluginResult(PluginResult.Status.OK);
- }
- else {
- result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION, "Audio not supported");
- }
-
- return result;
- }
-
- /**
- * Plays a tone the specified number of times on the device audio system.
- * @param repeatCount number of times to play tone
- */
- private static void playTone(int repeatCount) throws MediaException, IOException {
-
- // get tone player
- Player p = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR);
- p.realize();
-
- // set tone sequence
- ToneControl tc = (ToneControl)p.getControl("ToneControl");
- tc.setSequence(getToneSequence(repeatCount));
-
- // crank up the volume
- VolumeControl vc = (VolumeControl)p.getControl("VolumeControl");
- vc.setLevel(BEEP_VOLUME);
-
- // route audio to speaker phone
- p.prefetch();
- Control[] c = p.getControls();
- for(int i=c.length-1; i>=0; --i) {
- if(c[i] instanceof AudioPathControl) {
- AudioPathControl apc = (AudioPathControl)c[i];
- apc.setAudioPath(AudioPathControl.AUDIO_PATH_HANDSFREE);
- break;
- }
- }
-
- // play
- p.start();
- }
-
- /**
- * Creates a tone sequence to play.
- * @param repeatCount number of times to play tone
- * @return tone sequence
- */
- private static byte[] getToneSequence(int repeatCount) {
- // we have to build the sequence dynamically because
- // ToneControl.REPEAT, repeatCount, TONE, DURATION
- // doesn't seem to work
- byte[] sequence = new byte[TONE_SEQUENCE_START.length + TONE.length * repeatCount];
- System.arraycopy(TONE_SEQUENCE_START, 0, sequence, 0, TONE_SEQUENCE_START.length);
- for (int i = 0; i < repeatCount; i++) {
- System.arraycopy(TONE, 0, sequence, (TONE_SEQUENCE_START.length+TONE.length*i), TONE.length);
- }
-
- return sequence;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ConfirmAction.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ConfirmAction.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ConfirmAction.java
deleted file mode 100644
index 881ca0e..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ConfirmAction.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.notification;
-
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.ui.UiApplication;
-
-/**
- * Displays a confirmation dialog with customizable title, message, and button
- * fields.
- */
-public class ConfirmAction {
-
- private static final String DEFAULT_MESSAGE = "";
- private static final String DEFAULT_TITLE = "Confirm";
- private static final String DEFAULT_BUTTONS = "OK,Cancel";
-
- /**
- * Displays a custom confirmation dialog.
- *
- * @param args JSONArray formatted as [ message, title, buttonLabels ]
- * message: the message to display in the dialog body (default: "").
- * title: the title to display at the top of the dialog (default: "Confirm").
- * buttonLabel: the button text (default: "OK,Cancel").
- * @return A PluginResult object with index of dialog button pressed (1,2,3...).
- */
- public static PluginResult execute(JSONArray args) {
-
- PluginResult result = null;
-
- try {
- String message = DEFAULT_MESSAGE;
- String title = DEFAULT_TITLE;
- String buttonLabels = DEFAULT_BUTTONS;
- if (args.length() > 0 && !args.isNull(0))
- message = args.getString(0);
- if (args.length() > 1 && !args.isNull(1))
- title = args.getString(1);
- if (args.length() > 2 && !args.isNull(2))
- buttonLabels = args.getString(2);
-
- // construct the dialog
- final ConfirmDialog dialog = new ConfirmDialog(message, title, buttonLabels);
-
- // ask the event dispatch thread to show it
- Runnable runnable = new Runnable() {
- public void run() {
- UiApplication ui = UiApplication.getUiApplication();
- ui.pushModalScreen(dialog);
- }
- };
- Logger.log(ConfirmAction.class.getName() + ": showing confirm dialog: '" + title + "'");
- UiApplication.getUiApplication().invokeAndWait(runnable);
-
- // add +1 to the button index to match the JavaScript API (which starts at 1)
- int button = dialog.getSelectedValue() + 1;
- result = new PluginResult(PluginResult.Status.OK, Integer.toString(button));
- }
- catch (JSONException e) {
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSONException: " + e.getMessage());
- }
-
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ConfirmDialog.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ConfirmDialog.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ConfirmDialog.java
deleted file mode 100644
index d19003c..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ConfirmDialog.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.notification;
-
-import org.apache.cordova.ui.SpacerField;
-import org.apache.cordova.util.StringUtils;
-
-import net.rim.device.api.ui.Field;
-import net.rim.device.api.ui.FieldChangeListener;
-import net.rim.device.api.ui.component.ButtonField;
-import net.rim.device.api.ui.component.LabelField;
-import net.rim.device.api.ui.component.SeparatorField;
-import net.rim.device.api.ui.container.PopupScreen;
-import net.rim.device.api.ui.container.VerticalFieldManager;
-
-/**
- * Creates a dialog box in which the title, message, and button labels are all
- * customizable.
- */
-public final class ConfirmDialog extends PopupScreen implements FieldChangeListener {
-
- private ButtonField[] buttons; // the button fields
- private int selectedValue = -1; // the selected button
-
- /**
- * Construct a confirmation dialog, with customizable title and button text.
- *
- * @param {String} message Message to print in the body of the alert
- * @param {String} title Title of the alert dialog (default: 'Confirm')
- * @param {String} buttonLabels Labels of the buttons (default: 'OK,Cancel')
- */
- public ConfirmDialog(String message, String title, String buttonLabels) {
- super(new VerticalFieldManager());
-
- // title
- add(new LabelField(title));
-
- // separator
- add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
-
- // message
- add(new SpacerField(0, 20));
- add(new LabelField(message, FIELD_HCENTER | FIELD_VCENTER));
- add(new SpacerField(0, 20));
-
- // parse the button labels
- String[] labels = StringUtils.split(buttonLabels, ",");
- buttons = new ButtonField[labels.length];
-
- // add buttons
- for (int i = 0; i < labels.length; i++) {
- buttons[i] = new ButtonField(labels[i], ButtonField.CONSUME_CLICK | FIELD_HCENTER);
- buttons[i].setChangeListener(this);
- add(new SpacerField(0, 5));
- add(buttons[i]);
- }
- }
-
- /**
- * Returns the index of the button pressed.
- *
- * @return The index of the button pressed (0,1,2...).
- */
- public int getSelectedValue() {
- return this.selectedValue;
- }
-
- /**
- * Invoked when a button is pressed.
- */
- public void fieldChanged(Field field, int context) {
-
- // figure out which button was pressed
- for (int i = 0; i < buttons.length; i++) {
- if (buttons[i] == field) {
- this.selectedValue = i;
- break;
- }
- }
-
- // close the dialog
- close();
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/Notification.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/Notification.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/Notification.java
deleted file mode 100644
index 4183987..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/Notification.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.notification;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-
-import net.rim.device.api.notification.NotificationsConstants;
-import net.rim.device.api.notification.NotificationsManager;
-
-/**
- * Cordova Notification plugin.
- *
- * The Notification plugin can invoke the following actions:
- *
- * - alert(message, title, buttonLabel)
- * - confirm(message, title, button1,button2,button3...)
- * - beep(count)
- * - vibrate(duration)
- * - progressStart(title, message)
- * - progressStop()
- * - progressValue(value)
- * - activityStart(title, message)
- * - activityStop()
- */
-public class Notification extends Plugin {
-
- /**
- * Possible actions
- */
- private static final String ACTION_ALERT = "alert";
- private static final String ACTION_BEEP = "beep";
- private static final String ACTION_CONFIRM = "confirm";
- private static final String ACTION_VIBRATE = "vibrate";
- private static final String ACTION_PROGRESS_START = "progressStart";
- private static final String ACTION_PROGRESS_STOP = "progressStop";
- private static final String ACTION_PROGRESS_VALUE = "progressValue";
- private static final String ACTION_ACTIVITY_START = "activityStart";
- private static final String ACTION_ACTIVITY_STOP = "activityStop";
-
- /**
- * Creates a notification profile for the application on the device. The
- * application can trigger a notification event that will play the profile.
- * The profile settings are set by the user.
- */
- public static void registerProfile() {
- // Register with the NotificationsManager to create a notification
- // profile for this application and enable notifications to be
- // controlled by the user
- Object object = new Object() {
- private String appName = CordovaExtension.getAppName();
-
- public String toString() {
- return appName;
- }
- };
- NotificationsManager.registerSource(CordovaExtension.getAppID(),
- object, NotificationsConstants.IMPORTANT);
- }
-
- /**
- * Executes the request and returns CommandResult.
- *
- * @param action
- * The action to perform.
- * @param callbackId
- * The callback ID to be invoked upon action completion
- * @param args
- * JSONArry of arguments for the specified action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult result = null;
-
- if (ACTION_ALERT.equals(action)) {
- result = AlertAction.execute(args);
- } else if (ACTION_BEEP.equals(action)) {
- result = BeepAction.execute(args);
- } else if (ACTION_CONFIRM.equals(action)) {
- result = ConfirmAction.execute(args);
- } else if (ACTION_VIBRATE.equals(action)) {
- result = VibrateAction.execute(args);
- } else if (ACTION_ACTIVITY_START.equals(action)) {
- result = ActivityDialog.start(args);
- } else if (ACTION_ACTIVITY_STOP.equals(action)) {
- result = ActivityDialog.stop();
- } else if (ACTION_PROGRESS_START.equals(action)) {
- result = ProgressDialog.start(args);
- } else if (ACTION_PROGRESS_STOP.equals(action)) {
- result = ProgressDialog.stop();
- } else if (ACTION_PROGRESS_VALUE.equals(action)) {
- result = ProgressDialog.setValue(args);
- } else {
- result = new PluginResult(PluginResult.Status.INVALID_ACTION,
- "Notification: Invalid action: " + action);
- }
-
- return result;
- }
-
- /**
- * Identifies if action to be executed returns a value and should be run
- * synchronously.
- *
- * @param action
- * The action to execute
- * @return T=returns value
- */
- public boolean isSynch(String action) {
- if (ACTION_ALERT.equals(action) || ACTION_CONFIRM.equals(action)) {
- return false;
- }
-
- return true;
- }
-
-}
[21/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/ImageCaptureOperation.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/ImageCaptureOperation.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/ImageCaptureOperation.java
deleted file mode 100644
index a831dc2..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/ImageCaptureOperation.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import java.io.IOException;
-import java.util.Date;
-import javax.microedition.io.Connector;
-import javax.microedition.io.file.FileConnection;
-
-import org.apache.cordova.file.File;
-import org.apache.cordova.util.FileUtils;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.io.MIMETypeAssociations;
-import net.rim.device.api.ui.UiApplication;
-
-public class ImageCaptureOperation extends CaptureOperation {
- // content type
- public static String CONTENT_TYPE = "image/";
-
- // file system listener
- private ImageCaptureListener listener = null;
-
- /**
- * Creates and starts an image capture operation.
- *
- * @param limit
- * maximum number of media files to capture
- * @param callbackId
- * the callback to receive the files
- * @param queue
- * the queue from which to retrieve captured media files
- */
- public ImageCaptureOperation(long limit, String callbackId, MediaQueue queue) {
- super(limit, callbackId, queue);
-
- // listener to capture image files added to file system
- this.listener = new ImageCaptureListener(queue);
-
- start();
- }
-
- /**
- * Registers file system listener and launches native camera application.
- */
- protected void setup() {
- // register listener for files being written
- synchronized(UiApplication.getEventLock()) {
- UiApplication.getUiApplication().addFileSystemJournalListener(listener);
- }
-
- // launch the native camera application
- CameraControl.launchCamera();
- }
-
- /**
- * Unregisters file system listener and closes native camera application.
- */
- protected void teardown() {
- // remove file system listener
- synchronized(UiApplication.getEventLock()) {
- UiApplication.getUiApplication().removeFileSystemJournalListener(listener);
- }
-
- // close the native camera application
- CameraControl.closeCamera();
- }
-
- /**
- * Waits for image file to be written to file system and retrieves its file
- * properties.
- *
- * @param filePath
- * the full path of the media file
- */
- protected void processFile(final String filePath) {
- Logger.log(this.getClass().getName() + ": processing file: " + filePath);
-
- // wait for file to finish writing and add it to captured files
- addCaptureFile(getMediaFile(filePath));
- }
-
- /**
- * Waits for file to be fully written to the file system before retrieving
- * its file properties.
- *
- * @param filePath
- * Full path of the image file
- * @throws IOException
- */
- private File getMediaFile(String filePath) {
- File file = new File(FileUtils.stripSeparator(filePath));
-
- // time begin waiting for file write
- long start = (new Date()).getTime();
-
- // wait for the file to be fully written, then grab its properties
- FileConnection fconn = null;
- try {
- fconn = (FileConnection) Connector.open(filePath, Connector.READ);
- if (fconn.exists()) {
- // wait for file to be fully written
- long fileSize = fconn.fileSize();
- long size = 0;
- Thread thisThread = Thread.currentThread();
- while (myThread == thisThread) {
- try {
- Thread.sleep(100);
- }
- catch (InterruptedException e) {
- break;
- }
- size = fconn.fileSize();
- if (size == fileSize) {
- break;
- }
- fileSize = size;
- }
- Logger.log(this.getClass().getName() + ": " + filePath + " size="
- + Long.toString(fileSize) + " bytes");
-
- // retrieve file properties
- file.setLastModifiedDate(fconn.lastModified());
- file.setName(FileUtils.stripSeparator(fconn.getName()));
- file.setSize(fileSize);
- file.setType(MIMETypeAssociations.getMIMEType(filePath));
- }
- }
- catch (IOException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- } catch (IOException ignored) {}
- }
-
- // log time it took to write the file
- long end = (new Date()).getTime();
- Logger.log(this.getClass().getName() + ": wait time="
- + Long.toString(end - start) + " ms");
-
- return file;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/MediaCapture.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/MediaCapture.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/MediaCapture.java
deleted file mode 100644
index 76b0eac..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/MediaCapture.java
+++ /dev/null
@@ -1,502 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Vector;
-
-import javax.microedition.media.Manager;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.file.File;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.util.Logger;
-import org.apache.cordova.util.StringUtils;
-
-/**
- * This plugin provides the ability to capture media from the native media
- * applications. The appropriate media application is launched, and a capture
- * operation is started in the background to identify captured media files and
- * return the file info back to the caller.
- */
-public class MediaCapture extends Plugin {
-
- public static String PROTOCOL_CAPTURE = "capture";
-
- private static final String LOG_TAG = "MediaCapture: ";
-
- /**
- * Error codes.
- */
- // Camera or microphone failed to capture image or sound.
- private static final int CAPTURE_INTERNAL_ERR = 0;
- // Camera application or audio capture application is currently serving other capture request.
- private static final int CAPTURE_APPLICATION_BUSY = 1;
- // Invalid use of the API (e.g. limit parameter has value less than one).
- private static final int CAPTURE_INVALID_ARGUMENT = 2;
- // User exited camera application or audio capture application before capturing anything.
- private static final int CAPTURE_NO_MEDIA_FILES = 3;
- // The requested capture operation is not supported.
- private static final int CAPTURE_NOT_SUPPORTED = 20;
-
- /**
- * Possible actions.
- */
- protected static final String ACTION_GET_SUPPORTED_MODES = "captureModes";
- protected static final String ACTION_CAPTURE_AUDIO = "captureAudio";
- protected static final String ACTION_CAPTURE_IMAGE = "captureImage";
- protected static final String ACTION_CAPTURE_VIDEO = "captureVideo";
- protected static final String ACTION_CANCEL_CAPTURES = "stopCaptures";
-
- /**
- * Executes the requested action and returns a PluginResult.
- *
- * @param action
- * The action to execute.
- * @param callbackId
- * The callback ID to be invoked upon action completion
- * @param args
- * JSONArry of arguments for the action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult result = null;
-
- if (ACTION_GET_SUPPORTED_MODES.equals(action)) {
- result = getCaptureModes();
- } else if (ACTION_CAPTURE_AUDIO.equals(action)) {
- result = captureAudio(args, callbackId);
- } else if (ACTION_CAPTURE_IMAGE.equals(action)) {
- result = captureImage(args, callbackId);
- } else if (ACTION_CAPTURE_VIDEO.equals(action)) {
- result = captureVideo(args, callbackId);
- } else if (ACTION_CANCEL_CAPTURES.equals(action)) {
- CaptureControl.getCaptureControl().stopPendingOperations(true);
- result = new PluginResult(PluginResult.Status.OK);
- } else {
- result = new PluginResult(PluginResult.Status.INVALID_ACTION,
- "MediaCapture: invalid action " + action);
- }
-
- return result;
- }
-
- /**
- * Determines if audio capture is supported.
- * @return <code>true</code> if audio capture is supported
- */
- protected boolean isAudioCaptureSupported() {
- return (System.getProperty("supports.audio.capture").equals(Boolean.TRUE.toString())
- && AudioControl.hasAudioRecorderApplication());
- }
-
- /**
- * Determines if video capture is supported.
- * @return <code>true</code> if video capture is supported
- */
- protected boolean isVideoCaptureSupported() {
- return (System.getProperty("supports.video.capture").equals(Boolean.TRUE.toString()));
- }
-
- /**
- * Return the supported capture modes for audio, image and video.
- * @return supported capture modes.
- */
- private PluginResult getCaptureModes() {
- JSONArray audioModes = new JSONArray();
- JSONArray imageModes = new JSONArray();
- boolean audioSupported = isAudioCaptureSupported();
-
- // need to get the recording dimensions from supported image encodings
- String imageEncodings = System.getProperty("video.snapshot.encodings");
- Logger.log(this.getClass().getName() + ": video.snapshot.encodings="
- + imageEncodings);
- String[] encodings = StringUtils.split(imageEncodings, "encoding=");
- CaptureMode mode = null;
- Vector list = new Vector();
-
- // get all supported capture content types for audio and image
- String[] contentTypes = getCaptureContentTypes();
- for (int i = 0; i < contentTypes.length; i++) {
- if (audioSupported
- && contentTypes[i]
- .startsWith(AudioCaptureOperation.CONTENT_TYPE)) {
- audioModes.add(new CaptureMode(contentTypes[i]).toJSONObject());
- } else if (contentTypes[i]
- .startsWith(ImageCaptureOperation.CONTENT_TYPE)) {
- String type = contentTypes[i]
- .substring(ImageCaptureOperation.CONTENT_TYPE.length());
- for (int j = 0; j < encodings.length; j++) {
- // format: "jpeg&width=2592&height=1944 "
- String enc = encodings[j];
- if (enc.startsWith(type)) {
- Hashtable parms = parseEncodingString(enc);
- // "width="
- String w = (String)parms.get("width");
- long width = (w == null) ? 0 : Long.parseLong(w);
- // "height="
- String h = (String)parms.get("height");
- long height = (h == null) ? 0 : Long.parseLong(h);
- // new capture mode
- mode = new CaptureMode(contentTypes[i], width, height);
- // don't want duplicates
- if (!list.contains(mode)) {
- list.addElement(mode);
- imageModes.add(mode.toJSONObject());
- }
- }
- }
- }
- }
-
- JSONObject captureModes = new JSONObject();
- try {
- captureModes.put("supportedAudioModes", audioModes.toString());
- captureModes.put("supportedImageModes", imageModes.toString());
- captureModes.put("supportedVideoModes", getVideoCaptureModes().toString());
- } catch (JSONException e) {
- Logger.error("JSONException: " + e.getMessage());
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "Failed to build supported capture modes.");
- }
-
- return new PluginResult(PluginResult.Status.OK, captureModes);
- }
-
- /**
- * Retrieves supported video capture modes (content type, width and height).
- * @return supported video capture modes
- */
- protected JSONArray getVideoCaptureModes() {
- JSONArray videoModes = new JSONArray();
-
- if (!isVideoCaptureSupported()) {
- // if the device does not support video capture, return an empty
- // array of capture modes
- Logger.log(this.getClass().getName() + ": video capture not supported");
- return videoModes;
- }
-
- /**
- * DOH! Even if video capture is supported, BlackBerry's API
- * does not provide any 'video/' content types for the 'capture'
- * protocol. So if we looked at only capture content types,
- * it wouldn't return any results...
- *
- * // get all supported capture content types
- * String[] contentTypes = getCaptureContentTypes();
- *
- * A better alternative, and probably not too inaccurate, would be to
- * send back all supported video modes (not just capture). This will
- * at least give the developer an idea of the capabilities.
- */
-
- // retrieve ALL supported video encodings
- String videoEncodings = System.getProperty("video.encodings");
- Logger.log(this.getClass().getName() + ": video.encodings=" + videoEncodings);
- String[] encodings = StringUtils.split(videoEncodings, "encoding=");
-
- // parse them into CaptureModes
- String enc = null;
- CaptureMode mode = null;
- Vector list = new Vector();
- for (int i = 0; i < encodings.length; i++) {
- enc = encodings[i];
- // format: "video/3gpp&width=640&height=480&video_codec=MPEG-4&audio_codec=AAC "
- if (enc.startsWith(VideoCaptureOperation.CONTENT_TYPE)) {
- Hashtable parms = parseEncodingString(enc);
- // type "video/3gpp"
- String t = (String)parms.get("type");
- // "width="
- String w = (String)parms.get("width");
- long width = (w == null) ? 0 : Long.parseLong(w);
- // "height="
- String h = (String)parms.get("height");
- long height = (h == null) ? 0 : Long.parseLong(h);
- // new capture mode
- mode = new CaptureMode(t, width, height);
- // don't want duplicates
- if (!list.contains(mode)) {
- list.addElement(mode);
- videoModes.add(mode.toJSONObject());
- }
- }
- }
-
- return videoModes;
- }
-
- /**
- * Utility method to parse encoding strings.
- *
- * @param encodingString
- * encoding string
- * @return Hashtable containing key:value pairs
- */
- protected Hashtable parseEncodingString(final String encodingString) {
- // format: "video/3gpp&width=640&height=480&video_codec=MPEG-4&audio_codec=AAC "
- Hashtable props = new Hashtable();
- String[] parms = StringUtils.split(encodingString, "&");
- props.put("type", parms[0]);
- for (int i = 0; i < parms.length; i++) {
- String parameter = parms[i];
- if (parameter.indexOf('=') != -1) {
- String[] pair = StringUtils.split(parameter, "=");
- props.put(pair[0].trim(), pair[1].trim());
- }
- }
- return props;
- }
-
- /**
- * Returns the content types supported for the <code>capture://</code>
- * protocol.
- *
- * @return list of supported capture content types
- */
- protected static String[] getCaptureContentTypes() {
- // retrieve list of all content types supported for capture protocol
- return Manager.getSupportedContentTypes(PROTOCOL_CAPTURE);
- }
-
- /**
- * Starts an audio capture operation using the native voice notes recorder
- * application. If the native voice notes recorder application is already
- * running, the <code>CAPTURE_APPLICATION_BUSY</code> error is returned.
- *
- * @param args
- * capture options (e.g., limit)
- * @param callbackId
- * the callback to be invoked with the capture results
- * @return PluginResult containing captured media file properties
- */
- protected PluginResult captureAudio(final JSONArray args, final String callbackId) {
- PluginResult result = null;
-
- // if audio is not being recorded, start audio capture
- if (!AudioControl.hasAudioRecorderApplication()) {
- result = errorResult(CAPTURE_NOT_SUPPORTED,
- "Audio recorder application is not installed.");
- } else if (AudioControl.isAudioRecorderActive()) {
- result = errorResult(CAPTURE_APPLICATION_BUSY,
- "Audio recorder application is busy.");
- }
- else {
- // optional parameters
- long limit = 1;
- double duration = 0.0f;
-
- try {
- JSONObject options = args.getJSONObject(0);
- if (options != null) {
- limit = options.optLong("limit", 1);
- duration = options.optDouble("duration", 0.0f);
- }
- } catch (JSONException e) {
- // Eat it and use default value of 1.
- Logger.log(this.getClass().getName()
- + ": Invalid captureAudio options format. " + e.getMessage());
- }
-
- // start audio capture
- // start capture operation in the background
- CaptureControl.getCaptureControl().startAudioCaptureOperation(
- limit, duration, callbackId);
-
- // return NO_RESULT and allow callbacks to be invoked later
- result = new PluginResult(PluginResult.Status.NO_RESULT);
- result.setKeepCallback(true);
- }
-
- return result;
- }
-
- /**
- * Starts an image capture operation using the native camera application. If
- * the native camera application is already running, the
- * <code>CAPTURE_APPLICATION_BUSY</code> error is returned.
- *
- * @param args
- * capture options (e.g., limit)
- * @param callbackId
- * the callback to be invoked with the capture results
- * @return PluginResult containing captured media file properties
- */
- protected PluginResult captureImage(final JSONArray args,
- final String callbackId) {
- PluginResult result = null;
-
- if (CameraControl.isCameraActive()) {
- result = errorResult(CAPTURE_APPLICATION_BUSY,
- "Camera application is busy.");
- }
- else {
- // optional parameters
- long limit = 1;
-
- try {
- JSONObject options = args.getJSONObject(0);
- if (options != null) {
- limit = options.optLong("limit", 1);
- }
- } catch (JSONException e) {
- // Eat it and use default value of 1.
- Logger.log(this.getClass().getName()
- + ": Invalid captureImage options format. " + e.getMessage());
- }
-
- // start capture operation in the background
- CaptureControl.getCaptureControl().startImageCaptureOperation(
- limit, callbackId);
-
- // return NO_RESULT and allow callbacks to be invoked later
- result = new PluginResult(PluginResult.Status.NO_RESULT);
- result.setKeepCallback(true);
- }
-
- return result;
- }
-
- /**
- * Starts an video capture operation using the native video recorder
- * application. If the native video recorder application is already running,
- * the <code>CAPTURE_APPLICATION_BUSY</code> error is returned.
- *
- * @param args
- * capture options (e.g., limit)
- * @param callbackId
- * the callback to be invoked with the capture results
- * @return PluginResult containing captured media file properties
- */
- protected PluginResult captureVideo(final JSONArray args,
- final String callbackId) {
- PluginResult result = null;
-
- if (!isVideoCaptureSupported()) {
- result = errorResult(CAPTURE_NOT_SUPPORTED,
- "Video capture is not supported.");
- } else if (CameraControl.isVideoRecorderActive()) {
- result = errorResult(CAPTURE_APPLICATION_BUSY,
- "Video recorder application is busy.");
- }
- else {
- // optional parameters
- long limit = 1;
-
- try {
- JSONObject options = args.getJSONObject(0);
- if (options != null) {
- limit = options.optLong("limit", 1);
- }
- } catch (JSONException e) {
- // Eat it and use default value of 1.
- Logger.log(this.getClass().getName()
- + ": Invalid captureVideo options format. " + e.getMessage());
- }
-
- // start capture operation in the background
- CaptureControl.getCaptureControl().startVideoCaptureOperation(
- limit, callbackId);
-
- // return NO_RESULT and allow callbacks to be invoked later
- result = new PluginResult(PluginResult.Status.NO_RESULT);
- result.setKeepCallback(true);
- }
-
- return result;
- }
-
- /**
- * Sends media capture result back to JavaScript.
- *
- * @param mediaFiles
- * list of File objects describing captured media files
- * @param callbackId
- * the callback to receive the file descriptions
- */
- public static void captureSuccess(Vector mediaFiles, String callbackId) {
- PluginResult result = null;
- File file = null;
-
- JSONArray array = new JSONArray();
- for (Enumeration e = mediaFiles.elements(); e.hasMoreElements();) {
- file = (File) e.nextElement();
- array.add(file.toJSONObject());
- }
-
- // invoke the appropriate callback
- result = new PluginResult(PluginResult.Status.OK, array);
- success(result, callbackId);
- }
-
- /**
- * Sends error back to JavaScript.
- *
- * @param callbackId
- * the callback to receive the error
- */
- public static void captureError(String callbackId) {
- error(errorResult(CAPTURE_NO_MEDIA_FILES, ""), callbackId);
- }
-
- /**
- * Called when application is resumed.
- */
- public void onResume() {
- // We launch the native media applications for capture operations, which
- // puts this application in the background. This application will come
- // to the foreground when the user closes the native media application.
- // So we close any running capture operations any time we resume.
- //
- // It would be nice if we could catch the EVT_APP_FOREGROUND event that
- // is supposed to be triggered when the application comes to the
- // foreground, but have not seen a way to do that on the Java side.
- // Unfortunately, we have to get notification from the JavaScript side,
- // which does get the event. (Argh! Only BlackBerry.)
- //
- // In this case, we're just stopping the capture operations, not
- // canceling them.
- CaptureControl.getCaptureControl().stopPendingOperations(false);
- }
-
- /**
- * Invoked when this application terminates.
- */
- public void onDestroy() {
- CaptureControl.getCaptureControl().stopPendingOperations(true);
- }
-
- private static PluginResult errorResult(int code, String message) {
- Logger.log(LOG_TAG + message);
-
- JSONObject obj = new JSONObject();
- try {
- obj.put("code", code);
- obj.put("message", message);
- } catch (JSONException e) {
- // This will never happen
- }
-
- return new PluginResult(PluginResult.Status.ERROR, obj);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/MediaQueue.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/MediaQueue.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/MediaQueue.java
deleted file mode 100644
index 56ffff5..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/MediaQueue.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import java.util.Vector;
-
-/**
- * Acts as a container for captured media files. The media applications will
- * add to the queue when a media file is captured.
- */
-class MediaQueue {
- private Vector queue = new Vector();
-
- synchronized void add(final String filePath) {
- queue.addElement(filePath);
- notifyAll();
- }
-
- synchronized String remove() throws InterruptedException {
- while (queue.size() == 0) {
- wait();
- }
- String filePath = (String) queue.firstElement();
- queue.removeElement(filePath);
- notifyAll();
- return filePath;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/VideoCaptureListener.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/VideoCaptureListener.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/VideoCaptureListener.java
deleted file mode 100644
index 361b7ee..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/VideoCaptureListener.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import net.rim.device.api.io.file.FileSystemJournal;
-import net.rim.device.api.io.file.FileSystemJournalEntry;
-import net.rim.device.api.io.file.FileSystemJournalListener;
-
-/**
- * Listens for video recording files that are added to file system.
- * <p>
- * Video recordings are added to the file system in a multi-step process. The
- * video recorder application records the video on a background thread. While
- * the recording is in progress, it is added to the file system with a '.lock'
- * extension. When the user stops the recording, the file is renamed to the
- * video recorder extension (e.g. .3GP). Therefore, we listen for the
- * <code>FileSystemJournalEntry.FILE_RENAMED</code> event, capturing when the
- * new path name ends in the video recording file extension.
- * <p>
- * The file system notifications will arrive on the application event thread.
- * When it receives a notification, it adds the image file path to a MediaQueue
- * so that the capture thread can process the file.
- */
-class VideoCaptureListener implements FileSystemJournalListener {
-
- /**
- * Used to track file system changes.
- */
- private long lastUSN = 0;
-
- /**
- * Queue to send media files to for processing.
- */
- private MediaQueue queue = null;
-
- /**
- * Newly added video recording.
- */
- private String newFilePath = null;
-
- /**
- * Constructor.
- */
- VideoCaptureListener(MediaQueue queue) {
- this.queue = queue;
- }
-
- public void fileJournalChanged() {
- // next sequence number file system will use
- long USN = FileSystemJournal.getNextUSN();
-
- for (long i = USN - 1; i >= lastUSN && i < USN; --i)
- {
- FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
- if (entry == null)
- {
- break;
- }
-
- String path = entry.getPath();
- if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED
- && newFilePath == null) {
- // a new file has been added to the file system
- // if it has a video recording extension, store it until
- // it is renamed, indicating it has finished being written to
- int index = path.indexOf(".3GP");
- if (index == -1) {
- index = path.indexOf(".MP4");
- }
- if (index != -1) {
- newFilePath = path.substring(0, index + 4);
- }
- }
- else if (entry.getEvent() == FileSystemJournalEntry.FILE_RENAMED) {
- if (path != null && path.equals(newFilePath))
- {
- // add file path to the capture queue
- queue.add("file://" + path);
-
- // get ready for next file
- newFilePath = null;
- break;
- }
- }
- }
-
- // remember the file journal change number,
- // so we don't search the same events again and again
- lastUSN = USN;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/VideoCaptureOperation.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/VideoCaptureOperation.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/VideoCaptureOperation.java
deleted file mode 100644
index 589bc68..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/VideoCaptureOperation.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import java.io.IOException;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.file.FileConnection;
-
-import org.apache.cordova.file.File;
-import org.apache.cordova.util.FileUtils;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.io.MIMETypeAssociations;
-import net.rim.device.api.ui.UiApplication;
-
-public class VideoCaptureOperation extends CaptureOperation {
-
- // content type
- public static String CONTENT_TYPE = "video/";
-
- // file system listener
- private VideoCaptureListener listener = null;
-
- /**
- * Creates and starts an image capture operation.
- *
- * @param limit
- * maximum number of media files to capture
- * @param callbackId
- * the callback to receive the files
- * @param queue
- * the queue from which to retrieve captured media files
- */
- public VideoCaptureOperation(long limit, String callbackId, MediaQueue queue) {
- super(limit, callbackId, queue);
-
- // listener to capture image files added to file system
- this.listener = new VideoCaptureListener(queue);
-
- start();
- }
-
- /**
- * Registers file system listener and launches native video recorder
- * application.
- */
- protected void setup() {
- // register listener for files being written
- synchronized(UiApplication.getEventLock()) {
- UiApplication.getUiApplication().addFileSystemJournalListener(listener);
- }
-
- // launch the native video recorder application
- CameraControl.launchVideoRecorder();
- }
-
- /**
- * Unregisters file system listener and closes native video recorder
- * application.
- */
- protected void teardown() {
- // remove file system listener
- synchronized(UiApplication.getEventLock()) {
- UiApplication.getUiApplication().removeFileSystemJournalListener(listener);
- }
-
- // close the native video recorder application
- CameraControl.closeVideoRecorder();
- }
-
- /**
- * Retrieves the file properties for the captured video recording.
- *
- * @param filePath
- * full path of the video recording file
- */
- protected void processFile(String filePath) {
- Logger.log(this.getClass().getName() + ": processing file: " + filePath);
-
- File file = new File(FileUtils.stripSeparator(filePath));
-
- // grab file properties
- FileConnection fconn = null;
- try {
- fconn = (FileConnection) Connector.open(filePath, Connector.READ);
- if (fconn.exists()) {
- long size = fconn.fileSize();
- Logger.log(this.getClass().getName() + ": " + filePath + " size="
- + Long.toString(size) + " bytes");
- file.setLastModifiedDate(fconn.lastModified());
- file.setName(FileUtils.stripSeparator(fconn.getName()));
- file.setSize(size);
- file.setType(MIMETypeAssociations.getMIMEType(filePath));
- }
- }
- catch (IOException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- } catch (IOException ignored) {}
- }
-
- addCaptureFile(file);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/device/Device.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/device/Device.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/device/Device.java
deleted file mode 100644
index c006b3f..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/device/Device.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- * Copyright (c) 2011, Research In Motion Limited.
- */
-package org.apache.cordova.device;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-
-import net.rim.device.api.system.DeviceInfo;
-
-/**
- * Provides device information, including:
- *
- * - Device platform version (e.g. 2.13.0.95). Not to be confused with BlackBerry OS version.
- * - Unique device identifier (UUID).
- * - Cordova software version.
- */
-public final class Device extends Plugin {
-
- public static final String FIELD_PLATFORM = "platform";
- public static final String FIELD_UUID = "uuid";
- public static final String FIELD_CORDOVA = "cordova";
- public static final String FIELD_MODEL = "model";
- public static final String FIELD_NAME = "name";
- public static final String FIELD_VERSION = "version";
-
- public static final String ACTION_GET_DEVICE_INFO = "getDeviceInfo";
-
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult result = new PluginResult(PluginResult.Status.INVALID_ACTION, "Device: Invalid action:" + action);
-
- if(action.equals(ACTION_GET_DEVICE_INFO)){
- try {
- JSONObject device = new JSONObject();
- device.put( FIELD_PLATFORM, "BlackBerry");
- device.put( FIELD_UUID, new Integer( DeviceInfo.getDeviceId()) );
- device.put( FIELD_CORDOVA, "2.7.0" );
- device.put( FIELD_MODEL, new String(DeviceInfo.getDeviceName()) );
- device.put( FIELD_NAME, new String(DeviceInfo.getDeviceName()) );
- device.put( FIELD_VERSION, new String(DeviceInfo.getSoftwareVersion()) );
- result = new PluginResult(PluginResult.Status.OK, device);
- } catch (JSONException e) {
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
- }
- }
-
- return result;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/Entry.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/Entry.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/Entry.java
deleted file mode 100644
index 66fb59b..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/Entry.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.file;
-
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-
-public class Entry {
-
- private boolean isDirectory = false;
- private String name = null;
- private String fullPath = null;
-
- public boolean isDirectory() {
- return isDirectory;
- }
-
- public void setDirectory(boolean isDirectory) {
- this.isDirectory = isDirectory;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getFullPath() {
- return fullPath;
- }
-
- public void setFullPath(String fullPath) {
- this.fullPath = fullPath;
- }
-
- public JSONObject toJSONObject() {
- JSONObject o = new JSONObject();
- try {
- o.put("isDirectory", isDirectory);
- o.put("isFile", !isDirectory);
- o.put("name", name);
- o.put("fullPath", fullPath);
- }
- catch (JSONException ignored) {
- }
- return o;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/File.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/File.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/File.java
deleted file mode 100644
index 3d04041..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/File.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.file;
-
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-
-public class File {
- private String name = null;
- private String fullPath = null;
- private String type = null;
- private long lastModifiedDate;
- private long size = 0;
-
- public File(String filePath) {
- this.fullPath = filePath;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- public long getLastModifiedDate() {
- return lastModifiedDate;
- }
-
- public void setLastModifiedDate(long lastModifiedDate) {
- this.lastModifiedDate = lastModifiedDate;
- }
-
- public long getSize() {
- return size;
- }
-
- public void setSize(long size) {
- this.size = size;
- }
-
- public String getFullPath() {
- return fullPath;
- }
-
- public JSONObject toJSONObject() {
- JSONObject o = new JSONObject();
- try {
- o.put("fullPath", fullPath);
- o.put("type", type);
- o.put("name", name);
- o.put("lastModifiedDate", lastModifiedDate);
- o.put("size", size);
- }
- catch (JSONException ignored) {
- }
- return o;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/FileManager.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/FileManager.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/FileManager.java
deleted file mode 100644
index 55ea436..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/file/FileManager.java
+++ /dev/null
@@ -1,1051 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.file;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.util.Enumeration;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.file.FileConnection;
-import javax.microedition.io.file.FileSystemRegistry;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.util.FileUtils;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.io.Base64OutputStream;
-import net.rim.device.api.io.FileNotFoundException;
-import net.rim.device.api.io.MIMETypeAssociations;
-import net.rim.device.api.system.Application;
-
-public class FileManager extends Plugin {
-
- /**
- * File related errors.
- */
- public static int NOT_FOUND_ERR = 1;
- public static int SECURITY_ERR = 2;
- public static int ABORT_ERR = 3;
- public static int NOT_READABLE_ERR = 4;
- public static int ENCODING_ERR = 5;
- public static int NO_MODIFICATION_ALLOWED_ERR = 6;
- public static int INVALID_STATE_ERR = 7;
- public static int SYNTAX_ERR = 8;
- public static int INVALID_MODIFICATION_ERR = 9;
- public static int QUOTA_EXCEEDED_ERR = 10;
- public static int TYPE_MISMATCH_ERR = 11;
- public static int PATH_EXISTS_ERR = 12;
-
- /**
- * File system for storing information on a temporary basis (no guaranteed persistence).
- */
- public static final short FS_TEMPORARY = 0;
-
- /**
- * File system for storing information on a permanent basis.
- */
- public static final short FS_PERSISTENT = 1;
-
- /**
- * Possible actions.
- */
- protected static String ACTION_READ_AS_TEXT = "readAsText";
- protected static String ACTION_READ_AS_DATA_URL = "readAsDataURL";
- protected static String ACTION_WRITE = "write";
- protected static String ACTION_TRUNCATE = "truncate";
- protected static String ACTION_REQUEST_FILE_SYSTEM = "requestFileSystem";
- protected static String ACTION_RESOLVE_FILE_SYSTEM_URI = "resolveLocalFileSystemURI";
- protected static String ACTION_GET_METADATA = "getMetadata";
- protected static String ACTION_GET_FILE_METADATA = "getFileMetadata";
- protected static String ACTION_LIST_DIRECTORY = "readEntries";
- protected static String ACTION_COPY_TO = "copyTo";
- protected static String ACTION_MOVE_TO = "moveTo";
- protected static String ACTION_IS_FILE_SYSTEM_ROOT = "isFileSystemRoot";
-
- /**
- * Executes the requested action and returns a PluginResult.
- *
- * @param action
- * The action to execute.
- * @param callbackId
- * The callback ID to be invoked upon action completion
- * @param args
- * JSONArry of arguments for the action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- // perform specified action
- if (ACTION_READ_AS_TEXT.equals(action)) {
- // get file path
- String filePath = null;
- try {
- filePath = args.getString(0);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid or missing path: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return readAsText(filePath, args.optString(1));
- }
- else if (ACTION_READ_AS_DATA_URL.equals(action)) {
- // get file path
- String filePath = null;
- try {
- filePath = args.getString(0);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid or missing path: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return readAsDataURL(filePath);
- }
- else if (ACTION_WRITE.equals(action)) {
- // file path
- String filePath = null;
- try {
- filePath = args.getString(0);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid or missing path: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
-
- // file data
- String data = null;
- try {
- data = args.getString(1);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Unable to parse file data: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
-
- // position
- int position = 0;
- try {
- position = Integer.parseInt(args.optString(2));
- }
- catch (NumberFormatException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid position parameter: " + e);
- return new PluginResult(
- PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return writeFile(filePath, data, position);
- }
- else if (ACTION_TRUNCATE.equals(action)) {
- // file path
- String filePath = null;
- try {
- filePath = args.getString(0);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid or missing path: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
-
- // file size
- long fileSize = 0;
- try {
- // retrieve new file size
- fileSize = Long.parseLong(args.getString(1));
- }
- catch (Exception e) {
- Logger.log(this.getClass().getName()
- + ": Invalid file size parameter: " + e);
- return new PluginResult(
- PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return truncateFile(filePath, fileSize);
- }
- else if (ACTION_REQUEST_FILE_SYSTEM.equals(action)) {
- int fileSystemType = -1;
- long fileSystemSize = 0;
- try {
- fileSystemType = args.getInt(0);
- fileSystemSize = (args.isNull(1) == true) ? 0 : args.getLong(1);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid file system type: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return requestFileSystem(fileSystemType, fileSystemSize);
- }
- else if (ACTION_RESOLVE_FILE_SYSTEM_URI.equals(action)) {
- String uri = null;
- try {
- uri = args.getString(0);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid or missing file URI: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return resolveFileSystemURI(uri);
- }
- else if (ACTION_GET_METADATA.equals(action) || ACTION_GET_FILE_METADATA.equals(action)) {
- String path = null;
- try {
- path = args.getString(0);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid or missing file URI: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return getMetadata(path, ACTION_GET_FILE_METADATA.equals(action));
- }
- else if (ACTION_LIST_DIRECTORY.equals(action)) {
- String path = null;
- try {
- path = args.getString(0);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid or missing path: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return listDirectory(path);
- }
- else if (ACTION_COPY_TO.equals(action)) {
- String srcPath = null;
- String parent = null;
- String newName = null;
- try {
- srcPath = args.getString(0);
- parent = args.getString(1);
- newName = args.getString(2);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid or missing path: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return copyTo(srcPath, parent, newName);
- }
- else if (ACTION_MOVE_TO.equals(action)) {
- String srcPath = null;
- String parent = null;
- String newName = null;
- try {
- srcPath = args.getString(0);
- parent = args.getString(1);
- newName = args.getString(2);
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName()
- + ": Invalid or missing path: " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
- return moveTo(srcPath, parent, newName);
- }
- else if (ACTION_IS_FILE_SYSTEM_ROOT.equals(action)) {
- return new PluginResult(PluginResult.Status.OK,
- isFileSystemRoot(args.optString(0)));
- }
-
- // invalid action
- return new PluginResult(PluginResult.Status.INVALID_ACTION,
- "File: invalid action " + action);
- }
-
- /**
- * Reads a file and encodes the contents using the specified encoding.
- *
- * @param filePath
- * Full path of the file to be read
- * @param encoding
- * Encoding to use for the file contents
- * @return PluginResult containing encoded file contents or error code if
- * unable to read or encode file
- */
- protected static PluginResult readAsText(String filePath, String encoding) {
- PluginResult result = null;
- String logMsg = ": encoding file contents using " + encoding;
-
- // read the file
- try {
- // return encoded file contents
- byte[] blob = FileUtils.readFile(filePath, Connector.READ);
- result = new PluginResult(PluginResult.Status.OK,
- new String(blob, encoding));
- }
- catch (FileNotFoundException e) {
- logMsg = e.toString();
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_FOUND_ERR);
- }
- catch (UnsupportedEncodingException e) {
- logMsg = e.toString();
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- ENCODING_ERR);
- }
- catch (IOException e) {
- logMsg = e.toString();
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_READABLE_ERR);
- }
- finally {
- Logger.log(FileManager.class.getName() + ": " + logMsg);
- }
-
- return result;
- }
-
- /**
- * Read file and return data as a base64 encoded data url. A data url is of
- * the form: data:[<mediatype>][;base64],<data>
- *
- * @param filePath
- * Full path of the file to be read
- * @return PluginResult containing the encoded file contents or an error
- * code if unable to read the file
- */
- protected static PluginResult readAsDataURL(String filePath) {
- String data = null;
- try {
- // read file
- byte[] blob = FileUtils.readFile(filePath, Connector.READ);
-
- // encode file contents using BASE64 encoding
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- Base64OutputStream base64OutputStream = new Base64OutputStream(
- byteArrayOutputStream);
- base64OutputStream.write(blob);
- base64OutputStream.flush();
- base64OutputStream.close();
- data = byteArrayOutputStream.toString();
- }
- catch (FileNotFoundException e) {
- Logger.log(FileManager.class.getName() + ": " + e);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_FOUND_ERR);
- }
- catch (IOException e) {
- Logger.log(FileManager.class.getName() + ": " + e);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_READABLE_ERR);
- }
-
- // put result in proper form
- String mediaType = MIMETypeAssociations.getMIMEType(filePath);
- if (mediaType == null) {
- mediaType = "";
- }
- data = "data:" + mediaType + ";base64," + data;
-
- return new PluginResult(PluginResult.Status.OK, data);
- }
-
- /**
- * Writes data to the specified file.
- *
- * @param filePath
- * Full path of file to be written to
- * @param data
- * Data to be written
- * @param position
- * Position at which to begin writing
- * @return PluginResult containing the number of bytes written or error code
- * if unable to write file
- */
- protected static PluginResult writeFile(String filePath, String data, int position) {
- PluginResult result = null;
- int bytesWritten = 0;
- try {
- // write file data
- // The default String encoding on BB is ISO-8859-1 which causes
- // issues with extended characters. Force to UTF-8 to provide
- // greater character support and match other platforms.
- bytesWritten = FileUtils.writeFile(filePath, data.getBytes("UTF-8"), position);
- result = new PluginResult(PluginResult.Status.OK, bytesWritten);
- }
- catch (SecurityException e) {
- Logger.log(FileManager.class.getName() + ": " + e);
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NO_MODIFICATION_ALLOWED_ERR);
- }
- catch (IOException e) {
- // it's not a security issue, so the directory path is either
- // not fully created or a general error occurred
- Logger.log(FileManager.class.getName() + ": " + e);
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_FOUND_ERR);
- }
-
- return result;
- }
-
- /**
- * Changes the length of the specified file. If shortening, data beyond new
- * length is discarded.
- *
- * @param fileName
- * The full path of the file to truncate
- * @param size
- * The size to which the length of the file is to be adjusted
- * @return PluginResult containing new file size or an error code if an
- * error occurred
- */
- protected static PluginResult truncateFile(String filePath, long size) {
- long fileSize = 0;
- FileConnection fconn = null;
- try {
- fconn = (FileConnection) Connector.open(filePath,
- Connector.READ_WRITE);
- if (!fconn.exists()) {
- Logger.log(FileManager.class.getName() + ": path not found "
- + filePath);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_FOUND_ERR);
- }
- if (size >= 0) {
- fconn.truncate(size);
- }
- fileSize = fconn.fileSize();
- }
- catch (IOException e) {
- Logger.log(FileManager.class.getName() + ": " + e);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NO_MODIFICATION_ALLOWED_ERR);
- }
- finally {
- try {
- if (fconn != null)
- fconn.close();
- }
- catch (IOException e) {
- Logger.log(FileManager.class.getName() + ": " + e);
- }
- }
- return new PluginResult(PluginResult.Status.OK, fileSize);
- }
-
- /**
- * Returns a directory entry that represents the specified file system. The
- * directory entry does not represent the root of the file system, but a
- * directory within the file system that is writable. Users must provide the
- * file system type, which can be one of FS_TEMPORARY or FS_PERSISTENT.
- *
- * @param type
- * The type of file system desired.
- * @param size
- * The minimum size, in bytes, of space required
- * @return a PluginResult containing a file system object for the specified
- * file system
- */
- protected static PluginResult requestFileSystem(int type, long size) {
- if (!isValidFileSystemType(type)) {
- Logger.log(FileManager.class.getName()
- + ": Invalid file system type: " + Integer.toString(type));
- return new PluginResult(
- PluginResult.Status.JSON_EXCEPTION,
- SYNTAX_ERR);
- }
-
- PluginResult result = null;
- String filePath = null;
- switch (type) {
- case FS_TEMPORARY:
- // create application-specific temp directory
- try {
- filePath = FileUtils.createApplicationTempDirectory();
- }
- catch (IOException e) {
- Logger.log(FileManager.class.getName() + ": " + e);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NO_MODIFICATION_ALLOWED_ERR);
- }
- break;
- case FS_PERSISTENT:
- // get a path to SD card (if present) or user directory (internal)
- filePath = FileUtils.getFileSystemRoot();
- break;
- }
-
- // create a file system entry from the path
- Entry entry = null;
- try {
- // check the file system size
- if (size > FileUtils.availableSize(filePath)) {
- return new PluginResult(
- PluginResult.Status.IO_EXCEPTION,
- QUOTA_EXCEEDED_ERR);
- }
-
- entry = getEntryFromURI(filePath);
- }
- catch (Exception e) {
- // bad path (not likely)
- return new PluginResult(PluginResult.Status.IO_EXCEPTION,
- ENCODING_ERR);
- }
-
- try {
- JSONObject fileSystem = new JSONObject();
- fileSystem.put("name", getFileSystemName(type));
- fileSystem.put("root", entry.toJSONObject());
- result = new PluginResult(PluginResult.Status.OK, fileSystem);
- }
- catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "File system entry JSON conversion failed.");
- }
-
- return result;
- }
-
- /**
- * Creates a file system entry object from the specified file system URI.
- *
- * @param uri
- * the full path to the file or directory on the file system
- * @return a PluginResult containing the file system entry
- */
- protected static PluginResult resolveFileSystemURI(String uri) {
- PluginResult result = null;
- Entry entry = null;
- try {
- entry = getEntryFromURI(uri);
- }
- catch (IllegalArgumentException e) {
- Logger.log(e.toString());
- return new PluginResult(
- PluginResult.Status.JSON_EXCEPTION,
- ENCODING_ERR);
- }
-
- if (entry == null) {
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_FOUND_ERR);
- }
- else {
- result = new PluginResult(PluginResult.Status.OK,
- entry.toJSONObject());
- }
-
- return result;
- }
-
- /**
- * Retrieve metadata for file or directory specified by path.
- *
- * @param path
- * full path name of the file or directory
- * @param full
- * return full or partial meta data.
- * @return PluginResult containing metadata for file system entry or an
- * error code if unable to retrieve metadata
- */
- protected static PluginResult getMetadata(String path, boolean full) {
- PluginResult result = null;
- FileConnection fconn = null;
- try {
- fconn = (FileConnection)Connector.open(path);
- if (fconn.exists()) {
- if (full) {
- JSONObject metadata = new JSONObject();
- metadata.put("size", fconn.fileSize());
- metadata.put("type",
- MIMETypeAssociations.getMIMEType(fconn.getURL()));
- metadata.put("name", fconn.getName());
- metadata.put("fullPath", fconn.getURL());
- metadata.put("lastModifiedDate", fconn.lastModified());
- result = new PluginResult(PluginResult.Status.OK, metadata);
- } else {
- result = new PluginResult(PluginResult.Status.OK,
- fconn.lastModified());
- }
- }
- else {
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_FOUND_ERR);
- }
- }
- catch (IllegalArgumentException e) {
- // bad path
- Logger.log(FileUtils.class.getName() + ": " + e);
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_FOUND_ERR);
- }
- catch (IOException e) {
- Logger.log(FileUtils.class.getName() + ": " + e);
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_READABLE_ERR);
- }
- catch (JSONException e) {
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "File system entry JSON conversion failed.");
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- return result;
- }
-
- private static JSONObject buildEntry(String dirPath, String filePath) throws JSONException {
- JSONObject entry = new JSONObject();
- boolean isDir = filePath.endsWith(FileUtils.FILE_SEPARATOR);
-
- entry.put("isFile", !isDir);
- entry.put("isDirectory", isDir);
- entry.put("name", isDir ? filePath.substring(0, filePath.length()-1) : filePath);
- entry.put("fullPath", dirPath + filePath);
-
- return entry;
- }
-
- /**
- * Returns a listing of the specified directory contents. Names of both
- * files and directories are returned.
- *
- * @param path
- * full path name of directory
- * @return PluginResult containing list of file and directory names
- * corresponding to directory contents
- */
- protected static PluginResult listDirectory(String path) {
- Enumeration listing = null;
- try {
- listing = FileUtils.listDirectory(path);
- }
- catch (Exception e) {
- // bad path
- Logger.log(FileUtils.class.getName() + ": " + e);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION,
- NOT_FOUND_ERR);
- }
-
- try {
- // pass directory contents back as an array of JSONObjects (entries)
- JSONArray array = new JSONArray();
- while (listing.hasMoreElements()) {
- array.add(buildEntry(path, (String) listing.nextElement()));
- }
-
- return new PluginResult(PluginResult.Status.OK, array);
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "File system entry JSON conversion failed.");
- }
- }
-
- /**
- * Copies a file or directory to a new location. If copying a directory, the
- * entire contents of the directory are copied recursively.
- *
- * @param srcPath
- * the full path of the file or directory to be copied
- * @param parent
- * the full path of the target directory to which the file or
- * directory should be copied
- * @param newName
- * the new name of the file or directory
- * @return PluginResult containing an Entry object representing the new
- * entry, or an error code if an error occurs
- */
- protected static PluginResult copyTo(String srcPath, String parent, String newName) {
- try {
- FileUtils.copy(srcPath, parent, newName);
- }
- catch (IllegalArgumentException e) {
- Logger.log(FileManager.class.getName() + ": " + e.getMessage());
- return new PluginResult(
- PluginResult.Status.JSON_EXCEPTION, ENCODING_ERR);
- }
- catch (FileNotFoundException e) {
- Logger.log(FileManager.class.getName() + ": " + e.getMessage());
- return new PluginResult(
- PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR);
- }
- catch (SecurityException e) {
- Logger.log(FileManager.class.getName() + ": " + e.getMessage());
- return new PluginResult(
- PluginResult.Status.IO_EXCEPTION, SECURITY_ERR);
- }
- catch (IOException e) {
- Logger.log(FileManager.class.getName() + ": " + e.getMessage());
- return new PluginResult(
- PluginResult.Status.IO_EXCEPTION, INVALID_MODIFICATION_ERR);
- }
-
- return resolveFileSystemURI(getFullPath(parent, newName));
- }
-
- /**
- * Moves a file or directory to a new location. If moving a directory, the
- * entire contents of the directory are moved recursively.
- * <p>
- * It is an error to try to: move a directory inside itself; move a
- * directory into its parent unless the name has changed; move a file to a
- * path occupied by a directory; move a directory to a path occupied by a
- * file; move any element to a path occupied by a directory that is not
- * empty.
- * </p>
- * <p>
- * A move of a file on top of an existing file must attempt to delete and
- * replace that file. A move of a directory on top of an existing empty
- * directory must attempt to delete and replace that directory.
- * </p>
- *
- * @param srcPath
- * the full path of the file or directory to be moved
- * @param parent
- * the full path of the target directory to which the file or
- * directory should be copied
- * @param newName
- * the new name of the file or directory
- * @return PluginResult containing an Entry object representing the new
- * entry, or an error code if an error occurs
- */
- protected static PluginResult moveTo(String srcPath, String parent, String newName) {
-
- // check paths
- if (parent == null || newName == null) {
- Logger.log(FileManager.class.getName() + ": Parameter cannot be null.");
- return new PluginResult(
- PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR);
- }
- else if (!parent.endsWith(FileUtils.FILE_SEPARATOR)) {
- parent += FileUtils.FILE_SEPARATOR;
- }
-
- // Rules:
- // 1 - file replace existing file ==> OK
- // 2 - directory replace existing EMPTY directory ==> OK
- // 3 - file replace existing directory ==> NO!
- // 4 - directory replace existing file ==> NO!
- // 5 - ANYTHING replace non-empty directory ==> NO!
- //
- // The file-to-directory and directory-to-file checks are performed in
- // the copy operation (below). In addition, we check the destination
- // path to see if it is a directory that is not empty. Also, if the
- // source and target paths have the same parent directory, it is far
- // more efficient to rename the source.
- //
- FileConnection src = null;
- FileConnection dst = null;
- try {
- src = (FileConnection)Connector.open(srcPath, Connector.READ_WRITE);
- if (!src.exists()) {
- Logger.log(FileManager.class.getName() + ": Path not found: " + srcPath);
- return new PluginResult(
- PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR);
- }
-
- if (src.isDirectory() && !srcPath.endsWith(FileUtils.FILE_SEPARATOR)) {
- // Rename of a directory on OS 7+ is quirky in that it requires
- // the opened file path to have a trailing slash.
- src.close();
- src = (FileConnection)Connector.open(srcPath + '/', Connector.READ_WRITE);
- }
-
- // cannot delete the destination path if it is a directory that is
- // not empty
- dst = (FileConnection) Connector.open(parent + newName, Connector.READ_WRITE);
- if (dst.isDirectory() && dst.list("*", true).hasMoreElements()) {
- return new PluginResult(
- PluginResult.Status.IO_EXCEPTION, INVALID_MODIFICATION_ERR);
- }
-
- // simply rename if source path and parent are same directory
- String srcURL = src.getURL();
- String srcName = src.getName();
- String srcDir = srcURL.substring(0, srcURL.length() - srcName.length());
- if (srcDir.equals(parent)) {
- // rename to itself is an error
- if (FileUtils.stripSeparator(srcName).equals(
- FileUtils.stripSeparator(newName))) {
- return new PluginResult(PluginResult.Status.IO_EXCEPTION,
- INVALID_MODIFICATION_ERR);
- }
-
- // file replace file || directory replace directory ==> OK
- // delete the existing entry
- if (dst.exists() &&
- ( (src.isDirectory() && dst.isDirectory()) ||
- (!src.isDirectory() && !dst.isDirectory()) )) {
- dst.delete();
- }
-
- // rename
- src.rename(newName);
- Entry entry = getEntryFromURI(parent + newName);
- return new PluginResult(PluginResult.Status.OK, entry.toJSONObject());
- }
- }
- catch (IllegalArgumentException e) {
- Logger.log(FileManager.class.getName() + ": " + e);
- return new PluginResult(
- PluginResult.Status.JSON_EXCEPTION,
- ENCODING_ERR);
- }
- catch (IOException e) {
- // rename failed
- Logger.log(FileManager.class.getName() + ": " + e);
- return new PluginResult(
- PluginResult.Status.IO_EXCEPTION,
- INVALID_MODIFICATION_ERR);
- }
- finally {
- try {
- if (src != null) src.close();
- if (dst != null) dst.close();
- }
- catch (IOException ignored) {
- }
- }
-
- // There is no FileConnection API to move files and directories, so
- // the move is a copy operation from source to destination, followed by
- // a delete operation of the source.
- //
- // The following checks are made in the copy operation:
- // * moving a directory into itself,
- // * moving a file to an existing directory, and
- // * moving a directory to an existing file
- //
- // copy source to destination
- PluginResult result = copyTo(srcPath, parent, newName);
-
- // if copy succeeded, delete source
- if (result.getStatus() == PluginResult.Status.OK.ordinal()) {
- try {
- FileUtils.delete(srcPath);
- }
- catch (IOException e) {
- // FIXME: half of move failed, but deleting either source or
- // destination to compensate seems risky
- Logger.log(FileManager.class.getName()
- + ": Failed to delete source directory during move operation.");
- }
- }
- return result;
- }
-
- /**
- * Creates a file system entry for the file or directory located at the
- * specified path.
- *
- * @param filePath
- * full path name of an entry on the file system
- * @return a file system entry corresponding to the file path, or
- * <code>null</code> if the path is invalid or does not exist on the
- * file system
- * @throws IllegalArgumentException
- * is the file path is invalid
- * @throws IOException
- */
- protected static Entry getEntryFromURI(String filePath)
- throws IllegalArgumentException {
- // check for bogus path
- String path = (filePath == null) ? null : filePath.trim();
- if (path == null || path.length() < 1) {
- throw new IllegalArgumentException("Invalid URI.");
- }
-
- //check for query string
- int queryIndex = filePath.indexOf('?');
- if (queryIndex > 0) {
- path = filePath.substring(0, queryIndex); // discard the query string
- Logger.log(FileManager.class.getName() + ": found query string when resolving URI = " + filePath.substring(queryIndex));
- }
-
- // create a file system entry
- Entry entry = null;
- if (path.startsWith(FileUtils.LOCAL_PROTOCOL)) {
- entry = getEntryFromLocalURI(filePath);
- }
- else {
- FileConnection fconn = null;
- try {
- fconn = (FileConnection) Connector.open(path);
- if (fconn.exists()) {
- // create a new Entry
- entry = new Entry();
- entry.setDirectory(fconn.isDirectory());
- entry.setName(FileUtils.stripSeparator(fconn.getName()));
- entry.setFullPath(FileUtils.stripSeparator(path));
- }
- }
- catch (IOException e) {
- Logger.log(FileManager.class.getName() + ": " + e.getMessage());
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- }
-
- return entry;
- }
-
- /**
- * Creates a file system entry for a resource contained in the packaged
- * application. Use this method if the specified path begins with
- * <code>local:///</code> protocol.
- *
- * @param localPath
- * the path of the application resource
- * @return a file system entry corresponding to the local path, or
- * <code>null</code> if a resource does not exist at the specified
- * path
- */
- private static Entry getEntryFromLocalURI(String localPath) {
- // Remove local:// from filePath but leave a leading /
- String path = localPath.substring(8);
- Entry entry = null;
- if (FileUtils.FILE_SEPARATOR.equals(path)
- || Application.class.getResourceAsStream(path) != null) {
- entry = new Entry();
- entry.setName(path.substring(1));
- entry.setFullPath(localPath);
- }
- return entry;
- }
-
- /**
- * Tests whether the specified file system type is valid.
- *
- * @param type
- * file system type
- * @return true if file system type is valid
- */
- protected static boolean isValidFileSystemType(int type) {
- return (type == FS_TEMPORARY || type == FS_PERSISTENT);
- }
-
- /**
- * Determines if the specified path is the root path of a file system.
- *
- * @param path
- * full path
- * @return true if the path is the root path of a file system
- */
- protected static boolean isFileSystemRoot(String path) {
- if (path == null) {
- return false;
- }
-
- if (!path.endsWith(FileUtils.FILE_SEPARATOR)) {
- path += FileUtils.FILE_SEPARATOR;
- }
-
- boolean isRoot = false;
- Enumeration e = FileSystemRegistry.listRoots();
- while (e.hasMoreElements()) {
- String root = "file:///" + (String) e.nextElement();
- if (root.equals(path)) {
- isRoot = true;
- break;
- }
- }
-
- return (isRoot || path.equals(FileUtils.getApplicationTempDirPath()));
- }
-
- /**
- * Retrieves the name for the specified file system type.
- *
- * @param type
- * file system type
- * @return file system name
- */
- protected static String getFileSystemName(int type) {
- String name = null;
- switch (type) {
- case FS_TEMPORARY:
- name = "temporary";
- break;
- case FS_PERSISTENT:
- name = "persistent";
- break;
- }
- return name;
- }
-
- /**
- * Returns full path from the directory and name specified.
- *
- * @param parent
- * full path of the parent directory
- * @param name
- * name of the directory entry (can be <code>null</code>)
- * @return full path of the file system entry
- * @throws IllegalArgumentException
- * if <code>parent</code> is <code>null</code>
- */
- public static String getFullPath(String parent, String name)
- throws IllegalArgumentException {
- if (parent == null) {
- throw new IllegalArgumentException("Directory cannot be null.");
- }
-
- if (!parent.endsWith(FileUtils.FILE_SEPARATOR)) {
- parent += FileUtils.FILE_SEPARATOR;
- }
- return (name == null) ? parent : parent + name;
- }
-
- /**
- * Determines if the specified action should be run synchronously.
- *
- * @param action
- * the action to perform
- * @return true if the action should be synchronous
- */
- public boolean isSynch(String action) {
- if (ACTION_IS_FILE_SYSTEM_ROOT.equals(action)) {
- return true;
- }
- return super.isSynch(action);
- }
-}
[31/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/CordovaActivity.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/CordovaActivity.java b/lib/cordova-android/framework/src/org/apache/cordova/CordovaActivity.java
new file mode 100755
index 0000000..6e3d99d
--- /dev/null
+++ b/lib/cordova-android/framework/src/org/apache/cordova/CordovaActivity.java
@@ -0,0 +1,1158 @@
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+*/
+package org.apache.cordova;
+
+import java.util.HashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import org.apache.cordova.api.CordovaInterface;
+import org.apache.cordova.api.CordovaPlugin;
+import org.apache.cordova.api.LOG;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.ProgressDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.res.Configuration;
+import android.graphics.Color;
+import android.media.AudioManager;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Handler;
+import android.util.Log;
+import android.view.Display;
+import android.view.KeyEvent;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.Window;
+import android.view.WindowManager;
+import android.widget.ImageView;
+import android.webkit.ValueCallback;
+import android.webkit.WebViewClient;
+import android.widget.LinearLayout;
+
+/**
+ * This class is the main Android activity that represents the Cordova
+ * application. It should be extended by the user to load the specific
+ * html file that contains the application.
+ *
+ * As an example:
+ *
+ * package org.apache.cordova.examples;
+ * import android.app.Activity;
+ * import android.os.Bundle;
+ * import org.apache.cordova.*;
+ *
+ * public class Examples extends DroidGap {
+ * @Override
+ * public void onCreate(Bundle savedInstanceState) {
+ * super.onCreate(savedInstanceState);
+ *
+ * // Set properties for activity
+ * super.setStringProperty("loadingDialog", "Title,Message"); // show loading dialog
+ * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); // if error loading file in super.loadUrl().
+ *
+ * // Initialize activity
+ * super.init();
+ *
+ * // Clear cache if you want
+ * super.appView.clearCache(true);
+ *
+ * // Load your application
+ * super.setIntegerProperty("splashscreen", R.drawable.splash); // load splash.jpg image from the resource drawable directory
+ * super.loadUrl("file:///android_asset/www/index.html", 3000); // show splash screen 3 sec before loading app
+ * }
+ * }
+ *
+ * Properties: The application can be configured using the following properties:
+ *
+ * // Display a native loading dialog when loading app. Format for value = "Title,Message".
+ * // (String - default=null)
+ * super.setStringProperty("loadingDialog", "Wait,Loading Demo...");
+ *
+ * // Display a native loading dialog when loading sub-pages. Format for value = "Title,Message".
+ * // (String - default=null)
+ * super.setStringProperty("loadingPageDialog", "Loading page...");
+ *
+ * // Load a splash screen image from the resource drawable directory.
+ * // (Integer - default=0)
+ * super.setIntegerProperty("splashscreen", R.drawable.splash);
+ *
+ * // Set the background color.
+ * // (Integer - default=0 or BLACK)
+ * super.setIntegerProperty("backgroundColor", Color.WHITE);
+ *
+ * // Time in msec to wait before triggering a timeout error when loading
+ * // with super.loadUrl(). (Integer - default=20000)
+ * super.setIntegerProperty("loadUrlTimeoutValue", 60000);
+ *
+ * // URL to load if there's an error loading specified URL with loadUrl().
+ * // Should be a local URL starting with file://. (String - default=null)
+ * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html");
+ *
+ * // Enable app to keep running in background. (Boolean - default=true)
+ * super.setBooleanProperty("keepRunning", false);
+ *
+ * Cordova.xml configuration:
+ * Cordova uses a configuration file at res/xml/cordova.xml to specify the following settings.
+ *
+ * Approved list of URLs that can be loaded into DroidGap
+ * <access origin="http://server regexp" subdomains="true" />
+ * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR)
+ * <log level="DEBUG" />
+ *
+ * Cordova plugins:
+ * Cordova uses a file at res/xml/plugins.xml to list all plugins that are installed.
+ * Before using a new plugin, a new element must be added to the file.
+ * name attribute is the service name passed to Cordova.exec() in JavaScript
+ * value attribute is the Java class name to call.
+ *
+ * <plugins>
+ * <plugin name="App" value="org.apache.cordova.App"/>
+ * ...
+ * </plugins>
+ */
+public class CordovaActivity extends Activity implements CordovaInterface {
+ public static String TAG = "DroidGap";
+
+ // The webview for our app
+ protected CordovaWebView appView;
+ protected CordovaWebViewClient webViewClient;
+
+ protected LinearLayout root;
+ protected boolean cancelLoadUrl = false;
+ protected ProgressDialog spinnerDialog = null;
+ private final ExecutorService threadPool = Executors.newCachedThreadPool();
+
+
+ // The initial URL for our app
+ // ie http://server/path/index.html#abc?query
+ //private String url = null;
+
+ private static int ACTIVITY_STARTING = 0;
+ private static int ACTIVITY_RUNNING = 1;
+ private static int ACTIVITY_EXITING = 2;
+ private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down
+
+ // Plugin to call when activity result is received
+ protected CordovaPlugin activityResultCallback = null;
+ protected boolean activityResultKeepRunning;
+
+ // Default background color for activity
+ // (this is not the color for the webview, which is set in HTML)
+ private int backgroundColor = Color.BLACK;
+
+ /*
+ * The variables below are used to cache some of the activity properties.
+ */
+
+ // Draw a splash screen using an image located in the drawable resource directory.
+ // This is not the same as calling super.loadSplashscreen(url)
+ protected int splashscreen = 0;
+ protected int splashscreenTime = 3000;
+
+ // LoadUrl timeout value in msec (default of 20 sec)
+ protected int loadUrlTimeoutValue = 20000;
+
+ // Keep app running when pause is received. (default = true)
+ // If true, then the JavaScript and native code continue to run in the background
+ // when another application (activity) is started.
+ protected boolean keepRunning = true;
+
+ private int lastRequestCode;
+
+ private Object responseCode;
+
+ private Intent lastIntent;
+
+ private Object lastResponseCode;
+
+ private String initCallbackClass;
+
+ private Object LOG_TAG;
+
+ /**
+ * Sets the authentication token.
+ *
+ * @param authenticationToken
+ * @param host
+ * @param realm
+ */
+ public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) {
+ if (this.appView != null && this.appView.viewClient != null) {
+ this.appView.viewClient.setAuthenticationToken(authenticationToken, host, realm);
+ }
+ }
+
+ /**
+ * Removes the authentication token.
+ *
+ * @param host
+ * @param realm
+ *
+ * @return the authentication token or null if did not exist
+ */
+ public AuthenticationToken removeAuthenticationToken(String host, String realm) {
+ if (this.appView != null && this.appView.viewClient != null) {
+ return this.appView.viewClient.removeAuthenticationToken(host, realm);
+ }
+ return null;
+ }
+
+ /**
+ * Gets the authentication token.
+ *
+ * In order it tries:
+ * 1- host + realm
+ * 2- host
+ * 3- realm
+ * 4- no host, no realm
+ *
+ * @param host
+ * @param realm
+ *
+ * @return the authentication token
+ */
+ public AuthenticationToken getAuthenticationToken(String host, String realm) {
+ if (this.appView != null && this.appView.viewClient != null) {
+ return this.appView.viewClient.getAuthenticationToken(host, realm);
+ }
+ return null;
+ }
+
+ /**
+ * Clear all authentication tokens.
+ */
+ public void clearAuthenticationTokens() {
+ if (this.appView != null && this.appView.viewClient != null) {
+ this.appView.viewClient.clearAuthenticationTokens();
+ }
+ }
+
+ /**
+ * Called when the activity is first created.
+ *
+ * @param savedInstanceState
+ */
+ @SuppressWarnings("deprecation")
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ Config.init(this);
+ LOG.d(TAG, "DroidGap.onCreate()");
+ super.onCreate(savedInstanceState);
+
+ if(savedInstanceState != null)
+ {
+ initCallbackClass = savedInstanceState.getString("callbackClass");
+ }
+
+ if(!this.getBooleanProperty("showTitle", false))
+ {
+ getWindow().requestFeature(Window.FEATURE_NO_TITLE);
+ }
+
+ if(this.getBooleanProperty("setFullscreen", false))
+ {
+ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
+ WindowManager.LayoutParams.FLAG_FULLSCREEN);
+ }
+ else
+ {
+ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
+ WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
+ }
+ // This builds the view. We could probably get away with NOT having a LinearLayout, but I like having a bucket!
+ Display display = getWindowManager().getDefaultDisplay();
+ int width = display.getWidth();
+ int height = display.getHeight();
+
+ root = new LinearLayoutSoftKeyboardDetect(this, width, height);
+ root.setOrientation(LinearLayout.VERTICAL);
+ root.setBackgroundColor(this.backgroundColor);
+ root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT, 0.0F));
+
+ // Setup the hardware volume controls to handle volume control
+ setVolumeControlStream(AudioManager.STREAM_MUSIC);
+ }
+
+ /**
+ * Get the Android activity.
+ *
+ * @return
+ */
+ public Activity getActivity() {
+ return this;
+ }
+
+ /**
+ * Create and initialize web container with default web view objects.
+ */
+ public void init() {
+ CordovaWebView webView = new CordovaWebView(CordovaActivity.this);
+ CordovaWebViewClient webViewClient;
+ if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
+ {
+ webViewClient = new CordovaWebViewClient(this, webView);
+ }
+ else
+ {
+ webViewClient = new IceCreamCordovaWebViewClient(this, webView);
+ }
+ this.init(webView, webViewClient, new CordovaChromeClient(this, webView));
+ }
+
+ /**
+ * Initialize web container with web view objects.
+ *
+ * @param webView
+ * @param webViewClient
+ * @param webChromeClient
+ */
+ @SuppressLint("NewApi")
+ public void init(CordovaWebView webView, CordovaWebViewClient webViewClient, CordovaChromeClient webChromeClient) {
+ LOG.d(TAG, "DroidGap.init()");
+
+ // Set up web container
+ this.appView = webView;
+ this.appView.setId(100);
+
+ this.appView.setWebViewClient(webViewClient);
+ this.appView.setWebChromeClient(webChromeClient);
+ webViewClient.setWebView(this.appView);
+ webChromeClient.setWebView(this.appView);
+
+ this.appView.setLayoutParams(new LinearLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ 1.0F));
+
+ if (this.getBooleanProperty("disallowOverscroll", false)) {
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
+ this.appView.setOverScrollMode(CordovaWebView.OVER_SCROLL_NEVER);
+ }
+ }
+
+ // Add web view but make it invisible while loading URL
+ this.appView.setVisibility(View.INVISIBLE);
+ this.root.addView(this.appView);
+ setContentView(this.root);
+
+ // Clear cancel flag
+ this.cancelLoadUrl = false;
+
+ }
+
+ /**
+ * Load the url into the webview.
+ *
+ * @param url
+ */
+ public void loadUrl(String url) {
+
+ // Init web view if not already done
+ if (this.appView == null) {
+ this.init();
+ }
+
+ // Set backgroundColor
+ this.backgroundColor = this.getIntegerProperty("backgroundColor", Color.BLACK);
+ this.root.setBackgroundColor(this.backgroundColor);
+
+ // If keepRunning
+ this.keepRunning = this.getBooleanProperty("keepRunning", true);
+
+ // Then load the spinner
+ this.loadSpinner();
+
+ this.appView.loadUrl(url);
+ }
+
+ /*
+ * Load the spinner
+ */
+ void loadSpinner() {
+
+ // If loadingDialog property, then show the App loading dialog for first page of app
+ String loading = null;
+ if ((this.appView == null) || !this.appView.canGoBack()) {
+ loading = this.getStringProperty("loadingDialog", null);
+ }
+ else {
+ loading = this.getStringProperty("loadingPageDialog", null);
+ }
+ if (loading != null) {
+
+ String title = "";
+ String message = "Loading Application...";
+
+ if (loading.length() > 0) {
+ int comma = loading.indexOf(',');
+ if (comma > 0) {
+ title = loading.substring(0, comma);
+ message = loading.substring(comma + 1);
+ }
+ else {
+ title = "";
+ message = loading;
+ }
+ }
+ this.spinnerStart(title, message);
+ }
+ }
+
+ /**
+ * Load the url into the webview after waiting for period of time.
+ * This is used to display the splashscreen for certain amount of time.
+ *
+ * @param url
+ * @param time The number of ms to wait before loading webview
+ */
+ public void loadUrl(final String url, int time) {
+
+ // Init web view if not already done
+ if (this.appView == null) {
+ this.init();
+ }
+
+ this.splashscreenTime = time;
+ this.splashscreen = this.getIntegerProperty("splashscreen", 0);
+ this.showSplashScreen(this.splashscreenTime);
+ this.appView.loadUrl(url, time);
+ }
+
+ /**
+ * Cancel loadUrl before it has been loaded.
+ */
+ // TODO NO-OP
+ @Deprecated
+ public void cancelLoadUrl() {
+ this.cancelLoadUrl = true;
+ }
+
+ /**
+ * Clear the resource cache.
+ */
+ public void clearCache() {
+ if (this.appView == null) {
+ this.init();
+ }
+ this.appView.clearCache(true);
+ }
+
+ /**
+ * Clear web history in this web view.
+ */
+ public void clearHistory() {
+ this.appView.clearHistory();
+ }
+
+ /**
+ * Go to previous page in history. (We manage our own history)
+ *
+ * @return true if we went back, false if we are already at top
+ */
+ public boolean backHistory() {
+ if (this.appView != null) {
+ return appView.backHistory();
+ }
+ return false;
+ }
+
+ @Override
+ /**
+ * Called by the system when the device configuration changes while your activity is running.
+ *
+ * @param Configuration newConfig
+ */
+ public void onConfigurationChanged(Configuration newConfig) {
+ //don't reload the current page when the orientation is changed
+ super.onConfigurationChanged(newConfig);
+ }
+
+ /**
+ * Get boolean property for activity.
+ *
+ * @param name
+ * @param defaultValue
+ * @return
+ */
+ public boolean getBooleanProperty(String name, boolean defaultValue) {
+ Bundle bundle = this.getIntent().getExtras();
+ if (bundle == null) {
+ return defaultValue;
+ }
+ Boolean p;
+ try {
+ p = (Boolean) bundle.get(name);
+ } catch (ClassCastException e) {
+ String s = bundle.get(name).toString();
+ if ("true".equals(s)) {
+ p = true;
+ }
+ else {
+ p = false;
+ }
+ }
+ if (p == null) {
+ return defaultValue;
+ }
+ return p.booleanValue();
+ }
+
+ /**
+ * Get int property for activity.
+ *
+ * @param name
+ * @param defaultValue
+ * @return
+ */
+ public int getIntegerProperty(String name, int defaultValue) {
+ Bundle bundle = this.getIntent().getExtras();
+ if (bundle == null) {
+ return defaultValue;
+ }
+ Integer p;
+ try {
+ p = (Integer) bundle.get(name);
+ } catch (ClassCastException e) {
+ p = Integer.parseInt(bundle.get(name).toString());
+ }
+ if (p == null) {
+ return defaultValue;
+ }
+ return p.intValue();
+ }
+
+ /**
+ * Get string property for activity.
+ *
+ * @param name
+ * @param defaultValue
+ * @return
+ */
+ public String getStringProperty(String name, String defaultValue) {
+ Bundle bundle = this.getIntent().getExtras();
+ if (bundle == null) {
+ return defaultValue;
+ }
+ String p = bundle.getString(name);
+ if (p == null) {
+ return defaultValue;
+ }
+ return p;
+ }
+
+ /**
+ * Get double property for activity.
+ *
+ * @param name
+ * @param defaultValue
+ * @return
+ */
+ public double getDoubleProperty(String name, double defaultValue) {
+ Bundle bundle = this.getIntent().getExtras();
+ if (bundle == null) {
+ return defaultValue;
+ }
+ Double p;
+ try {
+ p = (Double) bundle.get(name);
+ } catch (ClassCastException e) {
+ p = Double.parseDouble(bundle.get(name).toString());
+ }
+ if (p == null) {
+ return defaultValue;
+ }
+ return p.doubleValue();
+ }
+
+ /**
+ * Set boolean property on activity.
+ *
+ * @param name
+ * @param value
+ */
+ public void setBooleanProperty(String name, boolean value) {
+ Log.d(TAG, "Setting boolean properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml");
+ this.getIntent().putExtra(name, value);
+ }
+
+ /**
+ * Set int property on activity.
+ *
+ * @param name
+ * @param value
+ */
+ public void setIntegerProperty(String name, int value) {
+ Log.d(TAG, "Setting integer properties in DroidGap will be deprecated in 3.1 on August 2013, please use config.xml");
+ this.getIntent().putExtra(name, value);
+ }
+
+ /**
+ * Set string property on activity.
+ *
+ * @param name
+ * @param value
+ */
+ public void setStringProperty(String name, String value) {
+ Log.d(TAG, "Setting string properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml");
+ this.getIntent().putExtra(name, value);
+ }
+
+ /**
+ * Set double property on activity.
+ *
+ * @param name
+ * @param value
+ */
+ public void setDoubleProperty(String name, double value) {
+ Log.d(TAG, "Setting double properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml");
+ this.getIntent().putExtra(name, value);
+ }
+
+ @Override
+ /**
+ * Called when the system is about to start resuming a previous activity.
+ */
+ protected void onPause() {
+ super.onPause();
+
+ LOG.d(TAG, "Paused the application!");
+
+ // Don't process pause if shutting down, since onDestroy() will be called
+ if (this.activityState == ACTIVITY_EXITING) {
+ return;
+ }
+
+ if (this.appView == null) {
+ return;
+ }
+ else
+ {
+ this.appView.handlePause(this.keepRunning);
+ }
+
+ // hide the splash screen to avoid leaking a window
+ this.removeSplashScreen();
+ }
+
+ @Override
+ /**
+ * Called when the activity receives a new intent
+ **/
+ protected void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+ //Forward to plugins
+ if (this.appView != null)
+ this.appView.onNewIntent(intent);
+ }
+
+ @Override
+ /**
+ * Called when the activity will start interacting with the user.
+ */
+ protected void onResume() {
+ super.onResume();
+ //Reload the configuration
+ Config.init(this);
+
+ LOG.d(TAG, "Resuming the App");
+
+
+ //Code to test CB-3064
+ String errorUrl = this.getStringProperty("errorUrl", null);
+ LOG.d(TAG, "CB-3064: The errorUrl is " + errorUrl);
+
+ if (this.activityState == ACTIVITY_STARTING) {
+ this.activityState = ACTIVITY_RUNNING;
+ return;
+ }
+
+ if (this.appView == null) {
+ return;
+ }
+
+ this.appView.handleResume(this.keepRunning, this.activityResultKeepRunning);
+
+ // If app doesn't want to run in background
+ if (!this.keepRunning || this.activityResultKeepRunning) {
+
+ // Restore multitasking state
+ if (this.activityResultKeepRunning) {
+ this.keepRunning = this.activityResultKeepRunning;
+ this.activityResultKeepRunning = false;
+ }
+ }
+ }
+
+ @Override
+ /**
+ * The final call you receive before your activity is destroyed.
+ */
+ public void onDestroy() {
+ LOG.d(TAG, "onDestroy()");
+ super.onDestroy();
+
+ // hide the splash screen to avoid leaking a window
+ this.removeSplashScreen();
+
+ if (this.appView != null) {
+ appView.handleDestroy();
+ }
+ else {
+ this.activityState = ACTIVITY_EXITING;
+ }
+ }
+
+ /**
+ * Send a message to all plugins.
+ *
+ * @param id The message id
+ * @param data The message data
+ */
+ public void postMessage(String id, Object data) {
+ if (this.appView != null) {
+ this.appView.postMessage(id, data);
+ }
+ }
+
+ /**
+ * @deprecated
+ * Add services to res/xml/plugins.xml instead.
+ *
+ * Add a class that implements a service.
+ *
+ * @param serviceType
+ * @param className
+ */
+ public void addService(String serviceType, String className) {
+ if (this.appView != null && this.appView.pluginManager != null) {
+ this.appView.pluginManager.addService(serviceType, className);
+ }
+ }
+
+ /**
+ * Send JavaScript statement back to JavaScript.
+ * (This is a convenience method)
+ *
+ * @param message
+ */
+ public void sendJavascript(String statement) {
+ if (this.appView != null) {
+ this.appView.jsMessageQueue.addJavaScript(statement);
+ }
+ }
+
+ /**
+ * Show the spinner. Must be called from the UI thread.
+ *
+ * @param title Title of the dialog
+ * @param message The message of the dialog
+ */
+ public void spinnerStart(final String title, final String message) {
+ if (this.spinnerDialog != null) {
+ this.spinnerDialog.dismiss();
+ this.spinnerDialog = null;
+ }
+ final CordovaActivity me = this;
+ this.spinnerDialog = ProgressDialog.show(CordovaActivity.this, title, message, true, true,
+ new DialogInterface.OnCancelListener() {
+ public void onCancel(DialogInterface dialog) {
+ me.spinnerDialog = null;
+ }
+ });
+ }
+
+ /**
+ * Stop spinner - Must be called from UI thread
+ */
+ public void spinnerStop() {
+ if (this.spinnerDialog != null && this.spinnerDialog.isShowing()) {
+ this.spinnerDialog.dismiss();
+ this.spinnerDialog = null;
+ }
+ }
+
+ /**
+ * End this activity by calling finish for activity
+ */
+ public void endActivity() {
+ this.activityState = ACTIVITY_EXITING;
+ super.finish();
+ }
+
+
+ /**
+ * Launch an activity for which you would like a result when it finished. When this activity exits,
+ * your onActivityResult() method will be called.
+ *
+ * @param command The command object
+ * @param intent The intent to start
+ * @param requestCode The request code that is passed to callback to identify the activity
+ */
+ public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
+ this.activityResultCallback = command;
+ this.activityResultKeepRunning = this.keepRunning;
+
+ // If multitasking turned on, then disable it for activities that return results
+ if (command != null) {
+ this.keepRunning = false;
+ }
+
+ // Start activity
+ super.startActivityForResult(intent, requestCode);
+ }
+
+ @Override
+ /**
+ * Called when an activity you launched exits, giving you the requestCode you started it with,
+ * the resultCode it returned, and any additional data from it.
+ *
+ * @param requestCode The request code originally supplied to startActivityForResult(),
+ * allowing you to identify who this result came from.
+ * @param resultCode The integer result code returned by the child activity through its setResult().
+ * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
+ */
+ protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
+ LOG.d(TAG, "Incoming Result");
+ super.onActivityResult(requestCode, resultCode, intent);
+ Log.d(TAG, "Request code = " + requestCode);
+ ValueCallback<Uri> mUploadMessage = this.appView.getWebChromeClient().getValueCallback();
+ if (requestCode == CordovaChromeClient.FILECHOOSER_RESULTCODE) {
+ Log.d(TAG, "did we get here?");
+ if (null == mUploadMessage)
+ return;
+ Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
+ Log.d(TAG, "result = " + result);
+// Uri filepath = Uri.parse("file://" + FileUtils.getRealPathFromURI(result, this));
+// Log.d(TAG, "result = " + filepath);
+ mUploadMessage.onReceiveValue(result);
+ mUploadMessage = null;
+ }
+ CordovaPlugin callback = this.activityResultCallback;
+ if(callback == null)
+ {
+ if(initCallbackClass != null)
+ {
+ this.activityResultCallback = appView.pluginManager.getPlugin(initCallbackClass);
+ callback = activityResultCallback;
+ LOG.d(TAG, "We have a callback to send this result to");
+ callback.onActivityResult(requestCode, resultCode, intent);
+ }
+ }
+ else
+ {
+ LOG.d(TAG, "We have a callback to send this result to");
+ callback.onActivityResult(requestCode, resultCode, intent);
+ }
+ }
+
+ public void setActivityResultCallback(CordovaPlugin plugin) {
+ this.activityResultCallback = plugin;
+ }
+
+ /**
+ * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
+ * The errorCode parameter corresponds to one of the ERROR_* constants.
+ *
+ * @param errorCode The error code corresponding to an ERROR_* value.
+ * @param description A String describing the error.
+ * @param failingUrl The url that failed to load.
+ */
+ public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
+ final CordovaActivity me = this;
+
+ // If errorUrl specified, then load it
+ final String errorUrl = me.getStringProperty("errorUrl", null);
+ if ((errorUrl != null) && (errorUrl.startsWith("file://") || Config.isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) {
+
+ // Load URL on UI thread
+ me.runOnUiThread(new Runnable() {
+ public void run() {
+ // Stop "app loading" spinner if showing
+ me.spinnerStop();
+ me.appView.showWebPage(errorUrl, false, true, null);
+ }
+ });
+ }
+ // If not, then display error dialog
+ else {
+ final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
+ me.runOnUiThread(new Runnable() {
+ public void run() {
+ if (exit) {
+ me.appView.setVisibility(View.GONE);
+ me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
+ }
+ }
+ });
+ }
+ }
+
+ /**
+ * Display an error dialog and optionally exit application.
+ *
+ * @param title
+ * @param message
+ * @param button
+ * @param exit
+ */
+ public void displayError(final String title, final String message, final String button, final boolean exit) {
+ final CordovaActivity me = this;
+ me.runOnUiThread(new Runnable() {
+ public void run() {
+ try {
+ AlertDialog.Builder dlg = new AlertDialog.Builder(me);
+ dlg.setMessage(message);
+ dlg.setTitle(title);
+ dlg.setCancelable(false);
+ dlg.setPositiveButton(button,
+ new AlertDialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.dismiss();
+ if (exit) {
+ me.endActivity();
+ }
+ }
+ });
+ dlg.create();
+ dlg.show();
+ } catch (Exception e) {
+ finish();
+ }
+ }
+ });
+ }
+
+ /**
+ * Determine if URL is in approved list of URLs to load.
+ *
+ * @param url
+ * @return
+ */
+ public boolean isUrlWhiteListed(String url) {
+ return Config.isUrlWhiteListed(url);
+ }
+
+ /*
+ * Hook in DroidGap for menu plugins
+ *
+ */
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ this.postMessage("onCreateOptionsMenu", menu);
+ return super.onCreateOptionsMenu(menu);
+ }
+
+ @Override
+ public boolean onPrepareOptionsMenu(Menu menu) {
+ this.postMessage("onPrepareOptionsMenu", menu);
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ this.postMessage("onOptionsItemSelected", item);
+ return true;
+ }
+
+ /**
+ * Get Activity context.
+ *
+ * @return
+ */
+ public Context getContext() {
+ LOG.d(TAG, "This will be deprecated December 2012");
+ return this;
+ }
+
+ /**
+ * Load the specified URL in the Cordova webview or a new browser instance.
+ *
+ * NOTE: If openExternal is false, only URLs listed in whitelist can be loaded.
+ *
+ * @param url The url to load.
+ * @param openExternal Load url in browser instead of Cordova webview.
+ * @param clearHistory Clear the history stack, so new page becomes top of history
+ * @param params DroidGap parameters for new app
+ */
+ public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) {
+ if (this.appView != null) {
+ appView.showWebPage(url, openExternal, clearHistory, params);
+ }
+ }
+
+ protected Dialog splashDialog;
+
+ /**
+ * Removes the Dialog that displays the splash screen
+ */
+ public void removeSplashScreen() {
+ if (splashDialog != null && splashDialog.isShowing()) {
+ splashDialog.dismiss();
+ splashDialog = null;
+ }
+ }
+
+ /**
+ * Shows the splash screen over the full Activity
+ */
+ @SuppressWarnings("deprecation")
+ protected void showSplashScreen(final int time) {
+ final CordovaActivity that = this;
+
+ Runnable runnable = new Runnable() {
+ public void run() {
+ // Get reference to display
+ Display display = getWindowManager().getDefaultDisplay();
+
+ // Create the layout for the dialog
+ LinearLayout root = new LinearLayout(that.getActivity());
+ root.setMinimumHeight(display.getHeight());
+ root.setMinimumWidth(display.getWidth());
+ root.setOrientation(LinearLayout.VERTICAL);
+ root.setBackgroundColor(that.getIntegerProperty("backgroundColor", Color.BLACK));
+ root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
+ ViewGroup.LayoutParams.FILL_PARENT, 0.0F));
+ root.setBackgroundResource(that.splashscreen);
+
+ // Create and show the dialog
+ splashDialog = new Dialog(that, android.R.style.Theme_Translucent_NoTitleBar);
+ // check to see if the splash screen should be full screen
+ if ((getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN)
+ == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
+ splashDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
+ WindowManager.LayoutParams.FLAG_FULLSCREEN);
+ }
+ splashDialog.setContentView(root);
+ splashDialog.setCancelable(false);
+ splashDialog.show();
+
+ // Set Runnable to remove splash screen just in case
+ final Handler handler = new Handler();
+ handler.postDelayed(new Runnable() {
+ public void run() {
+ removeSplashScreen();
+ }
+ }, time);
+ }
+ };
+ this.runOnUiThread(runnable);
+ }
+
+ @Override
+ public boolean onKeyUp(int keyCode, KeyEvent event)
+ {
+ //Get whatever has focus!
+ View childView = appView.getFocusedChild();
+ if ((appView.isCustomViewShowing() || childView != null ) &&
+ (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) {
+ return appView.onKeyUp(keyCode, event);
+ } else {
+ return super.onKeyUp(keyCode, event);
+ }
+ }
+
+ /*
+ * Android 2.x needs to be able to check where the cursor is. Android 4.x does not
+ *
+ * (non-Javadoc)
+ * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
+ */
+
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event)
+ {
+ //Get whatever has focus!
+ View childView = appView.getFocusedChild();
+ //Determine if the focus is on the current view or not
+ if (childView != null && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) {
+ return appView.onKeyDown(keyCode, event);
+ }
+ else
+ return super.onKeyDown(keyCode, event);
+ }
+
+
+ /**
+ * Called when a message is sent to plugin.
+ *
+ * @param id The message id
+ * @param data The message data
+ * @return Object or null
+ */
+ public Object onMessage(String id, Object data) {
+ LOG.d(TAG, "onMessage(" + id + "," + data + ")");
+ if ("splashscreen".equals(id)) {
+ if ("hide".equals(data.toString())) {
+ this.removeSplashScreen();
+ }
+ else {
+ // If the splash dialog is showing don't try to show it again
+ if (this.splashDialog == null || !this.splashDialog.isShowing()) {
+ this.splashscreen = this.getIntegerProperty("splashscreen", 0);
+ this.showSplashScreen(this.splashscreenTime);
+ }
+ }
+ }
+ else if ("spinner".equals(id)) {
+ if ("stop".equals(data.toString())) {
+ this.spinnerStop();
+ this.appView.setVisibility(View.VISIBLE);
+ }
+ }
+ else if ("onReceivedError".equals(id)) {
+ JSONObject d = (JSONObject) data;
+ try {
+ this.onReceivedError(d.getInt("errorCode"), d.getString("description"), d.getString("url"));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+ else if ("exit".equals(id)) {
+ this.endActivity();
+ }
+ return null;
+ }
+
+ public ExecutorService getThreadPool() {
+ return threadPool;
+ }
+
+ protected void onSaveInstanceState(Bundle outState)
+ {
+ super.onSaveInstanceState(outState);
+ if(this.activityResultCallback != null)
+ {
+ String cClass = this.activityResultCallback.getClass().getName();
+ outState.putString("callbackClass", cClass);
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/CordovaChromeClient.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/CordovaChromeClient.java b/lib/cordova-android/framework/src/org/apache/cordova/CordovaChromeClient.java
index fb6d45f..d9da6ba 100755
--- a/lib/cordova-android/framework/src/org/apache/cordova/CordovaChromeClient.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/CordovaChromeClient.java
@@ -322,8 +322,8 @@ public class CordovaChromeClient extends WebChromeClient {
public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{
if (consoleMessage.message() != null)
- LOG.d(TAG, consoleMessage.message());
- return super.onConsoleMessage(consoleMessage);
+ LOG.d(TAG, "%s: Line %d : %s" , consoleMessage.sourceId() , consoleMessage.lineNumber(), consoleMessage.message());
+ return super.onConsoleMessage(consoleMessage);
}
@Override
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/CordovaWebView.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/CordovaWebView.java b/lib/cordova-android/framework/src/org/apache/cordova/CordovaWebView.java
index 5dd061e..c57cd50 100755
--- a/lib/cordova-android/framework/src/org/apache/cordova/CordovaWebView.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/CordovaWebView.java
@@ -672,8 +672,10 @@ public class CordovaWebView extends WebView {
InputMethodManager imm = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(childView.getWindowToken(), 0);
cordova.getActivity().openOptionsMenu();
+ return true;
+ } else {
+ return super.onKeyDown(keyCode, event);
}
- return true;
}
return super.onKeyDown(keyCode, event);
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/Device.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/Device.java b/lib/cordova-android/framework/src/org/apache/cordova/Device.java
index dd3bdd4..ff7d118 100644
--- a/lib/cordova-android/framework/src/org/apache/cordova/Device.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/Device.java
@@ -38,7 +38,7 @@ import android.telephony.TelephonyManager;
public class Device extends CordovaPlugin {
public static final String TAG = "Device";
- public static String cordovaVersion = "2.7.0"; // Cordova version
+ public static String cordovaVersion = "2.8.0rc1"; // Cordova version
public static String platform = "Android"; // Device OS
public static String uuid; // Device UUID
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/DroidGap.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/DroidGap.java b/lib/cordova-android/framework/src/org/apache/cordova/DroidGap.java
old mode 100755
new mode 100644
index bb895e2..fbaf6c4
--- a/lib/cordova-android/framework/src/org/apache/cordova/DroidGap.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/DroidGap.java
@@ -16,1141 +16,11 @@
specific language governing permissions and limitations
under the License.
*/
-package org.apache.cordova;
-
-import java.util.HashMap;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-import org.apache.cordova.api.CordovaInterface;
-import org.apache.cordova.api.CordovaPlugin;
-import org.apache.cordova.api.LOG;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import android.annotation.SuppressLint;
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.Dialog;
-import android.app.ProgressDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.res.Configuration;
-import android.graphics.Color;
-import android.media.AudioManager;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Handler;
-import android.util.Log;
-import android.view.Display;
-import android.view.KeyEvent;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.Window;
-import android.view.WindowManager;
-import android.widget.ImageView;
-import android.webkit.ValueCallback;
-import android.webkit.WebViewClient;
-import android.widget.LinearLayout;
-
-/**
- * This class is the main Android activity that represents the Cordova
- * application. It should be extended by the user to load the specific
- * html file that contains the application.
- *
- * As an example:
- *
- * package org.apache.cordova.examples;
- * import android.app.Activity;
- * import android.os.Bundle;
- * import org.apache.cordova.*;
- *
- * public class Examples extends DroidGap {
- * @Override
- * public void onCreate(Bundle savedInstanceState) {
- * super.onCreate(savedInstanceState);
- *
- * // Set properties for activity
- * super.setStringProperty("loadingDialog", "Title,Message"); // show loading dialog
- * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); // if error loading file in super.loadUrl().
- *
- * // Initialize activity
- * super.init();
- *
- * // Clear cache if you want
- * super.appView.clearCache(true);
- *
- * // Load your application
- * super.setIntegerProperty("splashscreen", R.drawable.splash); // load splash.jpg image from the resource drawable directory
- * super.loadUrl("file:///android_asset/www/index.html", 3000); // show splash screen 3 sec before loading app
- * }
- * }
- *
- * Properties: The application can be configured using the following properties:
- *
- * // Display a native loading dialog when loading app. Format for value = "Title,Message".
- * // (String - default=null)
- * super.setStringProperty("loadingDialog", "Wait,Loading Demo...");
- *
- * // Display a native loading dialog when loading sub-pages. Format for value = "Title,Message".
- * // (String - default=null)
- * super.setStringProperty("loadingPageDialog", "Loading page...");
- *
- * // Load a splash screen image from the resource drawable directory.
- * // (Integer - default=0)
- * super.setIntegerProperty("splashscreen", R.drawable.splash);
- *
- * // Set the background color.
- * // (Integer - default=0 or BLACK)
- * super.setIntegerProperty("backgroundColor", Color.WHITE);
- *
- * // Time in msec to wait before triggering a timeout error when loading
- * // with super.loadUrl(). (Integer - default=20000)
- * super.setIntegerProperty("loadUrlTimeoutValue", 60000);
- *
- * // URL to load if there's an error loading specified URL with loadUrl().
- * // Should be a local URL starting with file://. (String - default=null)
- * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html");
- *
- * // Enable app to keep running in background. (Boolean - default=true)
- * super.setBooleanProperty("keepRunning", false);
- *
- * Cordova.xml configuration:
- * Cordova uses a configuration file at res/xml/cordova.xml to specify the following settings.
- *
- * Approved list of URLs that can be loaded into DroidGap
- * <access origin="http://server regexp" subdomains="true" />
- * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR)
- * <log level="DEBUG" />
- *
- * Cordova plugins:
- * Cordova uses a file at res/xml/plugins.xml to list all plugins that are installed.
- * Before using a new plugin, a new element must be added to the file.
- * name attribute is the service name passed to Cordova.exec() in JavaScript
- * value attribute is the Java class name to call.
- *
- * <plugins>
- * <plugin name="App" value="org.apache.cordova.App"/>
- * ...
- * </plugins>
- */
-public class DroidGap extends Activity implements CordovaInterface {
- public static String TAG = "DroidGap";
-
- // The webview for our app
- protected CordovaWebView appView;
- protected CordovaWebViewClient webViewClient;
-
- protected LinearLayout root;
- protected boolean cancelLoadUrl = false;
- protected ProgressDialog spinnerDialog = null;
- private final ExecutorService threadPool = Executors.newCachedThreadPool();
-
-
- // The initial URL for our app
- // ie http://server/path/index.html#abc?query
- //private String url = null;
-
- private static int ACTIVITY_STARTING = 0;
- private static int ACTIVITY_RUNNING = 1;
- private static int ACTIVITY_EXITING = 2;
- private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down
-
- // Plugin to call when activity result is received
- protected CordovaPlugin activityResultCallback = null;
- protected boolean activityResultKeepRunning;
-
- // Default background color for activity
- // (this is not the color for the webview, which is set in HTML)
- private int backgroundColor = Color.BLACK;
-
- /*
- * The variables below are used to cache some of the activity properties.
- */
-
- // Draw a splash screen using an image located in the drawable resource directory.
- // This is not the same as calling super.loadSplashscreen(url)
- protected int splashscreen = 0;
- protected int splashscreenTime = 3000;
-
- // LoadUrl timeout value in msec (default of 20 sec)
- protected int loadUrlTimeoutValue = 20000;
-
- // Keep app running when pause is received. (default = true)
- // If true, then the JavaScript and native code continue to run in the background
- // when another application (activity) is started.
- protected boolean keepRunning = true;
-
- private int lastRequestCode;
-
- private Object responseCode;
-
- private Intent lastIntent;
-
- private Object lastResponseCode;
-
- private String initCallbackClass;
-
- private Object LOG_TAG;
-
- /**
- * Sets the authentication token.
- *
- * @param authenticationToken
- * @param host
- * @param realm
- */
- public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) {
- if (this.appView != null && this.appView.viewClient != null) {
- this.appView.viewClient.setAuthenticationToken(authenticationToken, host, realm);
- }
- }
-
- /**
- * Removes the authentication token.
- *
- * @param host
- * @param realm
- *
- * @return the authentication token or null if did not exist
- */
- public AuthenticationToken removeAuthenticationToken(String host, String realm) {
- if (this.appView != null && this.appView.viewClient != null) {
- return this.appView.viewClient.removeAuthenticationToken(host, realm);
- }
- return null;
- }
-
- /**
- * Gets the authentication token.
- *
- * In order it tries:
- * 1- host + realm
- * 2- host
- * 3- realm
- * 4- no host, no realm
- *
- * @param host
- * @param realm
- *
- * @return the authentication token
- */
- public AuthenticationToken getAuthenticationToken(String host, String realm) {
- if (this.appView != null && this.appView.viewClient != null) {
- return this.appView.viewClient.getAuthenticationToken(host, realm);
- }
- return null;
- }
-
- /**
- * Clear all authentication tokens.
- */
- public void clearAuthenticationTokens() {
- if (this.appView != null && this.appView.viewClient != null) {
- this.appView.viewClient.clearAuthenticationTokens();
- }
- }
-
- /**
- * Called when the activity is first created.
- *
- * @param savedInstanceState
- */
- @SuppressWarnings("deprecation")
- @Override
- public void onCreate(Bundle savedInstanceState) {
- Config.init(this);
- LOG.d(TAG, "DroidGap.onCreate()");
- super.onCreate(savedInstanceState);
-
- if(savedInstanceState != null)
- {
- initCallbackClass = savedInstanceState.getString("callbackClass");
- }
-
- if(!this.getBooleanProperty("showTitle", false))
- {
- getWindow().requestFeature(Window.FEATURE_NO_TITLE);
- }
-
- if(this.getBooleanProperty("setFullscreen", false))
- {
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);
- }
- else
- {
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
- }
- // This builds the view. We could probably get away with NOT having a LinearLayout, but I like having a bucket!
- Display display = getWindowManager().getDefaultDisplay();
- int width = display.getWidth();
- int height = display.getHeight();
-
- root = new LinearLayoutSoftKeyboardDetect(this, width, height);
- root.setOrientation(LinearLayout.VERTICAL);
- root.setBackgroundColor(this.backgroundColor);
- root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
- ViewGroup.LayoutParams.MATCH_PARENT, 0.0F));
-
- // Setup the hardware volume controls to handle volume control
- setVolumeControlStream(AudioManager.STREAM_MUSIC);
- }
-
- /**
- * Get the Android activity.
- *
- * @return
- */
- public Activity getActivity() {
- return this;
- }
-
- /**
- * Create and initialize web container with default web view objects.
- */
- public void init() {
- CordovaWebView webView = new CordovaWebView(DroidGap.this);
- CordovaWebViewClient webViewClient;
- if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
- {
- webViewClient = new CordovaWebViewClient(this, webView);
- }
- else
- {
- webViewClient = new IceCreamCordovaWebViewClient(this, webView);
- }
- this.init(webView, webViewClient, new CordovaChromeClient(this, webView));
- }
-
- /**
- * Initialize web container with web view objects.
- *
- * @param webView
- * @param webViewClient
- * @param webChromeClient
- */
- @SuppressLint("NewApi")
- public void init(CordovaWebView webView, CordovaWebViewClient webViewClient, CordovaChromeClient webChromeClient) {
- LOG.d(TAG, "DroidGap.init()");
-
- // Set up web container
- this.appView = webView;
- this.appView.setId(100);
-
- this.appView.setWebViewClient(webViewClient);
- this.appView.setWebChromeClient(webChromeClient);
- webViewClient.setWebView(this.appView);
- webChromeClient.setWebView(this.appView);
-
- this.appView.setLayoutParams(new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.MATCH_PARENT,
- ViewGroup.LayoutParams.MATCH_PARENT,
- 1.0F));
-
- if (this.getBooleanProperty("disallowOverscroll", false)) {
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
- this.appView.setOverScrollMode(CordovaWebView.OVER_SCROLL_NEVER);
- }
- }
-
- // Add web view but make it invisible while loading URL
- this.appView.setVisibility(View.INVISIBLE);
- this.root.addView(this.appView);
- setContentView(this.root);
-
- // Clear cancel flag
- this.cancelLoadUrl = false;
-
- }
-
- /**
- * Load the url into the webview.
- *
- * @param url
- */
- public void loadUrl(String url) {
-
- // Init web view if not already done
- if (this.appView == null) {
- this.init();
- }
-
- // Set backgroundColor
- this.backgroundColor = this.getIntegerProperty("backgroundColor", Color.BLACK);
- this.root.setBackgroundColor(this.backgroundColor);
-
- // If keepRunning
- this.keepRunning = this.getBooleanProperty("keepRunning", true);
-
- // Then load the spinner
- this.loadSpinner();
-
- this.appView.loadUrl(url);
- }
-
- /*
- * Load the spinner
- */
- void loadSpinner() {
-
- // If loadingDialog property, then show the App loading dialog for first page of app
- String loading = null;
- if ((this.appView == null) || !this.appView.canGoBack()) {
- loading = this.getStringProperty("loadingDialog", null);
- }
- else {
- loading = this.getStringProperty("loadingPageDialog", null);
- }
- if (loading != null) {
-
- String title = "";
- String message = "Loading Application...";
-
- if (loading.length() > 0) {
- int comma = loading.indexOf(',');
- if (comma > 0) {
- title = loading.substring(0, comma);
- message = loading.substring(comma + 1);
- }
- else {
- title = "";
- message = loading;
- }
- }
- this.spinnerStart(title, message);
- }
- }
-
- /**
- * Load the url into the webview after waiting for period of time.
- * This is used to display the splashscreen for certain amount of time.
- *
- * @param url
- * @param time The number of ms to wait before loading webview
- */
- public void loadUrl(final String url, int time) {
-
- // Init web view if not already done
- if (this.appView == null) {
- this.init();
- }
-
- this.splashscreenTime = time;
- this.splashscreen = this.getIntegerProperty("splashscreen", 0);
- this.showSplashScreen(this.splashscreenTime);
- this.appView.loadUrl(url, time);
- }
-
- /**
- * Cancel loadUrl before it has been loaded.
- */
- // TODO NO-OP
- @Deprecated
- public void cancelLoadUrl() {
- this.cancelLoadUrl = true;
- }
-
- /**
- * Clear the resource cache.
- */
- public void clearCache() {
- if (this.appView == null) {
- this.init();
- }
- this.appView.clearCache(true);
- }
- /**
- * Clear web history in this web view.
- */
- public void clearHistory() {
- this.appView.clearHistory();
- }
+// We moved everything to CordovaActivity
- /**
- * Go to previous page in history. (We manage our own history)
- *
- * @return true if we went back, false if we are already at top
- */
- public boolean backHistory() {
- if (this.appView != null) {
- return appView.backHistory();
- }
- return false;
- }
-
- @Override
- /**
- * Called by the system when the device configuration changes while your activity is running.
- *
- * @param Configuration newConfig
- */
- public void onConfigurationChanged(Configuration newConfig) {
- //don't reload the current page when the orientation is changed
- super.onConfigurationChanged(newConfig);
- }
-
- /**
- * Get boolean property for activity.
- *
- * @param name
- * @param defaultValue
- * @return
- */
- public boolean getBooleanProperty(String name, boolean defaultValue) {
- Bundle bundle = this.getIntent().getExtras();
- if (bundle == null) {
- return defaultValue;
- }
- Boolean p;
- try {
- p = (Boolean) bundle.get(name);
- } catch (ClassCastException e) {
- String s = bundle.get(name).toString();
- if ("true".equals(s)) {
- p = true;
- }
- else {
- p = false;
- }
- }
- if (p == null) {
- return defaultValue;
- }
- return p.booleanValue();
- }
-
- /**
- * Get int property for activity.
- *
- * @param name
- * @param defaultValue
- * @return
- */
- public int getIntegerProperty(String name, int defaultValue) {
- Bundle bundle = this.getIntent().getExtras();
- if (bundle == null) {
- return defaultValue;
- }
- Integer p;
- try {
- p = (Integer) bundle.get(name);
- } catch (ClassCastException e) {
- p = Integer.parseInt(bundle.get(name).toString());
- }
- if (p == null) {
- return defaultValue;
- }
- return p.intValue();
- }
-
- /**
- * Get string property for activity.
- *
- * @param name
- * @param defaultValue
- * @return
- */
- public String getStringProperty(String name, String defaultValue) {
- Bundle bundle = this.getIntent().getExtras();
- if (bundle == null) {
- return defaultValue;
- }
- String p = bundle.getString(name);
- if (p == null) {
- return defaultValue;
- }
- return p;
- }
-
- /**
- * Get double property for activity.
- *
- * @param name
- * @param defaultValue
- * @return
- */
- public double getDoubleProperty(String name, double defaultValue) {
- Bundle bundle = this.getIntent().getExtras();
- if (bundle == null) {
- return defaultValue;
- }
- Double p;
- try {
- p = (Double) bundle.get(name);
- } catch (ClassCastException e) {
- p = Double.parseDouble(bundle.get(name).toString());
- }
- if (p == null) {
- return defaultValue;
- }
- return p.doubleValue();
- }
-
- /**
- * Set boolean property on activity.
- *
- * @param name
- * @param value
- */
- public void setBooleanProperty(String name, boolean value) {
- Log.d(TAG, "Setting boolean properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml");
- this.getIntent().putExtra(name, value);
- }
-
- /**
- * Set int property on activity.
- *
- * @param name
- * @param value
- */
- public void setIntegerProperty(String name, int value) {
- Log.d(TAG, "Setting integer properties in DroidGap will be deprecated in 3.1 on August 2013, please use config.xml");
- this.getIntent().putExtra(name, value);
- }
-
- /**
- * Set string property on activity.
- *
- * @param name
- * @param value
- */
- public void setStringProperty(String name, String value) {
- Log.d(TAG, "Setting string properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml");
- this.getIntent().putExtra(name, value);
- }
-
- /**
- * Set double property on activity.
- *
- * @param name
- * @param value
- */
- public void setDoubleProperty(String name, double value) {
- Log.d(TAG, "Setting double properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml");
- this.getIntent().putExtra(name, value);
- }
-
- @Override
- /**
- * Called when the system is about to start resuming a previous activity.
- */
- protected void onPause() {
- super.onPause();
-
- LOG.d(TAG, "Paused the application!");
-
- // Don't process pause if shutting down, since onDestroy() will be called
- if (this.activityState == ACTIVITY_EXITING) {
- return;
- }
-
- if (this.appView == null) {
- return;
- }
- else
- {
- this.appView.handlePause(this.keepRunning);
- }
-
- // hide the splash screen to avoid leaking a window
- this.removeSplashScreen();
- }
-
- @Override
- /**
- * Called when the activity receives a new intent
- **/
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- //Forward to plugins
- if (this.appView != null)
- this.appView.onNewIntent(intent);
- }
-
- @Override
- /**
- * Called when the activity will start interacting with the user.
- */
- protected void onResume() {
- super.onResume();
-
- LOG.d(TAG, "Resuming the App");
- if (this.activityState == ACTIVITY_STARTING) {
- this.activityState = ACTIVITY_RUNNING;
- return;
- }
-
- if (this.appView == null) {
- return;
- }
-
- this.appView.handleResume(this.keepRunning, this.activityResultKeepRunning);
-
- // If app doesn't want to run in background
- if (!this.keepRunning || this.activityResultKeepRunning) {
-
- // Restore multitasking state
- if (this.activityResultKeepRunning) {
- this.keepRunning = this.activityResultKeepRunning;
- this.activityResultKeepRunning = false;
- }
- }
- }
-
- @Override
- /**
- * The final call you receive before your activity is destroyed.
- */
- public void onDestroy() {
- LOG.d(TAG, "onDestroy()");
- super.onDestroy();
-
- // hide the splash screen to avoid leaking a window
- this.removeSplashScreen();
-
- if (this.appView != null) {
- appView.handleDestroy();
- }
- else {
- this.activityState = ACTIVITY_EXITING;
- }
- }
-
- /**
- * Send a message to all plugins.
- *
- * @param id The message id
- * @param data The message data
- */
- public void postMessage(String id, Object data) {
- if (this.appView != null) {
- this.appView.postMessage(id, data);
- }
- }
-
- /**
- * @deprecated
- * Add services to res/xml/plugins.xml instead.
- *
- * Add a class that implements a service.
- *
- * @param serviceType
- * @param className
- */
- public void addService(String serviceType, String className) {
- if (this.appView != null && this.appView.pluginManager != null) {
- this.appView.pluginManager.addService(serviceType, className);
- }
- }
-
- /**
- * Send JavaScript statement back to JavaScript.
- * (This is a convenience method)
- *
- * @param message
- */
- public void sendJavascript(String statement) {
- if (this.appView != null) {
- this.appView.jsMessageQueue.addJavaScript(statement);
- }
- }
-
- /**
- * Show the spinner. Must be called from the UI thread.
- *
- * @param title Title of the dialog
- * @param message The message of the dialog
- */
- public void spinnerStart(final String title, final String message) {
- if (this.spinnerDialog != null) {
- this.spinnerDialog.dismiss();
- this.spinnerDialog = null;
- }
- final DroidGap me = this;
- this.spinnerDialog = ProgressDialog.show(DroidGap.this, title, message, true, true,
- new DialogInterface.OnCancelListener() {
- public void onCancel(DialogInterface dialog) {
- me.spinnerDialog = null;
- }
- });
- }
-
- /**
- * Stop spinner - Must be called from UI thread
- */
- public void spinnerStop() {
- if (this.spinnerDialog != null && this.spinnerDialog.isShowing()) {
- this.spinnerDialog.dismiss();
- this.spinnerDialog = null;
- }
- }
-
- /**
- * End this activity by calling finish for activity
- */
- public void endActivity() {
- this.activityState = ACTIVITY_EXITING;
- super.finish();
- }
-
-
- /**
- * Launch an activity for which you would like a result when it finished. When this activity exits,
- * your onActivityResult() method will be called.
- *
- * @param command The command object
- * @param intent The intent to start
- * @param requestCode The request code that is passed to callback to identify the activity
- */
- public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
- this.activityResultCallback = command;
- this.activityResultKeepRunning = this.keepRunning;
-
- // If multitasking turned on, then disable it for activities that return results
- if (command != null) {
- this.keepRunning = false;
- }
-
- // Start activity
- super.startActivityForResult(intent, requestCode);
- }
-
- @Override
- /**
- * Called when an activity you launched exits, giving you the requestCode you started it with,
- * the resultCode it returned, and any additional data from it.
- *
- * @param requestCode The request code originally supplied to startActivityForResult(),
- * allowing you to identify who this result came from.
- * @param resultCode The integer result code returned by the child activity through its setResult().
- * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
- */
- protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
- LOG.d(TAG, "Incoming Result");
- super.onActivityResult(requestCode, resultCode, intent);
- Log.d(TAG, "Request code = " + requestCode);
- ValueCallback<Uri> mUploadMessage = this.appView.getWebChromeClient().getValueCallback();
- if (requestCode == CordovaChromeClient.FILECHOOSER_RESULTCODE) {
- Log.d(TAG, "did we get here?");
- if (null == mUploadMessage)
- return;
- Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
- Log.d(TAG, "result = " + result);
-// Uri filepath = Uri.parse("file://" + FileUtils.getRealPathFromURI(result, this));
-// Log.d(TAG, "result = " + filepath);
- mUploadMessage.onReceiveValue(result);
- mUploadMessage = null;
- }
- CordovaPlugin callback = this.activityResultCallback;
- if(callback == null)
- {
- if(initCallbackClass != null)
- {
- this.activityResultCallback = appView.pluginManager.getPlugin(initCallbackClass);
- callback = activityResultCallback;
- LOG.d(TAG, "We have a callback to send this result to");
- callback.onActivityResult(requestCode, resultCode, intent);
- }
- }
- else
- {
- LOG.d(TAG, "We have a callback to send this result to");
- callback.onActivityResult(requestCode, resultCode, intent);
- }
- }
-
- public void setActivityResultCallback(CordovaPlugin plugin) {
- this.activityResultCallback = plugin;
- }
-
- /**
- * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
- * The errorCode parameter corresponds to one of the ERROR_* constants.
- *
- * @param errorCode The error code corresponding to an ERROR_* value.
- * @param description A String describing the error.
- * @param failingUrl The url that failed to load.
- */
- public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
- final DroidGap me = this;
-
- // If errorUrl specified, then load it
- final String errorUrl = me.getStringProperty("errorUrl", null);
- if ((errorUrl != null) && (errorUrl.startsWith("file://") || Config.isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) {
-
- // Load URL on UI thread
- me.runOnUiThread(new Runnable() {
- public void run() {
- // Stop "app loading" spinner if showing
- me.spinnerStop();
- me.appView.showWebPage(errorUrl, false, true, null);
- }
- });
- }
- // If not, then display error dialog
- else {
- final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
- me.runOnUiThread(new Runnable() {
- public void run() {
- if (exit) {
- me.appView.setVisibility(View.GONE);
- me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
- }
- }
- });
- }
- }
-
- /**
- * Display an error dialog and optionally exit application.
- *
- * @param title
- * @param message
- * @param button
- * @param exit
- */
- public void displayError(final String title, final String message, final String button, final boolean exit) {
- final DroidGap me = this;
- me.runOnUiThread(new Runnable() {
- public void run() {
- try {
- AlertDialog.Builder dlg = new AlertDialog.Builder(me);
- dlg.setMessage(message);
- dlg.setTitle(title);
- dlg.setCancelable(false);
- dlg.setPositiveButton(button,
- new AlertDialog.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- if (exit) {
- me.endActivity();
- }
- }
- });
- dlg.create();
- dlg.show();
- } catch (Exception e) {
- finish();
- }
- }
- });
- }
-
- /**
- * Determine if URL is in approved list of URLs to load.
- *
- * @param url
- * @return
- */
- public boolean isUrlWhiteListed(String url) {
- return Config.isUrlWhiteListed(url);
- }
-
- /*
- * Hook in DroidGap for menu plugins
- *
- */
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- this.postMessage("onCreateOptionsMenu", menu);
- return super.onCreateOptionsMenu(menu);
- }
-
- @Override
- public boolean onPrepareOptionsMenu(Menu menu) {
- this.postMessage("onPrepareOptionsMenu", menu);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- this.postMessage("onOptionsItemSelected", item);
- return true;
- }
-
- /**
- * Get Activity context.
- *
- * @return
- */
- public Context getContext() {
- LOG.d(TAG, "This will be deprecated December 2012");
- return this;
- }
-
- /**
- * Load the specified URL in the Cordova webview or a new browser instance.
- *
- * NOTE: If openExternal is false, only URLs listed in whitelist can be loaded.
- *
- * @param url The url to load.
- * @param openExternal Load url in browser instead of Cordova webview.
- * @param clearHistory Clear the history stack, so new page becomes top of history
- * @param params DroidGap parameters for new app
- */
- public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) {
- if (this.appView != null) {
- appView.showWebPage(url, openExternal, clearHistory, params);
- }
- }
-
- protected Dialog splashDialog;
-
- /**
- * Removes the Dialog that displays the splash screen
- */
- public void removeSplashScreen() {
- if (splashDialog != null && splashDialog.isShowing()) {
- splashDialog.dismiss();
- splashDialog = null;
- }
- }
-
- /**
- * Shows the splash screen over the full Activity
- */
- @SuppressWarnings("deprecation")
- protected void showSplashScreen(final int time) {
- final DroidGap that = this;
-
- Runnable runnable = new Runnable() {
- public void run() {
- // Get reference to display
- Display display = getWindowManager().getDefaultDisplay();
-
- // Create the layout for the dialog
- LinearLayout root = new LinearLayout(that.getActivity());
- root.setMinimumHeight(display.getHeight());
- root.setMinimumWidth(display.getWidth());
- root.setOrientation(LinearLayout.VERTICAL);
- root.setBackgroundColor(that.getIntegerProperty("backgroundColor", Color.BLACK));
- root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
- ViewGroup.LayoutParams.FILL_PARENT, 0.0F));
- // We want the splashscreen to keep its ratio,
- // for this we need to use an ImageView and not simply the background of the LinearLayout
- ImageView splashscreenView = new ImageView(that.getActivity());
- splashscreenView.setImageResource(that.splashscreen);
- splashscreenView.setScaleType(ImageView.ScaleType.CENTER_CROP); // similar to the background-size:cover CSS property
- splashscreenView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
- root.addView(splashscreenView);
-
- // Create and show the dialog
- splashDialog = new Dialog(that, android.R.style.Theme_Translucent_NoTitleBar);
- // check to see if the splash screen should be full screen
- if ((getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN)
- == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
- splashDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);
- }
- splashDialog.setContentView(root);
- splashDialog.setCancelable(false);
- splashDialog.show();
-
- // Set Runnable to remove splash screen just in case
- final Handler handler = new Handler();
- handler.postDelayed(new Runnable() {
- public void run() {
- removeSplashScreen();
- }
- }, time);
- }
- };
- this.runOnUiThread(runnable);
- }
+package org.apache.cordova;
- @Override
- public boolean onKeyUp(int keyCode, KeyEvent event)
- {
- //Get whatever has focus!
- View childView = appView.getFocusedChild();
- if ((appView.isCustomViewShowing() || childView != null ) &&
- (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) {
- return appView.onKeyUp(keyCode, event);
- } else {
- return super.onKeyUp(keyCode, event);
- }
- }
-
- /*
- * Android 2.x needs to be able to check where the cursor is. Android 4.x does not
- *
- * (non-Javadoc)
- * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
- */
-
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event)
- {
- //Get whatever has focus!
- View childView = appView.getFocusedChild();
- //Determine if the focus is on the current view or not
- if (childView != null && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) {
- return appView.onKeyDown(keyCode, event);
- }
- else
- return super.onKeyDown(keyCode, event);
- }
-
-
- /**
- * Called when a message is sent to plugin.
- *
- * @param id The message id
- * @param data The message data
- * @return Object or null
- */
- public Object onMessage(String id, Object data) {
- LOG.d(TAG, "onMessage(" + id + "," + data + ")");
- if ("splashscreen".equals(id)) {
- if ("hide".equals(data.toString())) {
- this.removeSplashScreen();
- }
- else {
- // If the splash dialog is showing don't try to show it again
- if (this.splashDialog == null || !this.splashDialog.isShowing()) {
- this.splashscreen = this.getIntegerProperty("splashscreen", 0);
- this.showSplashScreen(this.splashscreenTime);
- }
- }
- }
- else if ("spinner".equals(id)) {
- if ("stop".equals(data.toString())) {
- this.spinnerStop();
- this.appView.setVisibility(View.VISIBLE);
- }
- }
- else if ("onReceivedError".equals(id)) {
- JSONObject d = (JSONObject) data;
- try {
- this.onReceivedError(d.getInt("errorCode"), d.getString("description"), d.getString("url"));
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- else if ("exit".equals(id)) {
- this.endActivity();
- }
- return null;
- }
+public class DroidGap extends CordovaActivity {
- public ExecutorService getThreadPool() {
- return threadPool;
- }
-
- protected void onSaveInstanceState(Bundle outState)
- {
- super.onSaveInstanceState(outState);
- if(this.activityResultCallback != null)
- {
- String cClass = this.activityResultCallback.getClass().getName();
- outState.putString("callbackClass", cClass);
- }
- }
}
-
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/org/apache/cordova/FileHelper.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/org/apache/cordova/FileHelper.java b/lib/cordova-android/framework/src/org/apache/cordova/FileHelper.java
index 8b446b0..8bc24aa 100644
--- a/lib/cordova-android/framework/src/org/apache/cordova/FileHelper.java
+++ b/lib/cordova-android/framework/src/org/apache/cordova/FileHelper.java
@@ -26,10 +26,11 @@ import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.LOG;
import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.net.URLConnection;
-import java.util.Locale;
+import java.io.OutputStream;
public class FileHelper {
private static final String LOG_TAG = "FileUtils";
@@ -90,16 +91,63 @@ public class FileHelper {
* @throws IOException
*/
public static InputStream getInputStreamFromUriString(String uriString, CordovaInterface cordova) throws IOException {
- if (uriString.startsWith("content")) {
+ if (uriString.startsWith("content:")) {
Uri uri = Uri.parse(uriString);
return cordova.getActivity().getContentResolver().openInputStream(uri);
} else if (uriString.startsWith("file:///android_asset/")) {
Uri uri = Uri.parse(uriString);
String relativePath = uri.getPath().substring(15);
return cordova.getActivity().getAssets().open(relativePath);
- } else {
+ } else if (uriString.startsWith("file://")) {
return new FileInputStream(getRealPath(uriString, cordova));
+ } else {
+ return null;
+ }
+ }
+
+ public static OutputStream getOutputStreamFromUriString(String uriString, CordovaInterface cordova) throws FileNotFoundException{
+ if (uriString.startsWith("content:")) {
+ Uri uri = Uri.parse(uriString);
+ return cordova.getActivity().getContentResolver().openOutputStream(uri);
+ } else if (uriString.startsWith("file:") && !uriString.startsWith("file:///android_asset/")) {
+ String realPath = uriString.substring(7);
+ return new FileOutputStream(realPath);
+ } else {
+ return null;
+ }
+ }
+ /**
+ * Returns whether the uri can be written to by openeing a File to that uri
+ *
+ * @param the URI to test
+ * @return boolean indicating whether the uri is writable
+ */
+ public static boolean isUriWritable(String uriString) {
+ String scheme = uriString.split(":")[0];
+
+ if(scheme.equals("file")){
+ // special case file
+ return !uriString.startsWith("file:///android_asset/");
+ }
+ return "content".equals(scheme);
+ }
+
+ /**
+ * Ensures the "file://" prefix exists for the given string
+ * If the given URI string already has a scheme, it is returned unchanged
+ *
+ * @param path - the path string to operate on
+ * @return a String with the "file://" scheme set
+ */
+ public static String insertFileProtocol(String path) {
+ if(!path.matches("^[a-z0-9+.-]+:.*")){
+ //Ensure it is not a relative path
+ if(!path.startsWith("/")){
+ throw new IllegalArgumentException("Relative paths" + path + "are not allowed.");
+ }
+ path = "file://" + path;
}
+ return path;
}
/**
[29/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/create.bat
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/create.bat b/lib/cordova-blackberry/bin/create.bat
index ecb039a..7b15594 100644
--- a/lib/cordova-blackberry/bin/create.bat
+++ b/lib/cordova-blackberry/bin/create.bat
@@ -18,16 +18,4 @@ goto comment
under the License.
:comment
-IF NOT DEFINED JAVA_HOME GOTO MISSING
-FOR %%X in (ant.bat) do (
- SET FOUND=%%~$PATH:X
- IF NOT DEFINED FOUND GOTO MISSING
-)
-cscript %~dp0\create.js %*
-GOTO END
-:MISSING
-ECHO Missing one of the following:
-ECHO JDK: http://java.oracle.com
-ECHO Apache ant: http://ant.apache.org
-EXIT /B 1
-:END
+node.exe %~dp0\create.js %*
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/create.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/create.js b/lib/cordova-blackberry/bin/create.js
index ac4b083..253c093 100644
--- a/lib/cordova-blackberry/bin/create.js
+++ b/lib/cordova-blackberry/bin/create.js
@@ -1,21 +1,21 @@
/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
/*
* create a cordova/blackberry project
@@ -24,106 +24,153 @@
* ./create [path package appname]
*/
-var fso = WScript.CreateObject('Scripting.FileSystemObject');
+var build,
+ path = require("path"),
+ fs = require("fs"),
+ wrench = require("wrench"),
+ utils = require(path.join(__dirname, 'lib/utils')),
+ version = getVersion(),
+ project_path = path.resolve(process.argv[2]),
+ app_id = process.argv[3],
+ bar_name = process.argv[4],
+ TARGETS = ["device", "simulator"],
+ TEMPLATE_PROJECT_DIR = path.join(__dirname, "templates", "project"),
+ MODULES_PROJECT_DIR = path.join(__dirname, "..", "node_modules"),
+ BOOTSTRAP_PROJECT_DIR = path.join(__dirname, "..", "framework", "bootstrap"),
+ FRAMEWORK_LIB_PROJECT_DIR = path.join(__dirname, "..", "framework", "lib"),
+ BUILD_DIR = path.join(__dirname, "build"),
+ CORDOVA_JS_SRC = path.join(__dirname, "..", "javascript", "cordova.blackberry10.js"),
+ update_dir = path.join(project_path, "lib", "cordova." + version),
+ native_dir = path.join(project_path, "native"),
+ js_path = "javascript",
+ js_basename = "cordova-" + version + ".js";
-function read(filename) {
- var fso=WScript.CreateObject("Scripting.FileSystemObject");
- var f=fso.OpenTextFile(filename, 1);
- var s=f.ReadAll();
- f.Close();
- return s;
+function getVersion() {
+ var version = fs.readFileSync(path.join(__dirname, "..", "VERSION"));
+ if (version) {
+ return version.toString().replace( /([^\x00-\xFF]|\s)*$/g, '' );
+ }
}
-function write(filename, contents) {
- var fso=WScript.CreateObject("Scripting.FileSystemObject");
- var f=fso.OpenTextFile(filename, 2, true);
- f.Write(contents);
- f.Close();
+
+function validPackageName(packageName) {
+ var domainRegex = /^[a-zA-Z]([a-zA-Z0-9])*(\.[a-zA-Z]([a-zA-Z0-9])*)*$/;
+ if (typeof packageName !== "undefined") {
+ if ((packageName.length > 50) || !domainRegex.test(packageName)) {
+ return false;
+ }
+ }
+ return true;
}
-function replaceInFile(filename, regexp, replacement) {
- write(filename, read(filename).replace(regexp, replacement));
+
+function validBarName(barName) {
+ var barNameRegex = /^[a-zA-Z0-9._\-]+$/;
+ return (typeof barName === "undefined") || barNameRegex.test(barName);
}
-function downloadAntContrib(){
- if (!fso.FileExists(ROOT + '\\bin\\templates\\project\\lib\\ant-contrib\\ant-contrib-1.0b3.jar')) {
- // We need the .jar
- var url = 'http://central.maven.org/maven2/ant-contrib/ant-contrib/1.0b3/ant-contrib-1.0b3.jar';
- var libsPath = ROOT + '\\bin\\templates\\project\\lib\\ant-contrib';
- var savePath = libsPath + '\\ant-contrib-1.0b3.jar';
- if (!fso.FileExists(savePath)) {
- if(!fso.FolderExists(libsPath)) {
- fso.CreateFolder(libsPath);
- }
- // We need the zip to get the jar
- var xhr = WScript.CreateObject('MSXML2.XMLHTTP');
- xhr.open('GET', url, false);
- xhr.send();
- if (xhr.status == 200) {
- var stream = WScript.CreateObject('ADODB.Stream');
- stream.Open();
- stream.Type = 1;
- stream.Write(xhr.ResponseBody);
- stream.Position = 0;
- stream.SaveToFile(savePath);
- stream.Close();
- } else {
- WScript.Echo('Could not retrieve the antcontrib. Please download it yourself and put into the bin/templates/project/lib directory. This process may fail now. Sorry.');
- }
- }
- var app = WScript.CreateObject('Shell.Application');
- var source = app.NameSpace(savePath).Items();
- var target = app.NameSpace(libsPath);
- target.CopyHere(source, 256);
+
+function validate() {
+ if (!project_path) {
+ throw "You must give a project PATH";
+ }
+ if (fs.existsSync(project_path)) {
+ throw "The project path must be an empty directory";
+ }
+ if (!validPackageName(app_id)) {
+ throw "App ID must be sequence of alpha-numeric (optionally seperated by '.') characters, no longer than 50 characters";
+ }
+ if (!validBarName(bar_name)) {
+ throw "BAR filename can only contain alpha-numeric, '.', '-' and '_' characters";
}
}
-function exec(s, output) {
- var o=shell.Exec(s);
- while (o.Status == 0) {
- WScript.Sleep(100);
+
+function clean() {
+ if (fs.existsSync(BUILD_DIR)) {
+ wrench.rmdirSyncRecursive(BUILD_DIR);
}
- //WScript.Echo("Command exited with code " + o.Status);
}
-function cleanup() {
- // Cleanup
- if(fso.FolderExists(ROOT + '\\dist')) {
- fso.DeleteFolder(ROOT + '\\dist', true);
+function copyJavascript() {
+ wrench.mkdirSyncRecursive(path.join(BUILD_DIR, js_path), 0777);
+ utils.copyFile(CORDOVA_JS_SRC, path.join(BUILD_DIR, js_path));
+
+ //rename copied cordova.blackberry10.js file
+ fs.renameSync(path.join(BUILD_DIR, js_path, "cordova.blackberry10.js"), path.join(BUILD_DIR, js_path, js_basename));
+}
+
+function copyFilesToProject() {
+ var nodeModulesDest = path.join(project_path, "cordova", "node_modules");
+
+ // create project using template directory
+ wrench.mkdirSyncRecursive(project_path, 0777);
+ wrench.copyDirSyncRecursive(TEMPLATE_PROJECT_DIR, project_path);
+
+ // change file permission for cordova scripts because ant copy doesn't preserve file permissions
+ wrench.chmodSyncRecursive(path.join(project_path,"cordova"), 0700);
+
+ //copy cordova-*version*.js to www
+ utils.copyFile(path.join(BUILD_DIR, js_path, js_basename), path.join(project_path, "www"));
+
+ //copy node modules to cordova build directory
+ wrench.mkdirSyncRecursive(nodeModulesDest, 0777);
+ wrench.copyDirSyncRecursive(MODULES_PROJECT_DIR, nodeModulesDest);
+ //change permissions of plugman
+ fs.chmodSync(path.join(nodeModulesDest, "plugman", "main.js"), 0755);
+
+ //copy framework bootstrap
+ TARGETS.forEach(function (target) {
+ var chromeDir = path.join(native_dir, target, "chrome"),
+ frameworkLibDir = path.join(chromeDir, "lib");
+
+ wrench.mkdirSyncRecursive(frameworkLibDir);
+ wrench.copyDirSyncRecursive(BOOTSTRAP_PROJECT_DIR, chromeDir);
+ wrench.copyDirSyncRecursive(FRAMEWORK_LIB_PROJECT_DIR, frameworkLibDir);
+ });
+
+ // save release
+ wrench.mkdirSyncRecursive(update_dir, 0777);
+ wrench.copyDirSyncRecursive(BUILD_DIR, update_dir);
+}
+
+function updateProject() {
+ var projectJson = require(path.resolve(path.join(project_path, "project.json"))),
+ configXMLPath = path.resolve(path.join(project_path, "www", "config.xml")),
+ xmlString;
+
+ if (typeof app_id !== "undefined") {
+ xmlString = fs.readFileSync(configXMLPath, "utf-8");
+ fs.writeFileSync(configXMLPath, xmlString.replace("default.app.id", app_id), "utf-8");
}
- if(fso.FolderExists(ROOT + '\\build')) {
- fso.DeleteFolder(ROOT + '\\build');
+
+ if (typeof bar_name !== "undefined") {
+ projectJson.barName = bar_name;
}
-}
-var args = WScript.Arguments, PROJECT_PATH="example",
- PACKAGE="org.apache.cordova.example",
- NAME="cordovaExample",
- shell=WScript.CreateObject("WScript.Shell");
-
-// working dir
-var ROOT = WScript.ScriptFullName.split('\\bin\\create.js').join('');
-
-if (args.Count() == 3) {
- PROJECT_PATH=args(0);
- PACKAGE=args(1);
- NAME=args(2);
+ projectJson.globalFetchDir = path.join(__dirname, "..", "plugins");
+
+ fs.writeFileSync(path.join(project_path, "project.json"), JSON.stringify(projectJson, null, 4) + "\n", "utf-8");
}
-if(fso.FolderExists(PROJECT_PATH)) {
- WScript.Echo("Project directory already exists! Please remove it first.");
- WScript.Quit(1);
+function installPlugins() {
+ var pluginScript = path.resolve(__dirname, "..", path.join(project_path, "cordova", "lib", "plugin.js"));
+ require(pluginScript).add(path.join(__dirname, "..", "plugins"));
}
-var MANIFEST_PATH=PROJECT_PATH+'\\www\\config.xml';
-var VERSION=read(ROOT+'\\VERSION').replace(/\r\n/,'').replace(/\n/,'');
-
-if(fso.FolderExists(ROOT+'\\framework')){
- downloadAntContrib();
- exec('ant.bat -f '+ ROOT +'\\build.xml create -Dproject.path="' + PROJECT_PATH + '"');
- replaceInFile(MANIFEST_PATH, /__PACKAGE__/, PACKAGE);
- replaceInFile(MANIFEST_PATH, /__ACTIVITY__/, NAME);
-}else{
- // copy in the project template
- exec('cmd /c xcopy '+ ROOT + '\\sample\\* '+PROJECT_PATH+' /I /S /Y');
- replaceInFile(MANIFEST_PATH, /org.apache.cordova.example/, PACKAGE);
- replaceInFile(MANIFEST_PATH, /cordovaExample/, NAME);
+if ( process.argv[2] === "-h" || process.argv[2] === "--help" ) {
+ console.log("\nUsage: create <project path> [package name [BAR filename]] \n");
+ console.log("Options: \n");
+ console.log(" -h, --help output usage information \n");
+} else {
+ try {
+ validate();
+ clean();
+ copyJavascript();
+ copyFilesToProject();
+ updateProject();
+ installPlugins();
+ clean();
+ process.exit();
+ } catch (ex) {
+ console.log("Project creation failed!\n" + "Error: " + ex);
+ process.exit(1);
+ }
}
-cleanup();
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/lib/localize.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/lib/localize.js b/lib/cordova-blackberry/bin/lib/localize.js
new file mode 100644
index 0000000..66bddfa
--- /dev/null
+++ b/lib/cordova-blackberry/bin/lib/localize.js
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var Localize = require("localize"),
+ loc = new Localize({
+ "SOME_WARNING": {
+ "en": "You have disabled all web security in this WebWorks application"
+ }
+ }, "", ""); // TODO maybe a bug in localize, must set default locale to "" in order get it to work
+
+loc.setLocale("en");
+
+module.exports = loc;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/lib/utils.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/lib/utils.js b/lib/cordova-blackberry/bin/lib/utils.js
new file mode 100644
index 0000000..88dc619
--- /dev/null
+++ b/lib/cordova-blackberry/bin/lib/utils.js
@@ -0,0 +1,167 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var fs = require('fs'),
+ path = require('path'),
+ wrench = require('wrench'),
+ localize = require("./localize"),
+ os = require('os'),
+ _self;
+
+function swapBytes(buffer) {
+ var l = buffer.length,
+ i,
+ a;
+
+ if (l % 2 === 0x01) {
+ throw localize.translate("EXCEPTION_BUFFER_ERROR");
+ }
+
+ for (i = 0; i < l; i += 2) {
+ a = buffer[i];
+ buffer[i] = buffer[i + 1];
+ buffer[i + 1] = a;
+ }
+
+ return buffer;
+}
+
+_self = {
+ writeFile: function (fileLocation, fileName, fileData) {
+ //If directory does not exist, create it.
+ if (!fs.existsSync(fileLocation)) {
+ wrench.mkdirSyncRecursive(fileLocation, "0755");
+ }
+
+ fs.writeFile(path.join(fileLocation, fileName), fileData, function (err) {
+ if (err) throw err;
+ });
+ },
+
+ copyFile: function (srcFile, destDir, baseDir) {
+ var filename = path.basename(srcFile),
+ fileBuffer = fs.readFileSync(srcFile),
+ fileLocation;
+
+ //if a base directory was provided, determine
+ //folder structure from the relative path of the base folder
+ if (baseDir && srcFile.indexOf(baseDir) === 0) {
+ fileLocation = srcFile.replace(baseDir, destDir);
+ wrench.mkdirSyncRecursive(path.dirname(fileLocation), "0755");
+ fs.writeFileSync(fileLocation, fileBuffer);
+ } else {
+ if (!fs.existsSync(destDir)) {
+ wrench.mkdirSyncRecursive(destDir, "0755");
+ }
+
+ fs.writeFileSync(path.join(destDir, filename), fileBuffer);
+ }
+ },
+
+ listFiles: function (directory, filter) {
+ var files = wrench.readdirSyncRecursive(directory),
+ filteredFiles = [];
+
+ files.forEach(function (file) {
+ //On mac wrench.readdirSyncRecursive does not return absolute paths, so resolve one.
+ file = path.resolve(directory, file);
+
+ if (filter(file)) {
+ filteredFiles.push(file);
+ }
+ });
+
+ return filteredFiles;
+ },
+
+ isWindows: function () {
+ return os.type().toLowerCase().indexOf("windows") >= 0;
+ },
+
+ isArray: function (obj) {
+ return obj.constructor.toString().indexOf("Array") !== -1;
+ },
+
+ isEmpty : function (obj) {
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop))
+ return false;
+ }
+ return true;
+ },
+
+ toBoolean: function (myString, defaultVal) {
+ // if defaultVal is not passed, default value is undefined
+ return myString === "true" ? true : myString === "false" ? false : defaultVal;
+ },
+
+ parseUri : function (str) {
+ var i, uri = {},
+ key = [ "source", "scheme", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor" ],
+ matcher = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(str);
+
+ for (i = key.length - 1; i >= 0; i--) {
+ uri[key[i]] = matcher[i] || "";
+ }
+
+ return uri;
+ },
+
+ // uri - output from parseUri
+ isAbsoluteURI : function (uri) {
+ if (uri && uri.source) {
+ return uri.relative !== uri.source;
+ }
+
+ return false;
+ },
+
+ isLocalURI : function (uri) {
+ return uri && uri.scheme && uri.scheme.toLowerCase() === "local";
+ },
+
+ // Convert node.js Buffer data (encoded) to String
+ bufferToString : function (data) {
+ var s = "";
+ if (Buffer.isBuffer(data)) {
+ if (data.length >= 2 && data[0] === 0xFF && data[1] === 0xFE) {
+ s = data.toString("ucs2", 2);
+ } else if (data.length >= 2 && data[0] === 0xFE && data[1] === 0xFF) {
+ swapBytes(data);
+ s = data.toString("ucs2", 2);
+ } else if (data.length >= 3 && data[0] === 0xEF && data[1] === 0xBB && data[2] === 0xBF) {
+ s = data.toString("utf8", 3);
+ } else {
+ s = data.toString("ascii");
+ }
+ }
+
+ return s;
+ },
+
+ // Wrap object property in an Array if the property is defined and it is not an Array
+ wrapPropertyInArray : function (obj, property) {
+ if (obj && obj[property] && !(obj[property] instanceof Array)) {
+ obj[property] = [ obj[property] ];
+ }
+ },
+
+ loadModule: function (path) {
+ return require(path);
+ }
+};
+
+module.exports = _self;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/dist/README.md
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/dist/README.md b/lib/cordova-blackberry/bin/templates/dist/README.md
deleted file mode 100644
index 35a8393..0000000
--- a/lib/cordova-blackberry/bin/templates/dist/README.md
+++ /dev/null
@@ -1,90 +0,0 @@
-Cordova BlackBerry Distribution
-===============================
-
-Cordova BlackBerry is a framework that allows for Cordova based projects to be built for the [BlackBerry WebWorks Platform](https://bdsc.webapps.blackberry.com/html5/). Cordova based applications are, at the core, an application written with web technology: HTML, CSS and JavaScript. The Cordova BlackBerry project allows web developers to develop applications targeting BlackBerry OS 5.0+ and PlayBook devices using the common [Cordova API](http://docs.phonegap.com).
-
-Apache Cordova is an effort undergoing incubation at The Apache Software Foundation (ASF), sponsored by the Apache Incubator project. Incubation is required of all newly accepted projects until a further review indicates that the infrastructure, communications, and decision making process have stabilized in a manner consistent with other successful ASF projects. While incubation status is not necessarily a reflection of the completeness or stability of the code, it does indicate that the project has yet to be fully endorsed by the ASF.
-
-Pre-requisites
---------------
-
-- Windows XP (32-bit) or Windows 7 (32-bit and 64-bit) or Mac OSX 10.6.4+
-- Java JDK 1.5
-- Apache ANT
-- [BlackBerry WebWorks SDK](https://bdsc.webapps.blackberry.com/html5/download/sdk)
-- PlayBook development requires [Adobe Air SDK](http://www.adobe.com/devnet/air/air-sdk-download.html)
-
-Directory Structure
--------------------
-
- sample/ ... Ready-to-run sample project
- www/ ...... Barebones project assets
-
-### Ready-to-Run Sample Project
-
-The quickest way to get started with Cordova BlackBerry is to make a copy of the `sample` folder. The `sample` folder is a complete Cordova BlackBerry project including build scripts. Copy the `sample` folder to a desired location to create a new Cordova BlackBerry project.
-
-#### Building and Deploying a Project
-
-The build scripts included in the `sample` folder automate common tasks, such as compiling your project, and deploying it to simulators or devices. To see what options are available, use:
-
- $ cd C:\development\my_new_project
- $ ant help
-
-Every command is in the form `ant TARGET COMMAND [options]`, where
-target is either `blackberry` or `playbook`.
-
-To build your project into a deployable application (.cod/.jad) file:
-
- $ ant TARGET build
-
-To build your project and load it in a BlackBerry simulator:
-
- $ ant TARGET load-simulator
-
-To build your project and load it onto a USB-attached device:
-
- $ ant TARGET load-device
-
-### Barebones Project Assets
-
-The `www` folder contains the Cordova specific assets that must be available in a BlackBerry WebWorks project. If you have an existing BlackBerry WebWorks project, copy/merge these files into your project to enable the project for Cordova.
-
- ext/cordova.jar - Native Cordova API implementations for smartphones.
- ext-air/ - PlayBook Adobe Air extensions for Cordova API.
- playbook/cordova.js - PlayBook Cordova JavaScript API.
- cordova.js - Smartphone Cordova JavaScript API.
- config.xml - BlackBerry WebWorks configuration file.
- plugins.xml - Cordova plugin configuration file.
-
-`config.xml` is a sample that you are free to alter or merge with an existing BlackBerry WebWorks configuration file. The necessary Cordova sections are contained in the `<feature>` and `<access>` sections:
-
- <!-- Cordova API -->
- <feature ... />
- <feature ... />
-
- <!-- Cordova API -->
- <access ... />
- <access ... />
-
-Frequently Asked Questions
---------------------------
-
-__Q: My simulator screen is not refreshing and I see blocks on a clicked position.__
-
-__A:__ Windows 7 and the simulator's graphics acceleration do not mix. On the simulator, set View -> Graphics Acceleration to Off.
-
-__Q: When I use the Cordova [Camera.getPicture API](http://docs.phonegap.com/phonegap_camera_camera.md.html#camera.getPicture) on my device, the camera never returns to my application. Why does this happen?__
-
-__A:__ Cordova uses a JavaScript Extension to invoke the native camera application so the user can take a picture. When the picture is taken, Cordova will close the native camera application by emulating a key injection (pressing the back/escape button). On a physical device, users will have to set permissions to allow the application to simulate key injections. Setting application permissions is device-specific. On a Storm2 (9550), for example, select the BlackBerry button from the Home screen to get to All Applications screen, then Options > Applications > Your Application. Then select Edit Default Permissions > Interactions > Input Simulation and set it to 'Allow'. Save your changes.
-
-__Q: None of the Cordova APIs are working, why is that?__
-
-__A:__ You probably need to update your plugins.xml file in the root of your application.
-
-Additional Information
-----------------------
-- [Cordova home](http://incubator.apache.org/cordova/)
-- [Cordova Documentation](http://docs.phonegap.com)
-- [Cordova Issue Tracker](https://issues.apache.org/jira/browse/CB)
-- [BlackBerry WebWorks Framework](https://bdsc.webapps.blackberry.com/html5/)
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/blackberry.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/blackberry.xml b/lib/cordova-blackberry/bin/templates/project/blackberry.xml
deleted file mode 100644
index ce3099f..0000000
--- a/lib/cordova-blackberry/bin/templates/project/blackberry.xml
+++ /dev/null
@@ -1,456 +0,0 @@
-<project default="help">
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
- <!-- LOAD PROPERTIES -->
-
- <property prefix="properties" file="project.properties" />
- <property name="build.dir" location="build" />
- <property name="widget.dir" location="${build.dir}/widget" />
- <property name="code.sign" value="false" />
- <property name="generate.ext" value="cod" />
- <property name="globalization" value="false" />
-
- <!-- BlackBerry WebWorks Packager directory is required. -->
- <fail unless="properties.blackberry.bbwp.dir" message="Please specify BlackBerry WebWorks Packager directory using 'blackberry.bbwp.dir' in your 'project.properties' file." />
-
- <!-- OS identification -->
- <condition property="isMacOSX" else="false">
- <and>
- <os family="mac" />
- <os family="unix" />
- </and>
- </condition>
-
- <condition property="javaloader" value="${properties.blackberry.bbwp.dir}/bin/javaloader" else="${properties.blackberry.bbwp.dir}/bin/JavaLoader.exe">
- <equals arg1="${isMacOSX}" arg2="true" />
- </condition>
-
- <condition property="bbwp" value="${properties.blackberry.bbwp.dir}/bbwp" else="${properties.blackberry.bbwp.dir}/bbwp.exe">
- <equals arg1="${isMacOSX}" arg2="true" />
- </condition>
-
-
- <!-- LOAD DEVICE -->
-
- <target name="load-device" depends="package-app">
- <bbwp code-sign="true" />
- <exec executable="${javaloader}" dir="." failonerror="true">
- <arg value="-u" />
- <arg value="-w${properties.blackberry.sim.password}" />
- <arg value="load" />
- <arg file="${build.dir}/StandardInstall/${cod.name}.cod" />
- </exec>
- </target>
-
- <!-- DEBUG-LOAD DEVICE -->
-
- <target name="debug-device" depends="package-app">
- <bbwp code-sign="true" debug="true" />
- <exec executable="${javaloader}" dir="." failonerror="true">
- <arg value="-u" />
- <arg value="-w${properties.blackberry.sim.password}" />
- <arg value="load" />
- <arg file="${build.dir}/StandardInstall/${cod.name}.cod" />
- </exec>
- </target>
-
- <!-- LOAD SIMULATOR -->
-
- <target name="load-simulator" depends="build">
-
- <!-- Find the simulator directory -->
- <set-simulator-dir />
-
- <!-- Locate BBWP simulator directory. There may be multiple, so choose the first. -->
- <path id="bbwp.sim.path">
- <first>
- <fileset dir="${properties.blackberry.bbwp.dir}/simpack">
- <include name="**/handhelds.manifest.txt" />
- </fileset>
- </first>
- </path>
- <dirname property="bbwp.sim.dir" file="${toString:bbwp.sim.path}" />
-
- <!-- Simulator directory: Use sim.dir property if set in project.properties file.
- Otherwise, use bbwp simulator directory. -->
- <condition
- property="simulator.dir"
- value="${properties.blackberry.sim.dir}"
- else="${bbwp.sim.dir}">
- <available file="${properties.blackberry.sim.dir}" type="dir" />
- </condition>
- <echo message="Simulator directory=${simulator.dir}" />
-
- <!-- Simulator binary: Use sim.bin property if set in project.properties file
- or try setting to 'defaultSimulator.bat' in simulator directory. -->
- <condition
- property="sim.bin"
- value="${properties.blackberry.sim.bin}"
- else="defaultSimulator.bat">
- <available file="${simulator.dir}/${properties.blackberry.sim.bin}"/>
- </condition>
-
- <!-- If simulator executable does not exist, use the first device listed
- in the 'handhelds.manifest.txt' file in the simulator directory. -->
- <loadfile
- property="device.list"
- srcFile="${simulator.dir}/handhelds.manifest.txt">
- <filterchain>
- <tokenFilter>
- <stringtokenizer/>
- </tokenFilter>
- </filterchain>
- </loadfile>
-
- <propertyregex property="device"
- input="${device.list}"
- regexp="^\d{4}"
- select="\0"
- override="true" />
- <property name="device.bin" value="${device}.bat" />
-
- <condition
- property="simulator.bin"
- value="${sim.bin}"
- else="${device.bin}">
- <available file="${simulator.dir}/${sim.bin}" />
- </condition>
-
- <echo message="Simulator executable=${simulator.dir}/${simulator.bin}" />
-
- <!-- Close running simulators -->
- <echo message="Closing all running simulators..." />
- <exec executable="${simulator.dir}/fledgecontroller.exe" dir="${simulator.dir}" spawn="false">
- <arg value="/execute=kill" />
- </exec>
-
- <!-- MDS directory: Use mds.dir property if set in project.properties file.
- Otherwise, use bbwp MDS directory. -->
- <condition
- property="mds.dir"
- value="${properties.blackberry.mds.dir}"
- else="${properties.blackberry.bbwp.dir}/mds">
- <available file="${properties.blackberry.mds.dir}" type="dir" />
- </condition>
- <echo message="MDS directory=${mds.dir}" />
-
- <copy todir="${simulator.dir}">
- <fileset dir="${build.dir}/StandardInstall" includes="*.cod, *.cso, *.csl, *.alx" />
- </copy>
- <exec executable="${mds.dir}/run.bat" dir="${mds.dir}" spawn="true" />
- <exec executable="${simulator.dir}/${simulator.bin}" dir="${simulator.dir}" spawn="true" />
-
- <!-- Only invoke FledgeHook.exe if it is found. Newer versions of the
- WebWorks SDK do not include it. -->
- <if>
- <available file="${properties.blackberry.bbwp.dir}/FledgeHook.exe" />
- <then>
- <exec executable="${properties.blackberry.bbwp.dir}/FledgeHook.exe" dir="${properties.blackberry.bbwp.dir}" spawn="true" />
- </then>
- </if>
- </target>
-
- <target name="debug-simulator" depends="package-app">
- <bbwp code-sign="false" debug="true" />
-
- <!-- Find the simulator directory -->
- <set-simulator-dir />
-
- <!-- Locate BBWP simulator directory. There may be multiple, so choose the first. -->
- <path id="bbwp.sim.path">
- <first>
- <fileset dir="${properties.blackberry.bbwp.dir}/simpack">
- <include name="**/handhelds.manifest.txt" />
- </fileset>
- </first>
- </path>
- <dirname property="bbwp.sim.dir" file="${toString:bbwp.sim.path}" />
-
- <!-- Simulator directory: Use sim.dir property if set in project.properties file.
- Otherwise, use bbwp simulator directory. -->
- <condition
- property="simulator.dir"
- value="${properties.blackberry.sim.dir}"
- else="${bbwp.sim.dir}">
- <available file="${properties.blackberry.sim.dir}" type="dir" />
- </condition>
- <echo message="Simulator directory=${simulator.dir}" />
-
- <!-- Simulator binary: Use sim.bin property if set in project.properties file
- or try setting to 'defaultSimulator.bat' in simulator directory. -->
- <condition
- property="sim.bin"
- value="${properties.blackberry.sim.bin}"
- else="defaultSimulator.bat">
- <available file="${simulator.dir}/${properties.blackberry.sim.bin}"/>
- </condition>
-
- <!-- If simulator executable does not exist, use the first device listed
- in the 'handhelds.manifest.txt' file in the simulator directory. -->
- <loadfile
- property="device.list"
- srcFile="${simulator.dir}/handhelds.manifest.txt">
- <filterchain>
- <tokenFilter>
- <stringtokenizer/>
- </tokenFilter>
- </filterchain>
- </loadfile>
-
- <propertyregex property="device"
- input="${device.list}"
- regexp="^\d{4}"
- select="\0"
- override="true" />
- <property name="device.bin" value="${device}.bat" />
-
- <condition
- property="simulator.bin"
- value="${sim.bin}"
- else="${device.bin}">
- <available file="${simulator.dir}/${sim.bin}" />
- </condition>
-
- <echo message="Simulator executable=${simulator.dir}/${simulator.bin}" />
-
- <!-- Close running simulators -->
- <echo message="Closing all running simulators..." />
- <exec executable="${simulator.dir}/fledgecontroller.exe" dir="${simulator.dir}" spawn="false">
- <arg value="/execute=kill" />
- </exec>
-
- <!-- MDS directory: Use mds.dir property if set in project.properties file.
- Otherwise, use bbwp MDS directory. -->
- <condition
- property="mds.dir"
- value="${properties.blackberry.mds.dir}"
- else="${properties.blackberry.bbwp.dir}/mds">
- <available file="${properties.blackberry.mds.dir}" type="dir" />
- </condition>
- <echo message="MDS directory=${mds.dir}" />
-
- <copy todir="${simulator.dir}">
- <fileset dir="${build.dir}/StandardInstall" includes="*.cod, *.cso, *.csl, *.alx" />
- </copy>
- <exec executable="${mds.dir}/run.bat" dir="${mds.dir}" spawn="true" />
- <exec executable="${simulator.dir}/${simulator.bin}" dir="${simulator.dir}" spawn="true" />
-
- <!-- Only invoke FledgeHook.exe if it is found. Newer versions of the
- WebWorks SDK do not include it. -->
- <if>
- <available file="${properties.blackberry.bbwp.dir}/FledgeHook.exe" />
- <then>
- <exec executable="${properties.blackberry.bbwp.dir}/FledgeHook.exe" dir="${properties.blackberry.bbwp.dir}" spawn="true" />
- </then>
- </if>
- </target>
-
- <!-- PACKAGE-APP -->
-
- <target name="package-app" depends="generate-cod-name, clean">
- <!-- Copy the WebWorks application -->
- <mkdir dir="${widget.dir}" />
- <copy todir="${widget.dir}" overwrite="true">
- <fileset dir="www" >
- <exclude name="ext-air/**"/>
- <exclude name="ext-qnx/**"/>
- <exclude name="res/resourceBundles/**" unless="${globalization}"/>
- </fileset>
- </copy>
-
- <!-- Package the WebWorks app by zipping the widget dir. -->
- <mkdir dir="${build.dir}" />
- <zip compress="false" destfile="${build.dir}/${cod.name}.zip" basedir="${widget.dir}" excludes="**/build/**,**/.settings/**,**/.project" />
- </target>
-
- <!-- BUILD -->
-
- <target name="build" depends="package-app">
- <bbwp code-sign="${code.sign}" />
- </target>
-
- <!-- BBWP MACRO -->
-
- <macrodef name="bbwp">
- <attribute name="code-sign" default="false" />
- <attribute name="debug" default="false" />
- <sequential>
- <!-- check if debug flag was passed in and set an appropriate flag for CLI exec of bbwp -->
- <if>
- <equals arg1="@{debug}" arg2="true" />
- <then>
- <property name="debug.flag" value="/d" />
- </then>
- <else>
- <property name="debug.flag" value="" />
- </else>
- </if>
-
- <!-- Ensure bbwp executable exists. -->
- <property name="properties.blackberry.bbwp.bin" location="${bbwp}" />
- <available file="${properties.blackberry.bbwp.bin}" property="properties.blackberry.bbwp.exists" />
- <fail unless="properties.blackberry.bbwp.exists" message="Cannot find ${properties.blackberry.bbwp.bin}. Please edit 'blackberry.bbwp.dir' in your 'project.properties' file." />
-
- <if>
- <equals arg1="@{code-sign}" arg2="true" />
- <then>
- <exec executable="${properties.blackberry.bbwp.bin}">
- <arg file="${build.dir}/${cod.name}.zip" />
- <arg value="/g" />
- <arg value="${properties.blackberry.sigtool.password}" />
- <arg line="${debug.flag} /o" />
- <arg file="${build.dir}" />
- </exec>
- </then>
- <else>
- <exec executable="${properties.blackberry.bbwp.bin}">
- <arg file="${build.dir}/${cod.name}.zip" />
- <arg line="${debug.flag} /o" />
- <arg file="${build.dir}" />
- </exec>
- </else>
- </if>
- </sequential>
- </macrodef>
-
- <!-- CLEAN -->
-
- <target name="clean">
- <delete dir="${build.dir}" />
- <delete dir="${widget.dir}" />
- </target>
-
- <!-- CLEAN DEVICE -->
-
- <target name="clean-device" depends="generate-cod-name">
- <exec executable="${javaloader}">
- <arg value="-usb" />
- <arg value="erase" />
- <arg value="-f" />
- <arg value="${cod.name}.cod" />
- </exec>
- </target>
-
- <!-- CLEAN SIMULATOR -->
-
- <target name="clean-simulator">
- <!-- Find the simulator directory -->
- <set-simulator-dir />
-
- <exec executable="${simulator.dir}/clean.bat" dir="${simulator.dir}" />
-
- <delete>
- <fileset dir="${simulator.dir}" includes="*.cod,*.csl,*.cso,*.debug,*.jar" />
- </delete>
- </target>
-
- <!-- HELPER TASKS -->
-
- <target name="generate-cod-name">
- <xmlproperty file="www/config.xml" prefix="config.xml" />
- <propertyregex property="cod.name"
- input="${config.xml.widget.name}"
- regexp="(\W+)"
- replace=""
- casesensitive="false"
- global="true"
- defaultValue="${config.xml.widget.name}" />
- <echo message="Generated name: ${cod.name}.cod" />
- </target>
-
- <!-- MACRO: SET SIMULATOR DIRECTORY -->
-
- <macrodef name="set-simulator-dir">
- <sequential>
- <!-- Locate BBWP simulator directory. There may be multiple, so choose the first. -->
- <path id="bbwp.sim.path">
- <first>
- <fileset dir="${properties.blackberry.bbwp.dir}/simpack">
- <include name="**/handhelds.manifest.txt" />
- </fileset>
- </first>
- </path>
- <dirname property="bbwp.sim.dir" file="${toString:bbwp.sim.path}" />
-
- <!-- Simulator directory: Use sim.dir property if set in project.properties file.
- Otherwise, use bbwp simulator directory. -->
- <condition
- property="simulator.dir"
- value="${properties.blackberry.sim.dir}"
- else="${bbwp.sim.dir}">
- <available file="${properties.blackberry.sim.dir}" type="dir" />
- </condition>
- <echo message="Simulator directory=${simulator.dir}" />
- </sequential>
- </macrodef>
-
- <!-- HELP -->
-
- <target name="help">
- <echo>
-NAME
- ${ant.project.name}
-
-SYNOPSIS
- ant TARGET COMMAND [-D<argument>=<value>]...
-
-DESCRIPTION
- You can build and deploy your project to a device or simulator.
-
-TARGETS
- blackberry ........ Builds a cod file and deploys to a device or simulator
-
- playbook .......... Builds a bar file and deploys to a device or simulator
-
-COMMANDS
- help .............. Show this help menu.
- ant, ant help
-
- load-device ....... Builds and deploys project to a connected USB device.
- ant load-device
-
- load-simulator .... Builds and deploys project to default simulator.
- ant load-simulator
-
- build ............. Compiles and packages the project for deployment.
- ant build
-
- clean ............. Remove all files from the build/ directory.
- ant clean
-
- clean-device ...... Remove this project from the connected USB device.
- ant clean-device
-
- clean-simulator ... Remove this project from the simulator (takes a while).
- ant clean-simulator
-
-GETTING STARTED
- 1. Edit project.properties
-
- 2. <ant load-simulator> to run the project on the simulator
-
- 3. Customize your project by editing www/config.xml
-
- 4. To run the project on a BlackBerry device, you will need to obtain
- code signing keys from RIM. Once you have the key, a project is
- installed by connecting a BlackBerry via USB and running
- <ant load-device>.
- </echo>
- </target>
-</project>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/build.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/build.xml b/lib/cordova-blackberry/bin/templates/project/build.xml
deleted file mode 100644
index d1fb939..0000000
--- a/lib/cordova-blackberry/bin/templates/project/build.xml
+++ /dev/null
@@ -1,160 +0,0 @@
-<project name="Build and Deploy a Cordova BlackBerry WebWorks Project" default="help">
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
- <!-- LOAD ANT-CONTRIB LIBRARY -->
-
- <taskdef resource="net/sf/antcontrib/antcontrib.properties">
- <classpath>
- <pathelement location="./lib/ant-contrib/ant-contrib-1.0b3.jar" />
- </classpath>
- </taskdef>
-
- <!-- LOAD PROPERTIES -->
-
- <property prefix="properties" file="project.properties" />
- <property name="build.dir" location="build" />
- <property name="widget.dir" location="${build.dir}/widget" />
- <property name="code.sign" value="false" />
- <property name="globalization" value="false" />
-
- <target name="blackberry" >
- <property name="subant.file" value="blackberry.xml" />
- </target>
-
- <target name="playbook" >
- <property name="subant.file" value="playbook.xml" />
- </target>
-
- <target name="qnx" >
- <property name="subant.file" value="qnx.xml" />
- </target>
-
- <target name="load-device">
- <subant target="load-device">
- <fileset dir="." includes="${subant.file}"/>
- </subant>
- </target>
-
- <target name="load-simulator">
- <subant target="load-simulator">
- <fileset dir="." includes="${subant.file}"/>
- </subant>
- </target>
-
- <target name="debug-simulator">
- <subant target="debug-simulator">
- <fileset dir="." includes="${subant.file}"/>
- </subant>
- </target>
-
- <target name="debug-device">
- <subant target="debug-device">
- <fileset dir="." includes="${subant.file}"/>
- </subant>
- </target>
-
- <target name="build">
- <subant target="build">
- <fileset dir="." includes="${subant.file}"/>
- </subant>
- </target>
-
- <target name="clean">
- <subant target="clean">
- <fileset dir="." includes="${subant.file}"/>
- </subant>
- </target>
-
- <target name="clean-device">
- <subant target="clean-device">
- <fileset dir="." includes="${subant.file}"/>
- </subant>
- </target>
-
- <target name="package-app">
- <subant target="package-app">
- <fileset dir="." includes="${subant.file}"/>
- </subant>
- </target>
-
- <target name="clean-simulator">
- <subant target="clean-simulator">
- <fileset dir="." includes="${subant.file}"/>
- </subant>
- </target>
-
- <!-- HELP -->
-
- <target name="help">
- <echo>
-NAME
- ${ant.project.name}
-
-SYNOPSIS
- ant TARGET COMMAND [-D<argument>=<value>]...
-
-DESCRIPTION
- You can build and deploy your project to a device or simulator.
-
-TARGETS
- blackberry ........ Builds a cod file and deploys to a device or simulator
-
- playbook .......... Builds a bar file and deploys to a device or simulator
-
- qnx ............... Builds a bar file and deploys to a device or simulator
-
-COMMANDS
- help .............. Show this help menu.
- ant, ant help
-
- load-device ....... Builds and deploys project to a connected USB device.
- ant TARGET load-device
-
- load-simulator .... Builds and deploys project to default simulator.
- ant TARGET load-simulator
-
- build ............. Compiles and packages the project for deployment.
- ant TARGET build
-
- package-app ....... Packages the app into a WebWorks-compatible .zip file.
- ant TARGET package-app
-
- clean ............. Remove all files from the build/ directory.
- ant TARGET clean
-
- clean-device ...... Remove this project from the connected USB device.
- ant TARGET clean-device
-
- clean-simulator ... Remove this project from the simulator (takes a while).
- ant TARGET clean-simulator
-
-GETTING STARTED
- 1. Edit project.properties
-
- 2. <ant load-simulator> to run the project on the simulator
-
- 3. Customize your project by editing www/config.xml
-
- 4. To run the project on a BlackBerry device, you will need to obtain
- code signing keys from RIM. Once you have the key, a project is
- installed by connecting a BlackBerry via USB and running
- <ant load-device>.
- </echo>
- </target>
-</project>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/build
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/build b/lib/cordova-blackberry/bin/templates/project/cordova/build
index d788360..c1e6f63 100755
--- a/lib/cordova-blackberry/bin/templates/project/cordova/build
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/build
@@ -1,34 +1,5 @@
-#! /bin/sh
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
+#!/bin/sh
-ANT=$(which ant)
+#package app
+node $(dirname "$0")"/lib/build" "$@"
-if [ -z "$1" ]
-then
- echo 'usage: build <platform>'
- echo 'where <platform> can be one of "blackberry", "playbook" or "qnx"'
- echo 'NOTE: please customize the project.properties file first before using this command!'
- exit 0
-fi
-
-if [ "$1" == "blackberry" -o "$1" == "playbook" -o "$1" == "qnx" ]
-then
- $ANT $1 build
-else
- echo 'Platform not recognized! Please use one of "blackberry", "playbook", or "qnx" for the platform parameter.'
-fi
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/build.bat
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/build.bat b/lib/cordova-blackberry/bin/templates/project/cordova/build.bat
new file mode 100755
index 0000000..186bbba
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/build.bat
@@ -0,0 +1,21 @@
+@ECHO OFF
+goto comment
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+:comment
+
+@node.exe %~dp0\lib\build %*
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/clean
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/clean b/lib/cordova-blackberry/bin/templates/project/cordova/clean
new file mode 100755
index 0000000..54d888c
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/clean
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+node $(dirname "$0")"/lib/clean"
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/clean.bat
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/clean.bat b/lib/cordova-blackberry/bin/templates/project/cordova/clean.bat
new file mode 100755
index 0000000..636862f
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/clean.bat
@@ -0,0 +1,21 @@
+@ECHO OFF
+goto comment
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+:comment
+
+@node.exe %~dp0\lib\clean %*
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/bar-builder.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/bar-builder.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/bar-builder.js
new file mode 100644
index 0000000..0a955f9
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/bar-builder.js
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var jWorkflow = require("jWorkflow"),
+ wrench = require("wrench"),
+ nativePkgr = require("./native-packager"),
+ fileManager = require("./file-manager"),
+ localize = require("./localize"),
+ logger = require("./logger"),
+ signingHelper = require("./signing-helper"),
+ targetIdx = 0;
+
+function buildTarget(previous, baton) {
+ baton.take();
+
+ var target = this.session.targets[targetIdx++],
+ session = this.session,
+ config = this.config;
+
+ //Create output folder
+ wrench.mkdirSyncRecursive(session.outputDir + "/" + target);
+
+ //Copy resources (could be lost if copying assets from other project)
+ fileManager.copyNative(this.session, target);
+ //Generate user config here to overwrite default
+ fileManager.generateUserConfig(session, config);
+
+ if (config.packageCordovaJs) {
+ //Package cordova.js to chrome folder
+ fileManager.copyWebworks(this.session);
+ }
+
+ //Generate frameworkModules.js (this needs to be done AFTER all files have been copied)
+ fileManager.generateFrameworkModulesJS(session);
+
+ //Call native-packager module for target
+ nativePkgr.exec(session, target, config, function (code) {
+ if (code !== 0) {
+ logger.error(localize.translate("EXCEPTION_NATIVEPACKAGER"));
+ baton.pass(code);
+ } else {
+ if (target === "device" && session.isSigningRequired(config)) {
+ signingHelper.execSigner(session, target, function (code) {
+ baton.pass(code);
+ });
+ } else {
+ baton.pass(code);
+ }
+ }
+ });
+}
+
+function buildWorkflow(session, context) {
+ if (session.targets && session.targets.length > 0) {
+ var order;
+
+ session.targets.forEach(function (target, idx) {
+ if (idx === 0) {
+ order = jWorkflow.order(buildTarget, context);
+ } else {
+ order = order.andThen(buildTarget, context);
+ }
+ });
+
+ return order;
+ } else {
+ logger.debug("NOTHING TO BUILD, NO TARGETS");
+ }
+}
+
+module.exports = {
+ build: function (session, config, callback) {
+ var context = {
+ session: session,
+ config: config
+ },
+ workflow = buildWorkflow(session, context);
+
+ if (workflow) {
+ workflow.start({
+ "callback": callback
+ });
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/bar-conf.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/bar-conf.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/bar-conf.js
new file mode 100644
index 0000000..857875b
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/bar-conf.js
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var self = {};
+
+self.ROOT = "";
+self.CHROME = self.ROOT + "/chrome";
+self.LIB = self.CHROME + "/lib";
+self.EXT = self.CHROME + "/plugin";
+self.UI = self.ROOT + "/ui-resources";
+self.PLUGINS = self.ROOT + "/plugins";
+self.JNEXT_PLUGINS = self.ROOT + "/plugins/jnext";
+
+module.exports = self;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/bbwpignore.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/bbwpignore.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/bbwpignore.js
new file mode 100755
index 0000000..29c6399
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/bbwpignore.js
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var fs = require("fs"),
+ path = require("path"),
+ BBWPignore;
+
+function getDirectory(file) {
+ if (file.match("/$")) {
+ return file;
+ } else if (file.indexOf("/") === -1) {
+ return "";
+ } else {
+ return file.substring(0, file.lastIndexOf("/"));
+ }
+}
+
+function trim(str) {
+ return str.replace(/^\s+|\s+$/g, "");
+}
+
+BBWPignore = function (bbwpIgnoreFile, filesToMatch) {
+ var comments = [],
+ directories = [],
+ wildcardEntries = [],
+ files = [],
+ split,
+ matched = [],
+ i,
+ temparr,
+ tempFiles = [];
+ temparr = fs.readFileSync(bbwpIgnoreFile, "utf-8").split('\n');
+
+ //switch all the paths to relative, so if someone has passed absolute paths convert them to relative to .bbwpignore
+ filesToMatch.forEach(function (file) {
+ if (file === path.resolve(file)) { //if path is absolute
+ tempFiles.push(path.relative(path.dirname(bbwpIgnoreFile), file));
+ } else {
+ tempFiles.push(file);
+ }
+ });
+ filesToMatch = tempFiles;
+
+ //run through all the patterns in the bbwpignore and put them in appropriate arrays
+ for (i = 0; i < temparr.length; i++) {
+ temparr[i] = trim(temparr[i]);
+ if (temparr[i] !== "") {
+ if (temparr[i].match("^#")) {
+ comments.push(temparr[i]);
+ } else if (temparr[i].match("^/") && temparr[i].match("/$")) {
+ directories.push(temparr[i]);
+ } else if (temparr[i].indexOf("*") !== -1) {
+ split = temparr[i].split("/");
+ if (split[split.length - 1].indexOf("*") !== -1) { // only wildcards in the file name are supported, not in directory names
+ wildcardEntries.push(temparr[i]);
+ } else {
+ files.push(temparr[i]);
+ }
+ } else {
+ files.push(temparr[i]);
+ }
+ }
+ }
+
+ //run through all the files and check it against each of the patterns collected earlier
+ filesToMatch.forEach(function (fileToMatch) {
+ var directory,
+ dirOrig = getDirectory(fileToMatch),
+ isMatch = false;
+ //match directories
+ directory = "/" + dirOrig + "/";
+ if (directories.indexOf(directory) !== -1) {
+ matched.push(fileToMatch);
+ //add the directory to the list as well but only check
+ if (matched.indexOf("/" + dirOrig) === -1) {
+ matched.push("/" + dirOrig);
+ }
+ isMatch = true;
+ } else {
+ //handle special case when match patterns begin with /
+ //match wildCards
+ wildcardEntries.forEach(function (wildcard) {
+ if (wildcard.match("^/")) { // special case looking for exact match
+ wildcard = "^" + wildcard.replace("*", "[^\/]*");
+ if (("/" + fileToMatch).match(wildcard)) {
+ matched.push(fileToMatch);
+ isMatch = true;
+ }
+ } else {
+ wildcard = wildcard.replace("*", "[^\/]*");
+ if (fileToMatch.match(wildcard)) {
+ matched.push(fileToMatch);
+ isMatch = true;
+ }
+ }
+ });
+ if (!isMatch) { //must be a file
+ files.forEach(function (file) {
+ if (file.match("^/")) { // special case looking for exact match
+ if (file === ("/" + fileToMatch)) {
+ matched.push(fileToMatch);
+ isMatch = true;
+ }
+ } else if (fileToMatch.match(file)) {
+ matched.push(fileToMatch);
+ isMatch = true;
+ }
+ });
+
+ }
+ }
+ });
+ this.matchedFiles = matched;
+};
+
+module.exports = BBWPignore;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/build
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/build b/lib/cordova-blackberry/bin/templates/project/cordova/lib/build
new file mode 100644
index 0000000..3fb3432
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/build
@@ -0,0 +1,174 @@
+#!/usr/bin/env node
+
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var path = require("path"),
+ command = require("commander"),
+ jWorkflow = require("jWorkflow"),
+ localize = require("./localize"),
+ logger = require("./logger"),
+ projectProperties = require("../../project.json"),
+ debugTokenHelper = require("./debugtoken-helper"),
+ bbwpArgv = [
+ process.argv[0],
+ path.resolve(path.join(__dirname, process.argv[1])),
+ path.resolve(path.join(__dirname, "..", "..", "www")),
+ "-o",
+ path.resolve(path.join(__dirname, "..", "..", "build"))
+ ],
+ built = false,
+ debugtoken = false;
+
+function getTarget() {
+ return typeof command.args[0] === "string" ? command.args[0] : undefined;
+}
+
+function copyArgIfExists(arg) {
+ if (command[arg]) {
+ bbwpArgv.push("--" + arg);
+ bbwpArgv.push(command[arg]);
+ }
+}
+
+function createDebugtoken(previous, baton) {
+ var keystorepass = command["keystorepass"] ? command["keystorepass"] : projectProperties.keystorepass;
+ baton.take();
+ logger.info(localize.translate("PROGRESS_WILL_CREATE_DEBUG_TOKEN"));
+ debugTokenHelper.createToken(projectProperties, getTarget(), keystorepass, function (code) {
+ if (code === 0) {
+ debugtoken = true;
+ }
+
+ baton.pass();
+ });
+}
+
+function deployDebugToken(previous, baton) {
+ baton.take();
+
+ // If in debug build and debug token was created, deploy the debug token and wait until the deployment is finished
+ if (debugtoken) {
+ logger.info(localize.translate("PROGRESS_WILL_DEPLOY_DEBUG_TOKEN"));
+ debugTokenHelper.deployToken(projectProperties, getTarget(), function () {
+ baton.pass();
+ });
+ } else {
+ baton.pass();
+ }
+}
+
+function doDebugBuild() {
+ built = true;
+
+ //build in debug mode by default
+ bbwpArgv.push("-d");
+
+ // In debug build, it needs to create debug token first
+ jWorkflow.order(createDebugtoken)
+ .andThen(deployDebugToken)
+ .andThen(build)
+ .start();
+}
+
+function doReleaseBuild() {
+ built = true;
+
+ //Note: Packager refers to signing password as "password" not "keystorepass"
+ if (command["keystorepass"]) {
+ bbwpArgv.push("--password");
+ bbwpArgv.push(command["keystorepass"]);
+ } else if (projectProperties.keystorepass) {
+ bbwpArgv.push("--password");
+ bbwpArgv.push( projectProperties.keystorepass);
+ } else {
+ throw "No signing password provided. Please use --keystorepass via command-line or enter a value for keystorepass in project.json";
+ }
+
+ copyArgIfExists("buildId");
+
+ build();
+}
+
+function build() {
+ copyArgIfExists("params");
+ copyArgIfExists("loglevel");
+
+ //Overrite process.argv, before calling packager
+ process.argv = bbwpArgv;
+
+ //Delete cached commander object. It will conflict with the packagers commander
+ delete require.cache[require.resolve("commander")];
+ delete require.cache[require.resolve("commander/lib/commander")];
+
+ //Package app. If successfull call run
+ require("./packager").start(run);
+}
+
+function run() {
+ var target = getTarget();
+
+ //Overrite process.argv, before calling run
+ process.argv = [
+ process.argv[0],
+ process.argv[1],
+ ];
+
+ if (target) {
+ process.argv.push(target);
+ }
+
+ //deploy app
+ require("./run");
+}
+
+command
+ .usage('command [<target>] [-k | --keystorepass] [-b | --buildId <number>] [-p | --params <json>] [-ll | --loglevel <level>]')
+ .option('-k, --keystorepass <password>', 'Signing key password')
+ .option('-b, --buildId <num>', 'Specifies the build number for signing (typically incremented from previous signing).')
+ .option('-p, --params <params JSON file>', 'Specifies additional parameters to pass to downstream tools.')
+ .option('-ll, --loglevel <loglevel>', 'set the logging level (error, warn, verbose)');
+
+command
+ .command('release')
+ .usage('[<target>] [-k | --keystorepass] [-b | --buildId <number>] [-p | --params <json>] [-ll | --loglevel <level>]')
+ .description(' Build in release mode. This will sign the resulting bar.')
+ .option('-k, --keystorepass <password>', 'Signing key password')
+ .option('-b, --buildId <num>', 'Specifies the build number for signing (typically incremented from previous signing).')
+ .option('-p, --params <params JSON file>', 'Specifies additional parameters to pass to downstream tools.')
+ .option('-ll, --loglevel <loglevel>', 'set the logging level (error, warn, verbose)')
+ .action(doReleaseBuild);
+
+command
+ .command('debug')
+ .usage('[<target>] [-p | --params <json>] [-ll | --loglevel <level>]')
+ .description(' Build in debug mode.')
+ .option('-p, --params <params JSON file>', 'Specifies additional parameters to pass to downstream tools.')
+ .option('-ll, --loglevel <loglevel>', 'set the logging level (error, warn, verbose)')
+ .action(doDebugBuild);
+
+try {
+ command.parse(process.argv);
+
+ //if we get here and haven't built yet then no mode was provided [debug, release], default to debug mode
+ if (!built) {
+ doDebugBuild();
+ }
+} catch (e) {
+ console.log(e);
+ process.exit();
+}
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/clean
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/clean b/lib/cordova-blackberry/bin/templates/project/cordova/lib/clean
new file mode 100644
index 0000000..46391d3
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/clean
@@ -0,0 +1,24 @@
+#!/usr/bin/env node
+
+/*
+ * Copyright 2013 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var wrench = require('wrench'),
+ path = require("path"),
+ buildPath = path.normalize(__dirname + "/../../build/");
+
+ wrench.rmdirSyncRecursive(buildPath, true);
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/cmdline.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/cmdline.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/cmdline.js
new file mode 100644
index 0000000..14eb172
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/cmdline.js
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var command = require("commander"),
+ logger = require("./logger"),
+ localize = require("./localize");
+
+command
+ .version('1.0.0.0')
+ .usage('[drive:][path]archive [-s [dir]] [[ -g genpassword] [-buildId num]] [-o dir] [-d] [-p paramsjsonfile]')
+ .option('-s, --source [dir]', 'Save source. The default behaviour is to not save the source files. If dir is specified then creates dir\\src\\ directory structure. If no dir specified then the path of archive is assumed')
+ .option('-g, --password <password>', 'Signing key password')
+ .option('-buildId <num>', '[deprecated] Use --buildId.')
+ .option('-b, --buildId <num>', 'Specifies the build number for signing (typically incremented from previous signing).')
+ .option('-o, --output <dir>', 'Redirects output file location to dir. If both -o and dir are not specified then the path of archive is assumed')
+ .option('-d, --debug', 'Allows use of not signed build on device by utilizing debug token and enables Web Inspector.')
+ .option('-p, --params <params JSON file>', 'Specifies additional parameters to pass to downstream tools.')
+ .option('--appdesc <filepath>', 'Optionally specifies the path to the bar descriptor file (bar-descriptor.xml). For internal use only.')
+ .option('-v, --verbose', 'Turn on verbose messages')
+ .option('-ll, --loglevel <loglevel>', 'set the logging level (error, warn, verbose)');
+
+function parseArgs(args) {
+ var option,
+ i;
+ if (!args[2]) {
+ //no args passed into [node bbwp.js], show the help information
+ args.push("-h");
+ }
+
+ //Handle deprecated option -buildId
+ for (i = 0; i < args.length; i++) {
+ if (args[i] === "-buildId") {
+ args[i] = "--buildId";
+ }
+ }
+
+ command.parse(args);
+
+ //Check for any invalid command line args
+ for (i = 0; i < args.length; i++) {
+ //Remove leading dashes if any
+ option = args[i].substring(2);
+ if (args[i].indexOf("--") === 0 && !command[option]) {
+ throw localize.translate("EXCEPTION_CMDLINE_ARG_INVALID", args[i]);
+ }
+ }
+
+ return this;
+}
+
+module.exports = {
+ "commander": command,
+ "parse": parseArgs
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/conf.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/conf.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/conf.js
new file mode 100644
index 0000000..89f8372
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/conf.js
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var path = require("path"),
+ fs = require("fs");
+
+function getToolsDir() {
+ if (process.env && process.env.QNX_HOST) {
+ var bbndkDir = path.join(process.env.QNX_HOST, "usr");
+ if (fs.existsSync(bbndkDir)) {
+ //BBNDK exists on path, use its tools
+ return bbndkDir;
+ }
+ }
+}
+
+module.exports = {
+ ROOT: path.normalize(__dirname + "/../framework"),
+ PROJECT_ROOT: path.normalize(__dirname + "/../../"),
+ NATIVE: path.normalize(__dirname + "/../../native"),
+ JNEXT_AUTH: path.normalize(__dirname + "/../../native/plugins/jnext/auth.txt"),
+ BIN: path.normalize(__dirname + "/../framework/bin"),
+ LIB: path.normalize(__dirname + "/../framework/lib"),
+ EXT: path.normalize(__dirname + "/../../plugins"),
+ UI: path.normalize(__dirname + "/../framework/ui-resources"),
+ DEPENDENCIES: path.normalize(__dirname + "/../framework/dependencies"),
+ DEPENDENCIES_BOOTSTRAP: path.normalize(__dirname + "/../framework/bootstrap"),
+ DEPENDENCIES_TOOLS: getToolsDir(),
+ DEPENDENCIES_WWE: path.normalize(__dirname + "/../dependencies/%s-wwe"),
+ DEBUG_TOKEN: path.normalize(__dirname + "/../debugtoken.bar"),
+ DEFAULT_ICON: path.normalize(__dirname + "/../default-icon.png"),
+ BAR_DESCRIPTOR: "bar-descriptor.xml",
+ BBWP_IGNORE_FILENAME: ".bbwpignore"
+};
[36/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/HttpResponseCache.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/HttpResponseCache.java b/lib/cordova-android/framework/src/com/squareup/okhttp/HttpResponseCache.java
new file mode 100644
index 0000000..a6d380a
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/HttpResponseCache.java
@@ -0,0 +1,693 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp;
+
+import com.squareup.okhttp.internal.Base64;
+import com.squareup.okhttp.internal.DiskLruCache;
+import com.squareup.okhttp.internal.StrictLineReader;
+import com.squareup.okhttp.internal.Util;
+import com.squareup.okhttp.internal.http.HttpEngine;
+import com.squareup.okhttp.internal.http.HttpURLConnectionImpl;
+import com.squareup.okhttp.internal.http.HttpsURLConnectionImpl;
+import com.squareup.okhttp.internal.http.OkResponseCache;
+import com.squareup.okhttp.internal.http.RawHeaders;
+import com.squareup.okhttp.internal.http.ResponseHeaders;
+import java.io.BufferedWriter;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+import java.net.CacheRequest;
+import java.net.CacheResponse;
+import java.net.HttpURLConnection;
+import java.net.ResponseCache;
+import java.net.SecureCacheResponse;
+import java.net.URI;
+import java.net.URLConnection;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.Principal;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLPeerUnverifiedException;
+
+import static com.squareup.okhttp.internal.Util.US_ASCII;
+import static com.squareup.okhttp.internal.Util.UTF_8;
+
+/**
+ * Caches HTTP and HTTPS responses to the filesystem so they may be reused,
+ * saving time and bandwidth.
+ *
+ * <h3>Cache Optimization</h3>
+ * To measure cache effectiveness, this class tracks three statistics:
+ * <ul>
+ * <li><strong>{@link #getRequestCount() Request Count:}</strong> the number
+ * of HTTP requests issued since this cache was created.
+ * <li><strong>{@link #getNetworkCount() Network Count:}</strong> the
+ * number of those requests that required network use.
+ * <li><strong>{@link #getHitCount() Hit Count:}</strong> the number of
+ * those requests whose responses were served by the cache.
+ * </ul>
+ * Sometimes a request will result in a conditional cache hit. If the cache
+ * contains a stale copy of the response, the client will issue a conditional
+ * {@code GET}. The server will then send either the updated response if it has
+ * changed, or a short 'not modified' response if the client's copy is still
+ * valid. Such responses increment both the network count and hit count.
+ *
+ * <p>The best way to improve the cache hit rate is by configuring the web
+ * server to return cacheable responses. Although this client honors all <a
+ * href="http://www.ietf.org/rfc/rfc2616.txt">HTTP/1.1 (RFC 2068)</a> cache
+ * headers, it doesn't cache partial responses.
+ *
+ * <h3>Force a Network Response</h3>
+ * In some situations, such as after a user clicks a 'refresh' button, it may be
+ * necessary to skip the cache, and fetch data directly from the server. To force
+ * a full refresh, add the {@code no-cache} directive: <pre> {@code
+ * connection.addRequestProperty("Cache-Control", "no-cache");
+ * }</pre>
+ * If it is only necessary to force a cached response to be validated by the
+ * server, use the more efficient {@code max-age=0} instead: <pre> {@code
+ * connection.addRequestProperty("Cache-Control", "max-age=0");
+ * }</pre>
+ *
+ * <h3>Force a Cache Response</h3>
+ * Sometimes you'll want to show resources if they are available immediately,
+ * but not otherwise. This can be used so your application can show
+ * <i>something</i> while waiting for the latest data to be downloaded. To
+ * restrict a request to locally-cached resources, add the {@code
+ * only-if-cached} directive: <pre> {@code
+ * try {
+ * connection.addRequestProperty("Cache-Control", "only-if-cached");
+ * InputStream cached = connection.getInputStream();
+ * // the resource was cached! show it
+ * } catch (FileNotFoundException e) {
+ * // the resource was not cached
+ * }
+ * }</pre>
+ * This technique works even better in situations where a stale response is
+ * better than no response. To permit stale cached responses, use the {@code
+ * max-stale} directive with the maximum staleness in seconds: <pre> {@code
+ * int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
+ * connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
+ * }</pre>
+ */
+public final class HttpResponseCache extends ResponseCache {
+ private static final char[] DIGITS =
+ { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+
+ // TODO: add APIs to iterate the cache?
+ private static final int VERSION = 201105;
+ private static final int ENTRY_METADATA = 0;
+ private static final int ENTRY_BODY = 1;
+ private static final int ENTRY_COUNT = 2;
+
+ private final DiskLruCache cache;
+
+ /* read and write statistics, all guarded by 'this' */
+ private int writeSuccessCount;
+ private int writeAbortCount;
+ private int networkCount;
+ private int hitCount;
+ private int requestCount;
+
+ /**
+ * Although this class only exposes the limited ResponseCache API, it
+ * implements the full OkResponseCache interface. This field is used as a
+ * package private handle to the complete implementation. It delegates to
+ * public and private members of this type.
+ */
+ final OkResponseCache okResponseCache = new OkResponseCache() {
+ @Override public CacheResponse get(URI uri, String requestMethod,
+ Map<String, List<String>> requestHeaders) throws IOException {
+ return HttpResponseCache.this.get(uri, requestMethod, requestHeaders);
+ }
+
+ @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
+ return HttpResponseCache.this.put(uri, connection);
+ }
+
+ @Override public void update(
+ CacheResponse conditionalCacheHit, HttpURLConnection connection) throws IOException {
+ HttpResponseCache.this.update(conditionalCacheHit, connection);
+ }
+
+ @Override public void trackConditionalCacheHit() {
+ HttpResponseCache.this.trackConditionalCacheHit();
+ }
+
+ @Override public void trackResponse(ResponseSource source) {
+ HttpResponseCache.this.trackResponse(source);
+ }
+ };
+
+ public HttpResponseCache(File directory, long maxSize) throws IOException {
+ cache = DiskLruCache.open(directory, VERSION, ENTRY_COUNT, maxSize);
+ }
+
+ private String uriToKey(URI uri) {
+ try {
+ MessageDigest messageDigest = MessageDigest.getInstance("MD5");
+ byte[] md5bytes = messageDigest.digest(uri.toString().getBytes("UTF-8"));
+ return bytesToHexString(md5bytes);
+ } catch (NoSuchAlgorithmException e) {
+ throw new AssertionError(e);
+ } catch (UnsupportedEncodingException e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ private static String bytesToHexString(byte[] bytes) {
+ char[] digits = DIGITS;
+ char[] buf = new char[bytes.length * 2];
+ int c = 0;
+ for (byte b : bytes) {
+ buf[c++] = digits[(b >> 4) & 0xf];
+ buf[c++] = digits[b & 0xf];
+ }
+ return new String(buf);
+ }
+
+ @Override public CacheResponse get(URI uri, String requestMethod,
+ Map<String, List<String>> requestHeaders) {
+ String key = uriToKey(uri);
+ DiskLruCache.Snapshot snapshot;
+ Entry entry;
+ try {
+ snapshot = cache.get(key);
+ if (snapshot == null) {
+ return null;
+ }
+ entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
+ } catch (IOException e) {
+ // Give up because the cache cannot be read.
+ return null;
+ }
+
+ if (!entry.matches(uri, requestMethod, requestHeaders)) {
+ snapshot.close();
+ return null;
+ }
+
+ return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
+ : new EntryCacheResponse(entry, snapshot);
+ }
+
+ @Override public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException {
+ if (!(urlConnection instanceof HttpURLConnection)) {
+ return null;
+ }
+
+ HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
+ String requestMethod = httpConnection.getRequestMethod();
+ String key = uriToKey(uri);
+
+ if (requestMethod.equals("POST") || requestMethod.equals("PUT") || requestMethod.equals(
+ "DELETE")) {
+ try {
+ cache.remove(key);
+ } catch (IOException ignored) {
+ // The cache cannot be written.
+ }
+ return null;
+ } else if (!requestMethod.equals("GET")) {
+ // Don't cache non-GET responses. We're technically allowed to cache
+ // HEAD requests and some POST requests, but the complexity of doing
+ // so is high and the benefit is low.
+ return null;
+ }
+
+ HttpEngine httpEngine = getHttpEngine(httpConnection);
+ if (httpEngine == null) {
+ // Don't cache unless the HTTP implementation is ours.
+ return null;
+ }
+
+ ResponseHeaders response = httpEngine.getResponseHeaders();
+ if (response.hasVaryAll()) {
+ return null;
+ }
+
+ RawHeaders varyHeaders =
+ httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
+ Entry entry = new Entry(uri, varyHeaders, httpConnection);
+ DiskLruCache.Editor editor = null;
+ try {
+ editor = cache.edit(key);
+ if (editor == null) {
+ return null;
+ }
+ entry.writeTo(editor);
+ return new CacheRequestImpl(editor);
+ } catch (IOException e) {
+ abortQuietly(editor);
+ return null;
+ }
+ }
+
+ private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
+ throws IOException {
+ HttpEngine httpEngine = getHttpEngine(httpConnection);
+ URI uri = httpEngine.getUri();
+ ResponseHeaders response = httpEngine.getResponseHeaders();
+ RawHeaders varyHeaders =
+ httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
+ Entry entry = new Entry(uri, varyHeaders, httpConnection);
+ DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
+ ? ((EntryCacheResponse) conditionalCacheHit).snapshot
+ : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
+ DiskLruCache.Editor editor = null;
+ try {
+ editor = snapshot.edit(); // returns null if snapshot is not current
+ if (editor != null) {
+ entry.writeTo(editor);
+ editor.commit();
+ }
+ } catch (IOException e) {
+ abortQuietly(editor);
+ }
+ }
+
+ private void abortQuietly(DiskLruCache.Editor editor) {
+ // Give up because the cache cannot be written.
+ try {
+ if (editor != null) {
+ editor.abort();
+ }
+ } catch (IOException ignored) {
+ }
+ }
+
+ private HttpEngine getHttpEngine(URLConnection httpConnection) {
+ if (httpConnection instanceof HttpURLConnectionImpl) {
+ return ((HttpURLConnectionImpl) httpConnection).getHttpEngine();
+ } else if (httpConnection instanceof HttpsURLConnectionImpl) {
+ return ((HttpsURLConnectionImpl) httpConnection).getHttpEngine();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Closes the cache and deletes all of its stored values. This will delete
+ * all files in the cache directory including files that weren't created by
+ * the cache.
+ */
+ public void delete() throws IOException {
+ cache.delete();
+ }
+
+ public synchronized int getWriteAbortCount() {
+ return writeAbortCount;
+ }
+
+ public synchronized int getWriteSuccessCount() {
+ return writeSuccessCount;
+ }
+
+ private synchronized void trackResponse(ResponseSource source) {
+ requestCount++;
+
+ switch (source) {
+ case CACHE:
+ hitCount++;
+ break;
+ case CONDITIONAL_CACHE:
+ case NETWORK:
+ networkCount++;
+ break;
+ }
+ }
+
+ private synchronized void trackConditionalCacheHit() {
+ hitCount++;
+ }
+
+ public synchronized int getNetworkCount() {
+ return networkCount;
+ }
+
+ public synchronized int getHitCount() {
+ return hitCount;
+ }
+
+ public synchronized int getRequestCount() {
+ return requestCount;
+ }
+
+ private final class CacheRequestImpl extends CacheRequest {
+ private final DiskLruCache.Editor editor;
+ private OutputStream cacheOut;
+ private boolean done;
+ private OutputStream body;
+
+ public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
+ this.editor = editor;
+ this.cacheOut = editor.newOutputStream(ENTRY_BODY);
+ this.body = new FilterOutputStream(cacheOut) {
+ @Override public void close() throws IOException {
+ synchronized (HttpResponseCache.this) {
+ if (done) {
+ return;
+ }
+ done = true;
+ writeSuccessCount++;
+ }
+ super.close();
+ editor.commit();
+ }
+
+ @Override
+ public void write(byte[] buffer, int offset, int length) throws IOException {
+ // Since we don't override "write(int oneByte)", we can write directly to "out"
+ // and avoid the inefficient implementation from the FilterOutputStream.
+ out.write(buffer, offset, length);
+ }
+ };
+ }
+
+ @Override public void abort() {
+ synchronized (HttpResponseCache.this) {
+ if (done) {
+ return;
+ }
+ done = true;
+ writeAbortCount++;
+ }
+ Util.closeQuietly(cacheOut);
+ try {
+ editor.abort();
+ } catch (IOException ignored) {
+ }
+ }
+
+ @Override public OutputStream getBody() throws IOException {
+ return body;
+ }
+ }
+
+ private static final class Entry {
+ private final String uri;
+ private final RawHeaders varyHeaders;
+ private final String requestMethod;
+ private final RawHeaders responseHeaders;
+ private final String cipherSuite;
+ private final Certificate[] peerCertificates;
+ private final Certificate[] localCertificates;
+
+ /**
+ * Reads an entry from an input stream. A typical entry looks like this:
+ * <pre>{@code
+ * http://google.com/foo
+ * GET
+ * 2
+ * Accept-Language: fr-CA
+ * Accept-Charset: UTF-8
+ * HTTP/1.1 200 OK
+ * 3
+ * Content-Type: image/png
+ * Content-Length: 100
+ * Cache-Control: max-age=600
+ * }</pre>
+ *
+ * <p>A typical HTTPS file looks like this:
+ * <pre>{@code
+ * https://google.com/foo
+ * GET
+ * 2
+ * Accept-Language: fr-CA
+ * Accept-Charset: UTF-8
+ * HTTP/1.1 200 OK
+ * 3
+ * Content-Type: image/png
+ * Content-Length: 100
+ * Cache-Control: max-age=600
+ *
+ * AES_256_WITH_MD5
+ * 2
+ * base64-encoded peerCertificate[0]
+ * base64-encoded peerCertificate[1]
+ * -1
+ * }</pre>
+ * The file is newline separated. The first two lines are the URL and
+ * the request method. Next is the number of HTTP Vary request header
+ * lines, followed by those lines.
+ *
+ * <p>Next is the response status line, followed by the number of HTTP
+ * response header lines, followed by those lines.
+ *
+ * <p>HTTPS responses also contain SSL session information. This begins
+ * with a blank line, and then a line containing the cipher suite. Next
+ * is the length of the peer certificate chain. These certificates are
+ * base64-encoded and appear each on their own line. The next line
+ * contains the length of the local certificate chain. These
+ * certificates are also base64-encoded and appear each on their own
+ * line. A length of -1 is used to encode a null array.
+ */
+ public Entry(InputStream in) throws IOException {
+ try {
+ StrictLineReader reader = new StrictLineReader(in, US_ASCII);
+ uri = reader.readLine();
+ requestMethod = reader.readLine();
+ varyHeaders = new RawHeaders();
+ int varyRequestHeaderLineCount = reader.readInt();
+ for (int i = 0; i < varyRequestHeaderLineCount; i++) {
+ varyHeaders.addLine(reader.readLine());
+ }
+
+ responseHeaders = new RawHeaders();
+ responseHeaders.setStatusLine(reader.readLine());
+ int responseHeaderLineCount = reader.readInt();
+ for (int i = 0; i < responseHeaderLineCount; i++) {
+ responseHeaders.addLine(reader.readLine());
+ }
+
+ if (isHttps()) {
+ String blank = reader.readLine();
+ if (blank.length() > 0) {
+ throw new IOException("expected \"\" but was \"" + blank + "\"");
+ }
+ cipherSuite = reader.readLine();
+ peerCertificates = readCertArray(reader);
+ localCertificates = readCertArray(reader);
+ } else {
+ cipherSuite = null;
+ peerCertificates = null;
+ localCertificates = null;
+ }
+ } finally {
+ in.close();
+ }
+ }
+
+ public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
+ throws IOException {
+ this.uri = uri.toString();
+ this.varyHeaders = varyHeaders;
+ this.requestMethod = httpConnection.getRequestMethod();
+ this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);
+
+ if (isHttps()) {
+ HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
+ cipherSuite = httpsConnection.getCipherSuite();
+ Certificate[] peerCertificatesNonFinal = null;
+ try {
+ peerCertificatesNonFinal = httpsConnection.getServerCertificates();
+ } catch (SSLPeerUnverifiedException ignored) {
+ }
+ peerCertificates = peerCertificatesNonFinal;
+ localCertificates = httpsConnection.getLocalCertificates();
+ } else {
+ cipherSuite = null;
+ peerCertificates = null;
+ localCertificates = null;
+ }
+ }
+
+ public void writeTo(DiskLruCache.Editor editor) throws IOException {
+ OutputStream out = editor.newOutputStream(ENTRY_METADATA);
+ Writer writer = new BufferedWriter(new OutputStreamWriter(out, UTF_8));
+
+ writer.write(uri + '\n');
+ writer.write(requestMethod + '\n');
+ writer.write(Integer.toString(varyHeaders.length()) + '\n');
+ for (int i = 0; i < varyHeaders.length(); i++) {
+ writer.write(varyHeaders.getFieldName(i) + ": " + varyHeaders.getValue(i) + '\n');
+ }
+
+ writer.write(responseHeaders.getStatusLine() + '\n');
+ writer.write(Integer.toString(responseHeaders.length()) + '\n');
+ for (int i = 0; i < responseHeaders.length(); i++) {
+ writer.write(responseHeaders.getFieldName(i) + ": " + responseHeaders.getValue(i) + '\n');
+ }
+
+ if (isHttps()) {
+ writer.write('\n');
+ writer.write(cipherSuite + '\n');
+ writeCertArray(writer, peerCertificates);
+ writeCertArray(writer, localCertificates);
+ }
+ writer.close();
+ }
+
+ private boolean isHttps() {
+ return uri.startsWith("https://");
+ }
+
+ private Certificate[] readCertArray(StrictLineReader reader) throws IOException {
+ int length = reader.readInt();
+ if (length == -1) {
+ return null;
+ }
+ try {
+ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
+ Certificate[] result = new Certificate[length];
+ for (int i = 0; i < result.length; i++) {
+ String line = reader.readLine();
+ byte[] bytes = Base64.decode(line.getBytes("US-ASCII"));
+ result[i] = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes));
+ }
+ return result;
+ } catch (CertificateException e) {
+ throw new IOException(e.getMessage());
+ }
+ }
+
+ private void writeCertArray(Writer writer, Certificate[] certificates) throws IOException {
+ if (certificates == null) {
+ writer.write("-1\n");
+ return;
+ }
+ try {
+ writer.write(Integer.toString(certificates.length) + '\n');
+ for (Certificate certificate : certificates) {
+ byte[] bytes = certificate.getEncoded();
+ String line = Base64.encode(bytes);
+ writer.write(line + '\n');
+ }
+ } catch (CertificateEncodingException e) {
+ throw new IOException(e.getMessage());
+ }
+ }
+
+ public boolean matches(URI uri, String requestMethod,
+ Map<String, List<String>> requestHeaders) {
+ return this.uri.equals(uri.toString())
+ && this.requestMethod.equals(requestMethod)
+ && new ResponseHeaders(uri, responseHeaders).varyMatches(varyHeaders.toMultimap(false),
+ requestHeaders);
+ }
+ }
+
+ /**
+ * Returns an input stream that reads the body of a snapshot, closing the
+ * snapshot when the stream is closed.
+ */
+ private static InputStream newBodyInputStream(final DiskLruCache.Snapshot snapshot) {
+ return new FilterInputStream(snapshot.getInputStream(ENTRY_BODY)) {
+ @Override public void close() throws IOException {
+ snapshot.close();
+ super.close();
+ }
+ };
+ }
+
+ static class EntryCacheResponse extends CacheResponse {
+ private final Entry entry;
+ private final DiskLruCache.Snapshot snapshot;
+ private final InputStream in;
+
+ public EntryCacheResponse(Entry entry, DiskLruCache.Snapshot snapshot) {
+ this.entry = entry;
+ this.snapshot = snapshot;
+ this.in = newBodyInputStream(snapshot);
+ }
+
+ @Override public Map<String, List<String>> getHeaders() {
+ return entry.responseHeaders.toMultimap(true);
+ }
+
+ @Override public InputStream getBody() {
+ return in;
+ }
+ }
+
+ static class EntrySecureCacheResponse extends SecureCacheResponse {
+ private final Entry entry;
+ private final DiskLruCache.Snapshot snapshot;
+ private final InputStream in;
+
+ public EntrySecureCacheResponse(Entry entry, DiskLruCache.Snapshot snapshot) {
+ this.entry = entry;
+ this.snapshot = snapshot;
+ this.in = newBodyInputStream(snapshot);
+ }
+
+ @Override public Map<String, List<String>> getHeaders() {
+ return entry.responseHeaders.toMultimap(true);
+ }
+
+ @Override public InputStream getBody() {
+ return in;
+ }
+
+ @Override public String getCipherSuite() {
+ return entry.cipherSuite;
+ }
+
+ @Override public List<Certificate> getServerCertificateChain()
+ throws SSLPeerUnverifiedException {
+ if (entry.peerCertificates == null || entry.peerCertificates.length == 0) {
+ throw new SSLPeerUnverifiedException(null);
+ }
+ return Arrays.asList(entry.peerCertificates.clone());
+ }
+
+ @Override public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
+ if (entry.peerCertificates == null || entry.peerCertificates.length == 0) {
+ throw new SSLPeerUnverifiedException(null);
+ }
+ return ((X509Certificate) entry.peerCertificates[0]).getSubjectX500Principal();
+ }
+
+ @Override public List<Certificate> getLocalCertificateChain() {
+ if (entry.localCertificates == null || entry.localCertificates.length == 0) {
+ return null;
+ }
+ return Arrays.asList(entry.localCertificates.clone());
+ }
+
+ @Override public Principal getLocalPrincipal() {
+ if (entry.localCertificates == null || entry.localCertificates.length == 0) {
+ return null;
+ }
+ return ((X509Certificate) entry.localCertificates[0]).getSubjectX500Principal();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/OkHttpClient.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/OkHttpClient.java b/lib/cordova-android/framework/src/com/squareup/okhttp/OkHttpClient.java
new file mode 100644
index 0000000..7834bd6
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/OkHttpClient.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright (C) 2012 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import com.squareup.okhttp.internal.http.HttpURLConnectionImpl;
+import com.squareup.okhttp.internal.http.HttpsURLConnectionImpl;
+import com.squareup.okhttp.internal.http.OkResponseCache;
+import com.squareup.okhttp.internal.http.OkResponseCacheAdapter;
+import java.net.CookieHandler;
+import java.net.HttpURLConnection;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.ResponseCache;
+import java.net.URL;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.Set;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLSocketFactory;
+
+/** Configures and creates HTTP connections. */
+public final class OkHttpClient {
+ private Proxy proxy;
+ private Set<Route> failedRoutes = Collections.synchronizedSet(new LinkedHashSet<Route>());
+ private ProxySelector proxySelector;
+ private CookieHandler cookieHandler;
+ private ResponseCache responseCache;
+ private SSLSocketFactory sslSocketFactory;
+ private HostnameVerifier hostnameVerifier;
+ private ConnectionPool connectionPool;
+ private boolean followProtocolRedirects = true;
+
+ /**
+ * Sets the HTTP proxy that will be used by connections created by this
+ * client. This takes precedence over {@link #setProxySelector}, which is
+ * only honored when this proxy is null (which it is by default). To disable
+ * proxy use completely, call {@code setProxy(Proxy.NO_PROXY)}.
+ */
+ public OkHttpClient setProxy(Proxy proxy) {
+ this.proxy = proxy;
+ return this;
+ }
+
+ public Proxy getProxy() {
+ return proxy;
+ }
+
+ /**
+ * Sets the proxy selection policy to be used if no {@link #setProxy proxy}
+ * is specified explicitly. The proxy selector may return multiple proxies;
+ * in that case they will be tried in sequence until a successful connection
+ * is established.
+ *
+ * <p>If unset, the {@link ProxySelector#getDefault() system-wide default}
+ * proxy selector will be used.
+ */
+ public OkHttpClient setProxySelector(ProxySelector proxySelector) {
+ this.proxySelector = proxySelector;
+ return this;
+ }
+
+ public ProxySelector getProxySelector() {
+ return proxySelector;
+ }
+
+ /**
+ * Sets the cookie handler to be used to read outgoing cookies and write
+ * incoming cookies.
+ *
+ * <p>If unset, the {@link CookieHandler#getDefault() system-wide default}
+ * cookie handler will be used.
+ */
+ public OkHttpClient setCookieHandler(CookieHandler cookieHandler) {
+ this.cookieHandler = cookieHandler;
+ return this;
+ }
+
+ public CookieHandler getCookieHandler() {
+ return cookieHandler;
+ }
+
+ /**
+ * Sets the response cache to be used to read and write cached responses.
+ *
+ * <p>If unset, the {@link ResponseCache#getDefault() system-wide default}
+ * response cache will be used.
+ */
+ public OkHttpClient setResponseCache(ResponseCache responseCache) {
+ this.responseCache = responseCache;
+ return this;
+ }
+
+ public ResponseCache getResponseCache() {
+ return responseCache;
+ }
+
+ private OkResponseCache okResponseCache() {
+ if (responseCache instanceof HttpResponseCache) {
+ return ((HttpResponseCache) responseCache).okResponseCache;
+ } else if (responseCache != null) {
+ return new OkResponseCacheAdapter(responseCache);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Sets the socket factory used to secure HTTPS connections.
+ *
+ * <p>If unset, the {@link HttpsURLConnection#getDefaultSSLSocketFactory()
+ * system-wide default} SSL socket factory will be used.
+ */
+ public OkHttpClient setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
+ this.sslSocketFactory = sslSocketFactory;
+ return this;
+ }
+
+ public SSLSocketFactory getSslSocketFactory() {
+ return sslSocketFactory;
+ }
+
+ /**
+ * Sets the verifier used to confirm that response certificates apply to
+ * requested hostnames for HTTPS connections.
+ *
+ * <p>If unset, the {@link HttpsURLConnection#getDefaultHostnameVerifier()
+ * system-wide default} hostname verifier will be used.
+ */
+ public OkHttpClient setHostnameVerifier(HostnameVerifier hostnameVerifier) {
+ this.hostnameVerifier = hostnameVerifier;
+ return this;
+ }
+
+ public HostnameVerifier getHostnameVerifier() {
+ return hostnameVerifier;
+ }
+
+ /**
+ * Sets the connection pool used to recycle HTTP and HTTPS connections.
+ *
+ * <p>If unset, the {@link ConnectionPool#getDefault() system-wide
+ * default} connection pool will be used.
+ */
+ public OkHttpClient setConnectionPool(ConnectionPool connectionPool) {
+ this.connectionPool = connectionPool;
+ return this;
+ }
+
+ public ConnectionPool getConnectionPool() {
+ return connectionPool;
+ }
+
+ /**
+ * Configure this client to follow redirects from HTTPS to HTTP and from HTTP
+ * to HTTPS.
+ *
+ * <p>If unset, protocol redirects will be followed. This is different than
+ * the built-in {@code HttpURLConnection}'s default.
+ */
+ public OkHttpClient setFollowProtocolRedirects(boolean followProtocolRedirects) {
+ this.followProtocolRedirects = followProtocolRedirects;
+ return this;
+ }
+
+ public boolean getFollowProtocolRedirects() {
+ return followProtocolRedirects;
+ }
+
+ public HttpURLConnection open(URL url) {
+ String protocol = url.getProtocol();
+ OkHttpClient copy = copyWithDefaults();
+ if (protocol.equals("http")) {
+ return new HttpURLConnectionImpl(url, copy, copy.okResponseCache(), copy.failedRoutes);
+ } else if (protocol.equals("https")) {
+ return new HttpsURLConnectionImpl(url, copy, copy.okResponseCache(), copy.failedRoutes);
+ } else {
+ throw new IllegalArgumentException("Unexpected protocol: " + protocol);
+ }
+ }
+
+ /**
+ * Returns a shallow copy of this OkHttpClient that uses the system-wide default for
+ * each field that hasn't been explicitly configured.
+ */
+ private OkHttpClient copyWithDefaults() {
+ OkHttpClient result = new OkHttpClient();
+ result.proxy = proxy;
+ result.failedRoutes = failedRoutes;
+ result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
+ result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
+ result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
+ result.sslSocketFactory = sslSocketFactory != null
+ ? sslSocketFactory
+ : HttpsURLConnection.getDefaultSSLSocketFactory();
+ result.hostnameVerifier = hostnameVerifier != null
+ ? hostnameVerifier
+ : HttpsURLConnection.getDefaultHostnameVerifier();
+ result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
+ result.followProtocolRedirects = followProtocolRedirects;
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/OkResponseCache.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/OkResponseCache.java b/lib/cordova-android/framework/src/com/squareup/okhttp/OkResponseCache.java
new file mode 100644
index 0000000..b7e3801
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/OkResponseCache.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import java.io.IOException;
+import java.net.CacheResponse;
+import java.net.HttpURLConnection;
+
+/**
+ * A response cache that supports statistics tracking and updating stored
+ * responses. Implementations of {@link java.net.ResponseCache} should implement
+ * this interface to receive additional support from the HTTP engine.
+ */
+public interface OkResponseCache {
+
+ /** Track an HTTP response being satisfied by {@code source}. */
+ void trackResponse(ResponseSource source);
+
+ /** Track an conditional GET that was satisfied by this cache. */
+ void trackConditionalCacheHit();
+
+ /** Updates stored HTTP headers using a hit on a conditional GET. */
+ void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
+ throws IOException;
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/ResponseSource.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/ResponseSource.java b/lib/cordova-android/framework/src/com/squareup/okhttp/ResponseSource.java
new file mode 100644
index 0000000..4eca172
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/ResponseSource.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+/** The source of an HTTP response. */
+public enum ResponseSource {
+
+ /** The response was returned from the local cache. */
+ CACHE,
+
+ /**
+ * The response is available in the cache but must be validated with the
+ * network. The cache result will be used if it is still valid; otherwise
+ * the network's response will be used.
+ */
+ CONDITIONAL_CACHE,
+
+ /** The response was returned from the network. */
+ NETWORK;
+
+ public boolean requiresConnection() {
+ return this == CONDITIONAL_CACHE || this == NETWORK;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/Route.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/Route.java b/lib/cordova-android/framework/src/com/squareup/okhttp/Route.java
new file mode 100644
index 0000000..6968c60
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/Route.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2013 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+
+/** Represents the route used by a connection to reach an endpoint. */
+public class Route {
+ final Address address;
+ final Proxy proxy;
+ final InetSocketAddress inetSocketAddress;
+ final boolean modernTls;
+
+ public Route(Address address, Proxy proxy, InetSocketAddress inetSocketAddress,
+ boolean modernTls) {
+ if (address == null) throw new NullPointerException("address == null");
+ if (proxy == null) throw new NullPointerException("proxy == null");
+ if (inetSocketAddress == null) throw new NullPointerException("inetSocketAddress == null");
+ this.address = address;
+ this.proxy = proxy;
+ this.inetSocketAddress = inetSocketAddress;
+ this.modernTls = modernTls;
+ }
+
+ /** Returns the {@link Address} of this route. */
+ public Address getAddress() {
+ return address;
+ }
+
+ /**
+ * Returns the {@link Proxy} of this route.
+ *
+ * <strong>Warning:</strong> This may be different than the proxy returned
+ * by {@link #getAddress}! That is the proxy that the user asked to be
+ * connected to; this returns the proxy that they were actually connected
+ * to. The two may disagree when a proxy selector selects a different proxy
+ * for a connection.
+ */
+ public Proxy getProxy() {
+ return proxy;
+ }
+
+ /** Returns the {@link InetSocketAddress} of this route. */
+ public InetSocketAddress getSocketAddress() {
+ return inetSocketAddress;
+ }
+
+ /** Returns true if this route uses modern tls. */
+ public boolean isModernTls() {
+ return modernTls;
+ }
+
+ /** Returns a copy of this route with flipped tls mode. */
+ public Route flipTlsMode() {
+ return new Route(address, proxy, inetSocketAddress, !modernTls);
+ }
+
+ @Override public boolean equals(Object obj) {
+ if (obj instanceof Route) {
+ Route other = (Route) obj;
+ return (address.equals(other.address)
+ && proxy.equals(other.proxy)
+ && inetSocketAddress.equals(other.inetSocketAddress)
+ && modernTls == other.modernTls);
+ }
+ return false;
+ }
+
+ @Override public int hashCode() {
+ int result = 17;
+ result = 31 * result + address.hashCode();
+ result = 31 * result + proxy.hashCode();
+ result = 31 * result + inetSocketAddress.hashCode();
+ result = result + (modernTls ? (31 * result) : 0);
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/TunnelRequest.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/TunnelRequest.java b/lib/cordova-android/framework/src/com/squareup/okhttp/TunnelRequest.java
new file mode 100644
index 0000000..5260b87
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/TunnelRequest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import com.squareup.okhttp.internal.http.RawHeaders;
+
+import static com.squareup.okhttp.internal.Util.getDefaultPort;
+
+/**
+ * Routing and authentication information sent to an HTTP proxy to create a
+ * HTTPS to an origin server. Everything in the tunnel request is sent
+ * unencrypted to the proxy server.
+ *
+ * <p>See <a href="http://www.ietf.org/rfc/rfc2817.txt">RFC 2817, Section
+ * 5.2</a>.
+ */
+public final class TunnelRequest {
+ final String host;
+ final int port;
+ final String userAgent;
+ final String proxyAuthorization;
+
+ /**
+ * @param host the origin server's hostname. Not null.
+ * @param port the origin server's port, like 80 or 443.
+ * @param userAgent the client's user-agent. Not null.
+ * @param proxyAuthorization proxy authorization, or null if the proxy is
+ * used without an authorization header.
+ */
+ public TunnelRequest(String host, int port, String userAgent, String proxyAuthorization) {
+ if (host == null) throw new NullPointerException("host == null");
+ if (userAgent == null) throw new NullPointerException("userAgent == null");
+ this.host = host;
+ this.port = port;
+ this.userAgent = userAgent;
+ this.proxyAuthorization = proxyAuthorization;
+ }
+
+ /**
+ * If we're creating a TLS tunnel, send only the minimum set of headers.
+ * This avoids sending potentially sensitive data like HTTP cookies to
+ * the proxy unencrypted.
+ */
+ RawHeaders getRequestHeaders() {
+ RawHeaders result = new RawHeaders();
+ result.setRequestLine("CONNECT " + host + ":" + port + " HTTP/1.1");
+
+ // Always set Host and User-Agent.
+ result.set("Host", port == getDefaultPort("https") ? host : (host + ":" + port));
+ result.set("User-Agent", userAgent);
+
+ // Copy over the Proxy-Authorization header if it exists.
+ if (proxyAuthorization != null) {
+ result.set("Proxy-Authorization", proxyAuthorization);
+ }
+
+ // Always set the Proxy-Connection to Keep-Alive for the benefit of
+ // HTTP/1.0 proxies like Squid.
+ result.set("Proxy-Connection", "Keep-Alive");
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/AbstractOutputStream.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/AbstractOutputStream.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/AbstractOutputStream.java
new file mode 100644
index 0000000..78c9691
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/AbstractOutputStream.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * An output stream for an HTTP request body.
+ *
+ * <p>Since a single socket's output stream may be used to write multiple HTTP
+ * requests to the same server, subclasses should not close the socket stream.
+ */
+public abstract class AbstractOutputStream extends OutputStream {
+ protected boolean closed;
+
+ @Override public final void write(int data) throws IOException {
+ write(new byte[] { (byte) data });
+ }
+
+ protected final void checkNotClosed() throws IOException {
+ if (closed) {
+ throw new IOException("stream closed");
+ }
+ }
+
+ /** Returns true if this stream was closed locally. */
+ public boolean isClosed() {
+ return closed;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Base64.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Base64.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Base64.java
new file mode 100644
index 0000000..79cd020
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Base64.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Alexander Y. Kleymenov
+ */
+
+package com.squareup.okhttp.internal;
+
+import java.io.UnsupportedEncodingException;
+
+import static com.squareup.okhttp.internal.Util.EMPTY_BYTE_ARRAY;
+
+/**
+ * <a href="http://www.ietf.org/rfc/rfc2045.txt">Base64</a> encoder/decoder.
+ * In violation of the RFC, this encoder doesn't wrap lines at 76 columns.
+ */
+public final class Base64 {
+ private Base64() {
+ }
+
+ public static byte[] decode(byte[] in) {
+ return decode(in, in.length);
+ }
+
+ public static byte[] decode(byte[] in, int len) {
+ // approximate output length
+ int length = len / 4 * 3;
+ // return an empty array on empty or short input without padding
+ if (length == 0) {
+ return EMPTY_BYTE_ARRAY;
+ }
+ // temporary array
+ byte[] out = new byte[length];
+ // number of padding characters ('=')
+ int pad = 0;
+ byte chr;
+ // compute the number of the padding characters
+ // and adjust the length of the input
+ for (; ; len--) {
+ chr = in[len - 1];
+ // skip the neutral characters
+ if ((chr == '\n') || (chr == '\r') || (chr == ' ') || (chr == '\t')) {
+ continue;
+ }
+ if (chr == '=') {
+ pad++;
+ } else {
+ break;
+ }
+ }
+ // index in the output array
+ int outIndex = 0;
+ // index in the input array
+ int inIndex = 0;
+ // holds the value of the input character
+ int bits = 0;
+ // holds the value of the input quantum
+ int quantum = 0;
+ for (int i = 0; i < len; i++) {
+ chr = in[i];
+ // skip the neutral characters
+ if ((chr == '\n') || (chr == '\r') || (chr == ' ') || (chr == '\t')) {
+ continue;
+ }
+ if ((chr >= 'A') && (chr <= 'Z')) {
+ // char ASCII value
+ // A 65 0
+ // Z 90 25 (ASCII - 65)
+ bits = chr - 65;
+ } else if ((chr >= 'a') && (chr <= 'z')) {
+ // char ASCII value
+ // a 97 26
+ // z 122 51 (ASCII - 71)
+ bits = chr - 71;
+ } else if ((chr >= '0') && (chr <= '9')) {
+ // char ASCII value
+ // 0 48 52
+ // 9 57 61 (ASCII + 4)
+ bits = chr + 4;
+ } else if (chr == '+') {
+ bits = 62;
+ } else if (chr == '/') {
+ bits = 63;
+ } else {
+ return null;
+ }
+ // append the value to the quantum
+ quantum = (quantum << 6) | (byte) bits;
+ if (inIndex % 4 == 3) {
+ // 4 characters were read, so make the output:
+ out[outIndex++] = (byte) (quantum >> 16);
+ out[outIndex++] = (byte) (quantum >> 8);
+ out[outIndex++] = (byte) quantum;
+ }
+ inIndex++;
+ }
+ if (pad > 0) {
+ // adjust the quantum value according to the padding
+ quantum = quantum << (6 * pad);
+ // make output
+ out[outIndex++] = (byte) (quantum >> 16);
+ if (pad == 1) {
+ out[outIndex++] = (byte) (quantum >> 8);
+ }
+ }
+ // create the resulting array
+ byte[] result = new byte[outIndex];
+ System.arraycopy(out, 0, result, 0, outIndex);
+ return result;
+ }
+
+ private static final byte[] MAP = new byte[] {
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
+ 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
+ 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
+ '5', '6', '7', '8', '9', '+', '/'
+ };
+
+ public static String encode(byte[] in) {
+ int length = (in.length + 2) * 4 / 3;
+ byte[] out = new byte[length];
+ int index = 0, end = in.length - in.length % 3;
+ for (int i = 0; i < end; i += 3) {
+ out[index++] = MAP[(in[i] & 0xff) >> 2];
+ out[index++] = MAP[((in[i] & 0x03) << 4) | ((in[i + 1] & 0xff) >> 4)];
+ out[index++] = MAP[((in[i + 1] & 0x0f) << 2) | ((in[i + 2] & 0xff) >> 6)];
+ out[index++] = MAP[(in[i + 2] & 0x3f)];
+ }
+ switch (in.length % 3) {
+ case 1:
+ out[index++] = MAP[(in[end] & 0xff) >> 2];
+ out[index++] = MAP[(in[end] & 0x03) << 4];
+ out[index++] = '=';
+ out[index++] = '=';
+ break;
+ case 2:
+ out[index++] = MAP[(in[end] & 0xff) >> 2];
+ out[index++] = MAP[((in[end] & 0x03) << 4) | ((in[end + 1] & 0xff) >> 4)];
+ out[index++] = MAP[((in[end + 1] & 0x0f) << 2)];
+ out[index++] = '=';
+ break;
+ }
+ try {
+ return new String(out, 0, index, "US-ASCII");
+ } catch (UnsupportedEncodingException e) {
+ throw new AssertionError(e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/DiskLruCache.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/DiskLruCache.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/DiskLruCache.java
new file mode 100644
index 0000000..f7fcb1e
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/DiskLruCache.java
@@ -0,0 +1,926 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * A cache that uses a bounded amount of space on a filesystem. Each cache
+ * entry has a string key and a fixed number of values. Each key must match
+ * the regex <strong>[a-z0-9_-]{1,64}</strong>. Values are byte sequences,
+ * accessible as streams or files. Each value must be between {@code 0} and
+ * {@code Integer.MAX_VALUE} bytes in length.
+ *
+ * <p>The cache stores its data in a directory on the filesystem. This
+ * directory must be exclusive to the cache; the cache may delete or overwrite
+ * files from its directory. It is an error for multiple processes to use the
+ * same cache directory at the same time.
+ *
+ * <p>This cache limits the number of bytes that it will store on the
+ * filesystem. When the number of stored bytes exceeds the limit, the cache will
+ * remove entries in the background until the limit is satisfied. The limit is
+ * not strict: the cache may temporarily exceed it while waiting for files to be
+ * deleted. The limit does not include filesystem overhead or the cache
+ * journal so space-sensitive applications should set a conservative limit.
+ *
+ * <p>Clients call {@link #edit} to create or update the values of an entry. An
+ * entry may have only one editor at one time; if a value is not available to be
+ * edited then {@link #edit} will return null.
+ * <ul>
+ * <li>When an entry is being <strong>created</strong> it is necessary to
+ * supply a full set of values; the empty value should be used as a
+ * placeholder if necessary.
+ * <li>When an entry is being <strong>edited</strong>, it is not necessary
+ * to supply data for every value; values default to their previous
+ * value.
+ * </ul>
+ * Every {@link #edit} call must be matched by a call to {@link Editor#commit}
+ * or {@link Editor#abort}. Committing is atomic: a read observes the full set
+ * of values as they were before or after the commit, but never a mix of values.
+ *
+ * <p>Clients call {@link #get} to read a snapshot of an entry. The read will
+ * observe the value at the time that {@link #get} was called. Updates and
+ * removals after the call do not impact ongoing reads.
+ *
+ * <p>This class is tolerant of some I/O errors. If files are missing from the
+ * filesystem, the corresponding entries will be dropped from the cache. If
+ * an error occurs while writing a cache value, the edit will fail silently.
+ * Callers should handle other problems by catching {@code IOException} and
+ * responding appropriately.
+ */
+public final class DiskLruCache implements Closeable {
+ static final String JOURNAL_FILE = "journal";
+ static final String JOURNAL_FILE_TEMP = "journal.tmp";
+ static final String JOURNAL_FILE_BACKUP = "journal.bkp";
+ static final String MAGIC = "libcore.io.DiskLruCache";
+ static final String VERSION_1 = "1";
+ static final long ANY_SEQUENCE_NUMBER = -1;
+ static final Pattern LEGAL_KEY_PATTERN = Pattern.compile("[a-z0-9_-]{1,64}");
+ private static final String CLEAN = "CLEAN";
+ private static final String DIRTY = "DIRTY";
+ private static final String REMOVE = "REMOVE";
+ private static final String READ = "READ";
+
+ /*
+ * This cache uses a journal file named "journal". A typical journal file
+ * looks like this:
+ * libcore.io.DiskLruCache
+ * 1
+ * 100
+ * 2
+ *
+ * CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
+ * DIRTY 335c4c6028171cfddfbaae1a9c313c52
+ * CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
+ * REMOVE 335c4c6028171cfddfbaae1a9c313c52
+ * DIRTY 1ab96a171faeeee38496d8b330771a7a
+ * CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
+ * READ 335c4c6028171cfddfbaae1a9c313c52
+ * READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
+ *
+ * The first five lines of the journal form its header. They are the
+ * constant string "libcore.io.DiskLruCache", the disk cache's version,
+ * the application's version, the value count, and a blank line.
+ *
+ * Each of the subsequent lines in the file is a record of the state of a
+ * cache entry. Each line contains space-separated values: a state, a key,
+ * and optional state-specific values.
+ * o DIRTY lines track that an entry is actively being created or updated.
+ * Every successful DIRTY action should be followed by a CLEAN or REMOVE
+ * action. DIRTY lines without a matching CLEAN or REMOVE indicate that
+ * temporary files may need to be deleted.
+ * o CLEAN lines track a cache entry that has been successfully published
+ * and may be read. A publish line is followed by the lengths of each of
+ * its values.
+ * o READ lines track accesses for LRU.
+ * o REMOVE lines track entries that have been deleted.
+ *
+ * The journal file is appended to as cache operations occur. The journal may
+ * occasionally be compacted by dropping redundant lines. A temporary file named
+ * "journal.tmp" will be used during compaction; that file should be deleted if
+ * it exists when the cache is opened.
+ */
+
+ private final File directory;
+ private final File journalFile;
+ private final File journalFileTmp;
+ private final File journalFileBackup;
+ private final int appVersion;
+ private long maxSize;
+ private final int valueCount;
+ private long size = 0;
+ private Writer journalWriter;
+ private final LinkedHashMap<String, Entry> lruEntries =
+ new LinkedHashMap<String, Entry>(0, 0.75f, true);
+ private int redundantOpCount;
+
+ /**
+ * To differentiate between old and current snapshots, each entry is given
+ * a sequence number each time an edit is committed. A snapshot is stale if
+ * its sequence number is not equal to its entry's sequence number.
+ */
+ private long nextSequenceNumber = 0;
+
+ /** This cache uses a single background thread to evict entries. */
+ final ThreadPoolExecutor executorService =
+ new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
+ private final Callable<Void> cleanupCallable = new Callable<Void>() {
+ public Void call() throws Exception {
+ synchronized (DiskLruCache.this) {
+ if (journalWriter == null) {
+ return null; // Closed.
+ }
+ trimToSize();
+ if (journalRebuildRequired()) {
+ rebuildJournal();
+ redundantOpCount = 0;
+ }
+ }
+ return null;
+ }
+ };
+
+ private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
+ this.directory = directory;
+ this.appVersion = appVersion;
+ this.journalFile = new File(directory, JOURNAL_FILE);
+ this.journalFileTmp = new File(directory, JOURNAL_FILE_TEMP);
+ this.journalFileBackup = new File(directory, JOURNAL_FILE_BACKUP);
+ this.valueCount = valueCount;
+ this.maxSize = maxSize;
+ }
+
+ /**
+ * Opens the cache in {@code directory}, creating a cache if none exists
+ * there.
+ *
+ * @param directory a writable directory
+ * @param valueCount the number of values per cache entry. Must be positive.
+ * @param maxSize the maximum number of bytes this cache should use to store
+ * @throws IOException if reading or writing the cache directory fails
+ */
+ public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
+ throws IOException {
+ if (maxSize <= 0) {
+ throw new IllegalArgumentException("maxSize <= 0");
+ }
+ if (valueCount <= 0) {
+ throw new IllegalArgumentException("valueCount <= 0");
+ }
+
+ // If a bkp file exists, use it instead.
+ File backupFile = new File(directory, JOURNAL_FILE_BACKUP);
+ if (backupFile.exists()) {
+ File journalFile = new File(directory, JOURNAL_FILE);
+ // If journal file also exists just delete backup file.
+ if (journalFile.exists()) {
+ backupFile.delete();
+ } else {
+ renameTo(backupFile, journalFile, false);
+ }
+ }
+
+ // Prefer to pick up where we left off.
+ DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
+ if (cache.journalFile.exists()) {
+ try {
+ cache.readJournal();
+ cache.processJournal();
+ cache.journalWriter = new BufferedWriter(
+ new OutputStreamWriter(new FileOutputStream(cache.journalFile, true), Util.US_ASCII));
+ return cache;
+ } catch (IOException journalIsCorrupt) {
+ Platform.get().logW("DiskLruCache " + directory + " is corrupt: "
+ + journalIsCorrupt.getMessage() + ", removing");
+ cache.delete();
+ }
+ }
+
+ // Create a new empty cache.
+ directory.mkdirs();
+ cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
+ cache.rebuildJournal();
+ return cache;
+ }
+
+ private void readJournal() throws IOException {
+ StrictLineReader reader = new StrictLineReader(new FileInputStream(journalFile), Util.US_ASCII);
+ try {
+ String magic = reader.readLine();
+ String version = reader.readLine();
+ String appVersionString = reader.readLine();
+ String valueCountString = reader.readLine();
+ String blank = reader.readLine();
+ if (!MAGIC.equals(magic)
+ || !VERSION_1.equals(version)
+ || !Integer.toString(appVersion).equals(appVersionString)
+ || !Integer.toString(valueCount).equals(valueCountString)
+ || !"".equals(blank)) {
+ throw new IOException("unexpected journal header: [" + magic + ", " + version + ", "
+ + valueCountString + ", " + blank + "]");
+ }
+
+ int lineCount = 0;
+ while (true) {
+ try {
+ readJournalLine(reader.readLine());
+ lineCount++;
+ } catch (EOFException endOfJournal) {
+ break;
+ }
+ }
+ redundantOpCount = lineCount - lruEntries.size();
+ } finally {
+ Util.closeQuietly(reader);
+ }
+ }
+
+ private void readJournalLine(String line) throws IOException {
+ int firstSpace = line.indexOf(' ');
+ if (firstSpace == -1) {
+ throw new IOException("unexpected journal line: " + line);
+ }
+
+ int keyBegin = firstSpace + 1;
+ int secondSpace = line.indexOf(' ', keyBegin);
+ final String key;
+ if (secondSpace == -1) {
+ key = line.substring(keyBegin);
+ if (firstSpace == REMOVE.length() && line.startsWith(REMOVE)) {
+ lruEntries.remove(key);
+ return;
+ }
+ } else {
+ key = line.substring(keyBegin, secondSpace);
+ }
+
+ Entry entry = lruEntries.get(key);
+ if (entry == null) {
+ entry = new Entry(key);
+ lruEntries.put(key, entry);
+ }
+
+ if (secondSpace != -1 && firstSpace == CLEAN.length() && line.startsWith(CLEAN)) {
+ String[] parts = line.substring(secondSpace + 1).split(" ");
+ entry.readable = true;
+ entry.currentEditor = null;
+ entry.setLengths(parts);
+ } else if (secondSpace == -1 && firstSpace == DIRTY.length() && line.startsWith(DIRTY)) {
+ entry.currentEditor = new Editor(entry);
+ } else if (secondSpace == -1 && firstSpace == READ.length() && line.startsWith(READ)) {
+ // This work was already done by calling lruEntries.get().
+ } else {
+ throw new IOException("unexpected journal line: " + line);
+ }
+ }
+
+ /**
+ * Computes the initial size and collects garbage as a part of opening the
+ * cache. Dirty entries are assumed to be inconsistent and will be deleted.
+ */
+ private void processJournal() throws IOException {
+ deleteIfExists(journalFileTmp);
+ for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
+ Entry entry = i.next();
+ if (entry.currentEditor == null) {
+ for (int t = 0; t < valueCount; t++) {
+ size += entry.lengths[t];
+ }
+ } else {
+ entry.currentEditor = null;
+ for (int t = 0; t < valueCount; t++) {
+ deleteIfExists(entry.getCleanFile(t));
+ deleteIfExists(entry.getDirtyFile(t));
+ }
+ i.remove();
+ }
+ }
+ }
+
+ /**
+ * Creates a new journal that omits redundant information. This replaces the
+ * current journal if it exists.
+ */
+ private synchronized void rebuildJournal() throws IOException {
+ if (journalWriter != null) {
+ journalWriter.close();
+ }
+
+ Writer writer = new BufferedWriter(
+ new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII));
+ try {
+ writer.write(MAGIC);
+ writer.write("\n");
+ writer.write(VERSION_1);
+ writer.write("\n");
+ writer.write(Integer.toString(appVersion));
+ writer.write("\n");
+ writer.write(Integer.toString(valueCount));
+ writer.write("\n");
+ writer.write("\n");
+
+ for (Entry entry : lruEntries.values()) {
+ if (entry.currentEditor != null) {
+ writer.write(DIRTY + ' ' + entry.key + '\n');
+ } else {
+ writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
+ }
+ }
+ } finally {
+ writer.close();
+ }
+
+ if (journalFile.exists()) {
+ renameTo(journalFile, journalFileBackup, true);
+ }
+ renameTo(journalFileTmp, journalFile, false);
+ journalFileBackup.delete();
+
+ journalWriter = new BufferedWriter(
+ new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII));
+ }
+
+ private static void deleteIfExists(File file) throws IOException {
+ if (file.exists() && !file.delete()) {
+ throw new IOException();
+ }
+ }
+
+ private static void renameTo(File from, File to, boolean deleteDestination) throws IOException {
+ if (deleteDestination) {
+ deleteIfExists(to);
+ }
+ if (!from.renameTo(to)) {
+ throw new IOException();
+ }
+ }
+
+ /**
+ * Returns a snapshot of the entry named {@code key}, or null if it doesn't
+ * exist is not currently readable. If a value is returned, it is moved to
+ * the head of the LRU queue.
+ */
+ public synchronized Snapshot get(String key) throws IOException {
+ checkNotClosed();
+ validateKey(key);
+ Entry entry = lruEntries.get(key);
+ if (entry == null) {
+ return null;
+ }
+
+ if (!entry.readable) {
+ return null;
+ }
+
+ // Open all streams eagerly to guarantee that we see a single published
+ // snapshot. If we opened streams lazily then the streams could come
+ // from different edits.
+ InputStream[] ins = new InputStream[valueCount];
+ try {
+ for (int i = 0; i < valueCount; i++) {
+ ins[i] = new FileInputStream(entry.getCleanFile(i));
+ }
+ } catch (FileNotFoundException e) {
+ // A file must have been deleted manually!
+ for (int i = 0; i < valueCount; i++) {
+ if (ins[i] != null) {
+ Util.closeQuietly(ins[i]);
+ } else {
+ break;
+ }
+ }
+ return null;
+ }
+
+ redundantOpCount++;
+ journalWriter.append(READ + ' ' + key + '\n');
+ if (journalRebuildRequired()) {
+ executorService.submit(cleanupCallable);
+ }
+
+ return new Snapshot(key, entry.sequenceNumber, ins, entry.lengths);
+ }
+
+ /**
+ * Returns an editor for the entry named {@code key}, or null if another
+ * edit is in progress.
+ */
+ public Editor edit(String key) throws IOException {
+ return edit(key, ANY_SEQUENCE_NUMBER);
+ }
+
+ private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
+ checkNotClosed();
+ validateKey(key);
+ Entry entry = lruEntries.get(key);
+ if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null
+ || entry.sequenceNumber != expectedSequenceNumber)) {
+ return null; // Snapshot is stale.
+ }
+ if (entry == null) {
+ entry = new Entry(key);
+ lruEntries.put(key, entry);
+ } else if (entry.currentEditor != null) {
+ return null; // Another edit is in progress.
+ }
+
+ Editor editor = new Editor(entry);
+ entry.currentEditor = editor;
+
+ // Flush the journal before creating files to prevent file leaks.
+ journalWriter.write(DIRTY + ' ' + key + '\n');
+ journalWriter.flush();
+ return editor;
+ }
+
+ /** Returns the directory where this cache stores its data. */
+ public File getDirectory() {
+ return directory;
+ }
+
+ /**
+ * Returns the maximum number of bytes that this cache should use to store
+ * its data.
+ */
+ public long getMaxSize() {
+ return maxSize;
+ }
+
+ /**
+ * Changes the maximum number of bytes the cache can store and queues a job
+ * to trim the existing store, if necessary.
+ */
+ public synchronized void setMaxSize(long maxSize) {
+ this.maxSize = maxSize;
+ executorService.submit(cleanupCallable);
+ }
+
+ /**
+ * Returns the number of bytes currently being used to store the values in
+ * this cache. This may be greater than the max size if a background
+ * deletion is pending.
+ */
+ public synchronized long size() {
+ return size;
+ }
+
+ private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
+ Entry entry = editor.entry;
+ if (entry.currentEditor != editor) {
+ throw new IllegalStateException();
+ }
+
+ // If this edit is creating the entry for the first time, every index must have a value.
+ if (success && !entry.readable) {
+ for (int i = 0; i < valueCount; i++) {
+ if (!editor.written[i]) {
+ editor.abort();
+ throw new IllegalStateException("Newly created entry didn't create value for index " + i);
+ }
+ if (!entry.getDirtyFile(i).exists()) {
+ editor.abort();
+ return;
+ }
+ }
+ }
+
+ for (int i = 0; i < valueCount; i++) {
+ File dirty = entry.getDirtyFile(i);
+ if (success) {
+ if (dirty.exists()) {
+ File clean = entry.getCleanFile(i);
+ dirty.renameTo(clean);
+ long oldLength = entry.lengths[i];
+ long newLength = clean.length();
+ entry.lengths[i] = newLength;
+ size = size - oldLength + newLength;
+ }
+ } else {
+ deleteIfExists(dirty);
+ }
+ }
+
+ redundantOpCount++;
+ entry.currentEditor = null;
+ if (entry.readable | success) {
+ entry.readable = true;
+ journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
+ if (success) {
+ entry.sequenceNumber = nextSequenceNumber++;
+ }
+ } else {
+ lruEntries.remove(entry.key);
+ journalWriter.write(REMOVE + ' ' + entry.key + '\n');
+ }
+ journalWriter.flush();
+
+ if (size > maxSize || journalRebuildRequired()) {
+ executorService.submit(cleanupCallable);
+ }
+ }
+
+ /**
+ * We only rebuild the journal when it will halve the size of the journal
+ * and eliminate at least 2000 ops.
+ */
+ private boolean journalRebuildRequired() {
+ final int redundantOpCompactThreshold = 2000;
+ return redundantOpCount >= redundantOpCompactThreshold //
+ && redundantOpCount >= lruEntries.size();
+ }
+
+ /**
+ * Drops the entry for {@code key} if it exists and can be removed. Entries
+ * actively being edited cannot be removed.
+ *
+ * @return true if an entry was removed.
+ */
+ public synchronized boolean remove(String key) throws IOException {
+ checkNotClosed();
+ validateKey(key);
+ Entry entry = lruEntries.get(key);
+ if (entry == null || entry.currentEditor != null) {
+ return false;
+ }
+
+ for (int i = 0; i < valueCount; i++) {
+ File file = entry.getCleanFile(i);
+ if (!file.delete()) {
+ throw new IOException("failed to delete " + file);
+ }
+ size -= entry.lengths[i];
+ entry.lengths[i] = 0;
+ }
+
+ redundantOpCount++;
+ journalWriter.append(REMOVE + ' ' + key + '\n');
+ lruEntries.remove(key);
+
+ if (journalRebuildRequired()) {
+ executorService.submit(cleanupCallable);
+ }
+
+ return true;
+ }
+
+ /** Returns true if this cache has been closed. */
+ public boolean isClosed() {
+ return journalWriter == null;
+ }
+
+ private void checkNotClosed() {
+ if (journalWriter == null) {
+ throw new IllegalStateException("cache is closed");
+ }
+ }
+
+ /** Force buffered operations to the filesystem. */
+ public synchronized void flush() throws IOException {
+ checkNotClosed();
+ trimToSize();
+ journalWriter.flush();
+ }
+
+ /** Closes this cache. Stored values will remain on the filesystem. */
+ public synchronized void close() throws IOException {
+ if (journalWriter == null) {
+ return; // Already closed.
+ }
+ for (Entry entry : new ArrayList<Entry>(lruEntries.values())) {
+ if (entry.currentEditor != null) {
+ entry.currentEditor.abort();
+ }
+ }
+ trimToSize();
+ journalWriter.close();
+ journalWriter = null;
+ }
+
+ private void trimToSize() throws IOException {
+ while (size > maxSize) {
+ Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();
+ remove(toEvict.getKey());
+ }
+ }
+
+ /**
+ * Closes the cache and deletes all of its stored values. This will delete
+ * all files in the cache directory including files that weren't created by
+ * the cache.
+ */
+ public void delete() throws IOException {
+ close();
+ Util.deleteContents(directory);
+ }
+
+ private void validateKey(String key) {
+ Matcher matcher = LEGAL_KEY_PATTERN.matcher(key);
+ if (!matcher.matches()) {
+ throw new IllegalArgumentException("keys must match regex [a-z0-9_-]{1,64}: \"" + key + "\"");
+ }
+ }
+
+ private static String inputStreamToString(InputStream in) throws IOException {
+ return Util.readFully(new InputStreamReader(in, Util.UTF_8));
+ }
+
+ /** A snapshot of the values for an entry. */
+ public final class Snapshot implements Closeable {
+ private final String key;
+ private final long sequenceNumber;
+ private final InputStream[] ins;
+ private final long[] lengths;
+
+ private Snapshot(String key, long sequenceNumber, InputStream[] ins, long[] lengths) {
+ this.key = key;
+ this.sequenceNumber = sequenceNumber;
+ this.ins = ins;
+ this.lengths = lengths;
+ }
+
+ /**
+ * Returns an editor for this snapshot's entry, or null if either the
+ * entry has changed since this snapshot was created or if another edit
+ * is in progress.
+ */
+ public Editor edit() throws IOException {
+ return DiskLruCache.this.edit(key, sequenceNumber);
+ }
+
+ /** Returns the unbuffered stream with the value for {@code index}. */
+ public InputStream getInputStream(int index) {
+ return ins[index];
+ }
+
+ /** Returns the string value for {@code index}. */
+ public String getString(int index) throws IOException {
+ return inputStreamToString(getInputStream(index));
+ }
+
+ /** Returns the byte length of the value for {@code index}. */
+ public long getLength(int index) {
+ return lengths[index];
+ }
+
+ public void close() {
+ for (InputStream in : ins) {
+ Util.closeQuietly(in);
+ }
+ }
+ }
+
+ private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() {
+ @Override
+ public void write(int b) throws IOException {
+ // Eat all writes silently. Nom nom.
+ }
+ };
+
+ /** Edits the values for an entry. */
+ public final class Editor {
+ private final Entry entry;
+ private final boolean[] written;
+ private boolean hasErrors;
+ private boolean committed;
+
+ private Editor(Entry entry) {
+ this.entry = entry;
+ this.written = (entry.readable) ? null : new boolean[valueCount];
+ }
+
+ /**
+ * Returns an unbuffered input stream to read the last committed value,
+ * or null if no value has been committed.
+ */
+ public InputStream newInputStream(int index) throws IOException {
+ synchronized (DiskLruCache.this) {
+ if (entry.currentEditor != this) {
+ throw new IllegalStateException();
+ }
+ if (!entry.readable) {
+ return null;
+ }
+ try {
+ return new FileInputStream(entry.getCleanFile(index));
+ } catch (FileNotFoundException e) {
+ return null;
+ }
+ }
+ }
+
+ /**
+ * Returns the last committed value as a string, or null if no value
+ * has been committed.
+ */
+ public String getString(int index) throws IOException {
+ InputStream in = newInputStream(index);
+ return in != null ? inputStreamToString(in) : null;
+ }
+
+ /**
+ * Returns a new unbuffered output stream to write the value at
+ * {@code index}. If the underlying output stream encounters errors
+ * when writing to the filesystem, this edit will be aborted when
+ * {@link #commit} is called. The returned output stream does not throw
+ * IOExceptions.
+ */
+ public OutputStream newOutputStream(int index) throws IOException {
+ synchronized (DiskLruCache.this) {
+ if (entry.currentEditor != this) {
+ throw new IllegalStateException();
+ }
+ if (!entry.readable) {
+ written[index] = true;
+ }
+ File dirtyFile = entry.getDirtyFile(index);
+ FileOutputStream outputStream;
+ try {
+ outputStream = new FileOutputStream(dirtyFile);
+ } catch (FileNotFoundException e) {
+ // Attempt to recreate the cache directory.
+ directory.mkdirs();
+ try {
+ outputStream = new FileOutputStream(dirtyFile);
+ } catch (FileNotFoundException e2) {
+ // We are unable to recover. Silently eat the writes.
+ return NULL_OUTPUT_STREAM;
+ }
+ }
+ return new FaultHidingOutputStream(outputStream);
+ }
+ }
+
+ /** Sets the value at {@code index} to {@code value}. */
+ public void set(int index, String value) throws IOException {
+ Writer writer = null;
+ try {
+ writer = new OutputStreamWriter(newOutputStream(index), Util.UTF_8);
+ writer.write(value);
+ } finally {
+ Util.closeQuietly(writer);
+ }
+ }
+
+ /**
+ * Commits this edit so it is visible to readers. This releases the
+ * edit lock so another edit may be started on the same key.
+ */
+ public void commit() throws IOException {
+ if (hasErrors) {
+ completeEdit(this, false);
+ remove(entry.key); // The previous entry is stale.
+ } else {
+ completeEdit(this, true);
+ }
+ committed = true;
+ }
+
+ /**
+ * Aborts this edit. This releases the edit lock so another edit may be
+ * started on the same key.
+ */
+ public void abort() throws IOException {
+ completeEdit(this, false);
+ }
+
+ public void abortUnlessCommitted() {
+ if (!committed) {
+ try {
+ abort();
+ } catch (IOException ignored) {
+ }
+ }
+ }
+
+ private class FaultHidingOutputStream extends FilterOutputStream {
+ private FaultHidingOutputStream(OutputStream out) {
+ super(out);
+ }
+
+ @Override public void write(int oneByte) {
+ try {
+ out.write(oneByte);
+ } catch (IOException e) {
+ hasErrors = true;
+ }
+ }
+
+ @Override public void write(byte[] buffer, int offset, int length) {
+ try {
+ out.write(buffer, offset, length);
+ } catch (IOException e) {
+ hasErrors = true;
+ }
+ }
+
+ @Override public void close() {
+ try {
+ out.close();
+ } catch (IOException e) {
+ hasErrors = true;
+ }
+ }
+
+ @Override public void flush() {
+ try {
+ out.flush();
+ } catch (IOException e) {
+ hasErrors = true;
+ }
+ }
+ }
+ }
+
+ private final class Entry {
+ private final String key;
+
+ /** Lengths of this entry's files. */
+ private final long[] lengths;
+
+ /** True if this entry has ever been published. */
+ private boolean readable;
+
+ /** The ongoing edit or null if this entry is not being edited. */
+ private Editor currentEditor;
+
+ /** The sequence number of the most recently committed edit to this entry. */
+ private long sequenceNumber;
+
+ private Entry(String key) {
+ this.key = key;
+ this.lengths = new long[valueCount];
+ }
+
+ public String getLengths() throws IOException {
+ StringBuilder result = new StringBuilder();
+ for (long size : lengths) {
+ result.append(' ').append(size);
+ }
+ return result.toString();
+ }
+
+ /** Set lengths using decimal numbers like "10123". */
+ private void setLengths(String[] strings) throws IOException {
+ if (strings.length != valueCount) {
+ throw invalidLengths(strings);
+ }
+
+ try {
+ for (int i = 0; i < strings.length; i++) {
+ lengths[i] = Long.parseLong(strings[i]);
+ }
+ } catch (NumberFormatException e) {
+ throw invalidLengths(strings);
+ }
+ }
+
+ private IOException invalidLengths(String[] strings) throws IOException {
+ throw new IOException("unexpected journal line: " + java.util.Arrays.toString(strings));
+ }
+
+ public File getCleanFile(int i) {
+ return new File(directory, key + "." + i);
+ }
+
+ public File getDirtyFile(int i) {
+ return new File(directory, key + "." + i + ".tmp");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Dns.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Dns.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Dns.java
new file mode 100644
index 0000000..69b2d37
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/Dns.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2012 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+/**
+ * Domain name service. Prefer this over {@link InetAddress#getAllByName} to
+ * make code more testable.
+ */
+public interface Dns {
+ Dns DEFAULT = new Dns() {
+ @Override public InetAddress[] getAllByName(String host) throws UnknownHostException {
+ return InetAddress.getAllByName(host);
+ }
+ };
+
+ InetAddress[] getAllByName(String host) throws UnknownHostException;
+}
[08/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/package.json
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/package.json b/lib/cordova-blackberry/package.json
new file mode 100644
index 0000000..a879ba3
--- /dev/null
+++ b/lib/cordova-blackberry/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "cordova-blackberry",
+ "version": "0.0.1",
+ "description": "cordova-blackberry",
+ "repository": "https://git-wip-us.apache.org/repos/asf?p=cordova-blackberry.git",
+ "author": {
+ "name": "BlackBerry",
+ "url": "http://developer.blackberry.com/html5/"
+ },
+ "licenses": [{
+ "type": "Apache 2.0",
+ "url": "http://www.apache.org/licenses/LICENSE-2.0"
+ }],
+ "scripts": {
+ "test": "./node_modules/jake/bin/cli.js"
+ },
+ "dependencies": {
+ "jasmine-node": "1.0.7",
+ "jWorkflow": "0.8.0",
+ "commander": "0.5.2",
+ "localize": "*0.4.2",
+ "zip": "0.0.6",
+ "xml2js": "0.1.13",
+ "validator": "0.4.1",
+ "wrench": "1.3.9",
+ "shelljs":"0.1.2",
+ "elementtree": "0.1.x",
+ "plugman": "0.7.7"
+ },
+ "devDependencies": {
+ "jake":"*"
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Accelerometer/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Accelerometer/plugin.xml b/lib/cordova-blackberry/plugins/Accelerometer/plugin.xml
new file mode 100644
index 0000000..0c8d3dd
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Accelerometer/plugin.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.core.Accelerometer"
+ version="0.0.1">
+
+ <name>Device Motion</name>
+
+ <platform name="blackberry10">
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="Accelerometer" value="Accelerometer"/>
+ </config-file>
+ <source-file src="src/blackberry10/index.js" target-dir="Accelerometer" />
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Accelerometer/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Accelerometer/src/blackberry10/index.js b/lib/cordova-blackberry/plugins/Accelerometer/src/blackberry10/index.js
new file mode 100644
index 0000000..47abe42
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Accelerometer/src/blackberry10/index.js
@@ -0,0 +1,45 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+*/
+
+var callback;
+
+module.exports = {
+ start: function (success, fail, args, env) {
+ var result = new PluginResult(args, env);
+ window.removeEventListener("devicemotion", callback);
+ callback = function (motion) {
+ var info = {
+ x: motion.accelerationIncludingGravity.x,
+ y: motion.accelerationIncludingGravity.y,
+ z: motion.accelerationIncludingGravity.z,
+ timestamp: motion.timestamp
+ };
+ result.callbackOk(info, true);
+ };
+ window.addEventListener("devicemotion", callback);
+ result.noResult(true);
+ },
+ stop: function (success, fail, args, env) {
+ var result = new PluginResult(args, env);
+ window.removeEventListener("devicemotion", callback);
+ result.ok("removed");
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Battery/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Battery/plugin.xml b/lib/cordova-blackberry/plugins/Battery/plugin.xml
new file mode 100644
index 0000000..58b6356
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Battery/plugin.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.core.Battery"
+ version="0.0.1">
+
+ <name>Battery</name>
+
+ <platform name="blackberry10">
+ <source-file src="src/blackberry10/index.js" target-dir="Battery" />
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="Battery" value="Battery"/>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Battery/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Battery/src/blackberry10/index.js b/lib/cordova-blackberry/plugins/Battery/src/blackberry10/index.js
new file mode 100644
index 0000000..07a943c
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Battery/src/blackberry10/index.js
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var SYSTEM_EVENTS = ["device.battery.statusChange",
+ "device.battery.chargeLow",
+ "device.battery.chargeCritical"],
+ device = window.qnx.webplatform.device,
+ _clientListeners = {};
+
+module.exports = {
+ start: function (success, fail, args, env) {
+ var result = new PluginResult(args, env),
+ listener = function (info) {
+ result.callbackOk(info, true);
+ };
+
+ if (_clientListeners[env.webview.id]) {
+ //TODO: Change back to erroring out after reset is implemented
+ //result.error("Battery listener already running");
+ SYSTEM_EVENTS.forEach(function (event) {
+ device.removeEventListener(event, _clientListeners[env.webview.id]);
+ });
+ }
+
+ _clientListeners[env.webview.id] = listener;
+ SYSTEM_EVENTS.forEach(function (event) {
+ device.addEventListener(event, listener);
+ });
+ result.noResult(true);
+ },
+ stop: function (success, fail, args, env) {
+ var result = new PluginResult(args, env),
+ listener = _clientListeners[env.webview.id];
+
+ if (!listener) {
+ result.error("Battery listener has not started");
+ } else {
+ SYSTEM_EVENTS.forEach(function (event) {
+ device.removeEventListener(event, listener);
+ });
+ delete _clientListeners[env.webview.id];
+ result.noResult(false);
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Camera/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Camera/plugin.xml b/lib/cordova-blackberry/plugins/Camera/plugin.xml
new file mode 100644
index 0000000..4fe8693
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Camera/plugin.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.core.Camera"
+ version="0.0.1">
+
+ <name>Camera</name>
+
+ <platform name="blackberry10">
+ <source-file src="src/blackberry10/index.js" target-dir="Camera" />
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="Camera" value="Camera"/>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Camera/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Camera/src/blackberry10/index.js b/lib/cordova-blackberry/plugins/Camera/src/blackberry10/index.js
new file mode 100644
index 0000000..922f049
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Camera/src/blackberry10/index.js
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var PictureSourceType = {
+ PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
+ CAMERA : 1, // Take picture from camera
+ SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
+ },
+ DestinationType = {
+ DATA_URL: 0, // Return base64 encoded string
+ FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
+ NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
+ };
+
+function encodeBase64(filePath, callback) {
+ var sandbox = window.qnx.webplatform.getController().setFileSystemSandbox, // save original sandbox value
+ errorHandler = function (err) {
+ var msg = "An error occured: ";
+
+ switch (err.code) {
+ case FileError.NOT_FOUND_ERR:
+ msg += "File or directory not found";
+ break;
+
+ case FileError.NOT_READABLE_ERR:
+ msg += "File or directory not readable";
+ break;
+
+ case FileError.PATH_EXISTS_ERR:
+ msg += "File or directory already exists";
+ break;
+
+ case FileError.TYPE_MISMATCH_ERR:
+ msg += "Invalid file type";
+ break;
+
+ default:
+ msg += "Unknown Error";
+ break;
+ };
+
+ // set it back to original value
+ window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
+ callback(msg);
+ },
+ gotFile = function (fileEntry) {
+ fileEntry.file(function (file) {
+ var reader = new FileReader();
+
+ reader.onloadend = function (e) {
+ // set it back to original value
+ window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
+ callback(this.result);
+ };
+
+ reader.readAsDataURL(file);
+ }, errorHandler);
+ },
+ onInitFs = function (fs) {
+ window.qnx.webplatform.getController().setFileSystemSandbox = false;
+ fs.root.getFile(filePath, {create: false}, gotFile, errorHandler);
+ };
+
+ window.webkitRequestFileSystem(window.TEMPORARY, 10 * 1024 * 1024, onInitFs, errorHandler); // set size to 10MB max
+}
+
+module.exports = {
+ takePicture: function (success, fail, args, env) {
+ var destinationType = JSON.parse(decodeURIComponent(args[1])),
+ sourceType = JSON.parse(decodeURIComponent(args[2])),
+ result = new PluginResult(args, env),
+ done = function (data) {
+ if (destinationType === DestinationType.FILE_URI) {
+ data = "file://" + data;
+ result.callbackOk(data, false);
+ } else {
+ encodeBase64(data, function (data) {
+ if (/^data:/.test(data)) {
+ data = data.slice(data.indexOf(",") + 1);
+ result.callbackOk(data, false);
+ } else {
+ result.callbackError(data, false);
+ }
+ });
+ }
+ },
+ cancel = function (reason) {
+ result.callbackError(reason, false);
+ },
+ invoked = function (error) {
+ if (error) {
+ result.callbackError(error, false);
+ }
+ };
+
+ switch(sourceType) {
+ case PictureSourceType.CAMERA:
+ window.qnx.webplatform.getApplication().cards.camera.open("photo", done, cancel, invoked);
+ break;
+
+ case PictureSourceType.PHOTOLIBRARY:
+ case PictureSourceType.SAVEDPHOTOALBUM:
+ window.qnx.webplatform.getApplication().cards.filePicker.open({
+ mode: "Picker",
+ type: ["picture"]
+ }, done, cancel, invoked);
+ break;
+ }
+
+ result.noResult(true);
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/plugin.xml b/lib/cordova-blackberry/plugins/Contacts/plugin.xml
new file mode 100644
index 0000000..d163585
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/plugin.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.core.Contacts"
+ version="0.0.1">
+
+ <name>Contacts</name>
+
+ <platform name="blackberry10">
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="Contacts" value="Contacts"/>
+ </config-file>
+ <source-file src="src/blackberry10/index.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/ContactActivity.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/ContactAddress.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/contactConsts.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/ContactError.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/ContactField.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/ContactFindOptions.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/ContactName.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/ContactNews.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/ContactOrganization.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/ContactPhoto.js" target-dir="Contacts"></source-file>
+ <source-file src="src/blackberry10/contactUtils.js" target-dir="Contacts"></source-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactActivity.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactActivity.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactActivity.js
new file mode 100644
index 0000000..0794d23
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactActivity.js
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ContactActivity = function (args) {
+ this.direction = args.direction || null;
+ this.description = args.description || "";
+ this.mimeType = args.mimeType || "";
+ this.timestamp = new Date(parseInt(args.timestamp, 10)) || null;
+};
+
+Object.defineProperty(ContactActivity, "INCOMING", {"value": true});
+Object.defineProperty(ContactActivity, "OUTGOING", {"value": false});
+
+module.exports = ContactActivity;
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactAddress.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactAddress.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactAddress.js
new file mode 100644
index 0000000..1ba9fe4
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactAddress.js
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ContactAddress = function (properties) {
+ this.type = properties && properties.type ? properties.type : "";
+ this.streetAddress = properties && properties.streetAddress ? properties.streetAddress : "";
+ this.streetOther = properties && properties.streetOther ? properties.streetOther : "";
+ this.locality = properties && properties.locality ? properties.locality : "";
+ this.region = properties && properties.region ? properties.region : "";
+ this.postalCode = properties && properties.postalCode ? properties.postalCode : "";
+ this.country = properties && properties.country ? properties.country : "";
+};
+
+Object.defineProperty(ContactAddress, "HOME", {"value": "home"});
+Object.defineProperty(ContactAddress, "WORK", {"value": "work"});
+Object.defineProperty(ContactAddress, "OTHER", {"value": "other"});
+
+module.exports = ContactAddress;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactError.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactError.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactError.js
new file mode 100644
index 0000000..f20f85e
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactError.js
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ContactError = function (code, msg) {
+ this.code = code;
+ this.message = msg;
+};
+
+Object.defineProperty(ContactError, "UNKNOWN_ERROR", { "value": 0 });
+Object.defineProperty(ContactError, "INVALID_ARGUMENT_ERROR", { "value": 1 });
+Object.defineProperty(ContactError, "TIMEOUT_ERROR", { "value": 2 });
+Object.defineProperty(ContactError, "PENDING_OPERATION_ERROR", { "value": 3 });
+Object.defineProperty(ContactError, "IO_ERROR", { "value": 4 });
+Object.defineProperty(ContactError, "NOT_SUPPORTED_ERROR", { "value": 5 });
+Object.defineProperty(ContactError, "PERMISSION_DENIED_ERROR", { "value": 20 });
+
+module.exports = ContactError;
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactField.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactField.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactField.js
new file mode 100644
index 0000000..aad735c
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactField.js
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ContactField = function (type, value) {
+ this.type = type || "";
+ this.value = value || "";
+};
+
+Object.defineProperty(ContactField, "HOME", {"value": "home"});
+Object.defineProperty(ContactField, "WORK", {"value": "work"});
+Object.defineProperty(ContactField, "OTHER", {"value": "other"});
+Object.defineProperty(ContactField, "MOBILE", {"value": "mobile"});
+Object.defineProperty(ContactField, "DIRECT", {"value": "direct"});
+
+module.exports = ContactField;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactFindOptions.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactFindOptions.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactFindOptions.js
new file mode 100644
index 0000000..8be830d
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactFindOptions.js
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * ContactFindOptions.
+ * @constructor
+ * @param filter search fields
+ * @param sort sort fields and order
+ * @param limit max number of contacts to return
+ * @param favorite if set, only favorite contacts will be returned
+ */
+
+var ContactFindOptions = function (filter, sort, limit, favorite) {
+ this.filter = filter || null;
+ this.sort = sort || null;
+ this.limit = limit || -1; // -1 for returning all results
+ this.favorite = favorite || false;
+ this.includeAccounts = [];
+ this.excludeAccounts = [];
+};
+
+Object.defineProperty(ContactFindOptions, "SEARCH_FIELD_GIVEN_NAME", { "value": 0 });
+Object.defineProperty(ContactFindOptions, "SEARCH_FIELD_FAMILY_NAME", { "value": 1 });
+Object.defineProperty(ContactFindOptions, "SEARCH_FIELD_ORGANIZATION_NAME", { "value": 2 });
+Object.defineProperty(ContactFindOptions, "SEARCH_FIELD_PHONE", { "value": 3 });
+Object.defineProperty(ContactFindOptions, "SEARCH_FIELD_EMAIL", { "value": 4 });
+Object.defineProperty(ContactFindOptions, "SEARCH_FIELD_BBMPIN", { "value": 5 });
+Object.defineProperty(ContactFindOptions, "SEARCH_FIELD_LINKEDIN", { "value": 6 });
+Object.defineProperty(ContactFindOptions, "SEARCH_FIELD_TWITTER", { "value": 7 });
+Object.defineProperty(ContactFindOptions, "SEARCH_FIELD_VIDEO_CHAT", { "value": 8 });
+
+Object.defineProperty(ContactFindOptions, "SORT_FIELD_GIVEN_NAME", { "value": 0 });
+Object.defineProperty(ContactFindOptions, "SORT_FIELD_FAMILY_NAME", { "value": 1 });
+Object.defineProperty(ContactFindOptions, "SORT_FIELD_ORGANIZATION_NAME", { "value": 2 });
+
+module.exports = ContactFindOptions;
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactName.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactName.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactName.js
new file mode 100644
index 0000000..9b74753
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactName.js
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+function toFormattedName(properties) {
+ var formatted = "";
+ if (properties && properties.givenName) {
+ formatted = properties.givenName;
+ if (properties && properties.familyName) {
+ formatted += " " + properties.familyName;
+ }
+ }
+ return formatted;
+}
+
+var ContactName = function (properties) {
+ this.familyName = properties && properties.familyName ? properties.familyName : "";
+ this.givenName = properties && properties.givenName ? properties.givenName : "";
+ this.formatted = toFormattedName(properties);
+ this.middleName = properties && properties.middleName ? properties.middleName : "";
+ this.honorificPrefix = properties && properties.honorificPrefix ? properties.honorificPrefix : "";
+ this.honorificSuffix = properties && properties.honorificSuffix ? properties.honorificSuffix : "";
+ this.phoneticFamilyName = properties && properties.phoneticFamilyName ? properties.phoneticFamilyName : "";
+ this.phoneticGivenName = properties && properties.phoneticGivenName ? properties.phoneticGivenName : "";
+};
+
+module.exports = ContactName;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactNews.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactNews.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactNews.js
new file mode 100644
index 0000000..7aa9d8c
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactNews.js
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ContactNews = function (args) {
+ this.title = args.title || "";
+ this.body = args.body || "";
+ this.articleSource = args.articleSource || "";
+ this.companies = args.companies || [];
+ this.publishedAt = new Date(parseInt(args.publishedAt, 10)) || null;
+ this.uri = args.uri || "";
+ this.type = args.type || "";
+};
+
+module.exports = ContactNews;
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactOrganization.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactOrganization.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactOrganization.js
new file mode 100644
index 0000000..ecf5d0c
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactOrganization.js
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ContactOrganization = function (properties) {
+ this.name = properties && properties.name ? properties.name : "";
+ this.department = properties && properties.department ? properties.department : "";
+ this.title = properties && properties.title ? properties.title : "";
+};
+
+module.exports = ContactOrganization;
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactPhoto.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactPhoto.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactPhoto.js
new file mode 100644
index 0000000..5b1c9d6
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/ContactPhoto.js
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ContactPhoto = function (originalFilePath, pref) {
+ this.originalFilePath = originalFilePath || "";
+ this.pref = pref || false;
+ this.largeFilePath = "";
+ this.smallFilePath = "";
+};
+
+module.exports = ContactPhoto;
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/contactConsts.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/contactConsts.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/contactConsts.js
new file mode 100644
index 0000000..ef25206
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/contactConsts.js
@@ -0,0 +1,225 @@
+/*
+* Copyright 2012 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+var ATTRIBUTE_KIND,
+ ATTRIBUTE_SUBKIND,
+ kindAttributeMap = {},
+ subKindAttributeMap = {},
+ _TITLE = 26,
+ _START_DATE = 43,
+ _END_DATE = 44;
+
+function populateKindAttributeMap() {
+ ATTRIBUTE_KIND = {
+ Invalid: 0,
+ Phone: 1,
+ Fax: 2,
+ Pager: 3,
+ Email: 4,
+ Website: 5,
+ Feed: 6,
+ Profile: 7,
+ Family: 8,
+ Person: 9,
+ Date: 10,
+ Group: 11,
+ Name: 12,
+ StockSymbol: 13,
+ Ranking: 14,
+ OrganizationAffiliation: 15,
+ Education: 16,
+ Note: 17,
+ InstantMessaging: 18,
+ VideoChat: 19,
+ ConnectionCount: 20,
+ Hidden: 21,
+ Biography: 22,
+ Sound: 23,
+ Notification: 24,
+ MessageSound: 25,
+ MessageNotification: 26
+ };
+
+ kindAttributeMap[ATTRIBUTE_KIND.Phone] = "phoneNumbers";
+ kindAttributeMap[ATTRIBUTE_KIND.Fax] = "faxNumbers";
+ kindAttributeMap[ATTRIBUTE_KIND.Pager] = "pagerNumber";
+ kindAttributeMap[ATTRIBUTE_KIND.Email] = "emails";
+ kindAttributeMap[ATTRIBUTE_KIND.Website] = "urls";
+ kindAttributeMap[ATTRIBUTE_KIND.Profile] = "socialNetworks";
+ kindAttributeMap[ATTRIBUTE_KIND.OrganizationAffiliation] = "organizations";
+ kindAttributeMap[ATTRIBUTE_KIND.Education] = "education";
+ kindAttributeMap[ATTRIBUTE_KIND.Note] = "note";
+ kindAttributeMap[ATTRIBUTE_KIND.InstantMessaging] = "ims";
+ kindAttributeMap[ATTRIBUTE_KIND.VideoChat] = "videoChat";
+ kindAttributeMap[ATTRIBUTE_KIND.Sound] = "ringtone";
+}
+
+function populateSubKindAttributeMap() {
+ ATTRIBUTE_SUBKIND = {
+ Invalid: 0,
+ Other: 1,
+ Home: 2,
+ Work: 3,
+ PhoneMobile: 4,
+ FaxDirect: 5,
+ Blog: 6,
+ WebsiteResume: 7,
+ WebsitePortfolio: 8,
+ WebsitePersonal: 9,
+ WebsiteCompany: 10,
+ ProfileFacebook: 11,
+ ProfileTwitter: 12,
+ ProfileLinkedIn: 13,
+ ProfileGist: 14,
+ ProfileTungle: 15,
+ FamilySpouse: 16,
+ FamilyChild: 17,
+ FamilyParent: 18,
+ PersonManager: 19,
+ PersonAssistant: 20,
+ DateBirthday: 21,
+ DateAnniversary: 22,
+ GroupDepartment: 23,
+ NameGiven: 24,
+ NameSurname: 25,
+ Title: _TITLE,
+ NameSuffix: 27,
+ NameMiddle: 28,
+ NameNickname: 29,
+ NameAlias: 30,
+ NameDisplayName: 31,
+ NamePhoneticGiven: 32,
+ NamePhoneticSurname: 33,
+ StockSymbolNyse: 34,
+ StockSymbolNasdaq: 35,
+ StockSymbolTse: 36,
+ StockSymbolLse: 37,
+ StockSymbolTsx: 38,
+ RankingKlout: 39,
+ RankingTrstRank: 40,
+ OrganizationAffiliationName: 41,
+ OrganizationAffiliationPhoneticName: 42,
+ OrganizationAffiliationTitle: _TITLE,
+ StartDate: _START_DATE,
+ EndDate: _END_DATE,
+ OrganizationAffiliationDetails: 45,
+ EducationInstitutionName: 46,
+ EducationStartDate: _START_DATE,
+ EducationEndDate: _END_DATE,
+ EducationDegree: 47,
+ EducationConcentration: 48,
+ EducationActivities: 49,
+ EducationNotes: 50,
+ InstantMessagingBbmPin: 51,
+ InstantMessagingAim: 52,
+ InstantMessagingAliwangwang: 53,
+ InstantMessagingGoogleTalk: 54,
+ InstantMessagingSametime: 55,
+ InstantMessagingIcq: 56,
+ InstantMessagingIrc: 57,
+ InstantMessagingJabber: 58,
+ InstantMessagingMsLcs: 59,
+ InstantMessagingMsn: 60,
+ InstantMessagingQq: 61,
+ InstantMessagingSkype: 62,
+ InstantMessagingYahooMessenger: 63,
+ InstantMessagingYahooMessengerJapan: 64,
+ VideoChatBbPlaybook: 65,
+ HiddenLinkedIn: 66,
+ HiddenFacebook: 67,
+ HiddenTwitter: 68,
+ ConnectionCountLinkedIn: 69,
+ ConnectionCountFacebook: 70,
+ ConnectionCountTwitter: 71,
+ HiddenChecksum: 72,
+ HiddenSpeedDial: 73,
+ BiographyFacebook: 74,
+ BiographyTwitter: 75,
+ BiographyLinkedIn: 76,
+ SoundRingtone: 77,
+ SimContactType: 78,
+ EcoID: 79,
+ Personal: 80,
+ StockSymbolAll: 81,
+ NotificationVibration: 82,
+ NotificationLED: 83,
+ MessageNotificationVibration: 84,
+ MessageNotificationLED: 85,
+ MessageNotificationDuringCall: 86,
+ VideoChatPin: 87
+ };
+
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.Other] = "other";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.Home] = "home";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.Work] = "work";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.PhoneMobile] = "mobile";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.FaxDirect] = "direct";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.Blog] = "blog";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.WebsiteResume] = "resume";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.WebsitePortfolio] = "portfolio";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.WebsitePersonal] = "personal";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.WebsiteCompany] = "company";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.ProfileFacebook] = "facebook";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.ProfileTwitter] = "twitter";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.ProfileLinkedIn] = "linkedin";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.ProfileGist] = "gist";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.ProfileTungle] = "tungle";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.DateBirthday] = "birthday";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.DateAnniversary] = "anniversary";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.NameGiven] = "givenName";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.NameSurname] = "familyName";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.Title] = "honorificPrefix";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.NameSuffix] = "honorificSuffix";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.NameMiddle] = "middleName";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.NamePhoneticGiven] = "phoneticGivenName";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.NamePhoneticSurname] = "phoneticFamilyName";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.NameNickname] = "nickname";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.NameDisplayName] = "displayName";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.OrganizationAffiliationName] = "name";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.OrganizationAffiliationDetails] = "department";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.Title] = "title";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingBbmPin] = "BbmPin";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingAim] = "Aim";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingAliwangwang] = "Aliwangwang";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingGoogleTalk] = "GoogleTalk";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingSametime] = "Sametime";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingIcq] = "Icq";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingJabber] = "Jabber";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingMsLcs] = "MsLcs";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingSkype] = "Skype";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingYahooMessenger] = "YahooMessenger";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.InstantMessagingYahooMessengerJapan] = "YahooMessegerJapan";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.VideoChatBbPlaybook] = "BbPlaybook";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.SoundRingtone] = "ringtone";
+ subKindAttributeMap[ATTRIBUTE_SUBKIND.Personal] = "personal";
+}
+
+module.exports = {
+ getKindAttributeMap: function () {
+ if (!ATTRIBUTE_KIND) {
+ populateKindAttributeMap();
+ }
+
+ return kindAttributeMap;
+ },
+ getSubKindAttributeMap: function () {
+ if (!ATTRIBUTE_SUBKIND) {
+ populateSubKindAttributeMap();
+ }
+
+ return subKindAttributeMap;
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/contactUtils.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/contactUtils.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/contactUtils.js
new file mode 100644
index 0000000..cd022c4
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/contactUtils.js
@@ -0,0 +1,223 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var self,
+ ContactFindOptions = require("./ContactFindOptions"),
+ ContactError = require("./ContactError"),
+ ContactName = require("./ContactName"),
+ ContactOrganization = require("./ContactOrganization"),
+ ContactAddress = require("./ContactAddress"),
+ ContactField = require("./ContactField"),
+ contactConsts = require("./contactConsts"),
+ ContactPhoto = require("./ContactPhoto"),
+ ContactNews = require("./ContactNews"),
+ ContactActivity = require("./ContactActivity");
+
+function populateFieldArray(contactProps, field, ClassName) {
+ if (contactProps[field]) {
+ var list = [],
+ obj;
+
+ contactProps[field].forEach(function (args) {
+ if (ClassName === ContactField) {
+ list.push(new ClassName(args.type, args.value));
+ } else if (ClassName === ContactPhoto) {
+ obj = new ContactPhoto(args.originalFilePath, args.pref);
+ obj.largeFilePath = args.largeFilePath;
+ obj.smallFilePath = args.smallFilePath;
+ list.push(obj);
+ } else if (ClassName === ContactNews) {
+ obj = new ContactNews(args);
+ list.push(obj);
+ } else if (ClassName === ContactActivity) {
+ obj = new ContactActivity(args);
+ list.push(obj);
+ } else {
+ list.push(new ClassName(args));
+ }
+ });
+ contactProps[field] = list;
+ }
+}
+
+function populateDate(contactProps, field) {
+ if (contactProps[field]) {
+ contactProps[field] = new Date(contactProps[field]);
+ }
+}
+
+function validateFindArguments(findOptions) {
+ var error = false;
+
+ // findOptions is mandatory
+ if (!findOptions) {
+ error = true;
+ } else {
+ // findOptions.filter is optional
+ if (findOptions.filter) {
+ findOptions.filter.forEach(function (f) {
+ switch (f.fieldName) {
+ case ContactFindOptions.SEARCH_FIELD_GIVEN_NAME:
+ case ContactFindOptions.SEARCH_FIELD_FAMILY_NAME:
+ case ContactFindOptions.SEARCH_FIELD_ORGANIZATION_NAME:
+ case ContactFindOptions.SEARCH_FIELD_PHONE:
+ case ContactFindOptions.SEARCH_FIELD_EMAIL:
+ case ContactFindOptions.SEARCH_FIELD_BBMPIN:
+ case ContactFindOptions.SEARCH_FIELD_LINKEDIN:
+ case ContactFindOptions.SEARCH_FIELD_TWITTER:
+ case ContactFindOptions.SEARCH_FIELD_VIDEO_CHAT:
+ break;
+ default:
+ error = true;
+ }
+
+ if (!f.fieldValue) {
+ error = true;
+ }
+ });
+ }
+
+ //findOptions.limit is optional
+ if (findOptions.limit) {
+ if (typeof findOptions.limit !== "number") {
+ error = true;
+ }
+ }
+
+ //findOptions.favorite is optional
+ if (findOptions.favorite) {
+ if (typeof findOptions.favorite !== "boolean") {
+ error = true;
+ }
+ }
+
+ // findOptions.sort is optional
+ if (!error && findOptions.sort && Array.isArray(findOptions.sort)) {
+ findOptions.sort.forEach(function (s) {
+ switch (s.fieldName) {
+ case ContactFindOptions.SORT_FIELD_GIVEN_NAME:
+ case ContactFindOptions.SORT_FIELD_FAMILY_NAME:
+ case ContactFindOptions.SORT_FIELD_ORGANIZATION_NAME:
+ break;
+ default:
+ error = true;
+ }
+
+ if (s.desc === undefined || typeof s.desc !== "boolean") {
+ error = true;
+ }
+ });
+ }
+
+ if (!error && findOptions.includeAccounts) {
+ if (!Array.isArray(findOptions.includeAccounts)) {
+ error = true;
+ } else {
+ findOptions.includeAccounts.forEach(function (acct) {
+ if (!error && (!acct.id || window.isNaN(window.parseInt(acct.id, 10)))) {
+ error = true;
+ }
+ });
+ }
+ }
+
+ if (!error && findOptions.excludeAccounts) {
+ if (!Array.isArray(findOptions.excludeAccounts)) {
+ error = true;
+ } else {
+ findOptions.excludeAccounts.forEach(function (acct) {
+ if (!error && (!acct.id || window.isNaN(window.parseInt(acct.id, 10)))) {
+ error = true;
+ }
+ });
+ }
+ }
+ }
+ return !error;
+}
+
+function validateContactsPickerFilter(filter) {
+ var isValid = true,
+ availableFields = {};
+
+ if (typeof(filter) === "undefined") {
+ isValid = false;
+ } else {
+ if (filter && Array.isArray(filter)) {
+ availableFields = contactConsts.getKindAttributeMap();
+ filter.forEach(function (e) {
+ isValid = isValid && Object.getOwnPropertyNames(availableFields).reduce(
+ function (found, key) {
+ return found || availableFields[key] === e;
+ }, false);
+ });
+ }
+ }
+
+ return isValid;
+}
+
+function validateContactsPickerOptions(options) {
+ var isValid = false,
+ mode = options.mode;
+
+ if (typeof(options) === "undefined") {
+ isValid = false;
+ } else {
+ isValid = mode === ContactPickerOptions.MODE_SINGLE || mode === ContactPickerOptions.MODE_MULTIPLE || mode === ContactPickerOptions.MODE_ATTRIBUTE;
+
+ // if mode is attribute, fields must be defined
+ if (mode === ContactPickerOptions.MODE_ATTRIBUTE && !validateContactsPickerFilter(options.fields)) {
+ isValid = false;
+ }
+ }
+
+ return isValid;
+}
+
+self = module.exports = {
+ populateContact: function (contact) {
+ if (contact.name) {
+ contact.name = new ContactName(contact.name);
+ }
+
+ populateFieldArray(contact, "addresses", ContactAddress);
+ populateFieldArray(contact, "organizations", ContactOrganization);
+ populateFieldArray(contact, "emails", ContactField);
+ populateFieldArray(contact, "phoneNumbers", ContactField);
+ populateFieldArray(contact, "faxNumbers", ContactField);
+ populateFieldArray(contact, "pagerNumbers", ContactField);
+ populateFieldArray(contact, "ims", ContactField);
+ populateFieldArray(contact, "socialNetworks", ContactField);
+ populateFieldArray(contact, "urls", ContactField);
+ populateFieldArray(contact, "photos", ContactPhoto);
+ populateFieldArray(contact, "news", ContactNews);
+ populateFieldArray(contact, "activities", ContactActivity);
+ // TODO categories
+
+ populateDate(contact, "birthday");
+ populateDate(contact, "anniversary");
+ },
+ invokeErrorCallback: function (errorCallback, code) {
+ if (errorCallback) {
+ errorCallback(new ContactError(code));
+ }
+ },
+ validateFindArguments: validateFindArguments,
+ validateContactsPickerFilter: validateContactsPickerFilter,
+ validateContactsPickerOptions: validateContactsPickerOptions
+};
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/index.js b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/index.js
new file mode 100644
index 0000000..09a4bd2
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Contacts/src/blackberry10/index.js
@@ -0,0 +1,374 @@
+/*
+ * Copyright 2013 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var pimContacts,
+ contactUtils = require("./contactUtils"),
+ contactConsts = require("./contactConsts"),
+ ContactError = require("./ContactError"),
+ ContactName = require("./ContactName"),
+ ContactFindOptions = require("./ContactFindOptions"),
+ noop = function () {};
+
+function getAccountFilters(options) {
+ if (options.includeAccounts) {
+ options.includeAccounts = options.includeAccounts.map(function (acct) {
+ return acct.id.toString();
+ });
+ }
+
+ if (options.excludeAccounts) {
+ options.excludeAccounts = options.excludeAccounts.map(function (acct) {
+ return acct.id.toString();
+ });
+ }
+}
+
+function populateSearchFields(fields) {
+ var i,
+ l,
+ key,
+ searchFieldsObject = {},
+ searchFields = [];
+
+ for (i = 0, l = fields.length; i < l; i++) {
+ if (fields[i] === "*") {
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_GIVEN_NAME] = true;
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_FAMILY_NAME] = true;
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_PHONE] = true;
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_EMAIL] = true;
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_ORGANIZATION_NAME] = true;
+ } else if (fields[i] === "displayName" || fields[i] === "name") {
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_GIVEN_NAME] = true;
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_FAMILY_NAME] = true;
+ } else if (fields[i] === "nickname") {
+ // not supported by Cascades
+ } else if (fields[i] === "phoneNumbers") {
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_PHONE] = true;
+ } else if (fields[i] === "emails") {
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_EMAIL] = true;
+ } else if (field === "addresses") {
+ // not supported by Cascades
+ } else if (field === "ims") {
+ // not supported by Cascades
+ } else if (field === "organizations") {
+ searchFieldsObject[ContactFindOptions.SEARCH_FIELD_ORGANIZATION_NAME] = true;
+ } else if (field === "birthday") {
+ // not supported by Cascades
+ } else if (field === "note") {
+ // not supported by Cascades
+ } else if (field === "photos") {
+ // not supported by Cascades
+ } else if (field === "categories") {
+ // not supported by Cascades
+ } else if (field === "urls") {
+ // not supported by Cascades
+ }
+ }
+
+ for (key in searchFieldsObject) {
+ if (searchFieldsObject.hasOwnProperty(key)) {
+ searchFields.push(window.parseInt(key));
+ }
+ }
+
+ return searchFields;
+}
+
+function convertBirthday(birthday) {
+ //Convert date string from native to milliseconds since epoch for cordova-js
+ var birthdayInfo;
+ if (birthday) {
+ birthdayInfo = birthday.split("-");
+ return new Date(birthdayInfo[0], birthdayInfo[1] - 1, birthdayInfo[2]).getTime();
+ } else {
+ return null;
+ }
+}
+
+function processJnextSaveData(result, JnextData) {
+ var data = JnextData,
+ birthdayInfo;
+
+ if (data._success === true) {
+ data.birthday = convertBirthday(data.birthday);
+ result.callbackOk(data, false);
+ } else {
+ result.callbackError(data.code, false);
+ }
+}
+
+function processJnextRemoveData(result, JnextData) {
+ var data = JnextData;
+
+ if (data._success === true) {
+ result.callbackOk(data);
+ } else {
+ result.callbackError(ContactError.UNKNOWN_ERROR, false);
+ }
+}
+
+function processJnextFindData(eventId, eventHandler, JnextData) {
+ var data = JnextData,
+ i,
+ l,
+ more = false,
+ resultsObject = {},
+ birthdayInfo;
+
+ if (data.contacts) {
+ for (i = 0, l = data.contacts.length; i < l; i++) {
+ data.contacts[i].birthday = convertBirthday(data.contacts[i].birthday);
+ data.contacts[i].name = new ContactName(data.contacts[i].name);
+ }
+ } else {
+ data.contacts = []; // if JnextData.contacts return null, return an empty array
+ }
+
+ if (data._success === true) {
+ eventHandler.error = false;
+ }
+
+ if (eventHandler.multiple) {
+ // Concatenate results; do not add the same contacts
+ for (i = 0, l = eventHandler.searchResult.length; i < l; i++) {
+ resultsObject[eventHandler.searchResult[i].id] = true;
+ }
+
+ for (i = 0, l = data.contacts.length; i < l; i++) {
+ if (resultsObject[data.contacts[i].id]) {
+ // Already existing
+ } else {
+ eventHandler.searchResult.push(data.contacts[i]);
+ }
+ }
+
+ // check if more search is required
+ eventHandler.searchFieldIndex++;
+ if (eventHandler.searchFieldIndex < eventHandler.searchFields.length) {
+ more = true;
+ }
+ } else {
+ eventHandler.searchResult = data.contacts;
+ }
+
+ if (more) {
+ pimContacts.getInstance().invokeJnextSearch(eventId);
+ } else {
+ if (eventHandler.error) {
+ eventHandler.result.callbackError(data.code, false);
+ } else {
+ eventHandler.result.callbackOk(eventHandler.searchResult, false);
+ }
+ }
+}
+
+module.exports = {
+ search: function (successCb, failCb, args, env) {
+ var cordovaFindOptions = {},
+ result = new PluginResult(args, env),
+ key;
+
+ for (key in args) {
+ if (args.hasOwnProperty(key)) {
+ cordovaFindOptions[key] = JSON.parse(decodeURIComponent(args[key]));
+ }
+ }
+
+ pimContacts.getInstance().find(cordovaFindOptions, result, processJnextFindData);
+ result.noResult(true);
+ },
+ save: function (successCb, failCb, args, env) {
+ var attributes = {},
+ result = new PluginResult(args, env),
+ key,
+ nativeEmails = [];
+
+ attributes = JSON.parse(decodeURIComponent(args[0]));
+
+ //convert birthday format for our native .so file
+ if (attributes.birthday) {
+ attributes.birthday = new Date(attributes.birthday).toDateString();
+ }
+
+ if (attributes.emails) {
+ attributes.emails.forEach(function (email) {
+ if (email.value) {
+ if (email.type) {
+ nativeEmails.push({ "type" : email.type, "value" : email.value });
+ } else {
+ nativeEmails.push({ "type" : "home", "value" : email.value });
+ }
+ }
+ });
+ attributes.emails = nativeEmails;
+ }
+
+ if (attributes.id !== null) {
+ attributes.id = window.parseInt(attributes.id);
+ }
+
+ attributes._eventId = result.callbackId;
+ pimContacts.getInstance().save(attributes, result, processJnextSaveData);
+ result.noResult(true);
+ },
+ remove: function (successCb, failCb, args, env) {
+ var result = new PluginResult(args, env),
+ attributes = {
+ "contactId": window.parseInt(JSON.parse(decodeURIComponent(args[0]))),
+ "_eventId": result.callbackId
+ };
+
+ if (!window.isNaN(attributes.contactId)) {
+ pimContacts.getInstance().remove(attributes, result, processJnextRemoveData);
+ result.noResult(true);
+ } else {
+ result.error(ContactError.UNKNOWN_ERROR);
+ result.noResult(false);
+ }
+ }
+};
+
+///////////////////////////////////////////////////////////////////
+// JavaScript wrapper for JNEXT plugin
+///////////////////////////////////////////////////////////////////
+
+JNEXT.PimContacts = function ()
+{
+ var self = this,
+ hasInstance = false;
+
+ self.find = function (cordovaFindOptions, pluginResult, handler) {
+ //register find eventHandler for when JNEXT onEvent fires
+ self.eventHandlers[cordovaFindOptions.callbackId] = {
+ "result" : pluginResult,
+ "action" : "find",
+ "multiple" : cordovaFindOptions[1].filter ? true : false,
+ "fields" : cordovaFindOptions[0],
+ "searchFilter" : cordovaFindOptions[1].filter,
+ "searchFields" : cordovaFindOptions[1].filter ? populateSearchFields(cordovaFindOptions[0]) : null,
+ "searchFieldIndex" : 0,
+ "searchResult" : [],
+ "handler" : handler,
+ "error" : true
+ };
+
+ self.invokeJnextSearch(cordovaFindOptions.callbackId);
+ return "";
+ };
+
+ self.invokeJnextSearch = function(eventId) {
+ var jnextArgs = {},
+ findHandler = self.eventHandlers[eventId];
+
+ jnextArgs._eventId = eventId;
+ jnextArgs.fields = findHandler.fields;
+ jnextArgs.options = {};
+ jnextArgs.options.filter = [];
+
+ if (findHandler.multiple) {
+ jnextArgs.options.filter.push({
+ "fieldName" : findHandler.searchFields[findHandler.searchFieldIndex],
+ "fieldValue" : findHandler.searchFilter
+ });
+ //findHandler.searchFieldIndex++;
+ }
+
+ JNEXT.invoke(self.m_id, "find " + JSON.stringify(jnextArgs));
+ }
+
+ self.getContact = function (args) {
+ return JSON.parse(JNEXT.invoke(self.m_id, "getContact " + JSON.stringify(args)));
+ };
+
+ self.save = function (args, pluginResult, handler) {
+ //register save eventHandler for when JNEXT onEvent fires
+ self.eventHandlers[args._eventId] = {
+ "result" : pluginResult,
+ "action" : "save",
+ "handler" : handler
+ };
+ JNEXT.invoke(self.m_id, "save " + JSON.stringify(args));
+ return "";
+ };
+
+ self.remove = function (args, pluginResult, handler) {
+ //register remove eventHandler for when JNEXT onEvent fires
+ self.eventHandlers[args._eventId] = {
+ "result" : pluginResult,
+ "action" : "remove",
+ "handler" : handler
+ };
+ JNEXT.invoke(self.m_id, "remove " + JSON.stringify(args));
+ return "";
+ };
+
+ self.getId = function () {
+ return self.m_id;
+ };
+
+ self.getContactAccounts = function () {
+ var value = JNEXT.invoke(self.m_id, "getContactAccounts");
+ return JSON.parse(value);
+ };
+
+ self.init = function () {
+ if (!JNEXT.require("libpimcontacts")) {
+ return false;
+ }
+
+ self.m_id = JNEXT.createObject("libpimcontacts.PimContacts");
+
+ if (self.m_id === "") {
+ return false;
+ }
+
+ JNEXT.registerEvents(self);
+ };
+
+ // Handle data coming back from JNEXT native layer. Each async function registers a handler and a PluginResult object.
+ // When JNEXT fires onEvent we parse the result string back into JSON and trigger the appropriate handler (eventHandlers map
+ // uses callbackId as key), along with the actual data coming back from the native layer. Each function may have its own way of
+ // processing native data so we do not do any processing here.
+
+ self.onEvent = function (strData) {
+ var arData = strData.split(" "),
+ strEventDesc = arData[0],
+ eventHandler,
+ args = {};
+
+ if (strEventDesc === "result") {
+ args.result = escape(strData.split(" ").slice(2).join(" "));
+ eventHandler = self.eventHandlers[arData[1]];
+ if (eventHandler.action === "save" || eventHandler.action === "remove") {
+ eventHandler.handler(eventHandler.result, JSON.parse(decodeURIComponent(args.result)));
+ } else if (eventHandler.action === "find") {
+ eventHandler.handler(arData[1], eventHandler, JSON.parse(decodeURIComponent(args.result)));
+ }
+ }
+ };
+
+ self.m_id = "";
+ self.eventHandlers = {};
+
+ self.getInstance = function () {
+ if (!hasInstance) {
+ self.init();
+ hasInstance = true;
+ }
+ return self;
+ };
+};
+
+pimContacts = new JNEXT.PimContacts();
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Device/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Device/plugin.xml b/lib/cordova-blackberry/plugins/Device/plugin.xml
new file mode 100644
index 0000000..db8b205
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Device/plugin.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.core.Device"
+ version="0.0.1">
+
+ <name>Device</name>
+
+ <platform name="blackberry10">
+ <source-file src="src/blackberry10/index.js" target-dir="Device" />
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="Device" value="Device"/>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Device/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Device/src/blackberry10/index.js b/lib/cordova-blackberry/plugins/Device/src/blackberry10/index.js
new file mode 100644
index 0000000..89a40e4
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Device/src/blackberry10/index.js
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+function getModelName () {
+ var modelName = window.qnx.webplatform.device.modelName;
+ //Pre 10.2 (meaning Z10 or Q10)
+ if (typeof modelName === "undefined") {
+ if (window.screen.height === 720 && window.screen.width === 720) {
+ modelName = "Q10";
+ } else if ((window.screen.height === 1280 && window.screen.width === 768) ||
+ (window.screen.height === 768 && window.screen.width === 1280)) {
+ modelName = "Z10";
+ } else {
+ modelName = window.qnx.webplatform.deviceName;
+ }
+ }
+
+ return modelName;
+}
+
+function getUUID () {
+ var uuid = "";
+ try {
+ //Must surround by try catch because this will throw if the app is missing permissions
+ uuid = window.qnx.webplatform.device.devicePin;
+ } catch (e) {
+ //DO Nothing
+ }
+ return uuid;
+}
+
+module.exports = {
+ getDeviceInfo: function (success, fail, args, env) {
+ var result = new PluginResult(args, env),
+ modelName = getModelName(),
+ uuid = getUUID(),
+ info = {
+ platform: "blackberry10",
+ version: window.qnx.webplatform.device.scmBundle,
+ model: modelName,
+ name: modelName, // deprecated: please use device.model
+ uuid: uuid,
+ cordova: "dev"
+ };
+ result.ok(info);
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Logger/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Logger/plugin.xml b/lib/cordova-blackberry/plugins/Logger/plugin.xml
new file mode 100644
index 0000000..f930d15
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Logger/plugin.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.core.Logger"
+ version="0.0.1">
+
+ <name>Logger</name>
+
+ <platform name="blackberry10">
+ <source-file src="src/blackberry10/index.js" target-dir="Logger" />
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="Logger" value="Logger"/>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Logger/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Logger/src/blackberry10/index.js b/lib/cordova-blackberry/plugins/Logger/src/blackberry10/index.js
new file mode 100644
index 0000000..497f477
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Logger/src/blackberry10/index.js
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+module.exports = {
+ logLevel: function (success, fail, args, env) {
+ var result = new PluginResult(args, env),
+ level = JSON.parse(decodeURIComponent(args[0])),
+ message = JSON.parse(decodeURIComponent(args[1]));
+ console.log(level + ": " + message);
+ result.noResult(false);
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/NetworkStatus/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/NetworkStatus/plugin.xml b/lib/cordova-blackberry/plugins/NetworkStatus/plugin.xml
new file mode 100644
index 0000000..47eea68
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/NetworkStatus/plugin.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.core.Network"
+ version="0.0.1">
+
+ <name>Network Information</name>
+
+ <platform name="blackberry10">
+ <source-file src="src/blackberry10/index.js" target-dir="NetworkStatus" />
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="NetworkStatus" value="NetworkStatus"/>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/NetworkStatus/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/NetworkStatus/src/blackberry10/index.js b/lib/cordova-blackberry/plugins/NetworkStatus/src/blackberry10/index.js
new file mode 100644
index 0000000..5a991fe
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/NetworkStatus/src/blackberry10/index.js
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//map from BB10 to cordova connection types:
+//https://github.com/apache/cordova-js/blob/master/lib/common/plugin/Connection.js
+function mapConnectionType(con) {
+ switch (con.type) {
+ case 'wired':
+ return 'ethernet';
+ case 'wifi':
+ return 'wifi';
+ case 'none':
+ return 'none';
+ case 'cellular':
+ switch (con.technology) {
+ case 'edge':
+ case 'gsm':
+ return '2g';
+ case 'evdo':
+ return '3g';
+ case 'umts':
+ return '3g';
+ case 'lte':
+ return '4g';
+ }
+ return "cellular";
+ }
+ return 'unknown';
+}
+
+function currentConnectionType() {
+ try {
+ //possible for webplatform to throw pps exception
+ return mapConnectionType(window.qnx.webplatform.device.activeConnection || { type : 'none' });
+ }
+ catch (e) {
+ return 'unknown';
+ }
+}
+
+module.exports = {
+ getConnectionInfo: function (success, fail, args, env) {
+ var result = new PluginResult(args, env);
+ result.ok(currentConnectionType());
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Notification/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Notification/plugin.xml b/lib/cordova-blackberry/plugins/Notification/plugin.xml
new file mode 100644
index 0000000..49566b2
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Notification/plugin.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.core.Notification"
+ version="0.0.1">
+
+ <name>Notification</name>
+
+ <platform name="blackberry10">
+ <source-file src="src/blackberry10/index.js" target-dir="Notification" />
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="Notification" value="Notification"/>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/Notification/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/Notification/src/blackberry10/index.js b/lib/cordova-blackberry/plugins/Notification/src/blackberry10/index.js
new file mode 100644
index 0000000..fad04f7
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/Notification/src/blackberry10/index.js
@@ -0,0 +1,91 @@
+/*
+* Copyright 2013 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+function showDialog(args, dialogType, result) {
+ //Unpack and map the args
+ var msg = JSON.parse(decodeURIComponent(args[0])),
+ title = JSON.parse(decodeURIComponent(args[1])),
+ btnLabel = JSON.parse(decodeURIComponent(args[2]));
+
+ if (!Array.isArray(btnLabel)) {
+ //Converts to array for (string) and (string,string, ...) cases
+ btnLabel = btnLabel.split(",");
+ }
+
+ if (msg && typeof msg === "string") {
+ msg = msg.replace(/^"|"$/g, "").replace(/\\"/g, '"').replace(/\\\\/g, '\\');
+ } else {
+ result.error("message is undefined");
+ return;
+ }
+
+ var messageObj = {
+ title : title,
+ htmlmessage : msg,
+ dialogType : dialogType,
+ optionalButtons : btnLabel
+ };
+
+ //TODO replace with getOverlayWebview() when available in webplatform
+ qnx.webplatform.getWebViews()[2].dialog.show(messageObj, function (data) {
+ if (typeof data === "number") {
+ //Confirm dialog call back needs to be called with one-based indexing [1,2,3 etc]
+ result.callbackOk(++data, false);
+ } else {
+ //Prompt dialog callback expects object
+ result.callbackOk({
+ buttonIndex: data.ok ? 1 : 0,
+ input1: (data.oktext) ? decodeURIComponent(data.oktext) : ""
+ }, false);
+ }
+ });
+
+ result.noResult(true);
+}
+
+module.exports = {
+ alert: function (success, fail, args, env) {
+ var result = new PluginResult(args, env);
+
+ if (Object.keys(args).length < 3) {
+ result.error("Notification action - alert arguments not found.");
+ } else {
+ showDialog(args, "CustomAsk", result);
+ }
+ },
+ confirm: function (success, fail, args, env) {
+ var result = new PluginResult(args, env);
+
+ if (Object.keys(args).length < 3) {
+ result.error("Notification action - confirm arguments not found.");
+ } else {
+ showDialog(args, "CustomAsk", result);
+ }
+ },
+ prompt: function (success, fail, args, env) {
+ var result = new PluginResult(args, env);
+
+ if (Object.keys(args).length < 3) {
+ result.error("Notification action - prompt arguments not found.");
+ } else {
+ showDialog(args, "JavaScriptPrompt", result);
+ }
+ },
+ beep: function (success, fail, args, env) {
+ var result = new PluginResult(args, env);
+ result.error("Beep not supported");
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/SplashScreen/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/SplashScreen/plugin.xml b/lib/cordova-blackberry/plugins/SplashScreen/plugin.xml
new file mode 100644
index 0000000..0b33d5a
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/SplashScreen/plugin.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.core.SplashScreen"
+ version="0.0.1">
+
+ <name>SplashScreen</name>
+
+ <platform name="blackberry10">
+ <source-file src="src/blackberry10/index.js" target-dir="SplashScreen" />
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="SplashScreen" value="SplashScreen"/>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/SplashScreen/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/SplashScreen/src/blackberry10/index.js b/lib/cordova-blackberry/plugins/SplashScreen/src/blackberry10/index.js
new file mode 100644
index 0000000..bd7e48c
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/SplashScreen/src/blackberry10/index.js
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2013 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+module.exports = {
+ show: function (success, fail, args, env) {
+ var result = new PluginResult(args, env);
+ result.error("Not supported on platform", false);
+ },
+
+ hide: function (success, fail, args, env) {
+ var result = new PluginResult(args, env);
+ window.qnx.webplatform.getApplication().windowVisible = true;
+ result.ok(undefined, false);
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/com.blackberry.jpps/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/com.blackberry.jpps/plugin.xml b/lib/cordova-blackberry/plugins/com.blackberry.jpps/plugin.xml
new file mode 100644
index 0000000..0eec7c6
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/com.blackberry.jpps/plugin.xml
@@ -0,0 +1,30 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="com.blackberry.jpps"
+ version="1.0.0">
+
+ <platform name="blackberry10">
+ <lib-file src="src/blackberry10/native/device/libjpps.so" arch="device"/>
+ <lib-file src="src/blackberry10/native/simulator/libjpps.so" arch="simulator"/>
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="com.blackberry.jpps"/>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/com.blackberry.jpps/src/blackberry10/native/device/libjpps.so
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/com.blackberry.jpps/src/blackberry10/native/device/libjpps.so b/lib/cordova-blackberry/plugins/com.blackberry.jpps/src/blackberry10/native/device/libjpps.so
new file mode 100644
index 0000000..f0eb90d
Binary files /dev/null and b/lib/cordova-blackberry/plugins/com.blackberry.jpps/src/blackberry10/native/device/libjpps.so differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/com.blackberry.jpps/src/blackberry10/native/simulator/libjpps.so
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/com.blackberry.jpps/src/blackberry10/native/simulator/libjpps.so b/lib/cordova-blackberry/plugins/com.blackberry.jpps/src/blackberry10/native/simulator/libjpps.so
new file mode 100644
index 0000000..f2c12ff
Binary files /dev/null and b/lib/cordova-blackberry/plugins/com.blackberry.jpps/src/blackberry10/native/simulator/libjpps.so differ
[07/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/com.blackberry.utils/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/com.blackberry.utils/plugin.xml b/lib/cordova-blackberry/plugins/com.blackberry.utils/plugin.xml
new file mode 100644
index 0000000..746fa76
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/com.blackberry.utils/plugin.xml
@@ -0,0 +1,30 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="com.blackberry.utils"
+ version="1.0.0">
+
+ <platform name="blackberry10">
+ <lib-file src="src/blackberry10/native/device/libutils.so" arch="device"/>
+ <lib-file src="src/blackberry10/native/simulator/libutils.so" arch="simulator"/>
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="com.blackberry.utils"/>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/com.blackberry.utils/src/blackberry10/native/device/libutils.so
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/com.blackberry.utils/src/blackberry10/native/device/libutils.so b/lib/cordova-blackberry/plugins/com.blackberry.utils/src/blackberry10/native/device/libutils.so
new file mode 100644
index 0000000..126d02c
Binary files /dev/null and b/lib/cordova-blackberry/plugins/com.blackberry.utils/src/blackberry10/native/device/libutils.so differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/com.blackberry.utils/src/blackberry10/native/simulator/libutils.so
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/com.blackberry.utils/src/blackberry10/native/simulator/libutils.so b/lib/cordova-blackberry/plugins/com.blackberry.utils/src/blackberry10/native/simulator/libutils.so
new file mode 100644
index 0000000..392ad33
Binary files /dev/null and b/lib/cordova-blackberry/plugins/com.blackberry.utils/src/blackberry10/native/simulator/libutils.so differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/plugin.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/plugin.xml b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/plugin.xml
new file mode 100644
index 0000000..474077e
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/plugin.xml
@@ -0,0 +1,31 @@
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ id="org.apache.cordova.blackberry10.pimlib"
+ version="1.0.0">
+
+ <platform name="blackberry10">
+ <lib-file src="src/blackberry10/native/device/libpimcontacts.so" arch="device"></lib-file>
+ <lib-file src="src/blackberry10/native/simulator/libpimcontacts.so" arch="simulator"></lib-file>
+ <config-file target="www/config.xml" parent="/widget">
+ <feature name="org.apache.cordova.blackberry10.pimlib"></feature>
+ </config-file>
+ </platform>
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/Makefile
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/Makefile b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/Makefile
new file mode 100644
index 0000000..0cc5eae
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/Makefile
@@ -0,0 +1,8 @@
+LIST=CPU
+ifndef QRECURSE
+QRECURSE=recurse.mk
+ifdef QCONFIG
+QRDIR=$(dir $(QCONFIG))
+endif
+endif
+include $(QRDIR)$(QRECURSE)
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/Makefile
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/Makefile b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/Makefile
new file mode 100644
index 0000000..0e22650
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/Makefile
@@ -0,0 +1,8 @@
+LIST=VARIANT
+ifndef QRECURSE
+QRECURSE=recurse.mk
+ifdef QCONFIG
+QRDIR=$(dir $(QCONFIG))
+endif
+endif
+include $(QRDIR)$(QRECURSE)
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/so.le-v7/Makefile
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/so.le-v7/Makefile b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/so.le-v7/Makefile
new file mode 100644
index 0000000..2c76089
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/so.le-v7/Makefile
@@ -0,0 +1 @@
+include ../../common.mk
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/so.le-v7/libpimcontacts.so
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/so.le-v7/libpimcontacts.so b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/so.le-v7/libpimcontacts.so
new file mode 100755
index 0000000..f90047f
Binary files /dev/null and b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/arm/so.le-v7/libpimcontacts.so differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/common.mk
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/common.mk b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/common.mk
new file mode 100644
index 0000000..7bc06fb
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/common.mk
@@ -0,0 +1,18 @@
+ifndef QCONFIG
+QCONFIG=qconfig.mk
+endif
+include $(QCONFIG)
+
+NAME=pimcontacts
+PLUGIN=yes
+UTILS=yes
+
+include ../../../../../../meta.mk
+
+SRCS+=pim_contacts_qt.cpp \
+ pim_contacts_js.cpp \
+ contact_account.cpp
+
+include $(MKFILES_ROOT)/qtargets.mk
+
+LIBS+=bbpim bbcascadespickers QtCore img
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/contact_account.cpp
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/contact_account.cpp b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/contact_account.cpp
new file mode 100644
index 0000000..3476e70
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/contact_account.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <webworks_utils.hpp>
+#include "contact_account.hpp"
+
+ContactAccount& ContactAccount::GetAccountInstance()
+{
+ static ContactAccount ca;
+ return ca;
+}
+
+ContactAccount::ContactAccount()
+{
+ fetchContactAccounts();
+}
+
+ContactAccount::~ContactAccount()
+{}
+
+QList<bb::pim::account::Account> ContactAccount::GetContactAccounts(bool fresh)
+{
+ if (fresh) {
+ fetchContactAccounts();
+ }
+ return _accounts;
+}
+
+bb::pim::account::Account ContactAccount::GetAccount(bb::pim::account::AccountKey id, bool fresh)
+{
+ if (fresh) {
+ fetchContactAccounts();
+ }
+ return _accountMap.value(id);
+}
+
+Json::Value ContactAccount::Account2Json(const bb::pim::account::Account& account)
+{
+ Json::Value jsonAccount;
+ jsonAccount["id"] = webworks::Utils::intToStr(account.id());
+ jsonAccount["name"] = account.displayName().isEmpty() ? account.provider().name().toStdString() : account.displayName().toStdString();
+ jsonAccount["enterprise"] = account.isEnterprise() == 1 ? true : false;
+
+ return jsonAccount;
+}
+
+void ContactAccount::fetchContactAccounts()
+{
+ QList<bb::pim::account::Account> accounts = _accountService.accounts(bb::pim::account::Service::Contacts);
+
+ _accounts.clear();
+ _accountMap.clear();
+ for (QList<bb::pim::account::Account>::const_iterator it = accounts.begin(); it != accounts.end(); ++it) {
+ if ((it->id() != ID_UNIFIED_ACCOUNT) && (it->id() != ID_ENHANCED_ACCOUNT)) {
+ _accounts.append(*it);
+ _accountMap.insert(it->id(), (bb::pim::account::Account)(*it));
+ }
+ }
+}
+
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/contact_account.hpp
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/contact_account.hpp b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/contact_account.hpp
new file mode 100644
index 0000000..3910de8
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/contact_account.hpp
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _CONTACT_ACCOUNT_HPP_
+#define _CONTACT_ACCOUNT_HPP_
+
+#include <bb/pim/account/Account>
+#include <bb/pim/account/AccountService>
+#include <bb/pim/account/Provider>
+
+#include <json/value.h>
+#include <QList>
+#include <QDebug>
+
+class ContactAccount
+{
+public:
+ static ContactAccount& GetAccountInstance();
+
+ // get all available accounts which provide contact service
+ QList<bb::pim::account::Account> GetContactAccounts(bool fresh = false);
+ // get the contact account with the specific id
+ bb::pim::account::Account GetAccount(bb::pim::account::AccountKey id, bool fresh = false);
+ // serialize account to json object
+ static Json::Value Account2Json(const bb::pim::account::Account& account);
+
+private:
+ ContactAccount();
+ ~ContactAccount();
+ explicit ContactAccount(ContactAccount const&);
+ void operator=(ContactAccount const&);
+ // Refresh the accounts list and map
+ void fetchContactAccounts();
+ QMap<bb::pim::account::AccountKey, bb::pim::account::Account> _accountMap;
+ QList<bb::pim::account::Account> _accounts;
+ bb::pim::account::AccountService _accountService;
+ static const int ID_UNIFIED_ACCOUNT = 4;
+ static const int ID_ENHANCED_ACCOUNT = 6;
+};
+
+#endif // end of _CONTACT_ACCOUNT_HPP_
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/device/libpimcontacts.so
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/device/libpimcontacts.so b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/device/libpimcontacts.so
new file mode 100644
index 0000000..f90047f
Binary files /dev/null and b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/device/libpimcontacts.so differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_js.cpp
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_js.cpp b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_js.cpp
new file mode 100644
index 0000000..4788bd1
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_js.cpp
@@ -0,0 +1,174 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <json/reader.h>
+#include <json/writer.h>
+#include <string>
+#include "pim_contacts_js.hpp"
+#include "pim_contacts_qt.hpp"
+
+PimContacts::PimContacts(const std::string& id) : m_id(id)
+{
+}
+
+char* onGetObjList()
+{
+ // Return list of classes in the object
+ static char name[] = "PimContacts";
+ return name;
+}
+
+JSExt* onCreateObject(const std::string& className, const std::string& id)
+{
+ // Make sure we are creating the right class
+ if (className != "PimContacts") {
+ return 0;
+ }
+
+ return new PimContacts(id);
+}
+
+std::string PimContacts::InvokeMethod(const std::string& command)
+{
+ unsigned int index = command.find_first_of(" ");
+
+ string strCommand;
+ string jsonObject;
+ Json::Value *obj;
+
+ if (index != std::string::npos) {
+ strCommand = command.substr(0, index);
+ jsonObject = command.substr(index + 1, command.length());
+
+ // Parse the JSON
+ obj = new Json::Value;
+ bool parse = Json::Reader().parse(jsonObject, *obj);
+
+ if (!parse) {
+ return "Cannot parse JSON object";
+ }
+ } else {
+ strCommand = command;
+ obj = NULL;
+ }
+
+ if (strCommand == "find") {
+ startThread(FindThread, obj);
+ } else if (strCommand == "save") {
+ startThread(SaveThread, obj);
+ } else if (strCommand == "remove") {
+ startThread(RemoveThread, obj);
+ } else if (strCommand == "getContact") {
+ std::string result = Json::FastWriter().write(webworks::PimContactsQt().GetContact(*obj));
+ delete obj;
+ return result;
+ } else if (strCommand == "invokePicker") {
+ Json::Value result = webworks::PimContactsQt::InvokePicker(*obj);
+ delete obj;
+
+ std::string event = Json::FastWriter().write(result);
+ NotifyEvent("invokeContactPicker.invokeEventId", event);
+ } else if (strCommand == "getContactAccounts") {
+ return Json::FastWriter().write(webworks::PimContactsQt::GetContactAccounts());
+ }
+
+ return "";
+}
+
+bool PimContacts::CanDelete()
+{
+ return true;
+}
+
+// Notifies JavaScript of an event
+void PimContacts::NotifyEvent(const std::string& eventId, const std::string& event)
+{
+ std::string eventString = m_id + " result ";
+ eventString.append(eventId);
+ eventString.append(" ");
+ eventString.append(event);
+ SendPluginEvent(eventString.c_str(), m_pContext);
+}
+
+bool PimContacts::startThread(ThreadFunc threadFunction, Json::Value *jsonObj) {
+ webworks::PimContactsThreadInfo *thread_info = new webworks::PimContactsThreadInfo;
+ thread_info->parent = this;
+ thread_info->jsonObj = jsonObj;
+ thread_info->eventId = jsonObj->removeMember("_eventId").asString();
+
+ pthread_attr_t thread_attr;
+ pthread_attr_init(&thread_attr);
+ pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
+
+ pthread_t thread;
+ pthread_create(&thread, &thread_attr, threadFunction, static_cast<void *>(thread_info));
+ pthread_attr_destroy(&thread_attr);
+
+ if (!thread) {
+ return false;
+ }
+
+ return true;
+}
+
+
+// Static functions:
+
+void* PimContacts::FindThread(void *args)
+{
+ webworks::PimContactsThreadInfo *thread_info = static_cast<webworks::PimContactsThreadInfo *>(args);
+
+ webworks::PimContactsQt pim_qt;
+ Json::Value result = pim_qt.Find(*(thread_info->jsonObj));
+ delete thread_info->jsonObj;
+
+ std::string event = Json::FastWriter().write(result);
+ thread_info->parent->NotifyEvent(thread_info->eventId, event);
+ delete thread_info;
+
+ return NULL;
+}
+
+void* PimContacts::SaveThread(void *args)
+{
+ webworks::PimContactsThreadInfo *thread_info = static_cast<webworks::PimContactsThreadInfo *>(args);
+
+ webworks::PimContactsQt pim_qt;
+ Json::Value result = pim_qt.Save(*(thread_info->jsonObj));
+ delete thread_info->jsonObj;
+
+ std::string event = Json::FastWriter().write(result);
+ thread_info->parent->NotifyEvent(thread_info->eventId, event);
+ delete thread_info;
+
+ return NULL;
+}
+
+void* PimContacts::RemoveThread(void *args)
+{
+ webworks::PimContactsThreadInfo *thread_info = static_cast<webworks::PimContactsThreadInfo *>(args);
+
+ webworks::PimContactsQt pim_qt;
+ Json::Value result = pim_qt.DeleteContact(*(thread_info->jsonObj));
+ delete thread_info->jsonObj;
+
+ std::string event = Json::FastWriter().write(result);
+ thread_info->parent->NotifyEvent(thread_info->eventId, event);
+ delete thread_info;
+
+ return NULL;
+}
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_js.hpp
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_js.hpp b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_js.hpp
new file mode 100644
index 0000000..df8bbd7
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_js.hpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef PIM_CONTACTS_JS_H_
+#define PIM_CONTACTS_JS_H_
+
+#include <json/value.h>
+#include <pthread.h>
+#include <string>
+#include "../common/plugin.h"
+
+typedef void* ThreadFunc(void *args);
+
+class PimContacts : public JSExt
+{
+public:
+ explicit PimContacts(const std::string& id);
+ virtual ~PimContacts() {}
+ virtual std::string InvokeMethod(const std::string& command);
+ virtual bool CanDelete();
+ void NotifyEvent(const std::string& eventId, const std::string& event);
+
+ static void* FindThread(void *args);
+ static void* SaveThread(void *args);
+ static void* RemoveThread(void *args);
+private:
+ bool startThread(ThreadFunc threadFunction, Json::Value *jsonObj);
+
+ std::string m_id;
+};
+
+#endif // PIM_CONTACTS_JS_H_
[03/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/cordova.js
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/cordova.js b/lib/cordova-ios/CordovaLib/cordova.js
new file mode 100644
index 0000000..f48d6f9
--- /dev/null
+++ b/lib/cordova-ios/CordovaLib/cordova.js
@@ -0,0 +1,6453 @@
+// Platform: ios
+// 2.8.0rc1-0-g22bc4d8
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+*/
+;(function() {
+var CORDOVA_JS_BUILD_LABEL = '2.8.0rc1-0-g22bc4d8';
+// file: lib/scripts/require.js
+
+var require,
+ define;
+
+(function () {
+ var modules = {},
+ // Stack of moduleIds currently being built.
+ requireStack = [],
+ // Map of module ID -> index into requireStack of modules currently being built.
+ inProgressModules = {},
+ SEPERATOR = ".";
+
+
+
+ function build(module) {
+ var factory = module.factory,
+ localRequire = function (id) {
+ var resultantId = id;
+ //Its a relative path, so lop off the last portion and add the id (minus "./")
+ if (id.charAt(0) === ".") {
+ resultantId = module.id.slice(0, module.id.lastIndexOf(SEPERATOR)) + SEPERATOR + id.slice(2);
+ }
+ return require(resultantId);
+ };
+ module.exports = {};
+ delete module.factory;
+ factory(localRequire, module.exports, module);
+ return module.exports;
+ }
+
+ require = function (id) {
+ if (!modules[id]) {
+ throw "module " + id + " not found";
+ } else if (id in inProgressModules) {
+ var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;
+ throw "Cycle in require graph: " + cycle;
+ }
+ if (modules[id].factory) {
+ try {
+ inProgressModules[id] = requireStack.length;
+ requireStack.push(id);
+ return build(modules[id]);
+ } finally {
+ delete inProgressModules[id];
+ requireStack.pop();
+ }
+ }
+ return modules[id].exports;
+ };
+
+ define = function (id, factory) {
+ if (modules[id]) {
+ throw "module " + id + " already defined";
+ }
+
+ modules[id] = {
+ id: id,
+ factory: factory
+ };
+ };
+
+ define.remove = function (id) {
+ delete modules[id];
+ };
+
+ define.moduleMap = modules;
+})();
+
+//Export for use in node
+if (typeof module === "object" && typeof require === "function") {
+ module.exports.require = require;
+ module.exports.define = define;
+}
+
+// file: lib/cordova.js
+define("cordova", function(require, exports, module) {
+
+
+var channel = require('cordova/channel');
+
+/**
+ * Listen for DOMContentLoaded and notify our channel subscribers.
+ */
+document.addEventListener('DOMContentLoaded', function() {
+ channel.onDOMContentLoaded.fire();
+}, false);
+if (document.readyState == 'complete' || document.readyState == 'interactive') {
+ channel.onDOMContentLoaded.fire();
+}
+
+/**
+ * Intercept calls to addEventListener + removeEventListener and handle deviceready,
+ * resume, and pause events.
+ */
+var m_document_addEventListener = document.addEventListener;
+var m_document_removeEventListener = document.removeEventListener;
+var m_window_addEventListener = window.addEventListener;
+var m_window_removeEventListener = window.removeEventListener;
+
+/**
+ * Houses custom event handlers to intercept on document + window event listeners.
+ */
+var documentEventHandlers = {},
+ windowEventHandlers = {};
+
+document.addEventListener = function(evt, handler, capture) {
+ var e = evt.toLowerCase();
+ if (typeof documentEventHandlers[e] != 'undefined') {
+ documentEventHandlers[e].subscribe(handler);
+ } else {
+ m_document_addEventListener.call(document, evt, handler, capture);
+ }
+};
+
+window.addEventListener = function(evt, handler, capture) {
+ var e = evt.toLowerCase();
+ if (typeof windowEventHandlers[e] != 'undefined') {
+ windowEventHandlers[e].subscribe(handler);
+ } else {
+ m_window_addEventListener.call(window, evt, handler, capture);
+ }
+};
+
+document.removeEventListener = function(evt, handler, capture) {
+ var e = evt.toLowerCase();
+ // If unsubscribing from an event that is handled by a plugin
+ if (typeof documentEventHandlers[e] != "undefined") {
+ documentEventHandlers[e].unsubscribe(handler);
+ } else {
+ m_document_removeEventListener.call(document, evt, handler, capture);
+ }
+};
+
+window.removeEventListener = function(evt, handler, capture) {
+ var e = evt.toLowerCase();
+ // If unsubscribing from an event that is handled by a plugin
+ if (typeof windowEventHandlers[e] != "undefined") {
+ windowEventHandlers[e].unsubscribe(handler);
+ } else {
+ m_window_removeEventListener.call(window, evt, handler, capture);
+ }
+};
+
+function createEvent(type, data) {
+ var event = document.createEvent('Events');
+ event.initEvent(type, false, false);
+ if (data) {
+ for (var i in data) {
+ if (data.hasOwnProperty(i)) {
+ event[i] = data[i];
+ }
+ }
+ }
+ return event;
+}
+
+if(typeof window.console === "undefined") {
+ window.console = {
+ log:function(){}
+ };
+}
+
+var cordova = {
+ define:define,
+ require:require,
+ /**
+ * Methods to add/remove your own addEventListener hijacking on document + window.
+ */
+ addWindowEventHandler:function(event) {
+ return (windowEventHandlers[event] = channel.create(event));
+ },
+ addStickyDocumentEventHandler:function(event) {
+ return (documentEventHandlers[event] = channel.createSticky(event));
+ },
+ addDocumentEventHandler:function(event) {
+ return (documentEventHandlers[event] = channel.create(event));
+ },
+ removeWindowEventHandler:function(event) {
+ delete windowEventHandlers[event];
+ },
+ removeDocumentEventHandler:function(event) {
+ delete documentEventHandlers[event];
+ },
+ /**
+ * Retrieve original event handlers that were replaced by Cordova
+ *
+ * @return object
+ */
+ getOriginalHandlers: function() {
+ return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},
+ 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};
+ },
+ /**
+ * Method to fire event from native code
+ * bNoDetach is required for events which cause an exception which needs to be caught in native code
+ */
+ fireDocumentEvent: function(type, data, bNoDetach) {
+ var evt = createEvent(type, data);
+ if (typeof documentEventHandlers[type] != 'undefined') {
+ if( bNoDetach ) {
+ documentEventHandlers[type].fire(evt);
+ }
+ else {
+ setTimeout(function() {
+ // Fire deviceready on listeners that were registered before cordova.js was loaded.
+ if (type == 'deviceready') {
+ document.dispatchEvent(evt);
+ }
+ documentEventHandlers[type].fire(evt);
+ }, 0);
+ }
+ } else {
+ document.dispatchEvent(evt);
+ }
+ },
+ fireWindowEvent: function(type, data) {
+ var evt = createEvent(type,data);
+ if (typeof windowEventHandlers[type] != 'undefined') {
+ setTimeout(function() {
+ windowEventHandlers[type].fire(evt);
+ }, 0);
+ } else {
+ window.dispatchEvent(evt);
+ }
+ },
+
+ /**
+ * Plugin callback mechanism.
+ */
+ // Randomize the starting callbackId to avoid collisions after refreshing or navigating.
+ // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.
+ callbackId: Math.floor(Math.random() * 2000000000),
+ callbacks: {},
+ callbackStatus: {
+ NO_RESULT: 0,
+ OK: 1,
+ CLASS_NOT_FOUND_EXCEPTION: 2,
+ ILLEGAL_ACCESS_EXCEPTION: 3,
+ INSTANTIATION_EXCEPTION: 4,
+ MALFORMED_URL_EXCEPTION: 5,
+ IO_EXCEPTION: 6,
+ INVALID_ACTION: 7,
+ JSON_EXCEPTION: 8,
+ ERROR: 9
+ },
+
+ /**
+ * Called by native code when returning successful result from an action.
+ */
+ callbackSuccess: function(callbackId, args) {
+ try {
+ cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
+ } catch (e) {
+ console.log("Error in error callback: " + callbackId + " = "+e);
+ }
+ },
+
+ /**
+ * Called by native code when returning error result from an action.
+ */
+ callbackError: function(callbackId, args) {
+ // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
+ // Derive success from status.
+ try {
+ cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
+ } catch (e) {
+ console.log("Error in error callback: " + callbackId + " = "+e);
+ }
+ },
+
+ /**
+ * Called by native code when returning the result from an action.
+ */
+ callbackFromNative: function(callbackId, success, status, args, keepCallback) {
+ var callback = cordova.callbacks[callbackId];
+ if (callback) {
+ if (success && status == cordova.callbackStatus.OK) {
+ callback.success && callback.success.apply(null, args);
+ } else if (!success) {
+ callback.fail && callback.fail.apply(null, args);
+ }
+
+ // Clear callback if not expecting any more results
+ if (!keepCallback) {
+ delete cordova.callbacks[callbackId];
+ }
+ }
+ },
+ addConstructor: function(func) {
+ channel.onCordovaReady.subscribe(function() {
+ try {
+ func();
+ } catch(e) {
+ console.log("Failed to run constructor: " + e);
+ }
+ });
+ }
+};
+
+// Register pause, resume and deviceready channels as events on document.
+channel.onPause = cordova.addDocumentEventHandler('pause');
+channel.onResume = cordova.addDocumentEventHandler('resume');
+channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');
+
+module.exports = cordova;
+
+});
+
+// file: lib/common/argscheck.js
+define("cordova/argscheck", function(require, exports, module) {
+
+var exec = require('cordova/exec');
+var utils = require('cordova/utils');
+
+var moduleExports = module.exports;
+
+var typeMap = {
+ 'A': 'Array',
+ 'D': 'Date',
+ 'N': 'Number',
+ 'S': 'String',
+ 'F': 'Function',
+ 'O': 'Object'
+};
+
+function extractParamName(callee, argIndex) {
+ return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex];
+}
+
+function checkArgs(spec, functionName, args, opt_callee) {
+ if (!moduleExports.enableChecks) {
+ return;
+ }
+ var errMsg = null;
+ var typeName;
+ for (var i = 0; i < spec.length; ++i) {
+ var c = spec.charAt(i),
+ cUpper = c.toUpperCase(),
+ arg = args[i];
+ // Asterix means allow anything.
+ if (c == '*') {
+ continue;
+ }
+ typeName = utils.typeName(arg);
+ if ((arg === null || arg === undefined) && c == cUpper) {
+ continue;
+ }
+ if (typeName != typeMap[cUpper]) {
+ errMsg = 'Expected ' + typeMap[cUpper];
+ break;
+ }
+ }
+ if (errMsg) {
+ errMsg += ', but got ' + typeName + '.';
+ errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;
+ // Don't log when running jake test.
+ if (typeof jasmine == 'undefined') {
+ console.error(errMsg);
+ }
+ throw TypeError(errMsg);
+ }
+}
+
+function getValue(value, defaultValue) {
+ return value === undefined ? defaultValue : value;
+}
+
+moduleExports.checkArgs = checkArgs;
+moduleExports.getValue = getValue;
+moduleExports.enableChecks = true;
+
+
+});
+
+// file: lib/common/builder.js
+define("cordova/builder", function(require, exports, module) {
+
+var utils = require('cordova/utils');
+
+function each(objects, func, context) {
+ for (var prop in objects) {
+ if (objects.hasOwnProperty(prop)) {
+ func.apply(context, [objects[prop], prop]);
+ }
+ }
+}
+
+function clobber(obj, key, value) {
+ exports.replaceHookForTesting(obj, key);
+ obj[key] = value;
+ // Getters can only be overridden by getters.
+ if (obj[key] !== value) {
+ utils.defineGetter(obj, key, function() {
+ return value;
+ });
+ }
+}
+
+function assignOrWrapInDeprecateGetter(obj, key, value, message) {
+ if (message) {
+ utils.defineGetter(obj, key, function() {
+ console.log(message);
+ delete obj[key];
+ clobber(obj, key, value);
+ return value;
+ });
+ } else {
+ clobber(obj, key, value);
+ }
+}
+
+function include(parent, objects, clobber, merge) {
+ each(objects, function (obj, key) {
+ try {
+ var result = obj.path ? require(obj.path) : {};
+
+ if (clobber) {
+ // Clobber if it doesn't exist.
+ if (typeof parent[key] === 'undefined') {
+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
+ } else if (typeof obj.path !== 'undefined') {
+ // If merging, merge properties onto parent, otherwise, clobber.
+ if (merge) {
+ recursiveMerge(parent[key], result);
+ } else {
+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
+ }
+ }
+ result = parent[key];
+ } else {
+ // Overwrite if not currently defined.
+ if (typeof parent[key] == 'undefined') {
+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
+ } else {
+ // Set result to what already exists, so we can build children into it if they exist.
+ result = parent[key];
+ }
+ }
+
+ if (obj.children) {
+ include(result, obj.children, clobber, merge);
+ }
+ } catch(e) {
+ utils.alert('Exception building cordova JS globals: ' + e + ' for key "' + key + '"');
+ }
+ });
+}
+
+/**
+ * Merge properties from one object onto another recursively. Properties from
+ * the src object will overwrite existing target property.
+ *
+ * @param target Object to merge properties into.
+ * @param src Object to merge properties from.
+ */
+function recursiveMerge(target, src) {
+ for (var prop in src) {
+ if (src.hasOwnProperty(prop)) {
+ if (target.prototype && target.prototype.constructor === target) {
+ // If the target object is a constructor override off prototype.
+ clobber(target.prototype, prop, src[prop]);
+ } else {
+ if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
+ recursiveMerge(target[prop], src[prop]);
+ } else {
+ clobber(target, prop, src[prop]);
+ }
+ }
+ }
+ }
+}
+
+exports.buildIntoButDoNotClobber = function(objects, target) {
+ include(target, objects, false, false);
+};
+exports.buildIntoAndClobber = function(objects, target) {
+ include(target, objects, true, false);
+};
+exports.buildIntoAndMerge = function(objects, target) {
+ include(target, objects, true, true);
+};
+exports.recursiveMerge = recursiveMerge;
+exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;
+exports.replaceHookForTesting = function() {};
+
+});
+
+// file: lib/common/channel.js
+define("cordova/channel", function(require, exports, module) {
+
+var utils = require('cordova/utils'),
+ nextGuid = 1;
+
+/**
+ * Custom pub-sub "channel" that can have functions subscribed to it
+ * This object is used to define and control firing of events for
+ * cordova initialization, as well as for custom events thereafter.
+ *
+ * The order of events during page load and Cordova startup is as follows:
+ *
+ * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.
+ * onNativeReady* Internal event that indicates the Cordova native side is ready.
+ * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.
+ * onCordovaInfoReady* Internal event fired when device properties are available.
+ * onCordovaConnectionReady* Internal event fired when the connection property has been set.
+ * onDeviceReady* User event fired to indicate that Cordova is ready
+ * onResume User event fired to indicate a start/resume lifecycle event
+ * onPause User event fired to indicate a pause lifecycle event
+ * onDestroy* Internal event fired when app is being destroyed (User should use window.onunload event, not this one).
+ *
+ * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.
+ * All listeners that subscribe after the event is fired will be executed right away.
+ *
+ * The only Cordova events that user code should register for are:
+ * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript
+ * pause App has moved to background
+ * resume App has returned to foreground
+ *
+ * Listeners can be registered as:
+ * document.addEventListener("deviceready", myDeviceReadyListener, false);
+ * document.addEventListener("resume", myResumeListener, false);
+ * document.addEventListener("pause", myPauseListener, false);
+ *
+ * The DOM lifecycle events should be used for saving and restoring state
+ * window.onload
+ * window.onunload
+ *
+ */
+
+/**
+ * Channel
+ * @constructor
+ * @param type String the channel name
+ */
+var Channel = function(type, sticky) {
+ this.type = type;
+ // Map of guid -> function.
+ this.handlers = {};
+ // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
+ this.state = sticky ? 1 : 0;
+ // Used in sticky mode to remember args passed to fire().
+ this.fireArgs = null;
+ // Used by onHasSubscribersChange to know if there are any listeners.
+ this.numHandlers = 0;
+ // Function that is called when the first listener is subscribed, or when
+ // the last listener is unsubscribed.
+ this.onHasSubscribersChange = null;
+},
+ channel = {
+ /**
+ * Calls the provided function only after all of the channels specified
+ * have been fired. All channels must be sticky channels.
+ */
+ join: function(h, c) {
+ var len = c.length,
+ i = len,
+ f = function() {
+ if (!(--i)) h();
+ };
+ for (var j=0; j<len; j++) {
+ if (c[j].state === 0) {
+ throw Error('Can only use join with sticky channels.');
+ }
+ c[j].subscribe(f);
+ }
+ if (!len) h();
+ },
+ create: function(type) {
+ return channel[type] = new Channel(type, false);
+ },
+ createSticky: function(type) {
+ return channel[type] = new Channel(type, true);
+ },
+
+ /**
+ * cordova Channels that must fire before "deviceready" is fired.
+ */
+ deviceReadyChannelsArray: [],
+ deviceReadyChannelsMap: {},
+
+ /**
+ * Indicate that a feature needs to be initialized before it is ready to be used.
+ * This holds up Cordova's "deviceready" event until the feature has been initialized
+ * and Cordova.initComplete(feature) is called.
+ *
+ * @param feature {String} The unique feature name
+ */
+ waitForInitialization: function(feature) {
+ if (feature) {
+ var c = channel[feature] || this.createSticky(feature);
+ this.deviceReadyChannelsMap[feature] = c;
+ this.deviceReadyChannelsArray.push(c);
+ }
+ },
+
+ /**
+ * Indicate that initialization code has completed and the feature is ready to be used.
+ *
+ * @param feature {String} The unique feature name
+ */
+ initializationComplete: function(feature) {
+ var c = this.deviceReadyChannelsMap[feature];
+ if (c) {
+ c.fire();
+ }
+ }
+ };
+
+function forceFunction(f) {
+ if (typeof f != 'function') throw "Function required as first argument!";
+}
+
+/**
+ * Subscribes the given function to the channel. Any time that
+ * Channel.fire is called so too will the function.
+ * Optionally specify an execution context for the function
+ * and a guid that can be used to stop subscribing to the channel.
+ * Returns the guid.
+ */
+Channel.prototype.subscribe = function(f, c) {
+ // need a function to call
+ forceFunction(f);
+ if (this.state == 2) {
+ f.apply(c || this, this.fireArgs);
+ return;
+ }
+
+ var func = f,
+ guid = f.observer_guid;
+ if (typeof c == "object") { func = utils.close(c, f); }
+
+ if (!guid) {
+ // first time any channel has seen this subscriber
+ guid = '' + nextGuid++;
+ }
+ func.observer_guid = guid;
+ f.observer_guid = guid;
+
+ // Don't add the same handler more than once.
+ if (!this.handlers[guid]) {
+ this.handlers[guid] = func;
+ this.numHandlers++;
+ if (this.numHandlers == 1) {
+ this.onHasSubscribersChange && this.onHasSubscribersChange();
+ }
+ }
+};
+
+/**
+ * Unsubscribes the function with the given guid from the channel.
+ */
+Channel.prototype.unsubscribe = function(f) {
+ // need a function to unsubscribe
+ forceFunction(f);
+
+ var guid = f.observer_guid,
+ handler = this.handlers[guid];
+ if (handler) {
+ delete this.handlers[guid];
+ this.numHandlers--;
+ if (this.numHandlers === 0) {
+ this.onHasSubscribersChange && this.onHasSubscribersChange();
+ }
+ }
+};
+
+/**
+ * Calls all functions subscribed to this channel.
+ */
+Channel.prototype.fire = function(e) {
+ var fail = false,
+ fireArgs = Array.prototype.slice.call(arguments);
+ // Apply stickiness.
+ if (this.state == 1) {
+ this.state = 2;
+ this.fireArgs = fireArgs;
+ }
+ if (this.numHandlers) {
+ // Copy the values first so that it is safe to modify it from within
+ // callbacks.
+ var toCall = [];
+ for (var item in this.handlers) {
+ toCall.push(this.handlers[item]);
+ }
+ for (var i = 0; i < toCall.length; ++i) {
+ toCall[i].apply(this, fireArgs);
+ }
+ if (this.state == 2 && this.numHandlers) {
+ this.numHandlers = 0;
+ this.handlers = {};
+ this.onHasSubscribersChange && this.onHasSubscribersChange();
+ }
+ }
+};
+
+
+// defining them here so they are ready super fast!
+// DOM event that is received when the web page is loaded and parsed.
+channel.createSticky('onDOMContentLoaded');
+
+// Event to indicate the Cordova native side is ready.
+channel.createSticky('onNativeReady');
+
+// Event to indicate that all Cordova JavaScript objects have been created
+// and it's time to run plugin constructors.
+channel.createSticky('onCordovaReady');
+
+// Event to indicate that device properties are available
+channel.createSticky('onCordovaInfoReady');
+
+// Event to indicate that the connection property has been set.
+channel.createSticky('onCordovaConnectionReady');
+
+// Event to indicate that all automatically loaded JS plugins are loaded and ready.
+channel.createSticky('onPluginsReady');
+
+// Event to indicate that Cordova is ready
+channel.createSticky('onDeviceReady');
+
+// Event to indicate a resume lifecycle event
+channel.create('onResume');
+
+// Event to indicate a pause lifecycle event
+channel.create('onPause');
+
+// Event to indicate a destroy lifecycle event
+channel.createSticky('onDestroy');
+
+// Channels that must fire before "deviceready" is fired.
+channel.waitForInitialization('onCordovaReady');
+channel.waitForInitialization('onCordovaConnectionReady');
+channel.waitForInitialization('onDOMContentLoaded');
+
+module.exports = channel;
+
+});
+
+// file: lib/common/commandProxy.js
+define("cordova/commandProxy", function(require, exports, module) {
+
+
+// internal map of proxy function
+var CommandProxyMap = {};
+
+module.exports = {
+
+ // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);
+ add:function(id,proxyObj) {
+ console.log("adding proxy for " + id);
+ CommandProxyMap[id] = proxyObj;
+ return proxyObj;
+ },
+
+ // cordova.commandProxy.remove("Accelerometer");
+ remove:function(id) {
+ var proxy = CommandProxyMap[id];
+ delete CommandProxyMap[id];
+ CommandProxyMap[id] = null;
+ return proxy;
+ },
+
+ get:function(service,action) {
+ return ( CommandProxyMap[service] ? CommandProxyMap[service][action] : null );
+ }
+};
+});
+
+// file: lib/ios/exec.js
+define("cordova/exec", function(require, exports, module) {
+
+/**
+ * Creates a gap bridge iframe used to notify the native code about queued
+ * commands.
+ *
+ * @private
+ */
+var cordova = require('cordova'),
+ channel = require('cordova/channel'),
+ utils = require('cordova/utils'),
+ jsToNativeModes = {
+ IFRAME_NAV: 0,
+ XHR_NO_PAYLOAD: 1,
+ XHR_WITH_PAYLOAD: 2,
+ XHR_OPTIONAL_PAYLOAD: 3
+ },
+ bridgeMode,
+ execIframe,
+ execXhr,
+ requestCount = 0,
+ vcHeaderValue = null,
+ commandQueue = [], // Contains pending JS->Native messages.
+ isInContextOfEvalJs = 0;
+
+function createExecIframe() {
+ var iframe = document.createElement("iframe");
+ iframe.style.display = 'none';
+ document.body.appendChild(iframe);
+ return iframe;
+}
+
+function shouldBundleCommandJson() {
+ if (bridgeMode == jsToNativeModes.XHR_WITH_PAYLOAD) {
+ return true;
+ }
+ if (bridgeMode == jsToNativeModes.XHR_OPTIONAL_PAYLOAD) {
+ var payloadLength = 0;
+ for (var i = 0; i < commandQueue.length; ++i) {
+ payloadLength += commandQueue[i].length;
+ }
+ // The value here was determined using the benchmark within CordovaLibApp on an iPad 3.
+ return payloadLength < 4500;
+ }
+ return false;
+}
+
+function massageArgsJsToNative(args) {
+ if (!args || utils.typeName(args) != 'Array') {
+ return args;
+ }
+ var ret = [];
+ var encodeArrayBufferAs8bitString = function(ab) {
+ return String.fromCharCode.apply(null, new Uint8Array(ab));
+ };
+ var encodeArrayBufferAsBase64 = function(ab) {
+ return window.btoa(encodeArrayBufferAs8bitString(ab));
+ };
+ args.forEach(function(arg, i) {
+ if (utils.typeName(arg) == 'ArrayBuffer') {
+ ret.push({
+ 'CDVType': 'ArrayBuffer',
+ 'data': encodeArrayBufferAsBase64(arg)
+ });
+ } else {
+ ret.push(arg);
+ }
+ });
+ return ret;
+}
+
+function massageMessageNativeToJs(message) {
+ if (message.CDVType == 'ArrayBuffer') {
+ var stringToArrayBuffer = function(str) {
+ var ret = new Uint8Array(str.length);
+ for (var i = 0; i < str.length; i++) {
+ ret[i] = str.charCodeAt(i);
+ }
+ return ret.buffer;
+ };
+ var base64ToArrayBuffer = function(b64) {
+ return stringToArrayBuffer(atob(b64));
+ };
+ message = base64ToArrayBuffer(message.data);
+ }
+ return message;
+}
+
+function convertMessageToArgsNativeToJs(message) {
+ var args = [];
+ if (!message || !message.hasOwnProperty('CDVType')) {
+ args.push(message);
+ } else if (message.CDVType == 'MultiPart') {
+ message.messages.forEach(function(e) {
+ args.push(massageMessageNativeToJs(e));
+ });
+ } else {
+ args.push(massageMessageNativeToJs(message));
+ }
+ return args;
+}
+
+function iOSExec() {
+ // XHR mode does not work on iOS 4.2, so default to IFRAME_NAV for such devices.
+ // XHR mode's main advantage is working around a bug in -webkit-scroll, which
+ // doesn't exist in 4.X devices anyways.
+ if (bridgeMode === undefined) {
+ bridgeMode = navigator.userAgent.indexOf(' 4_') == -1 ? jsToNativeModes.XHR_NO_PAYLOAD : jsToNativeModes.IFRAME_NAV;
+ }
+
+ var successCallback, failCallback, service, action, actionArgs, splitCommand;
+ var callbackId = null;
+ if (typeof arguments[0] !== "string") {
+ // FORMAT ONE
+ successCallback = arguments[0];
+ failCallback = arguments[1];
+ service = arguments[2];
+ action = arguments[3];
+ actionArgs = arguments[4];
+
+ // Since we need to maintain backwards compatibility, we have to pass
+ // an invalid callbackId even if no callback was provided since plugins
+ // will be expecting it. The Cordova.exec() implementation allocates
+ // an invalid callbackId and passes it even if no callbacks were given.
+ callbackId = 'INVALID';
+ } else {
+ // FORMAT TWO, REMOVED
+ try {
+ splitCommand = arguments[0].split(".");
+ action = splitCommand.pop();
+ service = splitCommand.join(".");
+ actionArgs = Array.prototype.splice.call(arguments, 1);
+
+ console.log('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' +
+ "cordova.exec(null, null, \"" + service + "\", " + action + "\"," + JSON.stringify(actionArgs) + ");"
+ );
+ return;
+ } catch (e) {
+ }
+ }
+
+ // Register the callbacks and add the callbackId to the positional
+ // arguments if given.
+ if (successCallback || failCallback) {
+ callbackId = service + cordova.callbackId++;
+ cordova.callbacks[callbackId] =
+ {success:successCallback, fail:failCallback};
+ }
+
+ actionArgs = massageArgsJsToNative(actionArgs);
+
+ var command = [callbackId, service, action, actionArgs];
+
+ // Stringify and queue the command. We stringify to command now to
+ // effectively clone the command arguments in case they are mutated before
+ // the command is executed.
+ commandQueue.push(JSON.stringify(command));
+
+ // If we're in the context of a stringByEvaluatingJavaScriptFromString call,
+ // then the queue will be flushed when it returns; no need for a poke.
+ // Also, if there is already a command in the queue, then we've already
+ // poked the native side, so there is no reason to do so again.
+ if (!isInContextOfEvalJs && commandQueue.length == 1) {
+ if (bridgeMode != jsToNativeModes.IFRAME_NAV) {
+ // This prevents sending an XHR when there is already one being sent.
+ // This should happen only in rare circumstances (refer to unit tests).
+ if (execXhr && execXhr.readyState != 4) {
+ execXhr = null;
+ }
+ // Re-using the XHR improves exec() performance by about 10%.
+ execXhr = execXhr || new XMLHttpRequest();
+ // Changing this to a GET will make the XHR reach the URIProtocol on 4.2.
+ // For some reason it still doesn't work though...
+ // Add a timestamp to the query param to prevent caching.
+ execXhr.open('HEAD', "/!gap_exec?" + (+new Date()), true);
+ if (!vcHeaderValue) {
+ vcHeaderValue = /.*\((.*)\)/.exec(navigator.userAgent)[1];
+ }
+ execXhr.setRequestHeader('vc', vcHeaderValue);
+ execXhr.setRequestHeader('rc', ++requestCount);
+ if (shouldBundleCommandJson()) {
+ execXhr.setRequestHeader('cmds', iOSExec.nativeFetchMessages());
+ }
+ execXhr.send(null);
+ } else {
+ execIframe = execIframe || createExecIframe();
+ execIframe.src = "gap://ready";
+ }
+ }
+}
+
+iOSExec.jsToNativeModes = jsToNativeModes;
+
+iOSExec.setJsToNativeBridgeMode = function(mode) {
+ // Remove the iFrame since it may be no longer required, and its existence
+ // can trigger browser bugs.
+ // https://issues.apache.org/jira/browse/CB-593
+ if (execIframe) {
+ execIframe.parentNode.removeChild(execIframe);
+ execIframe = null;
+ }
+ bridgeMode = mode;
+};
+
+iOSExec.nativeFetchMessages = function() {
+ // Each entry in commandQueue is a JSON string already.
+ if (!commandQueue.length) {
+ return '';
+ }
+ var json = '[' + commandQueue.join(',') + ']';
+ commandQueue.length = 0;
+ return json;
+};
+
+iOSExec.nativeCallback = function(callbackId, status, message, keepCallback) {
+ return iOSExec.nativeEvalAndFetch(function() {
+ var success = status === 0 || status === 1;
+ var args = convertMessageToArgsNativeToJs(message);
+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback);
+ });
+};
+
+iOSExec.nativeEvalAndFetch = function(func) {
+ // This shouldn't be nested, but better to be safe.
+ isInContextOfEvalJs++;
+ try {
+ func();
+ return iOSExec.nativeFetchMessages();
+ } finally {
+ isInContextOfEvalJs--;
+ }
+};
+
+module.exports = iOSExec;
+
+});
+
+// file: lib/common/modulemapper.js
+define("cordova/modulemapper", function(require, exports, module) {
+
+var builder = require('cordova/builder'),
+ moduleMap = define.moduleMap,
+ symbolList,
+ deprecationMap;
+
+exports.reset = function() {
+ symbolList = [];
+ deprecationMap = {};
+};
+
+function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) {
+ if (!(moduleName in moduleMap)) {
+ throw new Error('Module ' + moduleName + ' does not exist.');
+ }
+ symbolList.push(strategy, moduleName, symbolPath);
+ if (opt_deprecationMessage) {
+ deprecationMap[symbolPath] = opt_deprecationMessage;
+ }
+}
+
+// Note: Android 2.3 does have Function.bind().
+exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) {
+ addEntry('c', moduleName, symbolPath, opt_deprecationMessage);
+};
+
+exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) {
+ addEntry('m', moduleName, symbolPath, opt_deprecationMessage);
+};
+
+exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) {
+ addEntry('d', moduleName, symbolPath, opt_deprecationMessage);
+};
+
+function prepareNamespace(symbolPath, context) {
+ if (!symbolPath) {
+ return context;
+ }
+ var parts = symbolPath.split('.');
+ var cur = context;
+ for (var i = 0, part; part = parts[i]; ++i) {
+ cur = cur[part] = cur[part] || {};
+ }
+ return cur;
+}
+
+exports.mapModules = function(context) {
+ var origSymbols = {};
+ context.CDV_origSymbols = origSymbols;
+ for (var i = 0, len = symbolList.length; i < len; i += 3) {
+ var strategy = symbolList[i];
+ var moduleName = symbolList[i + 1];
+ var symbolPath = symbolList[i + 2];
+ var lastDot = symbolPath.lastIndexOf('.');
+ var namespace = symbolPath.substr(0, lastDot);
+ var lastName = symbolPath.substr(lastDot + 1);
+
+ var module = require(moduleName);
+ var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;
+ var parentObj = prepareNamespace(namespace, context);
+ var target = parentObj[lastName];
+
+ if (strategy == 'm' && target) {
+ builder.recursiveMerge(target, module);
+ } else if ((strategy == 'd' && !target) || (strategy != 'd')) {
+ if (!(symbolPath in origSymbols)) {
+ origSymbols[symbolPath] = target;
+ }
+ builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);
+ }
+ }
+};
+
+exports.getOriginalSymbol = function(context, symbolPath) {
+ var origSymbols = context.CDV_origSymbols;
+ if (origSymbols && (symbolPath in origSymbols)) {
+ return origSymbols[symbolPath];
+ }
+ var parts = symbolPath.split('.');
+ var obj = context;
+ for (var i = 0; i < parts.length; ++i) {
+ obj = obj && obj[parts[i]];
+ }
+ return obj;
+};
+
+exports.loadMatchingModules = function(matchingRegExp) {
+ for (var k in moduleMap) {
+ if (matchingRegExp.exec(k)) {
+ require(k);
+ }
+ }
+};
+
+exports.reset();
+
+
+});
+
+// file: lib/ios/platform.js
+define("cordova/platform", function(require, exports, module) {
+
+module.exports = {
+ id: "ios",
+ initialize:function() {
+ var modulemapper = require('cordova/modulemapper');
+
+ modulemapper.loadMatchingModules(/cordova.*\/plugininit$/);
+
+ modulemapper.loadMatchingModules(/cordova.*\/symbols$/);
+ modulemapper.mapModules(window);
+ }
+};
+
+
+});
+
+// file: lib/common/plugin/Acceleration.js
+define("cordova/plugin/Acceleration", function(require, exports, module) {
+
+var Acceleration = function(x, y, z, timestamp) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.timestamp = timestamp || (new Date()).getTime();
+};
+
+module.exports = Acceleration;
+
+});
+
+// file: lib/common/plugin/Camera.js
+define("cordova/plugin/Camera", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ Camera = require('cordova/plugin/CameraConstants'),
+ CameraPopoverHandle = require('cordova/plugin/CameraPopoverHandle');
+
+var cameraExport = {};
+
+// Tack on the Camera Constants to the base camera plugin.
+for (var key in Camera) {
+ cameraExport[key] = Camera[key];
+}
+
+/**
+ * Gets a picture from source defined by "options.sourceType", and returns the
+ * image as defined by the "options.destinationType" option.
+
+ * The defaults are sourceType=CAMERA and destinationType=FILE_URI.
+ *
+ * @param {Function} successCallback
+ * @param {Function} errorCallback
+ * @param {Object} options
+ */
+cameraExport.getPicture = function(successCallback, errorCallback, options) {
+ argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);
+ options = options || {};
+ var getValue = argscheck.getValue;
+
+ var quality = getValue(options.quality, 50);
+ var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);
+ var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);
+ var targetWidth = getValue(options.targetWidth, -1);
+ var targetHeight = getValue(options.targetHeight, -1);
+ var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);
+ var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);
+ var allowEdit = !!options.allowEdit;
+ var correctOrientation = !!options.correctOrientation;
+ var saveToPhotoAlbum = !!options.saveToPhotoAlbum;
+ var popoverOptions = getValue(options.popoverOptions, null);
+ var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
+
+ var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,
+ mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];
+
+ exec(successCallback, errorCallback, "Camera", "takePicture", args);
+ return new CameraPopoverHandle();
+};
+
+cameraExport.cleanup = function(successCallback, errorCallback) {
+ exec(successCallback, errorCallback, "Camera", "cleanup", []);
+};
+
+module.exports = cameraExport;
+
+});
+
+// file: lib/common/plugin/CameraConstants.js
+define("cordova/plugin/CameraConstants", function(require, exports, module) {
+
+module.exports = {
+ DestinationType:{
+ DATA_URL: 0, // Return base64 encoded string
+ FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
+ NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
+ },
+ EncodingType:{
+ JPEG: 0, // Return JPEG encoded image
+ PNG: 1 // Return PNG encoded image
+ },
+ MediaType:{
+ PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
+ VIDEO: 1, // allow selection of video only, ONLY RETURNS URL
+ ALLMEDIA : 2 // allow selection from all media types
+ },
+ PictureSourceType:{
+ PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
+ CAMERA : 1, // Take picture from camera
+ SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
+ },
+ PopoverArrowDirection:{
+ ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants to specify arrow location on popover
+ ARROW_DOWN : 2,
+ ARROW_LEFT : 4,
+ ARROW_RIGHT : 8,
+ ARROW_ANY : 15
+ },
+ Direction:{
+ BACK: 0,
+ FRONT: 1
+ }
+};
+
+});
+
+// file: lib/ios/plugin/CameraPopoverHandle.js
+define("cordova/plugin/CameraPopoverHandle", function(require, exports, module) {
+
+var exec = require('cordova/exec');
+
+/**
+ * A handle to an image picker popover.
+ */
+var CameraPopoverHandle = function() {
+ this.setPosition = function(popoverOptions) {
+ var args = [ popoverOptions ];
+ exec(null, null, "Camera", "repositionPopover", args);
+ };
+};
+
+module.exports = CameraPopoverHandle;
+
+});
+
+// file: lib/common/plugin/CameraPopoverOptions.js
+define("cordova/plugin/CameraPopoverOptions", function(require, exports, module) {
+
+var Camera = require('cordova/plugin/CameraConstants');
+
+/**
+ * Encapsulates options for iOS Popover image picker
+ */
+var CameraPopoverOptions = function(x,y,width,height,arrowDir){
+ // information of rectangle that popover should be anchored to
+ this.x = x || 0;
+ this.y = y || 32;
+ this.width = width || 320;
+ this.height = height || 480;
+ // The direction of the popover arrow
+ this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY;
+};
+
+module.exports = CameraPopoverOptions;
+
+});
+
+// file: lib/common/plugin/CaptureAudioOptions.js
+define("cordova/plugin/CaptureAudioOptions", function(require, exports, module) {
+
+/**
+ * Encapsulates all audio capture operation configuration options.
+ */
+var CaptureAudioOptions = function(){
+ // Upper limit of sound clips user can record. Value must be equal or greater than 1.
+ this.limit = 1;
+ // Maximum duration of a single sound clip in seconds.
+ this.duration = 0;
+};
+
+module.exports = CaptureAudioOptions;
+
+});
+
+// file: lib/common/plugin/CaptureError.js
+define("cordova/plugin/CaptureError", function(require, exports, module) {
+
+/**
+ * The CaptureError interface encapsulates all errors in the Capture API.
+ */
+var CaptureError = function(c) {
+ this.code = c || null;
+};
+
+// Camera or microphone failed to capture image or sound.
+CaptureError.CAPTURE_INTERNAL_ERR = 0;
+// Camera application or audio capture application is currently serving other capture request.
+CaptureError.CAPTURE_APPLICATION_BUSY = 1;
+// Invalid use of the API (e.g. limit parameter has value less than one).
+CaptureError.CAPTURE_INVALID_ARGUMENT = 2;
+// User exited camera application or audio capture application before capturing anything.
+CaptureError.CAPTURE_NO_MEDIA_FILES = 3;
+// The requested capture operation is not supported.
+CaptureError.CAPTURE_NOT_SUPPORTED = 20;
+
+module.exports = CaptureError;
+
+});
+
+// file: lib/common/plugin/CaptureImageOptions.js
+define("cordova/plugin/CaptureImageOptions", function(require, exports, module) {
+
+/**
+ * Encapsulates all image capture operation configuration options.
+ */
+var CaptureImageOptions = function(){
+ // Upper limit of images user can take. Value must be equal or greater than 1.
+ this.limit = 1;
+};
+
+module.exports = CaptureImageOptions;
+
+});
+
+// file: lib/common/plugin/CaptureVideoOptions.js
+define("cordova/plugin/CaptureVideoOptions", function(require, exports, module) {
+
+/**
+ * Encapsulates all video capture operation configuration options.
+ */
+var CaptureVideoOptions = function(){
+ // Upper limit of videos user can record. Value must be equal or greater than 1.
+ this.limit = 1;
+ // Maximum duration of a single video clip in seconds.
+ this.duration = 0;
+};
+
+module.exports = CaptureVideoOptions;
+
+});
+
+// file: lib/common/plugin/CompassError.js
+define("cordova/plugin/CompassError", function(require, exports, module) {
+
+/**
+ * CompassError.
+ * An error code assigned by an implementation when an error has occurred
+ * @constructor
+ */
+var CompassError = function(err) {
+ this.code = (err !== undefined ? err : null);
+};
+
+CompassError.COMPASS_INTERNAL_ERR = 0;
+CompassError.COMPASS_NOT_SUPPORTED = 20;
+
+module.exports = CompassError;
+
+});
+
+// file: lib/common/plugin/CompassHeading.js
+define("cordova/plugin/CompassHeading", function(require, exports, module) {
+
+var CompassHeading = function(magneticHeading, trueHeading, headingAccuracy, timestamp) {
+ this.magneticHeading = magneticHeading;
+ this.trueHeading = trueHeading;
+ this.headingAccuracy = headingAccuracy;
+ this.timestamp = timestamp || new Date().getTime();
+};
+
+module.exports = CompassHeading;
+
+});
+
+// file: lib/common/plugin/ConfigurationData.js
+define("cordova/plugin/ConfigurationData", function(require, exports, module) {
+
+/**
+ * Encapsulates a set of parameters that the capture device supports.
+ */
+function ConfigurationData() {
+ // The ASCII-encoded string in lower case representing the media type.
+ this.type = null;
+ // The height attribute represents height of the image or video in pixels.
+ // In the case of a sound clip this attribute has value 0.
+ this.height = 0;
+ // The width attribute represents width of the image or video in pixels.
+ // In the case of a sound clip this attribute has value 0
+ this.width = 0;
+}
+
+module.exports = ConfigurationData;
+
+});
+
+// file: lib/common/plugin/Connection.js
+define("cordova/plugin/Connection", function(require, exports, module) {
+
+/**
+ * Network status
+ */
+module.exports = {
+ UNKNOWN: "unknown",
+ ETHERNET: "ethernet",
+ WIFI: "wifi",
+ CELL_2G: "2g",
+ CELL_3G: "3g",
+ CELL_4G: "4g",
+ CELL:"cellular",
+ NONE: "none"
+};
+
+});
+
+// file: lib/common/plugin/Contact.js
+define("cordova/plugin/Contact", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ ContactError = require('cordova/plugin/ContactError'),
+ utils = require('cordova/utils');
+
+/**
+* Converts primitives into Complex Object
+* Currently only used for Date fields
+*/
+function convertIn(contact) {
+ var value = contact.birthday;
+ try {
+ contact.birthday = new Date(parseFloat(value));
+ } catch (exception){
+ console.log("Cordova Contact convertIn error: exception creating date.");
+ }
+ return contact;
+}
+
+/**
+* Converts Complex objects into primitives
+* Only conversion at present is for Dates.
+**/
+
+function convertOut(contact) {
+ var value = contact.birthday;
+ if (value !== null) {
+ // try to make it a Date object if it is not already
+ if (!utils.isDate(value)){
+ try {
+ value = new Date(value);
+ } catch(exception){
+ value = null;
+ }
+ }
+ if (utils.isDate(value)){
+ value = value.valueOf(); // convert to milliseconds
+ }
+ contact.birthday = value;
+ }
+ return contact;
+}
+
+/**
+* Contains information about a single contact.
+* @constructor
+* @param {DOMString} id unique identifier
+* @param {DOMString} displayName
+* @param {ContactName} name
+* @param {DOMString} nickname
+* @param {Array.<ContactField>} phoneNumbers array of phone numbers
+* @param {Array.<ContactField>} emails array of email addresses
+* @param {Array.<ContactAddress>} addresses array of addresses
+* @param {Array.<ContactField>} ims instant messaging user ids
+* @param {Array.<ContactOrganization>} organizations
+* @param {DOMString} birthday contact's birthday
+* @param {DOMString} note user notes about contact
+* @param {Array.<ContactField>} photos
+* @param {Array.<ContactField>} categories
+* @param {Array.<ContactField>} urls contact's web sites
+*/
+var Contact = function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
+ ims, organizations, birthday, note, photos, categories, urls) {
+ this.id = id || null;
+ this.rawId = null;
+ this.displayName = displayName || null;
+ this.name = name || null; // ContactName
+ this.nickname = nickname || null;
+ this.phoneNumbers = phoneNumbers || null; // ContactField[]
+ this.emails = emails || null; // ContactField[]
+ this.addresses = addresses || null; // ContactAddress[]
+ this.ims = ims || null; // ContactField[]
+ this.organizations = organizations || null; // ContactOrganization[]
+ this.birthday = birthday || null;
+ this.note = note || null;
+ this.photos = photos || null; // ContactField[]
+ this.categories = categories || null; // ContactField[]
+ this.urls = urls || null; // ContactField[]
+};
+
+/**
+* Removes contact from device storage.
+* @param successCB success callback
+* @param errorCB error callback
+*/
+Contact.prototype.remove = function(successCB, errorCB) {
+ argscheck.checkArgs('FF', 'Contact.remove', arguments);
+ var fail = errorCB && function(code) {
+ errorCB(new ContactError(code));
+ };
+ if (this.id === null) {
+ fail(ContactError.UNKNOWN_ERROR);
+ }
+ else {
+ exec(successCB, fail, "Contacts", "remove", [this.id]);
+ }
+};
+
+/**
+* Creates a deep copy of this Contact.
+* With the contact ID set to null.
+* @return copy of this Contact
+*/
+Contact.prototype.clone = function() {
+ var clonedContact = utils.clone(this);
+ clonedContact.id = null;
+ clonedContact.rawId = null;
+
+ function nullIds(arr) {
+ if (arr) {
+ for (var i = 0; i < arr.length; ++i) {
+ arr[i].id = null;
+ }
+ }
+ }
+
+ // Loop through and clear out any id's in phones, emails, etc.
+ nullIds(clonedContact.phoneNumbers);
+ nullIds(clonedContact.emails);
+ nullIds(clonedContact.addresses);
+ nullIds(clonedContact.ims);
+ nullIds(clonedContact.organizations);
+ nullIds(clonedContact.categories);
+ nullIds(clonedContact.photos);
+ nullIds(clonedContact.urls);
+ return clonedContact;
+};
+
+/**
+* Persists contact to device storage.
+* @param successCB success callback
+* @param errorCB error callback
+*/
+Contact.prototype.save = function(successCB, errorCB) {
+ argscheck.checkArgs('FFO', 'Contact.save', arguments);
+ var fail = errorCB && function(code) {
+ errorCB(new ContactError(code));
+ };
+ var success = function(result) {
+ if (result) {
+ if (successCB) {
+ var fullContact = require('cordova/plugin/contacts').create(result);
+ successCB(convertIn(fullContact));
+ }
+ }
+ else {
+ // no Entry object returned
+ fail(ContactError.UNKNOWN_ERROR);
+ }
+ };
+ var dupContact = convertOut(utils.clone(this));
+ exec(success, fail, "Contacts", "save", [dupContact]);
+};
+
+
+module.exports = Contact;
+
+});
+
+// file: lib/common/plugin/ContactAddress.js
+define("cordova/plugin/ContactAddress", function(require, exports, module) {
+
+/**
+* Contact address.
+* @constructor
+* @param {DOMString} id unique identifier, should only be set by native code
+* @param formatted // NOTE: not a W3C standard
+* @param streetAddress
+* @param locality
+* @param region
+* @param postalCode
+* @param country
+*/
+
+var ContactAddress = function(pref, type, formatted, streetAddress, locality, region, postalCode, country) {
+ this.id = null;
+ this.pref = (typeof pref != 'undefined' ? pref : false);
+ this.type = type || null;
+ this.formatted = formatted || null;
+ this.streetAddress = streetAddress || null;
+ this.locality = locality || null;
+ this.region = region || null;
+ this.postalCode = postalCode || null;
+ this.country = country || null;
+};
+
+module.exports = ContactAddress;
+
+});
+
+// file: lib/common/plugin/ContactError.js
+define("cordova/plugin/ContactError", function(require, exports, module) {
+
+/**
+ * ContactError.
+ * An error code assigned by an implementation when an error has occurred
+ * @constructor
+ */
+var ContactError = function(err) {
+ this.code = (typeof err != 'undefined' ? err : null);
+};
+
+/**
+ * Error codes
+ */
+ContactError.UNKNOWN_ERROR = 0;
+ContactError.INVALID_ARGUMENT_ERROR = 1;
+ContactError.TIMEOUT_ERROR = 2;
+ContactError.PENDING_OPERATION_ERROR = 3;
+ContactError.IO_ERROR = 4;
+ContactError.NOT_SUPPORTED_ERROR = 5;
+ContactError.PERMISSION_DENIED_ERROR = 20;
+
+module.exports = ContactError;
+
+});
+
+// file: lib/common/plugin/ContactField.js
+define("cordova/plugin/ContactField", function(require, exports, module) {
+
+/**
+* Generic contact field.
+* @constructor
+* @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard
+* @param type
+* @param value
+* @param pref
+*/
+var ContactField = function(type, value, pref) {
+ this.id = null;
+ this.type = (type && type.toString()) || null;
+ this.value = (value && value.toString()) || null;
+ this.pref = (typeof pref != 'undefined' ? pref : false);
+};
+
+module.exports = ContactField;
+
+});
+
+// file: lib/common/plugin/ContactFindOptions.js
+define("cordova/plugin/ContactFindOptions", function(require, exports, module) {
+
+/**
+ * ContactFindOptions.
+ * @constructor
+ * @param filter used to match contacts against
+ * @param multiple boolean used to determine if more than one contact should be returned
+ */
+
+var ContactFindOptions = function(filter, multiple) {
+ this.filter = filter || '';
+ this.multiple = (typeof multiple != 'undefined' ? multiple : false);
+};
+
+module.exports = ContactFindOptions;
+
+});
+
+// file: lib/common/plugin/ContactName.js
+define("cordova/plugin/ContactName", function(require, exports, module) {
+
+/**
+* Contact name.
+* @constructor
+* @param formatted // NOTE: not part of W3C standard
+* @param familyName
+* @param givenName
+* @param middle
+* @param prefix
+* @param suffix
+*/
+var ContactName = function(formatted, familyName, givenName, middle, prefix, suffix) {
+ this.formatted = formatted || null;
+ this.familyName = familyName || null;
+ this.givenName = givenName || null;
+ this.middleName = middle || null;
+ this.honorificPrefix = prefix || null;
+ this.honorificSuffix = suffix || null;
+};
+
+module.exports = ContactName;
+
+});
+
+// file: lib/common/plugin/ContactOrganization.js
+define("cordova/plugin/ContactOrganization", function(require, exports, module) {
+
+/**
+* Contact organization.
+* @constructor
+* @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard
+* @param name
+* @param dept
+* @param title
+* @param startDate
+* @param endDate
+* @param location
+* @param desc
+*/
+
+var ContactOrganization = function(pref, type, name, dept, title) {
+ this.id = null;
+ this.pref = (typeof pref != 'undefined' ? pref : false);
+ this.type = type || null;
+ this.name = name || null;
+ this.department = dept || null;
+ this.title = title || null;
+};
+
+module.exports = ContactOrganization;
+
+});
+
+// file: lib/common/plugin/Coordinates.js
+define("cordova/plugin/Coordinates", function(require, exports, module) {
+
+/**
+ * This class contains position information.
+ * @param {Object} lat
+ * @param {Object} lng
+ * @param {Object} alt
+ * @param {Object} acc
+ * @param {Object} head
+ * @param {Object} vel
+ * @param {Object} altacc
+ * @constructor
+ */
+var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
+ /**
+ * The latitude of the position.
+ */
+ this.latitude = lat;
+ /**
+ * The longitude of the position,
+ */
+ this.longitude = lng;
+ /**
+ * The accuracy of the position.
+ */
+ this.accuracy = acc;
+ /**
+ * The altitude of the position.
+ */
+ this.altitude = (alt !== undefined ? alt : null);
+ /**
+ * The direction the device is moving at the position.
+ */
+ this.heading = (head !== undefined ? head : null);
+ /**
+ * The velocity with which the device is moving at the position.
+ */
+ this.speed = (vel !== undefined ? vel : null);
+
+ if (this.speed === 0 || this.speed === null) {
+ this.heading = NaN;
+ }
+
+ /**
+ * The altitude accuracy of the position.
+ */
+ this.altitudeAccuracy = (altacc !== undefined) ? altacc : null;
+};
+
+module.exports = Coordinates;
+
+});
+
+// file: lib/common/plugin/DirectoryEntry.js
+define("cordova/plugin/DirectoryEntry", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ utils = require('cordova/utils'),
+ exec = require('cordova/exec'),
+ Entry = require('cordova/plugin/Entry'),
+ FileError = require('cordova/plugin/FileError'),
+ DirectoryReader = require('cordova/plugin/DirectoryReader');
+
+/**
+ * An interface representing a directory on the file system.
+ *
+ * {boolean} isFile always false (readonly)
+ * {boolean} isDirectory always true (readonly)
+ * {DOMString} name of the directory, excluding the path leading to it (readonly)
+ * {DOMString} fullPath the absolute full path to the directory (readonly)
+ * TODO: implement this!!! {FileSystem} filesystem on which the directory resides (readonly)
+ */
+var DirectoryEntry = function(name, fullPath) {
+ DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath);
+};
+
+utils.extend(DirectoryEntry, Entry);
+
+/**
+ * Creates a new DirectoryReader to read entries from this directory
+ */
+DirectoryEntry.prototype.createReader = function() {
+ return new DirectoryReader(this.fullPath);
+};
+
+/**
+ * Creates or looks up a directory
+ *
+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
+ * @param {Flags} options to create or exclusively create the directory
+ * @param {Function} successCallback is called with the new entry
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
+ var win = successCallback && function(result) {
+ var entry = new DirectoryEntry(result.name, result.fullPath);
+ successCallback(entry);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getDirectory", [this.fullPath, path, options]);
+};
+
+/**
+ * Deletes a directory and all of it's contents
+ *
+ * @param {Function} successCallback is called with no parameters
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(successCallback, fail, "File", "removeRecursively", [this.fullPath]);
+};
+
+/**
+ * Creates or looks up a file
+ *
+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
+ * @param {Flags} options to create or exclusively create the file
+ * @param {Function} successCallback is called with the new entry
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
+ var win = successCallback && function(result) {
+ var FileEntry = require('cordova/plugin/FileEntry');
+ var entry = new FileEntry(result.name, result.fullPath);
+ successCallback(entry);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getFile", [this.fullPath, path, options]);
+};
+
+module.exports = DirectoryEntry;
+
+});
+
+// file: lib/common/plugin/DirectoryReader.js
+define("cordova/plugin/DirectoryReader", function(require, exports, module) {
+
+var exec = require('cordova/exec'),
+ FileError = require('cordova/plugin/FileError') ;
+
+/**
+ * An interface that lists the files and directories in a directory.
+ */
+function DirectoryReader(path) {
+ this.path = path || null;
+}
+
+/**
+ * Returns a list of entries from a directory.
+ *
+ * @param {Function} successCallback is called with a list of entries
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
+ var win = typeof successCallback !== 'function' ? null : function(result) {
+ var retVal = [];
+ for (var i=0; i<result.length; i++) {
+ var entry = null;
+ if (result[i].isDirectory) {
+ entry = new (require('cordova/plugin/DirectoryEntry'))();
+ }
+ else if (result[i].isFile) {
+ entry = new (require('cordova/plugin/FileEntry'))();
+ }
+ entry.isDirectory = result[i].isDirectory;
+ entry.isFile = result[i].isFile;
+ entry.name = result[i].name;
+ entry.fullPath = result[i].fullPath;
+ retVal.push(entry);
+ }
+ successCallback(retVal);
+ };
+ var fail = typeof errorCallback !== 'function' ? null : function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "readEntries", [this.path]);
+};
+
+module.exports = DirectoryReader;
+
+});
+
+// file: lib/common/plugin/Entry.js
+define("cordova/plugin/Entry", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ FileError = require('cordova/plugin/FileError'),
+ Metadata = require('cordova/plugin/Metadata');
+
+/**
+ * Represents a file or directory on the local file system.
+ *
+ * @param isFile
+ * {boolean} true if Entry is a file (readonly)
+ * @param isDirectory
+ * {boolean} true if Entry is a directory (readonly)
+ * @param name
+ * {DOMString} name of the file or directory, excluding the path
+ * leading to it (readonly)
+ * @param fullPath
+ * {DOMString} the absolute full path to the file or directory
+ * (readonly)
+ */
+function Entry(isFile, isDirectory, name, fullPath, fileSystem) {
+ this.isFile = !!isFile;
+ this.isDirectory = !!isDirectory;
+ this.name = name || '';
+ this.fullPath = fullPath || '';
+ this.filesystem = fileSystem || null;
+}
+
+/**
+ * Look up the metadata of the entry.
+ *
+ * @param successCallback
+ * {Function} is called with a Metadata object
+ * @param errorCallback
+ * {Function} is called with a FileError
+ */
+Entry.prototype.getMetadata = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.getMetadata', arguments);
+ var success = successCallback && function(lastModified) {
+ var metadata = new Metadata(lastModified);
+ successCallback(metadata);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+
+ exec(success, fail, "File", "getMetadata", [this.fullPath]);
+};
+
+/**
+ * Set the metadata of the entry.
+ *
+ * @param successCallback
+ * {Function} is called with a Metadata object
+ * @param errorCallback
+ * {Function} is called with a FileError
+ * @param metadataObject
+ * {Object} keys and values to set
+ */
+Entry.prototype.setMetadata = function(successCallback, errorCallback, metadataObject) {
+ argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments);
+ exec(successCallback, errorCallback, "File", "setMetadata", [this.fullPath, metadataObject]);
+};
+
+/**
+ * Move a file or directory to a new location.
+ *
+ * @param parent
+ * {DirectoryEntry} the directory to which to move this entry
+ * @param newName
+ * {DOMString} new name of the entry, defaults to the current name
+ * @param successCallback
+ * {Function} called with the new DirectoryEntry object
+ * @param errorCallback
+ * {Function} called with a FileError
+ */
+Entry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
+ argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments);
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ // source path
+ var srcPath = this.fullPath,
+ // entry name
+ name = newName || this.name,
+ success = function(entry) {
+ if (entry) {
+ if (successCallback) {
+ // create appropriate Entry object
+ var result = (entry.isDirectory) ? new (require('cordova/plugin/DirectoryEntry'))(entry.name, entry.fullPath) : new (require('cordova/plugin/FileEntry'))(entry.name, entry.fullPath);
+ successCallback(result);
+ }
+ }
+ else {
+ // no Entry object returned
+ fail && fail(FileError.NOT_FOUND_ERR);
+ }
+ };
+
+ // copy
+ exec(success, fail, "File", "moveTo", [srcPath, parent.fullPath, name]);
+};
+
+/**
+ * Copy a directory to a different location.
+ *
+ * @param parent
+ * {DirectoryEntry} the directory to which to copy the entry
+ * @param newName
+ * {DOMString} new name of the entry, defaults to the current name
+ * @param successCallback
+ * {Function} called with the new Entry object
+ * @param errorCallback
+ * {Function} called with a FileError
+ */
+Entry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
+ argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments);
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+
+ // source path
+ var srcPath = this.fullPath,
+ // entry name
+ name = newName || this.name,
+ // success callback
+ success = function(entry) {
+ if (entry) {
+ if (successCallback) {
+ // create appropriate Entry object
+ var result = (entry.isDirectory) ? new (require('cordova/plugin/DirectoryEntry'))(entry.name, entry.fullPath) : new (require('cordova/plugin/FileEntry'))(entry.name, entry.fullPath);
+ successCallback(result);
+ }
+ }
+ else {
+ // no Entry object returned
+ fail && fail(FileError.NOT_FOUND_ERR);
+ }
+ };
+
+ // copy
+ exec(success, fail, "File", "copyTo", [srcPath, parent.fullPath, name]);
+};
+
+/**
+ * Return a URL that can be used to identify this entry.
+ */
+Entry.prototype.toURL = function() {
+ // fullPath attribute contains the full URL
+ return this.fullPath;
+};
+
+/**
+ * Returns a URI that can be used to identify this entry.
+ *
+ * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
+ * @return uri
+ */
+Entry.prototype.toURI = function(mimeType) {
+ console.log("DEPRECATED: Update your code to use 'toURL'");
+ // fullPath attribute contains the full URI
+ return this.toURL();
+};
+
+/**
+ * Remove a file or directory. It is an error to attempt to delete a
+ * directory that is not empty. It is an error to attempt to delete a
+ * root directory of a file system.
+ *
+ * @param successCallback {Function} called with no parameters
+ * @param errorCallback {Function} called with a FileError
+ */
+Entry.prototype.remove = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.remove', arguments);
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(successCallback, fail, "File", "remove", [this.fullPath]);
+};
+
+/**
+ * Look up the parent DirectoryEntry of this entry.
+ *
+ * @param successCallback {Function} called with the parent DirectoryEntry object
+ * @param errorCallback {Function} called with a FileError
+ */
+Entry.prototype.getParent = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.getParent', arguments);
+ var win = successCallback && function(result) {
+ var DirectoryEntry = require('cordova/plugin/DirectoryEntry');
+ var entry = new DirectoryEntry(result.name, result.fullPath);
+ successCallback(entry);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getParent", [this.fullPath]);
+};
+
+module.exports = Entry;
+
+});
+
+// file: lib/common/plugin/File.js
+define("cordova/plugin/File", function(require, exports, module) {
+
+/**
+ * Constructor.
+ * name {DOMString} name of the file, without path information
+ * fullPath {DOMString} the full path of the file, including the name
+ * type {DOMString} mime type
+ * lastModifiedDate {Date} last modified date
+ * size {Number} size of the file in bytes
+ */
+
+var File = function(name, fullPath, type, lastModifiedDate, size){
+ this.name = name || '';
+ this.fullPath = fullPath || null;
+ this.type = type || null;
+ this.lastModifiedDate = lastModifiedDate || null;
+ this.size = size || 0;
+
+ // These store the absolute start and end for slicing the file.
+ this.start = 0;
+ this.end = this.size;
+};
+
+/**
+ * Returns a "slice" of the file. Since Cordova Files don't contain the actual
+ * content, this really returns a File with adjusted start and end.
+ * Slices of slices are supported.
+ * start {Number} The index at which to start the slice (inclusive).
+ * end {Number} The index at which to end the slice (exclusive).
+ */
+File.prototype.slice = function(start, end) {
+ var size = this.end - this.start;
+ var newStart = 0;
+ var newEnd = size;
+ if (arguments.length) {
+ if (start < 0) {
+ newStart = Math.max(size + start, 0);
+ } else {
+ newStart = Math.min(size, start);
+ }
+ }
+
+ if (arguments.length >= 2) {
+ if (end < 0) {
+ newEnd = Math.max(size + end, 0);
+ } else {
+ newEnd = Math.min(end, size);
+ }
+ }
+
+ var newFile = new File(this.name, this.fullPath, this.type, this.lastModifiedData, this.size);
+ newFile.start = this.start + newStart;
+ newFile.end = this.start + newEnd;
+ return newFile;
+};
+
+
+module.exports = File;
+
+});
+
+// file: lib/common/plugin/FileEntry.js
+define("cordova/plugin/FileEntry", function(require, exports, module) {
+
+var utils = require('cordova/utils'),
+ exec = require('cordova/exec'),
+ Entry = require('cordova/plugin/Entry'),
+ FileWriter = require('cordova/plugin/FileWriter'),
+ File = require('cordova/plugin/File'),
+ FileError = require('cordova/plugin/FileError');
+
+/**
+ * An interface representing a file on the file system.
+ *
+ * {boolean} isFile always true (readonly)
+ * {boolean} isDirectory always false (readonly)
+ * {DOMString} name of the file, excluding the path leading to it (readonly)
+ * {DOMString} fullPath the absolute full path to the file (readonly)
+ * {FileSystem} filesystem on which the file resides (readonly)
+ */
+var FileEntry = function(name, fullPath) {
+ FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath]);
+};
+
+utils.extend(FileEntry, Entry);
+
+/**
+ * Creates a new FileWriter associated with the file that this FileEntry represents.
+ *
+ * @param {Function} successCallback is called with the new FileWriter
+ * @param {Function} errorCallback is called with a FileError
+ */
+FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
+ this.file(function(filePointer) {
+ var writer = new FileWriter(filePointer);
+
+ if (writer.fileName === null || writer.fileName === "") {
+ errorCallback && errorCallback(new FileError(FileError.INVALID_STATE_ERR));
+ } else {
+ successCallback && successCallback(writer);
+ }
+ }, errorCallback);
+};
+
+/**
+ * Returns a File that represents the current state of the file that this FileEntry represents.
+ *
+ * @param {Function} successCallback is called with the new File object
+ * @param {Function} errorCallback is called with a FileError
+ */
+FileEntry.prototype.file = function(successCallback, errorCallback) {
+ var win = successCallback && function(f) {
+ var file = new File(f.name, f.fullPath, f.type, f.lastModifiedDate, f.size);
+ successCallback(file);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getFileMetadata", [this.fullPath]);
+};
+
+
+module.exports = FileEntry;
+
+});
+
+// file: lib/common/plugin/FileError.js
+define("cordova/plugin/FileError", function(require, exports, module) {
+
+/**
+ * FileError
+ */
+function FileError(error) {
+ this.code = error || null;
+}
+
+// File error codes
+// Found in DOMException
+FileError.NOT_FOUND_ERR = 1;
+FileError.SECURITY_ERR = 2;
+FileError.ABORT_ERR = 3;
+
+// Added by File API specification
+FileError.NOT_READABLE_ERR = 4;
+FileError.ENCODING_ERR = 5;
+FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
+FileError.INVALID_STATE_ERR = 7;
+FileError.SYNTAX_ERR = 8;
+FileError.INVALID_MODIFICATION_ERR = 9;
+FileError.QUOTA_EXCEEDED_ERR = 10;
+FileError.TYPE_MISMATCH_ERR = 11;
+FileError.PATH_EXISTS_ERR = 12;
+
+module.exports = FileError;
+
+});
+
+// file: lib/common/plugin/FileReader.js
+define("cordova/plugin/FileReader", function(require, exports, module) {
+
+var exec = require('cordova/exec'),
+ modulemapper = require('cordova/modulemapper'),
+ utils = require('cordova/utils'),
+ File = require('cordova/plugin/File'),
+ FileError = require('cordova/plugin/FileError'),
+ ProgressEvent = require('cordova/plugin/ProgressEvent'),
+ origFileReader = modulemapper.getOriginalSymbol(this, 'FileReader');
+
+/**
+ * This class reads the mobile device file system.
+ *
+ * For Android:
+ * The root directory is the root of the file system.
+ * To read from the SD card, the file name is "sdcard/my_file.txt"
+ * @constructor
+ */
+var FileReader = function() {
+ this._readyState = 0;
+ this._error = null;
+ this._result = null;
+ this._fileName = '';
+ this._realReader = origFileReader ? new origFileReader() : {};
+};
+
+// States
+FileReader.EMPTY = 0;
+FileReader.LOADING = 1;
+FileReader.DONE = 2;
+
+utils.defineGetter(FileReader.prototype, 'readyState', function() {
+ return this._fileName ? this._readyState : this._realReader.readyState;
+});
+
+utils.defineGetter(FileReader.prototype, 'error', function() {
+ return this._fileName ? this._error: this._realReader.error;
+});
+
+utils.defineGetter(FileReader.prototype, 'result', function() {
+ return this._fileName ? this._result: this._realReader.result;
+});
+
+function defineEvent(eventName) {
+ utils.defineGetterSetter(FileReader.prototype, eventName, function() {
+ return this._realReader[eventName] || null;
+ }, function(value) {
+ this._realReader[eventName] = value;
+ });
+}
+defineEvent('onloadstart'); // When the read starts.
+defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total)
+defineEvent('onload'); // When the read has successfully completed.
+defineEvent('onerror'); // When the read has failed (see errors).
+defineEvent('onloadend'); // When the request has completed (either in success or failure).
+defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method.
+
+function initRead(reader, file) {
+ // Already loading something
+ if (reader.readyState == FileReader.LOADING) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ reader._result = null;
+ reader._error = null;
+ reader._readyState = FileReader.LOADING;
+
+ if (typeof file == 'string') {
+ // Deprecated in Cordova 2.4.
+ console.warn('Using a string argument with FileReader.readAs functions is deprecated.');
+ reader._fileName = file;
+ } else if (typeof file.fullPath == 'string') {
+ reader._fileName = file.fullPath;
+ } else {
+ reader._fileName = '';
+ return true;
+ }
+
+ reader.onloadstart && reader.onloadstart(new ProgressEvent("loadstart", {target:reader}));
+}
+
+/**
+ * Abort reading file.
+ */
+FileReader.prototype.abort = function() {
+ if (origFileReader && !this._fileName) {
+ return this._realReader.abort();
+ }
+ this._result = null;
+
+ if (this._readyState == FileReader.DONE || this._readyState == FileReader.EMPTY) {
+ return;
+ }
+
+ this._readyState = FileReader.DONE;
+
+ // If abort callback
+ if (typeof this.onabort === 'function') {
+ this.onabort(new ProgressEvent('abort', {target:this}));
+ }
+ // If load end callback
+ if (typeof this.onloadend === 'function') {
+ this.onloadend(new ProgressEvent('loadend', {target:this}));
+ }
+};
+
+/**
+ * Read text file.
+ *
+ * @param file {File} File object containing file properties
+ * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)
+ */
+FileReader.prototype.readAsText = function(file, encoding) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsText(file, encoding);
+ }
+
+ // Default encoding is UTF-8
+ var enc = encoding ? encoding : "UTF-8";
+ var me = this;
+ var execArgs = [this._fileName, enc, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // Save result
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ // null result
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsText", execArgs);
+};
+
+
+/**
+ * Read file and return data as a base64 encoded data url.
+ * A data url is of the form:
+ * data:[<mediatype>][;base64],<data>
+ *
+ * @param file {File} File object containing file properties
+ */
+FileReader.prototype.readAsDataURL = function(file) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsDataURL(file);
+ }
+
+ var me = this;
+ var execArgs = [this._fileName, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ // Save result
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsDataURL", execArgs);
+};
+
+/**
+ * Read file and return data as a binary data.
+ *
+ * @param file {File} File object containing file properties
+ */
+FileReader.prototype.readAsBinaryString = function(file) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsBinaryString(file);
+ }
+
+ var me = this;
+ var execArgs = [this._fileName, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsBinaryString", execArgs);
+};
+
+/**
+ * Read file and return data as a binary data.
+ *
+ * @param file {File} File object containing file properties
+ */
+FileReader.prototype.readAsArrayBuffer = function(file) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsArrayBuffer(file);
+ }
+
+ var me = this;
+ var execArgs = [this._fileName, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsArrayBuffer", execArgs);
+};
+
+module.exports = FileReader;
+
+});
+
+// file: lib/common/plugin/FileSystem.js
+define("cordova/plugin/FileSystem", function(require, exports, module) {
+
+var DirectoryEntry = require('cordova/plugin/DirectoryEntry');
+
+/**
+ * An interface representing a file system
+ *
+ * @constructor
+ * {DOMString} name the unique name of the file system (readonly)
+ * {DirectoryEntry} root directory of the file system (readonly)
+ */
+var FileSystem = function(name, root) {
+ this.name = name || null;
+ if (root) {
+ this.root = new DirectoryEntry(root.name, root.fullPath);
+ }
+};
+
+module.exports = FileSystem;
+
+});
+
+// file: lib/common/plugin/FileTransfer.js
+define("cordova/plugin/FileTransfer", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ FileTransferError = require('cordova/plugin/FileTransferError'),
+ ProgressEvent = require('cordova/plugin/ProgressEvent');
+
+function newProgressEvent(result) {
+ var pe = new ProgressEvent();
+ pe.lengthComputable = result.lengthComputable;
+ pe.loaded = result.loaded;
+ pe.total = result.total;
+ return pe;
+}
+
+funct
<TRUNCATED>
[06/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_qt.cpp
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_qt.cpp b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_qt.cpp
new file mode 100644
index 0000000..7c70b48
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_qt.cpp
@@ -0,0 +1,1611 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <json/value.h>
+#include <json/writer.h>
+#include <stdio.h>
+#include <webworks_utils.hpp>
+#include <bb/cascades/pickers/ContactPicker>
+#include <bb/cascades/pickers/ContactSelectionMode>
+#include <QSet>
+#include <QMap>
+#include <QtAlgorithms>
+#include <string>
+#include <sstream>
+#include <map>
+#include <algorithm>
+#include "pim_contacts_qt.hpp"
+
+namespace webworks {
+
+StringToKindMap PimContactsQt::_attributeKindMap;
+StringToSubKindMap PimContactsQt::_attributeSubKindMap;
+KindToStringMap PimContactsQt::_kindAttributeMap;
+SubKindToStringMap PimContactsQt::_subKindAttributeMap;
+QList<bbpim::SortSpecifier> PimContactsQt::_sortSpecs;
+std::map<bbpim::ContactId, bbpim::Contact> PimContactsQt::_contactSearchMap;
+ContactAccount& PimContactsQt::_contactAccount = ContactAccount::GetAccountInstance();
+
+PimContactsQt::PimContactsQt()
+{
+ static bool mapInit = false;
+
+ if (!mapInit) {
+ createAttributeKindMap();
+ createAttributeSubKindMap();
+ createKindAttributeMap();
+ createSubKindAttributeMap();
+ mapInit = true;
+ }
+}
+
+PimContactsQt::~PimContactsQt()
+{
+}
+
+/****************************************************************
+ * Public Functions
+ ****************************************************************/
+
+Json::Value PimContactsQt::Find(const Json::Value& args)
+{
+ Json::Value returnObj;
+
+ if (!args.isMember("fields") || args["fields"].empty() || !args.isMember("options") || args["options"].isNull()) {
+ returnObj["_success"] = false;
+ returnObj["code"] = INVALID_ARGUMENT_ERROR;
+ return returnObj;
+ }
+
+ QSet<bbpim::ContactId> results;
+ int limit = -1;
+ bool favorite = false;
+ Json::Value includeAccounts = args["options"].get("includeAccounts", Json::nullValue);
+ Json::Value excludeAccounts = args["options"].get("excludeAccounts", Json::nullValue);
+
+ if (args["options"].isMember("favorite") && args["options"]["favorite"].isBool()) {
+ favorite = args["options"]["favorite"].asBool();
+ }
+
+ if (args["options"].isMember("limit") && args["options"]["limit"].isInt()) {
+ limit = args["options"]["limit"].asInt();
+ }
+
+ if (args["options"].isMember("filter") && !args["options"]["filter"].empty()) {
+ results = getPartialSearchResults(args["options"]["filter"], args["fields"], favorite, includeAccounts, excludeAccounts);
+
+ getSortSpecs(args["options"]["sort"]);
+
+ returnObj["_success"] = true;
+ returnObj["contacts"] = assembleSearchResults(results, args["fields"], limit);
+ } else {
+ // if no filters specified, use list filters to get all contacts
+ bbpim::ContactService service;
+ bbpim::ContactListFilters listFilters;
+ QList<bbpim::Contact> results;
+ Json::Value contacts;
+
+ getSortSpecs(args["options"]["sort"]);
+ if (!_sortSpecs.empty()) {
+ listFilters.setSortBy(_sortSpecs);
+ }
+
+ listFilters.setIncludeAttributes(getIncludeAttributesList(args["fields"], &listFilters));
+
+ if (favorite) {
+ listFilters.setIsFavourite(favorite);
+ }
+
+ if (limit != -1) {
+ listFilters.setLimit(limit);
+ }
+
+ getAccountFilters(NULL, &listFilters, includeAccounts, excludeAccounts);
+
+ results = service.contacts(listFilters);
+ for (QList<bbpim::Contact>::const_iterator i = results.constBegin(); i != results.constEnd(); i++) {
+ Json::Value contactItem = populateContact(*i, args["fields"]);
+ contacts.append(contactItem);
+ }
+
+ returnObj["_success"] = true;
+ returnObj["contacts"] = contacts;
+ }
+
+ return returnObj;
+}
+
+Json::Value PimContactsQt::Save(const Json::Value& attributeObj)
+{
+ if (!attributeObj.isMember("id") || attributeObj["id"].isNull()) {
+ return CreateContact(attributeObj);
+ } else if (attributeObj.isMember("id") && attributeObj["id"].isInt()) {
+ int contactId = attributeObj["id"].asInt();
+ bbpim::ContactService service;
+
+ if (contactId > 0) {
+ bbpim::Contact contact = service.contactDetails(contactId);
+
+ if (contact.isValid()) {
+ return EditContact(contact, attributeObj);
+ }
+ } else {
+ bbpim::Contact contact = service.contactDetails(contactId * -1);
+
+ if (contact.isValid()) {
+ return CloneContact(contact, attributeObj);
+ }
+ }
+ }
+
+ Json::Value returnObj;
+ returnObj["_success"] = false;
+ returnObj["code"] = INVALID_ARGUMENT_ERROR;
+ return returnObj;
+}
+
+Json::Value PimContactsQt::CreateContact(const Json::Value& attributeObj)
+{
+ const Json::Value::Members attributeKeys = attributeObj.getMemberNames();
+ Json::Value contactFields;
+
+ bbpim::Contact newContact;
+ bbpim::ContactBuilder contactBuilder(newContact.edit());
+
+ for (unsigned int i = 0; i < attributeKeys.size(); i++) {
+ const std::string key = attributeKeys[i];
+ contactFields.append(Json::Value(key));
+ addAttributeKind(contactBuilder, attributeObj[key], key);
+ }
+
+ bbpim::ContactService service;
+ newContact = service.createContact(newContact, attributeObj["isWork"].asBool(), true);
+
+ Json::Value returnObj;
+
+ if (newContact.isValid()) {
+ returnObj = populateContact(newContact, contactFields);
+ returnObj["_success"] = true;
+ } else {
+ returnObj["_success"] = false;
+ returnObj["code"] = UNKNOWN_ERROR;
+ }
+
+ return returnObj;
+}
+
+Json::Value PimContactsQt::DeleteContact(const Json::Value& contactObj)
+{
+ Json::Value returnObj;
+
+ if (contactObj.isMember("contactId") && contactObj["contactId"].isInt()) {
+ bbpim::ContactId contactId = contactObj["contactId"].asInt();
+
+ bbpim::ContactService service;
+ bbpim::Contact contact = service.contactDetails(contactId);
+
+ if (contact.isValid()) {
+ service.deleteContact(contactId);
+ returnObj["_success"] = true;
+ return returnObj;
+ }
+ }
+
+ returnObj["_success"] = false;
+ returnObj["code"] = INVALID_ARGUMENT_ERROR;
+ return returnObj;
+}
+
+Json::Value PimContactsQt::EditContact(bbpim::Contact& contact, const Json::Value& attributeObj)
+{
+ bbpim::ContactBuilder contactBuilder(contact.edit());
+ const Json::Value::Members attributeKeys = attributeObj.getMemberNames();
+ Json::Value contactFields;
+
+ for (unsigned int i = 0; i < attributeKeys.size(); i++) {
+ const std::string key = attributeKeys[i];
+ contactFields.append(Json::Value(key));
+ syncAttributeKind(contact, attributeObj[key], key);
+ }
+
+ bbpim::ContactService service;
+ contact = service.updateContact(contact);
+
+ Json::Value returnObj;
+
+ if (contact.isValid()) {
+ returnObj = populateContact(contact, contactFields);
+ returnObj["_success"] = true;
+ } else {
+ returnObj["_success"] = false;
+ returnObj["code"] = UNKNOWN_ERROR;
+ }
+
+ return returnObj;
+}
+
+Json::Value PimContactsQt::CloneContact(bbpim::Contact& contact, const Json::Value& attributeObj)
+{
+ bbpim::ContactService service;
+ bbpim::Contact newContact;
+ bbpim::ContactBuilder contactBuilder(newContact.edit());
+ contactBuilder = contactBuilder.addFromContact(contact);
+ contactBuilder = contactBuilder.setFavorite(contact.isFavourite());
+
+ const Json::Value::Members attributeKeys = attributeObj.getMemberNames();
+ Json::Value contactFields;
+
+ for (unsigned int i = 0; i < attributeKeys.size(); i++) {
+ const std::string key = attributeKeys[i];
+ contactFields.append(Json::Value(key));
+ syncAttributeKind(newContact, attributeObj[key], key);
+ }
+
+ newContact = service.createContact(newContact, attributeObj["isWork"].asBool(), true);
+
+ Json::Value returnObj;
+
+ if (newContact.isValid()) {
+ returnObj = populateContact(newContact, contactFields);
+ returnObj["_success"] = true;
+ } else {
+ returnObj["_success"] = false;
+ returnObj["code"] = UNKNOWN_ERROR;
+ }
+
+ return returnObj;
+}
+
+Json::Value PimContactsQt::GetContact(const Json::Value& args)
+{
+ Json::Value returnObj;
+ Json::Value fields;
+ bbpim::ContactService contactService;
+ StringToKindMap::const_iterator it;
+ int loop = 0;
+
+ for (it = _attributeKindMap.begin(); it != _attributeKindMap.end(); ++it) {
+ fields[loop] = it->first;
+ loop++;
+ }
+
+ if (args.isMember("contactId")) {
+ bbpim::Contact contact;
+ bbpim::ContactId contactId = Utils::strToInt(args["contactId"].asString());
+
+ if (contactId == -1) {
+ returnObj["_success"] = false;
+ returnObj["code"] = INVALID_ARGUMENT_ERROR;
+ } else {
+ contact = contactService.contactDetails(contactId);
+ returnObj["_success"] = true;
+ if (contact.isValid()) {
+ returnObj["contact"] = populateContact(contact, fields);
+ }
+ }
+ } else {
+ returnObj["_success"] = false;
+ returnObj["code"] = INVALID_ARGUMENT_ERROR;
+ }
+
+ if (returnObj.empty()) {
+ returnObj["_success"] = false;
+ returnObj["code"] = UNKNOWN_ERROR;
+ }
+
+ return returnObj;
+}
+
+Json::Value PimContactsQt::InvokePicker(const Json::Value& args)
+{
+ bb::cascades::pickers::ContactPicker picker;
+ bb::cascades::pickers::ContactSelectionMode::Type mode;
+ QSet<bbpim::AttributeKind::Type> filters;
+ Json::Value result;
+
+ if (args.isMember("mode")) {
+ switch (args["mode"].asInt()) {
+ case bb::cascades::pickers::ContactSelectionMode::Single:
+ mode = bb::cascades::pickers::ContactSelectionMode::Single;
+ break;
+ case bb::cascades::pickers::ContactSelectionMode::Multiple:
+ mode = bb::cascades::pickers::ContactSelectionMode::Multiple;
+ break;
+ case bb::cascades::pickers::ContactSelectionMode::Attribute:
+ mode = bb::cascades::pickers::ContactSelectionMode::Attribute;
+ break;
+ default:
+ result["_success"] = false;
+ result["code"] = INVALID_ARGUMENT_ERROR;
+ return result;
+ }
+
+ picker.setMode(mode);
+
+ if (args.isMember("fields") && !args["fields"].empty()) {
+ std::string fieldName;
+ StringToKindMap::iterator found;
+
+ if (_attributeKindMap.empty()) {
+ createAttributeKindMap();
+ }
+
+ for (unsigned int i = 0; i < args["fields"].size(); i++) {
+ fieldName = args["fields"][i].asString();
+
+ if ((found = _attributeKindMap.find(fieldName)) != _attributeKindMap.end()) {
+ filters << found->second;
+ }
+ }
+
+ picker.setKindFilters(filters);
+ }
+
+ // cannot open picker if mode = attribute unless filters are specified
+ if (mode == bb::cascades::pickers::ContactSelectionMode::Attribute && filters.empty()) {
+ result["_success"] = false;
+ result["code"] = INVALID_ARGUMENT_ERROR;
+ return result;
+ }
+
+ if (args.isMember("title") && args["title"].isString()) {
+ picker.setTitle(QString(args["title"].asCString()));
+ }
+
+ if (args.isMember("confirmButtonLabel") && args["confirmButtonLabel"].isString()) {
+ picker.setConfirmButtonLabel(QString(args["confirmButtonLabel"].asCString()));
+ }
+
+ picker.open();
+
+ result["_success"] = true;
+ return result;
+ }
+
+ result["_success"] = false;
+ result["code"] = INVALID_ARGUMENT_ERROR;
+ return result;
+}
+
+Json::Value PimContactsQt::GetContactAccounts()
+{
+ Json::Value retVal;
+
+ retVal["accounts"] = Json::Value();
+ QList<bb::pim::account::Account> accounts = _contactAccount.GetContactAccounts();
+ for (int i = 0; i < accounts.size(); ++i) {
+ retVal["accounts"].append(ContactAccount::Account2Json(accounts[i]));
+ }
+ retVal["_success"] = true;
+ return retVal;
+}
+
+/****************************************************************
+ * Helper functions for Find
+ ****************************************************************/
+
+QList<bbpim::SearchField::Type> PimContactsQt::getSearchFields(const Json::Value& searchFieldsJson)
+{
+ QList<bbpim::SearchField::Type> searchFields;
+
+ switch (searchFieldsJson["fieldName"].asInt()) {
+ case bbpim::SearchField::FirstName:
+ searchFields.append(bbpim::SearchField::FirstName);
+ break;
+ case bbpim::SearchField::LastName:
+ searchFields.append(bbpim::SearchField::LastName);
+ break;
+ case bbpim::SearchField::CompanyName:
+ searchFields.append(bbpim::SearchField::CompanyName);
+ break;
+ case bbpim::SearchField::Phone:
+ searchFields.append(bbpim::SearchField::Phone);
+ break;
+ case bbpim::SearchField::Email:
+ searchFields.append(bbpim::SearchField::Email);
+ break;
+ case bbpim::SearchField::BBMPin:
+ searchFields.append(bbpim::SearchField::BBMPin);
+ break;
+ case bbpim::SearchField::LinkedIn:
+ searchFields.append(bbpim::SearchField::LinkedIn);
+ break;
+ case bbpim::SearchField::Twitter:
+ searchFields.append(bbpim::SearchField::Twitter);
+ break;
+ case bbpim::SearchField::VideoChat:
+ searchFields.append(bbpim::SearchField::VideoChat);
+ break;
+ }
+
+ return searchFields;
+}
+
+void PimContactsQt::getSortSpecs(const Json::Value& sort)
+{
+ _sortSpecs.clear();
+
+ if (sort.isArray()) {
+ for (unsigned int j = 0; j < sort.size(); j++) {
+ bbpim::SortOrder::Type order;
+ bbpim::SortColumn::Type sortField = bbpim::SortColumn::LastName;
+
+ if (sort[j]["desc"].asBool()) {
+ order = bbpim::SortOrder::Descending;
+ } else {
+ order = bbpim::SortOrder::Ascending;
+ }
+
+ switch (sort[j]["fieldName"].asInt()) {
+ case bbpim::SortColumn::FirstName:
+ sortField = bbpim::SortColumn::FirstName;
+ break;
+ case bbpim::SortColumn::LastName:
+ sortField = bbpim::SortColumn::LastName;
+ break;
+ case bbpim::SortColumn::CompanyName:
+ sortField = bbpim::SortColumn::CompanyName;
+ break;
+ }
+
+ _sortSpecs.append(bbpim::SortSpecifier(sortField, order));
+ }
+ }
+}
+
+QSet<bbpim::ContactId> PimContactsQt::getPartialSearchResults(const Json::Value& filter, const Json::Value& contactFields, const bool favorite, const Json::Value& includeAccounts, const Json::Value& excludeAccounts)
+{
+ QSet<bbpim::ContactId> results;
+
+ _contactSearchMap.clear();
+
+ if (!filter.empty()) {
+ for (unsigned int j = 0; j < filter.size(); j++) {
+ QSet<bbpim::ContactId> currentResults = singleFieldSearch(filter[j], contactFields, favorite, includeAccounts, excludeAccounts);
+
+ if (currentResults.empty()) {
+ // no need to continue, can return right away
+ results = currentResults;
+ break;
+ } else {
+ if (j == 0) {
+ results = currentResults;
+ } else {
+ results.intersect(currentResults);
+ }
+ }
+ }
+ }
+
+ return results;
+}
+
+void PimContactsQt::getAccountFilters(bbpim::ContactSearchFilters* searchFilter, bbpim::ContactListFilters* listFilter, const Json::Value& includeAccounts, const Json::Value& excludeAccounts)
+{
+ if (!includeAccounts.empty() && includeAccounts.isArray()) {
+ QList<bbpim::AccountId> accountIds;
+
+ for (unsigned int i = 0; i < includeAccounts.size(); i++) {
+ accountIds << Utils::strToInt(includeAccounts[i].asString());
+ }
+
+ if (searchFilter != NULL) {
+ searchFilter->setHasAccounts(accountIds);
+ }
+
+ if (listFilter != NULL) {
+ listFilter->setHasAccounts(accountIds);
+ }
+ }
+
+ if (!excludeAccounts.empty() && excludeAccounts.isArray()) {
+ QList<bbpim::AccountId> accountIds;
+
+ for (unsigned int i = 0; i < excludeAccounts.size(); i++) {
+ accountIds << Utils::strToInt(excludeAccounts[i].asString());
+ }
+
+ if (searchFilter != NULL) {
+ searchFilter->setExcludeAccounts(accountIds);
+ }
+
+ if (listFilter != NULL) {
+ listFilter->setExcludeAccounts(accountIds);
+ }
+ }
+}
+
+QList<bbpim::AttributeKind::Type> PimContactsQt::getIncludeAttributesList(const Json::Value& contactFields, bbpim::ContactListFilters* listFilters)
+{
+ QList<bbpim::AttributeKind::Type> includeFields;
+
+ for (unsigned int i = 0; i < contactFields.size(); i++) {
+ // favorite is always included, no need to include
+ if (contactFields[i].asString() == "favorite") {
+ continue;
+ }
+
+ StringToKindMap::const_iterator kindIter = _attributeKindMap.find(contactFields[i].asString());
+
+ if (kindIter != _attributeKindMap.end()) {
+ // multiple fields can map to the same kind, only add kind to the list if it's not already added
+ if (includeFields.count(kindIter->second) == 0) {
+ includeFields.append(kindIter->second);
+ }
+ } else if (contactFields[i].asString() == "displayName" || contactFields[i].asString() == "nickname") {
+ // special case: displayName and nickname are first-level fields under Contact but only map to AttributeSubKind
+ if (includeFields.count(bbpim::AttributeKind::Name) == 0) {
+ includeFields.append(bbpim::AttributeKind::Name);
+ }
+ } else if (contactFields[i].asString() == "addresses") {
+ if (listFilters != NULL) {
+ listFilters->setIncludePostalAddress(true);
+ }
+ } else if (contactFields[i].asString() == "photos") {
+ if (listFilters != NULL) {
+ listFilters->setIncludePhotos(true);
+ }
+ }
+ }
+
+ return includeFields;
+}
+
+QSet<bbpim::ContactId> PimContactsQt::singleFieldSearch(const Json::Value& searchFieldsJson, const Json::Value& contactFields, const bool favorite, const Json::Value& includeAccounts, const Json::Value& excludeAccounts)
+{
+ QList<bbpim::SearchField::Type> searchFields = PimContactsQt::getSearchFields(searchFieldsJson);
+ QSet<bbpim::ContactId> contactIds;
+
+ if (!searchFields.empty()) {
+ bbpim::ContactService contactService;
+ bbpim::ContactSearchFilters contactFilter;
+ QList<bbpim::Contact> results;
+
+ contactFilter.setSearchFields(searchFields);
+ contactFilter.setSearchValue(QString(searchFieldsJson["fieldValue"].asString().c_str()));
+
+ if (favorite) {
+ contactFilter.setIsFavourite(favorite);
+ }
+
+ contactFilter.setShowAttributes(true);
+ contactFilter.setIncludeAttributes(getIncludeAttributesList(contactFields));
+
+ getAccountFilters(&contactFilter, NULL, includeAccounts, excludeAccounts);
+
+ results = contactService.searchContacts(contactFilter);
+
+ for (int i = 0; i < results.size(); i++) {
+ contactIds.insert(results[i].id());
+ _contactSearchMap[results[i].id()] = results[i];
+ }
+ }
+
+ return contactIds;
+}
+
+QString PimContactsQt::getSortFieldValue(const bbpim::SortColumn::Type sort_field, const bbpim::Contact& contact)
+{
+ switch (sort_field) {
+ case bbpim::SortColumn::FirstName:
+ return contact.sortFirstName();
+ case bbpim::SortColumn::LastName:
+ return contact.sortLastName();
+ case bbpim::SortColumn::CompanyName:
+ return contact.sortCompanyName();
+ }
+
+ return QString();
+}
+
+bool PimContactsQt::lessThan(const bbpim::Contact& c1, const bbpim::Contact& c2)
+{
+ QList<bbpim::SortSpecifier>::const_iterator i = PimContactsQt::_sortSpecs.constBegin();
+ bbpim::SortSpecifier sortSpec;
+ QString val1, val2;
+
+ do {
+ sortSpec = *i;
+ val1 = PimContactsQt::getSortFieldValue(sortSpec.first, c1);
+ val2 = PimContactsQt::getSortFieldValue(sortSpec.first, c2);
+ ++i;
+ } while (val1 == val2 && i != PimContactsQt::_sortSpecs.constEnd());
+
+ if (sortSpec.second == bbpim::SortOrder::Ascending) {
+ return val1 < val2;
+ } else {
+ return !(val1 < val2);
+ }
+}
+
+Json::Value PimContactsQt::assembleSearchResults(const QSet<bbpim::ContactId>& resultIds, const Json::Value& contactFields, int limit)
+{
+ QMap<bbpim::ContactId, bbpim::Contact> completeResults;
+
+ // put complete contacts in map
+ for (QSet<bbpim::ContactId>::const_iterator i = resultIds.constBegin(); i != resultIds.constEnd(); i++) {
+ completeResults.insertMulti(*i, _contactSearchMap[*i]);
+ }
+
+ // sort results based on sort specs
+ QList<bbpim::Contact> sortedResults = completeResults.values();
+ if (!_sortSpecs.empty()) {
+ qSort(sortedResults.begin(), sortedResults.end(), lessThan);
+ }
+
+ Json::Value contactArray;
+
+ // if limit is -1, returned all available results, otherwise return based on the number passed in find options
+ if (limit == -1) {
+ limit = sortedResults.size();
+ } else {
+ limit = std::min(limit, sortedResults.size());
+ }
+
+ for (int i = 0; i < limit; i++) {
+ Json::Value contactItem = populateContact(sortedResults[i], contactFields);
+ contactArray.append(contactItem);
+ }
+
+ return contactArray;
+}
+
+std::string PimContactsQt::replaceAll(const std::string& s, const std::string& souce, const std::string& target) {
+ size_t start = 0;
+ std::string temp(s);
+ while ((start = temp.find(souce, start)) != std::string::npos) {
+ temp.replace(start, souce.length(), target);
+ start += target.length();
+ }
+ return temp;
+}
+std::string PimContactsQt::replaceString(const std::string& s) {
+ std::string temp = replaceAll(replaceAll(replaceAll(replaceAll(s), "\n", "\\\\n"), "\r", ""), "\t", "\\\\t");
+ return temp;
+}
+
+/****************************************************************
+ * Helper functions shared by Find and Save
+ ****************************************************************/
+
+Json::Value PimContactsQt::populateContact(const bbpim::Contact& contact, const Json::Value& contactFields)
+{
+ Json::Value contactItem;
+
+ for (unsigned int i = 0; i < contactFields.size(); i++) {
+ std::string field = contactFields[i].asString();
+ StringToKindMap::const_iterator kindIter = _attributeKindMap.find(field);
+
+ if (kindIter != _attributeKindMap.end()) {
+ switch (kindIter->second) {
+ case bbpim::AttributeKind::Name: {
+ contactItem[field] = Json::Value();
+ populateField(contact, kindIter->second, contactItem[field], false, false);
+ break;
+ }
+
+ case bbpim::AttributeKind::OrganizationAffiliation: {
+ contactItem[field] = Json::Value();
+ populateOrganizations(contact, contactItem[field]);
+ break;
+ }
+
+ case bbpim::AttributeKind::Date:
+ case bbpim::AttributeKind::Note:
+ case bbpim::AttributeKind::Sound: {
+ populateField(contact, kindIter->second, contactItem, false, false);
+ break;
+ }
+
+ case bbpim::AttributeKind::VideoChat: {
+ contactItem[field] = Json::Value();
+ populateField(contact, kindIter->second, contactItem[field], false, true);
+ break;
+ }
+
+ case bbpim::AttributeKind::Email:
+ case bbpim::AttributeKind::Fax:
+ case bbpim::AttributeKind::Pager:
+ case bbpim::AttributeKind::Phone:
+ case bbpim::AttributeKind::Profile:
+ case bbpim::AttributeKind::Website:
+ case bbpim::AttributeKind::InstantMessaging: {
+ contactItem[field] = Json::Value();
+ populateField(contact, kindIter->second, contactItem[field], true, false);
+ break;
+ }
+
+ // Special cases (treated differently in ContactBuilder):
+ default: {
+ if (field == "addresses") {
+ contactItem[field] = Json::Value();
+ populateAddresses(contact, contactItem[field]);
+ } else if (field == "photos") {
+ contactItem[field] = Json::Value();
+ populatePhotos(contact, contactItem[field]);
+ } else if (field == "news") {
+ contactItem[field] = Json::Value();
+ populateNews(contact, contactItem[field]);
+ } else if (field == "activities") {
+ contactItem[field] = Json::Value();
+ populateActivity(contact, contactItem[field]);
+ }
+
+ break;
+ }
+ }
+ } else {
+ if (field == "displayName" || field == "nickname") {
+ populateDisplayNameNickName(contact, contactItem, field);
+ }
+ }
+ }
+
+ contactItem["sourceAccounts"] = Json::Value();
+ // fetch sourceAccounts by sourceSourceIds
+ for (int i = 0; i < contact.sourceAccountIds().size(); ++i) {
+ bb::pim::account::AccountKey id = contact.sourceAccountIds()[i];
+ bb::pim::account::Account account = _contactAccount.GetAccount(id);
+ contactItem["sourceAccounts"].append(ContactAccount::Account2Json(account));
+ }
+
+ contactItem["id"] = Utils::intToStr(contact.id());
+ contactItem["favorite"] = Json::Value(contact.isFavourite()); // always populate favorite
+
+ return contactItem;
+}
+
+void PimContactsQt::populateField(const bbpim::Contact& contact, bbpim::AttributeKind::Type kind, Json::Value& contactItem, bool isContactField, bool isArray)
+{
+ QList<bbpim::ContactAttribute> attrs = contact.filteredAttributes(kind);
+
+ for (int i = 0; i < attrs.size(); i++) {
+ bbpim::ContactAttribute currentAttr = attrs[i];
+
+ // displayName and nickname are populated separately, do not populate within the name object
+ if (currentAttr.subKind() == bbpim::AttributeSubKind::NameDisplayName || currentAttr.subKind() == bbpim::AttributeSubKind::NameNickname) {
+ continue;
+ }
+
+ Json::Value val;
+ SubKindToStringMap::const_iterator typeIter = _subKindAttributeMap.find(currentAttr.subKind());
+
+ if (typeIter != _subKindAttributeMap.end()) {
+ if (isContactField) {
+ val["type"] = Json::Value(typeIter->second);
+
+ std::string value = currentAttr.value().toStdString();
+ value = replaceString(value);
+
+ val["value"] = Json::Value(value);
+ contactItem.append(val);
+ } else {
+ if (isArray) {
+ std::string value = currentAttr.value().toStdString();
+ value = replaceString(value);
+
+ val = Json::Value(value);
+ contactItem.append(val);
+ } else {
+ if (kind == bbpim::AttributeKind::Date) {
+ QString format = "yyyy-MM-dd";
+ contactItem[typeIter->second] = Json::Value(currentAttr.valueAsDateTime().date().toString(format).toStdString());
+ } else {
+ contactItem[typeIter->second] = Json::Value(currentAttr.value().toStdString());
+ }
+ }
+ }
+ } else if (kind == bbpim::AttributeKind::Note) {
+ std::string note = currentAttr.value().toStdString();
+ note = replaceString(note);
+ contactItem["note"] = Json::Value(note);
+ break;
+ }
+ }
+}
+
+void PimContactsQt::populateDisplayNameNickName(const bbpim::Contact& contact, Json::Value& contactItem, const std::string& field)
+{
+ QList<QList<bbpim::ContactAttribute> > nameGroups = contact.filteredAttributesByGroupKey(bbpim::AttributeKind::Name);
+ bbpim::AttributeSubKind::Type subkind = (field == "displayName" ? bbpim::AttributeSubKind::NameDisplayName : bbpim::AttributeSubKind::NameNickname);
+
+ if (!nameGroups.empty()) {
+ QList<bbpim::ContactAttribute> nameAttrs = nameGroups[0];
+
+ for (int i = 0; i < nameAttrs.size(); i++) {
+ bbpim::ContactAttribute currentAttr = nameAttrs[i];
+
+ if (currentAttr.subKind() == subkind) {
+ std::string value = currentAttr.value().toStdString();
+ value = replaceString(value);
+ contactItem[field] = Json::Value(value);
+ break;
+ }
+ }
+ }
+}
+
+void PimContactsQt::populateAddresses(const bbpim::Contact& contact, Json::Value& contactAddrs)
+{
+ bbpim::ContactService contactService;
+ bbpim::Contact fullContact = contactService.contactDetails(contact.id());
+ QList<bbpim::ContactPostalAddress> addrs = fullContact.postalAddresses();
+
+ for (int i = 0; i < addrs.size(); i++) {
+ bbpim::ContactPostalAddress currentAddr = addrs[i];
+ Json::Value addr;
+
+ SubKindToStringMap::const_iterator typeIter = _subKindAttributeMap.find(currentAddr.subKind());
+
+ if (typeIter != _subKindAttributeMap.end()) {
+ addr["type"] = Json::Value(typeIter->second);
+ }
+
+ addr["streetAddress"] = Json::Value(currentAddr.line1().toStdString());
+ addr["streetOther"] = Json::Value(currentAddr.line2().toStdString());
+ addr["country"] = Json::Value(currentAddr.country().toStdString());
+ addr["locality"] = Json::Value(currentAddr.city().toStdString());
+ addr["postalCode"] = Json::Value(currentAddr.postalCode().toStdString());
+ addr["region"] = Json::Value(currentAddr.region().toStdString());
+
+ contactAddrs.append(addr);
+ }
+}
+
+void PimContactsQt::populateOrganizations(const bbpim::Contact& contact, Json::Value& contactOrgs)
+{
+ QList<QList<bbpim::ContactAttribute> > orgAttrs = contact.filteredAttributesByGroupKey(bbpim::AttributeKind::OrganizationAffiliation);
+
+ for (int i = 0; i < orgAttrs.size(); i++) {
+ QList<bbpim::ContactAttribute> currentOrgAttrs = orgAttrs[i];
+ Json::Value org;
+
+ for (int j = 0; j < currentOrgAttrs.size(); j++) {
+ bbpim::ContactAttribute attr = currentOrgAttrs[j];
+ SubKindToStringMap::const_iterator typeIter = _subKindAttributeMap.find(attr.subKind());
+
+ if (typeIter != _subKindAttributeMap.end()) {
+ std::string value = attr.value().toStdString();
+ value = replaceString(value);
+ org[typeIter->second] = Json::Value(value);
+ }
+ }
+
+ contactOrgs.append(org);
+ }
+}
+
+void PimContactsQt::populatePhotos(const bbpim::Contact& contact, Json::Value& contactPhotos)
+{
+ bbpim::ContactService contactService;
+ bbpim::Contact fullContact = contactService.contactDetails(contact.id());
+ QList<bbpim::ContactPhoto> photos = fullContact.photos();
+ bbpim::ContactPhoto primaryPhoto = fullContact.primaryPhoto();
+
+ for (int i = 0; i < photos.size(); i++) {
+ bbpim::ContactPhoto currentPhoto = photos[i];
+ Json::Value photo;
+
+ photo["originalFilePath"] = Json::Value(currentPhoto.originalPhoto().toStdString());
+ photo["largeFilePath"] = Json::Value(currentPhoto.largePhoto().toStdString());
+ photo["smallFilePath"] = Json::Value(currentPhoto.smallPhoto().toStdString());
+ photo["pref"] = Json::Value((primaryPhoto.id() == currentPhoto.id()));
+
+ contactPhotos.append(photo);
+ }
+}
+
+void PimContactsQt::populateNews(const bbpim::Contact& contact, Json::Value& contactNews)
+{
+ QList<bbpim::ContactNews> newsList = contact.news(5);
+ QList<bbpim::ContactNews>::const_iterator k = newsList.constBegin();
+
+ while (k != newsList.constEnd()) {
+ Json::Value news;
+ Json::Value companies;
+ QString format = "yyyy-MM-dd";
+
+ std::string body = k->body().toStdString();
+ body = replaceString(body);
+ news["body"] = Json::Value(body);
+
+ std::string title = k->title().toStdString();
+ title = replaceString(title);
+ news["title"] = Json::Value(title);
+
+ std::string articleSource = k->articleSource().toStdString();
+ articleSource = replaceString(articleSource);
+ news["articleSource"] = Json::Value(articleSource);
+
+ news["type"] = Json::Value(k->type().toStdString());
+ news["publishedAt"] = Json::Value(QString::number(k->publishedAt().toUTC().toMSecsSinceEpoch()).toStdString());
+ news["uri"] = Json::Value(k->uri().toString().toStdString());
+
+ QStringList companiesList = k->companies();
+ QStringList::const_iterator j = companiesList.constBegin();
+
+ while (j != companiesList.constEnd()) {
+ companies.append(j->toStdString());
+ ++j;
+ }
+
+ news["companies"] = companies;
+
+ contactNews.append(news);
+ ++k;
+ }
+}
+
+void PimContactsQt::populateActivity(const bbpim::Contact& contact, Json::Value& contactActivity)
+{
+ QList<bbpim::ContactActivity> activities = contact.activities();
+ QList<bbpim::ContactActivity>::const_iterator k = activities.constBegin();
+
+ while (k != activities.constEnd()) {
+ Json::Value activity;
+
+ std::string desc = k->description().toStdString();
+ desc = replaceString(desc);
+
+ activity["description"] = Json::Value(desc);
+ activity["direction"] = Json::Value(k->direction());
+ activity["mimeType"] = Json::Value(k->mimeType().toStdString());
+ activity["timestamp"] = Json::Value(QString::number(k->statusTimeStamp().toUTC().toMSecsSinceEpoch()).toStdString());
+
+ contactActivity.append(activity);
+ ++k;
+ }
+}
+
+/****************************************************************
+ * Helper functions for Save
+ ****************************************************************/
+
+void PimContactsQt::addAttributeKind(bbpim::ContactBuilder& contactBuilder, const Json::Value& jsonObj, const std::string& field)
+{
+ StringToKindMap::const_iterator kindIter = _attributeKindMap.find(field);
+
+ if (kindIter != _attributeKindMap.end()) {
+ switch (kindIter->second) {
+ // Attributes requiring group keys:
+ case bbpim::AttributeKind::Name: {
+ QList<SubkindValuePair> convertedList = convertGroupedAttributes(jsonObj);
+ addConvertedList(contactBuilder, kindIter->second, convertedList, "1");
+ break;
+ }
+ case bbpim::AttributeKind::OrganizationAffiliation: {
+ for (unsigned int i = 0; i < jsonObj.size(); i++) {
+ std::stringstream groupKeyStream;
+ groupKeyStream << i + 1;
+
+ QList<SubkindValuePair> convertedList = convertGroupedAttributes(jsonObj[i]);
+ addConvertedList(contactBuilder, kindIter->second, convertedList, groupKeyStream.str());
+ }
+
+ break;
+ }
+
+ // String arrays:
+ case bbpim::AttributeKind::VideoChat: {
+ QList<SubkindValuePair> convertedList = convertStringArray(jsonObj, bbpim::AttributeSubKind::VideoChatBbPlaybook);
+ addConvertedList(contactBuilder, kindIter->second, convertedList);
+ break;
+ }
+
+ // Dates:
+ case bbpim::AttributeKind::Date: {
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(field);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ std::string value = jsonObj.asString();
+ addAttribute(contactBuilder, kindIter->second, subkindIter->second, value);
+ }
+
+ break;
+ }
+
+ // Strings:
+ case bbpim::AttributeKind::Note:
+ case bbpim::AttributeKind::Sound: {
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(field);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ QList<SubkindValuePair> convertedList;
+ std::string value = jsonObj.asString();
+ convertedList.append(SubkindValuePair(subkindIter->second, value));
+ addConvertedList(contactBuilder, kindIter->second, convertedList);
+ }
+
+ break;
+ }
+
+ // ContactField attributes:
+ case bbpim::AttributeKind::Phone:
+ case bbpim::AttributeKind::Email:
+ case bbpim::AttributeKind::Fax:
+ case bbpim::AttributeKind::Pager:
+ case bbpim::AttributeKind::InstantMessaging:
+ case bbpim::AttributeKind::Website:
+ case bbpim::AttributeKind::Group:
+ case bbpim::AttributeKind::Profile: {
+ QList<SubkindValuePair> convertedList = convertFieldAttributes(jsonObj);
+ addConvertedList(contactBuilder, kindIter->second, convertedList);
+ break;
+ }
+
+ // Special cases (treated differently in ContactBuilder):
+ default: {
+ if (field == "addresses") {
+ for (unsigned int i = 0; i < jsonObj.size(); i++) {
+ Json::Value addressObj = jsonObj[i];
+ addPostalAddress(contactBuilder, addressObj);
+ }
+ } else if (field == "photos") {
+ for (unsigned int i = 0; i < jsonObj.size(); i++) {
+ Json::Value photoObj = jsonObj[i];
+ addPhoto(contactBuilder, photoObj);
+ }
+ } else if (field == "favorite") {
+ bool isFavorite = jsonObj.asBool();
+ contactBuilder = contactBuilder.setFavorite(isFavorite);
+ }
+
+ break;
+ }
+ }
+ } else if (field == "displayName" || field == "nickname") {
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(field);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ addAttribute(contactBuilder, bbpim::AttributeKind::Name, subkindIter->second, jsonObj.asString(), "1");
+ }
+ }
+}
+
+void PimContactsQt::syncAttributeKind(bbpim::Contact& contact, const Json::Value& jsonObj, const std::string& field)
+{
+ StringToKindMap::const_iterator kindIter = _attributeKindMap.find(field);
+ bbpim::ContactBuilder contactBuilder(contact.edit());
+
+ if (kindIter != _attributeKindMap.end()) {
+ switch (kindIter->second) {
+ // Attributes requiring group keys:
+ case bbpim::AttributeKind::Name: {
+ QList<QList<bbpim::ContactAttribute> > savedList = contact.filteredAttributesByGroupKey(kindIter->second);
+ QList<SubkindValuePair> convertedList = convertGroupedAttributes(jsonObj);
+
+ if (!savedList.empty()) {
+ syncConvertedList(contactBuilder, kindIter->second, savedList[0], convertedList, "1");
+ } else {
+ addConvertedList(contactBuilder, kindIter->second, convertedList, "1");
+ }
+
+ break;
+ }
+ case bbpim::AttributeKind::OrganizationAffiliation: {
+ QList<QList<bbpim::ContactAttribute> > savedList = contact.filteredAttributesByGroupKey(kindIter->second);
+ syncAttributeGroup(contactBuilder, kindIter->second, savedList, jsonObj);
+ break;
+ }
+
+ // String arrays:
+ case bbpim::AttributeKind::VideoChat: {
+ QList<bbpim::ContactAttribute> savedList = contact.filteredAttributes(kindIter->second);
+ QList<SubkindValuePair> convertedList = convertStringArray(jsonObj, bbpim::AttributeSubKind::VideoChatBbPlaybook);
+ syncConvertedList(contactBuilder, kindIter->second, savedList, convertedList);
+ break;
+ }
+
+ // Dates:
+ case bbpim::AttributeKind::Date: {
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(field);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ QList<bbpim::ContactAttribute> savedList = contact.filteredAttributes(kindIter->second);
+ syncAttribute(contactBuilder, savedList, kindIter->second, subkindIter->second, jsonObj.asString());
+ }
+
+ break;
+ }
+
+ // Strings:
+ case bbpim::AttributeKind::Note:
+ case bbpim::AttributeKind::Sound: {
+ QList<bbpim::ContactAttribute> savedList = contact.filteredAttributes(kindIter->second);
+ QList<SubkindValuePair> convertedList;
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(field);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ std::string value = jsonObj.asString();
+ convertedList.append(SubkindValuePair(subkindIter->second, value));
+ }
+
+ syncConvertedList(contactBuilder, kindIter->second, savedList, convertedList);
+ break;
+ }
+
+ // ContactField attributes:
+ case bbpim::AttributeKind::Phone:
+ case bbpim::AttributeKind::Email:
+ case bbpim::AttributeKind::Fax:
+ case bbpim::AttributeKind::Pager:
+ case bbpim::AttributeKind::InstantMessaging:
+ case bbpim::AttributeKind::Website:
+ case bbpim::AttributeKind::Group:
+ case bbpim::AttributeKind::Profile: {
+ QList<bbpim::ContactAttribute> savedList = contact.filteredAttributes(kindIter->second);
+ QList<SubkindValuePair> convertedList = convertFieldAttributes(jsonObj);
+ syncConvertedList(contactBuilder, kindIter->second, savedList, convertedList);
+ break;
+ }
+
+ // Special cases (treated differently in ContactBuilder):
+ default: {
+ if (field == "addresses") {
+ QList<bbpim::ContactPostalAddress> savedList = contact.postalAddresses();
+ syncPostalAddresses(contactBuilder, savedList, jsonObj);
+ } else if (field == "photos") {
+ QList<bbpim::ContactPhoto> savedList = contact.photos();
+ syncPhotos(contactBuilder, savedList, jsonObj, contact.primaryPhoto());
+
+ } else if (field == "favorite") {
+ bool isFavorite = jsonObj.asBool();
+ contactBuilder.setFavorite(isFavorite);
+ }
+
+ break;
+ }
+ }
+ } else if (field == "displayName" || field == "nickname") {
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(field);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ QList<QList<bbpim::ContactAttribute> > savedList = contact.filteredAttributesByGroupKey(bbpim::AttributeKind::Name);
+
+ if (!savedList.empty()) {
+ syncAttribute(contactBuilder, savedList[0], bbpim::AttributeKind::Name, subkindIter->second, jsonObj.asString(), "1");
+ } else {
+ addAttribute(contactBuilder, bbpim::AttributeKind::Name, subkindIter->second, jsonObj.asString(), "1");
+ }
+ }
+ }
+}
+
+
+QList<SubkindValuePair> PimContactsQt::convertGroupedAttributes(const Json::Value& fieldsObj)
+{
+ const Json::Value::Members fields = fieldsObj.getMemberNames();
+ QList<SubkindValuePair> convertedList;
+
+ for (unsigned int i = 0; i < fields.size(); i++) {
+ const std::string fieldKey = fields[i];
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(fieldKey);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ convertedList.append(SubkindValuePair(subkindIter->second, fieldsObj[fieldKey].asString()));
+ }
+ }
+
+ return convertedList;
+}
+
+QList<SubkindValuePair> PimContactsQt::convertFieldAttributes(const Json::Value& fieldArray)
+{
+ QList<SubkindValuePair> convertedList;
+
+ for (unsigned int i = 0; i < fieldArray.size(); i++) {
+ Json::Value fieldObj = fieldArray[i];
+ std::string type = fieldObj.get("type", "").asString();
+ std::string value = fieldObj.get("value", "").asString();
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(type);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ convertedList.append(SubkindValuePair(subkindIter->second, value));
+ }
+ }
+
+ return convertedList;
+}
+
+QList<SubkindValuePair> PimContactsQt::convertStringArray(const Json::Value& stringArray, bbpim::AttributeSubKind::Type subkind)
+{
+ QList<SubkindValuePair> convertedList;
+
+ for (unsigned int i = 0; i < stringArray.size(); i++) {
+ std::string value = stringArray[i].asString();
+ convertedList.append(SubkindValuePair(subkind, value));
+ }
+
+ return convertedList;
+}
+
+void PimContactsQt::addConvertedList(bbpim::ContactBuilder& contactBuilder, const bbpim::AttributeKind::Type kind, const QList<SubkindValuePair>& convertedList, const std::string& groupKey)
+{
+ for (int i = 0; i < convertedList.size(); i++) {
+ addAttribute(contactBuilder, kind, convertedList[i].first, convertedList[i].second, groupKey);
+ }
+}
+
+void PimContactsQt::addAttribute(bbpim::ContactBuilder& contactBuilder, const bbpim::AttributeKind::Type kind, const bbpim::AttributeSubKind::Type subkind, const std::string& value, const std::string& groupKey)
+{
+ bbpim::ContactAttribute attribute;
+ bbpim::ContactAttributeBuilder attributeBuilder(attribute.edit());
+
+ attributeBuilder = attributeBuilder.setKind(kind);
+ attributeBuilder = attributeBuilder.setSubKind(subkind);
+
+ if (kind == bbpim::AttributeKind::Date) {
+ QDateTime date = QDateTime::fromString(QString(value.c_str()), QString("ddd MMM dd yyyy"));
+
+ if (date.isValid()) {
+ attributeBuilder = attributeBuilder.setValue(date);
+ } else {
+ attributeBuilder = attributeBuilder.setValue(QString(value.c_str()));
+ }
+ } else {
+ attributeBuilder = attributeBuilder.setValue(QString(value.c_str()));
+ }
+
+ if (!groupKey.empty()) {
+ attributeBuilder = attributeBuilder.setGroupKey(QString(groupKey.c_str()));
+ }
+
+ contactBuilder.addAttribute(attribute);
+}
+
+void PimContactsQt::addPostalAddress(bbpim::ContactBuilder& contactBuilder, const Json::Value& addressObj)
+{
+ bbpim::ContactPostalAddress address;
+ bbpim::ContactPostalAddressBuilder addressBuilder(address.edit());
+
+ if (addressObj.isMember("type")) {
+ std::string value = addressObj["type"].asString();
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(value);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ addressBuilder = addressBuilder.setSubKind(subkindIter->second);
+ }
+ }
+
+ addressBuilder = addressBuilder.setLine1(QString(addressObj.get("streetAddress", "").asCString()));
+ addressBuilder = addressBuilder.setLine2(QString(addressObj.get("streetOther", "").asCString()));
+ addressBuilder = addressBuilder.setCity(QString(addressObj.get("locality", "").asCString()));
+ addressBuilder = addressBuilder.setRegion(QString(addressObj.get("region", "").asCString()));
+ addressBuilder = addressBuilder.setCountry(QString(addressObj.get("country", "").asCString()));
+ addressBuilder = addressBuilder.setPostalCode(QString(addressObj.get("postalCode", "").asCString()));
+
+ contactBuilder = contactBuilder.addPostalAddress(address);
+}
+
+void PimContactsQt::addPhoto(bbpim::ContactBuilder& contactBuilder, const Json::Value& photoObj)
+{
+ bbpim::ContactPhoto photo;
+ bbpim::ContactPhotoBuilder photoBuilder(photo.edit());
+
+ std::string filepath = photoObj.get("originalFilePath", "").asString();
+ bool pref = photoObj.get("pref", false).asBool();
+
+ photoBuilder.setOriginalPhoto(QString(filepath.c_str()));
+ photoBuilder.setPrimaryPhoto(pref);
+
+ contactBuilder = contactBuilder.addPhoto(photo, pref);
+}
+
+void PimContactsQt::syncConvertedList(bbpim::ContactBuilder& contactBuilder, bbpim::AttributeKind::Type kind, QList<bbpim::ContactAttribute>& savedList, const QList<SubkindValuePair>& convertedList, const std::string& groupKey)
+{
+ int index;
+
+ for (index = 0; index < savedList.size() && index < convertedList.size(); index++) {
+ // Do not overwrite display name or nickname when syncing name
+ if (kind == bbpim::AttributeKind::Name &&
+ (savedList[index].subKind() == bbpim::AttributeSubKind::NameNickname ||
+ savedList[index].subKind() == bbpim::AttributeSubKind::NameDisplayName)) {
+ addAttribute(contactBuilder, kind, convertedList[index].first, convertedList[index].second, groupKey);
+ } else {
+ bbpim::ContactAttributeBuilder attributeBuilder(savedList[index].edit());
+ attributeBuilder = attributeBuilder.setSubKind(convertedList[index].first);
+ attributeBuilder = attributeBuilder.setValue(QString(convertedList[index].second.c_str()));
+
+ if (!groupKey.empty()) {
+ attributeBuilder = attributeBuilder.setGroupKey(QString(groupKey.c_str()));
+ }
+ }
+ }
+
+ if (index < savedList.size()) {
+ for (; index < savedList.size(); index++) {
+ // Do not delete display name or nickname when syncing name
+ if (savedList[index].subKind() != bbpim::AttributeSubKind::NameNickname &&
+ savedList[index].subKind() != bbpim::AttributeSubKind::NameDisplayName) {
+ contactBuilder = contactBuilder.deleteAttribute(savedList[index]);
+ }
+ }
+ } else if (index < convertedList.size()) {
+ for (; index < convertedList.size(); index++) {
+ QList<SubkindValuePair> remainingList = convertedList.mid(index);
+ addConvertedList(contactBuilder, kind, remainingList, groupKey);
+ }
+ }
+}
+
+void PimContactsQt::syncAttributeGroup(bbpim::ContactBuilder& contactBuilder, bbpim::AttributeKind::Type kind, QList<QList<bbpim::ContactAttribute> > savedList, const Json::Value& jsonObj)
+{
+ int i;
+
+ for (i = 0; i < static_cast<int>(jsonObj.size()) && i < savedList.size(); i++) {
+ std::stringstream groupKeyStream;
+ groupKeyStream << i + 1;
+
+ QList<SubkindValuePair> convertedList = convertGroupedAttributes(jsonObj[i]);
+ syncConvertedList(contactBuilder, kind, savedList[i], convertedList, groupKeyStream.str());
+ }
+
+ if (i < savedList.size()) {
+ for (; i < savedList.size(); i++) {
+ for (int j = 0; j < savedList[i].size(); j++) {
+ contactBuilder = contactBuilder.deleteAttribute(savedList[i][j]);
+ }
+ }
+ } else if (i < static_cast<int>(jsonObj.size())) {
+ for (; i < static_cast<int>(jsonObj.size()); i++) {
+ std::stringstream groupKeyStream;
+ groupKeyStream << i + 1;
+
+ QList<SubkindValuePair> convertedList = convertGroupedAttributes(jsonObj[i]);
+ addConvertedList(contactBuilder, kind, convertedList, groupKeyStream.str());
+ }
+ }
+}
+
+void PimContactsQt::syncAttribute(bbpim::ContactBuilder& contactBuilder, QList<bbpim::ContactAttribute>& savedList, const bbpim::AttributeKind::Type kind, const bbpim::AttributeSubKind::Type subkind, const std::string& value, const std::string& groupKey)
+{
+ bool found = false;
+
+ for (int i = 0; i < savedList.size() && !found; i++) {
+ if (savedList[i].subKind() == subkind) {
+ bbpim::ContactAttributeBuilder attributeBuilder(savedList[i].edit());
+
+ if (kind == bbpim::AttributeKind::Date) {
+ QDateTime date = QDateTime::fromString(QString(value.c_str()), QString("ddd MMM dd yyyy"));
+
+ if (date.isValid()) {
+ attributeBuilder = attributeBuilder.setValue(date);
+ } else {
+ attributeBuilder = attributeBuilder.setValue(QString(value.c_str()));
+ }
+ } else {
+ attributeBuilder = attributeBuilder.setValue(QString(value.c_str()));
+
+ if (!groupKey.empty()) {
+ attributeBuilder = attributeBuilder.setGroupKey(QString(groupKey.c_str()));
+ }
+ }
+
+ found = true;
+ }
+ }
+
+ if (!found) {
+ addAttribute(contactBuilder, kind, subkind, value, groupKey);
+ }
+}
+
+void PimContactsQt::syncPostalAddresses(bbpim::ContactBuilder& contactBuilder, QList<bbpim::ContactPostalAddress>& savedList, const Json::Value& jsonObj)
+{
+ int i;
+
+ for (i = 0; i < savedList.size() && i < static_cast<int>(jsonObj.size()); i++) {
+ Json::Value addressObj = jsonObj[i];
+ bbpim::ContactPostalAddressBuilder addressBuilder(savedList[i].edit());
+
+ std::string type = addressObj.get("type", "other").asString();
+ StringToSubKindMap::const_iterator subkindIter = _attributeSubKindMap.find(type);
+
+ if (subkindIter != _attributeSubKindMap.end()) {
+ addressBuilder = addressBuilder.setSubKind(subkindIter->second);
+ }
+
+ addressBuilder = addressBuilder.setLine1(QString(addressObj.get("streetAddress", "").asCString()));
+ addressBuilder = addressBuilder.setLine2(QString(addressObj.get("streetOther", "").asCString()));
+ addressBuilder = addressBuilder.setCity(QString(addressObj.get("locality", "").asCString()));
+ addressBuilder = addressBuilder.setRegion(QString(addressObj.get("region", "").asCString()));
+ addressBuilder = addressBuilder.setCountry(QString(addressObj.get("country", "").asCString()));
+ addressBuilder = addressBuilder.setPostalCode(QString(addressObj.get("postalCode", "").asCString()));
+ }
+
+ if (i < savedList.size()) {
+ for (; i < savedList.size(); i++) {
+ contactBuilder = contactBuilder.deletePostalAddress(savedList[i]);
+ }
+ } else if (i < static_cast<int>(jsonObj.size())) {
+ for (; i < static_cast<int>(jsonObj.size()); i++) {
+ addPostalAddress(contactBuilder, jsonObj[i]);
+ }
+ }
+}
+
+void PimContactsQt::syncPhotos(bbpim::ContactBuilder& contactBuilder, QList<bbpim::ContactPhoto>& savedList, const Json::Value& jsonObj, const bbpim::ContactPhoto& primaryPhoto)
+{
+ int i;
+
+ // We must do the delete first, because there seems to be a problem if we do it after
+ if (savedList.size() > static_cast<int>(jsonObj.size())) {
+ for (i = jsonObj.size(); i < savedList.size(); i++) {
+ contactBuilder = contactBuilder.deletePhoto(savedList[i]);
+ }
+ }
+
+ for (i = 0; i < savedList.size() && i < static_cast<int>(jsonObj.size()); i++) {
+ std::string filepath = jsonObj[i].get("originalFilePath", "").asString();
+ bool pref = jsonObj[i].get("pref", false).asBool();
+
+ if (filepath != savedList[i].originalPhoto().toStdString()) {
+ contactBuilder = contactBuilder.deletePhoto(savedList[i]);
+ addPhoto(contactBuilder, jsonObj[i]);
+ } else if (pref != (primaryPhoto.id() == savedList[i].id())) {
+ bbpim::ContactPhotoBuilder photoBuilder = savedList[i].edit();
+ photoBuilder.setPrimaryPhoto(pref);
+ }
+ }
+
+ if (i < static_cast<int>(jsonObj.size())) {
+ for (; i < static_cast<int>(jsonObj.size()); i++) {
+ addPhoto(contactBuilder, jsonObj[i]);
+ }
+ }
+}
+
+/****************************************************************
+ * Mapping functions
+ ****************************************************************/
+
+void PimContactsQt::createAttributeKindMap()
+{
+ _attributeKindMap["phoneNumbers"] = bbpim::AttributeKind::Phone;
+ _attributeKindMap["faxNumbers"] = bbpim::AttributeKind::Fax;
+ _attributeKindMap["pagerNumbers"] = bbpim::AttributeKind::Pager;
+ _attributeKindMap["emails"] = bbpim::AttributeKind::Email;
+ _attributeKindMap["urls"] = bbpim::AttributeKind::Website;
+ _attributeKindMap["socialNetworks"] = bbpim::AttributeKind::Profile;
+ _attributeKindMap["anniversary"] = bbpim::AttributeKind::Date;
+ _attributeKindMap["birthday"] = bbpim::AttributeKind::Date;
+ _attributeKindMap["categories"] = bbpim::AttributeKind::Group;
+ _attributeKindMap["name"] = bbpim::AttributeKind::Name;
+ _attributeKindMap["organizations"] = bbpim::AttributeKind::OrganizationAffiliation;
+ _attributeKindMap["education"] = bbpim::AttributeKind::Education;
+ _attributeKindMap["note"] = bbpim::AttributeKind::Note;
+ _attributeKindMap["ims"] = bbpim::AttributeKind::InstantMessaging;
+ _attributeKindMap["ringtone"] = bbpim::AttributeKind::Sound;
+ _attributeKindMap["videoChat"] = bbpim::AttributeKind::VideoChat;
+ _attributeKindMap["addresses"] = bbpim::AttributeKind::Invalid;
+ _attributeKindMap["favorite"] = bbpim::AttributeKind::Invalid;
+ _attributeKindMap["photos"] = bbpim::AttributeKind::Invalid;
+ _attributeKindMap["news"] = bbpim::AttributeKind::Invalid;
+ _attributeKindMap["activities"] = bbpim::AttributeKind::Invalid;
+}
+
+void PimContactsQt::createAttributeSubKindMap()
+{
+ _attributeSubKindMap["other"] = bbpim::AttributeSubKind::Other;
+ _attributeSubKindMap["home"] = bbpim::AttributeSubKind::Home;
+ _attributeSubKindMap["work"] = bbpim::AttributeSubKind::Work;
+ _attributeSubKindMap["mobile"] = bbpim::AttributeSubKind::PhoneMobile;
+ _attributeSubKindMap["direct"] = bbpim::AttributeSubKind::FaxDirect;
+ _attributeSubKindMap["blog"] = bbpim::AttributeSubKind::Blog;
+ _attributeSubKindMap["resume"] = bbpim::AttributeSubKind::WebsiteResume;
+ _attributeSubKindMap["portfolio"] = bbpim::AttributeSubKind::WebsitePortfolio;
+ _attributeSubKindMap["personal"] = bbpim::AttributeSubKind::WebsitePersonal;
+ _attributeSubKindMap["company"] = bbpim::AttributeSubKind::WebsiteCompany;
+ _attributeSubKindMap["facebook"] = bbpim::AttributeSubKind::ProfileFacebook;
+ _attributeSubKindMap["twitter"] = bbpim::AttributeSubKind::ProfileTwitter;
+ _attributeSubKindMap["linkedin"] = bbpim::AttributeSubKind::ProfileLinkedIn;
+ _attributeSubKindMap["gist"] = bbpim::AttributeSubKind::ProfileGist;
+ _attributeSubKindMap["tungle"] = bbpim::AttributeSubKind::ProfileTungle;
+ _attributeSubKindMap["birthday"] = bbpim::AttributeSubKind::DateBirthday;
+ _attributeSubKindMap["anniversary"] = bbpim::AttributeSubKind::DateAnniversary;
+ _attributeSubKindMap["categories"] = bbpim::AttributeSubKind::GroupDepartment;
+ _attributeSubKindMap["givenName"] = bbpim::AttributeSubKind::NameGiven;
+ _attributeSubKindMap["familyName"] = bbpim::AttributeSubKind::NameSurname;
+ _attributeSubKindMap["honorificPrefix"] = bbpim::AttributeSubKind::Title;
+ _attributeSubKindMap["honorificSuffix"] = bbpim::AttributeSubKind::NameSuffix;
+ _attributeSubKindMap["middleName"] = bbpim::AttributeSubKind::NameMiddle;
+ _attributeSubKindMap["nickname"] = bbpim::AttributeSubKind::NameNickname;
+ _attributeSubKindMap["displayName"] = bbpim::AttributeSubKind::NameDisplayName;
+ _attributeSubKindMap["phoneticGivenName"] = bbpim::AttributeSubKind::NamePhoneticGiven;
+ _attributeSubKindMap["phoneticFamilyName"] = bbpim::AttributeSubKind::NamePhoneticSurname;
+ _attributeSubKindMap["name"] = bbpim::AttributeSubKind::OrganizationAffiliationName;
+ _attributeSubKindMap["department"] = bbpim::AttributeSubKind::OrganizationAffiliationDetails;
+ _attributeSubKindMap["title"] = bbpim::AttributeSubKind::Title;
+ _attributeSubKindMap["BbmPin"] = bbpim::AttributeSubKind::InstantMessagingBbmPin;
+ _attributeSubKindMap["Aim"] = bbpim::AttributeSubKind::InstantMessagingAim;
+ _attributeSubKindMap["Aliwangwang"] = bbpim::AttributeSubKind::InstantMessagingAliwangwang;
+ _attributeSubKindMap["GoogleTalk"] = bbpim::AttributeSubKind::InstantMessagingGoogleTalk;
+ _attributeSubKindMap["Sametime"] = bbpim::AttributeSubKind::InstantMessagingSametime;
+ _attributeSubKindMap["Icq"] = bbpim::AttributeSubKind::InstantMessagingIcq;
+ _attributeSubKindMap["Jabber"] = bbpim::AttributeSubKind::InstantMessagingJabber;
+ _attributeSubKindMap["MsLcs"] = bbpim::AttributeSubKind::InstantMessagingMsLcs;
+ _attributeSubKindMap["Skype"] = bbpim::AttributeSubKind::InstantMessagingSkype;
+ _attributeSubKindMap["YahooMessenger"] = bbpim::AttributeSubKind::InstantMessagingYahooMessenger;
+ _attributeSubKindMap["YahooMessegerJapan"] = bbpim::AttributeSubKind::InstantMessagingYahooMessengerJapan;
+ _attributeSubKindMap["BbPlaybook"] = bbpim::AttributeSubKind::VideoChatBbPlaybook;
+ _attributeSubKindMap["ringtone"] = bbpim::AttributeSubKind::SoundRingtone;
+ _attributeSubKindMap["note"] = bbpim::AttributeSubKind::Invalid;
+}
+
+void PimContactsQt::createKindAttributeMap() {
+ _kindAttributeMap[bbpim::AttributeKind::Phone] = "phoneNumbers";
+ _kindAttributeMap[bbpim::AttributeKind::Fax] = "faxNumbers";
+ _kindAttributeMap[bbpim::AttributeKind::Pager] = "pagerNumber";
+ _kindAttributeMap[bbpim::AttributeKind::Email] = "emails";
+ _kindAttributeMap[bbpim::AttributeKind::Website] = "urls";
+ _kindAttributeMap[bbpim::AttributeKind::Profile] = "socialNetworks";
+ _kindAttributeMap[bbpim::AttributeKind::OrganizationAffiliation] = "organizations";
+ _kindAttributeMap[bbpim::AttributeKind::Education] = "education";
+ _kindAttributeMap[bbpim::AttributeKind::Note] = "note";
+ _kindAttributeMap[bbpim::AttributeKind::InstantMessaging] = "ims";
+ _kindAttributeMap[bbpim::AttributeKind::VideoChat] = "videoChat";
+ _kindAttributeMap[bbpim::AttributeKind::Sound] = "ringtone";
+ _kindAttributeMap[bbpim::AttributeKind::Website] = "urls";
+}
+
+void PimContactsQt::createSubKindAttributeMap() {
+ _subKindAttributeMap[bbpim::AttributeSubKind::Other] = "other";
+ _subKindAttributeMap[bbpim::AttributeSubKind::Home] = "home";
+ _subKindAttributeMap[bbpim::AttributeSubKind::Work] = "work";
+ _subKindAttributeMap[bbpim::AttributeSubKind::PhoneMobile] = "mobile";
+ _subKindAttributeMap[bbpim::AttributeSubKind::FaxDirect] = "direct";
+ _subKindAttributeMap[bbpim::AttributeSubKind::Blog] = "blog";
+ _subKindAttributeMap[bbpim::AttributeSubKind::WebsiteResume] = "resume";
+ _subKindAttributeMap[bbpim::AttributeSubKind::WebsitePortfolio] = "portfolio";
+ _subKindAttributeMap[bbpim::AttributeSubKind::WebsitePersonal] = "personal";
+ _subKindAttributeMap[bbpim::AttributeSubKind::WebsiteCompany] = "company";
+ _subKindAttributeMap[bbpim::AttributeSubKind::ProfileFacebook] = "facebook";
+ _subKindAttributeMap[bbpim::AttributeSubKind::ProfileTwitter] = "twitter";
+ _subKindAttributeMap[bbpim::AttributeSubKind::ProfileLinkedIn] = "linkedin";
+ _subKindAttributeMap[bbpim::AttributeSubKind::ProfileGist] = "gist";
+ _subKindAttributeMap[bbpim::AttributeSubKind::ProfileTungle] = "tungle";
+ _subKindAttributeMap[bbpim::AttributeSubKind::DateBirthday] = "birthday";
+ _subKindAttributeMap[bbpim::AttributeSubKind::DateAnniversary] = "anniversary";
+ _subKindAttributeMap[bbpim::AttributeSubKind::NameGiven] = "givenName";
+ _subKindAttributeMap[bbpim::AttributeSubKind::NameSurname] = "familyName";
+ _subKindAttributeMap[bbpim::AttributeSubKind::Title] = "honorificPrefix";
+ _subKindAttributeMap[bbpim::AttributeSubKind::NameSuffix] = "honorificSuffix";
+ _subKindAttributeMap[bbpim::AttributeSubKind::NameMiddle] = "middleName";
+ _subKindAttributeMap[bbpim::AttributeSubKind::NamePhoneticGiven] = "phoneticGivenName";
+ _subKindAttributeMap[bbpim::AttributeSubKind::NamePhoneticSurname] = "phoneticFamilyName";
+ _subKindAttributeMap[bbpim::AttributeSubKind::NameNickname] = "nickname";
+ _subKindAttributeMap[bbpim::AttributeSubKind::NameDisplayName] = "displayName";
+ _subKindAttributeMap[bbpim::AttributeSubKind::OrganizationAffiliationName] = "name";
+ _subKindAttributeMap[bbpim::AttributeSubKind::OrganizationAffiliationDetails] = "department";
+ _subKindAttributeMap[bbpim::AttributeSubKind::Title] = "title";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingBbmPin] = "BbmPin";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingAim] = "Aim";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingAliwangwang] = "Aliwangwang";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingGoogleTalk] = "GoogleTalk";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingSametime] = "Sametime";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingIcq] = "Icq";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingJabber] = "Jabber";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingMsLcs] = "MsLcs";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingSkype] = "Skype";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingYahooMessenger] = "YahooMessenger";
+ _subKindAttributeMap[bbpim::AttributeSubKind::InstantMessagingYahooMessengerJapan] = "YahooMessegerJapan";
+ _subKindAttributeMap[bbpim::AttributeSubKind::VideoChatBbPlaybook] = "BbPlaybook";
+ _subKindAttributeMap[bbpim::AttributeSubKind::SoundRingtone] = "ringtone";
+ _subKindAttributeMap[bbpim::AttributeSubKind::Personal] = "personal";
+}
+
+} // namespace webworks
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_qt.hpp
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_qt.hpp b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_qt.hpp
new file mode 100644
index 0000000..115469c
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/pim_contacts_qt.hpp
@@ -0,0 +1,148 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef PIM_CONTACTS_QT_H_
+#define PIM_CONTACTS_QT_H_
+
+#include <json/value.h>
+#include <bb/pim/contacts/ContactService.hpp>
+#include <bb/pim/contacts/ContactConsts.hpp>
+#include <bb/pim/contacts/Contact.hpp>
+#include <bb/pim/contacts/ContactBuilder.hpp>
+#include <bb/pim/contacts/ContactAttribute.hpp>
+#include <bb/pim/contacts/ContactAttributeBuilder.hpp>
+#include <bb/pim/contacts/ContactPostalAddress.hpp>
+#include <bb/pim/contacts/ContactPostalAddressBuilder.hpp>
+#include <bb/pim/contacts/ContactPhoto.hpp>
+#include <bb/pim/contacts/ContactPhotoBuilder.hpp>
+#include <bb/pim/contacts/ContactListFilters.hpp>
+#include <bb/pim/account/AccountService.hpp>
+#include <bb/pim/account/Account.hpp>
+#include <bb/pim/account/Provider>
+#include <webworks_utils.hpp>
+
+#include <string>
+#include <utility>
+#include <map>
+
+#include "contact_account.hpp"
+
+class PimContacts;
+
+namespace webworks {
+
+namespace bbpim = bb::pim::contacts;
+namespace bbpimacc = bb::pim::account;
+
+typedef std::map<std::string, bbpim::AttributeKind::Type> StringToKindMap;
+typedef std::map<std::string, bbpim::AttributeSubKind::Type> StringToSubKindMap;
+typedef std::map<bbpim::AttributeKind::Type, std::string> KindToStringMap;
+typedef std::map<bbpim::AttributeSubKind::Type, std::string> SubKindToStringMap;
+
+typedef std::pair<bbpim::AttributeSubKind::Type, std::string> SubkindValuePair;
+
+enum PimContactsError {
+ UNKNOWN_ERROR = 0,
+ INVALID_ARGUMENT_ERROR = 1,
+ TIMEOUT_ERROR = 2,
+ PENDING_OPERATION_ERROR = 3,
+ IO_ERROR = 4,
+ NOT_SUPPORTED_ERROR = 5,
+ PERMISSION_DENIED_ERROR = 20,
+};
+
+struct PimContactsThreadInfo {
+ PimContacts *parent;
+ Json::Value *jsonObj;
+ std::string eventId;
+};
+
+class PimContactsQt {
+public:
+ PimContactsQt();
+ ~PimContactsQt();
+ Json::Value Find(const Json::Value& argsObj);
+ Json::Value Save(const Json::Value& attributeObj);
+ Json::Value CreateContact(const Json::Value& attributeObj);
+ Json::Value DeleteContact(const Json::Value& contactObj);
+ Json::Value EditContact(bbpim::Contact& contact, const Json::Value& attributeObj);
+ Json::Value CloneContact(bbpim::Contact& contact, const Json::Value& attributeObj);
+ Json::Value GetContact(const Json::Value& argsObj);
+ static Json::Value InvokePicker(const Json::Value& args);
+ static Json::Value GetContactAccounts();
+
+private:
+ // Helper functions for Find
+ Json::Value assembleSearchResults(const QSet<bbpim::ContactId>& results, const Json::Value& contactFields, int limit);
+ Json::Value populateContact(const bbpim::Contact& contact, const Json::Value& contactFields);
+ void populateField(const bbpim::Contact& contact, bbpim::AttributeKind::Type kind, Json::Value& contactItem, bool isContactField, bool isArray);
+ void populateDisplayNameNickName(const bbpim::Contact& contact, Json::Value& contactItem, const std::string& field);
+ void populateOrganizations(const bbpim::Contact& contact, Json::Value& contactOrgs);
+ void populateAddresses(const bbpim::Contact& contact, Json::Value& contactAddrs);
+ void populatePhotos(const bbpim::Contact& contact, Json::Value& contactPhotos);
+ void populateNews(const bbpim::Contact& contact, Json::Value& contactNews);
+ void populateActivity(const bbpim::Contact& contact, Json::Value& contactActivity);
+ static void populateAccount(const bbpimacc::Account& account, Json::Value& jsonAccount);
+
+ static QSet<bbpim::ContactId> singleFieldSearch(const Json::Value& searchFieldsJson, const Json::Value& contactFields, const bool favorite, const Json::Value& includeAccounts, const Json::Value& excludeAccounts);
+ static QString getSortFieldValue(const bbpim::SortColumn::Type sortField, const bbpim::Contact& contact);
+ static QList<bbpim::SearchField::Type> getSearchFields(const Json::Value& searchFieldsJson);
+ static void getSortSpecs(const Json::Value& sort);
+ static QSet<bbpim::ContactId> getPartialSearchResults(const Json::Value& filter, const Json::Value& contactFields, const bool favorite, const Json::Value& includeAccounts, const Json::Value& excludeAccounts);
+ static bool lessThan(const bbpim::Contact& c1, const bbpim::Contact& c2);
+ static std::string replaceAll(const std::string& s, const std::string& souce = "\"", const std::string& target = "\\\"");
+ static std::string replaceString(const std::string& s);
+ static QList<bbpim::AttributeKind::Type> getIncludeAttributesList(const Json::Value& contactFields, bbpim::ContactListFilters* listFilters = NULL);
+ static void getAccountFilters(bbpim::ContactSearchFilters* searchFilter, bbpim::ContactListFilters* listFilter, const Json::Value& includeAccounts, const Json::Value& excludeAccounts);
+
+ // Helper functions for Save
+ void addAttributeKind(bbpim::ContactBuilder& contactBuilder, const Json::Value& jsonObj, const std::string& field);
+ void addPostalAddress(bbpim::ContactBuilder& contactBuilder, const Json::Value& addressObj);
+ void addPhoto(bbpim::ContactBuilder& contactBuilder, const Json::Value& photoObj);
+
+ void syncAttributeKind(bbpim::Contact& contact, const Json::Value& jsonObj, const std::string& field);
+ void syncConvertedList(bbpim::ContactBuilder& contactBuilder, bbpim::AttributeKind::Type kind, QList<bbpim::ContactAttribute>& savedList, const QList<SubkindValuePair>& convertedList, const std::string& groupKey = "");
+ void syncAttributeGroup(bbpim::ContactBuilder& contactBuilder, bbpim::AttributeKind::Type kind, QList<QList<bbpim::ContactAttribute> > savedList, const Json::Value& jsonObj);
+ void syncAttribute(bbpim::ContactBuilder& contactBuilder, QList<bbpim::ContactAttribute>& savedList, const bbpim::AttributeKind::Type kind, const bbpim::AttributeSubKind::Type subkind, const std::string& value, const std::string& groupKey = "");
+ void syncPostalAddresses(bbpim::ContactBuilder& contactBuilder, QList<bbpim::ContactPostalAddress>& savedList, const Json::Value& jsonObj);
+ void syncPhotos(bbpim::ContactBuilder& contactBuilder, QList<bbpim::ContactPhoto>& savedList, const Json::Value& jsonObj, const bbpim::ContactPhoto& primaryPhoto);
+
+ void addConvertedList(bbpim::ContactBuilder& contactBuilder, const bbpim::AttributeKind::Type kind, const QList<SubkindValuePair>& convertedList, const std::string& groupKey = "");
+ void addAttribute(bbpim::ContactBuilder& contactBuilder, const bbpim::AttributeKind::Type kind, const bbpim::AttributeSubKind::Type subkind, const std::string& value, const std::string& groupKey = "");
+
+ QList<SubkindValuePair> convertGroupedAttributes(const Json::Value& fieldsObj);
+ QList<SubkindValuePair> convertFieldAttributes(const Json::Value& fieldArray);
+ QList<SubkindValuePair> convertStringArray(const Json::Value& stringArray, bbpim::AttributeSubKind::Type subkind);
+
+ // Mappings between JSON strings and attribute kinds/subkinds
+ static void createAttributeKindMap();
+ static void createAttributeSubKindMap();
+ static void createKindAttributeMap();
+ static void createSubKindAttributeMap();
+
+ static StringToKindMap _attributeKindMap;
+ static StringToSubKindMap _attributeSubKindMap;
+ static KindToStringMap _kindAttributeMap;
+ static SubKindToStringMap _subKindAttributeMap;
+ static QList<bbpim::SortSpecifier> _sortSpecs;
+
+ static std::map<bbpim::ContactId, bbpim::Contact> _contactSearchMap;
+ static ContactAccount& _contactAccount;
+};
+
+} // namespace webworks
+
+#endif // PIM_CONTACTS_QT_H_
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/simulator/libpimcontacts.so
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/simulator/libpimcontacts.so b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/simulator/libpimcontacts.so
new file mode 100644
index 0000000..d6bf514
Binary files /dev/null and b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/simulator/libpimcontacts.so differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/Makefile
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/Makefile b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/Makefile
new file mode 100644
index 0000000..0e22650
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/Makefile
@@ -0,0 +1,8 @@
+LIST=VARIANT
+ifndef QRECURSE
+QRECURSE=recurse.mk
+ifdef QCONFIG
+QRDIR=$(dir $(QCONFIG))
+endif
+endif
+include $(QRDIR)$(QRECURSE)
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/so/Makefile
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/so/Makefile b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/so/Makefile
new file mode 100644
index 0000000..2c76089
--- /dev/null
+++ b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/so/Makefile
@@ -0,0 +1 @@
+include ../../common.mk
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/so/libpimcontacts.so
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/so/libpimcontacts.so b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/so/libpimcontacts.so
new file mode 100755
index 0000000..d6bf514
Binary files /dev/null and b/lib/cordova-blackberry/plugins/org.apache.cordova.blackberry10.pimlib/src/blackberry10/native/x86/so/libpimcontacts.so differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/scripts/lib/conf.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/scripts/lib/conf.js b/lib/cordova-blackberry/scripts/lib/conf.js
new file mode 100644
index 0000000..625964d
--- /dev/null
+++ b/lib/cordova-blackberry/scripts/lib/conf.js
@@ -0,0 +1,21 @@
+/*
+* Copyright 2011 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+var path = require("path");
+
+module.exports = {
+ ROOT: path.normalize(__dirname + "/../../"),
+ TEMP: path.normalize(__dirname + "/../../temp/"),
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/scripts/lib/utils.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/scripts/lib/utils.js b/lib/cordova-blackberry/scripts/lib/utils.js
new file mode 100644
index 0000000..28624a8
--- /dev/null
+++ b/lib/cordova-blackberry/scripts/lib/utils.js
@@ -0,0 +1,127 @@
+/*
+* Copyright 2011 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+var os = require("os"),
+ fs = require('fs'),
+ wrench = require("wrench"),
+ path = require('path'),
+ childProcess = require("child_process");
+
+module.exports = {
+ isWindows : function () {
+ return os.type().toLowerCase().indexOf("windows") >= 0;
+ },
+
+ copyFile: function (srcFile, destDir, baseDir, shouldNotOverwrite) {
+ var filename = path.basename(srcFile),
+ fileBuffer,
+ fileLocation = path.join(destDir, filename);
+
+ //if a base directory was provided, determine
+ //folder structure from the relative path of the base folder
+ if (baseDir && srcFile.indexOf(baseDir) === 0) {
+ fileLocation = srcFile.replace(baseDir, destDir);
+ wrench.mkdirSyncRecursive(path.dirname(fileLocation), "0755");
+ }
+
+ //By default we should copy
+ //ONLY if we should NOT overwrite && the file exists will we skip copying
+ if (!shouldNotOverwrite || !path.existsSync(fileLocation)) {
+ fileBuffer = fs.readFileSync(srcFile);
+ fs.writeFileSync(fileLocation, fileBuffer);
+ }
+
+ },
+
+ listFiles: function (directory, filter) {
+ var files = wrench.readdirSyncRecursive(directory),
+ filteredFiles = [];
+
+ files.forEach(function (file) {
+ //On mac wrench.readdirSyncRecursive does not return absolute paths, so resolve one.
+ file = path.resolve(directory, file);
+
+ if (filter(file)) {
+ filteredFiles.push(file);
+ }
+ });
+
+ return filteredFiles;
+ },
+
+ arrayContains: function (array, obj) {
+ var i = array.length;
+ while (i--) {
+ if (array[i] === obj) {
+ return true;
+ }
+ }
+ return false;
+ },
+
+ isValidIPAddress: function (ip) {
+ var regex = new RegExp("(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
+ return regex.test(ip);
+ },
+
+ trim: function (str) {
+ return str.replace(/^\s+|\s+$/g, "");
+ },
+
+ displayOutput: function (data) {
+ data = data.replace(/^\s+|\s+$/g, "");
+ if (data !== "") {
+ console.log(data);
+ }
+ },
+
+ execCommandWithJWorkflow: function (command, options, neverDrop) {
+ var displayOutput = this.displayOutput;
+ return function (prev, baton) {
+ baton.take();
+ console.log("EXECUTING " + command);
+ options = options || {};
+ options.maxBuffer = 1024 * 1024;
+ var c = childProcess.exec(command, options, function (error, stdout, stderr) {
+ if (error && !neverDrop) {
+ baton.drop(error.code);
+ } else {
+ baton.pass(prev);
+ }
+ });
+
+ c.stdout.on('data', function (data) {
+ displayOutput(data);
+ });
+
+ c.stderr.on('data', function (data) {
+ displayOutput(data);
+ });
+ };
+ },
+
+ copyFolder: function (source, destination) {
+ //create the destination folder if it does not exist
+ if (!path.existsSync(destination)) {
+ wrench.mkdirSyncRecursive(destination, "0755");
+ }
+
+ wrench.copyDirSyncRecursive(source, destination);
+ },
+
+ isDirectory: function (source) {
+ return fs.statSync(source).isDirectory();
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/scripts/test.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/scripts/test.js b/lib/cordova-blackberry/scripts/test.js
new file mode 100644
index 0000000..05408c1
--- /dev/null
+++ b/lib/cordova-blackberry/scripts/test.js
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2013 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var wrench = require('wrench'),
+ path = require('path'),
+ fs = require('fs');
+
+module.exports = function (done, custom) {
+ var jasmine = require('jasmine-node'),
+ verbose = false,
+ coloured = false,
+ specs = [
+ "framework/test",
+ "bin/test/cordova/integration",
+ "bin/test/cordova/unit",
+ "bin/test/plugins"
+ ];
+ key = {};
+
+ if (typeof custom !== "undefined" && fs.existsSync(custom)) {
+ specs = [custom];
+ }
+
+ for (key in jasmine) {
+ if (Object.prototype.hasOwnProperty.call(jasmine, key)) {
+ global[key] = jasmine[key];
+ }
+ }
+
+ function execSpecs(folders) {
+ var failed = 0;
+ if (folders.length > 0) {
+ console.log("Running tests in: " + folders[folders.length - 1]);
+ jasmine.executeSpecsInFolder(path.resolve(folders.pop()), function (runner) {
+ execSpecs(folders);
+ failed = runner.results().failedcount === 0 ? 0 : 1;
+ }, verbose, coloured);
+ }
+ else {
+ (typeof done !== "function" ? process.exit : done)(failed);
+ }
+ }
+
+ execSpecs(specs);
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/.reviewboardrc
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/.reviewboardrc b/lib/cordova-ios/.reviewboardrc
new file mode 100644
index 0000000..30e9587
--- /dev/null
+++ b/lib/cordova-ios/.reviewboardrc
@@ -0,0 +1,8 @@
+#
+# Settings for post-review (used for uploading diffs to reviews.apache.org).
+#
+GUESS_FIELDS = True
+OPEN_BROWSER = True
+TARGET_GROUPS = 'cordova'
+REVIEWBOARD_URL = 'http://reviews.apache.org'
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/.gitignore
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/.gitignore b/lib/cordova-ios/CordovaLib/.gitignore
deleted file mode 100755
index c946984..0000000
--- a/lib/cordova-ios/CordovaLib/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-build/*
-*.pbxuser
-*.perspectivev3
-*.mode1v3
-javascripts/cordova-*.js
-
[28/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/config-parser.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/config-parser.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/config-parser.js
new file mode 100644
index 0000000..0e3d9e9
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/config-parser.js
@@ -0,0 +1,670 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*jshint sub:true*/
+var fs = require("fs"),
+ util = require('util'),
+ xml2js = require('xml2js'),
+ packagerUtils = require('./packager-utils'),
+ check = require('validator').check,
+ sanitize = require('validator').sanitize,
+ localize = require("./localize"),
+ logger = require("./logger"),
+ fileManager = require("./file-manager"),
+ utils = require("./packager-utils"),
+ i18nMgr = require("./i18n-manager"),
+ _self,
+ _predefinedFeatures,
+ _hybridFeatures;
+
+//This function will convert a wc3 paramObj with a list of
+//<param name="" value=""> elements into a single object
+function processParamObj(paramObj) {
+ var processedObj = {},
+ attribs,
+ paramName,
+ paramValue;
+
+ if (paramObj) {
+ //Convert to array for single param entries where only an object is created
+ if (!Array.isArray(paramObj)) {
+ paramObj = [paramObj];
+ }
+
+ paramObj.forEach(function (param) {
+ attribs = param["@"];
+
+ if (attribs) {
+ paramName = attribs["name"];
+ paramValue = attribs["value"];
+
+ if (paramName && paramValue) {
+ //Add the key/value pair to the processedObj
+ processedObj[paramName] = paramValue;
+ }
+ }
+ });
+ }
+
+ return processedObj;
+}
+
+function processFeatures(featuresArray, widgetConfig, processPredefinedFeatures) {
+ var features = [],
+ attribs;
+ if (featuresArray) {
+ featuresArray.forEach(function (feature) {
+ attribs = feature["@"];
+ if (attribs) {
+ attribs.required = packagerUtils.toBoolean(attribs.required, true);
+
+ // We do NOT want to auto defer networking and JavaScript if the
+ // blackberry.push feature is being used
+ if (attribs.id === "blackberry.push") {
+ widgetConfig.autoDeferNetworkingAndJavaScript = false;
+ }
+
+ if (_predefinedFeatures[attribs.id]) {
+ //Handle features that do NOT contain an API namespace
+ if (processPredefinedFeatures) {
+ _predefinedFeatures[attribs.id](feature, widgetConfig);
+ }
+ } else {
+ //Handle features that contain both a namespace and custom params
+ if (_hybridFeatures[attribs.id]) {
+ _hybridFeatures[attribs.id](feature, widgetConfig);
+ }
+ features.push(attribs);
+ }
+ } else {
+ features.push(attribs);
+ }
+ });
+ }
+
+ return features;
+}
+
+function createAccessListObj(uri, allowSubDomain) {
+ return {
+ uri: uri,
+ allowSubDomain: allowSubDomain
+ };
+}
+
+function processVersion(widgetConfig) {
+ if (widgetConfig.version) {
+ var versionArray = widgetConfig.version.split(".");
+
+ //if 4rth number in version exists, extract for build id
+ if (versionArray.length > 3) {
+ widgetConfig.buildId = versionArray[3];
+ widgetConfig.version = widgetConfig.version.substring(0, widgetConfig.version.lastIndexOf('.'));
+ }
+ }
+}
+
+function processBuildID(widgetConfig, session) {
+ if (session.buildId) {
+ //user specified a build id (--buildId), overide any previously set build id
+ widgetConfig.buildId = session.buildId;
+ }
+}
+
+function processWidgetData(data, widgetConfig, session) {
+ var attribs, featureArray, header;
+
+ if (data["@"]) {
+ widgetConfig.version = data["@"].version;
+ widgetConfig.id = data["@"].id;
+
+ if (data["@"]["rim:header"]) {
+ widgetConfig.customHeaders = {};
+ header = data["@"]["rim:header"].split(":");
+ // Just set it for now, in the future we can append them
+ widgetConfig.customHeaders[header[0]] = header[1];
+ }
+
+ if (data["@"]["rim:userAgent"]) {
+ widgetConfig.userAgent = data["@"]["rim:userAgent"];
+ }
+ }
+
+ //Default values
+ widgetConfig.hasMultiAccess = false;
+ widgetConfig.accessList = [];
+ widgetConfig.enableFlash = false;
+ widgetConfig.autoOrientation = true;
+ widgetConfig.autoDeferNetworkingAndJavaScript = true;
+ widgetConfig.theme = "default";
+ widgetConfig.autoHideSplashScreen = "true";
+
+ //set locally available features to access list
+ if (data.feature) {
+ featureArray = packagerUtils.isArray(data.feature) ? data.feature : [data.feature];
+ }
+
+ //Handle features that do not have source code
+ featureArray = processFeatures(featureArray, widgetConfig, true);
+
+ //Push empty WIDGET_LOCAL access obj until whitelisting is cleaned up
+ widgetConfig.accessList.push(createAccessListObj("WIDGET_LOCAL", true));
+
+ //add whitelisted features to access list
+ if (data.access) {
+ //If there is only one access list element, it will be parsed as an object and not an array
+ if (!packagerUtils.isArray(data.access)) {
+ data.access = [data.access];
+ }
+
+ data.access.forEach(function (accessElement) {
+ attribs = accessElement["@"];
+
+ if (attribs) {
+ if (attribs.uri === "*") {
+ if (accessElement.feature) {
+ throw localize.translate("EXCEPTION_FEATURE_DEFINED_WITH_WILDCARD_ACCESS_URI");
+ }
+
+ widgetConfig.hasMultiAccess = true;
+ } else {
+ attribs.subdomains = packagerUtils.toBoolean(attribs.subdomains);
+ widgetConfig.accessList.push(createAccessListObj(attribs.uri, attribs.subdomains));
+ }
+ }
+ });
+ }
+}
+
+function trim(obj) {
+ return (typeof obj === "string" ? obj.trim() : obj);
+}
+
+function processSplashScreenIconSrc(data, widgetConfig, key) {
+ if (data[key]) {
+ widgetConfig[key] = [];
+
+ if (!(data[key] instanceof Array)) {
+ data[key] = [data[key]];
+ }
+
+ data[key].forEach(function (obj) {
+ if (obj["@"]) {
+ widgetConfig[key].push(obj["@"].src);
+ } else {
+ widgetConfig[key].push(obj);
+ }
+ });
+ }
+}
+
+function processSplashScreenData(data, widgetConfig) {
+ //
+ // This takes config.xml markup in the form of:
+ //
+ // <rim:splash src="splash-1280x768.jpg" />
+ // <rim:splash src="splash-768x1280.jpg" />
+ // <rim:splash src="splash-1024x600.jpg" />
+ // <rim:splash src="splash-600x1024.jpg" />
+ //
+ // and turns it into:
+ //
+ // icon: ["splash-1280x768.jpg", "splash-768x1280.jpg", "splash-1024x600.jpg", "splash-600x1024.jpg"]
+ //
+ // Folder-based localization now done in i18n-manager
+ //
+ processSplashScreenIconSrc(data, widgetConfig, "rim:splash");
+}
+
+function processIconData(data, widgetConfig, session) {
+ //
+ // This takes config.xml markup in the form of:
+ //
+ // <icon src="icon-86.png" />
+ // <icon src="icon-150.png" />
+ //
+ // and turns it into:
+ //
+ // icon: ["icon-86.png", "icon-150.png"]
+ //
+ // Folder-based localization now done in i18n-manager
+ //
+ var default_icon_filename = "default-icon.png",
+ default_icon_src = session.conf.DEFAULT_ICON,
+ default_icon_dst = session.sourceDir;
+
+ processSplashScreenIconSrc(data, widgetConfig, "icon");
+
+ if (!widgetConfig.icon) {
+ packagerUtils.copyFile(default_icon_src, default_icon_dst);
+
+ widgetConfig["icon"] = [];
+ widgetConfig["icon"].push(default_icon_filename);
+ }
+}
+
+function validateSplashScreensIcon(widgetConfig, key) {
+ if (widgetConfig[key]) {
+ var msg = localize.translate(key === "icon" ? "EXCEPTION_INVALID_ICON_SRC" : "EXCEPTION_INVALID_SPLASH_SRC");
+
+ if (widgetConfig[key].length === 0) {
+ // element without src attribute
+ throw msg;
+ } else {
+ widgetConfig[key].forEach(function (src) {
+ var msg2 = localize.translate(key === "icon" ? "EXCEPTION_INVALID_ICON_SRC_LOCALES" : "EXCEPTION_INVALID_SPLASH_SRC_LOCALES");
+
+ // check that src attribute is specified and is not empty
+ check(src, msg).notNull();
+
+ // check that src attribute does not start with reserved locales folder
+ src = src.replace(/\\/g, "/");
+ check(src, msg2).notRegex("^" + i18nMgr.LOCALES_DIR + "\/");
+ });
+ }
+
+ }
+}
+
+function processAuthorData(data, widgetConfig) {
+ if (data.author) {
+ var attribs = data.author["@"];
+
+ if (!attribs && typeof data.author === "string") {
+ //do not sanitize empty objects {} (must be string)
+ widgetConfig.author = sanitize(data.author).trim();
+ } else if (data.author["#"]) {
+ widgetConfig.author = sanitize(data.author["#"]).trim();
+ }
+
+ if (attribs) {
+ widgetConfig.authorURL = attribs.href;
+ widgetConfig.copyright = attribs["rim:copyright"];
+ widgetConfig.authorEmail = attribs.email;
+ }
+ }
+}
+
+function processLicenseData(data, widgetConfig) {
+ if (data.license && data.license["#"]) {
+ widgetConfig.license = data.license["#"];
+ } else {
+ widgetConfig.license = "";
+ }
+
+ if (data.license && data.license["@"]) {
+ widgetConfig.licenseURL = data.license["@"].href;
+ } else {
+ widgetConfig.licenseURL = "";
+ }
+}
+
+function processContentData(data, widgetConfig) {
+ if (data.content) {
+ var attribs = data.content["@"],
+ startPage;
+ if (attribs) {
+ widgetConfig.content = attribs.src;
+
+ startPage = packagerUtils.parseUri(attribs.src);
+
+ // if start page is local but does not start with local:///, will prepend it
+ // replace any backslash with forward slash
+ if (!packagerUtils.isAbsoluteURI(startPage) && !packagerUtils.isLocalURI(startPage)) {
+ if (!startPage.relative.match(/^\//)) {
+ widgetConfig.content = "local:///" + startPage.relative.replace(/\\/g, "/");
+ } else {
+ widgetConfig.content = "local://" + startPage.relative.replace(/\\/g, "/");
+ }
+ }
+
+ widgetConfig.foregroundSource = attribs.src;
+ widgetConfig.contentType = attribs.type;
+ widgetConfig.contentCharSet = attribs.charset;
+ widgetConfig.allowInvokeParams = attribs["rim:allowInvokeParams"];
+ //TODO content rim:background
+ }
+ }
+}
+
+function processPermissionsData(data, widgetConfig) {
+ if (data["rim:permissions"] && data["rim:permissions"]["rim:permit"]) {
+ var permissions = data["rim:permissions"]["rim:permit"];
+
+ if (permissions instanceof Array) {
+ widgetConfig.permissions = permissions;
+ } else {
+ //user entered one permission and it comes in as an object
+ widgetConfig.permissions = [permissions];
+ }
+ } else {
+ widgetConfig.permissions = [];
+ }
+
+ // We do NOT want to auto defer networking and JavaScript if the
+ // run_when_backgrounded permission is set
+ if (widgetConfig.permissions.indexOf("run_when_backgrounded") >= 0) {
+ widgetConfig.autoDeferNetworkingAndJavaScript = false;
+ }
+}
+
+function processInvokeTargetsData(data, widgetConfig) {
+
+ if (data["rim:invoke-target"]) {
+ widgetConfig["invoke-target"] = data["rim:invoke-target"];
+
+ //If invoke-target is not an array, wrap the invoke-target in an array
+ utils.wrapPropertyInArray(widgetConfig, "invoke-target");
+
+ widgetConfig["invoke-target"].forEach(function (invokeTarget) {
+ if (invokeTarget.type && !packagerUtils.isEmpty(invokeTarget.type)) {
+ invokeTarget.type = invokeTarget.type.toUpperCase();
+ }
+
+ if (invokeTarget.filter) {
+ utils.wrapPropertyInArray(invokeTarget, "filter");
+
+ invokeTarget.filter.forEach(function (filter) {
+
+ if (filter["action"]) {
+ utils.wrapPropertyInArray(filter, "action");
+ }
+
+ if (filter["mime-type"]) {
+ utils.wrapPropertyInArray(filter, "mime-type");
+ }
+
+ if (filter["property"]) {
+ utils.wrapPropertyInArray(filter, "property");
+ }
+ });
+ }
+ });
+ }
+}
+
+function validateConfig(widgetConfig) {
+ check(widgetConfig.version, localize.translate("EXCEPTION_INVALID_VERSION"))
+ .notNull()
+ .regex("^[0-9]{1,3}([.][0-9]{1,3}){2,3}$");
+
+ for (var prop in widgetConfig.name) {
+ if (widgetConfig.name.hasOwnProperty(prop)) {
+ check(widgetConfig.name[prop], localize.translate("EXCEPTION_INVALID_NAME")).notEmpty();
+ }
+ }
+
+ check(widgetConfig.author, localize.translate("EXCEPTION_INVALID_AUTHOR")).notNull();
+ check(widgetConfig.id, localize.translate("EXCEPTION_INVALID_ID")).notNull().notEmpty();
+ check(widgetConfig.content, localize.translate("EXCEPTION_INVALID_CONTENT"))
+ .notNull()
+ .notEmpty();
+
+ validateSplashScreensIcon(widgetConfig, "rim:splash");
+
+ validateSplashScreensIcon(widgetConfig, "icon");
+
+ if (widgetConfig.accessList) {
+ widgetConfig.accessList.forEach(function (access) {
+ if (access.uri) {
+ if (access.uri !== "WIDGET_LOCAL") {
+ check(access.uri, localize.translate("EXCEPTION_INVALID_ACCESS_URI_NO_PROTOCOL", access.uri))
+ .regex("^[a-zA-Z]+:\/\/");
+ check(access.uri, localize.translate("EXCEPTION_INVALID_ACCESS_URI_NO_URN", access.uri))
+ .notRegex("^[a-zA-Z]+:\/\/$");
+ }
+ }
+
+ if (access.features) {
+ // Assert each feature has a proper ID and is not empty
+ access.features.forEach(function (feature) {
+ if (!feature) {
+ throw localize.translate("EXCEPTION_INVALID_FEATURE_ID");
+ }
+ check(feature.id, localize.translate("EXCEPTION_INVALID_FEATURE_ID")).notNull().notEmpty();
+ });
+ }
+
+ });
+ }
+
+ if (widgetConfig["invoke-target"]) {
+
+ widgetConfig["invoke-target"].forEach(function (invokeTarget) {
+
+ check(typeof invokeTarget["@"] === "undefined",
+ localize.translate("EXCEPTION_INVOKE_TARGET_INVALID_ID"))
+ .equals(false);
+ check(invokeTarget["@"].id, localize.translate("EXCEPTION_INVOKE_TARGET_INVALID_ID"))
+ .notNull()
+ .notEmpty();
+ check(invokeTarget.type, localize.translate("EXCEPTION_INVOKE_TARGET_INVALID_TYPE"))
+ .notNull()
+ .notEmpty();
+
+ if (invokeTarget.filter) {
+
+ invokeTarget.filter.forEach(function (filter) {
+
+ check(filter["action"] && filter["action"] instanceof Array && filter["action"].length > 0,
+ localize.translate("EXCEPTION_INVOKE_TARGET_ACTION_INVALID"))
+ .equals(true);
+
+ check(filter["mime-type"] && filter["mime-type"] instanceof Array && filter["mime-type"].length > 0,
+ localize.translate("EXCEPTION_INVOKE_TARGET_MIME_TYPE_INVALID"))
+ .equals(true);
+
+ if (filter.property) {
+ filter.property.forEach(function (property) {
+ check(property["@"] && property["@"]["var"] && typeof property["@"]["var"] === "string",
+ localize.translate("EXCEPTION_INVOKE_TARGET_FILTER_PROPERTY_INVALID"))
+ .equals(true);
+ });
+ }
+ });
+ }
+ });
+ }
+}
+
+function processLocalizedText(tag, data, widgetConfig) {
+ var tagData = data[tag],
+ DEFAULT = 'default';
+
+ function processLanguage(tagElement) {
+ var attribs = tagElement['@'],
+ language;
+
+ if (attribs) {
+ language = attribs['xml:lang'] || DEFAULT;
+ widgetConfig[tag][language.toLowerCase()] = tagElement['#'];
+ } else {
+ widgetConfig[tag][DEFAULT] = tagElement;
+ }
+ }
+
+ if (Array.isArray(tagData)) {
+ //i.e. <element xml:lang="en">english value</element>
+ // <element xml:lang="fr">french value</element>
+ tagData.forEach(processLanguage);
+ } else if (tagData instanceof Object) {
+ //i.e. <element xml:lang="en">english value</element>
+ processLanguage(tagData);
+ } else {
+ //i.e <element>value</element>
+ widgetConfig[tag][DEFAULT] = tagData;
+ }
+}
+
+function processNameAndDescription(data, widgetConfig) {
+ widgetConfig.name = {};
+ widgetConfig.description = {};
+
+ processLocalizedText('name', data, widgetConfig);
+ processLocalizedText('description', data, widgetConfig);
+}
+
+function processCordovaPreferences(data, widgetConfig) {
+ if (data.preference) {
+ var preference = processParamObj(data.preference);
+ widgetConfig.packageCordovaJs = preference.packageCordovaJs === "enable";
+ widgetConfig.autoHideSplashScreen = preference.AutoHideSplashScreen !== "false";
+ }
+}
+
+function processResult(data, session) {
+ var widgetConfig = {};
+
+ processWidgetData(data, widgetConfig, session);
+ processIconData(data, widgetConfig, session);
+ processAuthorData(data, widgetConfig);
+ processLicenseData(data, widgetConfig);
+ processContentData(data, widgetConfig);
+ processPermissionsData(data, widgetConfig);
+ processInvokeTargetsData(data, widgetConfig);
+ processSplashScreenData(data, widgetConfig);
+ processNameAndDescription(data, widgetConfig);
+ processCordovaPreferences(data, widgetConfig);
+
+ widgetConfig.configXML = "config.xml";
+
+ //validate the widgetConfig
+ validateConfig(widgetConfig);
+
+ //special handling for version and grabbing the buildId if specified (4rth number)
+ processVersion(widgetConfig);
+
+ //if --buildId was specified, it takes precedence
+ processBuildID(widgetConfig, session);
+
+ return widgetConfig;
+}
+
+function init() {
+ //Predefined features are features that do NOT contain an API namespace
+ _predefinedFeatures = {
+ "enable-flash" : function (feature, widgetConfig) {
+ widgetConfig.enableFlash = true;
+ },
+ "blackberry.app.orientation": function (feature, widgetConfig) {
+ if (feature) {
+ var params = processParamObj(feature.param),
+ mode = params.mode;
+
+ if (!mode) {
+ //No mode provided, throw error
+ throw localize.translate("EXCEPTION_EMPTY_ORIENTATION_MODE", mode);
+ } else if (mode === "landscape" || mode === "portrait" || mode === "north") {
+ widgetConfig.autoOrientation = false;//Overwrites default value
+ widgetConfig.orientation = mode;
+ } else if (mode !== "auto") {
+ //Mode invalid, throw error
+ throw localize.translate("EXCEPTION_INVALID_ORIENTATION_MODE", mode);
+ }
+
+ // Throw a warning since this feature is deprecated
+ logger.warn(localize.translate("WARNING_ORIENTATION_DEPRECATED"));
+ }
+ }
+ };
+
+ //Hybrid features are features that have both an API namespace and custom parameters
+ _hybridFeatures = {
+ "blackberry.app": function (feature, widgetConfig) {
+ if (feature) {
+ var params = processParamObj(feature.param),
+ bgColor = params.backgroundColor,
+ childBrowser = params.childBrowser,
+ formControl = params.formControl,
+ orientation = params.orientation,
+ theme = params.theme,
+ popupBlocker = params.popupBlocker,
+ websecurity = params.websecurity;
+
+ if (bgColor) {
+ //Convert bgColor to a number
+ bgColor = parseInt(bgColor, 16);
+
+ if (isNaN(bgColor)) {
+ //bgcolor is not a number, throw error
+ throw localize.translate("EXCEPTION_BGCOLOR_INVALID", params.backgroundColor);
+ } else {
+ widgetConfig.backgroundColor = bgColor;
+ }
+ }
+
+ if (childBrowser) {
+ widgetConfig.enableChildWebView = ((childBrowser + '').toLowerCase() === 'disable') === false;
+ }
+
+ if (formControl) {
+ widgetConfig.enableFormControl = ((formControl + '').toLowerCase() === 'disable') === false;
+ }
+
+ if (popupBlocker) {
+ widgetConfig.enablePopupBlocker = ((popupBlocker + '').toLowerCase() === 'enable') === true;
+ }
+
+ if (orientation) {
+ if (orientation === "landscape" || orientation === "portrait" || orientation === "north") {
+ widgetConfig.autoOrientation = false;
+ widgetConfig.orientation = orientation;
+ } else if (orientation !== "auto") {
+ throw localize.translate("EXCEPTION_INVALID_ORIENTATION_MODE", orientation);
+ }
+ }
+
+ if (theme && (typeof theme === "string")) {
+ theme = theme.toLowerCase();
+
+ if (theme === "bright" || theme === "dark" || theme === "inherit" || theme === "default") {
+ widgetConfig.theme = theme;
+ }
+ }
+
+ if (websecurity && (typeof websecurity === "string") && (websecurity.toLowerCase() === "disable")) {
+ widgetConfig.enableWebSecurity = false;
+ logger.warn(localize.translate("WARNING_WEBSECURITY_DISABLED"));
+ }
+ }
+ }
+ };
+}
+
+_self = {
+ parse: function (xmlPath, session, callback) {
+ if (!fs.existsSync(xmlPath)) {
+ throw localize.translate("EXCEPTION_CONFIG_NOT_FOUND");
+ }
+
+ var fileData = fs.readFileSync(xmlPath),
+ xml = utils.bufferToString(fileData),
+ parser = new xml2js.Parser({trim: true, normalize: true, explicitRoot: false});
+
+ init();
+
+ //parse xml file data
+ parser.parseString(xml, function (err, result) {
+ if (err) {
+ logger.error(localize.translate("EXCEPTION_PARSING_XML"));
+ fileManager.cleanSource(session);
+ } else {
+ callback(processResult(result, session));
+ }
+ });
+ }
+};
+
+module.exports = _self;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/debugtoken-helper.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/debugtoken-helper.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/debugtoken-helper.js
new file mode 100755
index 0000000..791973c
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/debugtoken-helper.js
@@ -0,0 +1,211 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var childProcess = require("child_process"),
+ fs = require("fs"),
+ path = require("path"),
+ conf = require("./conf"),
+ localize = require("./localize"),
+ logger = require("./logger"),
+ pkgrUtils = require("./packager-utils"),
+ workingDir = path.normalize(__dirname + "/.."),
+ debugTokenDir = path.normalize(workingDir + "/" + "debugtoken.bar"),
+ properties,
+ targets,
+ deployCallback,
+ self = {};
+
+function generateCreateTokenOptions(pins, password) {
+ var options = [],
+ i;
+
+ options.push("-storepass");
+ options.push(password);
+
+ for (i = 0; i < pins.length; i++) {
+ options.push("-devicepin");
+ options.push(pins[i]);
+ }
+
+ options.push(debugTokenDir);
+
+ return options;
+}
+
+function generateDeployTokenOptions(target) {
+ var options = [];
+
+ options.push("-installDebugToken");
+ options.push(debugTokenDir);
+
+ options.push("-device");
+ options.push(properties.targets[target].ip);
+
+ options.push("-password");
+ options.push(properties.targets[target].password);
+
+ return options;
+}
+
+function execNativeScript(script, options, callback) {
+ var process;
+
+ if (pkgrUtils.isWindows()) {
+ script += ".bat";
+ }
+
+ if (fs.existsSync(conf.DEPENDENCIES_TOOLS)) {
+ process = childProcess.spawn(path.normalize(conf.DEPENDENCIES_TOOLS + script), options, {
+ "cwd" : workingDir,
+ "env" : process ? process.env : undefined
+ });
+
+ process.stdout.on("data", pkgrUtils.handleProcessOutput);
+
+ process.stderr.on("data", pkgrUtils.handleProcessOutput);
+
+ process.on("exit", function (code) {
+ if (callback && typeof callback === "function") {
+ callback(code);
+ }
+ });
+ } else {
+ throw localize.translate("EXCEPTION_MISSING_TOOLS");
+ }
+}
+
+function checkTarget(target) {
+ if (!properties.targets[target]) {
+ logger.warn(localize.translate("WARN_TARGET_NOT_EXIST", target));
+ return false;
+ }
+
+ if (!properties.targets[target].ip) {
+ logger.warn(localize.translate("WARN_IP_NOT_DEFINED", target));
+ return false;
+ }
+
+ if (!properties.targets[target].password) {
+ logger.warn(localize.translate("WARN_PASSWORD_NOT_DEFINED", target));
+ return false;
+ }
+
+ return true;
+
+}
+
+// Deploy the debug token for each target in targets array recursively
+function deployTokenToTargetsRecursively() {
+ var target;
+
+ if (targets.length > 0) {
+ target = targets.pop();
+
+ logger.info(localize.translate("PROGRESS_DEPLOYING_DEBUG_TOKEN", target));
+ if (checkTarget(target)) {
+ execNativeScript("/bin/blackberry-deploy",
+ generateDeployTokenOptions(target),
+ deployTokenToTargetsRecursively
+ );
+ } else {
+ deployTokenToTargetsRecursively();
+ }
+ } else {
+ if (deployCallback && typeof deployCallback === "function") {
+ deployCallback();
+ }
+ }
+}
+
+self.createToken = function (projectProperties, target, keystorepass, callback) {
+ var pins = [],
+ key;
+
+ // Store the global variable "properties"
+ properties = projectProperties;
+
+ // Gather PINs information from properties
+ if (target === "all") {
+ for (key in properties.targets) {
+ if (properties.targets.hasOwnProperty(key) && properties.targets[key].pin) {
+ pins.push(properties.targets[key].pin);
+ }
+ }
+ } else {
+ if (!target) {
+ target = properties.defaultTarget;
+ }
+
+ if (properties.targets.hasOwnProperty(target) && properties.targets[target].pin) {
+ pins.push(properties.targets[target].pin);
+ }
+ }
+
+ if (pins.length === 0) {
+ logger.warn(localize.translate("WARN_NO_DEVICE_PIN_FOUND"));
+ if (callback && typeof callback === "function") {
+ callback(-1);
+ }
+ } else if (!keystorepass) {
+ logger.warn(localize.translate("WARN_NO_SIGNING_PASSWORD_PROVIDED"));
+ if (callback && typeof callback === "function") {
+ callback(-1);
+ }
+ } else {
+ logger.info(localize.translate("PROGRESS_GENERATING_DEBUG_TOKEN"));
+ // Call "blackberry-debugtokenrequest" to generate debug token
+ execNativeScript("/bin/blackberry-debugtokenrequest",
+ generateCreateTokenOptions(pins, keystorepass),
+ callback
+ );
+ }
+};
+
+self.deployToken = function (projectProperties, target, callback) {
+ var key;
+
+ // Store the global variable "properties"
+ properties = projectProperties;
+
+ // Initialize the global variable "targets"
+ targets = [];
+
+ // Store callback so it will be invoked after debug token is deployed to all target(s)
+ deployCallback = callback;
+
+ // Gather targets information from properties
+ // Gather PINs information from properties
+ if (target === "all") {
+ for (key in properties.targets) {
+ if (properties.targets.hasOwnProperty(key) && properties.targets[key].pin) {
+ targets.push(key);
+ }
+ }
+ } else {
+ if (!target) {
+ target = properties.defaultTarget;
+ }
+
+ if (properties.targets.hasOwnProperty(target) && properties.targets[target].pin) {
+ targets.push(target);
+ }
+ }
+
+ // Deploy debug token recursively
+ deployTokenToTargetsRecursively();
+};
+
+module.exports = self;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/file-manager.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/file-manager.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/file-manager.js
new file mode 100755
index 0000000..1ce0cf3
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/file-manager.js
@@ -0,0 +1,208 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var path = require("path"),
+ util = require("util"),
+ packagerUtils = require("./packager-utils"),
+ fs = require("fs"),
+ conf = require("./conf"),
+ BBWPignore = require('./bbwpignore'),
+ wrench = require("wrench"),
+ zip = require("zip"),
+ localize = require("./localize"),
+ logger = require("./logger"),
+ CLIENT_JS = "client.js",
+ SERVER_JS = "index.js",
+ VALID_EXTENSIONS = [".js", ".json"],
+ CORDOVA_JS_REGEX = /(cordova-.+js)|cordova\.js/;
+
+function unzip(from, to) {
+ var data, entries, p, parent;
+
+ if (fs.existsSync(from)) {
+ data = fs.readFileSync(from);
+ entries = zip.Reader(data).toObject();
+
+ if (!fs.existsSync(to)) {
+ wrench.mkdirSyncRecursive(to, "0755");
+ }
+
+ for (p in entries) {
+ if (p.indexOf("__MACOSX") >= 0) {
+ continue;
+ }
+
+ if (p.split("/").length > 1) {
+ parent = p.split("/").slice(0, -1).join("/");
+ wrench.mkdirSyncRecursive(to + "/" + parent, "0755");
+ }
+
+ fs.writeFileSync(to + "/" + p, entries[p]);
+ }
+ } else {
+ throw localize.translate("EXCEPTION_WIDGET_ARCHIVE_NOT_FOUND", from);
+ }
+}
+
+function copyDirContents(from, to) {
+ var files = wrench.readdirSyncRecursive(from),
+ bbwpignore,
+ bbwpignoreFile = path.join(from, conf.BBWP_IGNORE_FILENAME),
+ toBeIgnored = [];
+
+ if (fs.existsSync(bbwpignoreFile)) {
+ bbwpignore = new BBWPignore(bbwpignoreFile, files);
+
+ bbwpignore.matchedFiles.forEach(function (i) {
+ toBeIgnored.push(from + "/" + i);
+ });
+ toBeIgnored.push(from + "/" + conf.BBWP_IGNORE_FILENAME); //add the .bbwpignore file to the ignore list
+ }
+ wrench.copyDirSyncRecursive(from, to, {preserve: true}, function (file) {
+ return toBeIgnored.indexOf(file) === -1;
+ });
+}
+
+function prepare(session) {
+ var conf = session.conf,
+ dest = session.sourcePaths;
+
+ if (fs.existsSync(session.sourceDir)) {
+ wrench.rmdirSyncRecursive(session.sourceDir);
+ }
+
+ // unzip archive
+ if (fs.existsSync(session.archivePath)) {
+ if (session.archivePath.toLowerCase().match("[.]zip$")) {
+ unzip(session.archivePath, session.sourceDir);
+ } else {
+ copyDirContents(session.archivePath, session.sourceDir);
+ }
+ } else {
+ throw localize.translate("EXCEPTION_INVALID_ARCHIVE_PATH", session.archivePath);
+ }
+}
+
+
+function getModulesArray(dest, files, baseDir) {
+ var modulesList = [],
+ EXCLUDE_FILES = ["client.js", "manifest.json"];
+
+ function isExcluded(file) {
+ return EXCLUDE_FILES.some(function (element) {
+ return path.basename(file) === element;
+ });
+ }
+
+ files.forEach(function (file) {
+ file = path.resolve(baseDir, file);
+
+ if (!fs.statSync(file).isDirectory()) {
+ if (baseDir !== dest.EXT || !isExcluded(file)) {
+ modulesList.push({name: path.relative(path.normalize(dest.CHROME), file).replace(/\\/g, "/"), file: file});
+ }
+ }
+ });
+
+ return modulesList;
+}
+
+function generateFrameworkModulesJS(session) {
+ var dest = session.sourcePaths,
+ modulesList = [],
+ modulesStr = "(function () { ",
+ frameworkModulesStr = "window.frameworkModules = [",
+ libFiles = wrench.readdirSyncRecursive(dest.LIB),
+ extFiles,
+ extModules;
+
+ modulesList = modulesList.concat(getModulesArray(dest, libFiles, dest.LIB));
+
+ if (fs.existsSync(dest.EXT)) {
+ extFiles = wrench.readdirSyncRecursive(dest.EXT);
+ extModules = getModulesArray(dest, extFiles, dest.EXT);
+ modulesList = modulesList.concat(extModules);
+ }
+
+ modulesList.forEach(function (module, index) {
+ modulesStr += "define('" + module.name + "', function (require, exports, module) {\n" +
+ fs.readFileSync(module.file, "utf-8") + "\n" +
+ "});\n";
+ frameworkModulesStr += "'" + module.name + "'" + (index !== modulesList.length-1 ? ", " : "");
+ });
+
+ modulesStr += "}());";
+ frameworkModulesStr += "];\n";
+ fs.writeFileSync(path.normalize(dest.CHROME + "/frameworkModules.js"), frameworkModulesStr + modulesStr);
+}
+
+function copyNative(session, target) {
+ var src = path.normalize(session.conf.NATIVE + "/" + target),
+ dest = path.normalize(session.sourceDir);
+
+ copyDirContents(src, dest);
+}
+
+function copyWebworks(session) {
+ var srcPath = path.normalize(session.conf.PROJECT_ROOT + "/lib"),
+ dest = path.normalize(session.sourceDir),
+ srcFiles;
+
+ srcFiles = packagerUtils.listFiles(srcPath, function (file) {
+ return CORDOVA_JS_REGEX.test(file);
+ });
+
+ if (srcFiles.length === 1) {
+ packagerUtils.copyFile(srcFiles[0], dest);
+
+ //Rename file to webworks.js
+ fs.renameSync(path.join(dest, path.basename(srcFiles[0])), path.join(dest, "cordova.js"));
+ } else {
+ throw localize.translate("EXCEPTION_CORDOVA_JS_IN_LIB_DIR", srcFiles.length);
+ }
+}
+
+function hasValidExtension(file) {
+ return VALID_EXTENSIONS.some(function (element, index, array) {
+ return path.extname(file) === element;
+ });
+}
+
+function generateUserConfig(session, config) {
+ packagerUtils.writeFile(path.join(session.sourcePaths.LIB, "config"), "user.js", "module.exports = " + JSON.stringify(config, null, " ") + ";");
+}
+
+module.exports = {
+ unzip: unzip,
+
+ copyNative: copyNative,
+
+ copyWebworks : copyWebworks,
+
+ prepareOutputFiles: prepare,
+
+ generateFrameworkModulesJS: generateFrameworkModulesJS,
+
+ generateUserConfig: generateUserConfig,
+
+ cleanSource: function (session) {
+ if (!session.keepSource) {
+ wrench.rmdirSyncRecursive(session.sourceDir);
+ }
+ },
+
+ copyDirContents: copyDirContents
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/i18n-manager.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/i18n-manager.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/i18n-manager.js
new file mode 100644
index 0000000..3aa1645
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/i18n-manager.js
@@ -0,0 +1,146 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*jshint sub:true*/
+var path = require("path"),
+ fs = require("fs"),
+ wrench = require("wrench"),
+ pkgrUtils = require("./packager-utils"),
+ LOCALES_DIR = "locales";
+
+// Given a list of locale files (as follows), based on un-localized splash/icon definition, generate
+// localized splash/icon metadata.
+//
+// zh-hans-cn/a.gif
+// zh-hans-cn/f.gif
+// zh-hans-cn/images/splash-1024x600.png
+// zh-hans-cn/images/splash-600x1024.png
+// zh-hans/a.gif
+// zh-hans/b.gif
+// zh/a.gif
+// zh/b.gif
+// zh/c.gif
+function generateLocalizedMetadataForSplashScreenIcon(config, configKey, xmlObject, xmlObjectKey, localeFiles) {
+ // localeMap looks like this:
+ // {
+ // "zh-hans-cn": ["a.gif", "f.gif", "images/splash-1024x600.png", "images/splash-600x1024.png"],
+ // "zh-hans": ["a.gif", "b.gif"],
+ // "zh": ["a.gif", "b.gif", "c.gif"]
+ // }
+ var localeMap = {};
+
+ if (localeFiles) {
+ localeFiles.forEach(function (path) {
+ var splitted = path.replace(/\.\./g, "").split("/"),
+ locale;
+
+ splitted = splitted.filter(function (element) {
+ return element.length > 0;
+ });
+
+ if (splitted.length > 1) {
+ locale = splitted[0];
+
+ if (!localeMap[locale]) {
+ localeMap[locale] = [];
+ }
+
+ // remove locale subfolder from path
+ splitted.splice(0, 1);
+ localeMap[locale].push(splitted.join("/"));
+ }
+ });
+ }
+
+ xmlObject[xmlObjectKey] = {};
+ xmlObject[xmlObjectKey]["image"] = [];
+
+ if (config[configKey]) {
+ config[configKey].forEach(function (imgPath) {
+ imgPath = imgPath.replace(/\\/g, "/"); // replace any backslash with forward slash
+
+ Object.getOwnPropertyNames(localeMap).forEach(function (locale) {
+ if (localeMap[locale].indexOf(imgPath) !== -1) {
+ // localized image found for locale
+ xmlObject[xmlObjectKey]["image"].push({
+ text: {
+ _attr: {
+ "xml:lang": locale
+ },
+ _value: LOCALES_DIR + "/" + locale + "/" + imgPath
+ }
+ });
+ }
+ });
+
+ xmlObject[xmlObjectKey]["image"].push({
+ _value: imgPath
+ });
+ });
+ }
+}
+
+function generateLocalizedText(session, config, xmlObject, key) {
+ var localizedText = config[key],
+ textElements = [],
+ locale;
+
+ for (locale in localizedText) {
+ if (localizedText.hasOwnProperty(locale)) {
+ //Don't add default locale and don't add locale if it already exists
+ if (locale !== 'default' && textElements && textElements.indexOf(locale) === -1) {
+ textElements.push({
+ _attr: {
+ "xml:lang": locale
+ },
+ _value: localizedText[locale]
+ });
+ }
+ }
+ }
+
+ xmlObject[key] = {
+ _value: localizedText['default'],
+ text: textElements
+ };
+}
+
+function generateLocalizedMetadata(session, config, xmlObject, key) {
+ if (config.icon || config["rim:splash"]) {
+ var localeFiles,
+ normalizedLocaleFiles = [];
+
+ if (fs.existsSync(session.sourceDir + "/" + LOCALES_DIR)) {
+ localeFiles = wrench.readdirSyncRecursive(session.sourceDir + "/" + LOCALES_DIR);
+ if (pkgrUtils.isWindows()) {
+
+ localeFiles.forEach(function (file) {
+ file = path.relative(path.resolve(session.sourceDir, "locales"), file).replace(/\\/g, "/");
+ normalizedLocaleFiles.push(file);
+ });
+ } else {
+ normalizedLocaleFiles = localeFiles;
+ }
+ }
+
+ generateLocalizedMetadataForSplashScreenIcon(config, key, xmlObject, key === "rim:splash" ? "splashScreens" : key, normalizedLocaleFiles);
+ }
+}
+
+module.exports = {
+ LOCALES_DIR: LOCALES_DIR,
+ generateLocalizedMetadata: generateLocalizedMetadata,
+ generateLocalizedText: generateLocalizedText
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/localize.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/localize.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/localize.js
new file mode 100644
index 0000000..04e89ac
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/localize.js
@@ -0,0 +1,207 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var Localize = require("localize"),
+ loc = new Localize({
+ "EXCEPTION_NATIVEPACKAGER": {
+ "en": "Native Packager exception occurred"
+ },
+ "EXCEPTION_WIDGET_ARCHIVE_NOT_FOUND": {
+ "en": "Failed to find WebWorks archive: $[1]"
+ },
+ "EXCEPTION_MISSING_SIGNING_KEY_FILE": {
+ "en": "Cannot sign application - failed to find signing key file: $[1]"
+ },
+ "WARNING_MISSING_SIGNING_KEY_FILE": {
+ "en": "Build ID set in config.xml [version], but signing key file was not found: $[1]"
+ },
+ "EXCEPTION_MISSING_SIGNING_PASSWORD": {
+ "en": "Cannot sign application - No signing password provided [-g]"
+ },
+ "WARNING_SIGNING_PASSWORD_EXPECTED": {
+ "en": "Build ID set in config.xml [version], but no signing password was provided [-g]. Bar will be unsigned"
+ },
+ "EXCEPTION_MISSING_SIGNING_BUILDID": {
+ "en": "Cannot sign application - No buildId provided [--buildId]"
+ },
+ "EXCEPTION_DEBUG_TOKEN_NOT_FOUND": {
+ "en": "Failed to find debug token"
+ },
+ "EXCEPTION_DEBUG_TOKEN_WRONG_FILE_EXTENSION": {
+ "en": "Specified debug token not a .bar extension"
+ },
+ "PROGRESS_SESSION_CONFIGXML": {
+ "en": "Parsing config.xml"
+ },
+ "PROGRESS_FILE_POPULATING_SOURCE": {
+ "en": "Populating application source"
+ },
+ "PROGRESS_GEN_OUTPUT": {
+ "en": "Generating output files"
+ },
+ "PROGRESS_PACKAGING": {
+ "en": "Packaging the BAR file"
+ },
+ "PROGRESS_COMPLETE": {
+ "en": "BAR packaging complete"
+ },
+ "EXCEPTION_PARSING_XML": {
+ "en": "An error has occurred parsing the config.xml. Please ensure that it is syntactically correct"
+ },
+ "EXCEPTION_INVALID_VERSION": {
+ "en": "Please enter a valid application version"
+ },
+ "EXCEPTION_INVALID_NAME": {
+ "en": "Please enter a valid application name"
+ },
+ "EXCEPTION_INVALID_AUTHOR": {
+ "en": "Please enter an author for the application"
+ },
+ "EXCEPTION_INVALID_ID": {
+ "en": "Please enter an application id"
+ },
+ "EXCEPTION_INVALID_CONTENT": {
+ "en": "Invalid config.xml - failed to parse the <content> element(Invalid source or the source is not specified.)"
+ },
+ "EXCEPTION_INVALID_FEATURE_ID": {
+ "en": "Invalid <feature> element - failed to find the id attribute"
+ },
+ "EXCEPTION_BUFFER_ERROR": {
+ "en": "ERROR in bufferToString(): Buffer length must be even"
+ },
+ "EXCEPTION_FEATURE_DEFINED_WITH_WILDCARD_ACCESS_URI": {
+ "en": "Invalid config.xml - no <feature> tags are allowed for this <access> element"
+ },
+ "EXCEPTION_INVALID_ACCESS_URI_NO_PROTOCOL": {
+ "en": "Invalid URI attribute in the access element - protocol required($[1])"
+ },
+ "EXCEPTION_INVALID_ACCESS_URI_NO_URN": {
+ "en": "Failed to parse the URI attribute in the access element($[1])"
+ },
+ "EXCEPTION_CMDLINE_ARG_INVALID": {
+ "en": "Invalid command line argument \"$[1]\""
+ },
+ "EXCEPTION_INVOKE_TARGET_INVALID_ID": {
+ "en": "Each rim:invoke-target element must specify a valid id attribute"
+ },
+ "EXCEPTION_INVOKE_TARGET_INVALID_TYPE": {
+ "en": "rim:invoke-target element must be specified and cannot be empty"
+ },
+ "EXCEPTION_INVOKE_TARGET_ACTION_INVALID": {
+ "en": "Each filter element must specify at least one valid action"
+ },
+ "EXCEPTION_INVOKE_TARGET_MIME_TYPE_INVALID": {
+ "en": "Each filter element must specify at least one valid mime-type"
+ },
+ "EXCEPTION_INVOKE_TARGET_FILTER_PROPERTY_INVALID": {
+ "en": "At least one property element in an invoke filter is invalid"
+ },
+ "EXCEPTION_INVALID_ICON_SRC": {
+ "en": "Icon src cannot be empty"
+ },
+ "EXCEPTION_INVALID_SPLASH_SRC": {
+ "en": "Splash src cannot be empty"
+ },
+ "EXCEPTION_INVALID_ICON_SRC_LOCALES": {
+ "en": "Icon src should not point to files under \"locales\" folder, bbwp will perform folder-based localization"
+ },
+ "EXCEPTION_INVALID_SPLASH_SRC_LOCALES": {
+ "en": "Splash src should not point to files under \"locales\" folder, bbwp will perform folder-based localization"
+ },
+ "EXCEPTION_EXTENSION_CIRCULAR_DEPENDENCY": {
+ "en": "Circular dependency detected for extension: \"$[1]\""
+ },
+ "EXCEPTION_EXTENSION_NOT_FOUND": {
+ "en": "Extension \"$[1]\" not found in \"ext\" folder"
+ },
+ "EXCEPTION_PARAMS_FILE_ERROR": {
+ "en": "An error has occurred parsing \"$[1]\""
+ },
+ "EXCEPTION_PARAMS_FILE_NOT_FOUND": {
+ "en": "\"$[1]\" does not exist"
+ },
+ "EXCEPTION_MISSING_TOOLS": {
+ "en": "BBNDK tools could not be found. Please ensure you have installed the BlackBerry Native SDK [http://developer.blackberry.com/native/] and have the PATH configured via bbndk-env script."
+ },
+ "EXCEPTION_INVALID_ORIENTATION_MODE": {
+ "en": "\"$[1]\" is not a valid orientation mode"
+ },
+ "EXCEPTION_EMPTY_ORIENTATION_MODE": {
+ "en": "blackberry.app.orientation parameter \"mode\" missing"
+ },
+ "EXCEPTION_BGCOLOR_INVALID" : {
+ "en": "Background color \"$[1]\" is not a valid number"
+ },
+ "EXCEPTION_CONFIG_NOT_FOUND" : {
+ "en": "No config.xml file was found at the root of the .zip file"
+ },
+ "EXCEPTION_CORDOVA_JS_IN_LIB_DIR" : {
+ "en": "$[1] cordova.js files found in lib"
+ },
+ "WARN_CORDOVA_JS_PACKAGED" : {
+ "en": "cordova.js is now packaged as local:///chrome/cordova.js"
+ },
+ "WARN_WEBPLATFORM_JS_PACKAGED" : {
+ "en": "webplatform.js has been packaged as an alternative to the on device version"
+ },
+ "WARN_WEBPLATFORM_I18N_PACKAGED" : {
+ "en": "i18n.js has been packaged as an alternative to the on device version"
+ },
+ "EXCEPTION_INVALID_ARCHIVE_PATH" : {
+ "en": "An archive or directory does not exist at the path specified: \"$[1]\""
+ },
+ "EXCEPTION_APPDESC_NOT_FOUND" : {
+ "en": "The bar descriptor file does not exist at the path specified: \"$[1]\""
+ },
+ "WARNING_ORIENTATION_DEPRECATED": {
+ "en": "blackberry.app.orientation has been deprecated, please use blackberry.app instead"
+ },
+ "WARNING_WEBSECURITY_DISABLED": {
+ "en": "You have disabled all web security in this WebWorks application"
+ },
+ "PROGRESS_WILL_CREATE_DEBUG_TOKEN": {
+ "en": "Will create debug token"
+ },
+ "PROGRESS_WILL_DEPLOY_DEBUG_TOKEN": {
+ "en": "Will deploy debug token"
+ },
+ "WARN_TARGET_NOT_EXIST": {
+ "en": "The target \"$[1]\" does not exist"
+ },
+ "WARN_IP_NOT_DEFINED": {
+ "en": "IP is not defined in target \"$[1]\""
+ },
+ "WARN_PASSWORD_NOT_DEFINED": {
+ "en": "Password is not defined in target \"$[1]\""
+ },
+ "PROGRESS_DEPLOYING_DEBUG_TOKEN": {
+ "en": "Deploying debug token to target \"$[1]\""
+ },
+ "WARN_NO_DEVICE_PIN_FOUND": {
+ "en": "No device PIN found, will omit debug token generation"
+ },
+ "WARN_NO_SIGNING_PASSWORD_PROVIDED": {
+ "en": "No signing password provided, will omit debug token generation"
+ },
+ "PROGRESS_GENERATING_DEBUG_TOKEN": {
+ "en": "Generating debug token"
+ }
+
+ }, "", ""); // TODO maybe a bug in localize, must set default locale to "" in order get it to work
+
+loc.setLocale("en");
+
+module.exports = loc;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/logger.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/logger.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/logger.js
new file mode 100644
index 0000000..6cab576
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/logger.js
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var level = 'verbose';
+
+module.exports = {
+ level: function (value) {
+ level = value;
+ },
+ info: function (msg) {
+ if (level === 'verbose') {
+ console.log("[INFO] " + msg);
+ }
+ },
+ error: function (msg) {
+ console.log("[ERROR] " + msg);
+ },
+ warn: function (msg) {
+ if (level !== 'error') {
+ console.log("[WARN] " + msg);
+ }
+ },
+ log: function (msg) {
+ console.log("[BUILD] " + msg);
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/native-packager.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/native-packager.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/native-packager.js
new file mode 100644
index 0000000..d9fe3a2
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/native-packager.js
@@ -0,0 +1,288 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*jshint sub:true*/
+var childProcess = require("child_process"),
+ fs = require("fs"),
+ path = require("path"),
+ util = require("util"),
+ data2xml = require("../third_party/data2xml/data2xml"),
+ wrench = require("wrench"),
+ conf = require("./conf"),
+ logger = require("./logger"),
+ localize = require("./localize"),
+ pkgrUtils = require("./packager-utils"),
+ i18nMgr = require("./i18n-manager"),
+ NL = pkgrUtils.isWindows() ? "\r\n" : "\n";
+
+function generateTabletXMLFile(session, config) {
+ var files = wrench.readdirSyncRecursive(session.sourceDir),
+ xmlObject = {
+ id : config.id,
+ versionNumber : config.version,
+ author : config.author,
+ asset : [{
+ _attr : { entry : 'true', type : 'qnx/elf' },
+ _value : 'wwe'
+ }],
+ entryPointType : {
+ _value : "Qnx/WebKit"
+ },
+ cascadesTheme : {
+ _value : config.theme
+ },
+ initialWindow : {
+ systemChrome : 'none',
+ transparent : 'true',
+ autoOrients : 'true'
+ },
+ env : [{
+ _attr : { value : '2.0.0', var : 'WEBWORKS_VERSION'}
+ }],
+ permission : [{
+ _attr : { system : 'true'},
+ _value : 'run_native'
+ }, {
+ // hardcoded access_internet to ensure user has internet (whitelist takes care of security)
+ _attr : { system : 'false'},
+ _value : 'access_internet'
+ }]
+ };
+
+ // If appdesc is specified, use it as the bar descriptor
+ if (session.appdesc) {
+ pkgrUtils.copyFile(session.appdesc, session.sourceDir);
+ return;
+ }
+
+ //Enable slog2 output if debugging
+ if (session.debug) {
+ xmlObject.env.push({
+ _attr : { value : 'slog2', 'var' : 'CONSOLE_MODE' }
+ });
+ }
+
+ //Write user specified permissions
+ if (config.permissions) {
+ config.permissions.forEach(function (permission) {
+ var permissionAttr,
+ permissionValue;
+
+ if (typeof permission === "string") {
+ //Permission with no attributes
+ permissionValue = permission;
+ } else if (permission["@"] && permission["#"]) {
+ //Permission with attributes
+ permissionAttr = permission["@"];
+ permissionValue = permission["#"];
+ }
+
+ if (permissionValue) {
+ xmlObject.permission.push({
+ _attr : permissionAttr,
+ _value : permissionValue
+ });
+ }
+ });
+ }
+
+ i18nMgr.generateLocalizedText(session, config, xmlObject, "name");
+
+ if (config.description) {
+ i18nMgr.generateLocalizedText(session, config, xmlObject, "description");
+ }
+
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "icon");
+ i18nMgr.generateLocalizedMetadata(session, config, xmlObject, "rim:splash");
+
+ if (config["invoke-target"]) {
+ xmlObject["invoke-target"] = [];
+
+ config["invoke-target"].forEach(function (invokeTarget) {
+
+ var xmlInvokeTarget = {
+ "_attr" : { id : invokeTarget["@"]["id"] },
+ "entry-point" : config.name,
+ "type" : invokeTarget["type"]
+ };
+
+ if (invokeTarget["require-source-permissions"]) {
+ xmlInvokeTarget["require-source-permissions"] = {
+ _value : invokeTarget["require-source-permissions"]
+ };
+ }
+
+ if (invokeTarget.filter) {
+ xmlInvokeTarget.filter = [];
+ invokeTarget.filter.forEach(function (filter) {
+ var xmlFilter = {
+ "action" : filter.action,
+ "mime-type": filter["mime-type"]
+ };
+
+ if (filter.property) {
+ xmlFilter.property = [];
+ filter.property.forEach(function (property) {
+ xmlFilter.property.push({
+ "_attr": { var : property["@"]["var"], value : property["@"].value }
+ });
+ });
+ }
+
+ xmlInvokeTarget.filter.push(xmlFilter);
+ });
+ }
+
+ xmlObject["invoke-target"].push(xmlInvokeTarget);
+
+ });
+ }
+
+ //buildId
+ if (config.buildId) {
+ xmlObject.buildId = config.buildId;
+ }
+
+ if (files) {
+ files.forEach(function (file) {
+ file = path.resolve(session.sourceDir, file);
+
+ if (file.indexOf(conf.BAR_DESCRIPTOR) < 0 && !fs.statSync(file).isDirectory()) {
+ file = file.replace(/\\/g, "/");
+ file = file.split("src/")[1];
+
+ if (path.extname(file) === ".so") {
+ xmlObject.asset.push({
+ _attr : { type : 'qnx/elf' },
+ _value : file
+ });
+ } else {
+ xmlObject.asset.push({
+ _value : file
+ });
+ }
+ }
+ });
+ }
+
+ //Add orientation mode
+ if (config.orientation) {
+ xmlObject.initialWindow.aspectRatio = config.orientation;
+ }
+
+ //Add auto orientation
+ xmlObject.initialWindow.autoOrients = config.autoOrientation;
+
+ pkgrUtils.writeFile(session.sourceDir, conf.BAR_DESCRIPTOR, data2xml('qnx', xmlObject));
+}
+
+function generateOptionsFile(session, target, config) {
+ var srcFiles = wrench.readdirSyncRecursive(session.sourceDir),
+ isSigning = session.isSigningRequired(config),
+ optionsStr = "-package" + NL,
+ debugToken,
+ params = session.getParams("blackberry-nativepackager");
+
+ //if -d was provided and we are not signing [-g], set debugToken
+ if (session.debug && !isSigning) {
+ if (path.extname(conf.DEBUG_TOKEN) === ".bar") {
+ if (fs.existsSync(conf.DEBUG_TOKEN)) {
+ debugToken = "-debugToken" + NL;
+ debugToken += conf.DEBUG_TOKEN + NL;
+ }
+ else {
+ logger.warn(localize.translate("EXCEPTION_DEBUG_TOKEN_NOT_FOUND"));
+ }
+ } else {
+ logger.warn(localize.translate("EXCEPTION_DEBUG_TOKEN_WRONG_FILE_EXTENSION"));
+ }
+ }
+
+ if (target === "device" && isSigning) {
+ optionsStr += "-buildId" + NL;
+ optionsStr += config.buildId + NL;
+ } else if (session.debug) {
+ //DebugToken params
+ optionsStr += "-devMode" + NL;
+ optionsStr += (debugToken ? debugToken : "");
+ }
+
+ if (params) {
+ Object.getOwnPropertyNames(params).forEach(function (p) {
+ optionsStr += p + NL;
+
+ if (params[p]) {
+ optionsStr += params[p] + NL;
+ }
+ });
+ }
+
+ optionsStr += path.resolve(util.format(session.barPath, target)) + NL;
+
+ //to supoprt splash screens/icons for multiple resolutions/devices
+ optionsStr += "-barVersion" + NL;
+ optionsStr += "1.5" + NL;
+
+ optionsStr += "-C" + NL;
+ optionsStr += session.sourceDir + NL;
+ optionsStr += conf.BAR_DESCRIPTOR + NL;
+
+ srcFiles.forEach(function (file) {
+ file = path.resolve(session.sourceDir, file);
+
+ if (file.indexOf(conf.BAR_DESCRIPTOR) < 0 && !fs.statSync(file).isDirectory()) {
+ optionsStr += file + NL;
+ }
+ });
+
+ fs.writeFileSync(path.normalize(session.sourceDir + "/options"), optionsStr);
+}
+
+function execNativePackager(session, callback) {
+ var script = "/bin/blackberry-nativepackager",
+ cwd = session.sourceDir,
+ nativePkgr;
+
+ if (pkgrUtils.isWindows()) {
+ script += ".bat";
+ }
+
+ if (fs.existsSync(conf.DEPENDENCIES_TOOLS)) {
+ nativePkgr = childProcess.spawn(path.normalize(conf.DEPENDENCIES_TOOLS + script), ["@options"], {
+ "cwd": cwd,
+ "env": process.env
+ });
+
+ nativePkgr.stdout.on("data", pkgrUtils.handleProcessOutput);
+
+ nativePkgr.stderr.on("data", pkgrUtils.handleProcessOutput);
+
+ nativePkgr.on("exit", function (code) {
+ if (callback && typeof callback === "function") {
+ callback(code);
+ }
+ });
+ } else {
+ throw localize.translate("EXCEPTION_MISSING_TOOLS");
+ }
+}
+
+module.exports = {
+ exec: function (session, target, config, callback) {
+ generateOptionsFile(session, target, config);
+ generateTabletXMLFile(session, config);
+ execNativePackager(session, callback);
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager-utils.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager-utils.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager-utils.js
new file mode 100644
index 0000000..09465e8
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager-utils.js
@@ -0,0 +1,176 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var fs = require('fs'),
+ path = require('path'),
+ wrench = require('wrench'),
+ localize = require("./localize"),
+ logger = require("./logger"),
+ os = require('os'),
+ _self;
+
+function swapBytes(buffer) {
+ var l = buffer.length,
+ i,
+ a;
+
+ if (l % 2 === 0x01) {
+ throw localize.translate("EXCEPTION_BUFFER_ERROR");
+ }
+
+ for (i = 0; i < l; i += 2) {
+ a = buffer[i];
+ buffer[i] = buffer[i + 1];
+ buffer[i + 1] = a;
+ }
+
+ return buffer;
+}
+
+_self = {
+ writeFile: function (fileLocation, fileName, fileData) {
+ //If directory does not exist, create it.
+ if (!fs.existsSync(fileLocation)) {
+ wrench.mkdirSyncRecursive(fileLocation, "0755");
+ }
+
+ fs.writeFileSync(path.join(fileLocation, fileName), fileData);
+ },
+
+ copyFile: function (srcFile, destDir, baseDir) {
+ var filename = path.basename(srcFile),
+ fileBuffer = fs.readFileSync(srcFile),
+ fileLocation;
+
+ //if a base directory was provided, determine
+ //folder structure from the relative path of the base folder
+ if (baseDir && srcFile.indexOf(baseDir) === 0) {
+ fileLocation = srcFile.replace(baseDir, destDir);
+ wrench.mkdirSyncRecursive(path.dirname(fileLocation), "0755");
+ fs.writeFileSync(fileLocation, fileBuffer);
+ } else {
+ fs.writeFileSync(path.join(destDir, filename), fileBuffer);
+ }
+ },
+
+ listFiles: function (directory, filter) {
+ var files = wrench.readdirSyncRecursive(directory),
+ filteredFiles = [];
+
+ files.forEach(function (file) {
+ //On mac wrench.readdirSyncRecursive does not return absolute paths, so resolve one.
+ file = path.resolve(directory, file);
+
+ if (filter(file)) {
+ filteredFiles.push(file);
+ }
+ });
+
+ return filteredFiles;
+ },
+
+ isWindows: function () {
+ return os.type().toLowerCase().indexOf("windows") >= 0;
+ },
+
+ isArray: function (obj) {
+ return obj.constructor.toString().indexOf("Array") !== -1;
+ },
+
+ isEmpty : function (obj) {
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop))
+ return false;
+ }
+ return true;
+ },
+
+ toBoolean: function (myString, defaultVal) {
+ // if defaultVal is not passed, default value is undefined
+ return myString === "true" ? true : myString === "false" ? false : defaultVal;
+ },
+
+ parseUri : function (str) {
+ var i, uri = {},
+ key = [ "source", "scheme", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor" ],
+ matcher = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(str);
+
+ for (i = key.length - 1; i >= 0; i--) {
+ uri[key[i]] = matcher[i] || "";
+ }
+
+ return uri;
+ },
+
+ // uri - output from parseUri
+ isAbsoluteURI : function (uri) {
+ if (uri && uri.source) {
+ return uri.relative !== uri.source;
+ }
+
+ return false;
+ },
+
+ isLocalURI : function (uri) {
+ return uri && uri.scheme && uri.scheme.toLowerCase() === "local";
+ },
+
+ // Convert node.js Buffer data (encoded) to String
+ bufferToString : function (data) {
+ var s = "";
+ if (Buffer.isBuffer(data)) {
+ if (data.length >= 2 && data[0] === 0xFF && data[1] === 0xFE) {
+ s = data.toString("ucs2", 2);
+ } else if (data.length >= 2 && data[0] === 0xFE && data[1] === 0xFF) {
+ swapBytes(data);
+ s = data.toString("ucs2", 2);
+ } else if (data.length >= 3 && data[0] === 0xEF && data[1] === 0xBB && data[2] === 0xBF) {
+ s = data.toString("utf8", 3);
+ } else {
+ s = data.toString("ascii");
+ }
+ }
+
+ return s;
+ },
+
+ // Wrap object property in an Array if the property is defined and it is not an Array
+ wrapPropertyInArray : function (obj, property) {
+ if (obj && obj[property] && !(obj[property] instanceof Array)) {
+ obj[property] = [ obj[property] ];
+ }
+ },
+
+ loadModule: function (path) {
+ return require(path);
+ },
+
+ handleProcessOutput: function (data) {
+ var msg = data.toString().replace(/[\n\r]/g, '');
+
+ if (msg) {
+ if (msg.toLowerCase().indexOf("error:") >= 0) {
+ logger.error(msg);
+ } else if (msg.toLowerCase().indexOf("warn") >= 0) {
+ logger.warn(msg);
+ } else {
+ logger.info(msg);
+ }
+ }
+ }
+};
+
+module.exports = _self;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager-validator.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager-validator.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager-validator.js
new file mode 100644
index 0000000..507b9f2
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager-validator.js
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var check = require('validator').check,
+ sanitize = require('validator').sanitize,
+ localize = require("./localize"),
+ logger = require("./logger"),
+ signingHelper = require("./signing-helper"),
+ path = require("path"),
+ fs = require("fs"),
+ packagerUtils = require("./packager-utils"),
+ CORDOVA_JS_REGEX = /(cordova-.+js)|cordova\.js/,
+ _self;
+
+//NOTE this class is unfinished and is a work in progress
+
+_self = {
+ //TODO create one global validate method that will validate
+ //both the session and configObj?
+ validateSession: function (session, widgetConfig) {
+ //The string checks below is to get around a really weird issue in commander
+ //where sometimes unspecified arguments come in as a function...
+ var keysFound = session.keystore,
+ cskFound = session.keystoreCsk,//barsigner.csk
+ dbFound = session.keystoreDb,//barsigner.db
+ keysPassword = session.storepass && typeof session.storepass === "string",
+ commandLinebuildId = session.buildId && typeof session.buildId === "string",//--buildId
+ buildId = widgetConfig.buildId && typeof widgetConfig.buildId === "string",//Finalized Build ID
+
+ //Constants
+ AUTHOR_P12 = "author.p12",
+ BARSIGNER_CSK = "barsigner.csk",
+ BARSIGNER_DB = "barsigner.db",
+
+ //Logging function
+ signingFileWarn = function (file) {
+ logger.warn(localize.translate("WARNING_MISSING_SIGNING_KEY_FILE", file));
+ },
+ signingFileError = function (file) {
+ throw localize.translate("EXCEPTION_MISSING_SIGNING_KEY_FILE", file);
+ };
+
+ //If -g <password> or --buildId is set, but signing key files are missing, throw an error
+ if (keysPassword || commandLinebuildId) {
+ if (!keysFound) {
+ signingFileError(AUTHOR_P12);
+ } else if (!cskFound) {
+ signingFileError(BARSIGNER_CSK);
+ } else if (!dbFound) {
+ signingFileError(BARSIGNER_DB);
+ }
+
+ //If a buildId exists in config, but no keys were found, throw a warning
+ } else if (buildId) {
+ if (!keysFound) {
+ signingFileWarn(AUTHOR_P12);
+ } else if (!cskFound) {
+ signingFileWarn(BARSIGNER_CSK);
+ } else if (!dbFound) {
+ signingFileWarn(BARSIGNER_DB);
+ }
+ }
+
+ //if -g was provided with NO build id, throw error
+ if (keysPassword && !buildId) {
+ throw localize.translate("EXCEPTION_MISSING_SIGNING_BUILDID");
+ }
+
+ if (commandLinebuildId && !keysPassword) {
+ //if --buildId was provided with NO password, throw error
+ throw localize.translate("EXCEPTION_MISSING_SIGNING_PASSWORD");
+ } else if (buildId && !keysPassword) {
+ //if a buildId was provided in config.xml with NO password, throw warning
+ logger.warn(localize.translate("WARNING_SIGNING_PASSWORD_EXPECTED"));
+ }
+
+ //if --appdesc was provided, but the file is not existing, throw an error
+ if (session.appdesc && !fs.existsSync(session.appdesc)) {
+ throw localize.translate("EXCEPTION_APPDESC_NOT_FOUND", session.appdesc);
+ }
+ },
+
+ //Validation for configObj, iterates through whitelisted features in configObj to remove any non-existing APIs
+ validateConfig: function (session, configObj) {
+ //if packageCordovaJs was set, test for existing cordova.js files
+ if (configObj.packageCordovaJs) {
+ cordovaJsFiles = packagerUtils.listFiles(session.sourceDir, function (file) {
+ return CORDOVA_JS_REGEX.test(file);
+ });
+ if (cordovaJsFiles.length > 0) {
+ logger.warn(localize.translate("WARN_CORDOVA_JS_PACKAGED"));
+ }
+ }
+
+ }
+};
+
+module.exports = _self;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager.js
new file mode 100644
index 0000000..01541ac
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/packager.js
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+require('./../third_party/wrench/wrench');
+
+var path = require("path"),
+ wrench = require("wrench"),
+ cmdline = require("./cmdline"),
+ logger = require("./logger"),
+ fileManager = require("./file-manager"),
+ localize = require("./localize"),
+ configParser = require("./config-parser"),
+ packagerUtils = require("./packager-utils"),
+ packagerValidator = require("./packager-validator"),
+ barBuilder = require("./bar-builder"),
+ session;
+
+module.exports = {
+ start: function(callback) {
+ try {
+ cmdline.parse(process.argv);
+ session = require("./session").initialize(cmdline.commander);
+
+ //prepare files for webworks archiving
+ logger.log(localize.translate("PROGRESS_FILE_POPULATING_SOURCE"));
+ fileManager.prepareOutputFiles(session);
+
+ //parse config.xml
+ logger.log(localize.translate("PROGRESS_SESSION_CONFIGXML"));
+ configParser.parse(path.join(session.sourceDir, "config.xml"), session, function (configObj) {
+ //validate session Object
+ packagerValidator.validateSession(session, configObj);
+ //validage configuration object
+ packagerValidator.validateConfig(session, configObj);
+
+ //generate user.js
+ logger.log(localize.translate("PROGRESS_GEN_OUTPUT"));
+ //Adding debuEnabled property to user.js. Framework will enable/disable WebInspector based on that variable.
+ configObj.debugEnabled = session.debug;
+
+ barBuilder.build(session, configObj, function (code) {
+ fileManager.cleanSource(session);
+
+ if (code === 0) {
+ logger.log(localize.translate("PROGRESS_COMPLETE"));
+
+ //call packager callback
+ callback();
+ }
+ });
+ });
+ } catch (e) {
+ try {
+ fileManager.cleanSource(session);
+ } catch (ex) {}
+
+ logger.error(e);
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/plugin.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/plugin.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/plugin.js
new file mode 100644
index 0000000..1f11481
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/plugin.js
@@ -0,0 +1,197 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+var path = require("path"),
+ shell = require('shelljs'),
+ wrench = require("wrench"),
+ fs = require('fs'),
+ et = require('elementtree'),
+ PROJECT_ROOT = path.join(__dirname, "..", ".."),
+ PLUGMAN = path.join(PROJECT_ROOT, "cordova", "node_modules", "plugman", "main.js"),
+ GLOBAL_PLUGIN_PATH = require(path.join(PROJECT_ROOT, "project.json")).globalFetchDir,
+ LOCAL_PLUGIN_PATH = path.join(PROJECT_ROOT, "plugins"),
+ argumentor = {
+ action : process.argv[2],
+ plugin: process.argv[3],
+ args: [],
+ reset: function () {
+ this.args = [];
+ return argumentor;
+ },
+ setAction: function () {
+ this.args.push("--" + this.action);
+ return argumentor;
+ },
+ setPlatform: function () {
+ this.args.push("--platform");
+ this.args.push("blackberry10");
+ return argumentor;
+ },
+ setProject: function () {
+ this.args.push("--project");
+ this.args.push(PROJECT_ROOT);
+ return argumentor;
+ },
+ setPlugin: function () {
+ var pluginWithoutTrailingSlash = this.plugin.charAt(this.plugin.length - 1) === "/" ? this.plugin.slice(0, -1) : this.plugin;
+ this.args.push("--plugin");
+ this.args.push(pluginWithoutTrailingSlash);
+ return argumentor;
+ },
+ setPluginsDir: function (isGlobal) {
+ this.args.push("--plugins_dir");
+ if (isGlobal) {
+ this.args.push(GLOBAL_PLUGIN_PATH);
+ } else {
+ this.args.push(LOCAL_PLUGIN_PATH);
+ }
+ return argumentor;
+ },
+ run: function () {
+ var cmd = "";
+ if (require('os').type().toLowerCase().indexOf("windows") >= 0) {
+ cmd += "@node.exe ";
+ }
+ cmd += PLUGMAN + " " + this.args.join(" ");
+ return shell.exec(cmd, {silent: false});
+ }
+ },
+ plugmanInterface= {
+ "uninstall": function (plugin) {
+ if (plugin) {
+ argumentor.plugin = plugin;
+ }
+ argumentor.action = "uninstall";
+ argumentor.reset().setAction().setPlatform().setProject().setPlugin().setPluginsDir().run();
+ },
+ "install": function (plugin) {
+ if (plugin) {
+ argumentor.plugin = plugin;
+ }
+ argumentor.reset().setPlatform().setProject().setPlugin().setPluginsDir().run();
+ }
+ };
+
+function getPluginId(pluginXMLPath) {
+ var pluginEt = new et.ElementTree(et.XML(fs.readFileSync(pluginXMLPath, "utf-8")));
+ return pluginEt._root.attrib.id;
+}
+
+function addPlugin (pluginPath) {
+ var plugin = pluginPath || argumentor.plugin,
+ pluginDirs = [],
+ allFiles;
+
+ //Check if the path they sent in exists
+ if (!fs.existsSync(plugin) ) {
+ //Check if the plugin has been fetched globally
+ plugin = path.resolve(GLOBAL_PLUGIN_PATH, plugin);
+ if (!fs.existsSync(plugin)) {
+ console.log("Input ", pluginPath || argumentor.plugin, " cannot be resolved as a plugin");
+ process.exit(1);
+ }
+ }
+
+ allFiles = wrench.readdirSyncRecursive(plugin);
+ allFiles.forEach(function (file) {
+ var fullPath = path.resolve(plugin, file);
+
+ if (path.basename(file) === "plugin.xml") {
+ pluginDirs.push(path.dirname(fullPath));
+ }
+ });
+
+ if (!pluginDirs.length) {
+ console.log("No plugins could be found given the input " + pluginPath || argumentor.plugin);
+ process.exit(1);
+ } else {
+ pluginDirs.forEach(function (pluginDir) {
+ plugmanInterface.install(pluginDir);
+ });
+ }
+}
+
+function removePlugin (pluginPath) {
+ var plugin = pluginPath || argumentor.plugin,
+ pluginIds = [],
+ allFiles;
+
+ //Check if the path they send in exists
+ if (!fs.existsSync(plugin) ) {
+ //Check if it is the folder name of an installed plugin
+ plugin = path.resolve(LOCAL_PLUGIN_PATH, plugin);
+ if (!fs.existsSync(plugin)) {
+ //Assume that this is a plugin id and continue
+ plugin = pluginPath || argumentor.plugin;
+ }
+ }
+
+ allFiles = wrench.readdirSyncRecursive(plugin);
+ allFiles.forEach(function (file) {
+ var fullPath = path.resolve(plugin, file),
+ pluginEt;
+
+ if (path.basename(file) === "plugin.xml") {
+ pluginIds.push(getPluginId(fullPath));
+ }
+ });
+
+ pluginIds.forEach(function (pluginId) {
+ plugmanInterface.uninstall(pluginId);
+ });
+
+}
+
+function listPlugins () {
+ fs.readdirSync(LOCAL_PLUGIN_PATH).forEach(function (pluginName) {
+ //TODO: Parse the plugin.xml and get any extra information ie description
+ console.log(pluginName);
+ });
+}
+
+function listHelp () {
+ console.log("\nUsage:");
+ console.log("add <plugin_dir> Adds all plugins contained in the given directory");
+ console.log("rm <plugin_name> [<plugin_name>] Removes all of the listed plugins");
+ console.log("ls Lists all of the currently installed plugins");
+}
+
+function cliEntry () {
+ switch (argumentor.action) {
+ case "add":
+ addPlugin();
+ break;
+ case "rm":
+ removePlugin();
+ break;
+ case "ls":
+ listPlugins();
+ break;
+ default:
+ listHelp();
+ }
+}
+
+module.exports = {
+ add: addPlugin,
+ rm: removePlugin,
+ ls: listPlugins,
+ help: listHelp,
+ cli: cliEntry
+};
[11/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/policy/whitelist.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/policy/whitelist.js b/lib/cordova-blackberry/framework/test/unit/lib/policy/whitelist.js
new file mode 100644
index 0000000..59f9425
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/policy/whitelist.js
@@ -0,0 +1,859 @@
+/*
+ * Copyright 2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var srcPath = __dirname + "/../../../../lib/",
+ Whitelist = require(srcPath + "policy/whitelist").Whitelist;
+
+describe("whitelist", function () {
+ describe("when user includes a wildcard access", function () {
+ it("can allow access to any domain not from XHR using uri *", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : true,
+ accessList : null
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.google.com")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.msn.com")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.cnn.com")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.rim.com")).toEqual(true);
+ expect(whitelist.isAccessAllowed("local:///index.html")).toEqual(true);
+ expect(whitelist.isAccessAllowed("file://store/home/user/documents/file.doc")).toEqual(true);
+ });
+ it("can allow access to explicit domains only when XHR using uri *", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : true,
+ accessList : [
+ {
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : null
+ }
+ ]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.google.com", true)).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.google.com/a/b/c", true)).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.msn.com", true)).toEqual(false);
+ expect(whitelist.isAccessAllowed("http://www.cnn.com", true)).toEqual(false);
+ });
+ });
+
+ describe("when user does not include a wildcard access", function () {
+ it("can deny all web access when no uris are whitelisted", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : null
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.google.com")).toEqual(false);
+ });
+
+ it("can deny all API access when no uris are whitelisted", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : null
+ });
+
+ expect(whitelist.isFeatureAllowed("http://www.google.com"), "blackberry.app").toEqual(false);
+ });
+
+ it("can return empty feature list when nothing is whitelisted", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : null
+ });
+
+ expect(whitelist.getFeaturesForUrl("http://www.google.com")).toEqual([]);
+ });
+
+ it("can allow access to whitelisted HTTP URL", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.google.com")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.cnn.com")).toEqual(false);
+ });
+
+ it("can allow access to whitelisted URL with different case (host)", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : null
+ },
+ {
+ uri : "http://ABC.com",
+ allowSubDomain : true,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.GOOGLE.com")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.abc.com")).toEqual(true);
+ });
+
+ it("can allow access to whitelisted URL with different case (path)", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com/SOME/path",
+ allowSubDomain : true,
+ features : null
+ },
+ {
+ uri : "http://google.com/another/path",
+ allowSubDomain : true,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.google.com/some/path")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.google.com/ANOTHER/path")).toEqual(true);
+ });
+
+ it("can deny access to non-whitelisted HTTP URL", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.cnn.com")).toEqual(false);
+ });
+
+ it("can allow access to whitelisted feature for whitelisted HTTP uris", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [
+ {
+ uri : "http://google.com",
+ allowSubDomain : false,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }, {
+ uri: "http://smoketest1-vmyyz.labyyz.testnet.rim.net:8080/",
+ allowSubDomain: false,
+ features: [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }
+ ]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://google.com", "blackberry.app")).toEqual(true);
+ expect(whitelist.isFeatureAllowed("http://smoketest1-vmyyz.labyyz.testnet.rim.net:8080/a/webworks.html", "blackberry.app")).toEqual(true);
+ });
+
+ it("can deny access to non-whitelisted feature for whitelisted HTTP uris", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : false,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://google.com", "blackberry.io.file")).toEqual(false);
+ });
+
+ it("can get all whitelisted features for url", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : false,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }, {
+ id : "blackberry.media.camera",
+ required : true,
+ version : "1.0.0"
+ }, {
+ id : "blackberry.io.dir",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.getFeaturesForUrl("http://google.com")).toContain("blackberry.app");
+ expect(whitelist.getFeaturesForUrl("http://google.com")).toContain("blackberry.media.camera");
+ expect(whitelist.getFeaturesForUrl("http://google.com")).toContain("blackberry.io.dir");
+ expect(whitelist.getFeaturesForUrl("http://www.wikipedia.org")).toEqual([]);
+ });
+
+ it("can allow access for query strings using a query string wildcard", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://www.google.com/search?*",
+ allowSubDomain : true,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.google.com/search?q=awesome")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.google.com/search?a=anyLetter")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.google.com/search")).toEqual(false);
+ expect(whitelist.isAccessAllowed("http://www.google.com/blah?q=awesome")).toEqual(false);
+ });
+
+ it("can deny access for query strings without a query string wildcard", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://www.google.com/search",
+ allowSubDomain : true,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.google.com/search?q=awesome", true)).toEqual(false);
+ expect(whitelist.isAccessAllowed("http://www.google.com/search?a=anyLetter", true)).toEqual(false);
+ });
+
+ it("can allow access for ports given just the whitelist url", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://www.awesome.com",
+ allowSubDomain : true,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.awesome.com:9000")).toEqual(true);
+ });
+
+ it("allows api access for ports given just the whitelist url", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://www.awesome.com",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://www.awesome.com:8080", "blackberry.app")).toEqual(true);
+ });
+
+ it("allows api access for child pages with ports given just the whitelist url", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://smoketest8-vmyyz.labyyz.testnet.rim.net/",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://www.smoketest8-vmyyz.labyyz.testnet.rim.net:8080//webworks.html", "blackberry.app")).toEqual(true);
+ });
+
+ it("can allow folder level access of whitelisted uris", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://www.awesome.com/parent/child",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.awesome.com/parent/child")).toEqual(true);
+ });
+
+ it("can deny access to parent folders of whitelisted uris", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://www.awesome.com/parent/child",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.awesome.com/parent")).toEqual(false);
+ });
+
+ it("can deny access to sibling folders of whitelisted uris", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://www.awesome.com/parent/child/",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://www.awesome.com/parent/sibling/")).toEqual(false);
+ });
+
+ it("can deny access to sibling folders of whitelisted uris", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://rim4.awesome.com/goodChild/index.html",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://rim4.awesome.com/goodChild/index.html")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://rim4.awesome.com/badChild/index.html")).toEqual(false);
+ });
+
+ it("can get whitelisted features at a folder level", function () {
+ var list1 = [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }],
+ list2 = [{
+ id : "blackberry.media.camera",
+ required : true,
+ version : "1.0.0"
+ }],
+ whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com/ninjas",
+ allowSubDomain : true,
+ features : list1
+ }, {
+ uri : "http://google.com/pirates",
+ allowSubDomain : true,
+ features : list2
+ }]
+ });
+
+ expect(whitelist.getFeaturesForUrl("http://google.com/ninjas")).toEqual(["blackberry.app"]);
+ expect(whitelist.getFeaturesForUrl("http://google.com/pirates")).toEqual(["blackberry.media.camera"]);
+ });
+
+ it("can allow API permissions at a folder level", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com/ninjas",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }, {
+ uri : "http://google.com/pirates",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.media.camera",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://google.com/ninjas", "blackberry.app")).toEqual(true);
+ expect(whitelist.isFeatureAllowed("http://google.com/pirates", "blackberry.media.camera")).toEqual(true);
+ });
+
+ it("can deny API permissions at a folder level", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com/ninjas",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }, {
+ uri : "http://google.com/pirates",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.media.camera",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://google.com/ninjas", "blackberry.media.camera")).toEqual(false);
+ expect(whitelist.isFeatureAllowed("http://google.com/pirates", "blackberry.app")).toEqual(false);
+ });
+
+ it("can allow access specific folder rules to override more general domain rules", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }, {
+ uri : "http://google.com/folder",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.media.camera",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://google.com/folder", "blackberry.app")).toEqual(false);
+ expect(whitelist.isFeatureAllowed("http://google.com/folder", "blackberry.media.camera")).toEqual(true);
+ });
+
+ describe("when access uris have subdomains", function () {
+ it("can get whitelisted features for subdomains", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.system",
+ required : true,
+ version : "1.0.0.0"
+ }, {
+ id : "blackberry.media.microphone",
+ required : true,
+ version : "1.0.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.getFeaturesForUrl("http://code.google.com")).toContain("blackberry.media.microphone");
+ expect(whitelist.getFeaturesForUrl("http://code.google.com")).toContain("blackberry.system");
+ expect(whitelist.getFeaturesForUrl("http://translate.google.com/lang=en")).toContain("blackberry.media.microphone");
+ expect(whitelist.getFeaturesForUrl("http://translate.google.com/lang=en")).toContain("blackberry.system");
+ expect(whitelist.getFeaturesForUrl("http://blah.goooooogle.com")).toEqual([]);
+ });
+
+ it("can allow access to whitelisted features for the subdomains", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://abc.google.com", "blackberry.app")).toEqual(true);
+ expect(whitelist.isFeatureAllowed("http://xyz.google.com", "blackberry.app")).toEqual(true);
+ });
+
+ it("can allow access to subdomains of whitelisted uris", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [
+ {
+ uri : "http://awesome.com/",
+ allowSubDomain : true,
+ features : null
+ }, {
+ uri: "http://smoketest9-vmyyz.labyyz.testnet.rim.net:8080",
+ allowSubDomain: true,
+ features: null
+ }
+ ]
+ });
+
+ expect(whitelist.isAccessAllowed("http://subdomain.awesome.com")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://www.smoketest9-vmyyz.labyyz.testnet.rim.net:8080")).toEqual(true);
+ });
+
+ it("can disallow access to subdomains of whitelisted uris", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://awesome.com/",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://subdomain.awesome.com")).toEqual(false);
+ });
+
+ it("can disallow access to subdomains of a specified uri", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://awesome.com/",
+ allowSubDomain : true,
+ features : null
+ }, {
+ uri : "http://moreawesome.com/",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://subdomain.moreawesome.com")).toEqual(false);
+ });
+
+ it("can allow specific subdomain rules to override more general domain rules when subdomains are allowed", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }, {
+ uri : "http://sub.google.com",
+ allowSubDomain : true,
+ features : [{
+ id : "blackberry.media.camera",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://sub.google.com", "blackberry.app")).toEqual(false);
+ expect(whitelist.isFeatureAllowed("http://sub.google.com", "blackberry.media.camera")).toEqual(true);
+ });
+
+ it("can get whitelisted features for a more specific subdomain", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : false,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }, {
+ uri : "http://sub.google.com",
+ allowSubDomain : false,
+ features : [{
+ id : "blackberry.media.camera",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.getFeaturesForUrl("http://google.com")).toContain("blackberry.app");
+ expect(whitelist.getFeaturesForUrl("http://sub.google.com")).toContain("blackberry.media.camera");
+ expect(whitelist.getFeaturesForUrl("http://sub.google.com")).not.toContain("blckberry.app");
+ expect(whitelist.getFeaturesForUrl("http://code.google.com")).toEqual([]);
+ });
+
+ it("can allow specific subdomain rules to override more general domain rules when subdomains are disallowed", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://google.com",
+ allowSubDomain : false,
+ features : [{
+ id : "blackberry.app",
+ required : true,
+ version : "1.0.0"
+ }]
+ }, {
+ uri : "http://sub.google.com",
+ allowSubDomain : false,
+ features : [{
+ id : "blackberry.media.camera",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("http://sub.google.com", "blackberry.app")).toEqual(false);
+ expect(whitelist.isFeatureAllowed("http://sub.google.com", "blackberry.media.camera")).toEqual(true);
+ });
+ });
+
+ describe("when uris with other protocols are requested", function () {
+ it("can allow access to whitelisted HTTPS URL", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "https://google.com",
+ allowSubDomain : true,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("https://www.google.com")).toEqual(true);
+ expect(whitelist.isAccessAllowed("https://www.cnn.com")).toEqual(false);
+ });
+
+ it("can deny access to non-whitelisted HTTPS URL", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "https://google.com",
+ allowSubDomain : true,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("https://www.cnn.com")).toEqual(false);
+ });
+
+ it("can allow access to local URLs", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "WIDGET_LOCAL", // packager always inserts a local access into access list
+ allowSubDomain : false
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("local:///index.html")).toEqual(true);
+ expect(whitelist.isAccessAllowed("local:///appDir/subDir/index.html")).toEqual(true);
+ });
+
+ it("can allow access to whitelisted features for local URLs", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "WIDGET_LOCAL", // packager always inserts a local access into access list
+ allowSubDomain : false,
+ features : [{
+ id : "blackberry.media.microphone",
+ required : true,
+ version : "2.0.0"
+ }, {
+ id : "blackberry.media.camera",
+ required : true,
+ version : "1.0.0"
+ }]
+ }]
+ });
+
+ expect(whitelist.isFeatureAllowed("local:///index.html", "blackberry.media.microphone")).toEqual(true);
+ expect(whitelist.isFeatureAllowed("local:///index.html", "blackberry.media.camera")).toEqual(true);
+ });
+
+ it("can allow access to whitelisted file URL", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "file://store/home/user/documents",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("file://store/home/user/documents/file.doc")).toEqual(true);
+ });
+
+ it("can access file if rule specifed was file:///", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [
+ {
+ uri : "file:///accounts/1000/shared/documents/textData.txt",
+ allowSubDomain : false,
+ features: []
+ }
+ ]
+ });
+
+ expect(whitelist.isAccessAllowed("file:///accounts/1000/shared/documents/textData.txt")).toEqual(true);
+ expect(whitelist.isAccessAllowed("file:///etc/passwd")).toEqual(false);
+ });
+
+ it("can access file if rule specifed was file:///", function () {
+ var whitelist = new Whitelist({
+ Â Â Â Â "hasMultiAccess": false,
+ Â Â Â Â "accessList": [
+ Â Â Â Â Â Â Â Â {
+ Â Â Â Â Â Â Â Â Â Â Â Â "features": [],
+ Â Â Â Â Â Â Â Â Â Â Â Â "uri": "WIDGET_LOCAL",
+ Â Â Â Â Â Â Â Â Â Â Â Â "allowSubDomain": true
+ Â Â Â Â Â Â Â Â },
+ Â Â Â Â Â Â Â Â {
+ Â Â Â Â Â Â Â Â Â Â Â Â "features": [],
+ Â Â Â Â Â Â Â Â Â Â Â Â "uri": "file:///accounts/1000/shared/documents/textData.txt"
+ Â Â Â Â Â Â Â Â }
+ Â Â Â Â ]
+ });
+ expect(whitelist.isAccessAllowed("file:///etc/passwd", false)).toEqual(false);
+ });
+
+ it("can deny file access when access file:/// with no rule", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : null
+ });
+
+ expect(whitelist.isAccessAllowed("file:///accounts/1000/shared/documents/textData.txt")).toEqual(false);
+ });
+
+ it("can allow access to whitelisted file URL from an external startup page", function () {
+ var whitelist = new Whitelist({
+ content: "http://www.google.com",
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "file://store/home/user/documents",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("file://store/home/user/documents/file.doc")).toEqual(true);
+ });
+
+ it("can allow access to whitelisted local URL from an external startup page", function () {
+ var whitelist = new Whitelist({
+ content: "http://www.google.com",
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "local://localpage.html",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("local://localpage.html")).toEqual(true);
+ });
+
+ it("can allow access to whitelisted file URL from an external startup page with wildcard access", function () {
+ var whitelist = new Whitelist({
+ content: "http://www.google.com",
+ hasMultiAccess : true
+ });
+
+ expect(whitelist.isAccessAllowed("file://store/home/user/documents/file.doc")).toEqual(true);
+ });
+
+ it("can allow access to whitelisted local URL from an external startup page with wildcard access", function () {
+ var whitelist = new Whitelist({
+ content: "http://www.google.com",
+ hasMultiAccess : true
+ });
+
+ expect(whitelist.isAccessAllowed("local://localpage.html")).toEqual(true);
+ });
+
+ it("can deny file URL access when no file urls are whitelisted", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : null
+ });
+
+ expect(whitelist.isAccessAllowed("file://store/home/user/documents/file.doc")).toEqual(false);
+ });
+
+ it("can allow access to a subfolder of a whitelisted file URL", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "file://store/home/user/",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("file://store/home/user/documents/file.doc")).toEqual(true);
+ });
+
+ it("can deny access to a different folder of a whitelisted file URL", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://store.com/home/user/documents",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("http://store.com/home/user/documents/file.doc")).toEqual(true);
+ expect(whitelist.isAccessAllowed("http://store.com/file2.doc")).toEqual(false);
+ });
+
+ it("can allow access to RTSP protocol urls", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "rtsp://media.com",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("rtsp://media.com/video.avi")).toEqual(true);
+ });
+
+ it("always allows access to data-uris", function () {
+ var whitelist = new Whitelist({
+ hasMultiAccess : false,
+ accessList : [{
+ uri : "http://awesome.com",
+ allowSubDomain : false,
+ features : null
+ }]
+ });
+
+ expect(whitelist.isAccessAllowed("data:image/png;base64,zamagawdbase64string")).toEqual(true);
+ });
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/server.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/server.js b/lib/cordova-blackberry/framework/test/unit/lib/server.js
new file mode 100644
index 0000000..2b89b0a
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/server.js
@@ -0,0 +1,293 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var ROOT = "../../../";
+
+describe("server", function () {
+
+ var server = require(ROOT + "lib/server"),
+ plugin = require(ROOT + "lib/plugins/default"),
+ applicationAPIServer,
+ utils,
+ DEFAULT_SERVICE = "default",
+ DEFAULT_ACTION = "exec",
+ config = {};
+
+ beforeEach(function () {
+ applicationAPIServer = {
+ getReadOnlyFields: function () {}
+ };
+ delete require.cache[require.resolve(ROOT + "lib/utils")];
+ utils = require("../../../lib/utils");
+ spyOn(utils, "loadModule").andCallFake(function (module) {
+ if (module.indexOf("plugin/") >= 0) {
+ // on device, "plugin/blackberry.app/index.js" would exist
+ return applicationAPIServer;
+ } else {
+ return require("../../../lib/" + module);
+ }
+ });
+ });
+
+ describe("when handling requests", function () {
+ var req, res;
+
+ beforeEach(function () {
+ req = {
+ params: {
+ service: "",
+ action: ""
+ },
+ body: "",
+ origin: ""
+ };
+ res = {
+ send: jasmine.createSpy()
+ };
+ GLOBAL.frameworkModules = ['plugin/blackberry.app/index.js', 'lib/plugins/default.js'];
+ });
+
+ afterEach(function () {
+ delete GLOBAL.frameworkModules;
+ });
+
+ it("calls the default plugin if the service doesn't exist", function () {
+ var rebuiltRequest = {
+ params: {
+ service: DEFAULT_SERVICE,
+ action: DEFAULT_ACTION,
+ ext: "not",
+ method: "here",
+ args: null
+ },
+ body: "",
+ origin: ""
+ },
+ webview = {};
+
+ spyOn(plugin, DEFAULT_ACTION);
+ req.params.service = "not";
+ req.params.action = "here";
+
+ server.handle(req, res, webview, config);
+
+ expect(plugin[DEFAULT_ACTION]).toHaveBeenCalledWith(
+ rebuiltRequest, jasmine.any(Function),
+ jasmine.any(Function),
+ rebuiltRequest.params.args,
+ {
+ request: rebuiltRequest,
+ response: res,
+ webview: webview,
+ config: config
+ }
+ );
+ });
+
+ it("returns 404 if the action doesn't exist", function () {
+ req.params.service = "default";
+ req.params.action = "ThisActionDoesNotExist";
+
+ spyOn(console, "error");
+
+ server.handle(req, res);
+ expect(res.send).toHaveBeenCalledWith(404, jasmine.any(String));
+ expect(console.error).toHaveBeenCalled();
+ });
+
+ it("calls the action method on the plugin", function () {
+ var webview = "BLAHBLAHBLAH";
+
+ spyOn(plugin, "exec");
+
+ req.params.service = "default";
+ req.params.action = "exec";
+
+ expect(function () {
+ return server.handle(req, res, webview, config);
+ }).not.toThrow();
+ expect(plugin.exec).toHaveBeenCalledWith(
+ req,
+ jasmine.any(Function),
+ jasmine.any(Function),
+ req.params.args,
+ {
+ request: req,
+ response: res,
+ webview: webview,
+ config: config
+ });
+ });
+
+ it("parses url encoded args", function () {
+ var webview = "BLAHBLAHBLAH";
+
+ spyOn(plugin, "exec");
+
+ expect(function () {
+ req.params.service = "default";
+ req.params.action = "exec";
+ req.params.args = "a=1&b=2&c=3";
+
+ return server.handle(req, res, webview);
+ }).not.toThrow();
+ expect(plugin.exec).toHaveBeenCalledWith(
+ jasmine.any(Object),
+ jasmine.any(Function),
+ jasmine.any(Function),
+ {
+ a: '1',
+ b: '2',
+ c: '3'
+ },
+ jasmine.any(Object)
+ );
+ });
+
+ it("parses url encoded args", function () {
+ var webview = "BLAHBLAHBLAH";
+
+ spyOn(plugin, "exec");
+
+ expect(function () {
+ req.params.service = "default";
+ req.params.action = "exec";
+ req.body = JSON.stringify({a: '1', b: '2', c: '3'});
+
+ return server.handle(req, res, webview);
+ }).not.toThrow();
+ expect(plugin.exec).toHaveBeenCalledWith(
+ jasmine.any(Object),
+ jasmine.any(Function),
+ jasmine.any(Function),
+ {
+ a: '1',
+ b: '2',
+ c: '3'
+ },
+ jasmine.any(Object)
+ );
+ });
+
+ it("returns the result and code 42 when success callback called", function () {
+ spyOn(plugin, "exec").andCallFake(function (request, succ, fail, body) {
+ succ(["MyFeatureId"]);
+ });
+
+ req.params.service = "default";
+ req.params.action = "exec";
+
+ server.handle(req, res);
+ expect(res.send).toHaveBeenCalledWith(200, encodeURIComponent(JSON.stringify({
+ code: 42,
+ data: ["MyFeatureId"]
+ })));
+ });
+
+ it("returns the result and code -1 when fail callback called", function () {
+ spyOn(plugin, "exec").andCallFake(function (request, succ, fail, body) {
+ fail(-1, "ErrorMessage");
+ });
+
+ req.params.service = "default";
+ req.params.action = "exec";
+
+ server.handle(req, res);
+ expect(res.send).toHaveBeenCalledWith(200, encodeURIComponent(JSON.stringify({
+ code: -1,
+ data: null,
+ msg: "ErrorMessage"
+ })));
+ });
+ });
+
+ describe("when handling feature requests", function () {
+ var req, res;
+
+ beforeEach(function () {
+ req = {
+ params: {
+ service: "default",
+ action: "exec",
+ ext: "blackberry.app",
+ method: "getReadOnlyFields",
+ args: null
+ },
+ headers: {
+ host: ""
+ },
+ url: "",
+ body: "",
+ origin: ""
+ };
+ res = {
+ send: jasmine.createSpy()
+ };
+ GLOBAL.frameworkModules = ['plugin/blackberry.app/index.js', 'lib/plugins/default.js'];
+ });
+
+ afterEach(function () {
+ delete GLOBAL.frameworkModules;
+ });
+
+ it("calls the action method on the feature", function () {
+ var webview = {};
+ spyOn(applicationAPIServer, "getReadOnlyFields");
+ server.handle(req, res, webview, config);
+ expect(applicationAPIServer.getReadOnlyFields).toHaveBeenCalledWith(
+ jasmine.any(Function),
+ jasmine.any(Function),
+ req.params.args,
+ {
+ request: req,
+ response: res,
+ webview: webview,
+ config: config
+ }
+ );
+ });
+
+ it("returns the result and code 42 when success callback called", function () {
+ var expectedResult = {"getReadOnlyFields": "Yogi bear"};
+
+ spyOn(applicationAPIServer, "getReadOnlyFields").andCallFake(function (success, fail) {
+ success(expectedResult);
+ });
+
+ server.handle(req, res);
+
+ expect(res.send).toHaveBeenCalledWith(200, encodeURIComponent(JSON.stringify({
+ code: 42,
+ data: expectedResult
+ })));
+ });
+
+ it("returns the result and code -1 when fail callback called", function () {
+ var expectedResult = "omg";
+
+ spyOn(applicationAPIServer, "getReadOnlyFields").andCallFake(function (success, fail) {
+ fail(-1, expectedResult);
+ });
+
+ server.handle(req, res);
+
+ expect(res.send).toHaveBeenCalledWith(200, encodeURIComponent(JSON.stringify({
+ code: -1,
+ data: null,
+ msg: expectedResult
+ })));
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/utils.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/utils.js b/lib/cordova-blackberry/framework/test/unit/lib/utils.js
new file mode 100644
index 0000000..4b7f5a8
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/utils.js
@@ -0,0 +1,280 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var srcPath = __dirname + '/../../../lib/';
+
+describe("Utils", function () {
+ var utils = require(srcPath + 'utils.js');
+
+ describe("endsWith", function () {
+ it("returns true when a string ends with another", function () {
+ expect(utils.endsWith("www.smoketest9-vmyyz.labyyz.testnet.rim.net:8080", ".smoketest9-vmyyz.labyyz.testnet.rim.net:8080")).toEqual(true);
+ });
+ });
+
+ it("Verify that the filenameToImageMIME is defined", function () {
+ expect(utils.fileNameToImageMIME).toBeDefined();
+ });
+
+ it("Verify that the proper PNG MIME types are returned", function () {
+ expect(utils.fileNameToImageMIME("test.png")).toEqual("image/png");
+ });
+
+ it("Verify that the proper period MIME types are returned", function () {
+ expect(utils.fileNameToImageMIME("test.t.png")).toEqual("image/png");
+ });
+
+ it("Verify that the proper JPG types are returned", function () {
+ expect(utils.fileNameToImageMIME("test.jpg")).toEqual("image/jpeg");
+ });
+
+ it("Verify that the proper GIF types are returned", function () {
+ expect(utils.fileNameToImageMIME("test.gif")).toEqual("image/gif");
+ });
+
+ it("Verify that the proper TIFF types are returned", function () {
+ expect(utils.fileNameToImageMIME("test_test_.tif")).toEqual("image/tiff");
+ });
+
+ it("Verify that the proper TIFF types are returned", function () {
+ expect(utils.fileNameToImageMIME("test_test_.tiff")).toEqual("image/tiff");
+ });
+
+ it("Verify that the proper JPE MIME types are returned", function () {
+ expect(utils.fileNameToImageMIME("test.jpe")).toEqual("image/jpeg");
+ });
+
+ it("Verify that the proper BMP MIME types are returned", function () {
+ expect(utils.fileNameToImageMIME("test.bmp")).toEqual("image/bmp");
+ });
+
+ it("Verify that the proper JPEG MIME types are returned", function () {
+ expect(utils.fileNameToImageMIME("test.jpeg")).toEqual("image/jpeg");
+ });
+
+ it("Verify that the proper SVG MIME types are returned", function () {
+ expect(utils.fileNameToImageMIME("test.svg")).toEqual("image/svg+xml");
+ });
+
+ it("has an invokeInBrowser function", function () {
+ var url = "http://www.webworks.com",
+ mockApplication = {
+ invocation: {
+ invoke: jasmine.createSpy("invocation.invoke")
+ }
+ },
+ mockWindow = {
+ qnx: {
+ webplatform: {
+ getApplication: function () {
+ return mockApplication;
+ }
+ }
+ }
+ };
+
+ GLOBAL.window = mockWindow;
+
+ this.after(function () {
+ delete GLOBAL.window;
+ });
+
+ expect(utils.invokeInBrowser).toBeDefined();
+
+ utils.invokeInBrowser(url);
+
+ expect(mockApplication.invocation.invoke).toHaveBeenCalledWith({
+ uri: url,
+ target: "sys.browser"
+ });
+ });
+
+ // A cascading method invoker, kinda like jWorkflow
+ describe("series", function () {
+ var tasks,
+ callbackObj,
+ seriesComplete,
+ callbackInvocations,
+ invocationCounter,
+ task;
+
+ beforeEach(function () {
+ tasks = [];
+ callbackInvocations = [];
+ invocationCounter = 0;
+ seriesComplete = false;
+ callbackObj = {
+ func: function (args) {
+ callbackInvocations.push('done');
+ seriesComplete = true;
+ },
+ args: []
+ };
+ task = {
+ func: function (callback) {
+ callbackInvocations.push(invocationCounter++);
+ callback();
+ },
+ args: []
+ };
+ });
+
+ afterEach(function () {
+ tasks = null;
+ callbackObj = null;
+ seriesComplete = null;
+ callbackInvocations = null;
+ invocationCounter = null;
+ task = null;
+ });
+
+ it('should call callback right away when there are no tasks to execute', function () {
+ spyOn(callbackObj, 'func');
+ utils.series(tasks, callbackObj);
+ expect(callbackObj.func).toHaveBeenCalled();
+ });
+
+ it('should invoke the task method before the callback', function () {
+ tasks.push(task);
+ utils.series(tasks, callbackObj);
+ waitsFor(function () {
+ return seriesComplete;
+ });
+
+ expect(callbackInvocations.length).toEqual(2);
+ expect(callbackInvocations[0]).toEqual(0);
+ expect(callbackInvocations[1]).toEqual('done');
+ });
+
+ it('should invocation the tasks in order with the callback being the last invocation', function () {
+ var i;
+
+ tasks.push(task);
+ tasks.push(task);
+ tasks.push(task);
+ tasks.push(task);
+
+ utils.series(tasks, callbackObj);
+
+ waitsFor(function () {
+ return seriesComplete;
+ });
+
+ expect(callbackInvocations.length).toEqual(5);
+
+ for (i = 0; i < 4; i++) {
+ expect(callbackInvocations[i]).toEqual(i);
+ }
+
+ expect(callbackInvocations[4]).toEqual('done');
+ });
+ });
+
+ describe("utils translate path", function () {
+ beforeEach(function () {
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ getApplication: function () {
+ return {
+ getEnv: function (path) {
+ if (path === "HOME")
+ return "/accounts/home";
+ }
+ };
+ }
+ }
+ }
+ };
+ });
+
+ afterEach(function () {
+ delete GLOBAL.window;
+ });
+
+ it("Expect translate path to be defined", function () {
+ expect(utils.translatePath).toBeDefined();
+ });
+ it("translate path successfully returns the original path when passed non local value", function () {
+ var path = "http://google.com";
+ path = utils.translatePath(path);
+ expect(path).toEqual("http://google.com");
+ });
+ it("translate path successfully returns the original path when passed a telephone uri", function () {
+ var path = "tel://250-654-34243";
+ path = utils.translatePath(path);
+ expect(path).toEqual("tel://250-654-34243");
+ });
+ it("translate path successfully retuns an updated string for a local path", function () {
+ var path = "local:///this-is-a-local/img/path.jpg";
+ path = utils.translatePath(path);
+ expect(path).toEqual("file:///accounts/home/../app/native/this-is-a-local/img/path.jpg");
+ });
+ });
+
+ describe("deepclone", function () {
+ it("passes through null", function () {
+ expect(utils.deepclone(null)).toBe(null);
+ });
+
+ it("passes through undefined", function () {
+ expect(utils.deepclone(undefined)).toBe(undefined);
+ });
+
+ it("passes through a Number", function () {
+ expect(utils.deepclone(1)).toBe(1);
+ });
+
+ it("passes through a String", function () {
+ var str = "hello world";
+ expect(utils.deepclone(str)).toBe(str);
+ });
+
+ it("passes through a Boolean", function () {
+ expect(utils.deepclone(true)).toBe(true);
+ expect(utils.deepclone(false)).toBe(false);
+ });
+
+ it("returns a new Date", function () {
+ var date = new Date(),
+ dateCopy = utils.deepclone(date);
+
+ expect(dateCopy instanceof Date).toBe(true, "Not a Date");
+ expect(date).not.toBe(dateCopy);
+ expect(date.getTime()).toBe(dateCopy.getTime());
+ });
+
+ it("returns a new RegExp", function () {
+ var regex = /a/,
+ regexCopy = utils.deepclone(regex);
+
+ expect(regexCopy instanceof RegExp).toBe(true, "Not a RegExp");
+ expect(regexCopy).not.toBe(regex);
+ expect(regexCopy.toString()).toBe(regex.toString());
+ });
+
+ it("copies nested Object properties", function () {
+ var obj = {
+ a: "hello world",
+ b: "hello again"
+ },
+ objCopy = utils.deepclone(obj);
+
+ expect(obj).not.toBe(objCopy);
+ expect(obj).toEqual(objCopy);
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/webkitHandlers/networkResourceRequested.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/webkitHandlers/networkResourceRequested.js b/lib/cordova-blackberry/framework/test/unit/lib/webkitHandlers/networkResourceRequested.js
new file mode 100644
index 0000000..efd4efe
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/webkitHandlers/networkResourceRequested.js
@@ -0,0 +1,167 @@
+describe("NetworkResourceRequested event handler", function () {
+ var LIB_PATH = "./../../../../lib/",
+ networkResourceRequested = require(LIB_PATH + "webkitHandlers/networkResourceRequested"),
+ Whitelist = require(LIB_PATH + 'policy/whitelist').Whitelist,
+ server = require(LIB_PATH + 'server'),
+ utils = require(LIB_PATH + 'utils'),
+ mockedWebview;
+
+ beforeEach(function () {
+ mockedWebview = {
+ originalLocation : "http://www.origin.com",
+ executeJavaScript : jasmine.createSpy(),
+ id: 42,
+ uiWebView: {
+ childwebviewcontrols: {
+ open: jasmine.createSpy()
+ }
+ }
+ };
+ });
+
+ afterEach(function () {
+ mockedWebview = undefined;
+ });
+
+ it("creates a callback for yous", function () {
+ var requestObj = networkResourceRequested.createHandler();
+ expect(requestObj.networkResourceRequestedHandler).toBeDefined();
+ });
+
+
+ it("can access the whitelist", function () {
+ spyOn(Whitelist.prototype, "isAccessAllowed").andReturn(true);
+ var url = "http://www.google.com",
+ requestObj = networkResourceRequested.createHandler(mockedWebview);
+ requestObj.networkResourceRequestedHandler(JSON.stringify({url: url}));
+ expect(Whitelist.prototype.isAccessAllowed).toHaveBeenCalled();
+ });
+
+ it("checks whether the request is for an iframe when accessing the whitelist", function () {
+ spyOn(Whitelist.prototype, "isAccessAllowed").andReturn(true);
+ var url = "http://www.google.com",
+ requestObj = networkResourceRequested.createHandler(mockedWebview);
+ requestObj.networkResourceRequestedHandler(JSON.stringify({url: url, targetType: "TargetIsXMLHTTPRequest"}));
+ expect(Whitelist.prototype.isAccessAllowed).toHaveBeenCalledWith(url, true);
+ });
+
+ it("can apply whitelist rules and allow valid urls", function () {
+ spyOn(Whitelist.prototype, "isAccessAllowed").andReturn(true);
+ var url = "http://www.google.com",
+ requestObj = networkResourceRequested.createHandler(mockedWebview),
+ returnValue = requestObj.networkResourceRequestedHandler(JSON.stringify({url: url}));
+ expect(Whitelist.prototype.isAccessAllowed).toHaveBeenCalled();
+ expect(JSON.parse(returnValue).setAction).toEqual("ACCEPT");
+ });
+
+ it("can apply whitelist rules and deny blocked urls", function () {
+ spyOn(Whitelist.prototype, "isAccessAllowed").andReturn(false);
+ spyOn(utils, "invokeInBrowser");
+ spyOn(console, "warn");
+
+ var url = "http://www.google.com",
+ requestObj = networkResourceRequested.createHandler(mockedWebview),
+ returnValue = requestObj.networkResourceRequestedHandler(JSON.stringify({url: url})),
+ deniedMsg = "Access to \"" + url + "\" not allowed";
+
+ expect(Whitelist.prototype.isAccessAllowed).toHaveBeenCalled();
+ expect(JSON.parse(returnValue).setAction).toEqual("DENY");
+ expect(utils.invokeInBrowser).not.toHaveBeenCalledWith(url);
+ expect(mockedWebview.uiWebView.childwebviewcontrols.open).not.toHaveBeenCalledWith(url);
+ expect(mockedWebview.executeJavaScript).toHaveBeenCalledWith("alert('" + deniedMsg + "')");
+ expect(console.warn).toHaveBeenCalledWith(deniedMsg);
+ });
+
+ it("can apply whitelist rules and deny blocked urls and route to a uiWebView when target is main frame", function () {
+ spyOn(Whitelist.prototype, "isAccessAllowed").andReturn(false);
+ spyOn(utils, "invokeInBrowser");
+ spyOn(console, "warn");
+
+ var url = "http://www.google.com",
+ requestObj = networkResourceRequested.createHandler(mockedWebview),
+ returnValue = requestObj.networkResourceRequestedHandler(JSON.stringify({url: url, targetType: "TargetIsMainFrame"})),
+ deniedMsg = "Access to \"" + url + "\" not allowed";
+
+ expect(Whitelist.prototype.isAccessAllowed).toHaveBeenCalled();
+ expect(mockedWebview.uiWebView.childwebviewcontrols.open).toHaveBeenCalledWith(url);
+ expect(mockedWebview.executeJavaScript).not.toHaveBeenCalledWith("alert('" + deniedMsg + "')");
+ expect(console.warn).toHaveBeenCalledWith(deniedMsg);
+ expect(utils.invokeInBrowser).not.toHaveBeenCalledWith(url);
+ expect(JSON.parse(returnValue).setAction).toEqual("DENY");
+ });
+
+ it("can apply whitelist rules and deny blocked urls and route to the browser when target is main frame and childWebView is disabled", function () {
+ var url = "http://www.google.com",
+ config = require(LIB_PATH + "config"),
+ deniedMsg = "Access to \"" + url + "\" not allowed",
+ requestObj,
+ returnValue;
+
+ spyOn(Whitelist.prototype, "isAccessAllowed").andReturn(false);
+ spyOn(utils, "invokeInBrowser");
+ spyOn(console, "warn");
+
+ config.enableChildWebView = false;
+
+ this.after(function () {
+ delete require.cache[require.resolve(LIB_PATH + "config")];
+ });
+
+ requestObj = networkResourceRequested.createHandler(mockedWebview);
+ returnValue = requestObj.networkResourceRequestedHandler(JSON.stringify({url: url, targetType: "TargetIsMainFrame"}));
+
+ expect(Whitelist.prototype.isAccessAllowed).toHaveBeenCalled();
+ expect(mockedWebview.uiWebView.childwebviewcontrols.open).not.toHaveBeenCalledWith(url);
+ expect(mockedWebview.executeJavaScript).not.toHaveBeenCalledWith("alert('" + deniedMsg + "')");
+ expect(console.warn).toHaveBeenCalledWith(deniedMsg);
+ expect(utils.invokeInBrowser).toHaveBeenCalledWith(url);
+ expect(JSON.parse(returnValue).setAction).toEqual("DENY");
+ });
+
+ it("can call the server handler when certain urls are detected", function () {
+ spyOn(server, "handle");
+ var url = "http://localhost:8472/roomService/kungfuAction/customExt/crystalMethod?blargs=yes",
+ requestObj = networkResourceRequested.createHandler(mockedWebview),
+ returnValue = requestObj.networkResourceRequestedHandler(JSON.stringify({url: url, referrer: "http://www.origin.com"})),
+ expectedRequest = {
+ params: {
+ service: "roomService",
+ action: "kungfuAction",
+ ext: "customExt",
+ method: "crystalMethod",
+ args: "blargs=yes"
+ },
+ body: undefined,
+ origin: "http://www.origin.com"
+ },
+ expectedResponse = {
+ send: jasmine.any(Function)
+ };
+ expect(JSON.parse(returnValue).setAction).toEqual("SUBSTITUTE");
+ expect(server.handle).toHaveBeenCalledWith(expectedRequest, expectedResponse, mockedWebview);
+ });
+
+ it("can call the server handler correctly with a multi-level method", function () {
+ spyOn(server, "handle");
+ var url = "http://localhost:8472/roomService/kungfuAction/customExt/crystal/Method?blargs=yes",
+ requestObj = networkResourceRequested.createHandler(mockedWebview),
+ returnValue = requestObj.networkResourceRequestedHandler(JSON.stringify({url: url, referrer: "http://www.origin.com"})),
+ expectedRequest = {
+ params: {
+ service: "roomService",
+ action: "kungfuAction",
+ ext: "customExt",
+ method: "crystal/Method",
+ args: "blargs=yes"
+ },
+ body: undefined,
+ origin: "http://www.origin.com"
+ },
+ expectedResponse = {
+ send: jasmine.any(Function)
+ };
+ expect(JSON.parse(returnValue).setAction).toEqual("SUBSTITUTE");
+ expect(server.handle).toHaveBeenCalledWith(expectedRequest, expectedResponse, mockedWebview);
+ });
+
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/test/unit/lib/webview.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/test/unit/lib/webview.js b/lib/cordova-blackberry/framework/test/unit/lib/webview.js
new file mode 100644
index 0000000..e96eb18
--- /dev/null
+++ b/lib/cordova-blackberry/framework/test/unit/lib/webview.js
@@ -0,0 +1,334 @@
+describe("webview", function () {
+ var libPath = "./../../../lib/",
+ networkResourceRequested = require(libPath + "webkitHandlers/networkResourceRequested"),
+ webkitOriginAccess = require(libPath + "policy/webkitOriginAccess"),
+ webview,
+ mockedController,
+ mockedWebview,
+ mockedQnx,
+ globalCreate;
+
+ beforeEach(function () {
+ webview = require(libPath + "webview");
+ mockedController = {
+ enableWebInspector: undefined,
+ enableCrossSiteXHR: undefined,
+ visible: undefined,
+ active: undefined,
+ setGeometry: jasmine.createSpy(),
+ dispatchEvent : jasmine.createSpy(),
+ addEventListener : jasmine.createSpy()
+ };
+ mockedWebview = {
+ id: 42,
+ enableCrossSiteXHR: undefined,
+ visible: undefined,
+ active: undefined,
+ zOrder: undefined,
+ url: undefined,
+ reload: jasmine.createSpy(),
+ extraHttpHeaders: undefined,
+ setFileSystemSandbox: undefined,
+ addOriginAccessWhitelistEntry: jasmine.createSpy(),
+ setGeometry: jasmine.createSpy(),
+ setApplicationOrientation: jasmine.createSpy(),
+ setExtraPluginDirectory: jasmine.createSpy(),
+ setEnablePlugins: jasmine.createSpy(),
+ getEnablePlugins: jasmine.createSpy(),
+ notifyApplicationOrientationDone: jasmine.createSpy(),
+ onContextMenuRequestEvent: undefined,
+ onContextMenuCancelEvent: undefined,
+ onNetworkResourceRequested: undefined,
+ destroy: jasmine.createSpy(),
+ executeJavaScript: jasmine.createSpy(),
+ windowGroup: undefined,
+ addEventListener: jasmine.createSpy(),
+ enableWebEventRedirect: jasmine.createSpy(),
+ addKnownSSLCertificate: jasmine.createSpy(),
+ continueSSLHandshaking: jasmine.createSpy(),
+ setSensitivity: jasmine.createSpy(),
+ getSensitivity: jasmine.createSpy(),
+ setBackgroundColor: jasmine.createSpy(),
+ getBackgroundColor: jasmine.createSpy(),
+ allowWebEvent: jasmine.createSpy(),
+ allowUserMedia: jasmine.createSpy(),
+ disallowUserMedia: jasmine.createSpy()
+ };
+ mockedQnx = {
+ callExtensionMethod: jasmine.createSpy(),
+ webplatform: {
+ getController: function () {
+ return mockedController;
+ },
+ createWebView: function (options, createFunction) {
+ //process.nextTick(createFunction);
+ //setTimeout(createFunction,0);
+ if (typeof options === 'function') {
+ runs(options);
+ globalCreate = options;
+ }
+ else {
+ runs(createFunction);
+ globalCreate = createFunction;
+ }
+ return mockedWebview;
+ },
+ getApplication: jasmine.createSpy()
+ }
+ };
+ GLOBAL.qnx = mockedQnx;
+ GLOBAL.window = {
+ qnx: mockedQnx
+ };
+ GLOBAL.screen = {
+ width : 1024,
+ height: 768
+ };
+ });
+
+ afterEach(function () {
+ delete GLOBAL.qnx;
+ delete GLOBAL.window;
+ delete GLOBAL.screen;
+ });
+
+ describe("create", function () {
+ it("sets up the visible webview", function () {
+ var mockNetworkHandler = { networkResourceRequestedHandler: function onNetworkResourceRequested() {} };
+
+ spyOn(networkResourceRequested, "createHandler").andReturn(mockNetworkHandler);
+ spyOn(webkitOriginAccess, "addWebView");
+ webview.create();
+ waits(1);
+ runs(function () {
+ expect(mockedWebview.visible).toEqual(true);
+ expect(mockedWebview.active).toEqual(true);
+ expect(mockedWebview.zOrder).toEqual(0);
+ expect(mockedWebview.setGeometry).toHaveBeenCalledWith(0, 0, screen.width, screen.height);
+ expect(Object.getOwnPropertyDescriptor(webview, 'onContextMenuRequestEvent')).toEqual(jasmine.any(Object));
+ expect(Object.getOwnPropertyDescriptor(webview, 'onContextMenuCancelEvent')).toEqual(jasmine.any(Object));
+ expect(Object.getOwnPropertyDescriptor(webview, 'onGeolocationPermissionRequest')).toEqual(jasmine.any(Object));
+
+
+ expect(networkResourceRequested.createHandler).toHaveBeenCalledWith(mockedWebview);
+ expect(mockedWebview.onNetworkResourceRequested).toEqual(mockNetworkHandler.networkResourceRequestedHandler);
+
+ expect(mockedWebview.allowWebEvent).toHaveBeenCalledWith("DialogRequested");
+ expect(mockedController.dispatchEvent).toHaveBeenCalledWith("webview.initialized", jasmine.any(Array));
+ //The default config.xml only has access to WIDGET_LOCAL
+ //and has permission for two apis
+ expect(webkitOriginAccess.addWebView).toHaveBeenCalledWith(mockedWebview);
+ });
+ });
+
+ it("calls the ready function", function () {
+ var chuck = jasmine.createSpy();
+ webview.create(chuck);
+ waits(1);
+ runs(function () {
+ expect(chuck).toHaveBeenCalled();
+ });
+ });
+
+ });
+
+ describe("file system sandbox", function () {
+ it("setSandbox", function () {
+ webview.create();
+ webview.setSandbox(false);
+ expect(mockedWebview.setFileSystemSandbox).toBeFalsy();
+ });
+
+ it("getSandbox", function () {
+ webview.create();
+ webview.setSandbox(false);
+ expect(webview.getSandbox()).toBeFalsy();
+ });
+ });
+
+ describe("id", function () {
+ it("can get the id for the webiew", function () {
+ webview.create();
+ expect(webview.id).toEqual(mockedWebview.id);
+ });
+ });
+
+ describe("enableCrossSiteXHR", function () {
+ it("can set enableCrossSiteXHR", function () {
+ webview.create();
+ webview.enableCrossSiteXHR = true;
+ expect(mockedWebview.enableCrossSiteXHR).toBe(true);
+ webview.enableCrossSiteXHR = false;
+ expect(mockedWebview.enableCrossSiteXHR).toBe(false);
+ });
+ });
+
+ describe("geometry", function () {
+ it("can set geometry", function () {
+ webview.create();
+ webview.setGeometry(0, 0, 100, 200);
+ expect(mockedWebview.setGeometry).toHaveBeenCalledWith(0, 0, 100, 200);
+ });
+
+ it("can get geometry", function () {
+ webview.create();
+ webview.setGeometry(0, 0, 100, 100);
+ expect(webview.getGeometry()).toEqual({x: 0, y: 0, w: 100, h: 100});
+ });
+ });
+
+ describe("application orientation", function () {
+ it("can set application orientation", function () {
+ webview.create();
+ webview.setApplicationOrientation(90);
+ expect(mockedWebview.setApplicationOrientation).toHaveBeenCalledWith(90);
+ });
+
+ it("can notifyApplicationOrientationDone", function () {
+ webview.create();
+ webview.notifyApplicationOrientationDone();
+ expect(mockedWebview.notifyApplicationOrientationDone).toHaveBeenCalled();
+ });
+ });
+
+ describe("plugins", function () {
+ it("can set an extra plugin directory", function () {
+ webview.create();
+ webview.setExtraPluginDirectory('/usr/lib/browser/plugins');
+ expect(mockedWebview.setExtraPluginDirectory).toHaveBeenCalledWith('/usr/lib/browser/plugins');
+ });
+
+ it("can enable plugins for the webview", function () {
+ webview.create();
+ webview.setEnablePlugins(true);
+ expect(mockedWebview.pluginsEnabled).toBeTruthy();
+ });
+
+ it("can retrieve whether plugins are enabled", function () {
+ webview.create();
+ webview.setEnablePlugins(true);
+ expect(webview.getEnablePlugins()).toBeTruthy();
+ });
+ });
+
+ describe("SSL Exception Methods", function () {
+ it("addKnownSSLException", function () {
+ var url = 'https://bojaps.com',
+ certificateInfo = {
+ test : 'test'
+ };
+ webview.create();
+ webview.addKnownSSLCertificate(url, certificateInfo);
+ expect(mockedWebview.addKnownSSLCertificate).toHaveBeenCalledWith(url, certificateInfo);
+ });
+
+ it("continue SSL Hanshaking", function () {
+ var streamId = 8,
+ SSLAction = 'SSLActionReject';
+ webview.create();
+ webview.continueSSLHandshaking(streamId, SSLAction);
+ expect(mockedWebview.continueSSLHandshaking).toHaveBeenCalledWith(streamId, SSLAction);
+ });
+ });
+
+ describe("User Media", function () {
+ it("has allowUserMedia defined", function () {
+ webview.create();
+ expect(webview.allowUserMedia).toBeDefined();
+ });
+
+ it("has disallowUserMedia defined", function () {
+ webview.create();
+ expect(webview.disallowUserMedia).toBeDefined();
+ });
+
+ it("calls allowUserMedia on WebView", function () {
+ var evtId = 10,
+ cameraName = "CAMERA_UNIT_FRONT";
+
+ webview.create();
+ webview.allowUserMedia(evtId, cameraName);
+ expect(mockedWebview.allowUserMedia).toHaveBeenCalledWith(evtId, cameraName);
+ });
+
+ it("calls disallowUserMedia on WebView", function () {
+ var evtId = 10;
+
+ webview.create();
+ webview.disallowUserMedia(evtId);
+ expect(mockedWebview.disallowUserMedia).toHaveBeenCalledWith(evtId);
+ });
+ });
+
+ describe("methods other than create", function () {
+
+ it("calls the underlying destroy", function () {
+ webview.create(mockedWebview);
+ webview.destroy();
+ expect(mockedWebview.destroy).toHaveBeenCalled();
+ });
+
+ it("sets the url property", function () {
+ var url = "http://AWESOMESAUCE.com";
+ webview.create(mockedWebview);
+ webview.setURL(url);
+ expect(mockedWebview.url).toEqual(url);
+ });
+
+ it("calls the underlying executeJavaScript", function () {
+ var js = "var awesome='Jasmine BDD'";
+ webview.create(mockedWebview);
+ webview.executeJavascript(js);
+ expect(mockedWebview.executeJavaScript).toHaveBeenCalledWith(js);
+ });
+ it("calls the underlying windowGroup property", function () {
+ webview.create(mockedWebview);
+ expect(webview.windowGroup()).toEqual(mockedWebview.windowGroup);
+ });
+
+ it("expect the config to set the extraHttpHeader", function () {
+ webview.create();
+ waits(1);
+ runs(function () {
+ expect(mockedWebview.extraHttpHeaders).toEqual({"rim-header": "RIM-Widget:rim/widget"});
+ });
+ });
+
+ it("expect the config to set the user agent", function () {
+ webview.create();
+ waits(1);
+ runs(function () {
+ expect(mockedWebview.userAgent).toEqual("Some extremely long user agent (with) spe/cial, characters");
+ });
+ });
+
+ it("expect reload to be defined", function () {
+ webview.create();
+ waits(1);
+ expect(webview.reload).toBeDefined();
+ webview.reload();
+ expect(mockedWebview.reload).toHaveBeenCalled();
+ });
+ });
+
+ describe("methods for sensitivity", function () {
+
+ it("setter getter for sensitivity", function () {
+ webview.create(mockedWebview);
+ webview.setSensitivity("Something");
+ expect(mockedWebview.setSensitivity).toHaveBeenCalled();
+ webview.getSensitivity();
+ expect(mockedWebview.getSensitivity).toHaveBeenCalled();
+ });
+
+ it("setter getter for background", function () {
+ webview.create(mockedWebview);
+ webview.setBackgroundColor("Something");
+ expect(mockedWebview.setBackgroundColor).toHaveBeenCalled();
+ webview.getBackgroundColor();
+ expect(mockedWebview.getBackgroundColor).toHaveBeenCalled();
+ });
+
+ });
+
+});
[14/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ProgressDialog.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ProgressDialog.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ProgressDialog.java
deleted file mode 100644
index 842b97a..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/ProgressDialog.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.notification;
-
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.ui.SpacerField;
-
-import net.rim.device.api.system.Characters;
-import net.rim.device.api.ui.UiApplication;
-import net.rim.device.api.ui.component.GaugeField;
-import net.rim.device.api.ui.component.LabelField;
-import net.rim.device.api.ui.component.SeparatorField;
-import net.rim.device.api.ui.container.PopupScreen;
-import net.rim.device.api.ui.container.VerticalFieldManager;
-
-/**
- * A Popup progress dialog box with an optional title and message and a progress
- * bar with a range from 0 to 100 (percent).
- */
-public final class ProgressDialog extends PopupScreen {
- private static ProgressDialog dialog = null;
- private GaugeField gauge = null;
-
- /**
- * Construct a progress dialog, with customizable title and message.
- *
- * @param title
- * Title of the progress dialog
- * @param message
- * Message to print in the body of the dialog
- */
- private ProgressDialog(String title, String message) {
- super(new VerticalFieldManager());
-
- if (title != null && title.length() > 0) {
- add(new LabelField(title));
- add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
- }
-
- if (message != null && message.length() > 0) {
- add(new SpacerField(0, 20));
- add(new LabelField(message, FIELD_HCENTER | FIELD_VCENTER));
- }
- add(new SpacerField(0, 20));
-
- gauge = new GaugeField(null, 0, 100, 0, GaugeField.PERCENT
- | GaugeField.FIELD_HCENTER);
- add(gauge);
- add(new SpacerField(0, 20));
- }
-
- /**
- * Changes the value displayed in the dialogs GaugeField.
- *
- * @param args
- * JSONArray of arguments.
- * @return a PluginResult indicating success or error.
- */
- static synchronized PluginResult setValue(JSONArray args) {
- if (dialog != null) {
- if (args.length() > 0 && !args.isNull(0)) {
- int value = -1;
- try {
- value = args.getInt(0);
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "JSONException: " + e.getMessage());
- }
-
- if (value >= 0 && value <= 100) {
- dialog.setValue(value);
- }
- }
- }
- return new PluginResult(PluginResult.Status.OK, "");
- }
-
- /**
- * Creates and displays the progress dialog.
- *
- * @param args
- * JSONArray of arguments.
- * @return a PluginResult indicating success or error.
- */
- static synchronized PluginResult start(JSONArray args) {
- if (dialog == null) {
- String message = null;
- String title = null;
-
- // Title and message are optional, grab the strings from the args
- // if they are there.
- if (args != null && args.length() > 0) {
- try {
- if (!args.isNull(0)) {
- title = args.getString(0);
- }
- if (args.length() > 1 && !args.isNull(1)) {
- message = args.getString(1);
- }
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "JSONException: " + e.getMessage());
- }
- }
-
- dialog = new ProgressDialog(title, message);
- final UiApplication uiApp = UiApplication.getUiApplication();
- uiApp.invokeLater(new Runnable() {
- public void run() {
- uiApp.pushModalScreen(dialog);
- }
- });
- }
-
- return new PluginResult(PluginResult.Status.OK, "");
- }
-
- /**
- * Closes the progress dialog.
- *
- * @return a PluginResult indicating success or error.
- */
- static synchronized PluginResult stop() {
- if (dialog != null) {
- final UiApplication uiApp = UiApplication.getUiApplication();
- final ProgressDialog tmpDialog = dialog;
- uiApp.invokeLater(new Runnable() {
- public void run() {
- uiApp.popScreen(tmpDialog);
- }
- });
- dialog = null;
- }
-
- return new PluginResult(PluginResult.Status.OK, "");
- }
-
- /**
- * @see net.rim.device.api.ui.Screen#keyChar(char, int, int)
- */
- protected boolean keyChar(char key, int status, int time) {
- // If the user clicks back key while progress dialog is displayed, close
- // the progress dialog.
- if (key == Characters.ESCAPE) {
- stop();
- }
-
- return super.keyChar(key, status, time);
- }
-
- /**
- * Changes the value displayed in the GaugeField.
- *
- * @param value
- * the value (percentage) to set in GaugeField.
- */
- private void setValue(final int value) {
- UiApplication.getUiApplication().invokeLater(new Runnable() {
- public void run() {
- gauge.setValue(value);
- }
- });
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/VibrateAction.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/VibrateAction.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/VibrateAction.java
deleted file mode 100644
index 76a545f..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/notification/VibrateAction.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.notification;
-
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-
-import net.rim.device.api.system.Alert;
-
-/**
- * Vibrate Action
- *
- * Vibrates the device for specified duration.
- */
-public class VibrateAction {
-
- private static final int DEFAULT_DURATION = 1000;
-
- /**
- * Vibrates the device for a given amount of time.
- *
- * @param args JSONArray formatted as [ duration ]
- * duration: specifies the vibration length in milliseconds (default: 1000).
- * @return A PluginResult object with the success or failure state for vibrating the device.
- */
- public static PluginResult execute(JSONArray args) {
- PluginResult result = null;
-
- if (Alert.isVibrateSupported()) {
- try {
- int duration = (args.length() >= 1) ? args.getInt(0) : DEFAULT_DURATION;
-
- Alert.startVibrate(duration);
- }
- catch (JSONException e) {
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSONException: " + e.getMessage());
- }
-
- result = new PluginResult(PluginResult.Status.OK, "OK");
- }
- else {
- result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION, "Vibrate not supported");
- }
-
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/pim/Contact.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/pim/Contact.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/pim/Contact.java
deleted file mode 100644
index 3e8e6d7..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/pim/Contact.java
+++ /dev/null
@@ -1,430 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.pim;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.HttpConnection;
-import javax.microedition.pim.PIM;
-import javax.microedition.pim.PIMException;
-import javax.microedition.pim.PIMItem;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.http.HttpUtils;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.util.FileUtils;
-import org.apache.cordova.util.Logger;
-
-import net.rim.blackberry.api.pdap.BlackBerryContact;
-import net.rim.blackberry.api.pdap.BlackBerryContactList;
-import net.rim.device.api.io.Base64InputStream;
-import net.rim.device.api.io.FileNotFoundException;
-import net.rim.device.api.io.IOUtilities;
-import net.rim.device.api.io.http.HttpProtocolConstants;
-import net.rim.device.api.math.Fixed32;
-import net.rim.device.api.system.Bitmap;
-import net.rim.device.api.system.EncodedImage;
-import net.rim.device.api.system.PNGEncodedImage;
-
-/**
- * Performs operations on Contacts stored in the BlackBerry Contacts database.
- */
-public class Contact extends Plugin {
-
- /**
- * Possible actions
- */
- public static final int ACTION_SET_PICTURE = 0;
- public static final int ACTION_GET_PICTURE = 1;
-
- /**
- * Maximum object size is 64KB in contact database. The raw image is Base64
- * encoded before insertion.
- * Base64 = (Bytes + 2 - ((Bytes + 2) MOD 3)) / 3 * 4
- */
- private static final long MAX_BYTES = 46080L;
-
- /**
- * Executes the requested action and returns a PluginResult.
- *
- * @param action The action to execute.
- * @param callbackId The callback ID to be invoked upon action completion.
- * @param args JSONArry of arguments for the action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
-
- PluginResult result = null;
- int a = getAction(action);
-
- // perform specified action
- if (a == ACTION_SET_PICTURE) {
- // get parameters
- String uid;
- String type;
- String value;
- try {
- uid = args.isNull(0) ? null : args.getString(0);
- type = args.isNull(1) ? null : args.getString(1).toLowerCase();
- value = args.isNull(2) ? null : args.getString(2);
- } catch (JSONException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "Invalid or missing photo parameters");
- }
-
- // get the raw image data
- byte[] photo = null;
- if ("base64".equals(type)) {
- // decode the image string
- try {
- photo = decodeBase64(value.getBytes());
- }
- catch (Exception e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.ERROR, "Unable to decode image.");
- }
- }
- else {
- // retrieve the photo from URL
- try {
- photo = getPhotoFromUrl(value);
- }
- catch (Exception e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.ERROR, "Unable to retrieve image at " + value);
- }
- }
-
- // set the contact picture
- result = setPicture(uid, photo);
- }
- else if (a == ACTION_GET_PICTURE) {
- // get required parameters
- String uid = null;
- try {
- uid = args.getString(0);
- } catch (JSONException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "Invalid or missing image URL");
- }
- result = getPictureURI(uid);
- }
- else {
- // invalid action
- result = new PluginResult(PluginResult.Status.INVALID_ACTION,
- "Contact: invalid action " + action);
- }
-
- return result;
- }
-
- /**
- * Decodes the base64 encoded data provided.
- * @param data Base64 encoded data
- * @return byte array containing decoded data
- * @throws IllegalArgumentException if encodedData is null
- * @throws IOException if there is an error decoding
- */
- protected byte[] decodeBase64(final byte[] encodedData) throws IllegalArgumentException, IOException {
- if (encodedData == null) {
- throw new IllegalArgumentException();
- }
- ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encodedData, 0, encodedData.length);
- Base64InputStream base64InputStream = new Base64InputStream(byteArrayInputStream);
- byte[] raw = null;
- try {
- raw = IOUtilities.streamToBytes(base64InputStream);
- }
- finally {
- base64InputStream.close();
- }
- return raw;
- }
-
- /**
- * Sets the photo of the specified contact to the picture at the specified URL.
- * Local file-based (file:///) and web-based (http://) URLs are supported.
- * The specified photo is retrieved and a scaled down copy is created and stored
- * in the contacts database.
- * @param uid Unique identifier of contact
- * @param url URL of the photo to use for contact photo
- * @return PluginResult providing status of operation
- */
- protected PluginResult setPicture(final String uid, final byte[] photo) {
- Logger.log(this.getClass().getName() + ": setting picture for contact " + uid);
-
- // We need to ensure the image encoding is supported, and resize the image
- // so that it will fit in the persistent store. Note: testing indicates
- // that the max image size is 64KB, so we scale it down considerably.
- byte[] thumbnail = null;
- try {
- thumbnail = resizeImage(photo);
- }
- catch (IllegalArgumentException e) {
- // unsupported image format
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Unsupported image format.");
- }
-
- // lookup contact and save the photo
- BlackBerryContactList contactList = null;
- try {
- // lookup the contact
- contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(
- PIM.CONTACT_LIST, PIM.READ_WRITE);
- BlackBerryContact contact = contactList.getByUID(uid);
- if (contact == null) {
- return new PluginResult(PluginResult.Status.ERROR, "Contact " + uid + " not found.");
- }
-
- // save photo image
- if(contact.countValues(javax.microedition.pim.Contact.PHOTO) > 0) {
- contact.setBinary(javax.microedition.pim.Contact.PHOTO, 0,
- PIMItem.ATTR_NONE, thumbnail, 0, thumbnail.length);
- }
- else {
- contact.addBinary(javax.microedition.pim.Contact.PHOTO,
- PIMItem.ATTR_NONE, thumbnail, 0, thumbnail.length);
- }
-
- // commit contact record to persistent store
- contact.commit();
- }
- catch (Exception e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
- }
- finally {
- // be sure to close the contact list to avoid locking it up
- if (contactList != null) {
- try { contactList.close(); } catch (PIMException ignored) { }
- }
- }
-
- return new PluginResult(PluginResult.Status.OK);
- }
-
- /**
- * Returns the URI of the contact photo. The photo image is extracted from
- * the Contacts database and saved to a temporary file system. The URI of
- * the saved photo is returned.
- * @param uid unique Contact identifier
- * @return PluginResult containing photo URI
- */
- protected PluginResult getPictureURI(final String uid) {
- Logger.log(this.getClass().getName() + ": retrieving picture for contact " + uid);
- String photoPath = null;
-
- // lookup contact
- BlackBerryContactList contactList = null;
- try {
- // lookup the contact
- contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(
- PIM.CONTACT_LIST, PIM.READ_WRITE);
- BlackBerryContact contact = contactList.getByUID(uid);
- if (contact == null) {
- return new PluginResult(PluginResult.Status.ERROR, "Contact " + uid + " not found.");
- }
-
- // get photo
- if(contact.countValues(javax.microedition.pim.Contact.PHOTO) > 0) {
- // decode from base64
- byte[] encPhoto = contact.getBinary(javax.microedition.pim.Contact.PHOTO, 0);
- byte[] photo = Base64InputStream.decode(encPhoto, 0, encPhoto.length);
-
- // save photo to file system and return file URI
- saveImage(uid, photo);
- }
- }
- catch (Exception e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
- }
- finally {
- // be sure to close the contact list to avoid locking it up
- if (contactList != null) {
- try { contactList.close(); } catch (PIMException ignored) { }
- }
- }
-
- return new PluginResult(PluginResult.Status.OK, photoPath);
- }
-
- /**
- * Retrieves the raw image data from the URL provided.
- * @param url URL of the image
- * @return raw image data from the URL provided
- * @throws FileNotFoundException - if file URL could not be found
- * @throws IOException - if there was an error processing the image file
- */
- protected byte[] getPhotoFromUrl(final String url) throws FileNotFoundException, IOException {
- byte[] photo = null;
-
- // externally hosted image
- if (url != null && url.startsWith("http")) {
- // open connection
- HttpConnection conn = HttpUtils.getHttpConnection(url);
- if (conn == null) {
- throw new IllegalArgumentException("Invalid URL: " + url);
- }
-
- // retrieve image
- InputStream in = null;
- try {
- conn.setRequestMethod(HttpConnection.GET);
- conn.setRequestProperty(
- HttpProtocolConstants.HEADER_USER_AGENT,
- System.getProperty("browser.useragent"));
- conn.setRequestProperty(
- HttpProtocolConstants.HEADER_KEEP_ALIVE, "300");
- conn.setRequestProperty(
- HttpProtocolConstants.HEADER_CONNECTION, "keep-alive");
- conn.setRequestProperty(
- HttpProtocolConstants.HEADER_CONTENT_TYPE,
- HttpProtocolConstants.CONTENT_TYPE_IMAGE_STAR);
-
- // send request and get response
- int rc = conn.getResponseCode();
- if (rc != HttpConnection.HTTP_OK) {
- throw new IOException("HTTP connection error: " + rc);
- }
- in = conn.openDataInputStream();
- photo = IOUtilities.streamToBytes(in, 64*1024);
- in.close();
- }
- finally {
- conn.close();
- }
- }
- // local image file
- else {
- photo = FileUtils.readFile(url, Connector.READ);
- }
- return photo;
- }
-
- /**
- * Saves the contact image to a temporary directory.
- * @param uid unique contact identifier
- * @param photo encoded photo image data
- * @throws IOException
- */
- protected void saveImage(final String uid, final byte[] photo) throws IOException {
- // create a temporary directory to store the contacts photos
- String contactsDir = "Contacts";
- String tempDir = FileUtils.getApplicationTempDirPath() + contactsDir;
- if (!FileUtils.exists(tempDir)) {
- FileUtils.createTempDirectory(contactsDir);
- }
-
- // save the photo image to the temporary directory, overwriting if necessary
- String photoPath = tempDir + FileUtils.FILE_SEPARATOR + uid + ".png";
- if (FileUtils.exists(photoPath)) {
- FileUtils.delete(photoPath);
- }
- FileUtils.writeFile(photoPath, photo, 0);
- }
-
- /**
- * Creates a scaled copy of the specified image.
- * @param photo Raw image data
- * @return a scaled-down copy of the image provided
- * @throws IllegalArgumentException
- */
- protected byte[] resizeImage(byte[] data) throws IllegalArgumentException {
- // create an EncodedImage to make sure the encoding is supported
- EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length);
-
- // we're limited to 64KB encoding size, do we need to scale?
- if (data.length < MAX_BYTES) {
- return data;
- }
-
- // if so, try to maintain aspect ratio of original image and set max resolution
- int srcWidth = image.getWidth();
- int srcHeight = image.getHeight();
- int dstWidth, dstHeight;
- int max_rez = 150;
- if (srcWidth > srcHeight) {
- dstWidth = max_rez;
- dstHeight = (dstWidth * srcHeight)/srcWidth;
- }
- else if (srcWidth < srcHeight) {
- dstHeight = max_rez;
- dstWidth = (dstHeight * srcWidth)/srcHeight;
- }
- else {
- dstWidth = max_rez;
- dstHeight = max_rez;
- }
-
- // calculate scale factors
- int currentWidthFixed32 = Fixed32.toFP(srcWidth);
- int currentHeightFixed32 = Fixed32.toFP(srcHeight);
- int requiredWidthFixed32 = Fixed32.toFP(dstWidth);
- int requiredHeightFixed32 = Fixed32.toFP(dstHeight);
- int scaleXFixed32 = Fixed32.div(currentWidthFixed32,
- requiredWidthFixed32);
- int scaleYFixed32 = Fixed32.div(currentHeightFixed32,
- requiredHeightFixed32);
-
- // scale image (must be redrawn)
- EncodedImage thumbnail = image.scaleImage32(scaleXFixed32, scaleYFixed32);
- Bitmap bitmap = thumbnail.getBitmap();
-
- // convert back to bytes
- PNGEncodedImage png = PNGEncodedImage.encode(bitmap);
- byte[] thumbData = png.getData();
- Logger.log(this.getClass().getName() + ": photo size reduced from " + data.length + " to " + thumbData.length);
- return thumbData;
- }
-
- /**
- * Returns action to perform.
- * @param action action to perform
- * @return action to perform
- */
- protected static int getAction(String action) {
- if ("setPicture".equals(action)) return ACTION_SET_PICTURE;
- if ("getPicture".equals(action)) return ACTION_GET_PICTURE;
- return -1;
- }
-
- /**
- * Identifies if action to be executed returns a value and should be run synchronously.
- *
- * @param action The action to execute
- * @return T=returns value
- */
- public boolean isSynch(String action) {
- if (getAction(action) == ACTION_GET_PICTURE) {
- return true;
- }
- else {
- return super.isSynch(action);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/ui/SpacerField.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/ui/SpacerField.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/ui/SpacerField.java
deleted file mode 100644
index d739617..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/ui/SpacerField.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.ui;
-
-import net.rim.device.api.ui.Field;
-import net.rim.device.api.ui.Graphics;
-
-/**
- * Provides an empty spacer field that can be used to provide custom spacing
- * between UI fields within a UI screen.
- */
-public class SpacerField extends Field {
-
- int width; // spacer width in pixels
- int height; // space height in pixels
-
- /**
- * Constructor.
- * @param width Width of the spacer in pixels.
- * @param height Height of the spacer in pixels.
- */
- public SpacerField(int width, int height) {
- super(NON_FOCUSABLE);
- this.width = width;
- this.height = height;
- }
-
- /**
- * Sets the extent to the custom width and height of this spacer.
- */
- protected void layout(int width, int height) {
- this.setExtent(this.width, this.height);
- }
-
- /**
- * Paints the field.
- */
- protected void paint(Graphics graphics) {
- // supposed to be empty. don't paint anything.
- }
-
- /**
- * Returns the custom width of this spacer as the preferred field width.
- */
- public int getPreferredWidth() {
- return this.width;
- }
-
- /**
- * Returns the custom height of this spacer as the preferred field height.
- */
- public int getPreferredHeight() {
- return this.height;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/ApplicationUtils.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/ApplicationUtils.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/ApplicationUtils.java
deleted file mode 100644
index e9ed784..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/ApplicationUtils.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.util;
-
-import org.apache.cordova.camera.Camera;
-
-import net.rim.device.api.system.ApplicationDescriptor;
-import net.rim.device.api.system.ApplicationManager;
-import net.rim.device.api.system.Characters;
-import net.rim.device.api.system.CodeModuleManager;
-import net.rim.device.api.system.ControlledAccessException;
-import net.rim.device.api.system.EventInjector;
-import net.rim.device.api.ui.UiApplication;
-
-public class ApplicationUtils {
- /**
- * Determines if the specified application is running in the foreground.
- *
- * @param handle
- * the name of the application handle (e.g., net_rim_bb_camera")
- * @return <code>true</code> if the application is running and in the
- * foreground
- */
- public static boolean isApplicationInForeground(String handle) {
- // determine if the specified application is running in the foreground
- ApplicationManager manager = ApplicationManager.getApplicationManager();
- int foregroundProcessId = manager.getForegroundProcessId();
- ApplicationDescriptor descriptors[] = manager.getVisibleApplications();
- for (int i = 0; i < descriptors.length; i++) {
- if (descriptors[i].getModuleName().equals(handle)
- && manager.getProcessId(descriptors[i]) == foregroundProcessId) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Determines if the specified application is installed.
- *
- * @param handle
- * the name of the application handle (e.g., net_rim_bb_camera")
- * @return <code>true</code> if the application is installed on the device
- */
- public static boolean isModuleInstalled(String handle) {
- return (CodeModuleManager.getModuleHandle(handle) != 0);
- }
-
- /**
- * Use this method when another native application has been launched by this
- * application, and you would like the application to be closed.
- * <p>
- * Unfortunately, the only way to do this programmatically is to simulate
- * the Escape (back) key being pressed. We do this by injecting key events,
- * which means the application permissions must have the key injection
- * permissions enabled for it to work.
- * <p>
- * An alternative to closing the applications would be to simply request
- * that our application be brought to the foreground; however, this just
- * pushes all the applications we've launched to the background, leaving a
- * mess for the user to cleanup after this application has been closed.
- *
- * @param repeat
- * the number of times to press the Esc key
- */
- public static void injectEscKeyPress(final int repeat) {
- // simulate escape characters (back button press)
- Runnable escKeyPresser = new Runnable() {
- public void run() {
- try {
- EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
- EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE,
- 0);
- int count = 0;
- while (count < repeat) {
- inject.post();
- count++;
- }
- }
- catch (ControlledAccessException e) {
- // the application doesn't have key injection
- // permissions
- Logger.log(Camera.class.getName() + ": "
- + ApplicationDescriptor
- .currentApplicationDescriptor().getName()
- + " does not have key injection permissions.");
- }
- }
- };
- UiApplication.getUiApplication().invokeLater(escKeyPresser);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/FileUtils.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/FileUtils.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/FileUtils.java
deleted file mode 100644
index 20ef492..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/FileUtils.java
+++ /dev/null
@@ -1,730 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.util;
-
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Enumeration;
-import java.util.Random;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.file.FileConnection;
-import javax.microedition.io.file.FileSystemRegistry;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.file.File;
-
-import net.rim.device.api.io.FileNotFoundException;
-import net.rim.device.api.io.IOUtilities;
-import net.rim.device.api.io.MIMETypeAssociations;
-import net.rim.device.api.system.Application;
-import net.rim.device.api.system.ControlledAccessException;
-
-/**
- * Contains file utility methods.
- */
-public class FileUtils {
-
- public static final String FILE_SEPARATOR = System.getProperty("file.separator");
- public static final String LOCAL_PROTOCOL = "local://";
- public static final String FILE_PROTOCOL = "file://";
-
- private static final String APP_TMP_DIR;
-
- // init APP_TMP_DIR with a random value
- static {
- Random gen = new Random();
- APP_TMP_DIR = "tmp" + Math.abs(gen.nextInt());
- }
-
- /**
- * Reads file as byte array.
- * @param filePath Full path of the file to be read
- * @param mode One of Connector.READ, READ_WRITE, WRITE
- * @return file content as a byte array
- */
- public static byte[] readFile(String filePath, int mode) throws FileNotFoundException, IOException {
- byte[] blob = null;
- DataInputStream dis = null;
- try {
- dis = openDataInputStream(filePath, mode);
- blob = IOUtilities.streamToBytes(dis);
- }
- finally {
- try {
- if (dis != null) dis.close();
- }
- catch (IOException ignored) {
- }
- }
- return blob;
- }
-
- /**
- * Utility function to open a DataInputStream from a file path.
- *
- * A file can be referenced with the following protocols:
- * - System.getProperty("fileconn.dir.*")
- * - local:/// references files bundled with the application
- *
- * @param filePath The full path to the file to open
- * @param mode One of Connector.READ, READ_WRITE, WRITE
- * @return Handle to the DataInputStream
- */
- private static DataInputStream openDataInputStream(final String filePath, int mode) throws FileNotFoundException, IOException {
- FileConnection fconn = null;
- DataInputStream dis = null;
- try {
- if (filePath.startsWith(LOCAL_PROTOCOL)) {
- // Remove local:// from filePath but leave a leading /
- dis = new DataInputStream(Application.class.getResourceAsStream(filePath.substring(8)));
- }
- else {
- fconn = (FileConnection)Connector.open(filePath, mode);
- if (!fconn.exists()) {
- throw new FileNotFoundException(filePath + " not found");
- }
- dis = fconn.openDataInputStream();
- }
-
- if (dis == null) {
- throw new FileNotFoundException(filePath + " not found");
- }
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- }
- catch (IOException ignored) {
- }
- }
-
- return dis;
- }
-
- /**
- * Writes data to the specified file.
- *
- * @param filePath
- * Full path of file to be written to
- * @param data
- * Data to be written
- * @param position
- * Position at which to begin writing
- * @return length of data written to file
- * @throws SecurityException
- * if the application does not have write access to the file
- * @throws IOException
- * if directory structure does not exist or an unspecified error
- * occurs
- */
- public static int writeFile(String filePath, byte[] data, int position)
- throws SecurityException, IOException {
- FileConnection fconn = null;
- OutputStream os = null;
- try {
- fconn = (FileConnection) Connector.open(filePath,
- Connector.READ_WRITE);
- if (!fconn.exists()) {
- fconn.create();
- } else {
- // Originally, this did an overwrite in place and did not
- // truncate. The truncate was added to match behavior on
- // other platforms.
- fconn.truncate(position);
- }
- os = fconn.openOutputStream(position);
- os.write(data);
- }
- finally {
- try {
- if (os != null)
- os.close();
- if (fconn != null)
- fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- return data.length;
- }
-
- /**
- * Deletes the specified file or directory from file system. If the
- * specified path is a directory, the deletion is recursive.
- *
- * @param path
- * full path of file or directory to be deleted
- * @throws IOException
- */
- public static void delete(String path) throws IOException {
- FileConnection fconn = null;
- try {
- fconn = (FileConnection)Connector.open(path, Connector.READ_WRITE);
- if (fconn.exists()) {
- // file
- if (!fconn.isDirectory()) {
- fconn.delete();
- Logger.log(FileUtils.class.getName() + ": " + path + " deleted");
- }
- // directory
- else {
- if (!path.endsWith(FILE_SEPARATOR)) {
- path += FILE_SEPARATOR;
- }
-
- // recursively delete directory contents
- Enumeration contents = fconn.list("*", true);
- if (contents.hasMoreElements()) {
- fconn.close();
- while (contents.hasMoreElements()) {
- delete(path + contents.nextElement().toString());
- }
- fconn = (FileConnection)Connector.open(path, Connector.READ_WRITE);
- }
- // now delete this directory
- fconn.delete();
- Logger.log(FileUtils.class.getName() + ": " + path + " deleted");
- }
- }
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- }
-
- /**
- * Creates a directory. Directories in the specified path are not created
- * recursively. If the directory already exists, no action is taken.
- *
- * @param dirPath
- * full path of directory to create
- * @throws IOException
- * if the target file system is not accessible, or an
- * unspecified error occurs
- */
- public static void mkdir(String dirPath) throws IOException {
- FileConnection fconn = null;
- try {
- fconn = (FileConnection)Connector.open(dirPath);
- if (fconn.isDirectory()) {
- // nothing to do
- return;
- }
- fconn.mkdir();
- } catch (ControlledAccessException e) {
- Logger.log("ControlledAccessException on dir " + dirPath + ", either directory conflict after reinstall of app, or device is connected via usb, see Cordova Docs File Blackberry Quirks");
- Logger.log(e.toString());
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- }
-
- /**
- * Determines the size of a file on the file system. Size always represents number of bytes contained in the file; never pre-allocated but empty space
- * @return size in bytes of the selected file, or -1 if the file does not exist or is inaccessible
- */
- public static long fileSize(String path) throws IOException {
- FileConnection fconn = null;
- long fsize = -1;
- try {
- fconn = (FileConnection)Connector.open(path);
- fsize = fconn.fileSize();
- } catch (IOException e) {
- Logger.log(FileUtils.class.getName() + " fileSize: " + path + "not found or inaccessible");
- } finally {
- try {
- if (fconn != null) fconn.close();
- } catch (IOException ignored) {}
- }
- return fsize;
- }
-
- /**
- * Copies a file or directory to a new location. If copying a directory, the
- * entire contents of the directory are copied recursively.
- *
- * @param srcPath
- * the full path of the file or directory to be copied
- * @param parent
- * the full path of the target directory to which the file or
- * directory should be copied
- * @param newName
- * the new name of the file or directory
- * @throws IllegalArgumentException
- * if an invalid source or destination path is provided
- * @throws FileNotFoundException
- * if the source path cannot be found on the file system
- * @throws SecurityException
- * if unable to create the new file or directory specified by
- * destination path
- * @throws IOException
- * if an attempt is made to copy the contents of a directory
- * into itself, or if the source and destination paths are
- * identical, or if a general error occurs
- */
- public static void copy(String srcPath, String parent, String newName)
- throws IllegalArgumentException, FileNotFoundException,
- SecurityException, IOException {
-
- FileConnection src = null;
- FileConnection dst = null;
- try {
- src = (FileConnection)Connector.open(srcPath, Connector.READ_WRITE);
-
- // ensure source exists
- if (!src.exists()) {
- throw new FileNotFoundException("Path not found: " + srcPath);
- }
-
- // ensure target parent directory exists
- if (!isDirectory(parent)) {
- throw new FileNotFoundException("Target directory not found: " + parent);
- }
-
- // form full destination path
- if (!parent.endsWith(FileUtils.FILE_SEPARATOR)) {
- parent += FileUtils.FILE_SEPARATOR;
- }
- String dstPath = parent + newName;
-
- // source is a directory
- if (src.isDirectory()) {
- // target should also be directory; append file separator
- if (!dstPath.endsWith(FILE_SEPARATOR)) {
- dstPath += FILE_SEPARATOR;
- }
-
- // can't copy directory into itself
- // file:///SDCard/tmp/ --> file:///SDCard/tmp/tmp/ ==> NO!
- // file:///SDCard/tmp/ --> file:///SDCard/tmp/ ==> NO!
- // file:///SDCard/tmp/ --> file:///SDCard/tmp2/ ==> OK
- String srcURL = src.getURL();
- if (dstPath.startsWith(srcURL)) {
- throw new IOException("Cannot copy directory into itself.");
- }
-
- // create the destination directory
- mkdir(dstPath);
-
- // recursively copy directory contents
- Enumeration contents = src.list("*", true);
- if (contents.hasMoreElements()) {
- src.close();
- while (contents.hasMoreElements()) {
- String name = contents.nextElement().toString();
- copy(srcURL + name, dstPath, name);
- }
- }
- }
- // source is a file
- else {
- // can't copy file onto itself
- if (dstPath.equals(srcPath)) {
- throw new IOException("Cannot copy file onto itself.");
- }
-
- dst = (FileConnection) Connector.open(dstPath, Connector.READ_WRITE);
-
- // replace existing file, but not directory
- if (dst.exists()) {
- if (dst.isDirectory()) {
- throw new IOException(
- "Cannot overwrite existing directory.");
- }
- else {
- dst.delete();
- }
- }
- dst.create();
-
- // copy the contents - wish there was a better way
- InputStream is = null;
- OutputStream os = null;
- try {
- is = src.openInputStream();
- os = dst.openOutputStream();
- byte[] buf = new byte[1024];
- int len;
- while ((len = is.read(buf)) > 0) {
- os.write(buf, 0, len);
- }
- }
- finally {
- if (is != null) is.close();
- if (os != null) os.close();
- }
- }
- }
- finally {
- try {
- if (src != null) src.close();
- if (dst != null) dst.close();
- }
- catch (IOException ignored) {
- }
- }
- }
-
- /**
- * Creates an temporary directory for the application. The temporary
- * directory is created in the following location:
- * <code><root>/tmpGUID/</code> where <code><root>/</code>
- * is the path of the writable directory on the file system (could be the SD
- * card, if present, or the root file system on internal storage); and
- * <code>tmpGUID/</code> is a application temporary directory that is
- * created using the unique application GUID. If the application temporary
- * directory does not exist, invoking this method will create it.
- * <em>NOTE:</em> The <code><root>/tmpGUID/</code> application
- * temporary directory and all its contents are deleted upon application
- * exit.
- *
- * @return full path name of the application temporary directory
- * @throws IOException
- * if there are no file systems mounted, or an unspecified error
- * occurs
- */
- public static String createApplicationTempDirectory() throws IOException {
- // <root>/tmpGUID/
- String tmpDir = getApplicationTempDirPath();
- mkdir(tmpDir);
-
- return tmpDir;
- }
-
- /**
- * Creates a temporary directory on the writable storage area of the file
- * system. The temporary directory is created in the following location:
- * <code><root>/tmpGUID/dirName/</code> where
- * <code><root>/tmpGUID/</code> is an application temporary
- * directory that is created using the unique application GUID; and
- * <code>dirName/</code> is an optional directory name to create beneath the
- * application temporary directory. If the application temporary directory
- * does not exist, invoking this method will create it. <em>NOTE:</em> The
- * <code><root>/tmpGUID/</code> application temporary directory
- * and all its contents are deleted upon application exit.
- *
- * @param dirName
- * name of directory to be created beneath the application
- * temporary directory
- * @return full path name of the directory that was created
- * @throws IOException
- * if there are no file systems mounted, or an unspecified error
- * occurs
- */
- public static String createTempDirectory(String dirName) throws IOException {
- // create the application temp directory
- String tmpDir = createApplicationTempDirectory();
-
- // create specified sub-directory as "<root>/tmpGUID/dirName/"
- dirName = (dirName == null) ? "" : dirName.trim();
- if (dirName.length() > 0) {
- if (!dirName.endsWith(FILE_SEPARATOR)) {
- dirName += FILE_SEPARATOR;
- }
- tmpDir += dirName;
- mkdir(tmpDir);
- }
- return tmpDir;
- }
-
- /**
- * Attempts to delete the application temporary directory and all contents.
- * The application temporary directory is:
- * <code><root>/tmpGUID/</code>, where <code><root></code> is
- * the file system root (could be the SD card or internal storage); and
- * <code>tmpGUID</code> is the application temporary directory that is
- * created using the unique application GUID. <em>NOTE:</em> The
- * <code>tmpGUID</code> application temporary directory and all
- * sub-directories are deleted upon application exit.
- *
- * @throws IOException
- * if an unspecified error occurs
- */
- public synchronized static void deleteApplicationTempDirectory()
- throws IOException {
- String tmpDir = getApplicationTempDirPath();
- delete(tmpDir);
- }
-
- /**
- * Returns the full path of the application temporary directory. The path
- * points to the following location: <code><root>/tmpGUID/</code>
- * where <code><root>/</code> is the path of the writable directory on
- * the file system (could be the SD card, if present, or the root file system
- * on internal storage); and <code>tmpGUID/</code> is a application temporary
- * directory that is created using the unique application GUID. The
- * directory may not exist. Invoke
- * <code>createApplicationTempDirectory</code> to create it.
- *
- * @return the full path name of the application temporary directory
- */
- public static String getApplicationTempDirPath() {
- return getFileSystemRoot() + APP_TMP_DIR + FILE_SEPARATOR;
- }
-
- /**
- * Returns the full path of a root file system. Will return the path of the
- * SD card first, if it exists, or the root file system located on internal
- * storage.
- *
- * @return full path that can be used to store files
- */
- public static String getFileSystemRoot() {
- String root = null;
- String sdcard = getSDCardPath();
-
- // retrieve root list
- Enumeration e = FileSystemRegistry.listRoots();
- while (e.hasMoreElements()) {
- root = "file:///" + (String) e.nextElement();
- // system directory won't be writable
- if (root.endsWith("system/")) {
- continue;
- }
- // prefer the SDCard
- else if (root.equals(sdcard)) {
- break;
- }
- }
- return root;
- }
-
- /**
- * Returns the full path name to external storage (SD card, e.g.
- * file:///SDCard/).
- *
- * @return full path name to the external storage (SD card)
- */
- public static String getSDCardPath() {
- return System.getProperty("fileconn.dir.memorycard");
- }
-
- /**
- * Returns the full path name of the user directory located on internal
- * storage (e.g. file:///store/home/user/).
- *
- * @return full path name of the user directory
- */
- public static String getUserPath() {
- // grab the music folder
- String musicDir = System.getProperty("fileconn.dir.music");
- // ignore trailing '/'
- int i = musicDir.lastIndexOf('/', musicDir.length() - 2);
- // strip off the last directory
- return musicDir.substring(0, i + 1);
- }
-
- /**
- * Returns the available size of the file system that the path resides on.
- *
- * @param path
- * full path of a file system entry
- * @return available size, in bytes, of the root file system
- * @throws IllegalArgumentException
- * if path is invalid
- * @throws IOException
- * if an error occurs
- */
- public static long availableSize(String path)
- throws IllegalArgumentException, IOException {
- long availableSize = 0;
- FileConnection fconn = null;
- try {
- fconn = (FileConnection) Connector.open(path);
- availableSize = fconn.availableSize();
- }
- finally {
- try {
- if (fconn != null)
- fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- return availableSize;
- }
-
- /**
- * Determines if the specified file system path exists.
- * @param path full path of file or directory
- * @return true if the file or directory exists
- */
- public static boolean exists(String path) {
- boolean exists = false;
- FileConnection fconn = null;
- try {
- fconn = (FileConnection)Connector.open(path);
- exists = fconn.exists();
- }
- catch (IllegalArgumentException e) {
- Logger.log(FileUtils.class.getName() + ": " + e);
- }
- catch (IOException e) {
- Logger.log(FileUtils.class.getName() + ": " + e);
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- return exists;
- }
-
- /**
- * Determines if the specified file system path refers to a directory.
- * @param path full path of file or directory
- * @return true if the file path exists, is accessible, and is a directory
- */
- public static boolean isDirectory(String path) {
- boolean isDirectory = false;
- FileConnection fconn = null;
- try {
- fconn = (FileConnection)Connector.open(path);
- isDirectory = fconn.isDirectory();
- }
- catch (IllegalArgumentException e) {
- Logger.log(FileUtils.class.getName() + ": " + e);
- }
- catch (IOException e) {
- Logger.log(FileUtils.class.getName() + ": " + e);
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- return isDirectory;
- }
-
- /**
- * Lists the contents of a directory. Lists both files and sub-directories.
- *
- * @param path
- * full path of the directory to list
- * @return Enumeration containing names of files and sub-directories.
- * @throws FileNotFoundException
- * if path is not found
- * @throws IOException
- * if an error occurs
- */
- public static Enumeration listDirectory(String path)
- throws FileNotFoundException, IOException {
- FileConnection fconn = null;
- Enumeration listing = null;
- try {
- fconn = (FileConnection) Connector.open(path);
- if (!fconn.exists()) {
- throw new FileNotFoundException(path + " does not exist.");
- }
- listing = fconn.list();
- }
- finally {
- try {
- if (fconn != null)
- fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- return listing;
- }
-
- public static File getFileProperties(String filePath) throws FileNotFoundException {
- File file = new File(stripSeparator(filePath));
- FileConnection fconn = null;
- try {
- fconn = (FileConnection)Connector.open(filePath);
- if (!fconn.exists()) {
- throw new FileNotFoundException();
- }
- file.setLastModifiedDate(fconn.lastModified());
- file.setName(stripSeparator(fconn.getName()));
- file.setType(MIMETypeAssociations.getMIMEType(filePath));
- file.setSize(fconn.fileSize());
- }
- catch (IllegalArgumentException e) {
- Logger.log(FileUtils.class.getName() + ": " + e);
- }
- catch (IOException e) {
- Logger.log(FileUtils.class.getName() + ": " + e);
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- }
- catch (IOException ignored) {
- }
- }
- return file;
- }
-
- /**
- * Strips the trailing slash from path names.
- *
- * @param path
- * full or relative path name
- * @return formatted path (without trailing slash)
- */
- public static String stripSeparator(String path) {
- int len = FILE_SEPARATOR.length();
- while (path.endsWith(FILE_SEPARATOR)) {
- path = path.substring(0, path.length() - len);
- }
- return path;
- }
-
-
- /**
- * If the specified file path does not have a URI prefix, prefix it with the
- * file:/// prefix.
- *
- * @param filePath
- * @return the prefixed URI.
- */
- public static String prefixFileURI(String filePath) {
- if (!filePath.startsWith(LOCAL_PROTOCOL)
- && !filePath.startsWith(FILE_PROTOCOL)
- && !filePath.startsWith("http://")
- && !filePath.startsWith("https://")) {
- if (filePath.indexOf(FILE_SEPARATOR) != 0) {
- filePath = FILE_PROTOCOL + FILE_SEPARATOR + filePath;
- } else {
- filePath = FILE_PROTOCOL + filePath;
- }
- }
-
- return filePath;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/Log.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/Log.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/Log.java
deleted file mode 100644
index 54396e7..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/Log.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.util;
-
-import net.rim.device.api.script.Scriptable;
-import net.rim.device.api.script.ScriptableFunction;
-
-/**
- * Log provides a mechanism for JavaScript code to utilize the Event Log.
- * Log represents an object in the script engine that can be accessed from the
- * script environment using <code>cordova.Logger</code>.
- *
- * Log provides a function, <code>log(msg)</code>, that logs messages to the
- * BlackBerry Event Log as well as to System.out.
- *
- * To use of the BlackBerry Event Log from JavaScript, you must first
- * invoke the <code>enable()</code> method:
- *
- * <code>cordova.Logger.enable();</code>
- * <code>cordova.Logger.log(msg);</code>
- */
-public final class Log extends Scriptable {
-
- /**
- * Field used to log messages.
- */
- public static final String FIELD_LOG = "log";
-
- /**
- * Field used to enable message logging.
- */
- public static final String FIELD_ENABLE = "enable";
-
- /**
- * Logs messages to the BlackBerry Event Log and to <code>System.out</code>.
- */
- public final LogFunction logFunction; // logs to the Event Log
-
- /**
- * Constructor.
- */
- public Log() {
- this.logFunction = new LogFunction();
- }
-
- /**
- * The following fields are supported from the script environment:
- *
- * <code>cordova.Logger.enable</code> - Enables message logging.
- * <code>cordova.Logger.log</code> - Logs the specified message.
- */
- public Object getField(String name) throws Exception {
-
- if (name.equals(FIELD_LOG)) {
- return this.logFunction;
- }
- else if (name.equals(FIELD_ENABLE)) {
- return new ScriptableFunction() {
- public Object invoke(Object obj, Object[] oargs) throws Exception {
- Logger.enableLogging();
- return null;
- }
- };
- }
- return super.getField(name);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/LogFunction.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/LogFunction.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/LogFunction.java
deleted file mode 100644
index 918371d..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/LogFunction.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.util;
-
-import net.rim.device.api.script.ScriptableFunction;
-
-/**
- * LogFunction represents a function that can be invoked from the script
- * environment of the widget framework. Messages are logged to the BlackBerry
- * Event Log. From JavaScript, invoke
- *
- * <code>cordova.Logger.log(msg);</code>
- */
-public class LogFunction extends ScriptableFunction {
-
- public Object invoke(Object obj, Object[] oargs) throws Exception {
-
- if (oargs != null) {
- String message = (String)oargs[0];
- Logger.log(message);
- }
-
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/Logger.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/Logger.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/Logger.java
deleted file mode 100644
index c5c21ad..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/Logger.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.util;
-
-import java.util.Date;
-
-import org.apache.cordova.CordovaExtension;
-
-import net.rim.device.api.i18n.SimpleDateFormat;
-import net.rim.device.api.system.EventLogger;
-
-/**
- * Logger provides a mechanism to log the the BlackBerry Event Log. It uses
- * the BlackBerry EventLogger class.
- *
- * The Event Log can be viewed on BlackBerry simulators using Tools > Show Event
- * Log, or on physical devices by pressing the <code>Alt</code> key, followed by
- * the <code>LGLG</code> key combination.
- *
- * To enable event logging, you must first call <code>enableLogging</code>.
- *
- * Logger also provides methods to write to <code>System.out</code> and
- * <code>System.err</code>.
- */
-public class Logger {
-
- /**
- * Application name
- */
- protected static String appName;
-
- /**
- * Application GUID
- */
- protected static long appID;
-
- /**
- * Used to format dates into a standard format
- */
- private static final SimpleDateFormat dateFormat =
- new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
-
- /**
- * Invoke this method to enable logging to the BlackBerry Event Log.
- */
- public static void enableLogging() {
- appID = CordovaExtension.getAppID();
- appName = CordovaExtension.getAppName();
- if (EventLogger.register(appID, appName, EventLogger.VIEWER_STRING)) {
- log("Logger enabled: " + "GUID=" + appID + ", name=" + appName);
- }
- else {
- log("EventLogger registration failed.");
- }
- }
-
- /**
- * Sets the minimum logging level.
- */
- public static void setMinimumLoggingLevel(int level) {
- EventLogger.setMinimumLevel(level);
- }
-
- /**
- * Logs formatted message to Event Log with ALWAYS_LOG level.
- */
- public static void log(String msg) {
- logEvent(msg, EventLogger.ALWAYS_LOG);
- }
-
- /**
- * Logs formatted message to Event Log with DEBUG_INFO level.
- */
- public static void debug(String msg) {
- logEvent(msg, EventLogger.DEBUG_INFO);
- }
-
- /**
- * Logs formatted message to Event Log with INFORMATION level.
- */
- public static void info(String msg) {
- logEvent(msg, EventLogger.INFORMATION);
- }
-
- /**
- * Logs formatted message to Event Log with WARNING level.
- */
- public static void warn(String msg) {
- logEvent(msg, EventLogger.WARNING);
- }
-
- /**
- * Logs formatted message to Event Log with ERROR level.
- */
- public static void error(String msg) {
- logEvent(msg, EventLogger.ERROR);
- }
-
- /**
- * Logs formatted message to Event Log with SEVERE_ERROR level.
- */
- public static void severe(String msg) {
- logEvent(msg, EventLogger.SEVERE_ERROR);
- }
-
- /**
- * Prints unformatted message to System.out.
- */
- public static void out(String msg) {
- System.out.println(msg);
- }
-
- /**
- * Prints unformatted message to System.err.
- */
- public static void err(String msg, Throwable t) {
- System.err.println(msg);
- t.printStackTrace();
- }
-
- /**
- * Logs formatted message to Event Log (if enabled) and System.out.
- */
- private static void logEvent(String msg, int level) {
- String message = formatMessage(msg);
- EventLogger.logEvent(appID, message.getBytes(), level);
- out(message);
- }
-
- private static String formatMessage(String msg) {
- StringBuffer sb = new StringBuffer();
- sb.append(appName);
- sb.append(" [");
- sb.append(dateFormat.format(new Date()));
- sb.append("]: ");
- sb.append(msg);
- return sb.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/StringUtils.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/StringUtils.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/StringUtils.java
deleted file mode 100644
index 0a4d45d..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/util/StringUtils.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/*
- * Taken from Research in Motion knowledge base article:
- *
- * DB-00728: "How To - Implement a string splitter based on a given string delimiter", 24 March 2009.
- * http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/832062/How_To_-_Implement_a_string_splitter_based_on_a_given_string_delimiter.html?nodeid=1498848&vernum=0
- */
-package org.apache.cordova.util;
-
-/**
- * Provides various string utility methods.
- */
-public class StringUtils {
-
- //Identifies the substrings in a given string that are delimited
- //by one or more characters specified in an array, and then
- //places the substrings into a String array.
- public static String[] split(String strString, String strDelimiter) {
- String[] strArray;
- int iOccurrences = 0;
- int iIndexOfInnerString = 0;
- int iIndexOfDelimiter = 0;
- int iCounter = 0;
-
- //Check for null input strings.
- if (strString == null) {
- throw new IllegalArgumentException("Input string cannot be null.");
- }
- //Check for null or empty delimiter strings.
- if (strDelimiter.length() <= 0 || strDelimiter == null) {
- throw new IllegalArgumentException("Delimeter cannot be null or empty.");
- }
-
- //strString must be in this format: (without {} )
- //"{str[0]}{delimiter}str[1]}{delimiter} ...
- // {str[n-1]}{delimiter}{str[n]}{delimiter}"
-
- //If strString begins with delimiter then remove it in order
- //to comply with the desired format.
-
- if (strString.startsWith(strDelimiter)) {
- strString = strString.substring(strDelimiter.length());
- }
-
- //If strString does not end with the delimiter then add it
- //to the string in order to comply with the desired format.
- if (!strString.endsWith(strDelimiter)) {
- strString += strDelimiter;
- }
-
- //Count occurrences of the delimiter in the string.
- //Occurrences should be the same amount of inner strings.
- while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
- iIndexOfInnerString)) != -1) {
- iOccurrences += 1;
- iIndexOfInnerString = iIndexOfDelimiter +
- strDelimiter.length();
- }
-
- //Declare the array with the correct size.
- strArray = new String[iOccurrences];
-
- //Reset the indices.
- iIndexOfInnerString = 0;
- iIndexOfDelimiter = 0;
-
- //Walk across the string again and this time add the
- //strings to the array.
- while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
- iIndexOfInnerString)) != -1) {
-
- //Add string to array.
- strArray[iCounter] = strString.substring(iIndexOfInnerString,iIndexOfDelimiter);
-
- //Increment the index to the next character after
- //the next delimiter.
- iIndexOfInnerString = iIndexOfDelimiter +
- strDelimiter.length();
-
- //Inc the counter.
- iCounter += 1;
- }
-
- return strArray;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/PluginResult.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/PluginResult.js b/lib/cordova-blackberry/framework/lib/PluginResult.js
new file mode 100644
index 0000000..68acf23
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/PluginResult.js
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2013 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+function PluginResult (args, env) {
+
+ var CALLBACK_STATUS_NO_RESULT = 0,
+ CALLBACK_STATUS_OK = 1,
+ CALLBACK_STATUS_ERROR = 9,
+ callbackId = JSON.parse(decodeURIComponent(args.callbackId)),
+ send = function (data) {
+ env.response.send(200, encodeURIComponent(JSON.stringify(data)));
+ },
+ callback = function (success, status, data, keepCallback) {
+ var executeString = "cordova.callbackFromNative('" + callbackId + "', " +
+ !!success + ", " + status + ", [" + data + "], " + !!keepCallback + ");";
+ env.webview.executeJavaScript(executeString);
+ };
+
+ Object.defineProperty(this, "callbackId", {enumerable: true, value: callbackId});
+
+ this.noResult = function (keepCallback) {
+ send({ code: CALLBACK_STATUS_NO_RESULT, keepCallback: !!keepCallback });
+ };
+
+ this.error = function (msg, keepCallback) {
+ send({ code: CALLBACK_STATUS_ERROR, msg: msg, keepCallback: !!keepCallback });
+ };
+
+ this.ok = function (data, keepCallback) {
+ send({ code: CALLBACK_STATUS_OK, data: data, keepCallback: !!keepCallback });
+ };
+
+ this.callbackOk = function (data, keepCallback) {
+ callback(true, CALLBACK_STATUS_OK, JSON.stringify(data), keepCallback);
+ };
+
+ this.callbackError = function (msg, keepCallback) {
+ callback(false, CALLBACK_STATUS_ERROR, JSON.stringify(msg), keepCallback);
+ };
+}
+
+window.PluginResult = PluginResult;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/config.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/config.js b/lib/cordova-blackberry/framework/lib/config.js
new file mode 100644
index 0000000..6fbe527
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/config.js
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var defaults = require('./config/default'),
+ user = require('./config/user'),
+ utils = require('./utils');
+
+module.exports = utils.mixin(user,
+ utils.mixin(defaults, {}));
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/config/default.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/config/default.js b/lib/cordova-blackberry/framework/lib/config/default.js
new file mode 100644
index 0000000..31990b1
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/config/default.js
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+module.exports = {
+ configXML: "config.xml",
+ configXMLDoc: null,
+
+ backButtonBehavior: "back",
+ customHeaders: {},
+ version: "1.0.0",
+
+ author: "",
+ authorURL: "",
+ authorEmail: "",
+ copyright: "",
+ content: "index.html",
+ contentCharset: "",
+ contentType: "",
+ description: "",
+ icon: "AIRApp_72.png",
+ iconHover: "",
+ id: "",
+ license: "",
+ licenseURL: "",
+ name: "WebWorksAppTemplate",
+
+ navigationMode: "pointer",
+
+ preferredTransports: null,
+ transportTimeout: 300000,
+
+ hasMultiAccess: false,
+ widgetExtensions: null,
+ featureTable: null,
+ accessList: null,
+ permissions: null,
+
+ loadingScreenColor: "#FFFFFF",
+ backgroundImage: "",
+ foregroundImage: "",
+ onFirstLaunch: false,
+ onLocalPageLoad: false,
+ onRemotePageLoad: false,
+ transitionType: -1,
+ transitionDuration: 250,
+ transitionDirection: 128,
+
+ disableAllCache: false,
+ aggressiveCacheAge: 2592000,
+ maxCacheSizeTotal: 1024,
+ maxCacheSizeItem: 128,
+ maxStandardCacheAge: 2592000,
+
+ runOnStartUp: false,
+ allowInvokeParams: false,
+ backgroundSource: "",
+ foregroundSource: "index.html",
+ debugEnabled: false,
+ enableFormControl: true,
+ enableChildWebView: true,
+ enableWebSecurity: true,
+ enablePopupBlocker: false
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/config/user.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/config/user.js b/lib/cordova-blackberry/framework/lib/config/user.js
new file mode 100644
index 0000000..5e36885
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/config/user.js
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2010-2011 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+module.exports = {
+ authorEmail: "guocat@gmail.com",
+ copyright: "@Rebecca",
+ customHeaders: {
+ "rim-header": "RIM-Widget:rim/widget"
+ },
+ userAgent: "Some extremely long user agent (with) spe/cial, characters",
+ author: "Me",
+ version: "1.0.0.0",
+ hasMultiAccess: true,
+ license: "This is a license",
+ accessList: [{
+ allowSubDomain: false,
+ features: [{
+ version: "1.0.0.0",
+ required: true,
+ id: "blackberry.example.test"
+ }, {
+ version: "1.0.0.0",
+ required: true,
+ id: "blackberry.app"
+ }],
+ uri: "WIDGET_LOCAL"
+ }],
+ licenseURL: "",
+ authorURL: "http://bbtools_win7_01/yui",
+ foregroundSource: "derp.html",
+ backgroundColor: 0xFFFF9900,
+ content: "http://localhost/lib/public/testbed.html",
+ description: "this is the description",
+ configXML: "config.xml",
+ name: "wwTest"
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/lib/controllerWebView.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/lib/controllerWebView.js b/lib/cordova-blackberry/framework/lib/controllerWebView.js
new file mode 100644
index 0000000..9c05ebe
--- /dev/null
+++ b/lib/cordova-blackberry/framework/lib/controllerWebView.js
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var controllerWebView,
+ overlayWebView = require("./overlayWebView"),
+ controller,
+ invocation,
+ utils;
+
+controllerWebView = {
+ init: function (config) {
+ controller = window.qnx.webplatform.getController();
+ invocation = window.qnx.webplatform.getApplication().invocation;
+ utils = require('./utils');
+ controller.enableWebInspector = config.debugEnabled;
+ controller.enableCrossSiteXHR = true;
+ controller.visible = false;
+ controller.active = false;
+ controller.setGeometry(0, 0, screen.width, screen.height);
+ controller.setFileSystemSandbox = false;
+
+ /* Remote functions that are published to allow communication with
+ * the overlay webview, they are called via the RPC bridge
+ */
+ controller.publishRemoteFunction('webview.setSensitivity', function (args) {
+ var sensitivityType = args[0];
+ overlayWebView.setSensitivity(sensitivityType);
+ });
+
+ controller.publishRemoteFunction('webview.notifyContextMenuCancelled', function () {
+ overlayWebView.notifyContextMenuCancelled();
+ });
+ },
+
+ setGeometry: function (x, y, width, height) {
+ controller.setGeometry(x, y, width, height);
+ },
+
+ setApplicationOrientation: function (angle) {
+ controller.setApplicationOrientation(angle);
+ },
+
+ notifyApplicationOrientationDone: function () {
+ controller.notifyApplicationOrientationDone();
+ },
+
+ dispatchEvent: function (eventType, args) {
+ controller.dispatchEvent(eventType, args);
+ }
+};
+
+controllerWebView.__defineGetter__('id', function () {
+ return controller.id;
+});
+
+controllerWebView.__defineSetter__('onChildWebViewCreated', function (input) {
+ controller.onChildWebViewCreated = input;
+});
+module.exports = controllerWebView;
[34/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpResponseCache.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpResponseCache.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpResponseCache.java
new file mode 100644
index 0000000..8735166
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpResponseCache.java
@@ -0,0 +1,608 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.OkResponseCache;
+import com.squareup.okhttp.ResponseSource;
+import com.squareup.okhttp.internal.Base64;
+import com.squareup.okhttp.internal.DiskLruCache;
+import com.squareup.okhttp.internal.StrictLineReader;
+import com.squareup.okhttp.internal.Util;
+import java.io.BufferedWriter;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+import java.net.CacheRequest;
+import java.net.CacheResponse;
+import java.net.HttpURLConnection;
+import java.net.ResponseCache;
+import java.net.SecureCacheResponse;
+import java.net.URI;
+import java.net.URLConnection;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.Principal;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLPeerUnverifiedException;
+
+import static com.squareup.okhttp.internal.Util.US_ASCII;
+import static com.squareup.okhttp.internal.Util.UTF_8;
+
+/**
+ * Cache responses in a directory on the file system. Most clients should use
+ * {@code android.net.HttpResponseCache}, the stable, documented front end for
+ * this.
+ */
+public final class HttpResponseCache extends ResponseCache implements OkResponseCache {
+ private static final char[] DIGITS =
+ { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+
+ // TODO: add APIs to iterate the cache?
+ private static final int VERSION = 201105;
+ private static final int ENTRY_METADATA = 0;
+ private static final int ENTRY_BODY = 1;
+ private static final int ENTRY_COUNT = 2;
+
+ private final DiskLruCache cache;
+
+ /* read and write statistics, all guarded by 'this' */
+ private int writeSuccessCount;
+ private int writeAbortCount;
+ private int networkCount;
+ private int hitCount;
+ private int requestCount;
+
+ public HttpResponseCache(File directory, long maxSize) throws IOException {
+ cache = DiskLruCache.open(directory, VERSION, ENTRY_COUNT, maxSize);
+ }
+
+ private String uriToKey(URI uri) {
+ try {
+ MessageDigest messageDigest = MessageDigest.getInstance("MD5");
+ byte[] md5bytes = messageDigest.digest(uri.toString().getBytes("UTF-8"));
+ return bytesToHexString(md5bytes);
+ } catch (NoSuchAlgorithmException e) {
+ throw new AssertionError(e);
+ } catch (UnsupportedEncodingException e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ private static String bytesToHexString(byte[] bytes) {
+ char[] digits = DIGITS;
+ char[] buf = new char[bytes.length * 2];
+ int c = 0;
+ for (byte b : bytes) {
+ buf[c++] = digits[(b >> 4) & 0xf];
+ buf[c++] = digits[b & 0xf];
+ }
+ return new String(buf);
+ }
+
+ @Override public CacheResponse get(URI uri, String requestMethod,
+ Map<String, List<String>> requestHeaders) {
+ String key = uriToKey(uri);
+ DiskLruCache.Snapshot snapshot;
+ Entry entry;
+ try {
+ snapshot = cache.get(key);
+ if (snapshot == null) {
+ return null;
+ }
+ entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
+ } catch (IOException e) {
+ // Give up because the cache cannot be read.
+ return null;
+ }
+
+ if (!entry.matches(uri, requestMethod, requestHeaders)) {
+ snapshot.close();
+ return null;
+ }
+
+ return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
+ : new EntryCacheResponse(entry, snapshot);
+ }
+
+ @Override public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException {
+ if (!(urlConnection instanceof HttpURLConnection)) {
+ return null;
+ }
+
+ HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
+ String requestMethod = httpConnection.getRequestMethod();
+ String key = uriToKey(uri);
+
+ if (requestMethod.equals("POST") || requestMethod.equals("PUT") || requestMethod.equals(
+ "DELETE")) {
+ try {
+ cache.remove(key);
+ } catch (IOException ignored) {
+ // The cache cannot be written.
+ }
+ return null;
+ } else if (!requestMethod.equals("GET")) {
+ // Don't cache non-GET responses. We're technically allowed to cache
+ // HEAD requests and some POST requests, but the complexity of doing
+ // so is high and the benefit is low.
+ return null;
+ }
+
+ HttpEngine httpEngine = getHttpEngine(httpConnection);
+ if (httpEngine == null) {
+ // Don't cache unless the HTTP implementation is ours.
+ return null;
+ }
+
+ ResponseHeaders response = httpEngine.getResponseHeaders();
+ if (response.hasVaryAll()) {
+ return null;
+ }
+
+ RawHeaders varyHeaders =
+ httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
+ Entry entry = new Entry(uri, varyHeaders, httpConnection);
+ DiskLruCache.Editor editor = null;
+ try {
+ editor = cache.edit(key);
+ if (editor == null) {
+ return null;
+ }
+ entry.writeTo(editor);
+ return new CacheRequestImpl(editor);
+ } catch (IOException e) {
+ abortQuietly(editor);
+ return null;
+ }
+ }
+
+ /**
+ * Handles a conditional request hit by updating the stored cache response
+ * with the headers from {@code httpConnection}. The cached response body is
+ * not updated. If the stored response has changed since {@code
+ * conditionalCacheHit} was returned, this does nothing.
+ */
+ @Override public void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
+ throws IOException {
+ HttpEngine httpEngine = getHttpEngine(httpConnection);
+ URI uri = httpEngine.getUri();
+ ResponseHeaders response = httpEngine.getResponseHeaders();
+ RawHeaders varyHeaders =
+ httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
+ Entry entry = new Entry(uri, varyHeaders, httpConnection);
+ DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
+ ? ((EntryCacheResponse) conditionalCacheHit).snapshot
+ : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
+ DiskLruCache.Editor editor = null;
+ try {
+ editor = snapshot.edit(); // returns null if snapshot is not current
+ if (editor != null) {
+ entry.writeTo(editor);
+ editor.commit();
+ }
+ } catch (IOException e) {
+ abortQuietly(editor);
+ }
+ }
+
+ private void abortQuietly(DiskLruCache.Editor editor) {
+ // Give up because the cache cannot be written.
+ try {
+ if (editor != null) {
+ editor.abort();
+ }
+ } catch (IOException ignored) {
+ }
+ }
+
+ private HttpEngine getHttpEngine(URLConnection httpConnection) {
+ if (httpConnection instanceof HttpURLConnectionImpl) {
+ return ((HttpURLConnectionImpl) httpConnection).getHttpEngine();
+ } else if (httpConnection instanceof HttpsURLConnectionImpl) {
+ return ((HttpsURLConnectionImpl) httpConnection).getHttpEngine();
+ } else {
+ return null;
+ }
+ }
+
+ public DiskLruCache getCache() {
+ return cache;
+ }
+
+ public synchronized int getWriteAbortCount() {
+ return writeAbortCount;
+ }
+
+ public synchronized int getWriteSuccessCount() {
+ return writeSuccessCount;
+ }
+
+ public synchronized void trackResponse(ResponseSource source) {
+ requestCount++;
+
+ switch (source) {
+ case CACHE:
+ hitCount++;
+ break;
+ case CONDITIONAL_CACHE:
+ case NETWORK:
+ networkCount++;
+ break;
+ }
+ }
+
+ public synchronized void trackConditionalCacheHit() {
+ hitCount++;
+ }
+
+ public synchronized int getNetworkCount() {
+ return networkCount;
+ }
+
+ public synchronized int getHitCount() {
+ return hitCount;
+ }
+
+ public synchronized int getRequestCount() {
+ return requestCount;
+ }
+
+ private final class CacheRequestImpl extends CacheRequest {
+ private final DiskLruCache.Editor editor;
+ private OutputStream cacheOut;
+ private boolean done;
+ private OutputStream body;
+
+ public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
+ this.editor = editor;
+ this.cacheOut = editor.newOutputStream(ENTRY_BODY);
+ this.body = new FilterOutputStream(cacheOut) {
+ @Override public void close() throws IOException {
+ synchronized (HttpResponseCache.this) {
+ if (done) {
+ return;
+ }
+ done = true;
+ writeSuccessCount++;
+ }
+ super.close();
+ editor.commit();
+ }
+
+ @Override
+ public void write(byte[] buffer, int offset, int length) throws IOException {
+ // Since we don't override "write(int oneByte)", we can write directly to "out"
+ // and avoid the inefficient implementation from the FilterOutputStream.
+ out.write(buffer, offset, length);
+ }
+ };
+ }
+
+ @Override public void abort() {
+ synchronized (HttpResponseCache.this) {
+ if (done) {
+ return;
+ }
+ done = true;
+ writeAbortCount++;
+ }
+ Util.closeQuietly(cacheOut);
+ try {
+ editor.abort();
+ } catch (IOException ignored) {
+ }
+ }
+
+ @Override public OutputStream getBody() throws IOException {
+ return body;
+ }
+ }
+
+ private static final class Entry {
+ private final String uri;
+ private final RawHeaders varyHeaders;
+ private final String requestMethod;
+ private final RawHeaders responseHeaders;
+ private final String cipherSuite;
+ private final Certificate[] peerCertificates;
+ private final Certificate[] localCertificates;
+
+ /**
+ * Reads an entry from an input stream. A typical entry looks like this:
+ * <pre>{@code
+ * http://google.com/foo
+ * GET
+ * 2
+ * Accept-Language: fr-CA
+ * Accept-Charset: UTF-8
+ * HTTP/1.1 200 OK
+ * 3
+ * Content-Type: image/png
+ * Content-Length: 100
+ * Cache-Control: max-age=600
+ * }</pre>
+ *
+ * <p>A typical HTTPS file looks like this:
+ * <pre>{@code
+ * https://google.com/foo
+ * GET
+ * 2
+ * Accept-Language: fr-CA
+ * Accept-Charset: UTF-8
+ * HTTP/1.1 200 OK
+ * 3
+ * Content-Type: image/png
+ * Content-Length: 100
+ * Cache-Control: max-age=600
+ *
+ * AES_256_WITH_MD5
+ * 2
+ * base64-encoded peerCertificate[0]
+ * base64-encoded peerCertificate[1]
+ * -1
+ * }</pre>
+ * The file is newline separated. The first two lines are the URL and
+ * the request method. Next is the number of HTTP Vary request header
+ * lines, followed by those lines.
+ *
+ * <p>Next is the response status line, followed by the number of HTTP
+ * response header lines, followed by those lines.
+ *
+ * <p>HTTPS responses also contain SSL session information. This begins
+ * with a blank line, and then a line containing the cipher suite. Next
+ * is the length of the peer certificate chain. These certificates are
+ * base64-encoded and appear each on their own line. The next line
+ * contains the length of the local certificate chain. These
+ * certificates are also base64-encoded and appear each on their own
+ * line. A length of -1 is used to encode a null array.
+ */
+ public Entry(InputStream in) throws IOException {
+ try {
+ StrictLineReader reader = new StrictLineReader(in, US_ASCII);
+ uri = reader.readLine();
+ requestMethod = reader.readLine();
+ varyHeaders = new RawHeaders();
+ int varyRequestHeaderLineCount = reader.readInt();
+ for (int i = 0; i < varyRequestHeaderLineCount; i++) {
+ varyHeaders.addLine(reader.readLine());
+ }
+
+ responseHeaders = new RawHeaders();
+ responseHeaders.setStatusLine(reader.readLine());
+ int responseHeaderLineCount = reader.readInt();
+ for (int i = 0; i < responseHeaderLineCount; i++) {
+ responseHeaders.addLine(reader.readLine());
+ }
+
+ if (isHttps()) {
+ String blank = reader.readLine();
+ if (!blank.isEmpty()) {
+ throw new IOException("expected \"\" but was \"" + blank + "\"");
+ }
+ cipherSuite = reader.readLine();
+ peerCertificates = readCertArray(reader);
+ localCertificates = readCertArray(reader);
+ } else {
+ cipherSuite = null;
+ peerCertificates = null;
+ localCertificates = null;
+ }
+ } finally {
+ in.close();
+ }
+ }
+
+ public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
+ throws IOException {
+ this.uri = uri.toString();
+ this.varyHeaders = varyHeaders;
+ this.requestMethod = httpConnection.getRequestMethod();
+ this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);
+
+ if (isHttps()) {
+ HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
+ cipherSuite = httpsConnection.getCipherSuite();
+ Certificate[] peerCertificatesNonFinal = null;
+ try {
+ peerCertificatesNonFinal = httpsConnection.getServerCertificates();
+ } catch (SSLPeerUnverifiedException ignored) {
+ }
+ peerCertificates = peerCertificatesNonFinal;
+ localCertificates = httpsConnection.getLocalCertificates();
+ } else {
+ cipherSuite = null;
+ peerCertificates = null;
+ localCertificates = null;
+ }
+ }
+
+ public void writeTo(DiskLruCache.Editor editor) throws IOException {
+ OutputStream out = editor.newOutputStream(ENTRY_METADATA);
+ Writer writer = new BufferedWriter(new OutputStreamWriter(out, UTF_8));
+
+ writer.write(uri + '\n');
+ writer.write(requestMethod + '\n');
+ writer.write(Integer.toString(varyHeaders.length()) + '\n');
+ for (int i = 0; i < varyHeaders.length(); i++) {
+ writer.write(varyHeaders.getFieldName(i) + ": " + varyHeaders.getValue(i) + '\n');
+ }
+
+ writer.write(responseHeaders.getStatusLine() + '\n');
+ writer.write(Integer.toString(responseHeaders.length()) + '\n');
+ for (int i = 0; i < responseHeaders.length(); i++) {
+ writer.write(responseHeaders.getFieldName(i) + ": " + responseHeaders.getValue(i) + '\n');
+ }
+
+ if (isHttps()) {
+ writer.write('\n');
+ writer.write(cipherSuite + '\n');
+ writeCertArray(writer, peerCertificates);
+ writeCertArray(writer, localCertificates);
+ }
+ writer.close();
+ }
+
+ private boolean isHttps() {
+ return uri.startsWith("https://");
+ }
+
+ private Certificate[] readCertArray(StrictLineReader reader) throws IOException {
+ int length = reader.readInt();
+ if (length == -1) {
+ return null;
+ }
+ try {
+ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
+ Certificate[] result = new Certificate[length];
+ for (int i = 0; i < result.length; i++) {
+ String line = reader.readLine();
+ byte[] bytes = Base64.decode(line.getBytes("US-ASCII"));
+ result[i] = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes));
+ }
+ return result;
+ } catch (CertificateException e) {
+ throw new IOException(e);
+ }
+ }
+
+ private void writeCertArray(Writer writer, Certificate[] certificates) throws IOException {
+ if (certificates == null) {
+ writer.write("-1\n");
+ return;
+ }
+ try {
+ writer.write(Integer.toString(certificates.length) + '\n');
+ for (Certificate certificate : certificates) {
+ byte[] bytes = certificate.getEncoded();
+ String line = Base64.encode(bytes);
+ writer.write(line + '\n');
+ }
+ } catch (CertificateEncodingException e) {
+ throw new IOException(e);
+ }
+ }
+
+ public boolean matches(URI uri, String requestMethod,
+ Map<String, List<String>> requestHeaders) {
+ return this.uri.equals(uri.toString())
+ && this.requestMethod.equals(requestMethod)
+ && new ResponseHeaders(uri, responseHeaders).varyMatches(varyHeaders.toMultimap(false),
+ requestHeaders);
+ }
+ }
+
+ /**
+ * Returns an input stream that reads the body of a snapshot, closing the
+ * snapshot when the stream is closed.
+ */
+ private static InputStream newBodyInputStream(final DiskLruCache.Snapshot snapshot) {
+ return new FilterInputStream(snapshot.getInputStream(ENTRY_BODY)) {
+ @Override public void close() throws IOException {
+ snapshot.close();
+ super.close();
+ }
+ };
+ }
+
+ static class EntryCacheResponse extends CacheResponse {
+ private final Entry entry;
+ private final DiskLruCache.Snapshot snapshot;
+ private final InputStream in;
+
+ public EntryCacheResponse(Entry entry, DiskLruCache.Snapshot snapshot) {
+ this.entry = entry;
+ this.snapshot = snapshot;
+ this.in = newBodyInputStream(snapshot);
+ }
+
+ @Override public Map<String, List<String>> getHeaders() {
+ return entry.responseHeaders.toMultimap(true);
+ }
+
+ @Override public InputStream getBody() {
+ return in;
+ }
+ }
+
+ static class EntrySecureCacheResponse extends SecureCacheResponse {
+ private final Entry entry;
+ private final DiskLruCache.Snapshot snapshot;
+ private final InputStream in;
+
+ public EntrySecureCacheResponse(Entry entry, DiskLruCache.Snapshot snapshot) {
+ this.entry = entry;
+ this.snapshot = snapshot;
+ this.in = newBodyInputStream(snapshot);
+ }
+
+ @Override public Map<String, List<String>> getHeaders() {
+ return entry.responseHeaders.toMultimap(true);
+ }
+
+ @Override public InputStream getBody() {
+ return in;
+ }
+
+ @Override public String getCipherSuite() {
+ return entry.cipherSuite;
+ }
+
+ @Override public List<Certificate> getServerCertificateChain()
+ throws SSLPeerUnverifiedException {
+ if (entry.peerCertificates == null || entry.peerCertificates.length == 0) {
+ throw new SSLPeerUnverifiedException(null);
+ }
+ return Arrays.asList(entry.peerCertificates.clone());
+ }
+
+ @Override public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
+ if (entry.peerCertificates == null || entry.peerCertificates.length == 0) {
+ throw new SSLPeerUnverifiedException(null);
+ }
+ return ((X509Certificate) entry.peerCertificates[0]).getSubjectX500Principal();
+ }
+
+ @Override public List<Certificate> getLocalCertificateChain() {
+ if (entry.localCertificates == null || entry.localCertificates.length == 0) {
+ return null;
+ }
+ return Arrays.asList(entry.localCertificates.clone());
+ }
+
+ @Override public Principal getLocalPrincipal() {
+ if (entry.localCertificates == null || entry.localCertificates.length == 0) {
+ return null;
+ }
+ return ((X509Certificate) entry.localCertificates[0]).getSubjectX500Principal();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpTransport.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpTransport.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpTransport.java
new file mode 100644
index 0000000..f6d77b2
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpTransport.java
@@ -0,0 +1,485 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.Connection;
+import com.squareup.okhttp.internal.AbstractOutputStream;
+import com.squareup.okhttp.internal.Util;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.CacheRequest;
+import java.net.ProtocolException;
+import java.net.Socket;
+
+import static com.squareup.okhttp.internal.Util.checkOffsetAndCount;
+
+public final class HttpTransport implements Transport {
+ /**
+ * The timeout to use while discarding a stream of input data. Since this is
+ * used for connection reuse, this timeout should be significantly less than
+ * the time it takes to establish a new connection.
+ */
+ private static final int DISCARD_STREAM_TIMEOUT_MILLIS = 100;
+
+ public static final int DEFAULT_CHUNK_LENGTH = 1024;
+
+ private final HttpEngine httpEngine;
+ private final InputStream socketIn;
+ private final OutputStream socketOut;
+
+ /**
+ * This stream buffers the request headers and the request body when their
+ * combined size is less than MAX_REQUEST_BUFFER_LENGTH. By combining them
+ * we can save socket writes, which in turn saves a packet transmission.
+ * This is socketOut if the request size is large or unknown.
+ */
+ private OutputStream requestOut;
+
+ public HttpTransport(HttpEngine httpEngine, OutputStream outputStream, InputStream inputStream) {
+ this.httpEngine = httpEngine;
+ this.socketOut = outputStream;
+ this.requestOut = outputStream;
+ this.socketIn = inputStream;
+ }
+
+ @Override public OutputStream createRequestBody() throws IOException {
+ boolean chunked = httpEngine.requestHeaders.isChunked();
+ if (!chunked
+ && httpEngine.policy.getChunkLength() > 0
+ && httpEngine.connection.getHttpMinorVersion() != 0) {
+ httpEngine.requestHeaders.setChunked();
+ chunked = true;
+ }
+
+ // Stream a request body of unknown length.
+ if (chunked) {
+ int chunkLength = httpEngine.policy.getChunkLength();
+ if (chunkLength == -1) {
+ chunkLength = DEFAULT_CHUNK_LENGTH;
+ }
+ writeRequestHeaders();
+ return new ChunkedOutputStream(requestOut, chunkLength);
+ }
+
+ // Stream a request body of a known length.
+ int fixedContentLength = httpEngine.policy.getFixedContentLength();
+ if (fixedContentLength != -1) {
+ httpEngine.requestHeaders.setContentLength(fixedContentLength);
+ writeRequestHeaders();
+ return new FixedLengthOutputStream(requestOut, fixedContentLength);
+ }
+
+ // Buffer a request body of a known length.
+ int contentLength = httpEngine.requestHeaders.getContentLength();
+ if (contentLength != -1) {
+ writeRequestHeaders();
+ return new RetryableOutputStream(contentLength);
+ }
+
+ // Buffer a request body of an unknown length. Don't write request
+ // headers until the entire body is ready; otherwise we can't set the
+ // Content-Length header correctly.
+ return new RetryableOutputStream();
+ }
+
+ @Override public void flushRequest() throws IOException {
+ requestOut.flush();
+ requestOut = socketOut;
+ }
+
+ @Override public void writeRequestBody(RetryableOutputStream requestBody) throws IOException {
+ requestBody.writeToSocket(requestOut);
+ }
+
+ /**
+ * Prepares the HTTP headers and sends them to the server.
+ *
+ * <p>For streaming requests with a body, headers must be prepared
+ * <strong>before</strong> the output stream has been written to. Otherwise
+ * the body would need to be buffered!
+ *
+ * <p>For non-streaming requests with a body, headers must be prepared
+ * <strong>after</strong> the output stream has been written to and closed.
+ * This ensures that the {@code Content-Length} header field receives the
+ * proper value.
+ */
+ public void writeRequestHeaders() throws IOException {
+ httpEngine.writingRequestHeaders();
+ RawHeaders headersToSend = httpEngine.requestHeaders.getHeaders();
+ byte[] bytes = headersToSend.toBytes();
+ requestOut.write(bytes);
+ }
+
+ @Override public ResponseHeaders readResponseHeaders() throws IOException {
+ RawHeaders headers = RawHeaders.fromBytes(socketIn);
+ httpEngine.connection.setHttpMinorVersion(headers.getHttpMinorVersion());
+ httpEngine.receiveHeaders(headers);
+ return new ResponseHeaders(httpEngine.uri, headers);
+ }
+
+ public boolean makeReusable(boolean streamCancelled, OutputStream requestBodyOut,
+ InputStream responseBodyIn) {
+ if (streamCancelled) {
+ return false;
+ }
+
+ // We cannot reuse sockets that have incomplete output.
+ if (requestBodyOut != null && !((AbstractOutputStream) requestBodyOut).isClosed()) {
+ return false;
+ }
+
+ // If the request specified that the connection shouldn't be reused, don't reuse it.
+ if (httpEngine.requestHeaders.hasConnectionClose()) {
+ return false;
+ }
+
+ // If the response specified that the connection shouldn't be reused, don't reuse it.
+ if (httpEngine.responseHeaders != null && httpEngine.responseHeaders.hasConnectionClose()) {
+ return false;
+ }
+
+ if (responseBodyIn instanceof UnknownLengthHttpInputStream) {
+ return false;
+ }
+
+ if (responseBodyIn != null) {
+ return discardStream(httpEngine, responseBodyIn);
+ }
+
+ return true;
+ }
+
+ /**
+ * Discards the response body so that the connection can be reused. This
+ * needs to be done judiciously, since it delays the current request in
+ * order to speed up a potential future request that may never occur.
+ */
+ private static boolean discardStream(HttpEngine httpEngine, InputStream responseBodyIn) {
+ Connection connection = httpEngine.connection;
+ if (connection == null) return false;
+ Socket socket = connection.getSocket();
+ if (socket == null) return false;
+ try {
+ int socketTimeout = socket.getSoTimeout();
+ socket.setSoTimeout(DISCARD_STREAM_TIMEOUT_MILLIS);
+ try {
+ Util.skipAll(responseBodyIn);
+ return true;
+ } finally {
+ socket.setSoTimeout(socketTimeout);
+ }
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ @Override public InputStream getTransferStream(CacheRequest cacheRequest) throws IOException {
+ if (!httpEngine.hasResponseBody()) {
+ return new FixedLengthInputStream(socketIn, cacheRequest, httpEngine, 0);
+ }
+
+ if (httpEngine.responseHeaders.isChunked()) {
+ return new ChunkedInputStream(socketIn, cacheRequest, this);
+ }
+
+ if (httpEngine.responseHeaders.getContentLength() != -1) {
+ return new FixedLengthInputStream(socketIn, cacheRequest, httpEngine,
+ httpEngine.responseHeaders.getContentLength());
+ }
+
+ // Wrap the input stream from the connection (rather than just returning
+ // "socketIn" directly here), so that we can control its use after the
+ // reference escapes.
+ return new UnknownLengthHttpInputStream(socketIn, cacheRequest, httpEngine);
+ }
+
+ /** An HTTP body with a fixed length known in advance. */
+ private static final class FixedLengthOutputStream extends AbstractOutputStream {
+ private final OutputStream socketOut;
+ private int bytesRemaining;
+
+ private FixedLengthOutputStream(OutputStream socketOut, int bytesRemaining) {
+ this.socketOut = socketOut;
+ this.bytesRemaining = bytesRemaining;
+ }
+
+ @Override public void write(byte[] buffer, int offset, int count) throws IOException {
+ checkNotClosed();
+ checkOffsetAndCount(buffer.length, offset, count);
+ if (count > bytesRemaining) {
+ throw new ProtocolException("expected " + bytesRemaining + " bytes but received " + count);
+ }
+ socketOut.write(buffer, offset, count);
+ bytesRemaining -= count;
+ }
+
+ @Override public void flush() throws IOException {
+ if (closed) {
+ return; // don't throw; this stream might have been closed on the caller's behalf
+ }
+ socketOut.flush();
+ }
+
+ @Override public void close() throws IOException {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ if (bytesRemaining > 0) {
+ throw new ProtocolException("unexpected end of stream");
+ }
+ }
+ }
+
+ /**
+ * An HTTP body with alternating chunk sizes and chunk bodies. Chunks are
+ * buffered until {@code maxChunkLength} bytes are ready, at which point the
+ * chunk is written and the buffer is cleared.
+ */
+ private static final class ChunkedOutputStream extends AbstractOutputStream {
+ private static final byte[] CRLF = { '\r', '\n' };
+ private static final byte[] HEX_DIGITS = {
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
+ };
+ private static final byte[] FINAL_CHUNK = new byte[] { '0', '\r', '\n', '\r', '\n' };
+
+ /** Scratch space for up to 8 hex digits, and then a constant CRLF. */
+ private final byte[] hex = { 0, 0, 0, 0, 0, 0, 0, 0, '\r', '\n' };
+
+ private final OutputStream socketOut;
+ private final int maxChunkLength;
+ private final ByteArrayOutputStream bufferedChunk;
+
+ private ChunkedOutputStream(OutputStream socketOut, int maxChunkLength) {
+ this.socketOut = socketOut;
+ this.maxChunkLength = Math.max(1, dataLength(maxChunkLength));
+ this.bufferedChunk = new ByteArrayOutputStream(maxChunkLength);
+ }
+
+ /**
+ * Returns the amount of data that can be transmitted in a chunk whose total
+ * length (data+headers) is {@code dataPlusHeaderLength}. This is presumably
+ * useful to match sizes with wire-protocol packets.
+ */
+ private int dataLength(int dataPlusHeaderLength) {
+ int headerLength = 4; // "\r\n" after the size plus another "\r\n" after the data
+ for (int i = dataPlusHeaderLength - headerLength; i > 0; i >>= 4) {
+ headerLength++;
+ }
+ return dataPlusHeaderLength - headerLength;
+ }
+
+ @Override public synchronized void write(byte[] buffer, int offset, int count)
+ throws IOException {
+ checkNotClosed();
+ checkOffsetAndCount(buffer.length, offset, count);
+
+ while (count > 0) {
+ int numBytesWritten;
+
+ if (bufferedChunk.size() > 0 || count < maxChunkLength) {
+ // fill the buffered chunk and then maybe write that to the stream
+ numBytesWritten = Math.min(count, maxChunkLength - bufferedChunk.size());
+ // TODO: skip unnecessary copies from buffer->bufferedChunk?
+ bufferedChunk.write(buffer, offset, numBytesWritten);
+ if (bufferedChunk.size() == maxChunkLength) {
+ writeBufferedChunkToSocket();
+ }
+ } else {
+ // write a single chunk of size maxChunkLength to the stream
+ numBytesWritten = maxChunkLength;
+ writeHex(numBytesWritten);
+ socketOut.write(buffer, offset, numBytesWritten);
+ socketOut.write(CRLF);
+ }
+
+ offset += numBytesWritten;
+ count -= numBytesWritten;
+ }
+ }
+
+ /**
+ * Equivalent to, but cheaper than writing Integer.toHexString().getBytes()
+ * followed by CRLF.
+ */
+ private void writeHex(int i) throws IOException {
+ int cursor = 8;
+ do {
+ hex[--cursor] = HEX_DIGITS[i & 0xf];
+ } while ((i >>>= 4) != 0);
+ socketOut.write(hex, cursor, hex.length - cursor);
+ }
+
+ @Override public synchronized void flush() throws IOException {
+ if (closed) {
+ return; // don't throw; this stream might have been closed on the caller's behalf
+ }
+ writeBufferedChunkToSocket();
+ socketOut.flush();
+ }
+
+ @Override public synchronized void close() throws IOException {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ writeBufferedChunkToSocket();
+ socketOut.write(FINAL_CHUNK);
+ }
+
+ private void writeBufferedChunkToSocket() throws IOException {
+ int size = bufferedChunk.size();
+ if (size <= 0) {
+ return;
+ }
+
+ writeHex(size);
+ bufferedChunk.writeTo(socketOut);
+ bufferedChunk.reset();
+ socketOut.write(CRLF);
+ }
+ }
+
+ /** An HTTP body with a fixed length specified in advance. */
+ private static class FixedLengthInputStream extends AbstractHttpInputStream {
+ private int bytesRemaining;
+
+ public FixedLengthInputStream(InputStream is, CacheRequest cacheRequest, HttpEngine httpEngine,
+ int length) throws IOException {
+ super(is, httpEngine, cacheRequest);
+ bytesRemaining = length;
+ if (bytesRemaining == 0) {
+ endOfInput(false);
+ }
+ }
+
+ @Override public int read(byte[] buffer, int offset, int count) throws IOException {
+ checkOffsetAndCount(buffer.length, offset, count);
+ checkNotClosed();
+ if (bytesRemaining == 0) {
+ return -1;
+ }
+ int read = in.read(buffer, offset, Math.min(count, bytesRemaining));
+ if (read == -1) {
+ unexpectedEndOfInput(); // the server didn't supply the promised content length
+ throw new ProtocolException("unexpected end of stream");
+ }
+ bytesRemaining -= read;
+ cacheWrite(buffer, offset, read);
+ if (bytesRemaining == 0) {
+ endOfInput(false);
+ }
+ return read;
+ }
+
+ @Override public int available() throws IOException {
+ checkNotClosed();
+ return bytesRemaining == 0 ? 0 : Math.min(in.available(), bytesRemaining);
+ }
+
+ @Override public void close() throws IOException {
+ if (closed) {
+ return;
+ }
+ if (bytesRemaining != 0 && !discardStream(httpEngine, this)) {
+ unexpectedEndOfInput();
+ }
+ closed = true;
+ }
+ }
+
+ /** An HTTP body with alternating chunk sizes and chunk bodies. */
+ private static class ChunkedInputStream extends AbstractHttpInputStream {
+ private static final int NO_CHUNK_YET = -1;
+ private final HttpTransport transport;
+ private int bytesRemainingInChunk = NO_CHUNK_YET;
+ private boolean hasMoreChunks = true;
+
+ ChunkedInputStream(InputStream is, CacheRequest cacheRequest, HttpTransport transport)
+ throws IOException {
+ super(is, transport.httpEngine, cacheRequest);
+ this.transport = transport;
+ }
+
+ @Override public int read(byte[] buffer, int offset, int count) throws IOException {
+ checkOffsetAndCount(buffer.length, offset, count);
+ checkNotClosed();
+
+ if (!hasMoreChunks) {
+ return -1;
+ }
+ if (bytesRemainingInChunk == 0 || bytesRemainingInChunk == NO_CHUNK_YET) {
+ readChunkSize();
+ if (!hasMoreChunks) {
+ return -1;
+ }
+ }
+ int read = in.read(buffer, offset, Math.min(count, bytesRemainingInChunk));
+ if (read == -1) {
+ unexpectedEndOfInput(); // the server didn't supply the promised chunk length
+ throw new IOException("unexpected end of stream");
+ }
+ bytesRemainingInChunk -= read;
+ cacheWrite(buffer, offset, read);
+ return read;
+ }
+
+ private void readChunkSize() throws IOException {
+ // read the suffix of the previous chunk
+ if (bytesRemainingInChunk != NO_CHUNK_YET) {
+ Util.readAsciiLine(in);
+ }
+ String chunkSizeString = Util.readAsciiLine(in);
+ int index = chunkSizeString.indexOf(";");
+ if (index != -1) {
+ chunkSizeString = chunkSizeString.substring(0, index);
+ }
+ try {
+ bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16);
+ } catch (NumberFormatException e) {
+ throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString);
+ }
+ if (bytesRemainingInChunk == 0) {
+ hasMoreChunks = false;
+ RawHeaders rawResponseHeaders = httpEngine.responseHeaders.getHeaders();
+ RawHeaders.readHeaders(transport.socketIn, rawResponseHeaders);
+ httpEngine.receiveHeaders(rawResponseHeaders);
+ endOfInput(false);
+ }
+ }
+
+ @Override public int available() throws IOException {
+ checkNotClosed();
+ if (!hasMoreChunks || bytesRemainingInChunk == NO_CHUNK_YET) {
+ return 0;
+ }
+ return Math.min(in.available(), bytesRemainingInChunk);
+ }
+
+ @Override public void close() throws IOException {
+ if (closed) {
+ return;
+ }
+ if (hasMoreChunks && !discardStream(httpEngine, this)) {
+ unexpectedEndOfInput();
+ }
+ closed = true;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java
new file mode 100644
index 0000000..eabe649
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java
@@ -0,0 +1,556 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.Connection;
+import com.squareup.okhttp.ConnectionPool;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Route;
+import com.squareup.okhttp.internal.AbstractOutputStream;
+import com.squareup.okhttp.internal.FaultRecoveringOutputStream;
+import com.squareup.okhttp.internal.Util;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.CookieHandler;
+import java.net.HttpRetryException;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.ProtocolException;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.SocketPermission;
+import java.net.URL;
+import java.security.Permission;
+import java.security.cert.CertificateException;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.SSLHandshakeException;
+import javax.net.ssl.SSLSocketFactory;
+
+import static com.squareup.okhttp.internal.Util.getEffectivePort;
+
+/**
+ * This implementation uses HttpEngine to send requests and receive responses.
+ * This class may use multiple HttpEngines to follow redirects, authentication
+ * retries, etc. to retrieve the final response body.
+ *
+ * <h3>What does 'connected' mean?</h3>
+ * This class inherits a {@code connected} field from the superclass. That field
+ * is <strong>not</strong> used to indicate not whether this URLConnection is
+ * currently connected. Instead, it indicates whether a connection has ever been
+ * attempted. Once a connection has been attempted, certain properties (request
+ * header fields, request method, etc.) are immutable. Test the {@code
+ * connection} field on this class for null/non-null to determine of an instance
+ * is currently connected to a server.
+ */
+public class HttpURLConnectionImpl extends HttpURLConnection {
+
+ /** Numeric status code, 307: Temporary Redirect. */
+ static final int HTTP_TEMP_REDIRECT = 307;
+
+ /**
+ * How many redirects should we follow? Chrome follows 21; Firefox, curl,
+ * and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5.
+ */
+ private static final int MAX_REDIRECTS = 20;
+
+ /**
+ * The minimum number of request body bytes to transmit before we're willing
+ * to let a routine {@link IOException} bubble up to the user. This is used to
+ * size a buffer for data that will be replayed upon error.
+ */
+ private static final int MAX_REPLAY_BUFFER_LENGTH = 8192;
+
+ private final boolean followProtocolRedirects;
+
+ /** The proxy requested by the client, or null for a proxy to be selected automatically. */
+ final Proxy requestedProxy;
+
+ final ProxySelector proxySelector;
+ final CookieHandler cookieHandler;
+ final OkResponseCache responseCache;
+ final ConnectionPool connectionPool;
+ /* SSL configuration; necessary for HTTP requests that get redirected to HTTPS. */
+ SSLSocketFactory sslSocketFactory;
+ HostnameVerifier hostnameVerifier;
+ final Set<Route> failedRoutes;
+
+ private final RawHeaders rawRequestHeaders = new RawHeaders();
+
+ private int redirectionCount;
+ private FaultRecoveringOutputStream faultRecoveringRequestBody;
+
+ protected IOException httpEngineFailure;
+ protected HttpEngine httpEngine;
+
+ public HttpURLConnectionImpl(URL url, OkHttpClient client, OkResponseCache responseCache,
+ Set<Route> failedRoutes) {
+ super(url);
+ this.followProtocolRedirects = client.getFollowProtocolRedirects();
+ this.failedRoutes = failedRoutes;
+ this.requestedProxy = client.getProxy();
+ this.proxySelector = client.getProxySelector();
+ this.cookieHandler = client.getCookieHandler();
+ this.connectionPool = client.getConnectionPool();
+ this.sslSocketFactory = client.getSslSocketFactory();
+ this.hostnameVerifier = client.getHostnameVerifier();
+ this.responseCache = responseCache;
+ }
+
+ Set<Route> getFailedRoutes() {
+ return failedRoutes;
+ }
+
+ @Override public final void connect() throws IOException {
+ initHttpEngine();
+ boolean success;
+ do {
+ success = execute(false);
+ } while (!success);
+ }
+
+ @Override public final void disconnect() {
+ // Calling disconnect() before a connection exists should have no effect.
+ if (httpEngine != null) {
+ // We close the response body here instead of in
+ // HttpEngine.release because that is called when input
+ // has been completely read from the underlying socket.
+ // However the response body can be a GZIPInputStream that
+ // still has unread data.
+ if (httpEngine.hasResponse()) {
+ Util.closeQuietly(httpEngine.getResponseBody());
+ }
+ httpEngine.release(true);
+ }
+ }
+
+ /**
+ * Returns an input stream from the server in the case of error such as the
+ * requested file (txt, htm, html) is not found on the remote server.
+ */
+ @Override public final InputStream getErrorStream() {
+ try {
+ HttpEngine response = getResponse();
+ if (response.hasResponseBody() && response.getResponseCode() >= HTTP_BAD_REQUEST) {
+ return response.getResponseBody();
+ }
+ return null;
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the value of the field at {@code position}. Returns null if there
+ * are fewer than {@code position} headers.
+ */
+ @Override public final String getHeaderField(int position) {
+ try {
+ return getResponse().getResponseHeaders().getHeaders().getValue(position);
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the value of the field corresponding to the {@code fieldName}, or
+ * null if there is no such field. If the field has multiple values, the
+ * last value is returned.
+ */
+ @Override public final String getHeaderField(String fieldName) {
+ try {
+ RawHeaders rawHeaders = getResponse().getResponseHeaders().getHeaders();
+ return fieldName == null ? rawHeaders.getStatusLine() : rawHeaders.get(fieldName);
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ @Override public final String getHeaderFieldKey(int position) {
+ try {
+ return getResponse().getResponseHeaders().getHeaders().getFieldName(position);
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ @Override public final Map<String, List<String>> getHeaderFields() {
+ try {
+ return getResponse().getResponseHeaders().getHeaders().toMultimap(true);
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ @Override public final Map<String, List<String>> getRequestProperties() {
+ if (connected) {
+ throw new IllegalStateException(
+ "Cannot access request header fields after connection is set");
+ }
+ return rawRequestHeaders.toMultimap(false);
+ }
+
+ @Override public final InputStream getInputStream() throws IOException {
+ if (!doInput) {
+ throw new ProtocolException("This protocol does not support input");
+ }
+
+ HttpEngine response = getResponse();
+
+ // if the requested file does not exist, throw an exception formerly the
+ // Error page from the server was returned if the requested file was
+ // text/html this has changed to return FileNotFoundException for all
+ // file types
+ if (getResponseCode() >= HTTP_BAD_REQUEST) {
+ throw new FileNotFoundException(url.toString());
+ }
+
+ InputStream result = response.getResponseBody();
+ if (result == null) {
+ throw new ProtocolException("No response body exists; responseCode=" + getResponseCode());
+ }
+ return result;
+ }
+
+ @Override public final OutputStream getOutputStream() throws IOException {
+ connect();
+
+ OutputStream out = httpEngine.getRequestBody();
+ if (out == null) {
+ throw new ProtocolException("method does not support a request body: " + method);
+ } else if (httpEngine.hasResponse()) {
+ throw new ProtocolException("cannot write request body after response has been read");
+ }
+
+ if (faultRecoveringRequestBody == null) {
+ faultRecoveringRequestBody = new FaultRecoveringOutputStream(MAX_REPLAY_BUFFER_LENGTH, out) {
+ @Override protected OutputStream replacementStream(IOException e) throws IOException {
+ if (httpEngine.getRequestBody() instanceof AbstractOutputStream
+ && ((AbstractOutputStream) httpEngine.getRequestBody()).isClosed()) {
+ return null; // Don't recover once the underlying stream has been closed.
+ }
+ if (handleFailure(e)) {
+ return httpEngine.getRequestBody();
+ }
+ return null; // This is a permanent failure.
+ }
+ };
+ }
+
+ return faultRecoveringRequestBody;
+ }
+
+ @Override public final Permission getPermission() throws IOException {
+ String hostName = getURL().getHost();
+ int hostPort = Util.getEffectivePort(getURL());
+ if (usingProxy()) {
+ InetSocketAddress proxyAddress = (InetSocketAddress) requestedProxy.address();
+ hostName = proxyAddress.getHostName();
+ hostPort = proxyAddress.getPort();
+ }
+ return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
+ }
+
+ @Override public final String getRequestProperty(String field) {
+ if (field == null) {
+ return null;
+ }
+ return rawRequestHeaders.get(field);
+ }
+
+ private void initHttpEngine() throws IOException {
+ if (httpEngineFailure != null) {
+ throw httpEngineFailure;
+ } else if (httpEngine != null) {
+ return;
+ }
+
+ connected = true;
+ try {
+ if (doOutput) {
+ if (method.equals("GET")) {
+ // they are requesting a stream to write to. This implies a POST method
+ method = "POST";
+ } else if (!method.equals("POST") && !method.equals("PUT")) {
+ // If the request method is neither POST nor PUT, then you're not writing
+ throw new ProtocolException(method + " does not support writing");
+ }
+ }
+ httpEngine = newHttpEngine(method, rawRequestHeaders, null, null);
+ } catch (IOException e) {
+ httpEngineFailure = e;
+ throw e;
+ }
+ }
+
+ protected HttpURLConnection getHttpConnectionToCache() {
+ return this;
+ }
+
+ private HttpEngine newHttpEngine(String method, RawHeaders requestHeaders,
+ Connection connection, RetryableOutputStream requestBody) throws IOException {
+ if (url.getProtocol().equals("http")) {
+ return new HttpEngine(this, method, requestHeaders, connection, requestBody);
+ } else if (url.getProtocol().equals("https")) {
+ return new HttpsURLConnectionImpl.HttpsEngine(
+ this, method, requestHeaders, connection, requestBody);
+ } else {
+ throw new AssertionError();
+ }
+ }
+
+ /**
+ * Aggressively tries to get the final HTTP response, potentially making
+ * many HTTP requests in the process in order to cope with redirects and
+ * authentication.
+ */
+ private HttpEngine getResponse() throws IOException {
+ initHttpEngine();
+
+ if (httpEngine.hasResponse()) {
+ return httpEngine;
+ }
+
+ while (true) {
+ if (!execute(true)) {
+ continue;
+ }
+
+ Retry retry = processResponseHeaders();
+ if (retry == Retry.NONE) {
+ httpEngine.automaticallyReleaseConnectionToPool();
+ return httpEngine;
+ }
+
+ // The first request was insufficient. Prepare for another...
+ String retryMethod = method;
+ OutputStream requestBody = httpEngine.getRequestBody();
+
+ // Although RFC 2616 10.3.2 specifies that a HTTP_MOVED_PERM
+ // redirect should keep the same method, Chrome, Firefox and the
+ // RI all issue GETs when following any redirect.
+ int responseCode = getResponseCode();
+ if (responseCode == HTTP_MULT_CHOICE
+ || responseCode == HTTP_MOVED_PERM
+ || responseCode == HTTP_MOVED_TEMP
+ || responseCode == HTTP_SEE_OTHER) {
+ retryMethod = "GET";
+ requestBody = null;
+ }
+
+ if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
+ throw new HttpRetryException("Cannot retry streamed HTTP body",
+ httpEngine.getResponseCode());
+ }
+
+ if (retry == Retry.DIFFERENT_CONNECTION) {
+ httpEngine.automaticallyReleaseConnectionToPool();
+ }
+
+ httpEngine.release(false);
+
+ httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
+ (RetryableOutputStream) requestBody);
+ }
+ }
+
+ /**
+ * Sends a request and optionally reads a response. Returns true if the
+ * request was successfully executed, and false if the request can be
+ * retried. Throws an exception if the request failed permanently.
+ */
+ private boolean execute(boolean readResponse) throws IOException {
+ try {
+ httpEngine.sendRequest();
+ if (readResponse) {
+ httpEngine.readResponse();
+ }
+ return true;
+ } catch (IOException e) {
+ if (handleFailure(e)) {
+ return false;
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ /**
+ * Report and attempt to recover from {@code e}. Returns true if the HTTP
+ * engine was replaced and the request should be retried. Otherwise the
+ * failure is permanent.
+ */
+ private boolean handleFailure(IOException e) throws IOException {
+ RouteSelector routeSelector = httpEngine.routeSelector;
+ if (routeSelector != null && httpEngine.connection != null) {
+ routeSelector.connectFailed(httpEngine.connection, e);
+ }
+
+ OutputStream requestBody = httpEngine.getRequestBody();
+ boolean canRetryRequestBody = requestBody == null
+ || requestBody instanceof RetryableOutputStream
+ || (faultRecoveringRequestBody != null && faultRecoveringRequestBody.isRecoverable());
+ if (routeSelector == null && httpEngine.connection == null // No connection.
+ || routeSelector != null && !routeSelector.hasNext() // No more routes to attempt.
+ || !isRecoverable(e)
+ || !canRetryRequestBody) {
+ httpEngineFailure = e;
+ return false;
+ }
+
+ httpEngine.release(true);
+ RetryableOutputStream retryableOutputStream = requestBody instanceof RetryableOutputStream
+ ? (RetryableOutputStream) requestBody
+ : null;
+ httpEngine = newHttpEngine(method, rawRequestHeaders, null, retryableOutputStream);
+ httpEngine.routeSelector = routeSelector; // Keep the same routeSelector.
+ if (faultRecoveringRequestBody != null && faultRecoveringRequestBody.isRecoverable()) {
+ httpEngine.sendRequest();
+ faultRecoveringRequestBody.replaceStream(httpEngine.getRequestBody());
+ }
+ return true;
+ }
+
+ private boolean isRecoverable(IOException e) {
+ // If the problem was a CertificateException from the X509TrustManager,
+ // do not retry, we didn't have an abrupt server initiated exception.
+ boolean sslFailure =
+ e instanceof SSLHandshakeException && e.getCause() instanceof CertificateException;
+ boolean protocolFailure = e instanceof ProtocolException;
+ return !sslFailure && !protocolFailure;
+ }
+
+ public HttpEngine getHttpEngine() {
+ return httpEngine;
+ }
+
+ enum Retry {
+ NONE,
+ SAME_CONNECTION,
+ DIFFERENT_CONNECTION
+ }
+
+ /**
+ * Returns the retry action to take for the current response headers. The
+ * headers, proxy and target URL or this connection may be adjusted to
+ * prepare for a follow up request.
+ */
+ private Retry processResponseHeaders() throws IOException {
+ Proxy selectedProxy = httpEngine.connection != null
+ ? httpEngine.connection.getRoute().getProxy()
+ : requestedProxy;
+ final int responseCode = getResponseCode();
+ switch (responseCode) {
+ case HTTP_PROXY_AUTH:
+ if (selectedProxy.type() != Proxy.Type.HTTP) {
+ throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
+ }
+ // fall-through
+ case HTTP_UNAUTHORIZED:
+ boolean credentialsFound = HttpAuthenticator.processAuthHeader(getResponseCode(),
+ httpEngine.getResponseHeaders().getHeaders(), rawRequestHeaders, selectedProxy, url);
+ return credentialsFound ? Retry.SAME_CONNECTION : Retry.NONE;
+
+ case HTTP_MULT_CHOICE:
+ case HTTP_MOVED_PERM:
+ case HTTP_MOVED_TEMP:
+ case HTTP_SEE_OTHER:
+ case HTTP_TEMP_REDIRECT:
+ if (!getInstanceFollowRedirects()) {
+ return Retry.NONE;
+ }
+ if (++redirectionCount > MAX_REDIRECTS) {
+ throw new ProtocolException("Too many redirects: " + redirectionCount);
+ }
+ if (responseCode == HTTP_TEMP_REDIRECT && !method.equals("GET") && !method.equals("HEAD")) {
+ // "If the 307 status code is received in response to a request other than GET or HEAD,
+ // the user agent MUST NOT automatically redirect the request"
+ return Retry.NONE;
+ }
+ String location = getHeaderField("Location");
+ if (location == null) {
+ return Retry.NONE;
+ }
+ URL previousUrl = url;
+ url = new URL(previousUrl, location);
+ if (!url.getProtocol().equals("https") && !url.getProtocol().equals("http")) {
+ return Retry.NONE; // Don't follow redirects to unsupported protocols.
+ }
+ boolean sameProtocol = previousUrl.getProtocol().equals(url.getProtocol());
+ if (!sameProtocol && !followProtocolRedirects) {
+ return Retry.NONE; // This client doesn't follow redirects across protocols.
+ }
+ boolean sameHost = previousUrl.getHost().equals(url.getHost());
+ boolean samePort = getEffectivePort(previousUrl) == getEffectivePort(url);
+ if (sameHost && samePort && sameProtocol) {
+ return Retry.SAME_CONNECTION;
+ } else {
+ return Retry.DIFFERENT_CONNECTION;
+ }
+
+ default:
+ return Retry.NONE;
+ }
+ }
+
+ /** @see java.net.HttpURLConnection#setFixedLengthStreamingMode(int) */
+ final int getFixedContentLength() {
+ return fixedContentLength;
+ }
+
+ /** @see java.net.HttpURLConnection#setChunkedStreamingMode(int) */
+ final int getChunkLength() {
+ return chunkLength;
+ }
+
+ @Override public final boolean usingProxy() {
+ return (requestedProxy != null && requestedProxy.type() != Proxy.Type.DIRECT);
+ }
+
+ @Override public String getResponseMessage() throws IOException {
+ return getResponse().getResponseHeaders().getHeaders().getResponseMessage();
+ }
+
+ @Override public final int getResponseCode() throws IOException {
+ return getResponse().getResponseCode();
+ }
+
+ @Override public final void setRequestProperty(String field, String newValue) {
+ if (connected) {
+ throw new IllegalStateException("Cannot set request property after connection is made");
+ }
+ if (field == null) {
+ throw new NullPointerException("field == null");
+ }
+ rawRequestHeaders.set(field, newValue);
+ }
+
+ @Override public final void addRequestProperty(String field, String value) {
+ if (connected) {
+ throw new IllegalStateException("Cannot add request property after connection is made");
+ }
+ if (field == null) {
+ throw new NullPointerException("field == null");
+ }
+ rawRequestHeaders.add(field, value);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java
new file mode 100644
index 0000000..235f862
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java
@@ -0,0 +1,461 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.Connection;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Route;
+import com.squareup.okhttp.TunnelRequest;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.CacheResponse;
+import java.net.HttpURLConnection;
+import java.net.ProtocolException;
+import java.net.SecureCacheResponse;
+import java.net.URL;
+import java.security.Permission;
+import java.security.Principal;
+import java.security.cert.Certificate;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+
+import static com.squareup.okhttp.internal.Util.getEffectivePort;
+
+public final class HttpsURLConnectionImpl extends HttpsURLConnection {
+
+ /** HttpUrlConnectionDelegate allows reuse of HttpURLConnectionImpl. */
+ private final HttpUrlConnectionDelegate delegate;
+
+ public HttpsURLConnectionImpl(URL url, OkHttpClient client, OkResponseCache responseCache,
+ Set<Route> failedRoutes) {
+ super(url);
+ delegate = new HttpUrlConnectionDelegate(url, client, responseCache, failedRoutes);
+ }
+
+ @Override public String getCipherSuite() {
+ SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
+ if (cacheResponse != null) {
+ return cacheResponse.getCipherSuite();
+ }
+ SSLSocket sslSocket = getSslSocket();
+ if (sslSocket != null) {
+ return sslSocket.getSession().getCipherSuite();
+ }
+ return null;
+ }
+
+ @Override public Certificate[] getLocalCertificates() {
+ SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
+ if (cacheResponse != null) {
+ List<Certificate> result = cacheResponse.getLocalCertificateChain();
+ return result != null ? result.toArray(new Certificate[result.size()]) : null;
+ }
+ SSLSocket sslSocket = getSslSocket();
+ if (sslSocket != null) {
+ return sslSocket.getSession().getLocalCertificates();
+ }
+ return null;
+ }
+
+ @Override public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
+ SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
+ if (cacheResponse != null) {
+ List<Certificate> result = cacheResponse.getServerCertificateChain();
+ return result != null ? result.toArray(new Certificate[result.size()]) : null;
+ }
+ SSLSocket sslSocket = getSslSocket();
+ if (sslSocket != null) {
+ return sslSocket.getSession().getPeerCertificates();
+ }
+ return null;
+ }
+
+ @Override public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
+ SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
+ if (cacheResponse != null) {
+ return cacheResponse.getPeerPrincipal();
+ }
+ SSLSocket sslSocket = getSslSocket();
+ if (sslSocket != null) {
+ return sslSocket.getSession().getPeerPrincipal();
+ }
+ return null;
+ }
+
+ @Override public Principal getLocalPrincipal() {
+ SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
+ if (cacheResponse != null) {
+ return cacheResponse.getLocalPrincipal();
+ }
+ SSLSocket sslSocket = getSslSocket();
+ if (sslSocket != null) {
+ return sslSocket.getSession().getLocalPrincipal();
+ }
+ return null;
+ }
+
+ public HttpEngine getHttpEngine() {
+ return delegate.getHttpEngine();
+ }
+
+ private SSLSocket getSslSocket() {
+ if (delegate.httpEngine == null || delegate.httpEngine.sentRequestMillis == -1) {
+ throw new IllegalStateException("Connection has not yet been established");
+ }
+ return delegate.httpEngine instanceof HttpsEngine
+ ? ((HttpsEngine) delegate.httpEngine).sslSocket
+ : null; // Not HTTPS! Probably an https:// to http:// redirect.
+ }
+
+ @Override
+ public void disconnect() {
+ delegate.disconnect();
+ }
+
+ @Override
+ public InputStream getErrorStream() {
+ return delegate.getErrorStream();
+ }
+
+ @Override
+ public String getRequestMethod() {
+ return delegate.getRequestMethod();
+ }
+
+ @Override
+ public int getResponseCode() throws IOException {
+ return delegate.getResponseCode();
+ }
+
+ @Override
+ public String getResponseMessage() throws IOException {
+ return delegate.getResponseMessage();
+ }
+
+ @Override
+ public void setRequestMethod(String method) throws ProtocolException {
+ delegate.setRequestMethod(method);
+ }
+
+ @Override
+ public boolean usingProxy() {
+ return delegate.usingProxy();
+ }
+
+ @Override
+ public boolean getInstanceFollowRedirects() {
+ return delegate.getInstanceFollowRedirects();
+ }
+
+ @Override
+ public void setInstanceFollowRedirects(boolean followRedirects) {
+ delegate.setInstanceFollowRedirects(followRedirects);
+ }
+
+ @Override
+ public void connect() throws IOException {
+ connected = true;
+ delegate.connect();
+ }
+
+ @Override
+ public boolean getAllowUserInteraction() {
+ return delegate.getAllowUserInteraction();
+ }
+
+ @Override
+ public Object getContent() throws IOException {
+ return delegate.getContent();
+ }
+
+ @SuppressWarnings("unchecked") // Spec does not generify
+ @Override
+ public Object getContent(Class[] types) throws IOException {
+ return delegate.getContent(types);
+ }
+
+ @Override
+ public String getContentEncoding() {
+ return delegate.getContentEncoding();
+ }
+
+ @Override
+ public int getContentLength() {
+ return delegate.getContentLength();
+ }
+
+ @Override
+ public String getContentType() {
+ return delegate.getContentType();
+ }
+
+ @Override
+ public long getDate() {
+ return delegate.getDate();
+ }
+
+ @Override
+ public boolean getDefaultUseCaches() {
+ return delegate.getDefaultUseCaches();
+ }
+
+ @Override
+ public boolean getDoInput() {
+ return delegate.getDoInput();
+ }
+
+ @Override
+ public boolean getDoOutput() {
+ return delegate.getDoOutput();
+ }
+
+ @Override
+ public long getExpiration() {
+ return delegate.getExpiration();
+ }
+
+ @Override
+ public String getHeaderField(int pos) {
+ return delegate.getHeaderField(pos);
+ }
+
+ @Override
+ public Map<String, List<String>> getHeaderFields() {
+ return delegate.getHeaderFields();
+ }
+
+ @Override
+ public Map<String, List<String>> getRequestProperties() {
+ return delegate.getRequestProperties();
+ }
+
+ @Override
+ public void addRequestProperty(String field, String newValue) {
+ delegate.addRequestProperty(field, newValue);
+ }
+
+ @Override
+ public String getHeaderField(String key) {
+ return delegate.getHeaderField(key);
+ }
+
+ @Override
+ public long getHeaderFieldDate(String field, long defaultValue) {
+ return delegate.getHeaderFieldDate(field, defaultValue);
+ }
+
+ @Override
+ public int getHeaderFieldInt(String field, int defaultValue) {
+ return delegate.getHeaderFieldInt(field, defaultValue);
+ }
+
+ @Override
+ public String getHeaderFieldKey(int position) {
+ return delegate.getHeaderFieldKey(position);
+ }
+
+ @Override
+ public long getIfModifiedSince() {
+ return delegate.getIfModifiedSince();
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return delegate.getInputStream();
+ }
+
+ @Override
+ public long getLastModified() {
+ return delegate.getLastModified();
+ }
+
+ @Override
+ public OutputStream getOutputStream() throws IOException {
+ return delegate.getOutputStream();
+ }
+
+ @Override
+ public Permission getPermission() throws IOException {
+ return delegate.getPermission();
+ }
+
+ @Override
+ public String getRequestProperty(String field) {
+ return delegate.getRequestProperty(field);
+ }
+
+ @Override
+ public URL getURL() {
+ return delegate.getURL();
+ }
+
+ @Override
+ public boolean getUseCaches() {
+ return delegate.getUseCaches();
+ }
+
+ @Override
+ public void setAllowUserInteraction(boolean newValue) {
+ delegate.setAllowUserInteraction(newValue);
+ }
+
+ @Override
+ public void setDefaultUseCaches(boolean newValue) {
+ delegate.setDefaultUseCaches(newValue);
+ }
+
+ @Override
+ public void setDoInput(boolean newValue) {
+ delegate.setDoInput(newValue);
+ }
+
+ @Override
+ public void setDoOutput(boolean newValue) {
+ delegate.setDoOutput(newValue);
+ }
+
+ @Override
+ public void setIfModifiedSince(long newValue) {
+ delegate.setIfModifiedSince(newValue);
+ }
+
+ @Override
+ public void setRequestProperty(String field, String newValue) {
+ delegate.setRequestProperty(field, newValue);
+ }
+
+ @Override
+ public void setUseCaches(boolean newValue) {
+ delegate.setUseCaches(newValue);
+ }
+
+ @Override
+ public void setConnectTimeout(int timeoutMillis) {
+ delegate.setConnectTimeout(timeoutMillis);
+ }
+
+ @Override
+ public int getConnectTimeout() {
+ return delegate.getConnectTimeout();
+ }
+
+ @Override
+ public void setReadTimeout(int timeoutMillis) {
+ delegate.setReadTimeout(timeoutMillis);
+ }
+
+ @Override
+ public int getReadTimeout() {
+ return delegate.getReadTimeout();
+ }
+
+ @Override
+ public String toString() {
+ return delegate.toString();
+ }
+
+ @Override
+ public void setFixedLengthStreamingMode(int contentLength) {
+ delegate.setFixedLengthStreamingMode(contentLength);
+ }
+
+ @Override
+ public void setChunkedStreamingMode(int chunkLength) {
+ delegate.setChunkedStreamingMode(chunkLength);
+ }
+
+ @Override public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
+ delegate.hostnameVerifier = hostnameVerifier;
+ }
+
+ @Override public HostnameVerifier getHostnameVerifier() {
+ return delegate.hostnameVerifier;
+ }
+
+ @Override public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
+ delegate.sslSocketFactory = sslSocketFactory;
+ }
+
+ @Override public SSLSocketFactory getSSLSocketFactory() {
+ return delegate.sslSocketFactory;
+ }
+
+ private final class HttpUrlConnectionDelegate extends HttpURLConnectionImpl {
+ private HttpUrlConnectionDelegate(URL url, OkHttpClient client, OkResponseCache responseCache,
+ Set<Route> failedRoutes) {
+ super(url, client, responseCache, failedRoutes);
+ }
+
+ @Override protected HttpURLConnection getHttpConnectionToCache() {
+ return HttpsURLConnectionImpl.this;
+ }
+
+ public SecureCacheResponse getSecureCacheResponse() {
+ return httpEngine instanceof HttpsEngine
+ ? (SecureCacheResponse) httpEngine.getCacheResponse()
+ : null;
+ }
+ }
+
+ public static final class HttpsEngine extends HttpEngine {
+ /**
+ * Stash of HttpsEngine.connection.socket to implement requests like
+ * {@link #getCipherSuite} even after the connection has been recycled.
+ */
+ private SSLSocket sslSocket;
+
+ /**
+ * @param policy the HttpURLConnectionImpl with connection configuration
+ */
+ public HttpsEngine(HttpURLConnectionImpl policy, String method, RawHeaders requestHeaders,
+ Connection connection, RetryableOutputStream requestBody) throws IOException {
+ super(policy, method, requestHeaders, connection, requestBody);
+ this.sslSocket = connection != null ? (SSLSocket) connection.getSocket() : null;
+ }
+
+ @Override protected void connected(Connection connection) {
+ this.sslSocket = (SSLSocket) connection.getSocket();
+ }
+
+ @Override protected boolean acceptCacheResponseType(CacheResponse cacheResponse) {
+ return cacheResponse instanceof SecureCacheResponse;
+ }
+
+ @Override protected boolean includeAuthorityInRequestLine() {
+ // Even if there is a proxy, it isn't involved. Always request just the file.
+ return false;
+ }
+
+ @Override protected TunnelRequest getTunnelConfig() {
+ String userAgent = requestHeaders.getUserAgent();
+ if (userAgent == null) {
+ userAgent = getDefaultUserAgent();
+ }
+
+ URL url = policy.getURL();
+ return new TunnelRequest(url.getHost(), getEffectivePort(url), userAgent,
+ requestHeaders.getProxyAuthorization());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCache.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCache.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCache.java
new file mode 100644
index 0000000..5829f02
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCache.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2013 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.ResponseSource;
+import java.io.IOException;
+import java.net.CacheRequest;
+import java.net.CacheResponse;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URLConnection;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * An extended response cache API. Unlike {@link java.net.ResponseCache}, this
+ * interface supports conditional caching and statistics.
+ *
+ * <p>Along with the rest of the {@code internal} package, this is not a public
+ * API. Applications wishing to supply their own caches must use the more
+ * limited {@link java.net.ResponseCache} interface.
+ */
+public interface OkResponseCache {
+ CacheResponse get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders)
+ throws IOException;
+
+ CacheRequest put(URI uri, URLConnection urlConnection) throws IOException;
+
+ /**
+ * Handles a conditional request hit by updating the stored cache response
+ * with the headers from {@code httpConnection}. The cached response body is
+ * not updated. If the stored response has changed since {@code
+ * conditionalCacheHit} was returned, this does nothing.
+ */
+ void update(CacheResponse conditionalCacheHit, HttpURLConnection connection) throws IOException;
+
+ /** Track an conditional GET that was satisfied by this cache. */
+ void trackConditionalCacheHit();
+
+ /** Track an HTTP response being satisfied by {@code source}. */
+ void trackResponse(ResponseSource source);
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java
new file mode 100644
index 0000000..2ac915a
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2013 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal.http;
+
+import com.squareup.okhttp.ResponseSource;
+import java.io.IOException;
+import java.net.CacheRequest;
+import java.net.CacheResponse;
+import java.net.HttpURLConnection;
+import java.net.ResponseCache;
+import java.net.URI;
+import java.net.URLConnection;
+import java.util.List;
+import java.util.Map;
+
+public final class OkResponseCacheAdapter implements OkResponseCache {
+ private final ResponseCache responseCache;
+ public OkResponseCacheAdapter(ResponseCache responseCache) {
+ this.responseCache = responseCache;
+ }
+
+ @Override public CacheResponse get(URI uri, String requestMethod,
+ Map<String, List<String>> requestHeaders) throws IOException {
+ return responseCache.get(uri, requestMethod, requestHeaders);
+ }
+
+ @Override public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException {
+ return responseCache.put(uri, urlConnection);
+ }
+
+ @Override public void update(CacheResponse conditionalCacheHit, HttpURLConnection connection)
+ throws IOException {
+ }
+
+ @Override public void trackConditionalCacheHit() {
+ }
+
+ @Override public void trackResponse(ResponseSource source) {
+ }
+}
[24/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/packager-utils.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/packager-utils.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/packager-utils.js
new file mode 100644
index 0000000..5acad8e
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/packager-utils.js
@@ -0,0 +1,65 @@
+var testData = require("./test-data"),
+ utils = require(testData.libPath + "/packager-utils"),
+ fs = require("fs"),
+ path = require("path"),
+ asciiFile = path.resolve("bin/test/cordova/unit/data/ascii_text.txt"),
+ utf8File = path.resolve("bin/test/cordova/unit/data/utf8_text.txt"),
+ ucs2beFile = path.resolve("bin/test/cordova/unit/data/ucs2be_text.txt"),
+ ucs2leFile = path.resolve("bin/test/cordova/unit/data/ucs2le_text.txt"),
+ helloWorld = "Hello World";
+
+describe("Encoded Buffer data to String", function () {
+ it("Ascii text to String", function () {
+ // Read text file encoded in ascii
+ var fileData = fs.readFileSync(asciiFile);
+ expect(utils.bufferToString(fileData)).toEqual(helloWorld);
+ });
+
+ it("Utf8 text to String", function () {
+ // Read text file encoded in utf8
+ var fileData = fs.readFileSync(utf8File);
+ expect(utils.bufferToString(fileData)).toEqual(helloWorld);
+ });
+
+ it("Ucs2BE text to String", function () {
+ // Read text file encoded in 2 byte Unicode big endian
+ var fileData = fs.readFileSync(ucs2beFile);
+ expect(utils.bufferToString(fileData)).toEqual(helloWorld);
+ });
+
+ it("Ucs2LE text to String", function () {
+ // Read text file encoded in 2 byte Unicode little endian
+ var fileData = fs.readFileSync(ucs2leFile);
+ expect(utils.bufferToString(fileData)).toEqual(helloWorld);
+ });
+});
+
+describe("property wrapper", function () {
+ it("wraps a property of an object in an array", function () {
+ var obj = {
+ prop: "value"
+ };
+
+ utils.wrapPropertyInArray(obj, "prop");
+ expect(obj.prop[0]).toEqual("value");
+ });
+
+ it("does not wrap an array object in an array", function () {
+ var obj = {
+ prop: ["value"]
+ };
+
+ utils.wrapPropertyInArray(obj, "prop");
+ expect(obj.prop[0][0]).not.toEqual("value");
+ expect(obj.prop[0]).toEqual("value");
+ });
+
+ it("does not wrap a property that doesn't esist in the object", function () {
+ var obj = {
+ prop: "value"
+ };
+
+ utils.wrapPropertyInArray(obj, "secondValue");
+ expect(obj.secondValue).not.toBeDefined();
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/packager-validator.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/packager-validator.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/packager-validator.js
new file mode 100644
index 0000000..b6ecf4c
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/packager-validator.js
@@ -0,0 +1,277 @@
+var srcPath = __dirname + "/../../../../../templates/project/cordova/lib/",
+ testData = require("./test-data"),
+ testUtilities = require("./test-utilities"),
+ localize = require(srcPath + "localize"),
+ logger = require(srcPath + "logger"),
+ packagerValidator = require(srcPath + "packager-validator"),
+ fs = require("fs"),
+ cmd,
+ extManager = {
+ getExtensionBasenameByFeatureId: function (featureId) {
+ if (featureId && featureId.indexOf("blackberry.") >= 0) {
+ return featureId.substring(featureId.indexOf(".") + 1);
+ } else {
+ return null;
+ }
+ }
+ };
+
+describe("Packager Validator", function () {
+ it("throws an exception when -g set and keys were not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup signing parameters
+ session.keystore = undefined;
+ session.storepass = "myPassword";
+
+ expect(function () {
+ packagerValidator.validateSession(session, configObj);
+ }).toThrow(localize.translate("EXCEPTION_MISSING_SIGNING_KEY_FILE", "author.p12"));
+ });
+
+ it("throws an exception when --buildId set and keys were not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup signing parameters
+ session.keystore = undefined;
+ session.buildId = "100";
+
+ expect(function () {
+ packagerValidator.validateSession(session, configObj);
+ }).toThrow(localize.translate("EXCEPTION_MISSING_SIGNING_KEY_FILE", "author.p12"));
+ });
+
+ it("throws an exception when -g set and barsigner.csk was not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup signing parameters
+ session.keystore = "c:/author.p12";
+ session.keystoreCsk = undefined;
+ session.storepass = "myPassword";
+
+ expect(function () {
+ packagerValidator.validateSession(session, configObj);
+ }).toThrow(localize.translate("EXCEPTION_MISSING_SIGNING_KEY_FILE", "barsigner.csk"));
+ });
+
+ it("throws an exception when --buildId set and barsigner.csk was not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup signing parameters
+ session.keystore = "c:/author.p12";
+ session.keystoreCsk = undefined;
+ session.buildId = "100";
+
+ expect(function () {
+ packagerValidator.validateSession(session, configObj);
+ }).toThrow(localize.translate("EXCEPTION_MISSING_SIGNING_KEY_FILE", "barsigner.csk"));
+ });
+
+ it("throws an exception when -g set and barsigner.db was not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup signing parameters
+ session.keystore = "c:/author.p12";
+ session.keystoreCsk = "c:/barsigner.csk";
+ session.keystoreDb = undefined;
+ session.storepass = "myPassword";
+
+ expect(function () {
+ packagerValidator.validateSession(session, configObj);
+ }).toThrow(localize.translate("EXCEPTION_MISSING_SIGNING_KEY_FILE", "barsigner.db"));
+ });
+
+ it("throws an exception when --buildId set and barsigner.db was not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup signing parameters
+ session.keystore = "c:/author.p12";
+ session.keystoreCsk = "c:/barsigner.csk";
+ session.keystoreDb = undefined;
+ session.buildId = "100";
+
+ expect(function () {
+ packagerValidator.validateSession(session, configObj);
+ }).toThrow(localize.translate("EXCEPTION_MISSING_SIGNING_KEY_FILE", "barsigner.db"));
+ });
+
+ it("generated a warning when Build ID is set in config and keys were not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //Mock the logger
+ spyOn(logger, "warn");
+
+ //setup signing parameters
+ session.keystore = undefined;
+ session.buildId = undefined;
+ configObj.buildId = "100";
+
+ packagerValidator.validateSession(session, configObj);
+ expect(logger.warn).toHaveBeenCalledWith(localize.translate("WARNING_MISSING_SIGNING_KEY_FILE", "author.p12"));
+ });
+
+ it("generated a warning when Build ID is set in config and barsigner.csk was not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //Mock the logger
+ spyOn(logger, "warn");
+
+ //setup signing parameters
+ session.keystore = "c:/author.p12";
+ session.keystoreCsk = undefined;
+ session.buildId = undefined;
+ configObj.buildId = "100";
+
+ packagerValidator.validateSession(session, configObj);
+ expect(logger.warn).toHaveBeenCalledWith(localize.translate("WARNING_MISSING_SIGNING_KEY_FILE", "barsigner.csk"));
+ });
+
+ it("generated a warning when Build ID is set in config and barsigner.db was not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //Mock the logger
+ spyOn(logger, "warn");
+
+ //setup signing parameters
+ session.keystore = "c:/author.p12";
+ session.keystoreCsk = "c:/barsigner.csk";
+ session.keystoreDb = undefined;
+ session.buildId = undefined;
+ configObj.buildId = "100";
+
+ packagerValidator.validateSession(session, configObj);
+ expect(logger.warn).toHaveBeenCalledWith(localize.translate("WARNING_MISSING_SIGNING_KEY_FILE", "barsigner.db"));
+ });
+
+ it("throws an exception when appdesc was not found", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup appdesc which is not existing
+ session.buildId = undefined;
+ configObj.buildId = undefined;
+ session.appdesc = "c:/bardescriptor.xml";
+
+ expect(function () {
+ packagerValidator.validateSession(session, configObj);
+ }).toThrow(localize.translate("EXCEPTION_APPDESC_NOT_FOUND", "c:/bardescriptor.xml"));
+ });
+
+ it("throws an exception when a password [-g] was set with no buildId", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup signing parameters
+ session.keystore = "c:/author.p12";
+ session.keystoreCsk = "c:/barsigner.csk";
+ session.keystoreDb = "c:/barsigner.db";
+ session.storepass = "myPassword";
+ configObj.buildId = undefined;
+
+ expect(function () {
+ packagerValidator.validateSession(session, configObj);
+ }).toThrow(localize.translate("EXCEPTION_MISSING_SIGNING_BUILDID"));
+ });
+
+ it("throws an exception when --buildId was set with no password [-g]", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup signing parameters
+ session.keystore = "c:/author.p12";
+ session.keystoreCsk = "c:/barsigner.csk";
+ session.keystoreDb = "c:/barsigner.db";
+ session.storepass = undefined;
+ session.buildId = "100";
+
+ expect(function () {
+ packagerValidator.validateSession(session, configObj);
+ }).toThrow(localize.translate("EXCEPTION_MISSING_SIGNING_PASSWORD"));
+ });
+
+ it("generates a warning when the config contains a build id and no password was provided[-g]", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = testUtilities.cloneObj(testData.config);
+
+ //setup signing parameters
+ session.keystore = "c:/author.p12";
+ session.storepass = undefined;
+ session.buildId = undefined;
+ configObj.buildId = "100";
+
+ //Mock the logger
+ spyOn(logger, "warn");
+
+ packagerValidator.validateSession(session, configObj);
+ expect(logger.warn).toHaveBeenCalledWith(localize.translate("WARNING_SIGNING_PASSWORD_EXPECTED"));
+ });
+});
+
+describe("Packager Validator: validateConfig", function () {
+ it("does not remove APIs that do exist from features whitelist", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = {
+ accessList: [{
+ features: [{
+ id: "blackberry.identity",
+ required: true,
+ version: "1.0.0.0"
+ }, {
+ version: "1.0.0.0",
+ required: true,
+ id: "blackberry.event"
+ }],
+ uri: "WIDGET_LOCAL",
+ allowSubDomain: true
+ }]
+ };
+
+ spyOn(fs, "existsSync").andCallFake(function () {
+ //since both of these APIs exist, existsSync would return true
+ return true;
+ });
+
+ packagerValidator.validateConfig(session, configObj, extManager);
+ expect(configObj.accessList[0].features.length).toEqual(2);
+
+
+ });
+
+ it("does not crash if user whitelists a feature with no id", function () {
+ var session = testUtilities.cloneObj(testData.session),
+ configObj = {
+ accessList: [{
+ features: [{
+ id: "blackberry.identity",
+ required: true,
+ version: "1.0.0.0"
+ }, {
+ version: "1.0.0.0",
+ required: true,
+ }],
+ uri: "WIDGET_LOCAL",
+ allowSubDomain: true
+ }]
+ };
+ spyOn(logger, "warn");
+
+ spyOn(fs, "existsSync").andCallFake(function () {
+ //since both of these APIs exist, existsSync would return true
+ return true;
+ });
+
+ expect(function () {
+ packagerValidator.validateConfig(session, configObj, extManager);
+ }).not.toThrow();
+ });
+
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/session.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/session.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/session.js
new file mode 100644
index 0000000..bbf6eb3
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/session.js
@@ -0,0 +1,209 @@
+var session = require(__dirname + "/../../../../../templates/project/cordova/lib/session"),
+ localize = require(__dirname + "/../../../../../templates/project/cordova/lib/localize"),
+ testUtils = require("./test-utilities"),
+ path = require("path"),
+ fs = require("fs"),
+ wrench = require("wrench"),
+ zipLocation = __dirname + "/../../config.xml";
+
+describe("Session", function () {
+ beforeEach(function () {
+ //Do not create the source folder
+ spyOn(wrench, "mkdirSyncRecursive");
+ });
+
+ it("sets the source directory correctly when specified [-s C:/sampleApp/mySource]", function () {
+ testUtils.mockResolve(path);
+
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ output: 'C:/sampleApp/bin',
+ source: 'C:/sampleApp/mySource'//equivalent to [-s C:/sampleApp/mySource]
+ },
+ result = session.initialize(data);
+
+ expect(result.sourceDir).toEqual(path.normalize("C:/sampleApp/mySource/src"));
+ });
+
+ it("sets the source directory correctly when unspecified [-s] and output path set [-o]", function () {
+ testUtils.mockResolve(path);
+
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ output: 'C:/sampleApp/bin',
+ source: true//equivalent to [-s]
+ },
+ result = session.initialize(data);
+
+ //src folder should be created in output directory
+ expect(result.sourceDir).toEqual(path.normalize("C:/sampleApp/bin/src"));
+ });
+
+ it("sets the source directory correctly when unspecified [-s] and no output path is set", function () {
+ testUtils.mockResolve(path);
+
+ var data = {
+ args: [ zipLocation ],
+ source: true//equivalent to [-s]
+ },
+ result = session.initialize(data);
+
+ //src folder should be created in output directory
+ expect(result.sourceDir).toEqual(path.join(path.dirname(zipLocation), "src"));
+ });
+
+ it("sets the password when specified using -g", function () {
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ output: 'C:/sampleApp/bin',
+ source: 'C:/sampleApp/mySource',//equivalent to [-s C:/sampleApp/mySource]
+ password: 'myPassword'
+ },
+ result = session.initialize(data);
+ expect(result.storepass).toEqual('myPassword');
+ });
+
+ it("does not set the password when not a string", function () {
+ //Commander somtimes improperly sets password to a function, when no value provided
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ output: 'C:/sampleApp/bin',
+ source: 'C:/sampleApp/mySource',//equivalent to [-s C:/sampleApp/mySource]
+ password: function () {}
+ },
+ result = session.initialize(data);
+ expect(result.storepass).toBeUndefined();
+ });
+
+ it("sets the buildId when specified [-buildId]", function () {
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ output: 'C:/sampleApp/bin',
+ source: 'C:/sampleApp/mySource',//equivalent to [-s C:/sampleApp/mySource]
+ buildId: '100'
+ },
+ result = session.initialize(data);
+ expect(result.buildId).toEqual('100');
+ });
+
+ it("sets the appdesc correctly when specified [--appdesc C:/path/bardescriptor.xml]", function () {
+ testUtils.mockResolve(path);
+
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ appdesc: 'C:/path/bardescriptor.xml' //equivalent to [--appdesc C:/path/bardescriptor.xml]
+ },
+ result = session.initialize(data);
+
+ expect(result.appdesc).toEqual(path.normalize("C:/path/bardescriptor.xml"));
+ });
+
+ it("sets the appdesc correctly when not specified", function () {
+ testUtils.mockResolve(path);
+
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ]
+ },
+ result = session.initialize(data);
+
+ expect(result.appdesc).toBeUndefined();
+ });
+
+ it("sets the output directory correctly when specified with a relative path [-o myOutput]", function () {
+ var bbwpDir = __dirname + "/../../../../../../",
+ data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ output: 'myOutput',
+ },
+ result = session.initialize(data);
+
+ //output should be set to bbwp location + outputFolder
+ expect(result.outputDir).toEqual(path.normalize(path.join(bbwpDir, "myOutput")));
+ });
+
+ describe("get params", function () {
+ beforeEach(function () {
+ delete require.cache[require.resolve(__dirname + "/../../../../../templates/project/cordova/lib/session")];
+ session = require(__dirname + "/../../../../../templates/project/cordova/lib/session");
+ });
+
+ it("get params from external file", function () {
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ params: "params.json"
+ },
+ result;
+
+ spyOn(path, "resolve").andReturn("bin/test/cordova/unit/params.json");
+ spyOn(fs, "existsSync").andReturn(true);
+
+ result = session.initialize(data);
+
+ expect(result.getParams("blackberry-signer")).toEqual({
+ "-proxyhost": "abc.com",
+ "-proxyport": "80"
+ });
+ });
+
+ it("get params from non-existent file should throw error", function () {
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ params: "blah.json"
+ },
+ result;
+
+ spyOn(fs, "existsSync").andReturn(false);
+
+ result = session.initialize(data);
+
+ expect(function () {
+ result.getParams("blackberry-signer");
+ }).toThrow(localize.translate("EXCEPTION_PARAMS_FILE_NOT_FOUND", path.resolve("blah.json")));
+ });
+
+ it("get params from bad JSON file should throw error", function () {
+ var data = {
+ args: [ 'C:/sampleApp/sample.zip' ],
+ params: "params-bad.json"
+ },
+ result;
+
+ spyOn(path, "resolve").andReturn("test/params-bad.json");
+ spyOn(fs, "existsSync").andReturn(true);
+
+ result = session.initialize(data);
+
+ expect(function () {
+ result.getParams("blackberry-signer");
+ }).toThrow(localize.translate("EXCEPTION_PARAMS_FILE_ERROR", path.resolve("blah.json")));
+ });
+ });
+
+ describe("when setting the log level", function () {
+ var logger = require(__dirname + "/../../../../../templates/project/cordova/lib/logger");
+
+ beforeEach(function () {
+ spyOn(logger, "level");
+ });
+
+ it("defaults to verbose with no args", function () {
+ session.initialize({args: []});
+ expect(logger.level).toHaveBeenCalledWith("verbose");
+ });
+
+ it("sets level to verbose", function () {
+ session.initialize({args: [], loglevel: 'verbose'});
+ expect(logger.level).toHaveBeenCalledWith("verbose");
+ });
+
+ it("sets level to warn", function () {
+ session.initialize({args: [], loglevel: 'warn'});
+ expect(logger.level).toHaveBeenCalledWith("warn");
+ });
+
+ it("sets level to error", function () {
+ session.initialize({args: [], loglevel: 'error'});
+ expect(logger.level).toHaveBeenCalledWith("error");
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/signing-helper.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/signing-helper.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/signing-helper.js
new file mode 100644
index 0000000..ad91726
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/signing-helper.js
@@ -0,0 +1,420 @@
+var testData = require('./test-data'),
+ signingHelper = require(testData.libPath + '/signing-helper'),
+ localize = require(testData.libPath + '/localize'),
+ pkgrUtils = require(testData.libPath + "/packager-utils"),
+ conf = require(testData.libPath + "/conf"),
+ path = require('path'),
+ fs = require('fs'),
+ os = require('os'),
+ childProcess = require("child_process"),
+ properties = {
+ homepath: "",
+ homedrive: ""
+ },
+ session;
+
+describe("signing-helper", function () {
+
+ describe("on windows", function () {
+
+ beforeEach(function () {
+
+ /* Preserve the value of the HOMEPATH and HOMEDRIVE environment
+ * variables if they are defined. If they are not defined, mark
+ * variable for deletion after the test.*/
+ if (typeof process.env.HOMEPATH === 'undefined') {
+ properties.homepath = "delete";
+ } else {
+ properties.homepath = process.env.HOMEPATH;
+ }
+
+ if (typeof process.env.HOMEDRIVE === 'undefined') {
+ properties.homedrive = "delete";
+ } else {
+ properties.homedrive = process.env.HOMEDRIVE;
+ }
+
+ spyOn(os, "type").andReturn("windows");
+ });
+
+ afterEach(function () {
+
+ /* Restore the value of the HOMEPATH and HOMEDRIVE environment
+ * variables if they are defined. If they are not defined, delete
+ * the property if it was defined in the test.*/
+ if (typeof process.env.HOMEPATH === 'string') {
+ if (properties.homepath === 'delete') {
+ delete process.env.HOMEPATH;
+ } else {
+ process.env.HOMEPATH = properties.homepath;
+ }
+ }
+
+ if (typeof process.env.HOMEDRIVE === 'string') {
+ if (properties.homedrive === 'delete') {
+ delete process.env.HOMEDRIVE;
+ } else {
+ process.env.HOMEDRIVE = properties.homedrive;
+ }
+ }
+ });
+
+ it("can find keys in Local Settings", function () {
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("\\Local Settings") !== -1;
+ });
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toContain("\\Local Settings");
+ });
+
+ it("can find barsigner.csk in Local Settings", function () {
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("\\Local Settings") !== -1;
+ });
+
+ var result = signingHelper.getCskPath();
+ expect(result).toContain("\\Local Settings");
+ });
+
+ it("can find barsigner.db in Local Settings", function () {
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("\\Local Settings") !== -1;
+ });
+
+ var result = signingHelper.getDbPath();
+ expect(result).toContain("\\Local Settings");
+ });
+
+ it("can find keys in AppData", function () {
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("\\AppData") !== -1;
+ });
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toContain("\\AppData");
+ });
+
+ it("can find barsigner.csk in AppData", function () {
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("\\AppData") !== -1;
+ });
+
+ var result = signingHelper.getCskPath();
+ expect(result).toContain("\\AppData");
+ });
+
+ it("can find barsigner.db in AppData", function () {
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("\\AppData") !== -1;
+ });
+
+ var result = signingHelper.getDbPath();
+ expect(result).toContain("\\AppData");
+ });
+
+ it("can find keys in home path", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "C:";
+
+ spyOn(fs, "existsSync").andCallFake(function (p) {
+ return p.indexOf("\\Users\\user") !== -1;
+ });
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toContain("\\Users\\user");
+ });
+
+ it("can find keys on C drive", function () {
+
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "C:";
+
+ spyOn(fs, "existsSync").andCallFake(function (p) {
+ return p.indexOf("C:") !== -1;
+ });
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toContain("C:");
+ });
+
+ it("can find keys on a drive other than C", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "D:";
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("D:") !== -1;
+ });
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toContain("D:");
+ });
+
+ it("can find barsigner.csk on a drive other than C", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "D:";
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("D:") !== -1;
+ });
+
+ var result = signingHelper.getCskPath();
+ expect(result).toContain("D:");
+ });
+
+ it("can find barsigner.db on a drive other than C", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "D:";
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("D:") !== -1;
+ });
+
+ var result = signingHelper.getDbPath();
+ expect(result).toContain("D:");
+ });
+
+ it("can find keys in Local Settings on the correct drive", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "C:";
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("C:") !== -1 &&
+ path.indexOf("\\Local Settings") !== -1;
+ });
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toContain("C:");
+ expect(result).toContain("\\Local Settings");
+ });
+
+ it("can find barsigner.csk in Local Settings on the correct drive", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "D:";
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("D:") !== -1 &&
+ path.indexOf("\\Local Settings") !== -1;
+ });
+
+ var result = signingHelper.getCskPath();
+ expect(result).toContain("D:");
+ expect(result).toContain("\\Local Settings");
+ });
+
+ it("can find barsigner.db in Local Settings on the correct drive", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "D:";
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("D:") !== -1 &&
+ path.indexOf("\\Local Settings") !== -1;
+ });
+
+ var result = signingHelper.getDbPath();
+ expect(result).toContain("D:");
+ expect(result).toContain("\\Local Settings");
+ });
+
+ it("can find keys in AppData on the correct drive", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "C:";
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("C:") !== -1 &&
+ path.indexOf("\\AppData") !== -1;
+ });
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toContain("C:");
+ expect(result).toContain("\\AppData");
+ });
+
+ it("can find barsigner.csk in AppData on the correct drive", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "D:";
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("D:") !== -1 &&
+ path.indexOf("\\AppData") !== -1;
+ });
+
+ var result = signingHelper.getCskPath();
+ expect(result).toContain("D:");
+ expect(result).toContain("\\AppData");
+ });
+
+ it("can find barsigner.db in AppData on the correct drive", function () {
+ process.env.HOMEPATH = "\\Users\\user";
+ process.env.HOMEDRIVE = "D:";
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("D:") !== -1 &&
+ path.indexOf("\\AppData") !== -1;
+ });
+
+ var result = signingHelper.getDbPath();
+ expect(result).toContain("D:");
+ expect(result).toContain("\\AppData");
+ });
+
+ it("returns undefined when keys cannot be found", function () {
+ spyOn(fs, "existsSync").andReturn(false);
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toBeUndefined();
+ });
+
+ it("returns undefined when barsigner.csk cannot be found", function () {
+ spyOn(fs, "existsSync").andReturn(false);
+
+ var result = signingHelper.getCskPath();
+ expect(result).toBeUndefined();
+ });
+
+ it("returns undefined when barsigner.db cannot be found", function () {
+ spyOn(fs, "existsSync").andReturn(false);
+
+ var result = signingHelper.getDbPath();
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe("on mac", function () {
+
+ beforeEach(function () {
+ spyOn(os, "type").andReturn("darwin");
+ });
+
+ it("can find keys in the Library folder", function () {
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("/Library/Research In Motion/") !== -1;
+ });
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toContain("/Library/Research In Motion/");
+ });
+
+ it("can find barsigner.csk in the Library folder", function () {
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("/Library/Research In Motion/") !== -1;
+ });
+
+ var result = signingHelper.getCskPath();
+ expect(result).toContain("/Library/Research In Motion/");
+ });
+
+ it("can find barsigner.db in the Library folder", function () {
+
+ spyOn(fs, "existsSync").andCallFake(function (path) {
+ return path.indexOf("/Library/Research In Motion/") !== -1;
+ });
+
+ var result = signingHelper.getDbPath();
+ expect(result).toContain("/Library/Research In Motion/");
+ });
+
+ it("returns undefined when keys cannot be found", function () {
+
+ spyOn(fs, "existsSync").andReturn(false);
+
+ var result = signingHelper.getKeyStorePath();
+ expect(result).toBeUndefined();
+ });
+
+ it("returns undefined when barsigner.csk cannot be found", function () {
+
+ spyOn(fs, "existsSync").andReturn(false);
+
+ var result = signingHelper.getCskPath();
+ expect(result).toBeUndefined();
+ });
+
+ it("returns undefined when barsigner.db cannot be found", function () {
+
+ spyOn(fs, "existsSync").andReturn(false);
+
+ var result = signingHelper.getDbPath();
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe("Exec blackberry-signer", function () {
+ var stdoutOn = jasmine.createSpy("stdout on"),
+ stderrOn = jasmine.createSpy("stderr on");
+
+ beforeEach(function () {
+ session = testData.session;
+ session.keystore = "/blah/author.p12";
+ session.storepass = "123";
+ session.barPath = path.normalize("c:/%s/" + "Demo.bar");
+
+ spyOn(childProcess, "spawn").andReturn({
+ stdout: {
+ on: stdoutOn
+ },
+ stderr: {
+ on: stderrOn
+ },
+ on: jasmine.createSpy("on").andCallFake(function (event, callback) {
+ if (callback && typeof callback === "function") {
+ callback(0);
+ }
+ })
+ });
+ });
+
+ it("exec blackberry-signer without extra params", function () {
+ var callback = jasmine.createSpy("callback"),
+ cmd = "blackberry-signer" + (pkgrUtils.isWindows() ? ".bat" : "");
+
+ if (!pkgrUtils.isWindows()) {
+ cmd = path.normalize(conf.DEPENDENCIES_TOOLS + "/bin/") + cmd;
+ }
+
+ session.getParams = jasmine.createSpy("session getParams").andReturn(null);
+ signingHelper.execSigner(session, "device", callback);
+ expect(childProcess.spawn).toHaveBeenCalledWith(cmd, ["-keystore", session.keystore, "-storepass", session.storepass, path.resolve("c:/device/Demo.bar")], jasmine.any(Object));
+ expect(stdoutOn).toHaveBeenCalledWith("data", pkgrUtils.handleProcessOutput);
+ expect(stderrOn).toHaveBeenCalledWith("data", pkgrUtils.handleProcessOutput);
+ expect(callback).toHaveBeenCalledWith(0);
+ });
+
+ it("exec blackberry-signer with extra params", function () {
+ var callback = jasmine.createSpy("callback"),
+ cmd = "blackberry-signer" + (pkgrUtils.isWindows() ? ".bat" : "");
+
+ if (!pkgrUtils.isWindows()) {
+ cmd = path.normalize(conf.DEPENDENCIES_TOOLS + "/bin/") + cmd;
+ }
+
+ session.getParams = jasmine.createSpy("session getParams").andReturn({
+ "-proxyhost": "abc.com",
+ "-proxyport": "80"
+ });
+ signingHelper.execSigner(session, "device", callback);
+ expect(childProcess.spawn.mostRecentCall.args[0]).toBe(cmd);
+ expect(childProcess.spawn.mostRecentCall.args[1]).toContain("-keystore");
+ expect(childProcess.spawn.mostRecentCall.args[1]).toContain(session.keystore);
+ expect(childProcess.spawn.mostRecentCall.args[1]).toContain("-storepass");
+ expect(childProcess.spawn.mostRecentCall.args[1]).toContain(session.storepass);
+ expect(childProcess.spawn.mostRecentCall.args[1]).toContain("-proxyport");
+ expect(childProcess.spawn.mostRecentCall.args[1]).toContain("80");
+ expect(childProcess.spawn.mostRecentCall.args[1]).toContain("-proxyhost");
+ expect(childProcess.spawn.mostRecentCall.args[1]).toContain("abc.com");
+ expect(childProcess.spawn.mostRecentCall.args[1]).toContain(path.resolve("c:/device/Demo.bar"));
+ expect(childProcess.spawn.mostRecentCall.args[1].length).toBe(9);
+ expect(stdoutOn).toHaveBeenCalledWith("data", pkgrUtils.handleProcessOutput);
+ expect(stderrOn).toHaveBeenCalledWith("data", pkgrUtils.handleProcessOutput);
+ expect(callback).toHaveBeenCalledWith(0);
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/test-data.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/test-data.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/test-data.js
new file mode 100644
index 0000000..11ec335
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/test-data.js
@@ -0,0 +1,87 @@
+var path = require("path"),
+ outputDir = path.resolve("../packager.test"),
+ libPath = __dirname + "/../../../../../templates/project/cordova/lib/",
+ barConf = require(libPath + "/bar-conf"),
+ configPath = path.resolve("test") + "/config.xml";
+
+module.exports = {
+ libPath: libPath,
+ configPath: configPath,
+ session: {
+ "barPath": outputDir + "/%s/" + "Demo.bar",
+ "outputDir": outputDir,
+ "sourceDir": path.resolve(outputDir + "/src"),
+ "sourcePaths": {
+ "ROOT": path.resolve(outputDir + "/src"),
+ "CHROME": path.normalize(path.resolve(outputDir + "/src") + barConf.CHROME),
+ "LIB": path.normalize(path.resolve(outputDir + "/src") + barConf.LIB),
+ "UI": path.normalize(path.resolve(outputDir + "/src") + barConf.UI),
+ "EXT": path.normalize(path.resolve(outputDir + "/src") + barConf.EXT),
+ "PLUGINS": path.normalize(path.resolve(outputDir + "/src") + barConf.PLUGINS),
+ "JNEXT_PLUGINS": path.normalize(path.resolve(outputDir + "/src") + barConf.JNEXT_PLUGINS)
+ },
+ "archivePath": path.resolve("bin/test/cordova/unit/test.zip"),
+ "conf": require(path.resolve(libPath + "/conf")),
+ "targets": ["simulator"],
+ isSigningRequired: function () {
+ return false;
+ },
+ getParams: function () {
+ return null;
+ }
+ },
+ config: {
+ "id": 'Demo',
+ "name": { 'default': 'Demo' },
+ "version": '1.0.0',
+ "author": 'Research In Motion Ltd.',
+ "description": { 'default': 'This is a test!' },
+ "image": 'test.png',
+ "autoOrientation": true,
+ "theme": "default"
+ },
+ accessList: [{
+ uri: "http://google.com",
+ allowSubDomain: false,
+ features: [{
+ id: "blackberry.app",
+ required: true,
+ version: "1.0.0"
+ }, {
+ id: "blackberry.system",
+ required: true,
+ version: "1.0.0"
+ }]
+ }, {
+ uri: "WIDGET_LOCAL",
+ allowSubDomain: false,
+ features: [{
+ id: "blackberry.system",
+ required: true,
+ version: "1.0.0"
+ }]
+ }],
+ xml2jsConfig: {
+ "@": {
+ "xmlns": " http://www.w3.org/ns/widgets",
+ "xmlns:rim": "http://www.blackberry.com/ns/widgets",
+ "version": "1.0.0",
+ "id": "myID",
+ "rim:header" : "RIM-Widget:rim/widget",
+ "rim:userAgent" : "A Test-User-Agent/(Blackberry-Agent)"
+ },
+ "name": "Demo",
+ "content": {
+ "@": {
+ "src": "local:///startPage.html"
+ }
+ },
+ "author": "Research In Motion Ltd.",
+ "license": {
+ "#": "Licensed under the Apache License, Version 2.0 (the \"License\"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at # #http://www.apache.org/licenses/LICENSE-2.0 # #Unless required by applicable law or agreed to in writing, software #distributed under the License is distributed on an \"AS IS\" BASIS, #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #See the License for the specific language governing permissions and limitations under the License.",
+ "@": {
+ "href": "http://www.apache.org/licenses/LICENSE-2.0"
+ }
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/test-utilities.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/test-utilities.js b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/test-utilities.js
new file mode 100644
index 0000000..6f0dbf9
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/cordova/unit/spec/lib/test-utilities.js
@@ -0,0 +1,82 @@
+var xml2js = require("xml2js");
+
+function getObjectByProperty(array, propertyName, propertyValue) {
+ for (var i = 0; i < array.length; i++) {
+ if (propertyValue === array[i][propertyName]) {
+ return array[i];
+ }
+ }
+}
+
+module.exports = {
+ getAccessListForUri: function (accessListArray, uriValue) {
+ return getObjectByProperty(accessListArray, "uri", uriValue);
+ },
+
+ getFeatureByID: function (featureArray, featureID) {
+ return getObjectByProperty(featureArray, "id", featureID);
+ },
+
+ mockResolve: function (path) {
+ //Mock resolve because of a weird issue where resolve would return an
+ //invalid path on Mac if it cannot find the directory (c:/ doesnt exist on mac)
+ spyOn(path, "resolve").andCallFake(function (to) {
+ if (arguments.length === 2) {
+ //Handle optional from attribute
+ return path.normalize(path.join(arguments[0], arguments[1]));
+ } else {
+ return path.normalize(to);
+ }
+ });
+ },
+
+ cloneObj: function (obj) {
+ var newObj = (obj instanceof Array) ? [] : {}, i;
+
+ for (i in obj) {
+ if (i === 'clone') continue;
+
+ if (obj[i] && typeof obj[i] === "object") {
+ newObj[i] = this.cloneObj(obj[i]);
+ } else {
+ newObj[i] = obj[i];
+ }
+ }
+
+ return newObj;
+ },
+
+ mockParsing: function (data, error) {
+ spyOn(xml2js, "Parser").andReturn({
+ parseString: function (fileData, callback) {
+ //call callback with no error and altered xml2jsConfig data
+ callback(error, data);
+ }
+ });
+ }
+};
+
+describe("test-utilities", function () {
+ var testUtilities = require("./test-utilities");
+
+ it("can clone objects using cloneObj", function () {
+ var obj = {
+ A: "A",
+ B: "B",
+ C: {
+ CA: "CA",
+ CB: "CB",
+ CC: {
+ CCA: "CCA"
+ }
+ }
+ },
+ clonedObj = testUtilities.cloneObj(obj);
+
+ //not the same object
+ expect(clonedObj).not.toBe(obj);
+
+ //has the same data
+ expect(clonedObj).toEqual(obj);
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/cordova/unit/test.zip
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/cordova/unit/test.zip b/lib/cordova-blackberry/bin/test/cordova/unit/test.zip
new file mode 100644
index 0000000..8859a66
Binary files /dev/null and b/lib/cordova-blackberry/bin/test/cordova/unit/test.zip differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/plugins/Accelerometer/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/plugins/Accelerometer/index.js b/lib/cordova-blackberry/bin/test/plugins/Accelerometer/index.js
new file mode 100644
index 0000000..1819ba7
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/plugins/Accelerometer/index.js
@@ -0,0 +1,81 @@
+/*
+* Copyright 2013 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+describe("Accelerometer", function () {
+ var _apiDir = __dirname + "./../../../../plugins/Accelerometer/src/blackberry10/",
+ index,
+ callback,
+ result = {
+ ok: jasmine.createSpy(),
+ error: jasmine.createSpy(),
+ noResult: jasmine.createSpy(),
+ callbackOk: jasmine.createSpy()
+ },
+ motion = {
+ timestamp: 0,
+ accelerationIncludingGravity: {
+ x: 0,
+ y: 0,
+ z: 0
+ }
+ };
+
+ beforeEach(function () {
+ index = require(_apiDir + "index");
+ GLOBAL.window = {
+ removeEventListener: jasmine.createSpy("removeEventListener spy"),
+ addEventListener: jasmine.createSpy("addEventListener spy").andCallFake(function (evt, cb) {
+ callback = cb;
+ })
+ };
+ GLOBAL.PluginResult = function () {
+ return result;
+ };
+ });
+
+ afterEach(function () {
+ index = null;
+ delete GLOBAL.window;
+ delete GLOBAL.PluginResult;
+ });
+
+ describe("start", function () {
+ it("calls noResult and keeps callbacks", function () {
+ index.start();
+ expect(window.addEventListener).toHaveBeenCalled();
+ expect(result.noResult).toHaveBeenCalledWith(true);
+ });
+
+ it("callback calls ok and keeps callbacks", function () {
+ callback(motion);
+ expect(result.callbackOk).toHaveBeenCalled();
+ });
+
+ it("does not call error if already started", function () {
+ index.start();
+ expect(window.removeEventListener).toHaveBeenCalled();
+ expect(window.addEventListener).toHaveBeenCalled();
+ expect(result.error).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("stop", function () {
+ it("calls result ok", function () {
+ index.stop();
+ expect(window.removeEventListener).toHaveBeenCalled();
+ expect(result.ok).toHaveBeenCalledWith("removed");
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/plugins/Battery/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/plugins/Battery/index.js b/lib/cordova-blackberry/bin/test/plugins/Battery/index.js
new file mode 100644
index 0000000..ff82a21
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/plugins/Battery/index.js
@@ -0,0 +1,103 @@
+/*
+* Copyright 2013 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+describe("Battery", function () {
+
+ var _apiDir = __dirname + "./../../../../plugins/Battery/src/blackberry10/",
+ index,
+ callback,
+ mockPluginResult = {
+ ok: jasmine.createSpy(),
+ error: jasmine.createSpy(),
+ noResult: jasmine.createSpy(),
+ callbackOk: jasmine.createSpy()
+ },
+ noop = function () {},
+ args,
+ env = {
+ webview: {
+ id: 42
+ }
+ };
+
+
+ beforeEach(function () {
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ device: {
+ addEventListener: jasmine.createSpy("webplatform.device.addEventListener").andCallFake(function (evt, cb) {
+ callback = cb;
+ }),
+ removeEventListener: jasmine.createSpy("webplatform.device.removeEventListener")
+ }
+ }
+ }
+ };
+ GLOBAL.PluginResult = function () {
+ return mockPluginResult;
+ };
+ index = require(_apiDir + "index");
+ });
+
+ afterEach(function () {
+ delete GLOBAL.window;
+ delete GLOBAL.PluginResult;
+ delete require.cache[require.resolve(_apiDir + "index")];
+ });
+
+ describe("start", function () {
+
+ it("calls noResult and keeps callbacks", function () {
+ index.start(noop, noop, args, env);
+ expect(window.qnx.webplatform.device.removeEventListener).not.toHaveBeenCalled();
+ expect(window.qnx.webplatform.device.addEventListener).toHaveBeenCalled();
+ expect(mockPluginResult.noResult).toHaveBeenCalledWith(true);
+ expect(mockPluginResult.error).not.toHaveBeenCalled();
+ });
+
+ it("callback calls ok and keeps callbacks", function () {
+ callback("OK");
+ expect(mockPluginResult.callbackOk).toHaveBeenCalledWith("OK", true);
+ expect(mockPluginResult.error).not.toHaveBeenCalled();
+ });
+
+ it("does not call error if already started", function () {
+ index.start(noop, noop, args, env);
+ window.qnx.webplatform.device.addEventListener.reset();
+ mockPluginResult.noResult.reset();
+ index.start(noop, noop, args, env);
+ expect(window.qnx.webplatform.device.removeEventListener).toHaveBeenCalled();
+ expect(window.qnx.webplatform.device.addEventListener).toHaveBeenCalled();
+ expect(mockPluginResult.error).not.toHaveBeenCalled();
+ expect(mockPluginResult.noResult).toHaveBeenCalledWith(true);
+ });
+
+
+ });
+
+ describe("stop", function () {
+
+ it("calls noResult and does not keep callbacks", function () {
+ index.start(noop, noop, args, env);
+ window.qnx.webplatform.device.removeEventListener.reset();
+ index.stop(noop, noop, args, env);
+ expect(window.qnx.webplatform.device.removeEventListener).toHaveBeenCalled();
+ expect(mockPluginResult.noResult).toHaveBeenCalledWith(false);
+ });
+
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/plugins/Camera/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/plugins/Camera/index.js b/lib/cordova-blackberry/bin/test/plugins/Camera/index.js
new file mode 100644
index 0000000..3dcee33
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/plugins/Camera/index.js
@@ -0,0 +1,298 @@
+/*
+* Copyright 2013 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+describe("Camera", function () {
+ var _apiDir = __dirname + "./../../../../plugins/Camera/src/blackberry10/",
+ index,
+ mockDone,
+ mockCancel,
+ mockError,
+ mockedEnv = {
+ response: {
+ send: jasmine.createSpy()
+ },
+ webview: {
+ executeJavaScript: jasmine.createSpy()
+ }
+ },
+ PictureSourceType = {
+ PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
+ CAMERA : 1, // Take picture from camera
+ SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
+ },
+ DestinationType = {
+ DATA_URL: 0, // Return base64 encoded string
+ FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
+ NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
+ },
+ readFail,
+ mockBase64Data = "/9j/4QHRw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
+
+ function mockOpen(options, done, cancel, invoked) {
+ if (!mockError) {
+ invoked();
+ }
+
+ if (mockDone) {
+ done(mockDone.path);
+ } else if (mockCancel) {
+ cancel(mockCancel.reason);
+ } else if (mockError) {
+ invoked(mockError.error);
+ }
+ }
+
+ beforeEach(function () {
+ index = require(_apiDir + "index");
+ mockedEnv.response.send.reset();
+ mockedEnv.webview.executeJavaScript.reset();
+ });
+
+ afterEach(function () {
+ index = null;
+ mockDone = null;
+ mockCancel = null;
+ mockError = null;
+ readFail = false;
+ });
+
+ describe("takePicture", function () {
+ beforeEach(function () {
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ getApplication: function () {
+ return {
+ cards: {
+ camera: {
+ open: jasmine.createSpy().andCallFake(mockOpen)
+ },
+ filePicker: {
+ open: jasmine.createSpy().andCallFake(mockOpen)
+ }
+ }
+ };
+ },
+ getController: function () {
+ return {
+ setFileSystemSandbox: true
+ };
+ }
+ }
+ },
+ webkitRequestFileSystem: jasmine.createSpy().andCallFake(function (type, size, success, error) {
+ success({
+ root: {
+ getFile: jasmine.createSpy().andCallFake(function (path, options, success, error) {
+ if (readFail) {
+ error({
+ code: -1
+ });
+ } else {
+ success({
+ file: jasmine.createSpy().andCallFake(function (cb) {
+ cb();
+ })
+ });
+ }
+ })
+ }
+ });
+ })
+ };
+
+ GLOBAL.FileReader = function () {
+ return {
+ onloadend: jasmine.createSpy(),
+ readAsDataURL: jasmine.createSpy().andCallFake(function (file) {
+ this.onloadend.apply({
+ result: "data:image/jpeg;base64," + mockBase64Data
+ });
+ })
+ };
+ };
+
+ GLOBAL.FileError = {
+ NOT_FOUND_ERR: 1,
+ NOT_READABLE_ERR: 4,
+ PATH_EXISTS_ERR: 12,
+ TYPE_MISMATCH_ERR: 11
+ };
+
+ GLOBAL.PluginResult = function (args, env) {};
+ GLOBAL.PluginResult.prototype.callbackOk = jasmine.createSpy();
+ GLOBAL.PluginResult.prototype.callbackError = jasmine.createSpy();
+ GLOBAL.PluginResult.prototype.noResult = jasmine.createSpy();
+ });
+
+ afterEach(function () {
+ delete GLOBAL.window;
+ delete GLOBAL.FileReader;
+ delete GLOBAL.PluginResult;
+ });
+
+ it("calls PluginResult.callbackOk if invoke camera is successful and image doesn't need encoding", function () {
+ mockDone = {
+ path: "/foo/bar/abc.jpg"
+ };
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.FILE_URI.toString(),
+ "2": PictureSourceType.CAMERA.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackOk).toHaveBeenCalledWith("file://" + mockDone.path, false);
+ });
+
+ it("calls PluginResult.callbackOk if invoke camera and base64 encode image is successful", function () {
+ mockDone = {
+ path: "/foo/bar/abc.jpg"
+ };
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.DATA_URL.toString(),
+ "2": PictureSourceType.CAMERA.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackOk).toHaveBeenCalledWith(mockBase64Data, false);
+ });
+
+ it("calls PluginResult.callbackError if invoke camera is successful but base64 encode image failed", function () {
+ mockDone = {
+ path: "/foo/bar/abc.jpg"
+ };
+ readFail = true;
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.DATA_URL.toString(),
+ "2": PictureSourceType.CAMERA.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackError).toHaveBeenCalledWith("An error occured: Unknown Error", false);
+ });
+
+ it("calls PluginResult.callbackError if invoke camera is cancelled by user", function () {
+ mockCancel = {
+ reason: "done"
+ };
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.FILE_URI.toString(),
+ "2": PictureSourceType.CAMERA.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackError).toHaveBeenCalledWith(mockCancel.reason, false);
+ });
+
+ it("calls PluginResult.callbackError if invoke camera encounters error", function () {
+ mockError = {
+ error: "Camera error"
+ };
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.FILE_URI.toString(),
+ "2": PictureSourceType.CAMERA.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackError).toHaveBeenCalledWith(mockError.error, false);
+ });
+
+ it("calls PluginResult.callbackOk if invoke file picker is successful and image doesn't need encoding", function () {
+ mockDone = {
+ path: "/foo/bar/abc.jpg"
+ };
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.FILE_URI.toString(),
+ "2": PictureSourceType.PHOTOLIBRARY.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackOk).toHaveBeenCalledWith("file://" + mockDone.path, false);
+ });
+
+ it("calls PluginResult.callbackOk if invoke file picker and base64 encode image is successful", function () {
+ mockDone = {
+ path: "/foo/bar/abc.jpg"
+ };
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.DATA_URL.toString(),
+ "2": PictureSourceType.PHOTOLIBRARY.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackOk).toHaveBeenCalledWith(mockBase64Data, false);
+ });
+
+ it("calls PluginResult.callbackError if invoke file picker is successful but base64 encode image failed", function () {
+ mockDone = {
+ path: "/foo/bar/abc.jpg"
+ };
+ readFail = true;
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.DATA_URL.toString(),
+ "2": PictureSourceType.PHOTOLIBRARY.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackError).toHaveBeenCalledWith("An error occured: Unknown Error", false);
+ });
+
+ it("calls PluginResult.callbackError if invoke file picker is cancelled by user", function () {
+ mockCancel = {
+ reason: "cancel"
+ };
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.DATA_URL.toString(),
+ "2": PictureSourceType.PHOTOLIBRARY.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackError).toHaveBeenCalledWith(mockCancel.reason, false);
+ });
+
+ it("calls PluginResult.callbackError if invoke file picker encounters error", function () {
+ mockError = {
+ error: "File picker error"
+ };
+
+ index.takePicture(undefined, undefined, {
+ "1": DestinationType.DATA_URL.toString(),
+ "2": PictureSourceType.PHOTOLIBRARY.toString(),
+ callbackId: "123"
+ }, mockedEnv);
+
+ expect(PluginResult.prototype.noResult).toHaveBeenCalledWith(true);
+ expect(PluginResult.prototype.callbackError).toHaveBeenCalledWith(mockError.error, false);
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/plugins/Contacts/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/plugins/Contacts/index.js b/lib/cordova-blackberry/bin/test/plugins/Contacts/index.js
new file mode 100644
index 0000000..a14d89b
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/plugins/Contacts/index.js
@@ -0,0 +1,197 @@
+/*
+ * Copyright 2013 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+describe("Contacts", function () {
+ var _apiDir = __dirname + "./../../../templates/project/plugins/Contacts/src/blackberry10/",
+ index,
+ ContactError = require(_apiDir + "ContactError"),
+ ContactFindOptions = require(_apiDir + "ContactFindOptions"),
+ result = {
+ noResult: jasmine.createSpy("PluginResult.noResult"),
+ error: jasmine.createSpy("PluginResult.error"),
+ ok: jasmine.createSpy("PluginResult.ok"),
+ callbackError: jasmine.createSpy("PluginResult.callbackError"),
+ callbackOk: jasmine.createSpy("PluginResult.callbackOk"),
+ callbackId: "Contacts12345"
+ };
+
+ beforeEach(function () {
+ GLOBAL.JNEXT = {
+ require: jasmine.createSpy("JNEXT.require").andCallFake(function () {
+ return true;
+ }),
+ createObject: jasmine.createSpy("JNEXT.createObject").andCallFake(function () {
+ return 123;
+ }),
+ invoke: jasmine.createSpy("JNEXT.invoke").andCallFake(function () {
+ return JSON.stringify({
+ _success: true,
+ contact: { id: "123" }
+ });
+ }),
+ registerEvents: jasmine.createSpy("JNEXT.regsiterEvents")
+ };
+ GLOBAL.PluginResult = function () {
+ return result;
+ };
+ index = require(_apiDir + "index");
+ GLOBAL.window = {
+ parseInt: jasmine.createSpy("window.parseInt"),
+ isNaN: jasmine.createSpy("window.isNaN")
+ };
+ });
+
+ afterEach(function () {
+ index = null;
+ delete GLOBAL.JNEXT;
+ delete GLOBAL.window;
+ delete GLOBAL.PluginResult;
+ });
+
+ describe("index.search", function () {
+ it("correctly parses args to pass down to native (with filter)", function () {
+ var findOptions = new ContactFindOptions("test"),
+ args = {
+ "0": encodeURIComponent(JSON.stringify(["phoneNumbers", "emails"])),
+ "1": encodeURIComponent(JSON.stringify(findOptions)),
+ "callbackId": encodeURIComponent(JSON.stringify("Contacts12345"))
+ },
+ jnextArgs = {
+ "_eventId": "Contacts12345",
+ "fields": ["phoneNumbers", "emails"],
+ "options": {
+ "filter": [
+ { "fieldValue": "test" }
+ ]
+ }
+ };
+ index.search(function () {}, function () {}, args, {});
+ expect(JNEXT.invoke).toHaveBeenCalledWith(123, 'find ' + JSON.stringify(jnextArgs));
+ expect(result.noResult).toHaveBeenCalledWith(true);
+ });
+
+ it("correctly parses args to pass down to native (with no filter)", function () {
+ var findOptions = new ContactFindOptions(),
+ args = {
+ "0": encodeURIComponent(JSON.stringify(["phoneNumbers", "emails"])),
+ "1": encodeURIComponent(JSON.stringify(findOptions)),
+ "callbackId": encodeURIComponent(JSON.stringify("Contacts12345"))
+ },
+ jnextArgs = {
+ "_eventId": "Contacts12345",
+ "fields": ["phoneNumbers", "emails"],
+ "options": {
+ "filter": []
+ }
+ };
+ index.search(function () {}, function () {}, args, {});
+ expect(JNEXT.invoke).toHaveBeenCalledWith(123, 'find ' + JSON.stringify(jnextArgs));
+ expect(result.noResult).toHaveBeenCalledWith(true);
+ });
+ });
+
+ describe("index.save", function () {
+ it("calls JNEXT save with the correct param if contactId provided", function () {
+ var contactProps = {
+ "id": "123"
+ },
+ args = {
+ "0": encodeURIComponent(JSON.stringify(contactProps)),
+ "callbackId": encodeURIComponent(JSON.stringify("Contacts12345"))
+ };
+
+ window.parseInt.andCallFake(function () {
+ return 123;
+ });
+ index.save(function () {}, function () {}, args, {});
+ expect(JNEXT.invoke).toHaveBeenCalledWith(123, 'save ' + JSON.stringify({"id": 123, "_eventId": "Contacts12345"}));
+ expect(result.noResult).toHaveBeenCalledWith(true);
+ });
+
+ it("properly converts birthdays for native", function () {
+ var contactProps = {
+ birthday: 1367259069028,
+ },
+ args = {
+ "0": encodeURIComponent(JSON.stringify(contactProps)),
+ "callbackId": encodeURIComponent(JSON.stringify("Contacts12345"))
+ },
+ processedArgs = {
+ "birthday": "Mon Apr 29 2013",
+ "_eventId": "Contacts12345"
+ };
+
+ index.save(function () {}, function () {}, args, {});
+ expect(JNEXT.invoke).toHaveBeenCalledWith(123, 'save ' + JSON.stringify(processedArgs));
+ expect(result.noResult).toHaveBeenCalledWith(true);
+ });
+
+ it("processes emails contactFeild array", function () {
+ var contactProps = {
+ "emails": [
+ { "value": "a@c.com" },
+ { "type" : "home", "value": "a@b.com" }
+ ]
+ },
+ args = {
+ "0": encodeURIComponent(JSON.stringify(contactProps)),
+ "callbackId": encodeURIComponent(JSON.stringify("Contacts12345"))
+ },
+ processedArgs = {
+ "emails": [
+ { "type": "home", "value": "a@c.com" },
+ { "type": "home", "value": "a@b.com" },
+ ],
+ "_eventId": "Contacts12345"
+ };
+ index.save(function () {}, function () {}, args, {});
+ expect(JNEXT.invoke).toHaveBeenCalledWith(123, 'save ' + JSON.stringify(processedArgs));
+ expect(result.noResult).toHaveBeenCalledWith(true);
+
+ });
+
+ });
+
+ describe("index.remove", function () {
+ it("calls JNEXT remove with the correct params for valid contactId", function () {
+ var args = {
+ "0": encodeURIComponent(JSON.stringify(123)),
+ "callbackId": encodeURIComponent(JSON.stringify("Contacts12345"))
+ };
+
+ window.parseInt.andCallFake(function () {
+ return 123;
+ });
+ index.remove(function () {}, function () {}, args, {});
+ expect(JNEXT.invoke).toHaveBeenCalledWith(123, 'remove ' + JSON.stringify({"contactId": 123, "_eventId": "Contacts12345"}));
+ expect(result.noResult).toHaveBeenCalledWith(true);
+ });
+
+ it("calls callbackError if invalid ID", function () {
+ var args = {
+ "0": encodeURIComponent(JSON.stringify("asdfas")),
+ "callbackId": encodeURIComponent(JSON.stringify("Contacts12345"))
+ };
+
+ window.isNaN.andCallFake(function() {
+ return true;
+ });
+ index.remove(function () {}, function () {}, args, {});
+ expect(result.error).toHaveBeenCalledWith(ContactError.UNKNOWN_ERROR);
+ expect(result.noResult).toHaveBeenCalledWith(false);
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/plugins/Device/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/plugins/Device/index.js b/lib/cordova-blackberry/bin/test/plugins/Device/index.js
new file mode 100644
index 0000000..4c5fb29
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/plugins/Device/index.js
@@ -0,0 +1,76 @@
+/*
+* Copyright 2013 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+describe("Device", function () {
+
+ var _apiDir = __dirname + "./../../../../plugins/Device/src/blackberry10/",
+ index,
+ result = {
+ ok: jasmine.createSpy()
+ };
+
+ beforeEach(function () {
+ index = require(_apiDir + "index");
+ });
+
+ afterEach(function () {
+ index = null;
+ });
+
+ describe("getDeviceInfo", function () {
+ beforeEach(function () {
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ device: {
+ }
+ }
+ }
+ };
+ GLOBAL.PluginResult = function () {
+ return result;
+ };
+ });
+
+ afterEach(function () {
+ delete GLOBAL.window;
+ delete GLOBAL.PluginResult;
+ });
+
+ it("calls ok with the Device info", function () {
+ var mockedDevice = {
+ scmBundle: "1.0.0.0",
+ modelName: "q10",
+ devicePin: (new Date()).getTime()
+ };
+
+ result.ok = jasmine.createSpy().andCallFake(function (deviceInfo) {
+ expect(deviceInfo.platform).toEqual("blackberry10");
+ expect(deviceInfo.version).toEqual(mockedDevice.scmBundle);
+ expect(deviceInfo.model).toEqual(mockedDevice.modelName);
+ expect(deviceInfo.name).toEqual(mockedDevice.modelName);
+ expect(deviceInfo.uuid).toEqual(mockedDevice.devicePin);
+ expect(deviceInfo.cordova).toBeDefined();
+ });
+
+ window.qnx.webplatform.device = mockedDevice;
+
+ index.getDeviceInfo();
+
+ expect(result.ok).toHaveBeenCalled();
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/plugins/Logger/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/plugins/Logger/index.js b/lib/cordova-blackberry/bin/test/plugins/Logger/index.js
new file mode 100644
index 0000000..cec4556
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/plugins/Logger/index.js
@@ -0,0 +1,51 @@
+/*
+* Copyright 2013 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+describe("Logger", function () {
+
+ var _apiDir = __dirname + "./../../../../plugins/Logger/src/blackberry10/",
+ index,
+ result = {
+ noResult: jasmine.createSpy("noResult")
+ };
+
+ beforeEach(function () {
+ index = require(_apiDir + "index");
+ });
+
+ afterEach(function () {
+ index = null;
+ });
+
+ describe("logLevel", function () {
+ beforeEach(function () {
+ spyOn(console, "log");
+ GLOBAL.PluginResult = function () {
+ return result;
+ };
+ });
+
+ afterEach(function () {
+ delete GLOBAL.PluginResult;
+ });
+
+ it("calls console.log", function () {
+ index.logLevel(function () {}, function () {}, ["%22ERROR%22", "%22message%22"]);
+ expect(console.log).toHaveBeenCalledWith("ERROR: message");
+ expect(result.noResult).toHaveBeenCalledWith(false);
+ });
+ });
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/plugins/NetworkStatus/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/plugins/NetworkStatus/index.js b/lib/cordova-blackberry/bin/test/plugins/NetworkStatus/index.js
new file mode 100644
index 0000000..ac87390
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/plugins/NetworkStatus/index.js
@@ -0,0 +1,118 @@
+/*
+* Copyright 2013 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+
+describe("NetworkStatus", function () {
+ var _apiDir = __dirname + "./../../../../plugins/NetworkStatus/src/blackberry10/",
+ index,
+ result = {
+ ok: jasmine.createSpy(),
+ error: jasmine.createSpy()
+ };
+
+ beforeEach(function () {
+ index = require(_apiDir + "index");
+ });
+
+ afterEach(function () {
+ index = null;
+ });
+
+ describe("getConnectionInfo", function () {
+ beforeEach(function () {
+ GLOBAL.window = {
+ qnx: {
+ webplatform: {
+ device: {
+ }
+ }
+ }
+ };
+ GLOBAL.PluginResult = function () {
+ return result;
+ };
+ });
+
+ afterEach(function () {
+ delete GLOBAL.window;
+ delete GLOBAL.PluginResult;
+ });
+
+ function testConnection(expectedResult, mockedType, mockedTechnology) {
+ var mockedDevice = {
+ activeConnection: {
+ type: mockedType,
+ technology: mockedTechnology
+ }
+ };
+
+ if (mockedType) {
+ window.qnx.webplatform.device = mockedDevice;
+ }
+
+ index.getConnectionInfo();
+
+ expect(result.ok).toHaveBeenCalledWith(expectedResult);
+ expect(result.error).not.toHaveBeenCalled();
+ }
+
+ it("calls success with a wired connection", function () {
+ testConnection("ethernet", "wired");
+ });
+
+ it("calls success with a wifi connection", function () {
+ testConnection("wifi", "wifi");
+ });
+
+ it("calls success with no connection", function () {
+ testConnection("none", "none");
+ });
+
+ it("calls success with a cellular edge connection", function () {
+ testConnection("2g", "cellular", "edge");
+ });
+
+ it("calls success with a cellular gsm connection", function () {
+ testConnection("2g", "cellular", "gsm");
+ });
+
+ it("calls success with a cellular evdo connection", function () {
+ testConnection("3g", "cellular", "evdo");
+ });
+
+ it("calls success with a cellular umts connection", function () {
+ testConnection("3g", "cellular", "umts");
+ });
+
+ it("calls success with a lte connection", function () {
+ testConnection("4g", "cellular", "lte");
+ });
+
+ it("calls success with a cellular connection", function () {
+ testConnection("cellular", "cellular");
+ });
+
+ it("defaults to none if no connection is found", function () {
+ testConnection("none");
+ });
+
+ it("defaults to unknown if connection type doesn't exist", function () {
+ testConnection("unknown", "fakeConnectionType");
+ });
+
+ });
+
+});
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/test/plugins/Notification/index.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/test/plugins/Notification/index.js b/lib/cordova-blackberry/bin/test/plugins/Notification/index.js
new file mode 100644
index 0000000..8d10e25
--- /dev/null
+++ b/lib/cordova-blackberry/bin/test/plugins/Notification/index.js
@@ -0,0 +1,119 @@
+/*
+* Copyright 2013 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+function mockAndTestDialog(htmlmessage, title, dialogType, buttonLabel) {
+ GLOBAL.qnx = {
+ webplatform: {
+ getWebViews: function () {
+ var webviews = [{}, {},
+ {//overlayWebview
+ dialog: {
+ show: function(messageObj, callback) {
+ expect(messageObj.title).toEqual(title);
+ expect(messageObj.htmlmessage).toEqual(htmlmessage);
+ expect(messageObj.dialogType).toEqual(dialogType);
+ expect(messageObj.optionalButtons).toEqual(buttonLabel);
+ expect(typeof callback).toEqual("function");
+ }
+ }
+ }];
+ return webviews;
+ }
+ }
+ };
+
+}
+
+describe("Notification", function () {
+ var _apiDir = __dirname + "./../../../../plugins/Notification/src/blackberry10/",
+ index,
+ success = function() {},
+ fail = function() {},
+ result = {
+ error: jasmine.createSpy(),
+ noResult: jasmine.createSpy()
+ },
+ args = {
+ 0: "%22Dialog%20message.%22",
+ 1: "%22Dialog%20Title%22",
+ 2: "%22Continue%22"
+ };
+
+ beforeEach(function () {
+ index = require(_apiDir + "index");
+
+ GLOBAL.PluginResult = function () {
+ return result;
+ };
+ });
+
+ afterEach(function () {
+ delete require.cache[require.resolve(_apiDir + "index")];
+ delete GLOBAL.qnx;
+ delete GLOBAL.PluginResult;
+ });
+
+ describe("alert", function () {
+ it("fails with invalid number of args", function () {
+ index.alert(success, fail, {}, {});
+ expect(result.error).toHaveBeenCalledWith("Notification action - alert arguments not found.");
+ });
+
+ it("calls dialog.show with correct params", function () {
+ mockAndTestDialog("Dialog message.", "Dialog Title", "CustomAsk", ["Continue"]);
+ index.alert(success, fail, args, {});
+ expect(result.noResult).toHaveBeenCalled();
+ });
+ });
+
+ describe("confirm", function () {
+ it("fails with invalid number of args", function () {
+ index.confirm(success, fail, {}, {});
+ expect(result.error).toHaveBeenCalledWith("Notification action - confirm arguments not found.");
+ });
+
+ it("calls dialog.show with correct params", function () {
+ mockAndTestDialog("Dialog message.", "Dialog Title", "CustomAsk", ["Continue"]);
+ index.confirm(success, fail, args, {});
+ expect(result.noResult).toHaveBeenCalled();
+ });
+
+ it("calls dialog.show with correct params [deprecated buttonArg]", function () {
+ var args = {
+ 0: "%22Dialog%20message.%22",
+ 1: "%22Dialog%20Title%22",
+ 2: "%22Continue,Cancel%22"
+ };
+
+ mockAndTestDialog("Dialog message.", "Dialog Title", "CustomAsk", ["Continue", "Cancel"]);
+ index.confirm(success, fail, args, {});
+ expect(result.noResult).toHaveBeenCalled();
+ });
+ });
+
+ describe("prompt", function () {
+ it("fails with invalid number of args", function () {
+ index.prompt(success, fail, {}, {});
+ expect(result.error).toHaveBeenCalledWith("Notification action - prompt arguments not found.");
+ });
+
+ it("calls dialog.show with correct params", function () {
+ mockAndTestDialog("Dialog message.", "Dialog Title", "JavaScriptPrompt", ["Continue"]);
+ index.prompt(success, fail, args, {});
+ expect(result.noResult).toHaveBeenCalled();
+ });
+ });
+});
[22/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginResult.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginResult.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginResult.java
deleted file mode 100644
index ce84884..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/api/PluginResult.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.api;
-
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONObject;
-
-/**
- * This class defines the standard object that should be returned as the
- * result of any Cordova plugin invocation.
- */
-public class PluginResult {
-
- private final int status;
- private final String message;
- private boolean keepCallback = false;
-
- public PluginResult(Status status) {
- this.status = status.ordinal();
- this.message = JSONObject.quote(status.getMessage());
- }
-
- public PluginResult(Status status, String message) {
- this.status = status.ordinal();
- this.message = JSONObject.quote(message);
- }
-
- public PluginResult(Status status, JSONArray message) {
- this.status = status.ordinal();
- this.message = message.toString();
- }
-
- public PluginResult(Status status, JSONObject message) {
- this.status = status.ordinal();
- this.message = (message != null) ? message.toString(): "null";
- }
-
- public PluginResult(Status status, int i) {
- this.status = status.ordinal();
- this.message = ""+i;
- }
-
- public PluginResult(Status status, float f) {
- this.status = status.ordinal();
- this.message = ""+f;
- }
-
- public PluginResult(Status status, boolean b) {
- this.status = status.ordinal();
- this.message = ""+b;
- }
-
- public PluginResult(Status status, long l) {
- this.status = status.ordinal();
- this.message = ""+l;
- }
-
- public int getStatus() {
- return status;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setKeepCallback(boolean b) {
- this.keepCallback = b;
- }
-
- public boolean getKeepCallback() {
- return this.keepCallback;
- }
-
- public String getJSONString() {
- return "{\"status\":" + this.status + ",\"message\":" + this.message + ",\"keepCallback\":" + this.keepCallback + "}";
- }
-
- /**
- * Returns the JavaScript string that executes the success callback for the
- * appropriate Cordova plugin. The string is intended to be passed to the
- * JavaScript engine.
- * @param callbackId Unique id of the callback that is associated with the invoked plugin
- * @return JavaScript string that invokes the appropriate plugin success callback
- */
- public String toSuccessCallbackString(String callbackId) {
- return "try { cordova.callbackSuccess('"+callbackId+"', " + this.getJSONString() + "); } catch(e) { alert('error in callbackSuccess:' + e.message); }";
- }
-
- /**
- * Returns the JavaScript string that executes the error callback for the
- * appropriate Cordova plugin. The string is intended to be passed to the
- * JavaScript engine.
- * @param callbackId Unique id of the callback that is associated with the invoked plugin
- * @return JavaScript string that invokes the appropriate plugin error callback
- */
- public String toErrorCallbackString(String callbackId) {
- return "try { cordova.callbackError('"+callbackId+"', " + this.getJSONString() + "); } catch(e) { alert('error in callbackError:' + e.message); }";
- }
-
- public String toErrorString() {
- return "alert('general error');";
- }
-
- /**
- * Enumerates PluginResult status.
- */
- public static class Status
- {
- private int val;
- private String message;
-
- protected Status(int val, String message) {
- this.val = val;
- this.message = message;
- }
-
- public int ordinal() {
- return this.val;
- }
-
- public String getMessage() {
- return this.message;
- }
-
- public static final Status NO_RESULT = new Status(0, "No result");
- public static final Status OK = new Status(1, "OK");
- public static final Status CLASS_NOT_FOUND_EXCEPTION = new Status(2, "Class not found");
- public static final Status ILLEGAL_ACCESS_EXCEPTION = new Status(3, "Illegal access");
- public static final Status INSTANTIATION_EXCEPTION = new Status(4, "Instantiation error");
- public static final Status MALFORMED_URL_EXCEPTION = new Status(5, "Malformed URL");
- public static final Status IO_EXCEPTION = new Status(6, "IO error");
- public static final Status INVALID_ACTION = new Status(7, "Invalid action");
- public static final Status JSON_EXCEPTION = new Status(8, "JSON error");
- public static final Status ERROR = new Status(9, "Error");
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/app/App.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/app/App.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/app/App.java
deleted file mode 100644
index 38ae205..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/app/App.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.app;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-
-import net.rim.device.api.browser.field2.BrowserFieldHistory;
-import net.rim.device.api.system.Application;
-import net.rim.device.api.system.SystemListener2;
-
-/**
- * The App plug-in. This class provides access to application specific
- * management. The following actions are supported:
- *
- * clearHistory - Clear the browser history.
- * backHistory - Navigate back in the browser history.
- * detectBacklight - Start a system listener for backlight changes.
- * ignoreBacklight - Stop the system listener for backlight changes.
- */
-public class App extends Plugin {
-
- private final static String ACTION_CLEAR_HISTORY = "clearHistory";
- private final static String ACTION_BACK_HISTORY = "backHistory";
- private final static String ACTION_DETECT_BACKLIGHT = "detectBacklight";
- private final static String ACTION_IGNORE_BACKLIGHT = "ignoreBacklight";
-
- private SystemListener2 listener = null;
- private String callbackId = null;
-
- /**
- * Executes the requested action and returns a PluginResult.
- *
- * @param action
- * The action to execute.
- * @param callbackId
- * The callback ID to be invoked upon action completion
- * @param args
- * JSONArry of arguments for the action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args,
- final String callbackId) {
- PluginResult result = null;
-
- if (ACTION_CLEAR_HISTORY.equals(action)) {
- BrowserFieldHistory history = CordovaExtension.getBrowserField()
- .getHistory();
- if (history != null) {
- history.clearHistory();
- }
- result = new PluginResult(PluginResult.Status.OK);
- } else if (ACTION_BACK_HISTORY.equals(action)) {
- CordovaExtension.getBrowserField().back();
- result = new PluginResult(PluginResult.Status.OK);
- } else if (ACTION_DETECT_BACKLIGHT.equals(action)) {
- addListener(callbackId);
- result = new PluginResult(PluginResult.Status.NO_RESULT);
- result.setKeepCallback(true);
- } else if (ACTION_IGNORE_BACKLIGHT.equals(action)) {
- removeListener();
- result = new PluginResult(PluginResult.Status.OK);
- } else {
- result = new PluginResult(PluginResult.Status.INVALID_ACTION,
- "App: Invalid action: " + action);
- }
-
- return result;
- }
-
- /**
- * Called when Plugin is destroyed.
- */
- public void onDestroy() {
- removeListener();
- }
-
- /**
- * Register a system listener for backlight changes if one has not already
- * been registered.
- *
- * @param callbackId
- * the callback ID associated with the system listener
- */
- private synchronized void addListener(final String callbackId) {
- if (listener == null) {
- listener = new SystemListener2() {
- public void batteryGood() {}
- public void batteryLow() {}
- public void batteryStatusChange(int status) {}
- public void powerOff() {}
- public void powerUp() {}
-
- public void backlightStateChange(boolean on) {
- PluginResult result = new PluginResult(
- PluginResult.Status.OK, on);
-
- // Must keep the call back active for future events.
- result.setKeepCallback(true);
- success(result, callbackId);
- }
-
- public void cradleMismatch(boolean mismatch) {}
- public void fastReset() {}
- public void powerOffRequested(int reason) {}
- public void usbConnectionStateChange(int state) {}
- };
-
- this.callbackId = callbackId;
- Application.getApplication().addSystemListener(listener);
- }
- }
-
- /**
- * Remove the system listener if it is registered and close out the
- * callback handler.
- */
- private synchronized void removeListener() {
- if (listener != null) {
- Application.getApplication().removeSystemListener(listener);
- listener = null;
-
- if (callbackId != null) {
- success(new PluginResult(PluginResult.Status.NO_RESULT),
- callbackId);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/battery/Battery.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/battery/Battery.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/battery/Battery.java
deleted file mode 100644
index 55356a5..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/battery/Battery.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.battery;
-
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.system.Application;
-import net.rim.device.api.system.DeviceInfo;
-import net.rim.device.api.system.SystemListener;
-
-/**
- * The Battery plug-in. This class provides information about the state of the
- * battery on the phone. The following actions are supported:
- *
- * start - Start listening for changes in battery level (%) and batter
- * charging state.
- * stop - Stop listening for changes in battery level and state.
- */
-public class Battery extends Plugin {
-
- /** Actions to start and stop listening for battery changes. */
- private final static String ACTION_START = "start";
- private final static String ACTION_STOP = "stop";
-
- /** The percentage of battery remaining. */
- private final static String LEVEL = "level";
-
- /** Whether the battery is currently charging or not. */
- private final static String CHARGING = "isPlugged";
-
- // The set of call back IDs to send results to. Using Hashtable because
- // BlackBerry does not support Collections. There should only ever be one
- // call back ID, but this allows multiple.
- private Hashtable callbackIds = new Hashtable();
-
- private SystemListener batteryListener = null;
-
- /**
- * Executes the requested action and returns a PluginResult.
- *
- * @param action
- * The action to execute.
- * @param callbackId
- * The callback ID to be invoked upon action completion
- * @param args
- * JSONArry of arguments for the action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult result = null;
-
- if (ACTION_START.equals(action)) {
- // Register a listener to detect battery changes.
- addListener(callbackId);
-
- // Don't return any result now, since battery status results are
- // sent when listener is notified.
- result = new PluginResult(PluginResult.Status.NO_RESULT);
-
- // Must keep the call back active for future events.
- result.setKeepCallback(true);
- } else if (ACTION_STOP.equals(action)) {
- // Remove the battery listener and cleanup call back IDs.
- removeListener();
- result = new PluginResult(PluginResult.Status.OK);
- } else {
- result = new PluginResult(PluginResult.Status.INVALID_ACTION,
- "Battery: Invalid action: " + action);
- }
-
- return result;
- }
-
- /**
- * Remove the listener when the application is destroyed. Note that onPause
- * is not overridden, so the listener will continue if the application is
- * simply paused instead of destroyed.
- */
- public void onDestroy() {
- removeListener();
- }
-
- /**
- * Adds a SystemListener to listen for changes to the battery state. The
- * listener is only registered if one has not already been added. If a
- * listener has already been registered the call back id is simply saved so
- * that it can be notified upon next battery state change.
- *
- * @param callbackId
- * The reference point to call back when a listener event occurs.
- */
- private synchronized void addListener(String callbackId) {
- callbackIds.put(callbackId, callbackId);
-
- // Only register a listener if one has not been registered.
- if (batteryListener == null) {
- batteryListener = new SystemListener() {
- // Initialize the charging state and battery level.
- private boolean prevChargeState = (DeviceInfo
- .getBatteryStatus() & DeviceInfo.BSTAT_CHARGING) != 0;
- private int prevLevel = DeviceInfo.getBatteryLevel();
-
- public void batteryGood() { }
- public void batteryLow() { }
-
- public void batteryStatusChange(int status) {
- // The status bits passed into this method are unreliable
- // in determining when the battery level has changed.
- // Instead, when any state change occurs, get the current
- // battery level and report the change if it is different
- // then previous value.
- int newLevel = DeviceInfo.getBatteryLevel();
- boolean newChargeState = (DeviceInfo.BSTAT_CHARGING & status) != 0;
-
- // Report change if level or charge state is different then
- // previous values.
- if (newLevel != prevLevel || newChargeState != prevChargeState) {
- prevChargeState = newChargeState;
- prevLevel = newLevel;
-
- // Store the retrieved properties in a JSON object.
- JSONObject connectionInfo = new JSONObject();
- try {
- connectionInfo.put(LEVEL, newLevel);
- connectionInfo.put(CHARGING, newChargeState);
- } catch (JSONException e) {
- Logger.error("JSONException: " + e.getMessage());
- return;
- }
-
- PluginResult result = new PluginResult(
- PluginResult.Status.OK, connectionInfo);
-
- sendSuccessResult(result, true);
- }
- }
-
- public void powerOff() { }
- public void powerUp() { }
- };
- Application.getApplication().addSystemListener(batteryListener);
- }
- }
-
- /**
- * Remove the registered battery status listener and cleanup the call back
- * IDs.
- */
- private synchronized void removeListener() {
- if (batteryListener != null) {
-
- // Remove the battery listener.
- Application.getApplication().removeSystemListener(batteryListener);
- batteryListener = null;
-
- // Close out the call back IDs.
- sendSuccessResult(new PluginResult(PluginResult.Status.OK), false);
- callbackIds.clear();
- }
- }
-
- /**
- * Helper function to send the PluginResult to the saved call back IDs.
- *
- * @param result
- * the PluginResult to return
- * @param keepCallback
- * Boolean value indicating whether to keep the call back id
- * active.
- */
- private void sendSuccessResult(PluginResult result, boolean keepCallback) {
-
- if (result != null) {
- // Must keep the call back active for future events.
- result.setKeepCallback(keepCallback);
-
- // Iterate through the saved call back IDs. Really should only ever
- // be one.
- for (Enumeration callbacks = this.callbackIds.elements(); callbacks
- .hasMoreElements();) {
- success(result, (String) callbacks.nextElement());
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/Camera.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/Camera.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/Camera.java
deleted file mode 100644
index d54483f..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/Camera.java
+++ /dev/null
@@ -1,470 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.camera;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Date;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.file.FileConnection;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.util.Logger;
-
-import net.rim.blackberry.api.invoke.CameraArguments;
-import net.rim.blackberry.api.invoke.Invoke;
-import net.rim.device.api.io.Base64OutputStream;
-import net.rim.device.api.io.IOUtilities;
-import net.rim.device.api.system.ApplicationDescriptor;
-import net.rim.device.api.system.Bitmap;
-import net.rim.device.api.system.Characters;
-import net.rim.device.api.system.ControlledAccessException;
-import net.rim.device.api.system.EncodedImage;
-import net.rim.device.api.system.EventInjector;
-import net.rim.device.api.system.JPEGEncodedImage;
-import net.rim.device.api.system.PNGEncodedImage;
-import net.rim.device.api.ui.UiApplication;
-
-/**
- * The Camera plugin interface.
- *
- * The Camera class can invoke the following actions:
- *
- * - takePicture: takes photo and returns base64 encoded image or image file URI
- *
- * future?
- * - captureVideo...
- *
- */
-public class Camera extends Plugin
-{
- /**
- * Possible actions.
- */
- public static final String ACTION_TAKE_PICTURE = "takePicture";
-
- /**
- * Maximum image encoding size (in bytes) to allow. (Obtained unofficially
- * through trial and error). Anything larger will cause stability issues
- * when sending back to the browser.
- */
- private static final long MAX_ENCODING_SIZE = 1500000L;
-
- /**
- * Executes the requested action and returns a PluginResult.
- *
- * @param action The action to execute.
- * @param callbackId The callback ID to be invoked upon action completion
- * @param args JSONArry of arguments for the action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId)
- {
- PluginResult result = null;
-
- // take a picture
- if (action != null && action.equals(ACTION_TAKE_PICTURE))
- {
- // Parse the options specified for the take picture action.
- CameraOptions options;
- try {
- options = CameraOptions.fromJSONArray(args);
- } catch (NumberFormatException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "One of the camera options is not a valid number.");
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "One of the camera options is not valid JSON.");
- }
-
- // launch native camera application
- launchCamera(new PhotoListener(options, callbackId));
-
- // The native camera application runs in a separate process, so we
- // must now wait for the listener to retrieve the photo taken.
- // Return NO_RESULT status so plugin manager does not invoke a callback,
- // but keep the callback so the listener can invoke it later.
- result = new PluginResult(PluginResult.Status.NO_RESULT);
- result.setKeepCallback(true);
- return result;
- }
- else
- {
- result = new PluginResult(PluginResult.Status.INVALID_ACTION, "Camera: Invalid action:" + action);
- }
-
- return result;
- }
-
- /**
- * Launches the native camera application.
- */
- private static void launchCamera(PhotoListener listener)
- {
- // MMAPI interface doesn't use the native Camera application or interface
- // (we would have to replicate it). So, we invoke the native Camera application,
- // which doesn't allow us to set any options.
- synchronized(UiApplication.getEventLock()) {
- UiApplication.getUiApplication().addFileSystemJournalListener(listener);
- Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA, new CameraArguments());
- }
- }
-
- /**
- * Closes the native camera application.
- */
- public static void closeCamera()
- {
- // simulate two escape characters to exit native camera application
- // no, there is no other way to do this
- UiApplication.getUiApplication().invokeLater(new Runnable() {
- public void run() {
- try
- {
- EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
- EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0);
- inject.post();
- inject.post();
- }
- catch (ControlledAccessException e)
- {
- // the application doesn't have key injection permissions
- Logger.log(Camera.class.getName() + ": Unable to close camera. " +
- ApplicationDescriptor.currentApplicationDescriptor().getName() +
- " does not have key injection permissions.");
- }
- }
- });
- }
-
- /**
- * Returns the image file URI or the Base64-encoded image.
- * @param filePath The full path of the image file
- * @param options Specifies the format of the image and the result
- * @param callbackId The id of the callback to receive the result
- */
- public static void processImage(String filePath, CameraOptions options,
- String callbackId) {
- PluginResult result = null;
- try
- {
- // wait for the file to be fully written to the file system
- // to avoid premature access to it (yes, this has happened)
- waitForImageFile(filePath);
-
- // Reformat the image if the specified options require it,
- // otherwise, get encoded string if base 64 string is output format.
- String imageURIorData = filePath;
-
- // save to file:///store/home/user/ as oppsed to photo album
- // so it doesn't show up in the camera's photo album viewer
- if(!options.saveToPhotoAlbum){
- FileConnection fconnIn = null;
- FileConnection fconnOut = null;
- InputStream in = null;
- OutputStream out = null;
- String newOutName = "";
- try
- {
- fconnIn = (FileConnection)Connector.open(filePath);
- if (fconnIn.exists())
- {
- newOutName = "file:///store/home/user/"+fconnIn.getName();
- fconnOut = (FileConnection)Connector.open(newOutName);
- if (!fconnOut.exists())
- {
- fconnOut.create();
- in = fconnIn.openInputStream();
- out = fconnOut.openOutputStream();
- out.write(IOUtilities.streamToBytes(in, 96*1024));
- fconnIn.delete();
- out.close();
- imageURIorData = newOutName;
- filePath = newOutName;
- waitForImageFile(newOutName);
- }
- }
- }
- finally
- {
- if (in != null) in.close();
- if (out != null) out.close();
- if (fconnIn != null) fconnIn.close();
- if (fconnOut != null) fconnOut.close();
- }
-
- }
-
- if (options.reformat) {
- imageURIorData = reformatImage(filePath, options);
- } else if (options.destinationType == CameraOptions.DESTINATION_DATA_URL) {
- imageURIorData = encodeImage(filePath);
- }
-
- // we have to check the size to avoid memory errors in the browser
- if (imageURIorData.length() > MAX_ENCODING_SIZE)
- {
- // it's a big one. this is for your own good.
- String msg = "Encoded image is too large. Try reducing camera image size.";
- Logger.log(Camera.class.getName() + ": " + msg);
- result = new PluginResult(PluginResult.Status.ERROR, msg);
- }
- else
- {
- result = new PluginResult(PluginResult.Status.OK, imageURIorData);
- }
- }
- catch (Exception e)
- {
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION, e.toString());
- }
-
- // send result back to JavaScript
- sendResult(result, callbackId);
- }
-
- /**
- * Waits for the image file to be fully written to the file system.
- * @param filePath Full path of the image file
- * @throws IOException
- */
- private static void waitForImageFile(String filePath) throws IOException
- {
- long start = (new Date()).getTime();
- FileConnection fconn = null;
- try
- {
- fconn = (FileConnection)Connector.open(filePath, Connector.READ);
- if (fconn.exists())
- {
- long fileSize = fconn.fileSize();
- long size = 0;
- while (true)
- {
- try { Thread.sleep(100); } catch (InterruptedException e) {}
- size = fconn.fileSize();
- if (size == fileSize) {
- break;
- }
- fileSize = size;
- }
- Logger.log(Camera.class.getName() + ": " + filePath +
- " size=" + Long.toString(fileSize) + " bytes");
- }
- }
- finally
- {
- if (fconn != null) fconn.close();
- }
- long end = (new Date()).getTime();
- Logger.log(Camera.class.getName() + ": wait time=" + Long.toString(end-start) + " ms");
- }
-
- /**
- * Opens the specified image file and converts its contents to a Base64-encoded string.
- * @param filePath Full path of the image file
- * @return file contents as a Base64-encoded String
- */
- private static String encodeImage(String filePath) throws IOException
- {
- String imageData = null;
-
- // open the image file
- FileConnection fconn = null;
- InputStream in = null;
- ByteArrayOutputStream byteArrayOS = null;
- try
- {
- fconn = (FileConnection)Connector.open(filePath);
- if (fconn.exists())
- {
- // encode file contents using BASE64 encoding
- in = fconn.openInputStream();
- byteArrayOS = new ByteArrayOutputStream();
- Base64OutputStream base64OS = new Base64OutputStream(byteArrayOS);
- base64OS.write(IOUtilities.streamToBytes(in, 96*1024));
- base64OS.flush();
- base64OS.close();
- imageData = byteArrayOS.toString();
-
- Logger.log(Camera.class.getName() + ": Base64 encoding size=" +
- Integer.toString(imageData.length()));
- }
- }
- finally
- {
- if (in != null) in.close();
- if (fconn != null) fconn.close();
- if (byteArrayOS != null) byteArrayOS.close();
- }
-
- return imageData;
- }
-
- /**
- * Reformats the image taken with the camera based on the options specified.
- *
- * Unfortunately, reformatting the image will cause EXIF data in the photo
- * to be lost. Most importantly the orientation data is lost so the
- * picture is not auto rotated by software that recognizes EXIF data.
- *
- * @param filePath
- * The full path of the image file
- * @param options
- * Specifies the format of the image and the result
- * @return the reformatted image file URI or Base64-encoded image
- * @throws IOException
- */
- private static String reformatImage(String filePath, CameraOptions options)
- throws IOException {
- long start = (new Date()).getTime();
-
- // Open the original image created by the camera application and read
- // it into an EncodedImage object.
- FileConnection fconn = null;
- InputStream in = null;
- Bitmap originalImage = null;
- try {
- fconn = (FileConnection) Connector.open(filePath);
- in = fconn.openInputStream();
- originalImage = Bitmap.createBitmapFromBytes(IOUtilities.streamToBytes(in, 96*1024), 0, -1, 1);
- } finally {
- if (in != null)
- in.close();
- if (fconn != null)
- fconn.close();
- }
-
- int newWidth = options.targetWidth;
- int newHeight = options.targetHeight;
- int origWidth = originalImage.getWidth();
- int origHeight = originalImage.getHeight();
-
- // If only width or only height was specified, the missing dimension is
- // set based on the current aspect ratio of the image.
- if (newWidth > 0 && newHeight <= 0) {
- newHeight = (newWidth * origHeight) / origWidth;
- } else if (newWidth <= 0 && newHeight > 0) {
- newWidth = (newHeight * origWidth) / origHeight;
- } else if (newWidth <= 0 && newHeight <= 0) {
- newWidth = origWidth;
- newHeight = origHeight;
- } else {
- // If the user specified both a positive width and height
- // (potentially different aspect ratio) then the width or height is
- // scaled so that the image fits while maintaining aspect ratio.
- // Alternatively, the specified width and height could have been
- // kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
- // would result in whitespace in the new image.
- double newRatio = newWidth / (double)newHeight;
- double origRatio = origWidth / (double)origHeight;
-
- if (origRatio > newRatio) {
- newHeight = (newWidth * origHeight) / origWidth;
- } else if (origRatio < newRatio) {
- newWidth = (newHeight * origWidth) / origHeight;
- }
- }
-
- Bitmap newImage = new Bitmap(newWidth, newHeight);
- originalImage.scaleInto(newImage, options.imageFilter, Bitmap.SCALE_TO_FILL);
-
- // Convert the image to the appropriate encoding. PNG does not allow
- // quality to be specified so the only affect that the quality option
- // has for a PNG is on the seelction of the image filter.
- EncodedImage encodedImage;
- if (options.encoding == CameraOptions.ENCODING_PNG) {
- encodedImage = PNGEncodedImage.encode(newImage);
- } else {
- encodedImage = JPEGEncodedImage.encode(newImage, options.quality);
- }
-
- // Rewrite the modified image back out to the same file. This is done
- // to ensure that for every picture taken, only one shows up in the
- // gallery. If the encoding changed the file extension will differ
- // from the original.
- OutputStream out = null;
- int dirIndex = filePath.lastIndexOf('/');
- String filename = filePath.substring(dirIndex + 1, filePath.lastIndexOf('.'))
- + options.fileExtension;
- try {
- fconn = (FileConnection) Connector.open(filePath);
- fconn.truncate(0);
- out = fconn.openOutputStream();
- out.write(encodedImage.getData());
- fconn.rename(filename);
- } finally {
- if (out != null)
- out.close();
- if (fconn != null)
- fconn.close();
- }
-
- // Return either the Base64-encoded string or the image URI for the
- // new image.
- String imageURIorData;
- if (options.destinationType == CameraOptions.DESTINATION_DATA_URL) {
- ByteArrayOutputStream byteArrayOS = null;
-
- try {
- byteArrayOS = new ByteArrayOutputStream();
- Base64OutputStream base64OS = new Base64OutputStream(
- byteArrayOS);
- base64OS.write(encodedImage.getData());
- base64OS.flush();
- base64OS.close();
- imageURIorData = byteArrayOS.toString();
- Logger.log(Camera.class.getName() + ": Base64 encoding size="
- + Integer.toString(imageURIorData.length()));
- } finally {
- if (byteArrayOS != null) {
- byteArrayOS.close();
- }
- }
- } else {
- imageURIorData = filePath.substring(0, dirIndex + 1) + filename;
- }
-
- long end = (new Date()).getTime();
- Logger.log(Camera.class.getName() + ": reformat time=" + Long.toString(end-start) + " ms");
-
- return imageURIorData;
- }
-
- /**
- * Sends result back to JavaScript.
- * @param result PluginResult
- */
- private static void sendResult(PluginResult result, String callbackId)
- {
- // invoke the appropriate callback
- if (result.getStatus() == PluginResult.Status.OK.ordinal())
- {
- success(result, callbackId);
- }
- else
- {
- error(result, callbackId);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/CameraOptions.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/CameraOptions.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/CameraOptions.java
deleted file mode 100644
index 8bfa0df..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/CameraOptions.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.camera;
-
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-
-import net.rim.device.api.system.Bitmap;
-
-/**
- * A helper class to hold all the options specified when using the camera api.
- */
-public class CameraOptions {
-
- /** Return the result as a Base-64 encoded string. */
- public static final int DESTINATION_DATA_URL = 0;
-
- /** Return the result as a file URI. */
- public static final int DESTINATION_FILE_URI = 1;
-
- /** JPEG image encoding. */
- public static final int ENCODING_JPEG = 0;
-
- /** PNG image encoding. */
- public static final int ENCODING_PNG = 1;
-
- /** Select image from picture library. */
- public static final int SOURCE_PHOTOLIBRARY = 0;
-
- /** Take picture from camera. */
- public static final int SOURCE_CAMERA = 1;
-
- /** Select image from picture library. */
- public static final int SOURCE_SAVEDPHOTOALBUM = 2;
-
- // Class members with defaults set.
- public int quality = 80;
- public int destinationType = DESTINATION_DATA_URL;
- public int sourceType = SOURCE_CAMERA;
- public int targetWidth = -1;
- public int targetHeight = -1;
- public int encoding = ENCODING_JPEG;
- public String fileExtension = ".jpg";
- public int imageFilter = Bitmap.FILTER_LANCZOS;
- public boolean reformat = false;
- public boolean saveToPhotoAlbum = true;
-
- /**
- * Defines the order of args in the JSONArray
- *
- * [ 80, // quality
- * Camera.DestinationType.DATA_URL, // destinationType
- * Camera.PictureSourceType.PHOTOLIBRARY // sourceType (ignored)
- * 400, // targetWidth
- * 600, // targetHeight
- * Camera.EncodingType.JPEG // encoding
- * Camera.mediaType
- * Camera.allowEdit
- * Camera.correctOrientation
- * Camera.saveToPhotoAlbum // save to photo album
- * Camera.popoverOptions]
- */
- private static final int ARG_QUALITY = 0;
- private static final int ARG_DESTINATION_TYPE = 1;
- private static final int ARG_SOURCE_TYPE = 2;
- private static final int ARG_TARGET_WIDTH = 3;
- private static final int ARG_TARGET_HEIGHT = 4;
- private static final int ARG_ENCODING = 5;
- private static final int ARG_SAVETOPHOTOALBUM = 9;
-
- /**
- * Parse the JSONArray and populate the class members with the values.
- *
- * @param args
- * a JSON Array of camera options.
- * @return a new CameraOptions object with values set.
- * @throws NumberFormatException
- * @throws JSONException
- */
- public static CameraOptions fromJSONArray(JSONArray args)
- throws NumberFormatException, JSONException {
- CameraOptions options = new CameraOptions();
-
- if (args != null && args.length() > 0) {
- // Use the quality value to determine what image filter to use
- // if a reformat is necessary. The possible values in order from
- // fastest (poorest quality) to slowest (best quality) are:
- //
- // FILTER_BOX -> FILTER_BILINEAR -> FILTER_LANCZOS
- if (!args.isNull(ARG_QUALITY)) {
- int quality = Integer.parseInt(args.getString(ARG_QUALITY));
- if (quality > 0) {
- options.quality = quality > 100 ? 100 : quality;
- if (options.quality < 30) {
- options.imageFilter = Bitmap.FILTER_BOX;
- } else if (options.quality < 60) {
- options.imageFilter = Bitmap.FILTER_BILINEAR;
- }
- }
- }
-
- if (!args.isNull(ARG_DESTINATION_TYPE)) {
- int destType = Integer.parseInt(args
- .getString(ARG_DESTINATION_TYPE));
- if (destType == DESTINATION_FILE_URI) {
- options.destinationType = DESTINATION_FILE_URI;
- }
- }
-
- if (!args.isNull(ARG_SOURCE_TYPE)) {
- options.sourceType = Integer.parseInt(args
- .getString(ARG_SOURCE_TYPE));
- }
-
- if (!args.isNull(ARG_TARGET_WIDTH)) {
- options.targetWidth = Integer.parseInt(args
- .getString(ARG_TARGET_WIDTH));
- }
-
- if (!args.isNull(ARG_TARGET_HEIGHT)) {
- options.targetHeight = Integer.parseInt(args
- .getString(ARG_TARGET_HEIGHT));
- }
-
- if (!args.isNull(ARG_ENCODING)) {
- int encoding = Integer.parseInt(args.getString(ARG_ENCODING));
- if (encoding == ENCODING_PNG) {
- options.encoding = ENCODING_PNG;
- options.fileExtension = ".png";
- }
- }
-
- // A reformat of the picture taken from the camera is only performed
- // if a custom width or height was specified or the user wants
- // the output in an encoded form which is not JPEG.
- if (options.targetWidth > 0 || options.targetHeight > 0
- || options.encoding != ENCODING_JPEG) {
- options.reformat = true;
- }
-
- if (!args.isNull(ARG_SAVETOPHOTOALBUM)) {
- options.saveToPhotoAlbum = parseBoolean(args.getString(ARG_SAVETOPHOTOALBUM));
- }
-
- }
-
- return options;
- }
-
- /**
- * no parseBoolean in JDK 1.3 :(
- */
- public static boolean parseBoolean(String s) {
- if(s.equals("true")){
- return true;
- }else{
- return false;
- }
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- StringBuffer str = new StringBuffer();
- str.append("Destination: " + destinationType + "\n");
- str.append("Source: " + sourceType + "\n");
- str.append("Quality: " + quality + "\n");
- str.append("Width: " + targetWidth + "\n");
- str.append("Height: " + targetHeight + "\n");
- str.append("Encoding: " + encoding + "\n");
- str.append("Filter: " + imageFilter + "\n");
- str.append("Reformat: " + reformat);
- str.append("Save To Photo Album: " + saveToPhotoAlbum);
- return str.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/PhotoListener.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/PhotoListener.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/PhotoListener.java
deleted file mode 100644
index 8571788..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/camera/PhotoListener.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.camera;
-
-import net.rim.device.api.io.file.FileSystemJournal;
-import net.rim.device.api.io.file.FileSystemJournalEntry;
-import net.rim.device.api.io.file.FileSystemJournalListener;
-import net.rim.device.api.ui.UiApplication;
-
-/**
- * Listens for photo added to file system and invokes the specified callback
- * with the result formatted according the specified destination type.
- */
-public class PhotoListener implements FileSystemJournalListener {
-
- /**
- * Image format options specified by the caller.
- */
- private CameraOptions options;
-
- /**
- * Callback to be invoked with the result.
- */
- private String callbackId;
-
- /**
- * Used to track file system changes.
- */
- private long lastUSN = 0;
-
- /**
- * Constructor.
- * @param options Specifies the format of the image and result
- * @param callbackId The id of the callback to receive the result
- */
- public PhotoListener(CameraOptions options, String callbackId)
- {
- this.options = options;
- this.callbackId = callbackId;
- }
-
- /**
- * Listens for file system changes. When a JPEG file is added, we process
- * it and send it back.
- */
- public void fileJournalChanged()
- {
- // next sequence number file system will use
- long USN = FileSystemJournal.getNextUSN();
-
- for (long i = USN - 1; i >= lastUSN && i < USN; --i)
- {
- FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
- if (entry == null)
- {
- break;
- }
-
- if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED)
- {
- String path = entry.getPath();
- if (path != null && path.indexOf(".jpg") != -1)
- {
- // we found a new JPEG file
- // first, stop listening to avoid processing the file more than once
- synchronized(UiApplication.getEventLock()) {
- UiApplication.getUiApplication().removeFileSystemJournalListener(this);
- }
-
- // process the image on a background thread to avoid clogging the event queue
- final String filePath = "file://" + path;
- Thread thread = new Thread(new Runnable() {
- public void run() {
- Camera.processImage(filePath, options, callbackId);
- }
- });
- thread.start();
-
- // clean up
- Camera.closeCamera();
-
- break;
- }
- }
- }
-
- // remember the file journal change number,
- // so we don't search the same events again and again
- lastUSN = USN;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioCaptureListener.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioCaptureListener.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioCaptureListener.java
deleted file mode 100644
index 9267e9b..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioCaptureListener.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import net.rim.device.api.io.file.FileSystemJournal;
-import net.rim.device.api.io.file.FileSystemJournalEntry;
-import net.rim.device.api.io.file.FileSystemJournalListener;
-
-/**
- * Listens for audio recording files that are added to file system.
- * <p>
- * Audio recordings are added to the file system when the user stops the
- * recording. The audio recording file extension is '.amr'. Therefore, we listen
- * for the <code>FileSystemJournalEntry.FILE_ADDED</code> event, capturing when
- * the new file is written.
- * <p>
- * The file system notifications will arrive on the application event thread.
- * When it receives a notification, it adds the image file path to a MediaQueue
- * so that the capture thread can process the file.
- */
-public class AudioCaptureListener implements FileSystemJournalListener {
- /**
- * Used to track file system changes.
- */
- private long lastUSN = 0;
-
- /**
- * Queue to send media files to for processing.
- */
- private MediaQueue queue = null;
-
- /**
- * Constructor.
- */
- AudioCaptureListener(MediaQueue queue) {
- this.queue = queue;
- }
-
- public void fileJournalChanged() {
- // next sequence number file system will use
- long USN = FileSystemJournal.getNextUSN();
-
- for (long i = USN - 1; i >= lastUSN && i < USN; --i) {
- FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
- if (entry == null) {
- break;
- }
-
- // has audio recording file has been added to the file system?
- String path = entry.getPath();
- if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED
- && path.endsWith(".amr")) {
- // add file path to the capture queue
- queue.add("file://" + path);
-
- break;
- }
- }
-
- // remember the file journal change number,
- // so we don't search the same events again and again
- lastUSN = USN;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioCaptureOperation.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioCaptureOperation.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioCaptureOperation.java
deleted file mode 100644
index f4fd9b4..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioCaptureOperation.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import java.io.IOException;
-import java.util.Date;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.file.FileConnection;
-
-import org.apache.cordova.file.File;
-import org.apache.cordova.util.FileUtils;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.io.MIMETypeAssociations;
-import net.rim.device.api.ui.UiApplication;
-
-public class AudioCaptureOperation extends CaptureOperation {
-
- // content type
- public static final String CONTENT_TYPE = "audio/";
-
- // maximum duration to capture media (milliseconds)
- private double duration = 0;
-
- // file system listener
- private AudioCaptureListener listener = null;
-
- /**
- * Creates and starts an audio capture operation.
- *
- * @param limit
- * maximum number of media files to capture
- * @param duration
- * maximum duration to capture media (milliseconds)
- * @param callbackId
- * the callback to receive the files
- * @param queue
- * the queue from which to retrieve captured media files
- */
- public AudioCaptureOperation(long limit, double duration, String callbackId, MediaQueue queue) {
- super(limit, callbackId, queue);
-
- if (duration > 0) {
- this.duration = duration;
- }
-
- // listener to capture image files added to file system
- this.listener = new AudioCaptureListener(queue);
-
- start();
- }
-
- /**
- * Registers file system listener and launches native voice notes recorder
- * application.
- */
- protected void setup() {
- // register listener for files being written
- synchronized(UiApplication.getEventLock()) {
- UiApplication.getUiApplication().addFileSystemJournalListener(listener);
- }
-
- // launch the native voice notes recorder application
- AudioControl.launchAudioRecorder();
- }
-
- /**
- * Unregisters file system listener and closes native voice notes recorder
- * application.
- */
- protected void teardown() {
- // remove file system listener
- synchronized(UiApplication.getEventLock()) {
- UiApplication.getUiApplication().removeFileSystemJournalListener(listener);
- }
-
- // close the native voice notes recorder application
- AudioControl.closeAudioRecorder();
- }
-
- /**
- * Retrieves the file properties for the captured audio recording.
- *
- * @param filePath
- * full path of the audio recording file
- */
- protected void processFile(String filePath) {
- Logger.log(this.getClass().getName() + ": processing file: " + filePath);
-
- // wait for file to finish writing and add it to captured files
- addCaptureFile(getMediaFile(filePath));
- }
-
- /**
- * Waits for file to be fully written to the file system before retrieving
- * its file properties.
- *
- * @param filePath
- * Full path of the image file
- * @throws IOException
- */
- private File getMediaFile(String filePath) {
- File file = new File(FileUtils.stripSeparator(filePath));
-
- // time begin waiting for file write
- long start = (new Date()).getTime();
-
- // wait for the file to be fully written, then grab its properties
- FileConnection fconn = null;
- try {
- fconn = (FileConnection) Connector.open(filePath, Connector.READ);
- if (fconn.exists()) {
- // wait for file to be fully written
- long fileSize = fconn.fileSize();
- long size = 0;
- Thread thisThread = Thread.currentThread();
- while (myThread == thisThread) {
- try {
- Thread.sleep(100);
- }
- catch (InterruptedException e) {
- break;
- }
- size = fconn.fileSize();
- if (fileSize != 0 && size == fileSize) {
- break;
- }
- fileSize = size;
- }
- Logger.log(this.getClass().getName() + ": " + filePath + " size="
- + Long.toString(fileSize) + " bytes");
-
- // retrieve file properties
- file.setLastModifiedDate(fconn.lastModified());
- file.setName(FileUtils.stripSeparator(fconn.getName()));
- file.setSize(fileSize);
- file.setType(MIMETypeAssociations.getMIMEType(filePath));
- }
- }
- catch (IOException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- }
- finally {
- try {
- if (fconn != null) fconn.close();
- } catch (IOException ignored) {}
- }
-
- // log time it took to write the file
- long end = (new Date()).getTime();
- Logger.log(this.getClass().getName() + ": wait time="
- + Long.toString(end - start) + " ms");
-
- return file;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioControl.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioControl.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioControl.java
deleted file mode 100644
index 45e9f9c..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/AudioControl.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import org.apache.cordova.util.ApplicationUtils;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.system.ApplicationDescriptor;
-import net.rim.device.api.system.ApplicationManager;
-import net.rim.device.api.system.ApplicationManagerException;
-import net.rim.device.api.system.CodeModuleManager;
-
-public class AudioControl {
- /**
- * Determines if the native voice notes recorder application is installed
- * on the device.
- *
- * @return true if native voice notes recorder application is installed
- */
- public static boolean hasAudioRecorderApplication() {
- return ApplicationUtils.isModuleInstalled("net_rim_bb_voicenotesrecorder");
- }
-
- /**
- * Determines if the native voice notes recorder application is running in
- * the foreground.
- *
- * @return true if native voice notes recorder application is running in
- * foreground
- */
- public static boolean isAudioRecorderActive() {
- return ApplicationUtils.isApplicationInForeground("net_rim_bb_voicenotesrecorder");
- }
-
- /**
- * Launches the native audio recorder application.
- */
- public static void launchAudioRecorder() {
- int handle = CodeModuleManager.getModuleHandle("net_rim_bb_voicenotesrecorder");
- ApplicationDescriptor ad = CodeModuleManager.getApplicationDescriptors(handle)[0];
- ApplicationDescriptor ad2 = new ApplicationDescriptor(ad, null);
- try {
- ApplicationManager.getApplicationManager().runApplication(ad2, true);
- }
- catch (ApplicationManagerException e) {
- Logger.log(AudioControl.class.getName() + ": unable to launch net_rim_bb_voicenotesrecorder");
- }
- }
-
- /**
- * Closes the native audio recorder application.
- */
- public static void closeAudioRecorder() {
- if (!isAudioRecorderActive()) {
- return;
- }
- ApplicationUtils.injectEscKeyPress(1);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CameraControl.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CameraControl.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CameraControl.java
deleted file mode 100644
index 2ed9206..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CameraControl.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import org.apache.cordova.util.ApplicationUtils;
-
-import net.rim.blackberry.api.invoke.CameraArguments;
-import net.rim.blackberry.api.invoke.Invoke;
-import net.rim.device.api.ui.UiApplication;
-
-public class CameraControl {
- /**
- * Determines if the native camera application is running in the foreground.
- *
- * @return true if native camera application is running in foreground
- */
- public static boolean isCameraActive() {
- return ApplicationUtils.isApplicationInForeground("net_rim_bb_camera");
- }
-
- /**
- * Determines if the native video recorder application is running in the
- * foreground.
- *
- * @return true if native video recorder application is running in
- * foreground
- */
- public static boolean isVideoRecorderActive() {
- return ApplicationUtils.isApplicationInForeground("net_rim_bb_videorecorder");
- }
-
- /**
- * Launches the native camera application.
- */
- public static void launchCamera() {
- synchronized(UiApplication.getEventLock()) {
- Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
- new CameraArguments());
- }
- }
-
- /**
- * Launches the native video recorder application.
- */
- public static void launchVideoRecorder() {
- synchronized(UiApplication.getEventLock()) {
- Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
- new CameraArguments(CameraArguments.ARG_VIDEO_RECORDER));
- }
- }
-
- /**
- * Closes the native camera application.
- */
- public static void closeCamera() {
- if (!isCameraActive()) {
- return;
- }
- ApplicationUtils.injectEscKeyPress(2);
- }
-
- /**
- * Closes the native video recorder application.
- */
- public static void closeVideoRecorder() {
- if (!isVideoRecorderActive()) {
- return;
- }
- ApplicationUtils.injectEscKeyPress(2);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureControl.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureControl.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureControl.java
deleted file mode 100644
index e37dd56..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureControl.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import java.util.Enumeration;
-import java.util.Vector;
-
-public class CaptureControl {
-
- /**
- * Pending capture operations.
- */
- private Vector pendingOperations = new Vector();
-
- /**
- * Singleton.
- */
- private CaptureControl() {}
-
- /**
- * Holds the singleton for lazy instantiation.
- */
- private static class CaptureControlHolder {
- static final CaptureControl INSTANCE = new CaptureControl();
- }
-
- /**
- * Retrieves a CaptureControl instance.
- * @return CaptureControl instance.
- */
- public static final CaptureControl getCaptureControl() {
- return CaptureControlHolder.INSTANCE;
- }
-
- /**
- * Add capture operation so we can stop it manually.
- */
- public void addCaptureOperation(CaptureOperation operation) {
- if (operation == null) {
- return;
- }
-
- synchronized (pendingOperations) {
- pendingOperations.addElement(operation);
- }
- }
-
- /**
- * Remove capture operation.
- */
- public void removeCaptureOperation(CaptureOperation operation) {
- if (operation == null) {
- return;
- }
-
- synchronized (pendingOperations) {
- pendingOperations.removeElement(operation);
- }
- }
-
- /**
- * Starts an image capture operation, during which a user can take multiple
- * photos. The capture operation runs in the background.
- *
- * @param limit
- * the maximum number of images to capture during the operation
- * @param callbackId
- * the callback to be invoked with capture file properties
- */
- public void startImageCaptureOperation(long limit, String callbackId) {
- // setup a queue to receive image file paths
- MediaQueue queue = new MediaQueue();
-
- // start a capture operation on a background thread
- CaptureOperation operation = new ImageCaptureOperation(limit,
- callbackId, queue);
-
- // track the operation so we can stop or cancel it later
- addCaptureOperation(operation);
- }
-
- /**
- * Starts a video capture operation, during which a user can record multiple
- * recordings. The capture operation runs in the background.
- *
- * @param limit
- * the maximum number of images to capture during the operation
- * @param callbackId
- * the callback to be invoked with capture file properties
- */
- public void startVideoCaptureOperation(long limit, String callbackId) {
- // setup a queue to receive video recording file paths
- MediaQueue queue = new MediaQueue();
-
- // start a capture operation on a background thread
- CaptureOperation operation = new VideoCaptureOperation(limit,
- callbackId, queue);
-
- // track the operation so we can stop or cancel it later
- addCaptureOperation(operation);
- }
-
- /**
- * Starts an audio capture operation using the native voice notes recorder
- * application.
- *
- * @param limit
- * the maximum number of audio clips to capture during the
- * operation
- * @param duration
- * the maximum duration of each captured clip
- * @param callbackId
- * the callback to be invoked with the capture results
- */
- public void startAudioCaptureOperation(long limit, double duration, String callbackId) {
- // setup a queue to receive recording file paths
- MediaQueue queue = new MediaQueue();
-
- // start a capture operation on a background thread
- CaptureOperation operation = new AudioCaptureOperation(limit, duration,
- callbackId, queue);
-
- // track the operation so we can stop or cancel it later
- addCaptureOperation(operation);
- }
-
- /**
- * Stops all pending capture operations. If the <code>cancel</code>
- * parameter is <code>true</code>, no results will be sent via the callback
- * mechanism and any captured files will be removed from the file system.
- *
- * @param cancel
- * true if operations should be canceled
- */
- public void stopPendingOperations(boolean cancel) {
- // There are two scenarios where the capture operation would be stopped
- // manually:
- // 1- The user stops the capture application, and this application
- // returns to the foreground.
- // 2- It is canceled programmatically. No results should be sent.
- synchronized (pendingOperations) {
- for (Enumeration e = pendingOperations.elements(); e.hasMoreElements(); ) {
- CaptureOperation operation = (CaptureOperation) e.nextElement();
- if (cancel) {
- operation.cancel();
- }
- else {
- operation.stop();
- }
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureMode.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureMode.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureMode.java
deleted file mode 100644
index 7c71f96..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureMode.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-
-public class CaptureMode {
-
- private String mimeType = null;
- private long height = 0;
- private long width = 0;
-
- public CaptureMode() {
- }
-
- public CaptureMode(String type) {
- this.mimeType = type;
- }
-
- public CaptureMode(String type, long width, long height) {
- this.mimeType = type;
- this.height = height;
- this.width = width;
- }
-
- public String getMimeType() {
- return mimeType;
- }
-
- public long getHeight() {
- return height;
- }
-
- public long getWidth() {
- return width;
- }
-
- public JSONObject toJSONObject() {
- JSONObject o = new JSONObject();
- try {
- o.put("type", getMimeType());
- o.put("height", getHeight());
- o.put("width", getWidth());
- }
- catch (JSONException ignored) {
- }
- return o;
- }
-
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof CaptureMode)) {
- return false;
- }
- CaptureMode cm = (CaptureMode)o;
- return ((mimeType == null ? cm.mimeType == null :
- mimeType.equals(cm.mimeType))
- && (width == cm.width)
- && (height == cm.height));
- }
-
- public int hashCode() {
- int hash = (mimeType != null ? mimeType.hashCode() : 19);
- hash = 37*hash + (int)width;
- hash = 37*hash + (int)height;
- return hash;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureOperation.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureOperation.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureOperation.java
deleted file mode 100644
index dc85bd8..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/CaptureOperation.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import java.io.IOException;
-import java.util.Enumeration;
-import java.util.Vector;
-
-import org.apache.cordova.file.File;
-import org.apache.cordova.util.FileUtils;
-import org.apache.cordova.util.Logger;
-
-public abstract class CaptureOperation implements Runnable {
- // max number of media files to capture
- protected long limit = 1;
-
- // for sending results
- protected String callbackId = null;
-
- // list of captured media files
- protected final Vector captureFiles = new Vector();
-
- // media file queue
- protected MediaQueue mediaQueue = null;
-
- // used to interrupt thread
- protected volatile Thread myThread;
-
- // to determine if operation has been canceled
- protected boolean canceled = false;
-
- /**
- * Creates and starts a capture operation on a new thread.
- *
- * @param limit
- * maximum number of media files to capture
- * @param callbackId
- * the callback to receive the files
- * @param queue
- * the queue from which to retrieve captured media files
- */
- public CaptureOperation(long limit, String callbackId, MediaQueue queue) {
- if (limit > 1) {
- this.limit = limit;
- }
-
- this.callbackId = callbackId;
- this.mediaQueue = queue;
- this.myThread = new Thread(this);
- }
-
- /**
- * Waits for media file to be captured.
- */
- public void run() {
- if (myThread == null) {
- return; // stopped before started
- }
-
- Logger.log(this.getClass().getName() + ": " + callbackId + " started");
-
- // tasks to be run before entering main loop
- setup();
-
- // capture until interrupted or we've reached capture limit
- Thread thisThread = Thread.currentThread();
- String filePath = null;
- while (myThread == thisThread && captureFiles.size() < limit) {
- try {
- // consume file added to media capture queue
- filePath = mediaQueue.remove();
- }
- catch (InterruptedException e) {
- Logger.log(this.getClass().getName() + ": " + callbackId + " interrupted");
- // and we're done
- break;
- }
- processFile(filePath);
- }
-
- // perform cleanup tasks
- teardown();
-
- // process captured results
- processResults();
-
- // unregister the operation from the controller
- CaptureControl.getCaptureControl().removeCaptureOperation(this);
-
- Logger.log(this.getClass().getName() + ": " + callbackId + " finished");
- }
-
- /**
- * Starts this capture operation on a new thread.
- */
- protected void start() {
- if (myThread == null) {
- return; // stopped before started
- }
- myThread.start();
- }
-
- /**
- * Stops the operation.
- */
- public void stop() {
- // interrupt capture thread
- Thread tmpThread = myThread;
- myThread = null;
- if (tmpThread != null && tmpThread.isAlive()) {
- tmpThread.interrupt();
- }
- }
-
- /**
- * Cancels the operation.
- */
- public void cancel() {
- canceled = true;
- stop();
- }
-
- /**
- * Processes the results of the capture operation.
- */
- protected void processResults() {
- // process results
- if (!canceled) {
- // invoke appropriate callback
- if (captureFiles.size() > 0) {
- // send capture files
- MediaCapture.captureSuccess(captureFiles, callbackId);
- }
- else {
- // error
- MediaCapture.captureError(callbackId);
- }
- }
- else {
- removeCaptureFiles();
- }
- }
-
- /**
- * Adds a media file to list of collected media files for this operation.
- *
- * @param file
- * object containing media file properties
- */
- protected void addCaptureFile(File file) {
- captureFiles.addElement(file);
- }
-
- /**
- * Removes captured files from the file system.
- */
- protected void removeCaptureFiles() {
- for (Enumeration e = captureFiles.elements(); e.hasMoreElements();) {
- File file = (File) e.nextElement();
- try {
- FileUtils.delete(file.getFullPath());
- }
- catch (IOException ignored) {
- }
- }
- }
-
- /**
- * Override this method to perform tasks before the operation starts.
- */
- protected void setup() {
- }
-
- /**
- * Override this method to perform tasks after the operation has
- * stopped.
- */
- protected void teardown() {
- }
-
- /**
- * Subclasses must implement this method to process a captured media file.
- * @param filePath the full path of the media file
- */
- protected abstract void processFile(final String filePath);
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/ImageCaptureListener.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/ImageCaptureListener.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/ImageCaptureListener.java
deleted file mode 100644
index 4906ee8..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/capture/ImageCaptureListener.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.capture;
-
-import net.rim.device.api.io.file.FileSystemJournal;
-import net.rim.device.api.io.file.FileSystemJournalEntry;
-import net.rim.device.api.io.file.FileSystemJournalListener;
-
-/**
- * Listens for image files that are added to file system.
- * <p>
- * The file system notifications will arrive on the application event thread.
- * When it receives a notification, it adds the image file path to a MediaQueue
- * so that the capture thread can process the file.
- */
-class ImageCaptureListener implements FileSystemJournalListener {
-
- /**
- * Used to track file system changes.
- */
- private long lastUSN = 0;
-
- /**
- * Collection of media files.
- */
- private MediaQueue queue = null;
-
- /**
- * Constructor.
- */
- ImageCaptureListener(MediaQueue queue) {
- this.queue = queue;
- }
-
- /**
- * Listens for file system changes. When a JPEG file is added, we process
- * it and send it back.
- */
- public void fileJournalChanged()
- {
- // next sequence number file system will use
- long USN = FileSystemJournal.getNextUSN();
-
- for (long i = USN - 1; i >= lastUSN && i < USN; --i)
- {
- FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
- if (entry == null)
- {
- break;
- }
-
- if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED)
- {
- String path = entry.getPath();
- if (path != null && path.indexOf(".jpg") != -1)
- {
- // add file path to the capture queue
- queue.add("file://" + path);
- break;
- }
- }
- }
-
- // remember the file journal change number,
- // so we don't search the same events again and again
- lastUSN = USN;
- }
-}
[04/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-ios/CordovaLib/cordova.ios.js
----------------------------------------------------------------------
diff --git a/lib/cordova-ios/CordovaLib/cordova.ios.js b/lib/cordova-ios/CordovaLib/cordova.ios.js
deleted file mode 100644
index b716939..0000000
--- a/lib/cordova-ios/CordovaLib/cordova.ios.js
+++ /dev/null
@@ -1,6419 +0,0 @@
-// Platform: ios
-
-// commit cd29cf0f224ccf25e9d422a33fd02ef67d3a78f4
-
-// File generated at :: Mon Apr 29 2013 16:14:47 GMT-0700 (PDT)
-
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-
-;(function() {
-
-// file: lib/scripts/require.js
-
-var require,
- define;
-
-(function () {
- var modules = {};
- // Stack of moduleIds currently being built.
- var requireStack = [];
- // Map of module ID -> index into requireStack of modules currently being built.
- var inProgressModules = {};
-
- function build(module) {
- var factory = module.factory;
- module.exports = {};
- delete module.factory;
- factory(require, module.exports, module);
- return module.exports;
- }
-
- require = function (id) {
- if (!modules[id]) {
- throw "module " + id + " not found";
- } else if (id in inProgressModules) {
- var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;
- throw "Cycle in require graph: " + cycle;
- }
- if (modules[id].factory) {
- try {
- inProgressModules[id] = requireStack.length;
- requireStack.push(id);
- return build(modules[id]);
- } finally {
- delete inProgressModules[id];
- requireStack.pop();
- }
- }
- return modules[id].exports;
- };
-
- define = function (id, factory) {
- if (modules[id]) {
- throw "module " + id + " already defined";
- }
-
- modules[id] = {
- id: id,
- factory: factory
- };
- };
-
- define.remove = function (id) {
- delete modules[id];
- };
-
- define.moduleMap = modules;
-})();
-
-//Export for use in node
-if (typeof module === "object" && typeof require === "function") {
- module.exports.require = require;
- module.exports.define = define;
-}
-
-// file: lib/cordova.js
-define("cordova", function(require, exports, module) {
-
-
-var channel = require('cordova/channel');
-
-/**
- * Listen for DOMContentLoaded and notify our channel subscribers.
- */
-document.addEventListener('DOMContentLoaded', function() {
- channel.onDOMContentLoaded.fire();
-}, false);
-if (document.readyState == 'complete' || document.readyState == 'interactive') {
- channel.onDOMContentLoaded.fire();
-}
-
-/**
- * Intercept calls to addEventListener + removeEventListener and handle deviceready,
- * resume, and pause events.
- */
-var m_document_addEventListener = document.addEventListener;
-var m_document_removeEventListener = document.removeEventListener;
-var m_window_addEventListener = window.addEventListener;
-var m_window_removeEventListener = window.removeEventListener;
-
-/**
- * Houses custom event handlers to intercept on document + window event listeners.
- */
-var documentEventHandlers = {},
- windowEventHandlers = {};
-
-document.addEventListener = function(evt, handler, capture) {
- var e = evt.toLowerCase();
- if (typeof documentEventHandlers[e] != 'undefined') {
- documentEventHandlers[e].subscribe(handler);
- } else {
- m_document_addEventListener.call(document, evt, handler, capture);
- }
-};
-
-window.addEventListener = function(evt, handler, capture) {
- var e = evt.toLowerCase();
- if (typeof windowEventHandlers[e] != 'undefined') {
- windowEventHandlers[e].subscribe(handler);
- } else {
- m_window_addEventListener.call(window, evt, handler, capture);
- }
-};
-
-document.removeEventListener = function(evt, handler, capture) {
- var e = evt.toLowerCase();
- // If unsubscribing from an event that is handled by a plugin
- if (typeof documentEventHandlers[e] != "undefined") {
- documentEventHandlers[e].unsubscribe(handler);
- } else {
- m_document_removeEventListener.call(document, evt, handler, capture);
- }
-};
-
-window.removeEventListener = function(evt, handler, capture) {
- var e = evt.toLowerCase();
- // If unsubscribing from an event that is handled by a plugin
- if (typeof windowEventHandlers[e] != "undefined") {
- windowEventHandlers[e].unsubscribe(handler);
- } else {
- m_window_removeEventListener.call(window, evt, handler, capture);
- }
-};
-
-function createEvent(type, data) {
- var event = document.createEvent('Events');
- event.initEvent(type, false, false);
- if (data) {
- for (var i in data) {
- if (data.hasOwnProperty(i)) {
- event[i] = data[i];
- }
- }
- }
- return event;
-}
-
-if(typeof window.console === "undefined") {
- window.console = {
- log:function(){}
- };
-}
-
-var cordova = {
- define:define,
- require:require,
- /**
- * Methods to add/remove your own addEventListener hijacking on document + window.
- */
- addWindowEventHandler:function(event) {
- return (windowEventHandlers[event] = channel.create(event));
- },
- addStickyDocumentEventHandler:function(event) {
- return (documentEventHandlers[event] = channel.createSticky(event));
- },
- addDocumentEventHandler:function(event) {
- return (documentEventHandlers[event] = channel.create(event));
- },
- removeWindowEventHandler:function(event) {
- delete windowEventHandlers[event];
- },
- removeDocumentEventHandler:function(event) {
- delete documentEventHandlers[event];
- },
- /**
- * Retrieve original event handlers that were replaced by Cordova
- *
- * @return object
- */
- getOriginalHandlers: function() {
- return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},
- 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};
- },
- /**
- * Method to fire event from native code
- * bNoDetach is required for events which cause an exception which needs to be caught in native code
- */
- fireDocumentEvent: function(type, data, bNoDetach) {
- var evt = createEvent(type, data);
- if (typeof documentEventHandlers[type] != 'undefined') {
- if( bNoDetach ) {
- documentEventHandlers[type].fire(evt);
- }
- else {
- setTimeout(function() {
- // Fire deviceready on listeners that were registered before cordova.js was loaded.
- if (type == 'deviceready') {
- document.dispatchEvent(evt);
- }
- documentEventHandlers[type].fire(evt);
- }, 0);
- }
- } else {
- document.dispatchEvent(evt);
- }
- },
- fireWindowEvent: function(type, data) {
- var evt = createEvent(type,data);
- if (typeof windowEventHandlers[type] != 'undefined') {
- setTimeout(function() {
- windowEventHandlers[type].fire(evt);
- }, 0);
- } else {
- window.dispatchEvent(evt);
- }
- },
-
- /**
- * Plugin callback mechanism.
- */
- // Randomize the starting callbackId to avoid collisions after refreshing or navigating.
- // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.
- callbackId: Math.floor(Math.random() * 2000000000),
- callbacks: {},
- callbackStatus: {
- NO_RESULT: 0,
- OK: 1,
- CLASS_NOT_FOUND_EXCEPTION: 2,
- ILLEGAL_ACCESS_EXCEPTION: 3,
- INSTANTIATION_EXCEPTION: 4,
- MALFORMED_URL_EXCEPTION: 5,
- IO_EXCEPTION: 6,
- INVALID_ACTION: 7,
- JSON_EXCEPTION: 8,
- ERROR: 9
- },
-
- /**
- * Called by native code when returning successful result from an action.
- */
- callbackSuccess: function(callbackId, args) {
- try {
- cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
- } catch (e) {
- console.log("Error in error callback: " + callbackId + " = "+e);
- }
- },
-
- /**
- * Called by native code when returning error result from an action.
- */
- callbackError: function(callbackId, args) {
- // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
- // Derive success from status.
- try {
- cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
- } catch (e) {
- console.log("Error in error callback: " + callbackId + " = "+e);
- }
- },
-
- /**
- * Called by native code when returning the result from an action.
- */
- callbackFromNative: function(callbackId, success, status, args, keepCallback) {
- var callback = cordova.callbacks[callbackId];
- if (callback) {
- if (success && status == cordova.callbackStatus.OK) {
- callback.success && callback.success.apply(null, args);
- } else if (!success) {
- callback.fail && callback.fail.apply(null, args);
- }
-
- // Clear callback if not expecting any more results
- if (!keepCallback) {
- delete cordova.callbacks[callbackId];
- }
- }
- },
- addConstructor: function(func) {
- channel.onCordovaReady.subscribe(function() {
- try {
- func();
- } catch(e) {
- console.log("Failed to run constructor: " + e);
- }
- });
- }
-};
-
-// Register pause, resume and deviceready channels as events on document.
-channel.onPause = cordova.addDocumentEventHandler('pause');
-channel.onResume = cordova.addDocumentEventHandler('resume');
-channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');
-
-module.exports = cordova;
-
-});
-
-// file: lib/common/argscheck.js
-define("cordova/argscheck", function(require, exports, module) {
-
-var exec = require('cordova/exec');
-var utils = require('cordova/utils');
-
-var moduleExports = module.exports;
-
-var typeMap = {
- 'A': 'Array',
- 'D': 'Date',
- 'N': 'Number',
- 'S': 'String',
- 'F': 'Function',
- 'O': 'Object'
-};
-
-function extractParamName(callee, argIndex) {
- return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex];
-}
-
-function checkArgs(spec, functionName, args, opt_callee) {
- if (!moduleExports.enableChecks) {
- return;
- }
- var errMsg = null;
- var typeName;
- for (var i = 0; i < spec.length; ++i) {
- var c = spec.charAt(i),
- cUpper = c.toUpperCase(),
- arg = args[i];
- // Asterix means allow anything.
- if (c == '*') {
- continue;
- }
- typeName = utils.typeName(arg);
- if ((arg === null || arg === undefined) && c == cUpper) {
- continue;
- }
- if (typeName != typeMap[cUpper]) {
- errMsg = 'Expected ' + typeMap[cUpper];
- break;
- }
- }
- if (errMsg) {
- errMsg += ', but got ' + typeName + '.';
- errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;
- // Don't log when running jake test.
- if (typeof jasmine == 'undefined') {
- console.error(errMsg);
- }
- throw TypeError(errMsg);
- }
-}
-
-function getValue(value, defaultValue) {
- return value === undefined ? defaultValue : value;
-}
-
-moduleExports.checkArgs = checkArgs;
-moduleExports.getValue = getValue;
-moduleExports.enableChecks = true;
-
-
-});
-
-// file: lib/common/builder.js
-define("cordova/builder", function(require, exports, module) {
-
-var utils = require('cordova/utils');
-
-function each(objects, func, context) {
- for (var prop in objects) {
- if (objects.hasOwnProperty(prop)) {
- func.apply(context, [objects[prop], prop]);
- }
- }
-}
-
-function clobber(obj, key, value) {
- exports.replaceHookForTesting(obj, key);
- obj[key] = value;
- // Getters can only be overridden by getters.
- if (obj[key] !== value) {
- utils.defineGetter(obj, key, function() {
- return value;
- });
- }
-}
-
-function assignOrWrapInDeprecateGetter(obj, key, value, message) {
- if (message) {
- utils.defineGetter(obj, key, function() {
- console.log(message);
- delete obj[key];
- clobber(obj, key, value);
- return value;
- });
- } else {
- clobber(obj, key, value);
- }
-}
-
-function include(parent, objects, clobber, merge) {
- each(objects, function (obj, key) {
- try {
- var result = obj.path ? require(obj.path) : {};
-
- if (clobber) {
- // Clobber if it doesn't exist.
- if (typeof parent[key] === 'undefined') {
- assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
- } else if (typeof obj.path !== 'undefined') {
- // If merging, merge properties onto parent, otherwise, clobber.
- if (merge) {
- recursiveMerge(parent[key], result);
- } else {
- assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
- }
- }
- result = parent[key];
- } else {
- // Overwrite if not currently defined.
- if (typeof parent[key] == 'undefined') {
- assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
- } else {
- // Set result to what already exists, so we can build children into it if they exist.
- result = parent[key];
- }
- }
-
- if (obj.children) {
- include(result, obj.children, clobber, merge);
- }
- } catch(e) {
- utils.alert('Exception building cordova JS globals: ' + e + ' for key "' + key + '"');
- }
- });
-}
-
-/**
- * Merge properties from one object onto another recursively. Properties from
- * the src object will overwrite existing target property.
- *
- * @param target Object to merge properties into.
- * @param src Object to merge properties from.
- */
-function recursiveMerge(target, src) {
- for (var prop in src) {
- if (src.hasOwnProperty(prop)) {
- if (target.prototype && target.prototype.constructor === target) {
- // If the target object is a constructor override off prototype.
- clobber(target.prototype, prop, src[prop]);
- } else {
- if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
- recursiveMerge(target[prop], src[prop]);
- } else {
- clobber(target, prop, src[prop]);
- }
- }
- }
- }
-}
-
-exports.buildIntoButDoNotClobber = function(objects, target) {
- include(target, objects, false, false);
-};
-exports.buildIntoAndClobber = function(objects, target) {
- include(target, objects, true, false);
-};
-exports.buildIntoAndMerge = function(objects, target) {
- include(target, objects, true, true);
-};
-exports.recursiveMerge = recursiveMerge;
-exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;
-exports.replaceHookForTesting = function() {};
-
-});
-
-// file: lib/common/channel.js
-define("cordova/channel", function(require, exports, module) {
-
-var utils = require('cordova/utils'),
- nextGuid = 1;
-
-/**
- * Custom pub-sub "channel" that can have functions subscribed to it
- * This object is used to define and control firing of events for
- * cordova initialization, as well as for custom events thereafter.
- *
- * The order of events during page load and Cordova startup is as follows:
- *
- * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.
- * onNativeReady* Internal event that indicates the Cordova native side is ready.
- * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.
- * onCordovaInfoReady* Internal event fired when device properties are available.
- * onCordovaConnectionReady* Internal event fired when the connection property has been set.
- * onDeviceReady* User event fired to indicate that Cordova is ready
- * onResume User event fired to indicate a start/resume lifecycle event
- * onPause User event fired to indicate a pause lifecycle event
- * onDestroy* Internal event fired when app is being destroyed (User should use window.onunload event, not this one).
- *
- * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.
- * All listeners that subscribe after the event is fired will be executed right away.
- *
- * The only Cordova events that user code should register for are:
- * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript
- * pause App has moved to background
- * resume App has returned to foreground
- *
- * Listeners can be registered as:
- * document.addEventListener("deviceready", myDeviceReadyListener, false);
- * document.addEventListener("resume", myResumeListener, false);
- * document.addEventListener("pause", myPauseListener, false);
- *
- * The DOM lifecycle events should be used for saving and restoring state
- * window.onload
- * window.onunload
- *
- */
-
-/**
- * Channel
- * @constructor
- * @param type String the channel name
- */
-var Channel = function(type, sticky) {
- this.type = type;
- // Map of guid -> function.
- this.handlers = {};
- // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
- this.state = sticky ? 1 : 0;
- // Used in sticky mode to remember args passed to fire().
- this.fireArgs = null;
- // Used by onHasSubscribersChange to know if there are any listeners.
- this.numHandlers = 0;
- // Function that is called when the first listener is subscribed, or when
- // the last listener is unsubscribed.
- this.onHasSubscribersChange = null;
-},
- channel = {
- /**
- * Calls the provided function only after all of the channels specified
- * have been fired. All channels must be sticky channels.
- */
- join: function(h, c) {
- var len = c.length,
- i = len,
- f = function() {
- if (!(--i)) h();
- };
- for (var j=0; j<len; j++) {
- if (c[j].state === 0) {
- throw Error('Can only use join with sticky channels.');
- }
- c[j].subscribe(f);
- }
- if (!len) h();
- },
- create: function(type) {
- return channel[type] = new Channel(type, false);
- },
- createSticky: function(type) {
- return channel[type] = new Channel(type, true);
- },
-
- /**
- * cordova Channels that must fire before "deviceready" is fired.
- */
- deviceReadyChannelsArray: [],
- deviceReadyChannelsMap: {},
-
- /**
- * Indicate that a feature needs to be initialized before it is ready to be used.
- * This holds up Cordova's "deviceready" event until the feature has been initialized
- * and Cordova.initComplete(feature) is called.
- *
- * @param feature {String} The unique feature name
- */
- waitForInitialization: function(feature) {
- if (feature) {
- var c = channel[feature] || this.createSticky(feature);
- this.deviceReadyChannelsMap[feature] = c;
- this.deviceReadyChannelsArray.push(c);
- }
- },
-
- /**
- * Indicate that initialization code has completed and the feature is ready to be used.
- *
- * @param feature {String} The unique feature name
- */
- initializationComplete: function(feature) {
- var c = this.deviceReadyChannelsMap[feature];
- if (c) {
- c.fire();
- }
- }
- };
-
-function forceFunction(f) {
- if (typeof f != 'function') throw "Function required as first argument!";
-}
-
-/**
- * Subscribes the given function to the channel. Any time that
- * Channel.fire is called so too will the function.
- * Optionally specify an execution context for the function
- * and a guid that can be used to stop subscribing to the channel.
- * Returns the guid.
- */
-Channel.prototype.subscribe = function(f, c) {
- // need a function to call
- forceFunction(f);
- if (this.state == 2) {
- f.apply(c || this, this.fireArgs);
- return;
- }
-
- var func = f,
- guid = f.observer_guid;
- if (typeof c == "object") { func = utils.close(c, f); }
-
- if (!guid) {
- // first time any channel has seen this subscriber
- guid = '' + nextGuid++;
- }
- func.observer_guid = guid;
- f.observer_guid = guid;
-
- // Don't add the same handler more than once.
- if (!this.handlers[guid]) {
- this.handlers[guid] = func;
- this.numHandlers++;
- if (this.numHandlers == 1) {
- this.onHasSubscribersChange && this.onHasSubscribersChange();
- }
- }
-};
-
-/**
- * Unsubscribes the function with the given guid from the channel.
- */
-Channel.prototype.unsubscribe = function(f) {
- // need a function to unsubscribe
- forceFunction(f);
-
- var guid = f.observer_guid,
- handler = this.handlers[guid];
- if (handler) {
- delete this.handlers[guid];
- this.numHandlers--;
- if (this.numHandlers === 0) {
- this.onHasSubscribersChange && this.onHasSubscribersChange();
- }
- }
-};
-
-/**
- * Calls all functions subscribed to this channel.
- */
-Channel.prototype.fire = function(e) {
- var fail = false,
- fireArgs = Array.prototype.slice.call(arguments);
- // Apply stickiness.
- if (this.state == 1) {
- this.state = 2;
- this.fireArgs = fireArgs;
- }
- if (this.numHandlers) {
- // Copy the values first so that it is safe to modify it from within
- // callbacks.
- var toCall = [];
- for (var item in this.handlers) {
- toCall.push(this.handlers[item]);
- }
- for (var i = 0; i < toCall.length; ++i) {
- toCall[i].apply(this, fireArgs);
- }
- if (this.state == 2 && this.numHandlers) {
- this.numHandlers = 0;
- this.handlers = {};
- this.onHasSubscribersChange && this.onHasSubscribersChange();
- }
- }
-};
-
-
-// defining them here so they are ready super fast!
-// DOM event that is received when the web page is loaded and parsed.
-channel.createSticky('onDOMContentLoaded');
-
-// Event to indicate the Cordova native side is ready.
-channel.createSticky('onNativeReady');
-
-// Event to indicate that all Cordova JavaScript objects have been created
-// and it's time to run plugin constructors.
-channel.createSticky('onCordovaReady');
-
-// Event to indicate that device properties are available
-channel.createSticky('onCordovaInfoReady');
-
-// Event to indicate that the connection property has been set.
-channel.createSticky('onCordovaConnectionReady');
-
-// Event to indicate that all automatically loaded JS plugins are loaded and ready.
-channel.createSticky('onPluginsReady');
-
-// Event to indicate that Cordova is ready
-channel.createSticky('onDeviceReady');
-
-// Event to indicate a resume lifecycle event
-channel.create('onResume');
-
-// Event to indicate a pause lifecycle event
-channel.create('onPause');
-
-// Event to indicate a destroy lifecycle event
-channel.createSticky('onDestroy');
-
-// Channels that must fire before "deviceready" is fired.
-channel.waitForInitialization('onCordovaReady');
-channel.waitForInitialization('onCordovaConnectionReady');
-channel.waitForInitialization('onDOMContentLoaded');
-
-module.exports = channel;
-
-});
-
-// file: lib/common/commandProxy.js
-define("cordova/commandProxy", function(require, exports, module) {
-
-
-// internal map of proxy function
-var CommandProxyMap = {};
-
-module.exports = {
-
- // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);
- add:function(id,proxyObj) {
- console.log("adding proxy for " + id);
- CommandProxyMap[id] = proxyObj;
- return proxyObj;
- },
-
- // cordova.commandProxy.remove("Accelerometer");
- remove:function(id) {
- var proxy = CommandProxyMap[id];
- delete CommandProxyMap[id];
- CommandProxyMap[id] = null;
- return proxy;
- },
-
- get:function(service,action) {
- return ( CommandProxyMap[service] ? CommandProxyMap[service][action] : null );
- }
-};
-});
-
-// file: lib/ios/exec.js
-define("cordova/exec", function(require, exports, module) {
-
-/**
- * Creates a gap bridge iframe used to notify the native code about queued
- * commands.
- *
- * @private
- */
-var cordova = require('cordova'),
- channel = require('cordova/channel'),
- utils = require('cordova/utils'),
- jsToNativeModes = {
- IFRAME_NAV: 0,
- XHR_NO_PAYLOAD: 1,
- XHR_WITH_PAYLOAD: 2,
- XHR_OPTIONAL_PAYLOAD: 3
- },
- bridgeMode,
- execIframe,
- execXhr,
- requestCount = 0,
- vcHeaderValue = null,
- commandQueue = [], // Contains pending JS->Native messages.
- isInContextOfEvalJs = 0;
-
-function createExecIframe() {
- var iframe = document.createElement("iframe");
- iframe.style.display = 'none';
- document.body.appendChild(iframe);
- return iframe;
-}
-
-function shouldBundleCommandJson() {
- if (bridgeMode == jsToNativeModes.XHR_WITH_PAYLOAD) {
- return true;
- }
- if (bridgeMode == jsToNativeModes.XHR_OPTIONAL_PAYLOAD) {
- var payloadLength = 0;
- for (var i = 0; i < commandQueue.length; ++i) {
- payloadLength += commandQueue[i].length;
- }
- // The value here was determined using the benchmark within CordovaLibApp on an iPad 3.
- return payloadLength < 4500;
- }
- return false;
-}
-
-function massageArgsJsToNative(args) {
- if (!args || utils.typeName(args) != 'Array') {
- return args;
- }
- var ret = [];
- var encodeArrayBufferAs8bitString = function(ab) {
- return String.fromCharCode.apply(null, new Uint8Array(ab));
- };
- var encodeArrayBufferAsBase64 = function(ab) {
- return window.btoa(encodeArrayBufferAs8bitString(ab));
- };
- args.forEach(function(arg, i) {
- if (utils.typeName(arg) == 'ArrayBuffer') {
- ret.push({
- 'CDVType': 'ArrayBuffer',
- 'data': encodeArrayBufferAsBase64(arg)
- });
- } else {
- ret.push(arg);
- }
- });
- return ret;
-}
-
-function massageMessageNativeToJs(message) {
- if (message.CDVType == 'ArrayBuffer') {
- var stringToArrayBuffer = function(str) {
- var ret = new Uint8Array(str.length);
- for (var i = 0; i < str.length; i++) {
- ret[i] = str.charCodeAt(i);
- }
- return ret.buffer;
- };
- var base64ToArrayBuffer = function(b64) {
- return stringToArrayBuffer(atob(b64));
- };
- message = base64ToArrayBuffer(message.data);
- }
- return message;
-}
-
-function convertMessageToArgsNativeToJs(message) {
- var args = [];
- if (!message || !message.hasOwnProperty('CDVType')) {
- args.push(message);
- } else if (message.CDVType == 'MultiPart') {
- message.messages.forEach(function(e) {
- args.push(massageMessageNativeToJs(e));
- });
- } else {
- args.push(massageMessageNativeToJs(message));
- }
- return args;
-}
-
-function iOSExec() {
- // XHR mode does not work on iOS 4.2, so default to IFRAME_NAV for such devices.
- // XHR mode's main advantage is working around a bug in -webkit-scroll, which
- // doesn't exist in 4.X devices anyways.
- if (bridgeMode === undefined) {
- bridgeMode = navigator.userAgent.indexOf(' 4_') == -1 ? jsToNativeModes.XHR_NO_PAYLOAD : jsToNativeModes.IFRAME_NAV;
- }
-
- var successCallback, failCallback, service, action, actionArgs, splitCommand;
- var callbackId = null;
- if (typeof arguments[0] !== "string") {
- // FORMAT ONE
- successCallback = arguments[0];
- failCallback = arguments[1];
- service = arguments[2];
- action = arguments[3];
- actionArgs = arguments[4];
-
- // Since we need to maintain backwards compatibility, we have to pass
- // an invalid callbackId even if no callback was provided since plugins
- // will be expecting it. The Cordova.exec() implementation allocates
- // an invalid callbackId and passes it even if no callbacks were given.
- callbackId = 'INVALID';
- } else {
- // FORMAT TWO, REMOVED
- try {
- splitCommand = arguments[0].split(".");
- action = splitCommand.pop();
- service = splitCommand.join(".");
- actionArgs = Array.prototype.splice.call(arguments, 1);
-
- console.log('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' +
- "cordova.exec(null, null, \"" + service + "\", " + action + "\"," + JSON.stringify(actionArgs) + ");"
- );
- return;
- } catch (e) {
- }
- }
-
- // Register the callbacks and add the callbackId to the positional
- // arguments if given.
- if (successCallback || failCallback) {
- callbackId = service + cordova.callbackId++;
- cordova.callbacks[callbackId] =
- {success:successCallback, fail:failCallback};
- }
-
- actionArgs = massageArgsJsToNative(actionArgs);
-
- var command = [callbackId, service, action, actionArgs];
-
- // Stringify and queue the command. We stringify to command now to
- // effectively clone the command arguments in case they are mutated before
- // the command is executed.
- commandQueue.push(JSON.stringify(command));
-
- // If we're in the context of a stringByEvaluatingJavaScriptFromString call,
- // then the queue will be flushed when it returns; no need for a poke.
- // Also, if there is already a command in the queue, then we've already
- // poked the native side, so there is no reason to do so again.
- if (!isInContextOfEvalJs && commandQueue.length == 1) {
- if (bridgeMode != jsToNativeModes.IFRAME_NAV) {
- // This prevents sending an XHR when there is already one being sent.
- // This should happen only in rare circumstances (refer to unit tests).
- if (execXhr && execXhr.readyState != 4) {
- execXhr = null;
- }
- // Re-using the XHR improves exec() performance by about 10%.
- execXhr = execXhr || new XMLHttpRequest();
- // Changing this to a GET will make the XHR reach the URIProtocol on 4.2.
- // For some reason it still doesn't work though...
- // Add a timestamp to the query param to prevent caching.
- execXhr.open('HEAD', "/!gap_exec?" + (+new Date()), true);
- if (!vcHeaderValue) {
- vcHeaderValue = /.*\((.*)\)/.exec(navigator.userAgent)[1];
- }
- execXhr.setRequestHeader('vc', vcHeaderValue);
- execXhr.setRequestHeader('rc', ++requestCount);
- if (shouldBundleCommandJson()) {
- execXhr.setRequestHeader('cmds', iOSExec.nativeFetchMessages());
- }
- execXhr.send(null);
- } else {
- execIframe = execIframe || createExecIframe();
- execIframe.src = "gap://ready";
- }
- }
-}
-
-iOSExec.jsToNativeModes = jsToNativeModes;
-
-iOSExec.setJsToNativeBridgeMode = function(mode) {
- // Remove the iFrame since it may be no longer required, and its existence
- // can trigger browser bugs.
- // https://issues.apache.org/jira/browse/CB-593
- if (execIframe) {
- execIframe.parentNode.removeChild(execIframe);
- execIframe = null;
- }
- bridgeMode = mode;
-};
-
-iOSExec.nativeFetchMessages = function() {
- // Each entry in commandQueue is a JSON string already.
- if (!commandQueue.length) {
- return '';
- }
- var json = '[' + commandQueue.join(',') + ']';
- commandQueue.length = 0;
- return json;
-};
-
-iOSExec.nativeCallback = function(callbackId, status, message, keepCallback) {
- return iOSExec.nativeEvalAndFetch(function() {
- var success = status === 0 || status === 1;
- var args = convertMessageToArgsNativeToJs(message);
- cordova.callbackFromNative(callbackId, success, status, args, keepCallback);
- });
-};
-
-iOSExec.nativeEvalAndFetch = function(func) {
- // This shouldn't be nested, but better to be safe.
- isInContextOfEvalJs++;
- try {
- func();
- return iOSExec.nativeFetchMessages();
- } finally {
- isInContextOfEvalJs--;
- }
-};
-
-module.exports = iOSExec;
-
-});
-
-// file: lib/common/modulemapper.js
-define("cordova/modulemapper", function(require, exports, module) {
-
-var builder = require('cordova/builder'),
- moduleMap = define.moduleMap,
- symbolList,
- deprecationMap;
-
-exports.reset = function() {
- symbolList = [];
- deprecationMap = {};
-};
-
-function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) {
- if (!(moduleName in moduleMap)) {
- throw new Error('Module ' + moduleName + ' does not exist.');
- }
- symbolList.push(strategy, moduleName, symbolPath);
- if (opt_deprecationMessage) {
- deprecationMap[symbolPath] = opt_deprecationMessage;
- }
-}
-
-// Note: Android 2.3 does have Function.bind().
-exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) {
- addEntry('c', moduleName, symbolPath, opt_deprecationMessage);
-};
-
-exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) {
- addEntry('m', moduleName, symbolPath, opt_deprecationMessage);
-};
-
-exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) {
- addEntry('d', moduleName, symbolPath, opt_deprecationMessage);
-};
-
-function prepareNamespace(symbolPath, context) {
- if (!symbolPath) {
- return context;
- }
- var parts = symbolPath.split('.');
- var cur = context;
- for (var i = 0, part; part = parts[i]; ++i) {
- cur = cur[part] = cur[part] || {};
- }
- return cur;
-}
-
-exports.mapModules = function(context) {
- var origSymbols = {};
- context.CDV_origSymbols = origSymbols;
- for (var i = 0, len = symbolList.length; i < len; i += 3) {
- var strategy = symbolList[i];
- var moduleName = symbolList[i + 1];
- var symbolPath = symbolList[i + 2];
- var lastDot = symbolPath.lastIndexOf('.');
- var namespace = symbolPath.substr(0, lastDot);
- var lastName = symbolPath.substr(lastDot + 1);
-
- var module = require(moduleName);
- var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;
- var parentObj = prepareNamespace(namespace, context);
- var target = parentObj[lastName];
-
- if (strategy == 'm' && target) {
- builder.recursiveMerge(target, module);
- } else if ((strategy == 'd' && !target) || (strategy != 'd')) {
- if (!(symbolPath in origSymbols)) {
- origSymbols[symbolPath] = target;
- }
- builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);
- }
- }
-};
-
-exports.getOriginalSymbol = function(context, symbolPath) {
- var origSymbols = context.CDV_origSymbols;
- if (origSymbols && (symbolPath in origSymbols)) {
- return origSymbols[symbolPath];
- }
- var parts = symbolPath.split('.');
- var obj = context;
- for (var i = 0; i < parts.length; ++i) {
- obj = obj && obj[parts[i]];
- }
- return obj;
-};
-
-exports.loadMatchingModules = function(matchingRegExp) {
- for (var k in moduleMap) {
- if (matchingRegExp.exec(k)) {
- require(k);
- }
- }
-};
-
-exports.reset();
-
-
-});
-
-// file: lib/ios/platform.js
-define("cordova/platform", function(require, exports, module) {
-
-module.exports = {
- id: "ios",
- initialize:function() {
- var modulemapper = require('cordova/modulemapper');
-
- modulemapper.loadMatchingModules(/cordova.*\/plugininit$/);
-
- modulemapper.loadMatchingModules(/cordova.*\/symbols$/);
- modulemapper.mapModules(window);
- }
-};
-
-
-});
-
-// file: lib/common/plugin/Acceleration.js
-define("cordova/plugin/Acceleration", function(require, exports, module) {
-
-var Acceleration = function(x, y, z, timestamp) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.timestamp = timestamp || (new Date()).getTime();
-};
-
-module.exports = Acceleration;
-
-});
-
-// file: lib/common/plugin/Camera.js
-define("cordova/plugin/Camera", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- exec = require('cordova/exec'),
- Camera = require('cordova/plugin/CameraConstants'),
- CameraPopoverHandle = require('cordova/plugin/CameraPopoverHandle');
-
-var cameraExport = {};
-
-// Tack on the Camera Constants to the base camera plugin.
-for (var key in Camera) {
- cameraExport[key] = Camera[key];
-}
-
-/**
- * Gets a picture from source defined by "options.sourceType", and returns the
- * image as defined by the "options.destinationType" option.
-
- * The defaults are sourceType=CAMERA and destinationType=FILE_URI.
- *
- * @param {Function} successCallback
- * @param {Function} errorCallback
- * @param {Object} options
- */
-cameraExport.getPicture = function(successCallback, errorCallback, options) {
- argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);
- options = options || {};
- var getValue = argscheck.getValue;
-
- var quality = getValue(options.quality, 50);
- var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);
- var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);
- var targetWidth = getValue(options.targetWidth, -1);
- var targetHeight = getValue(options.targetHeight, -1);
- var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);
- var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);
- var allowEdit = !!options.allowEdit;
- var correctOrientation = !!options.correctOrientation;
- var saveToPhotoAlbum = !!options.saveToPhotoAlbum;
- var popoverOptions = getValue(options.popoverOptions, null);
- var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
-
- var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,
- mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];
-
- exec(successCallback, errorCallback, "Camera", "takePicture", args);
- return new CameraPopoverHandle();
-};
-
-cameraExport.cleanup = function(successCallback, errorCallback) {
- exec(successCallback, errorCallback, "Camera", "cleanup", []);
-};
-
-module.exports = cameraExport;
-
-});
-
-// file: lib/common/plugin/CameraConstants.js
-define("cordova/plugin/CameraConstants", function(require, exports, module) {
-
-module.exports = {
- DestinationType:{
- DATA_URL: 0, // Return base64 encoded string
- FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
- NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
- },
- EncodingType:{
- JPEG: 0, // Return JPEG encoded image
- PNG: 1 // Return PNG encoded image
- },
- MediaType:{
- PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
- VIDEO: 1, // allow selection of video only, ONLY RETURNS URL
- ALLMEDIA : 2 // allow selection from all media types
- },
- PictureSourceType:{
- PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
- CAMERA : 1, // Take picture from camera
- SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
- },
- PopoverArrowDirection:{
- ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants to specify arrow location on popover
- ARROW_DOWN : 2,
- ARROW_LEFT : 4,
- ARROW_RIGHT : 8,
- ARROW_ANY : 15
- },
- Direction:{
- BACK: 0,
- FRONT: 1
- }
-};
-
-});
-
-// file: lib/ios/plugin/CameraPopoverHandle.js
-define("cordova/plugin/CameraPopoverHandle", function(require, exports, module) {
-
-var exec = require('cordova/exec');
-
-/**
- * A handle to an image picker popover.
- */
-var CameraPopoverHandle = function() {
- this.setPosition = function(popoverOptions) {
- var args = [ popoverOptions ];
- exec(null, null, "Camera", "repositionPopover", args);
- };
-};
-
-module.exports = CameraPopoverHandle;
-
-});
-
-// file: lib/common/plugin/CameraPopoverOptions.js
-define("cordova/plugin/CameraPopoverOptions", function(require, exports, module) {
-
-var Camera = require('cordova/plugin/CameraConstants');
-
-/**
- * Encapsulates options for iOS Popover image picker
- */
-var CameraPopoverOptions = function(x,y,width,height,arrowDir){
- // information of rectangle that popover should be anchored to
- this.x = x || 0;
- this.y = y || 32;
- this.width = width || 320;
- this.height = height || 480;
- // The direction of the popover arrow
- this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY;
-};
-
-module.exports = CameraPopoverOptions;
-
-});
-
-// file: lib/common/plugin/CaptureAudioOptions.js
-define("cordova/plugin/CaptureAudioOptions", function(require, exports, module) {
-
-/**
- * Encapsulates all audio capture operation configuration options.
- */
-var CaptureAudioOptions = function(){
- // Upper limit of sound clips user can record. Value must be equal or greater than 1.
- this.limit = 1;
- // Maximum duration of a single sound clip in seconds.
- this.duration = 0;
- // The selected audio mode. Must match with one of the elements in supportedAudioModes array.
- this.mode = null;
-};
-
-module.exports = CaptureAudioOptions;
-
-});
-
-// file: lib/common/plugin/CaptureError.js
-define("cordova/plugin/CaptureError", function(require, exports, module) {
-
-/**
- * The CaptureError interface encapsulates all errors in the Capture API.
- */
-var CaptureError = function(c) {
- this.code = c || null;
-};
-
-// Camera or microphone failed to capture image or sound.
-CaptureError.CAPTURE_INTERNAL_ERR = 0;
-// Camera application or audio capture application is currently serving other capture request.
-CaptureError.CAPTURE_APPLICATION_BUSY = 1;
-// Invalid use of the API (e.g. limit parameter has value less than one).
-CaptureError.CAPTURE_INVALID_ARGUMENT = 2;
-// User exited camera application or audio capture application before capturing anything.
-CaptureError.CAPTURE_NO_MEDIA_FILES = 3;
-// The requested capture operation is not supported.
-CaptureError.CAPTURE_NOT_SUPPORTED = 20;
-
-module.exports = CaptureError;
-
-});
-
-// file: lib/common/plugin/CaptureImageOptions.js
-define("cordova/plugin/CaptureImageOptions", function(require, exports, module) {
-
-/**
- * Encapsulates all image capture operation configuration options.
- */
-var CaptureImageOptions = function(){
- // Upper limit of images user can take. Value must be equal or greater than 1.
- this.limit = 1;
- // The selected image mode. Must match with one of the elements in supportedImageModes array.
- this.mode = null;
-};
-
-module.exports = CaptureImageOptions;
-
-});
-
-// file: lib/common/plugin/CaptureVideoOptions.js
-define("cordova/plugin/CaptureVideoOptions", function(require, exports, module) {
-
-/**
- * Encapsulates all video capture operation configuration options.
- */
-var CaptureVideoOptions = function(){
- // Upper limit of videos user can record. Value must be equal or greater than 1.
- this.limit = 1;
- // Maximum duration of a single video clip in seconds.
- this.duration = 0;
- // The selected video mode. Must match with one of the elements in supportedVideoModes array.
- this.mode = null;
-};
-
-module.exports = CaptureVideoOptions;
-
-});
-
-// file: lib/common/plugin/CompassError.js
-define("cordova/plugin/CompassError", function(require, exports, module) {
-
-/**
- * CompassError.
- * An error code assigned by an implementation when an error has occurred
- * @constructor
- */
-var CompassError = function(err) {
- this.code = (err !== undefined ? err : null);
-};
-
-CompassError.COMPASS_INTERNAL_ERR = 0;
-CompassError.COMPASS_NOT_SUPPORTED = 20;
-
-module.exports = CompassError;
-
-});
-
-// file: lib/common/plugin/CompassHeading.js
-define("cordova/plugin/CompassHeading", function(require, exports, module) {
-
-var CompassHeading = function(magneticHeading, trueHeading, headingAccuracy, timestamp) {
- this.magneticHeading = magneticHeading;
- this.trueHeading = trueHeading;
- this.headingAccuracy = headingAccuracy;
- this.timestamp = timestamp || new Date().getTime();
-};
-
-module.exports = CompassHeading;
-
-});
-
-// file: lib/common/plugin/ConfigurationData.js
-define("cordova/plugin/ConfigurationData", function(require, exports, module) {
-
-/**
- * Encapsulates a set of parameters that the capture device supports.
- */
-function ConfigurationData() {
- // The ASCII-encoded string in lower case representing the media type.
- this.type = null;
- // The height attribute represents height of the image or video in pixels.
- // In the case of a sound clip this attribute has value 0.
- this.height = 0;
- // The width attribute represents width of the image or video in pixels.
- // In the case of a sound clip this attribute has value 0
- this.width = 0;
-}
-
-module.exports = ConfigurationData;
-
-});
-
-// file: lib/common/plugin/Connection.js
-define("cordova/plugin/Connection", function(require, exports, module) {
-
-/**
- * Network status
- */
-module.exports = {
- UNKNOWN: "unknown",
- ETHERNET: "ethernet",
- WIFI: "wifi",
- CELL_2G: "2g",
- CELL_3G: "3g",
- CELL_4G: "4g",
- CELL:"cellular",
- NONE: "none"
-};
-
-});
-
-// file: lib/common/plugin/Contact.js
-define("cordova/plugin/Contact", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- exec = require('cordova/exec'),
- ContactError = require('cordova/plugin/ContactError'),
- utils = require('cordova/utils');
-
-/**
-* Converts primitives into Complex Object
-* Currently only used for Date fields
-*/
-function convertIn(contact) {
- var value = contact.birthday;
- try {
- contact.birthday = new Date(parseFloat(value));
- } catch (exception){
- console.log("Cordova Contact convertIn error: exception creating date.");
- }
- return contact;
-}
-
-/**
-* Converts Complex objects into primitives
-* Only conversion at present is for Dates.
-**/
-
-function convertOut(contact) {
- var value = contact.birthday;
- if (value !== null) {
- // try to make it a Date object if it is not already
- if (!utils.isDate(value)){
- try {
- value = new Date(value);
- } catch(exception){
- value = null;
- }
- }
- if (utils.isDate(value)){
- value = value.valueOf(); // convert to milliseconds
- }
- contact.birthday = value;
- }
- return contact;
-}
-
-/**
-* Contains information about a single contact.
-* @constructor
-* @param {DOMString} id unique identifier
-* @param {DOMString} displayName
-* @param {ContactName} name
-* @param {DOMString} nickname
-* @param {Array.<ContactField>} phoneNumbers array of phone numbers
-* @param {Array.<ContactField>} emails array of email addresses
-* @param {Array.<ContactAddress>} addresses array of addresses
-* @param {Array.<ContactField>} ims instant messaging user ids
-* @param {Array.<ContactOrganization>} organizations
-* @param {DOMString} birthday contact's birthday
-* @param {DOMString} note user notes about contact
-* @param {Array.<ContactField>} photos
-* @param {Array.<ContactField>} categories
-* @param {Array.<ContactField>} urls contact's web sites
-*/
-var Contact = function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
- ims, organizations, birthday, note, photos, categories, urls) {
- this.id = id || null;
- this.rawId = null;
- this.displayName = displayName || null;
- this.name = name || null; // ContactName
- this.nickname = nickname || null;
- this.phoneNumbers = phoneNumbers || null; // ContactField[]
- this.emails = emails || null; // ContactField[]
- this.addresses = addresses || null; // ContactAddress[]
- this.ims = ims || null; // ContactField[]
- this.organizations = organizations || null; // ContactOrganization[]
- this.birthday = birthday || null;
- this.note = note || null;
- this.photos = photos || null; // ContactField[]
- this.categories = categories || null; // ContactField[]
- this.urls = urls || null; // ContactField[]
-};
-
-/**
-* Removes contact from device storage.
-* @param successCB success callback
-* @param errorCB error callback
-*/
-Contact.prototype.remove = function(successCB, errorCB) {
- argscheck.checkArgs('FF', 'Contact.remove', arguments);
- var fail = errorCB && function(code) {
- errorCB(new ContactError(code));
- };
- if (this.id === null) {
- fail(ContactError.UNKNOWN_ERROR);
- }
- else {
- exec(successCB, fail, "Contacts", "remove", [this.id]);
- }
-};
-
-/**
-* Creates a deep copy of this Contact.
-* With the contact ID set to null.
-* @return copy of this Contact
-*/
-Contact.prototype.clone = function() {
- var clonedContact = utils.clone(this);
- clonedContact.id = null;
- clonedContact.rawId = null;
-
- function nullIds(arr) {
- if (arr) {
- for (var i = 0; i < arr.length; ++i) {
- arr[i].id = null;
- }
- }
- }
-
- // Loop through and clear out any id's in phones, emails, etc.
- nullIds(clonedContact.phoneNumbers);
- nullIds(clonedContact.emails);
- nullIds(clonedContact.addresses);
- nullIds(clonedContact.ims);
- nullIds(clonedContact.organizations);
- nullIds(clonedContact.categories);
- nullIds(clonedContact.photos);
- nullIds(clonedContact.urls);
- return clonedContact;
-};
-
-/**
-* Persists contact to device storage.
-* @param successCB success callback
-* @param errorCB error callback
-*/
-Contact.prototype.save = function(successCB, errorCB) {
- argscheck.checkArgs('FFO', 'Contact.save', arguments);
- var fail = errorCB && function(code) {
- errorCB(new ContactError(code));
- };
- var success = function(result) {
- if (result) {
- if (successCB) {
- var fullContact = require('cordova/plugin/contacts').create(result);
- successCB(convertIn(fullContact));
- }
- }
- else {
- // no Entry object returned
- fail(ContactError.UNKNOWN_ERROR);
- }
- };
- var dupContact = convertOut(utils.clone(this));
- exec(success, fail, "Contacts", "save", [dupContact]);
-};
-
-
-module.exports = Contact;
-
-});
-
-// file: lib/common/plugin/ContactAddress.js
-define("cordova/plugin/ContactAddress", function(require, exports, module) {
-
-/**
-* Contact address.
-* @constructor
-* @param {DOMString} id unique identifier, should only be set by native code
-* @param formatted // NOTE: not a W3C standard
-* @param streetAddress
-* @param locality
-* @param region
-* @param postalCode
-* @param country
-*/
-
-var ContactAddress = function(pref, type, formatted, streetAddress, locality, region, postalCode, country) {
- this.id = null;
- this.pref = (typeof pref != 'undefined' ? pref : false);
- this.type = type || null;
- this.formatted = formatted || null;
- this.streetAddress = streetAddress || null;
- this.locality = locality || null;
- this.region = region || null;
- this.postalCode = postalCode || null;
- this.country = country || null;
-};
-
-module.exports = ContactAddress;
-
-});
-
-// file: lib/common/plugin/ContactError.js
-define("cordova/plugin/ContactError", function(require, exports, module) {
-
-/**
- * ContactError.
- * An error code assigned by an implementation when an error has occurred
- * @constructor
- */
-var ContactError = function(err) {
- this.code = (typeof err != 'undefined' ? err : null);
-};
-
-/**
- * Error codes
- */
-ContactError.UNKNOWN_ERROR = 0;
-ContactError.INVALID_ARGUMENT_ERROR = 1;
-ContactError.TIMEOUT_ERROR = 2;
-ContactError.PENDING_OPERATION_ERROR = 3;
-ContactError.IO_ERROR = 4;
-ContactError.NOT_SUPPORTED_ERROR = 5;
-ContactError.PERMISSION_DENIED_ERROR = 20;
-
-module.exports = ContactError;
-
-});
-
-// file: lib/common/plugin/ContactField.js
-define("cordova/plugin/ContactField", function(require, exports, module) {
-
-/**
-* Generic contact field.
-* @constructor
-* @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard
-* @param type
-* @param value
-* @param pref
-*/
-var ContactField = function(type, value, pref) {
- this.id = null;
- this.type = (type && type.toString()) || null;
- this.value = (value && value.toString()) || null;
- this.pref = (typeof pref != 'undefined' ? pref : false);
-};
-
-module.exports = ContactField;
-
-});
-
-// file: lib/common/plugin/ContactFindOptions.js
-define("cordova/plugin/ContactFindOptions", function(require, exports, module) {
-
-/**
- * ContactFindOptions.
- * @constructor
- * @param filter used to match contacts against
- * @param multiple boolean used to determine if more than one contact should be returned
- */
-
-var ContactFindOptions = function(filter, multiple) {
- this.filter = filter || '';
- this.multiple = (typeof multiple != 'undefined' ? multiple : false);
-};
-
-module.exports = ContactFindOptions;
-
-});
-
-// file: lib/common/plugin/ContactName.js
-define("cordova/plugin/ContactName", function(require, exports, module) {
-
-/**
-* Contact name.
-* @constructor
-* @param formatted // NOTE: not part of W3C standard
-* @param familyName
-* @param givenName
-* @param middle
-* @param prefix
-* @param suffix
-*/
-var ContactName = function(formatted, familyName, givenName, middle, prefix, suffix) {
- this.formatted = formatted || null;
- this.familyName = familyName || null;
- this.givenName = givenName || null;
- this.middleName = middle || null;
- this.honorificPrefix = prefix || null;
- this.honorificSuffix = suffix || null;
-};
-
-module.exports = ContactName;
-
-});
-
-// file: lib/common/plugin/ContactOrganization.js
-define("cordova/plugin/ContactOrganization", function(require, exports, module) {
-
-/**
-* Contact organization.
-* @constructor
-* @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard
-* @param name
-* @param dept
-* @param title
-* @param startDate
-* @param endDate
-* @param location
-* @param desc
-*/
-
-var ContactOrganization = function(pref, type, name, dept, title) {
- this.id = null;
- this.pref = (typeof pref != 'undefined' ? pref : false);
- this.type = type || null;
- this.name = name || null;
- this.department = dept || null;
- this.title = title || null;
-};
-
-module.exports = ContactOrganization;
-
-});
-
-// file: lib/common/plugin/Coordinates.js
-define("cordova/plugin/Coordinates", function(require, exports, module) {
-
-/**
- * This class contains position information.
- * @param {Object} lat
- * @param {Object} lng
- * @param {Object} alt
- * @param {Object} acc
- * @param {Object} head
- * @param {Object} vel
- * @param {Object} altacc
- * @constructor
- */
-var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
- /**
- * The latitude of the position.
- */
- this.latitude = lat;
- /**
- * The longitude of the position,
- */
- this.longitude = lng;
- /**
- * The accuracy of the position.
- */
- this.accuracy = acc;
- /**
- * The altitude of the position.
- */
- this.altitude = (alt !== undefined ? alt : null);
- /**
- * The direction the device is moving at the position.
- */
- this.heading = (head !== undefined ? head : null);
- /**
- * The velocity with which the device is moving at the position.
- */
- this.speed = (vel !== undefined ? vel : null);
-
- if (this.speed === 0 || this.speed === null) {
- this.heading = NaN;
- }
-
- /**
- * The altitude accuracy of the position.
- */
- this.altitudeAccuracy = (altacc !== undefined) ? altacc : null;
-};
-
-module.exports = Coordinates;
-
-});
-
-// file: lib/common/plugin/DirectoryEntry.js
-define("cordova/plugin/DirectoryEntry", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- utils = require('cordova/utils'),
- exec = require('cordova/exec'),
- Entry = require('cordova/plugin/Entry'),
- FileError = require('cordova/plugin/FileError'),
- DirectoryReader = require('cordova/plugin/DirectoryReader');
-
-/**
- * An interface representing a directory on the file system.
- *
- * {boolean} isFile always false (readonly)
- * {boolean} isDirectory always true (readonly)
- * {DOMString} name of the directory, excluding the path leading to it (readonly)
- * {DOMString} fullPath the absolute full path to the directory (readonly)
- * TODO: implement this!!! {FileSystem} filesystem on which the directory resides (readonly)
- */
-var DirectoryEntry = function(name, fullPath) {
- DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath);
-};
-
-utils.extend(DirectoryEntry, Entry);
-
-/**
- * Creates a new DirectoryReader to read entries from this directory
- */
-DirectoryEntry.prototype.createReader = function() {
- return new DirectoryReader(this.fullPath);
-};
-
-/**
- * Creates or looks up a directory
- *
- * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
- * @param {Flags} options to create or exclusively create the directory
- * @param {Function} successCallback is called with the new entry
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
- argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
- var win = successCallback && function(result) {
- var entry = new DirectoryEntry(result.name, result.fullPath);
- successCallback(entry);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getDirectory", [this.fullPath, path, options]);
-};
-
-/**
- * Deletes a directory and all of it's contents
- *
- * @param {Function} successCallback is called with no parameters
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(successCallback, fail, "File", "removeRecursively", [this.fullPath]);
-};
-
-/**
- * Creates or looks up a file
- *
- * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
- * @param {Flags} options to create or exclusively create the file
- * @param {Function} successCallback is called with the new entry
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
- argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
- var win = successCallback && function(result) {
- var FileEntry = require('cordova/plugin/FileEntry');
- var entry = new FileEntry(result.name, result.fullPath);
- successCallback(entry);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getFile", [this.fullPath, path, options]);
-};
-
-module.exports = DirectoryEntry;
-
-});
-
-// file: lib/common/plugin/DirectoryReader.js
-define("cordova/plugin/DirectoryReader", function(require, exports, module) {
-
-var exec = require('cordova/exec'),
- FileError = require('cordova/plugin/FileError') ;
-
-/**
- * An interface that lists the files and directories in a directory.
- */
-function DirectoryReader(path) {
- this.path = path || null;
-}
-
-/**
- * Returns a list of entries from a directory.
- *
- * @param {Function} successCallback is called with a list of entries
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
- var win = typeof successCallback !== 'function' ? null : function(result) {
- var retVal = [];
- for (var i=0; i<result.length; i++) {
- var entry = null;
- if (result[i].isDirectory) {
- entry = new (require('cordova/plugin/DirectoryEntry'))();
- }
- else if (result[i].isFile) {
- entry = new (require('cordova/plugin/FileEntry'))();
- }
- entry.isDirectory = result[i].isDirectory;
- entry.isFile = result[i].isFile;
- entry.name = result[i].name;
- entry.fullPath = result[i].fullPath;
- retVal.push(entry);
- }
- successCallback(retVal);
- };
- var fail = typeof errorCallback !== 'function' ? null : function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "readEntries", [this.path]);
-};
-
-module.exports = DirectoryReader;
-
-});
-
-// file: lib/common/plugin/Entry.js
-define("cordova/plugin/Entry", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- exec = require('cordova/exec'),
- FileError = require('cordova/plugin/FileError'),
- Metadata = require('cordova/plugin/Metadata');
-
-/**
- * Represents a file or directory on the local file system.
- *
- * @param isFile
- * {boolean} true if Entry is a file (readonly)
- * @param isDirectory
- * {boolean} true if Entry is a directory (readonly)
- * @param name
- * {DOMString} name of the file or directory, excluding the path
- * leading to it (readonly)
- * @param fullPath
- * {DOMString} the absolute full path to the file or directory
- * (readonly)
- */
-function Entry(isFile, isDirectory, name, fullPath, fileSystem) {
- this.isFile = !!isFile;
- this.isDirectory = !!isDirectory;
- this.name = name || '';
- this.fullPath = fullPath || '';
- this.filesystem = fileSystem || null;
-}
-
-/**
- * Look up the metadata of the entry.
- *
- * @param successCallback
- * {Function} is called with a Metadata object
- * @param errorCallback
- * {Function} is called with a FileError
- */
-Entry.prototype.getMetadata = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'Entry.getMetadata', arguments);
- var success = successCallback && function(lastModified) {
- var metadata = new Metadata(lastModified);
- successCallback(metadata);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
-
- exec(success, fail, "File", "getMetadata", [this.fullPath]);
-};
-
-/**
- * Set the metadata of the entry.
- *
- * @param successCallback
- * {Function} is called with a Metadata object
- * @param errorCallback
- * {Function} is called with a FileError
- * @param metadataObject
- * {Object} keys and values to set
- */
-Entry.prototype.setMetadata = function(successCallback, errorCallback, metadataObject) {
- argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments);
- exec(successCallback, errorCallback, "File", "setMetadata", [this.fullPath, metadataObject]);
-};
-
-/**
- * Move a file or directory to a new location.
- *
- * @param parent
- * {DirectoryEntry} the directory to which to move this entry
- * @param newName
- * {DOMString} new name of the entry, defaults to the current name
- * @param successCallback
- * {Function} called with the new DirectoryEntry object
- * @param errorCallback
- * {Function} called with a FileError
- */
-Entry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
- argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- // source path
- var srcPath = this.fullPath,
- // entry name
- name = newName || this.name,
- success = function(entry) {
- if (entry) {
- if (successCallback) {
- // create appropriate Entry object
- var result = (entry.isDirectory) ? new (require('cordova/plugin/DirectoryEntry'))(entry.name, entry.fullPath) : new (require('cordova/plugin/FileEntry'))(entry.name, entry.fullPath);
- successCallback(result);
- }
- }
- else {
- // no Entry object returned
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- // copy
- exec(success, fail, "File", "moveTo", [srcPath, parent.fullPath, name]);
-};
-
-/**
- * Copy a directory to a different location.
- *
- * @param parent
- * {DirectoryEntry} the directory to which to copy the entry
- * @param newName
- * {DOMString} new name of the entry, defaults to the current name
- * @param successCallback
- * {Function} called with the new Entry object
- * @param errorCallback
- * {Function} called with a FileError
- */
-Entry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
- argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
-
- // source path
- var srcPath = this.fullPath,
- // entry name
- name = newName || this.name,
- // success callback
- success = function(entry) {
- if (entry) {
- if (successCallback) {
- // create appropriate Entry object
- var result = (entry.isDirectory) ? new (require('cordova/plugin/DirectoryEntry'))(entry.name, entry.fullPath) : new (require('cordova/plugin/FileEntry'))(entry.name, entry.fullPath);
- successCallback(result);
- }
- }
- else {
- // no Entry object returned
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- // copy
- exec(success, fail, "File", "copyTo", [srcPath, parent.fullPath, name]);
-};
-
-/**
- * Return a URL that can be used to identify this entry.
- */
-Entry.prototype.toURL = function() {
- // fullPath attribute contains the full URL
- return this.fullPath;
-};
-
-/**
- * Returns a URI that can be used to identify this entry.
- *
- * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
- * @return uri
- */
-Entry.prototype.toURI = function(mimeType) {
- console.log("DEPRECATED: Update your code to use 'toURL'");
- // fullPath attribute contains the full URI
- return this.toURL();
-};
-
-/**
- * Remove a file or directory. It is an error to attempt to delete a
- * directory that is not empty. It is an error to attempt to delete a
- * root directory of a file system.
- *
- * @param successCallback {Function} called with no parameters
- * @param errorCallback {Function} called with a FileError
- */
-Entry.prototype.remove = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'Entry.remove', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(successCallback, fail, "File", "remove", [this.fullPath]);
-};
-
-/**
- * Look up the parent DirectoryEntry of this entry.
- *
- * @param successCallback {Function} called with the parent DirectoryEntry object
- * @param errorCallback {Function} called with a FileError
- */
-Entry.prototype.getParent = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'Entry.getParent', arguments);
- var win = successCallback && function(result) {
- var DirectoryEntry = require('cordova/plugin/DirectoryEntry');
- var entry = new DirectoryEntry(result.name, result.fullPath);
- successCallback(entry);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getParent", [this.fullPath]);
-};
-
-module.exports = Entry;
-
-});
-
-// file: lib/common/plugin/File.js
-define("cordova/plugin/File", function(require, exports, module) {
-
-/**
- * Constructor.
- * name {DOMString} name of the file, without path information
- * fullPath {DOMString} the full path of the file, including the name
- * type {DOMString} mime type
- * lastModifiedDate {Date} last modified date
- * size {Number} size of the file in bytes
- */
-
-var File = function(name, fullPath, type, lastModifiedDate, size){
- this.name = name || '';
- this.fullPath = fullPath || null;
- this.type = type || null;
- this.lastModifiedDate = lastModifiedDate || null;
- this.size = size || 0;
-
- // These store the absolute start and end for slicing the file.
- this.start = 0;
- this.end = this.size;
-};
-
-/**
- * Returns a "slice" of the file. Since Cordova Files don't contain the actual
- * content, this really returns a File with adjusted start and end.
- * Slices of slices are supported.
- * start {Number} The index at which to start the slice (inclusive).
- * end {Number} The index at which to end the slice (exclusive).
- */
-File.prototype.slice = function(start, end) {
- var size = this.end - this.start;
- var newStart = 0;
- var newEnd = size;
- if (arguments.length) {
- if (start < 0) {
- newStart = Math.max(size + start, 0);
- } else {
- newStart = Math.min(size, start);
- }
- }
-
- if (arguments.length >= 2) {
- if (end < 0) {
- newEnd = Math.max(size + end, 0);
- } else {
- newEnd = Math.min(end, size);
- }
- }
-
- var newFile = new File(this.name, this.fullPath, this.type, this.lastModifiedData, this.size);
- newFile.start = this.start + newStart;
- newFile.end = this.start + newEnd;
- return newFile;
-};
-
-
-module.exports = File;
-
-});
-
-// file: lib/common/plugin/FileEntry.js
-define("cordova/plugin/FileEntry", function(require, exports, module) {
-
-var utils = require('cordova/utils'),
- exec = require('cordova/exec'),
- Entry = require('cordova/plugin/Entry'),
- FileWriter = require('cordova/plugin/FileWriter'),
- File = require('cordova/plugin/File'),
- FileError = require('cordova/plugin/FileError');
-
-/**
- * An interface representing a file on the file system.
- *
- * {boolean} isFile always true (readonly)
- * {boolean} isDirectory always false (readonly)
- * {DOMString} name of the file, excluding the path leading to it (readonly)
- * {DOMString} fullPath the absolute full path to the file (readonly)
- * {FileSystem} filesystem on which the file resides (readonly)
- */
-var FileEntry = function(name, fullPath) {
- FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath]);
-};
-
-utils.extend(FileEntry, Entry);
-
-/**
- * Creates a new FileWriter associated with the file that this FileEntry represents.
- *
- * @param {Function} successCallback is called with the new FileWriter
- * @param {Function} errorCallback is called with a FileError
- */
-FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
- this.file(function(filePointer) {
- var writer = new FileWriter(filePointer);
-
- if (writer.fileName === null || writer.fileName === "") {
- errorCallback && errorCallback(new FileError(FileError.INVALID_STATE_ERR));
- } else {
- successCallback && successCallback(writer);
- }
- }, errorCallback);
-};
-
-/**
- * Returns a File that represents the current state of the file that this FileEntry represents.
- *
- * @param {Function} successCallback is called with the new File object
- * @param {Function} errorCallback is called with a FileError
- */
-FileEntry.prototype.file = function(successCallback, errorCallback) {
- var win = successCallback && function(f) {
- var file = new File(f.name, f.fullPath, f.type, f.lastModifiedDate, f.size);
- successCallback(file);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getFileMetadata", [this.fullPath]);
-};
-
-
-module.exports = FileEntry;
-
-});
-
-// file: lib/common/plugin/FileError.js
-define("cordova/plugin/FileError", function(require, exports, module) {
-
-/**
- * FileError
- */
-function FileError(error) {
- this.code = error || null;
-}
-
-// File error codes
-// Found in DOMException
-FileError.NOT_FOUND_ERR = 1;
-FileError.SECURITY_ERR = 2;
-FileError.ABORT_ERR = 3;
-
-// Added by File API specification
-FileError.NOT_READABLE_ERR = 4;
-FileError.ENCODING_ERR = 5;
-FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
-FileError.INVALID_STATE_ERR = 7;
-FileError.SYNTAX_ERR = 8;
-FileError.INVALID_MODIFICATION_ERR = 9;
-FileError.QUOTA_EXCEEDED_ERR = 10;
-FileError.TYPE_MISMATCH_ERR = 11;
-FileError.PATH_EXISTS_ERR = 12;
-
-module.exports = FileError;
-
-});
-
-// file: lib/common/plugin/FileReader.js
-define("cordova/plugin/FileReader", function(require, exports, module) {
-
-var exec = require('cordova/exec'),
- modulemapper = require('cordova/modulemapper'),
- utils = require('cordova/utils'),
- File = require('cordova/plugin/File'),
- FileError = require('cordova/plugin/FileError'),
- ProgressEvent = require('cordova/plugin/ProgressEvent'),
- origFileReader = modulemapper.getOriginalSymbol(this, 'FileReader');
-
-/**
- * This class reads the mobile device file system.
- *
- * For Android:
- * The root directory is the root of the file system.
- * To read from the SD card, the file name is "sdcard/my_file.txt"
- * @constructor
- */
-var FileReader = function() {
- this._readyState = 0;
- this._error = null;
- this._result = null;
- this._fileName = '';
- this._realReader = origFileReader ? new origFileReader() : {};
-};
-
-// States
-FileReader.EMPTY = 0;
-FileReader.LOADING = 1;
-FileReader.DONE = 2;
-
-utils.defineGetter(FileReader.prototype, 'readyState', function() {
- return this._fileName ? this._readyState : this._realReader.readyState;
-});
-
-utils.defineGetter(FileReader.prototype, 'error', function() {
- return this._fileName ? this._error: this._realReader.error;
-});
-
-utils.defineGetter(FileReader.prototype, 'result', function() {
- return this._fileName ? this._result: this._realReader.result;
-});
-
-function defineEvent(eventName) {
- utils.defineGetterSetter(FileReader.prototype, eventName, function() {
- return this._realReader[eventName] || null;
- }, function(value) {
- this._realReader[eventName] = value;
- });
-}
-defineEvent('onloadstart'); // When the read starts.
-defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total)
-defineEvent('onload'); // When the read has successfully completed.
-defineEvent('onerror'); // When the read has failed (see errors).
-defineEvent('onloadend'); // When the request has completed (either in success or failure).
-defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method.
-
-function initRead(reader, file) {
- // Already loading something
- if (reader.readyState == FileReader.LOADING) {
- throw new FileError(FileError.INVALID_STATE_ERR);
- }
-
- reader._result = null;
- reader._error = null;
- reader._readyState = FileReader.LOADING;
-
- if (typeof file == 'string') {
- // Deprecated in Cordova 2.4.
- console.warn('Using a string argument with FileReader.readAs functions is deprecated.');
- reader._fileName = file;
- } else if (typeof file.fullPath == 'string') {
- reader._fileName = file.fullPath;
- } else {
- reader._fileName = '';
- return true;
- }
-
- reader.onloadstart && reader.onloadstart(new ProgressEvent("loadstart", {target:reader}));
-}
-
-/**
- * Abort reading file.
- */
-FileReader.prototype.abort = function() {
- if (origFileReader && !this._fileName) {
- return this._realReader.abort();
- }
- this._result = null;
-
- if (this._readyState == FileReader.DONE || this._readyState == FileReader.EMPTY) {
- return;
- }
-
- this._readyState = FileReader.DONE;
-
- // If abort callback
- if (typeof this.onabort === 'function') {
- this.onabort(new ProgressEvent('abort', {target:this}));
- }
- // If load end callback
- if (typeof this.onloadend === 'function') {
- this.onloadend(new ProgressEvent('loadend', {target:this}));
- }
-};
-
-/**
- * Read text file.
- *
- * @param file {File} File object containing file properties
- * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)
- */
-FileReader.prototype.readAsText = function(file, encoding) {
- if (initRead(this, file)) {
- return this._realReader.readAsText(file, encoding);
- }
-
- // Default encoding is UTF-8
- var enc = encoding ? encoding : "UTF-8";
- var me = this;
- var execArgs = [this._fileName, enc, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // Save result
- me._result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", {target:me}));
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- },
- // Error callback
- function(e) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- // null result
- me._result = null;
-
- // Save error
- me._error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- }, "File", "readAsText", execArgs);
-};
-
-
-/**
- * Read file and return data as a base64 encoded data url.
- * A data url is of the form:
- * data:[<mediatype>][;base64],<data>
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsDataURL = function(file) {
- if (initRead(this, file)) {
- return this._realReader.readAsDataURL(file);
- }
-
- var me = this;
- var execArgs = [this._fileName, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- // Save result
- me._result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- },
- // Error callback
- function(e) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = null;
-
- // Save error
- me._error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- }, "File", "readAsDataURL", execArgs);
-};
-
-/**
- * Read file and return data as a binary data.
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsBinaryString = function(file) {
- if (initRead(this, file)) {
- return this._realReader.readAsBinaryString(file);
- }
-
- var me = this;
- var execArgs = [this._fileName, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- },
- // Error callback
- function(e) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = null;
-
- // Save error
- me._error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- }, "File", "readAsBinaryString", execArgs);
-};
-
-/**
- * Read file and return data as a binary data.
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsArrayBuffer = function(file) {
- if (initRead(this, file)) {
- return this._realReader.readAsArrayBuffer(file);
- }
-
- var me = this;
- var execArgs = [this._fileName, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- },
- // Error callback
- function(e) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = null;
-
- // Save error
- me._error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- }, "File", "readAsArrayBuffer", execArgs);
-};
-
-module.exports = FileReader;
-
-});
-
-// file: lib/common/plugin/FileSystem.js
-define("cordova/plugin/FileSystem", function(require, exports, module) {
-
-var DirectoryEntry = require('cordova/plugin/DirectoryEntry');
-
-/**
- * An interface representing a file system
- *
- * @constructor
- * {DOMString} name the unique name of the file system (readonly)
- * {DirectoryEntry} root directory of the file system (readonly)
- */
-var FileSystem = function(name, root) {
- this.name = name || null;
- if (root) {
- this.root = new DirectoryEntry(root.name, root.fullPath);
- }
-};
-
-module.exports = FileSystem;
-
-});
-
-// file: lib/common/plugin/FileTransfer.js
-define("cordova/plugin/FileTransfer", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- exec = require('cordova/exec'),
- FileTransferError = require('cordova/plugin/FileTransferError'),
- ProgressEvent = require('cordova/plugin/ProgressEvent');
-
-function newProgressEvent(result) {
- var pe = new ProgressEvent();
- pe.lengthComputable = result.lengthComputable;
- pe.loaded = result.loaded;
- pe.total = result.total;
- return pe;
-}
-
-function getBasicAuthHea
<TRUNCATED>
[10/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/javascript/cordova.blackberry.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/javascript/cordova.blackberry.js b/lib/cordova-blackberry/javascript/cordova.blackberry.js
deleted file mode 100644
index 73a040d..0000000
--- a/lib/cordova-blackberry/javascript/cordova.blackberry.js
+++ /dev/null
@@ -1,10904 +0,0 @@
-// Platform: blackberry
-
-// 2.7.0-4-gabc9de8
-
-// File generated at :: Tue Apr 30 2013 10:52:06 GMT-0700 (PDT)
-
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-
-;(function() {
-
-// file: lib/scripts/require.js
-
-var require,
- define;
-
-(function () {
- var modules = {};
- // Stack of moduleIds currently being built.
- var requireStack = [];
- // Map of module ID -> index into requireStack of modules currently being built.
- var inProgressModules = {};
-
- function build(module) {
- var factory = module.factory;
- module.exports = {};
- delete module.factory;
- factory(require, module.exports, module);
- return module.exports;
- }
-
- require = function (id) {
- if (!modules[id]) {
- throw "module " + id + " not found";
- } else if (id in inProgressModules) {
- var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;
- throw "Cycle in require graph: " + cycle;
- }
- if (modules[id].factory) {
- try {
- inProgressModules[id] = requireStack.length;
- requireStack.push(id);
- return build(modules[id]);
- } finally {
- delete inProgressModules[id];
- requireStack.pop();
- }
- }
- return modules[id].exports;
- };
-
- define = function (id, factory) {
- if (modules[id]) {
- throw "module " + id + " already defined";
- }
-
- modules[id] = {
- id: id,
- factory: factory
- };
- };
-
- define.remove = function (id) {
- delete modules[id];
- };
-
- define.moduleMap = modules;
-})();
-
-//Export for use in node
-if (typeof module === "object" && typeof require === "function") {
- module.exports.require = require;
- module.exports.define = define;
-}
-
-// file: lib/cordova.js
-define("cordova", function(require, exports, module) {
-
-
-var channel = require('cordova/channel');
-
-/**
- * Listen for DOMContentLoaded and notify our channel subscribers.
- */
-document.addEventListener('DOMContentLoaded', function() {
- channel.onDOMContentLoaded.fire();
-}, false);
-if (document.readyState == 'complete' || document.readyState == 'interactive') {
- channel.onDOMContentLoaded.fire();
-}
-
-/**
- * Intercept calls to addEventListener + removeEventListener and handle deviceready,
- * resume, and pause events.
- */
-var m_document_addEventListener = document.addEventListener;
-var m_document_removeEventListener = document.removeEventListener;
-var m_window_addEventListener = window.addEventListener;
-var m_window_removeEventListener = window.removeEventListener;
-
-/**
- * Houses custom event handlers to intercept on document + window event listeners.
- */
-var documentEventHandlers = {},
- windowEventHandlers = {};
-
-document.addEventListener = function(evt, handler, capture) {
- var e = evt.toLowerCase();
- if (typeof documentEventHandlers[e] != 'undefined') {
- documentEventHandlers[e].subscribe(handler);
- } else {
- m_document_addEventListener.call(document, evt, handler, capture);
- }
-};
-
-window.addEventListener = function(evt, handler, capture) {
- var e = evt.toLowerCase();
- if (typeof windowEventHandlers[e] != 'undefined') {
- windowEventHandlers[e].subscribe(handler);
- } else {
- m_window_addEventListener.call(window, evt, handler, capture);
- }
-};
-
-document.removeEventListener = function(evt, handler, capture) {
- var e = evt.toLowerCase();
- // If unsubscribing from an event that is handled by a plugin
- if (typeof documentEventHandlers[e] != "undefined") {
- documentEventHandlers[e].unsubscribe(handler);
- } else {
- m_document_removeEventListener.call(document, evt, handler, capture);
- }
-};
-
-window.removeEventListener = function(evt, handler, capture) {
- var e = evt.toLowerCase();
- // If unsubscribing from an event that is handled by a plugin
- if (typeof windowEventHandlers[e] != "undefined") {
- windowEventHandlers[e].unsubscribe(handler);
- } else {
- m_window_removeEventListener.call(window, evt, handler, capture);
- }
-};
-
-function createEvent(type, data) {
- var event = document.createEvent('Events');
- event.initEvent(type, false, false);
- if (data) {
- for (var i in data) {
- if (data.hasOwnProperty(i)) {
- event[i] = data[i];
- }
- }
- }
- return event;
-}
-
-if(typeof window.console === "undefined") {
- window.console = {
- log:function(){}
- };
-}
-
-var cordova = {
- define:define,
- require:require,
- /**
- * Methods to add/remove your own addEventListener hijacking on document + window.
- */
- addWindowEventHandler:function(event) {
- return (windowEventHandlers[event] = channel.create(event));
- },
- addStickyDocumentEventHandler:function(event) {
- return (documentEventHandlers[event] = channel.createSticky(event));
- },
- addDocumentEventHandler:function(event) {
- return (documentEventHandlers[event] = channel.create(event));
- },
- removeWindowEventHandler:function(event) {
- delete windowEventHandlers[event];
- },
- removeDocumentEventHandler:function(event) {
- delete documentEventHandlers[event];
- },
- /**
- * Retrieve original event handlers that were replaced by Cordova
- *
- * @return object
- */
- getOriginalHandlers: function() {
- return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},
- 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};
- },
- /**
- * Method to fire event from native code
- * bNoDetach is required for events which cause an exception which needs to be caught in native code
- */
- fireDocumentEvent: function(type, data, bNoDetach) {
- var evt = createEvent(type, data);
- if (typeof documentEventHandlers[type] != 'undefined') {
- if( bNoDetach ) {
- documentEventHandlers[type].fire(evt);
- }
- else {
- setTimeout(function() {
- // Fire deviceready on listeners that were registered before cordova.js was loaded.
- if (type == 'deviceready') {
- document.dispatchEvent(evt);
- }
- documentEventHandlers[type].fire(evt);
- }, 0);
- }
- } else {
- document.dispatchEvent(evt);
- }
- },
- fireWindowEvent: function(type, data) {
- var evt = createEvent(type,data);
- if (typeof windowEventHandlers[type] != 'undefined') {
- setTimeout(function() {
- windowEventHandlers[type].fire(evt);
- }, 0);
- } else {
- window.dispatchEvent(evt);
- }
- },
-
- /**
- * Plugin callback mechanism.
- */
- // Randomize the starting callbackId to avoid collisions after refreshing or navigating.
- // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.
- callbackId: Math.floor(Math.random() * 2000000000),
- callbacks: {},
- callbackStatus: {
- NO_RESULT: 0,
- OK: 1,
- CLASS_NOT_FOUND_EXCEPTION: 2,
- ILLEGAL_ACCESS_EXCEPTION: 3,
- INSTANTIATION_EXCEPTION: 4,
- MALFORMED_URL_EXCEPTION: 5,
- IO_EXCEPTION: 6,
- INVALID_ACTION: 7,
- JSON_EXCEPTION: 8,
- ERROR: 9
- },
-
- /**
- * Called by native code when returning successful result from an action.
- */
- callbackSuccess: function(callbackId, args) {
- try {
- cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
- } catch (e) {
- console.log("Error in error callback: " + callbackId + " = "+e);
- }
- },
-
- /**
- * Called by native code when returning error result from an action.
- */
- callbackError: function(callbackId, args) {
- // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
- // Derive success from status.
- try {
- cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
- } catch (e) {
- console.log("Error in error callback: " + callbackId + " = "+e);
- }
- },
-
- /**
- * Called by native code when returning the result from an action.
- */
- callbackFromNative: function(callbackId, success, status, args, keepCallback) {
- var callback = cordova.callbacks[callbackId];
- if (callback) {
- if (success && status == cordova.callbackStatus.OK) {
- callback.success && callback.success.apply(null, args);
- } else if (!success) {
- callback.fail && callback.fail.apply(null, args);
- }
-
- // Clear callback if not expecting any more results
- if (!keepCallback) {
- delete cordova.callbacks[callbackId];
- }
- }
- },
- addConstructor: function(func) {
- channel.onCordovaReady.subscribe(function() {
- try {
- func();
- } catch(e) {
- console.log("Failed to run constructor: " + e);
- }
- });
- }
-};
-
-// Register pause, resume and deviceready channels as events on document.
-channel.onPause = cordova.addDocumentEventHandler('pause');
-channel.onResume = cordova.addDocumentEventHandler('resume');
-channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');
-
-module.exports = cordova;
-
-});
-
-// file: lib/common/argscheck.js
-define("cordova/argscheck", function(require, exports, module) {
-
-var exec = require('cordova/exec');
-var utils = require('cordova/utils');
-
-var moduleExports = module.exports;
-
-var typeMap = {
- 'A': 'Array',
- 'D': 'Date',
- 'N': 'Number',
- 'S': 'String',
- 'F': 'Function',
- 'O': 'Object'
-};
-
-function extractParamName(callee, argIndex) {
- return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex];
-}
-
-function checkArgs(spec, functionName, args, opt_callee) {
- if (!moduleExports.enableChecks) {
- return;
- }
- var errMsg = null;
- var typeName;
- for (var i = 0; i < spec.length; ++i) {
- var c = spec.charAt(i),
- cUpper = c.toUpperCase(),
- arg = args[i];
- // Asterix means allow anything.
- if (c == '*') {
- continue;
- }
- typeName = utils.typeName(arg);
- if ((arg === null || arg === undefined) && c == cUpper) {
- continue;
- }
- if (typeName != typeMap[cUpper]) {
- errMsg = 'Expected ' + typeMap[cUpper];
- break;
- }
- }
- if (errMsg) {
- errMsg += ', but got ' + typeName + '.';
- errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;
- // Don't log when running jake test.
- if (typeof jasmine == 'undefined') {
- console.error(errMsg);
- }
- throw TypeError(errMsg);
- }
-}
-
-function getValue(value, defaultValue) {
- return value === undefined ? defaultValue : value;
-}
-
-moduleExports.checkArgs = checkArgs;
-moduleExports.getValue = getValue;
-moduleExports.enableChecks = true;
-
-
-});
-
-// file: lib/common/builder.js
-define("cordova/builder", function(require, exports, module) {
-
-var utils = require('cordova/utils');
-
-function each(objects, func, context) {
- for (var prop in objects) {
- if (objects.hasOwnProperty(prop)) {
- func.apply(context, [objects[prop], prop]);
- }
- }
-}
-
-function clobber(obj, key, value) {
- exports.replaceHookForTesting(obj, key);
- obj[key] = value;
- // Getters can only be overridden by getters.
- if (obj[key] !== value) {
- utils.defineGetter(obj, key, function() {
- return value;
- });
- }
-}
-
-function assignOrWrapInDeprecateGetter(obj, key, value, message) {
- if (message) {
- utils.defineGetter(obj, key, function() {
- console.log(message);
- delete obj[key];
- clobber(obj, key, value);
- return value;
- });
- } else {
- clobber(obj, key, value);
- }
-}
-
-function include(parent, objects, clobber, merge) {
- each(objects, function (obj, key) {
- try {
- var result = obj.path ? require(obj.path) : {};
-
- if (clobber) {
- // Clobber if it doesn't exist.
- if (typeof parent[key] === 'undefined') {
- assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
- } else if (typeof obj.path !== 'undefined') {
- // If merging, merge properties onto parent, otherwise, clobber.
- if (merge) {
- recursiveMerge(parent[key], result);
- } else {
- assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
- }
- }
- result = parent[key];
- } else {
- // Overwrite if not currently defined.
- if (typeof parent[key] == 'undefined') {
- assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
- } else {
- // Set result to what already exists, so we can build children into it if they exist.
- result = parent[key];
- }
- }
-
- if (obj.children) {
- include(result, obj.children, clobber, merge);
- }
- } catch(e) {
- utils.alert('Exception building cordova JS globals: ' + e + ' for key "' + key + '"');
- }
- });
-}
-
-/**
- * Merge properties from one object onto another recursively. Properties from
- * the src object will overwrite existing target property.
- *
- * @param target Object to merge properties into.
- * @param src Object to merge properties from.
- */
-function recursiveMerge(target, src) {
- for (var prop in src) {
- if (src.hasOwnProperty(prop)) {
- if (target.prototype && target.prototype.constructor === target) {
- // If the target object is a constructor override off prototype.
- clobber(target.prototype, prop, src[prop]);
- } else {
- if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
- recursiveMerge(target[prop], src[prop]);
- } else {
- clobber(target, prop, src[prop]);
- }
- }
- }
- }
-}
-
-exports.buildIntoButDoNotClobber = function(objects, target) {
- include(target, objects, false, false);
-};
-exports.buildIntoAndClobber = function(objects, target) {
- include(target, objects, true, false);
-};
-exports.buildIntoAndMerge = function(objects, target) {
- include(target, objects, true, true);
-};
-exports.recursiveMerge = recursiveMerge;
-exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;
-exports.replaceHookForTesting = function() {};
-
-});
-
-// file: lib/common/channel.js
-define("cordova/channel", function(require, exports, module) {
-
-var utils = require('cordova/utils'),
- nextGuid = 1;
-
-/**
- * Custom pub-sub "channel" that can have functions subscribed to it
- * This object is used to define and control firing of events for
- * cordova initialization, as well as for custom events thereafter.
- *
- * The order of events during page load and Cordova startup is as follows:
- *
- * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.
- * onNativeReady* Internal event that indicates the Cordova native side is ready.
- * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.
- * onCordovaInfoReady* Internal event fired when device properties are available.
- * onCordovaConnectionReady* Internal event fired when the connection property has been set.
- * onDeviceReady* User event fired to indicate that Cordova is ready
- * onResume User event fired to indicate a start/resume lifecycle event
- * onPause User event fired to indicate a pause lifecycle event
- * onDestroy* Internal event fired when app is being destroyed (User should use window.onunload event, not this one).
- *
- * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.
- * All listeners that subscribe after the event is fired will be executed right away.
- *
- * The only Cordova events that user code should register for are:
- * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript
- * pause App has moved to background
- * resume App has returned to foreground
- *
- * Listeners can be registered as:
- * document.addEventListener("deviceready", myDeviceReadyListener, false);
- * document.addEventListener("resume", myResumeListener, false);
- * document.addEventListener("pause", myPauseListener, false);
- *
- * The DOM lifecycle events should be used for saving and restoring state
- * window.onload
- * window.onunload
- *
- */
-
-/**
- * Channel
- * @constructor
- * @param type String the channel name
- */
-var Channel = function(type, sticky) {
- this.type = type;
- // Map of guid -> function.
- this.handlers = {};
- // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
- this.state = sticky ? 1 : 0;
- // Used in sticky mode to remember args passed to fire().
- this.fireArgs = null;
- // Used by onHasSubscribersChange to know if there are any listeners.
- this.numHandlers = 0;
- // Function that is called when the first listener is subscribed, or when
- // the last listener is unsubscribed.
- this.onHasSubscribersChange = null;
-},
- channel = {
- /**
- * Calls the provided function only after all of the channels specified
- * have been fired. All channels must be sticky channels.
- */
- join: function(h, c) {
- var len = c.length,
- i = len,
- f = function() {
- if (!(--i)) h();
- };
- for (var j=0; j<len; j++) {
- if (c[j].state === 0) {
- throw Error('Can only use join with sticky channels.');
- }
- c[j].subscribe(f);
- }
- if (!len) h();
- },
- create: function(type) {
- return channel[type] = new Channel(type, false);
- },
- createSticky: function(type) {
- return channel[type] = new Channel(type, true);
- },
-
- /**
- * cordova Channels that must fire before "deviceready" is fired.
- */
- deviceReadyChannelsArray: [],
- deviceReadyChannelsMap: {},
-
- /**
- * Indicate that a feature needs to be initialized before it is ready to be used.
- * This holds up Cordova's "deviceready" event until the feature has been initialized
- * and Cordova.initComplete(feature) is called.
- *
- * @param feature {String} The unique feature name
- */
- waitForInitialization: function(feature) {
- if (feature) {
- var c = channel[feature] || this.createSticky(feature);
- this.deviceReadyChannelsMap[feature] = c;
- this.deviceReadyChannelsArray.push(c);
- }
- },
-
- /**
- * Indicate that initialization code has completed and the feature is ready to be used.
- *
- * @param feature {String} The unique feature name
- */
- initializationComplete: function(feature) {
- var c = this.deviceReadyChannelsMap[feature];
- if (c) {
- c.fire();
- }
- }
- };
-
-function forceFunction(f) {
- if (typeof f != 'function') throw "Function required as first argument!";
-}
-
-/**
- * Subscribes the given function to the channel. Any time that
- * Channel.fire is called so too will the function.
- * Optionally specify an execution context for the function
- * and a guid that can be used to stop subscribing to the channel.
- * Returns the guid.
- */
-Channel.prototype.subscribe = function(f, c) {
- // need a function to call
- forceFunction(f);
- if (this.state == 2) {
- f.apply(c || this, this.fireArgs);
- return;
- }
-
- var func = f,
- guid = f.observer_guid;
- if (typeof c == "object") { func = utils.close(c, f); }
-
- if (!guid) {
- // first time any channel has seen this subscriber
- guid = '' + nextGuid++;
- }
- func.observer_guid = guid;
- f.observer_guid = guid;
-
- // Don't add the same handler more than once.
- if (!this.handlers[guid]) {
- this.handlers[guid] = func;
- this.numHandlers++;
- if (this.numHandlers == 1) {
- this.onHasSubscribersChange && this.onHasSubscribersChange();
- }
- }
-};
-
-/**
- * Unsubscribes the function with the given guid from the channel.
- */
-Channel.prototype.unsubscribe = function(f) {
- // need a function to unsubscribe
- forceFunction(f);
-
- var guid = f.observer_guid,
- handler = this.handlers[guid];
- if (handler) {
- delete this.handlers[guid];
- this.numHandlers--;
- if (this.numHandlers === 0) {
- this.onHasSubscribersChange && this.onHasSubscribersChange();
- }
- }
-};
-
-/**
- * Calls all functions subscribed to this channel.
- */
-Channel.prototype.fire = function(e) {
- var fail = false,
- fireArgs = Array.prototype.slice.call(arguments);
- // Apply stickiness.
- if (this.state == 1) {
- this.state = 2;
- this.fireArgs = fireArgs;
- }
- if (this.numHandlers) {
- // Copy the values first so that it is safe to modify it from within
- // callbacks.
- var toCall = [];
- for (var item in this.handlers) {
- toCall.push(this.handlers[item]);
- }
- for (var i = 0; i < toCall.length; ++i) {
- toCall[i].apply(this, fireArgs);
- }
- if (this.state == 2 && this.numHandlers) {
- this.numHandlers = 0;
- this.handlers = {};
- this.onHasSubscribersChange && this.onHasSubscribersChange();
- }
- }
-};
-
-
-// defining them here so they are ready super fast!
-// DOM event that is received when the web page is loaded and parsed.
-channel.createSticky('onDOMContentLoaded');
-
-// Event to indicate the Cordova native side is ready.
-channel.createSticky('onNativeReady');
-
-// Event to indicate that all Cordova JavaScript objects have been created
-// and it's time to run plugin constructors.
-channel.createSticky('onCordovaReady');
-
-// Event to indicate that device properties are available
-channel.createSticky('onCordovaInfoReady');
-
-// Event to indicate that the connection property has been set.
-channel.createSticky('onCordovaConnectionReady');
-
-// Event to indicate that all automatically loaded JS plugins are loaded and ready.
-channel.createSticky('onPluginsReady');
-
-// Event to indicate that Cordova is ready
-channel.createSticky('onDeviceReady');
-
-// Event to indicate a resume lifecycle event
-channel.create('onResume');
-
-// Event to indicate a pause lifecycle event
-channel.create('onPause');
-
-// Event to indicate a destroy lifecycle event
-channel.createSticky('onDestroy');
-
-// Channels that must fire before "deviceready" is fired.
-channel.waitForInitialization('onCordovaReady');
-channel.waitForInitialization('onCordovaConnectionReady');
-channel.waitForInitialization('onDOMContentLoaded');
-
-module.exports = channel;
-
-});
-
-// file: lib/common/commandProxy.js
-define("cordova/commandProxy", function(require, exports, module) {
-
-
-// internal map of proxy function
-var CommandProxyMap = {};
-
-module.exports = {
-
- // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);
- add:function(id,proxyObj) {
- console.log("adding proxy for " + id);
- CommandProxyMap[id] = proxyObj;
- return proxyObj;
- },
-
- // cordova.commandProxy.remove("Accelerometer");
- remove:function(id) {
- var proxy = CommandProxyMap[id];
- delete CommandProxyMap[id];
- CommandProxyMap[id] = null;
- return proxy;
- },
-
- get:function(service,action) {
- return ( CommandProxyMap[service] ? CommandProxyMap[service][action] : null );
- }
-};
-});
-
-// file: lib/blackberry/exec.js
-define("cordova/exec", function(require, exports, module) {
-
-var cordova = require('cordova'),
- platform = require('cordova/platform'),
- utils = require('cordova/utils');
-
-/**
- * Execute a cordova command. It is up to the native side whether this action
- * is synchronous or asynchronous. The native side can return:
- * Synchronous: PluginResult object as a JSON string
- * Asynchronous: Empty string ""
- * If async, the native side will cordova.callbackSuccess or cordova.callbackError,
- * depending upon the result of the action.
- *
- * @param {Function} success The success callback
- * @param {Function} fail The fail callback
- * @param {String} service The name of the service to use
- * @param {String} action Action to be run in cordova
- * @param {String[]} [args] Zero or more arguments to pass to the method
- */
-
-module.exports = function(success, fail, service, action, args) {
- try {
- var manager = require('cordova/plugin/' + platform.runtime() + '/manager'),
- v = manager.exec(success, fail, service, action, args);
-
- // If status is OK, then return value back to caller
- if (v.status == cordova.callbackStatus.OK) {
-
- // If there is a success callback, then call it now with returned value
- if (success) {
- try {
- success(v.message);
- }
- catch (e) {
- console.log("Error in success callback: "+cordova.callbackId+" = "+e);
- }
- }
- return v.message;
- } else if (v.status == cordova.callbackStatus.NO_RESULT) {
-
- } else {
- // If error, then display error
- console.log("Error: Status="+v.status+" Message="+v.message);
-
- // If there is a fail callback, then call it now with returned value
- if (fail) {
- try {
- fail(v.message);
- }
- catch (e) {
- console.log("Error in error callback: "+cordova.callbackId+" = "+e);
- }
- }
- return null;
- }
- } catch (e) {
- utils.alert("Error: "+e);
- }
-};
-
-});
-
-// file: lib/common/modulemapper.js
-define("cordova/modulemapper", function(require, exports, module) {
-
-var builder = require('cordova/builder'),
- moduleMap = define.moduleMap,
- symbolList,
- deprecationMap;
-
-exports.reset = function() {
- symbolList = [];
- deprecationMap = {};
-};
-
-function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) {
- if (!(moduleName in moduleMap)) {
- throw new Error('Module ' + moduleName + ' does not exist.');
- }
- symbolList.push(strategy, moduleName, symbolPath);
- if (opt_deprecationMessage) {
- deprecationMap[symbolPath] = opt_deprecationMessage;
- }
-}
-
-// Note: Android 2.3 does have Function.bind().
-exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) {
- addEntry('c', moduleName, symbolPath, opt_deprecationMessage);
-};
-
-exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) {
- addEntry('m', moduleName, symbolPath, opt_deprecationMessage);
-};
-
-exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) {
- addEntry('d', moduleName, symbolPath, opt_deprecationMessage);
-};
-
-function prepareNamespace(symbolPath, context) {
- if (!symbolPath) {
- return context;
- }
- var parts = symbolPath.split('.');
- var cur = context;
- for (var i = 0, part; part = parts[i]; ++i) {
- cur = cur[part] = cur[part] || {};
- }
- return cur;
-}
-
-exports.mapModules = function(context) {
- var origSymbols = {};
- context.CDV_origSymbols = origSymbols;
- for (var i = 0, len = symbolList.length; i < len; i += 3) {
- var strategy = symbolList[i];
- var moduleName = symbolList[i + 1];
- var symbolPath = symbolList[i + 2];
- var lastDot = symbolPath.lastIndexOf('.');
- var namespace = symbolPath.substr(0, lastDot);
- var lastName = symbolPath.substr(lastDot + 1);
-
- var module = require(moduleName);
- var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;
- var parentObj = prepareNamespace(namespace, context);
- var target = parentObj[lastName];
-
- if (strategy == 'm' && target) {
- builder.recursiveMerge(target, module);
- } else if ((strategy == 'd' && !target) || (strategy != 'd')) {
- if (!(symbolPath in origSymbols)) {
- origSymbols[symbolPath] = target;
- }
- builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);
- }
- }
-};
-
-exports.getOriginalSymbol = function(context, symbolPath) {
- var origSymbols = context.CDV_origSymbols;
- if (origSymbols && (symbolPath in origSymbols)) {
- return origSymbols[symbolPath];
- }
- var parts = symbolPath.split('.');
- var obj = context;
- for (var i = 0; i < parts.length; ++i) {
- obj = obj && obj[parts[i]];
- }
- return obj;
-};
-
-exports.loadMatchingModules = function(matchingRegExp) {
- for (var k in moduleMap) {
- if (matchingRegExp.exec(k)) {
- require(k);
- }
- }
-};
-
-exports.reset();
-
-
-});
-
-// file: lib/blackberry/platform.js
-define("cordova/platform", function(require, exports, module) {
-
-module.exports = {
- id: "blackberry",
- runtime: function () {
- if (navigator.userAgent.indexOf("BB10") > -1) {
- return 'qnx';
- }
- else if (navigator.userAgent.indexOf("PlayBook") > -1) {
- return 'air';
- }
- else if (navigator.userAgent.indexOf("BlackBerry") > -1) {
- return 'java';
- }
- else {
- console.log("Unknown user agent?!?!? defaulting to java");
- return 'java';
- }
- },
- initialize: function() {
- var modulemapper = require('cordova/modulemapper'),
- platform = require('cordova/plugin/' + this.runtime() + '/platform');
-
- modulemapper.loadMatchingModules(/cordova.*\/symbols$/);
- modulemapper.loadMatchingModules(new RegExp('cordova/.*' + this.runtime() + '/.*bbsymbols$'));
- modulemapper.mapModules(this.contextObj);
-
- platform.initialize();
- },
- contextObj: this // Used for testing.
-};
-
-});
-
-// file: lib/common/plugin/Acceleration.js
-define("cordova/plugin/Acceleration", function(require, exports, module) {
-
-var Acceleration = function(x, y, z, timestamp) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.timestamp = timestamp || (new Date()).getTime();
-};
-
-module.exports = Acceleration;
-
-});
-
-// file: lib/common/plugin/Camera.js
-define("cordova/plugin/Camera", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- exec = require('cordova/exec'),
- Camera = require('cordova/plugin/CameraConstants'),
- CameraPopoverHandle = require('cordova/plugin/CameraPopoverHandle');
-
-var cameraExport = {};
-
-// Tack on the Camera Constants to the base camera plugin.
-for (var key in Camera) {
- cameraExport[key] = Camera[key];
-}
-
-/**
- * Gets a picture from source defined by "options.sourceType", and returns the
- * image as defined by the "options.destinationType" option.
-
- * The defaults are sourceType=CAMERA and destinationType=FILE_URI.
- *
- * @param {Function} successCallback
- * @param {Function} errorCallback
- * @param {Object} options
- */
-cameraExport.getPicture = function(successCallback, errorCallback, options) {
- argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);
- options = options || {};
- var getValue = argscheck.getValue;
-
- var quality = getValue(options.quality, 50);
- var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);
- var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);
- var targetWidth = getValue(options.targetWidth, -1);
- var targetHeight = getValue(options.targetHeight, -1);
- var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);
- var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);
- var allowEdit = !!options.allowEdit;
- var correctOrientation = !!options.correctOrientation;
- var saveToPhotoAlbum = !!options.saveToPhotoAlbum;
- var popoverOptions = getValue(options.popoverOptions, null);
- var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
-
- var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,
- mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];
-
- exec(successCallback, errorCallback, "Camera", "takePicture", args);
- return new CameraPopoverHandle();
-};
-
-cameraExport.cleanup = function(successCallback, errorCallback) {
- exec(successCallback, errorCallback, "Camera", "cleanup", []);
-};
-
-module.exports = cameraExport;
-
-});
-
-// file: lib/common/plugin/CameraConstants.js
-define("cordova/plugin/CameraConstants", function(require, exports, module) {
-
-module.exports = {
- DestinationType:{
- DATA_URL: 0, // Return base64 encoded string
- FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
- NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
- },
- EncodingType:{
- JPEG: 0, // Return JPEG encoded image
- PNG: 1 // Return PNG encoded image
- },
- MediaType:{
- PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
- VIDEO: 1, // allow selection of video only, ONLY RETURNS URL
- ALLMEDIA : 2 // allow selection from all media types
- },
- PictureSourceType:{
- PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
- CAMERA : 1, // Take picture from camera
- SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
- },
- PopoverArrowDirection:{
- ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants to specify arrow location on popover
- ARROW_DOWN : 2,
- ARROW_LEFT : 4,
- ARROW_RIGHT : 8,
- ARROW_ANY : 15
- },
- Direction:{
- BACK: 0,
- FRONT: 1
- }
-};
-
-});
-
-// file: lib/common/plugin/CameraPopoverHandle.js
-define("cordova/plugin/CameraPopoverHandle", function(require, exports, module) {
-
-var exec = require('cordova/exec');
-
-/**
- * A handle to an image picker popover.
- */
-var CameraPopoverHandle = function() {
- this.setPosition = function(popoverOptions) {
- console.log('CameraPopoverHandle.setPosition is only supported on iOS.');
- };
-};
-
-module.exports = CameraPopoverHandle;
-
-});
-
-// file: lib/common/plugin/CameraPopoverOptions.js
-define("cordova/plugin/CameraPopoverOptions", function(require, exports, module) {
-
-var Camera = require('cordova/plugin/CameraConstants');
-
-/**
- * Encapsulates options for iOS Popover image picker
- */
-var CameraPopoverOptions = function(x,y,width,height,arrowDir){
- // information of rectangle that popover should be anchored to
- this.x = x || 0;
- this.y = y || 32;
- this.width = width || 320;
- this.height = height || 480;
- // The direction of the popover arrow
- this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY;
-};
-
-module.exports = CameraPopoverOptions;
-
-});
-
-// file: lib/common/plugin/CaptureAudioOptions.js
-define("cordova/plugin/CaptureAudioOptions", function(require, exports, module) {
-
-/**
- * Encapsulates all audio capture operation configuration options.
- */
-var CaptureAudioOptions = function(){
- // Upper limit of sound clips user can record. Value must be equal or greater than 1.
- this.limit = 1;
- // Maximum duration of a single sound clip in seconds.
- this.duration = 0;
-};
-
-module.exports = CaptureAudioOptions;
-
-});
-
-// file: lib/common/plugin/CaptureError.js
-define("cordova/plugin/CaptureError", function(require, exports, module) {
-
-/**
- * The CaptureError interface encapsulates all errors in the Capture API.
- */
-var CaptureError = function(c) {
- this.code = c || null;
-};
-
-// Camera or microphone failed to capture image or sound.
-CaptureError.CAPTURE_INTERNAL_ERR = 0;
-// Camera application or audio capture application is currently serving other capture request.
-CaptureError.CAPTURE_APPLICATION_BUSY = 1;
-// Invalid use of the API (e.g. limit parameter has value less than one).
-CaptureError.CAPTURE_INVALID_ARGUMENT = 2;
-// User exited camera application or audio capture application before capturing anything.
-CaptureError.CAPTURE_NO_MEDIA_FILES = 3;
-// The requested capture operation is not supported.
-CaptureError.CAPTURE_NOT_SUPPORTED = 20;
-
-module.exports = CaptureError;
-
-});
-
-// file: lib/common/plugin/CaptureImageOptions.js
-define("cordova/plugin/CaptureImageOptions", function(require, exports, module) {
-
-/**
- * Encapsulates all image capture operation configuration options.
- */
-var CaptureImageOptions = function(){
- // Upper limit of images user can take. Value must be equal or greater than 1.
- this.limit = 1;
-};
-
-module.exports = CaptureImageOptions;
-
-});
-
-// file: lib/common/plugin/CaptureVideoOptions.js
-define("cordova/plugin/CaptureVideoOptions", function(require, exports, module) {
-
-/**
- * Encapsulates all video capture operation configuration options.
- */
-var CaptureVideoOptions = function(){
- // Upper limit of videos user can record. Value must be equal or greater than 1.
- this.limit = 1;
- // Maximum duration of a single video clip in seconds.
- this.duration = 0;
-};
-
-module.exports = CaptureVideoOptions;
-
-});
-
-// file: lib/common/plugin/CompassError.js
-define("cordova/plugin/CompassError", function(require, exports, module) {
-
-/**
- * CompassError.
- * An error code assigned by an implementation when an error has occurred
- * @constructor
- */
-var CompassError = function(err) {
- this.code = (err !== undefined ? err : null);
-};
-
-CompassError.COMPASS_INTERNAL_ERR = 0;
-CompassError.COMPASS_NOT_SUPPORTED = 20;
-
-module.exports = CompassError;
-
-});
-
-// file: lib/common/plugin/CompassHeading.js
-define("cordova/plugin/CompassHeading", function(require, exports, module) {
-
-var CompassHeading = function(magneticHeading, trueHeading, headingAccuracy, timestamp) {
- this.magneticHeading = magneticHeading;
- this.trueHeading = trueHeading;
- this.headingAccuracy = headingAccuracy;
- this.timestamp = timestamp || new Date().getTime();
-};
-
-module.exports = CompassHeading;
-
-});
-
-// file: lib/common/plugin/ConfigurationData.js
-define("cordova/plugin/ConfigurationData", function(require, exports, module) {
-
-/**
- * Encapsulates a set of parameters that the capture device supports.
- */
-function ConfigurationData() {
- // The ASCII-encoded string in lower case representing the media type.
- this.type = null;
- // The height attribute represents height of the image or video in pixels.
- // In the case of a sound clip this attribute has value 0.
- this.height = 0;
- // The width attribute represents width of the image or video in pixels.
- // In the case of a sound clip this attribute has value 0
- this.width = 0;
-}
-
-module.exports = ConfigurationData;
-
-});
-
-// file: lib/common/plugin/Connection.js
-define("cordova/plugin/Connection", function(require, exports, module) {
-
-/**
- * Network status
- */
-module.exports = {
- UNKNOWN: "unknown",
- ETHERNET: "ethernet",
- WIFI: "wifi",
- CELL_2G: "2g",
- CELL_3G: "3g",
- CELL_4G: "4g",
- CELL:"cellular",
- NONE: "none"
-};
-
-});
-
-// file: lib/common/plugin/Contact.js
-define("cordova/plugin/Contact", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- exec = require('cordova/exec'),
- ContactError = require('cordova/plugin/ContactError'),
- utils = require('cordova/utils');
-
-/**
-* Converts primitives into Complex Object
-* Currently only used for Date fields
-*/
-function convertIn(contact) {
- var value = contact.birthday;
- try {
- contact.birthday = new Date(parseFloat(value));
- } catch (exception){
- console.log("Cordova Contact convertIn error: exception creating date.");
- }
- return contact;
-}
-
-/**
-* Converts Complex objects into primitives
-* Only conversion at present is for Dates.
-**/
-
-function convertOut(contact) {
- var value = contact.birthday;
- if (value !== null) {
- // try to make it a Date object if it is not already
- if (!utils.isDate(value)){
- try {
- value = new Date(value);
- } catch(exception){
- value = null;
- }
- }
- if (utils.isDate(value)){
- value = value.valueOf(); // convert to milliseconds
- }
- contact.birthday = value;
- }
- return contact;
-}
-
-/**
-* Contains information about a single contact.
-* @constructor
-* @param {DOMString} id unique identifier
-* @param {DOMString} displayName
-* @param {ContactName} name
-* @param {DOMString} nickname
-* @param {Array.<ContactField>} phoneNumbers array of phone numbers
-* @param {Array.<ContactField>} emails array of email addresses
-* @param {Array.<ContactAddress>} addresses array of addresses
-* @param {Array.<ContactField>} ims instant messaging user ids
-* @param {Array.<ContactOrganization>} organizations
-* @param {DOMString} birthday contact's birthday
-* @param {DOMString} note user notes about contact
-* @param {Array.<ContactField>} photos
-* @param {Array.<ContactField>} categories
-* @param {Array.<ContactField>} urls contact's web sites
-*/
-var Contact = function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
- ims, organizations, birthday, note, photos, categories, urls) {
- this.id = id || null;
- this.rawId = null;
- this.displayName = displayName || null;
- this.name = name || null; // ContactName
- this.nickname = nickname || null;
- this.phoneNumbers = phoneNumbers || null; // ContactField[]
- this.emails = emails || null; // ContactField[]
- this.addresses = addresses || null; // ContactAddress[]
- this.ims = ims || null; // ContactField[]
- this.organizations = organizations || null; // ContactOrganization[]
- this.birthday = birthday || null;
- this.note = note || null;
- this.photos = photos || null; // ContactField[]
- this.categories = categories || null; // ContactField[]
- this.urls = urls || null; // ContactField[]
-};
-
-/**
-* Removes contact from device storage.
-* @param successCB success callback
-* @param errorCB error callback
-*/
-Contact.prototype.remove = function(successCB, errorCB) {
- argscheck.checkArgs('FF', 'Contact.remove', arguments);
- var fail = errorCB && function(code) {
- errorCB(new ContactError(code));
- };
- if (this.id === null) {
- fail(ContactError.UNKNOWN_ERROR);
- }
- else {
- exec(successCB, fail, "Contacts", "remove", [this.id]);
- }
-};
-
-/**
-* Creates a deep copy of this Contact.
-* With the contact ID set to null.
-* @return copy of this Contact
-*/
-Contact.prototype.clone = function() {
- var clonedContact = utils.clone(this);
- clonedContact.id = null;
- clonedContact.rawId = null;
-
- function nullIds(arr) {
- if (arr) {
- for (var i = 0; i < arr.length; ++i) {
- arr[i].id = null;
- }
- }
- }
-
- // Loop through and clear out any id's in phones, emails, etc.
- nullIds(clonedContact.phoneNumbers);
- nullIds(clonedContact.emails);
- nullIds(clonedContact.addresses);
- nullIds(clonedContact.ims);
- nullIds(clonedContact.organizations);
- nullIds(clonedContact.categories);
- nullIds(clonedContact.photos);
- nullIds(clonedContact.urls);
- return clonedContact;
-};
-
-/**
-* Persists contact to device storage.
-* @param successCB success callback
-* @param errorCB error callback
-*/
-Contact.prototype.save = function(successCB, errorCB) {
- argscheck.checkArgs('FFO', 'Contact.save', arguments);
- var fail = errorCB && function(code) {
- errorCB(new ContactError(code));
- };
- var success = function(result) {
- if (result) {
- if (successCB) {
- var fullContact = require('cordova/plugin/contacts').create(result);
- successCB(convertIn(fullContact));
- }
- }
- else {
- // no Entry object returned
- fail(ContactError.UNKNOWN_ERROR);
- }
- };
- var dupContact = convertOut(utils.clone(this));
- exec(success, fail, "Contacts", "save", [dupContact]);
-};
-
-
-module.exports = Contact;
-
-});
-
-// file: lib/common/plugin/ContactAddress.js
-define("cordova/plugin/ContactAddress", function(require, exports, module) {
-
-/**
-* Contact address.
-* @constructor
-* @param {DOMString} id unique identifier, should only be set by native code
-* @param formatted // NOTE: not a W3C standard
-* @param streetAddress
-* @param locality
-* @param region
-* @param postalCode
-* @param country
-*/
-
-var ContactAddress = function(pref, type, formatted, streetAddress, locality, region, postalCode, country) {
- this.id = null;
- this.pref = (typeof pref != 'undefined' ? pref : false);
- this.type = type || null;
- this.formatted = formatted || null;
- this.streetAddress = streetAddress || null;
- this.locality = locality || null;
- this.region = region || null;
- this.postalCode = postalCode || null;
- this.country = country || null;
-};
-
-module.exports = ContactAddress;
-
-});
-
-// file: lib/common/plugin/ContactError.js
-define("cordova/plugin/ContactError", function(require, exports, module) {
-
-/**
- * ContactError.
- * An error code assigned by an implementation when an error has occurred
- * @constructor
- */
-var ContactError = function(err) {
- this.code = (typeof err != 'undefined' ? err : null);
-};
-
-/**
- * Error codes
- */
-ContactError.UNKNOWN_ERROR = 0;
-ContactError.INVALID_ARGUMENT_ERROR = 1;
-ContactError.TIMEOUT_ERROR = 2;
-ContactError.PENDING_OPERATION_ERROR = 3;
-ContactError.IO_ERROR = 4;
-ContactError.NOT_SUPPORTED_ERROR = 5;
-ContactError.PERMISSION_DENIED_ERROR = 20;
-
-module.exports = ContactError;
-
-});
-
-// file: lib/common/plugin/ContactField.js
-define("cordova/plugin/ContactField", function(require, exports, module) {
-
-/**
-* Generic contact field.
-* @constructor
-* @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard
-* @param type
-* @param value
-* @param pref
-*/
-var ContactField = function(type, value, pref) {
- this.id = null;
- this.type = (type && type.toString()) || null;
- this.value = (value && value.toString()) || null;
- this.pref = (typeof pref != 'undefined' ? pref : false);
-};
-
-module.exports = ContactField;
-
-});
-
-// file: lib/common/plugin/ContactFindOptions.js
-define("cordova/plugin/ContactFindOptions", function(require, exports, module) {
-
-/**
- * ContactFindOptions.
- * @constructor
- * @param filter used to match contacts against
- * @param multiple boolean used to determine if more than one contact should be returned
- */
-
-var ContactFindOptions = function(filter, multiple) {
- this.filter = filter || '';
- this.multiple = (typeof multiple != 'undefined' ? multiple : false);
-};
-
-module.exports = ContactFindOptions;
-
-});
-
-// file: lib/common/plugin/ContactName.js
-define("cordova/plugin/ContactName", function(require, exports, module) {
-
-/**
-* Contact name.
-* @constructor
-* @param formatted // NOTE: not part of W3C standard
-* @param familyName
-* @param givenName
-* @param middle
-* @param prefix
-* @param suffix
-*/
-var ContactName = function(formatted, familyName, givenName, middle, prefix, suffix) {
- this.formatted = formatted || null;
- this.familyName = familyName || null;
- this.givenName = givenName || null;
- this.middleName = middle || null;
- this.honorificPrefix = prefix || null;
- this.honorificSuffix = suffix || null;
-};
-
-module.exports = ContactName;
-
-});
-
-// file: lib/common/plugin/ContactOrganization.js
-define("cordova/plugin/ContactOrganization", function(require, exports, module) {
-
-/**
-* Contact organization.
-* @constructor
-* @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard
-* @param name
-* @param dept
-* @param title
-* @param startDate
-* @param endDate
-* @param location
-* @param desc
-*/
-
-var ContactOrganization = function(pref, type, name, dept, title) {
- this.id = null;
- this.pref = (typeof pref != 'undefined' ? pref : false);
- this.type = type || null;
- this.name = name || null;
- this.department = dept || null;
- this.title = title || null;
-};
-
-module.exports = ContactOrganization;
-
-});
-
-// file: lib/common/plugin/Coordinates.js
-define("cordova/plugin/Coordinates", function(require, exports, module) {
-
-/**
- * This class contains position information.
- * @param {Object} lat
- * @param {Object} lng
- * @param {Object} alt
- * @param {Object} acc
- * @param {Object} head
- * @param {Object} vel
- * @param {Object} altacc
- * @constructor
- */
-var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
- /**
- * The latitude of the position.
- */
- this.latitude = lat;
- /**
- * The longitude of the position,
- */
- this.longitude = lng;
- /**
- * The accuracy of the position.
- */
- this.accuracy = acc;
- /**
- * The altitude of the position.
- */
- this.altitude = (alt !== undefined ? alt : null);
- /**
- * The direction the device is moving at the position.
- */
- this.heading = (head !== undefined ? head : null);
- /**
- * The velocity with which the device is moving at the position.
- */
- this.speed = (vel !== undefined ? vel : null);
-
- if (this.speed === 0 || this.speed === null) {
- this.heading = NaN;
- }
-
- /**
- * The altitude accuracy of the position.
- */
- this.altitudeAccuracy = (altacc !== undefined) ? altacc : null;
-};
-
-module.exports = Coordinates;
-
-});
-
-// file: lib/common/plugin/DirectoryEntry.js
-define("cordova/plugin/DirectoryEntry", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- utils = require('cordova/utils'),
- exec = require('cordova/exec'),
- Entry = require('cordova/plugin/Entry'),
- FileError = require('cordova/plugin/FileError'),
- DirectoryReader = require('cordova/plugin/DirectoryReader');
-
-/**
- * An interface representing a directory on the file system.
- *
- * {boolean} isFile always false (readonly)
- * {boolean} isDirectory always true (readonly)
- * {DOMString} name of the directory, excluding the path leading to it (readonly)
- * {DOMString} fullPath the absolute full path to the directory (readonly)
- * TODO: implement this!!! {FileSystem} filesystem on which the directory resides (readonly)
- */
-var DirectoryEntry = function(name, fullPath) {
- DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath);
-};
-
-utils.extend(DirectoryEntry, Entry);
-
-/**
- * Creates a new DirectoryReader to read entries from this directory
- */
-DirectoryEntry.prototype.createReader = function() {
- return new DirectoryReader(this.fullPath);
-};
-
-/**
- * Creates or looks up a directory
- *
- * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
- * @param {Flags} options to create or exclusively create the directory
- * @param {Function} successCallback is called with the new entry
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
- argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
- var win = successCallback && function(result) {
- var entry = new DirectoryEntry(result.name, result.fullPath);
- successCallback(entry);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getDirectory", [this.fullPath, path, options]);
-};
-
-/**
- * Deletes a directory and all of it's contents
- *
- * @param {Function} successCallback is called with no parameters
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(successCallback, fail, "File", "removeRecursively", [this.fullPath]);
-};
-
-/**
- * Creates or looks up a file
- *
- * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
- * @param {Flags} options to create or exclusively create the file
- * @param {Function} successCallback is called with the new entry
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
- argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
- var win = successCallback && function(result) {
- var FileEntry = require('cordova/plugin/FileEntry');
- var entry = new FileEntry(result.name, result.fullPath);
- successCallback(entry);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getFile", [this.fullPath, path, options]);
-};
-
-module.exports = DirectoryEntry;
-
-});
-
-// file: lib/common/plugin/DirectoryReader.js
-define("cordova/plugin/DirectoryReader", function(require, exports, module) {
-
-var exec = require('cordova/exec'),
- FileError = require('cordova/plugin/FileError') ;
-
-/**
- * An interface that lists the files and directories in a directory.
- */
-function DirectoryReader(path) {
- this.path = path || null;
-}
-
-/**
- * Returns a list of entries from a directory.
- *
- * @param {Function} successCallback is called with a list of entries
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
- var win = typeof successCallback !== 'function' ? null : function(result) {
- var retVal = [];
- for (var i=0; i<result.length; i++) {
- var entry = null;
- if (result[i].isDirectory) {
- entry = new (require('cordova/plugin/DirectoryEntry'))();
- }
- else if (result[i].isFile) {
- entry = new (require('cordova/plugin/FileEntry'))();
- }
- entry.isDirectory = result[i].isDirectory;
- entry.isFile = result[i].isFile;
- entry.name = result[i].name;
- entry.fullPath = result[i].fullPath;
- retVal.push(entry);
- }
- successCallback(retVal);
- };
- var fail = typeof errorCallback !== 'function' ? null : function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "readEntries", [this.path]);
-};
-
-module.exports = DirectoryReader;
-
-});
-
-// file: lib/common/plugin/Entry.js
-define("cordova/plugin/Entry", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- exec = require('cordova/exec'),
- FileError = require('cordova/plugin/FileError'),
- Metadata = require('cordova/plugin/Metadata');
-
-/**
- * Represents a file or directory on the local file system.
- *
- * @param isFile
- * {boolean} true if Entry is a file (readonly)
- * @param isDirectory
- * {boolean} true if Entry is a directory (readonly)
- * @param name
- * {DOMString} name of the file or directory, excluding the path
- * leading to it (readonly)
- * @param fullPath
- * {DOMString} the absolute full path to the file or directory
- * (readonly)
- */
-function Entry(isFile, isDirectory, name, fullPath, fileSystem) {
- this.isFile = !!isFile;
- this.isDirectory = !!isDirectory;
- this.name = name || '';
- this.fullPath = fullPath || '';
- this.filesystem = fileSystem || null;
-}
-
-/**
- * Look up the metadata of the entry.
- *
- * @param successCallback
- * {Function} is called with a Metadata object
- * @param errorCallback
- * {Function} is called with a FileError
- */
-Entry.prototype.getMetadata = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'Entry.getMetadata', arguments);
- var success = successCallback && function(lastModified) {
- var metadata = new Metadata(lastModified);
- successCallback(metadata);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
-
- exec(success, fail, "File", "getMetadata", [this.fullPath]);
-};
-
-/**
- * Set the metadata of the entry.
- *
- * @param successCallback
- * {Function} is called with a Metadata object
- * @param errorCallback
- * {Function} is called with a FileError
- * @param metadataObject
- * {Object} keys and values to set
- */
-Entry.prototype.setMetadata = function(successCallback, errorCallback, metadataObject) {
- argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments);
- exec(successCallback, errorCallback, "File", "setMetadata", [this.fullPath, metadataObject]);
-};
-
-/**
- * Move a file or directory to a new location.
- *
- * @param parent
- * {DirectoryEntry} the directory to which to move this entry
- * @param newName
- * {DOMString} new name of the entry, defaults to the current name
- * @param successCallback
- * {Function} called with the new DirectoryEntry object
- * @param errorCallback
- * {Function} called with a FileError
- */
-Entry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
- argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- // source path
- var srcPath = this.fullPath,
- // entry name
- name = newName || this.name,
- success = function(entry) {
- if (entry) {
- if (successCallback) {
- // create appropriate Entry object
- var result = (entry.isDirectory) ? new (require('cordova/plugin/DirectoryEntry'))(entry.name, entry.fullPath) : new (require('cordova/plugin/FileEntry'))(entry.name, entry.fullPath);
- successCallback(result);
- }
- }
- else {
- // no Entry object returned
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- // copy
- exec(success, fail, "File", "moveTo", [srcPath, parent.fullPath, name]);
-};
-
-/**
- * Copy a directory to a different location.
- *
- * @param parent
- * {DirectoryEntry} the directory to which to copy the entry
- * @param newName
- * {DOMString} new name of the entry, defaults to the current name
- * @param successCallback
- * {Function} called with the new Entry object
- * @param errorCallback
- * {Function} called with a FileError
- */
-Entry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
- argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
-
- // source path
- var srcPath = this.fullPath,
- // entry name
- name = newName || this.name,
- // success callback
- success = function(entry) {
- if (entry) {
- if (successCallback) {
- // create appropriate Entry object
- var result = (entry.isDirectory) ? new (require('cordova/plugin/DirectoryEntry'))(entry.name, entry.fullPath) : new (require('cordova/plugin/FileEntry'))(entry.name, entry.fullPath);
- successCallback(result);
- }
- }
- else {
- // no Entry object returned
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- // copy
- exec(success, fail, "File", "copyTo", [srcPath, parent.fullPath, name]);
-};
-
-/**
- * Return a URL that can be used to identify this entry.
- */
-Entry.prototype.toURL = function() {
- // fullPath attribute contains the full URL
- return this.fullPath;
-};
-
-/**
- * Returns a URI that can be used to identify this entry.
- *
- * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
- * @return uri
- */
-Entry.prototype.toURI = function(mimeType) {
- console.log("DEPRECATED: Update your code to use 'toURL'");
- // fullPath attribute contains the full URI
- return this.toURL();
-};
-
-/**
- * Remove a file or directory. It is an error to attempt to delete a
- * directory that is not empty. It is an error to attempt to delete a
- * root directory of a file system.
- *
- * @param successCallback {Function} called with no parameters
- * @param errorCallback {Function} called with a FileError
- */
-Entry.prototype.remove = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'Entry.remove', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(successCallback, fail, "File", "remove", [this.fullPath]);
-};
-
-/**
- * Look up the parent DirectoryEntry of this entry.
- *
- * @param successCallback {Function} called with the parent DirectoryEntry object
- * @param errorCallback {Function} called with a FileError
- */
-Entry.prototype.getParent = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'Entry.getParent', arguments);
- var win = successCallback && function(result) {
- var DirectoryEntry = require('cordova/plugin/DirectoryEntry');
- var entry = new DirectoryEntry(result.name, result.fullPath);
- successCallback(entry);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getParent", [this.fullPath]);
-};
-
-module.exports = Entry;
-
-});
-
-// file: lib/common/plugin/File.js
-define("cordova/plugin/File", function(require, exports, module) {
-
-/**
- * Constructor.
- * name {DOMString} name of the file, without path information
- * fullPath {DOMString} the full path of the file, including the name
- * type {DOMString} mime type
- * lastModifiedDate {Date} last modified date
- * size {Number} size of the file in bytes
- */
-
-var File = function(name, fullPath, type, lastModifiedDate, size){
- this.name = name || '';
- this.fullPath = fullPath || null;
- this.type = type || null;
- this.lastModifiedDate = lastModifiedDate || null;
- this.size = size || 0;
-
- // These store the absolute start and end for slicing the file.
- this.start = 0;
- this.end = this.size;
-};
-
-/**
- * Returns a "slice" of the file. Since Cordova Files don't contain the actual
- * content, this really returns a File with adjusted start and end.
- * Slices of slices are supported.
- * start {Number} The index at which to start the slice (inclusive).
- * end {Number} The index at which to end the slice (exclusive).
- */
-File.prototype.slice = function(start, end) {
- var size = this.end - this.start;
- var newStart = 0;
- var newEnd = size;
- if (arguments.length) {
- if (start < 0) {
- newStart = Math.max(size + start, 0);
- } else {
- newStart = Math.min(size, start);
- }
- }
-
- if (arguments.length >= 2) {
- if (end < 0) {
- newEnd = Math.max(size + end, 0);
- } else {
- newEnd = Math.min(end, size);
- }
- }
-
- var newFile = new File(this.name, this.fullPath, this.type, this.lastModifiedData, this.size);
- newFile.start = this.start + newStart;
- newFile.end = this.start + newEnd;
- return newFile;
-};
-
-
-module.exports = File;
-
-});
-
-// file: lib/common/plugin/FileEntry.js
-define("cordova/plugin/FileEntry", function(require, exports, module) {
-
-var utils = require('cordova/utils'),
- exec = require('cordova/exec'),
- Entry = require('cordova/plugin/Entry'),
- FileWriter = require('cordova/plugin/FileWriter'),
- File = require('cordova/plugin/File'),
- FileError = require('cordova/plugin/FileError');
-
-/**
- * An interface representing a file on the file system.
- *
- * {boolean} isFile always true (readonly)
- * {boolean} isDirectory always false (readonly)
- * {DOMString} name of the file, excluding the path leading to it (readonly)
- * {DOMString} fullPath the absolute full path to the file (readonly)
- * {FileSystem} filesystem on which the file resides (readonly)
- */
-var FileEntry = function(name, fullPath) {
- FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath]);
-};
-
-utils.extend(FileEntry, Entry);
-
-/**
- * Creates a new FileWriter associated with the file that this FileEntry represents.
- *
- * @param {Function} successCallback is called with the new FileWriter
- * @param {Function} errorCallback is called with a FileError
- */
-FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
- this.file(function(filePointer) {
- var writer = new FileWriter(filePointer);
-
- if (writer.fileName === null || writer.fileName === "") {
- errorCallback && errorCallback(new FileError(FileError.INVALID_STATE_ERR));
- } else {
- successCallback && successCallback(writer);
- }
- }, errorCallback);
-};
-
-/**
- * Returns a File that represents the current state of the file that this FileEntry represents.
- *
- * @param {Function} successCallback is called with the new File object
- * @param {Function} errorCallback is called with a FileError
- */
-FileEntry.prototype.file = function(successCallback, errorCallback) {
- var win = successCallback && function(f) {
- var file = new File(f.name, f.fullPath, f.type, f.lastModifiedDate, f.size);
- successCallback(file);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getFileMetadata", [this.fullPath]);
-};
-
-
-module.exports = FileEntry;
-
-});
-
-// file: lib/common/plugin/FileError.js
-define("cordova/plugin/FileError", function(require, exports, module) {
-
-/**
- * FileError
- */
-function FileError(error) {
- this.code = error || null;
-}
-
-// File error codes
-// Found in DOMException
-FileError.NOT_FOUND_ERR = 1;
-FileError.SECURITY_ERR = 2;
-FileError.ABORT_ERR = 3;
-
-// Added by File API specification
-FileError.NOT_READABLE_ERR = 4;
-FileError.ENCODING_ERR = 5;
-FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
-FileError.INVALID_STATE_ERR = 7;
-FileError.SYNTAX_ERR = 8;
-FileError.INVALID_MODIFICATION_ERR = 9;
-FileError.QUOTA_EXCEEDED_ERR = 10;
-FileError.TYPE_MISMATCH_ERR = 11;
-FileError.PATH_EXISTS_ERR = 12;
-
-module.exports = FileError;
-
-});
-
-// file: lib/common/plugin/FileReader.js
-define("cordova/plugin/FileReader", function(require, exports, module) {
-
-var exec = require('cordova/exec'),
- modulemapper = require('cordova/modulemapper'),
- utils = require('cordova/utils'),
- File = require('cordova/plugin/File'),
- FileError = require('cordova/plugin/FileError'),
- ProgressEvent = require('cordova/plugin/ProgressEvent'),
- origFileReader = modulemapper.getOriginalSymbol(this, 'FileReader');
-
-/**
- * This class reads the mobile device file system.
- *
- * For Android:
- * The root directory is the root of the file system.
- * To read from the SD card, the file name is "sdcard/my_file.txt"
- * @constructor
- */
-var FileReader = function() {
- this._readyState = 0;
- this._error = null;
- this._result = null;
- this._fileName = '';
- this._realReader = origFileReader ? new origFileReader() : {};
-};
-
-// States
-FileReader.EMPTY = 0;
-FileReader.LOADING = 1;
-FileReader.DONE = 2;
-
-utils.defineGetter(FileReader.prototype, 'readyState', function() {
- return this._fileName ? this._readyState : this._realReader.readyState;
-});
-
-utils.defineGetter(FileReader.prototype, 'error', function() {
- return this._fileName ? this._error: this._realReader.error;
-});
-
-utils.defineGetter(FileReader.prototype, 'result', function() {
- return this._fileName ? this._result: this._realReader.result;
-});
-
-function defineEvent(eventName) {
- utils.defineGetterSetter(FileReader.prototype, eventName, function() {
- return this._realReader[eventName] || null;
- }, function(value) {
- this._realReader[eventName] = value;
- });
-}
-defineEvent('onloadstart'); // When the read starts.
-defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total)
-defineEvent('onload'); // When the read has successfully completed.
-defineEvent('onerror'); // When the read has failed (see errors).
-defineEvent('onloadend'); // When the request has completed (either in success or failure).
-defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method.
-
-function initRead(reader, file) {
- // Already loading something
- if (reader.readyState == FileReader.LOADING) {
- throw new FileError(FileError.INVALID_STATE_ERR);
- }
-
- reader._result = null;
- reader._error = null;
- reader._readyState = FileReader.LOADING;
-
- if (typeof file == 'string') {
- // Deprecated in Cordova 2.4.
- console.warn('Using a string argument with FileReader.readAs functions is deprecated.');
- reader._fileName = file;
- } else if (typeof file.fullPath == 'string') {
- reader._fileName = file.fullPath;
- } else {
- reader._fileName = '';
- return true;
- }
-
- reader.onloadstart && reader.onloadstart(new ProgressEvent("loadstart", {target:reader}));
-}
-
-/**
- * Abort reading file.
- */
-FileReader.prototype.abort = function() {
- if (origFileReader && !this._fileName) {
- return this._realReader.abort();
- }
- this._result = null;
-
- if (this._readyState == FileReader.DONE || this._readyState == FileReader.EMPTY) {
- return;
- }
-
- this._readyState = FileReader.DONE;
-
- // If abort callback
- if (typeof this.onabort === 'function') {
- this.onabort(new ProgressEvent('abort', {target:this}));
- }
- // If load end callback
- if (typeof this.onloadend === 'function') {
- this.onloadend(new ProgressEvent('loadend', {target:this}));
- }
-};
-
-/**
- * Read text file.
- *
- * @param file {File} File object containing file properties
- * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)
- */
-FileReader.prototype.readAsText = function(file, encoding) {
- if (initRead(this, file)) {
- return this._realReader.readAsText(file, encoding);
- }
-
- // Default encoding is UTF-8
- var enc = encoding ? encoding : "UTF-8";
- var me = this;
- var execArgs = [this._fileName, enc, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // Save result
- me._result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", {target:me}));
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- },
- // Error callback
- function(e) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- // null result
- me._result = null;
-
- // Save error
- me._error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- }, "File", "readAsText", execArgs);
-};
-
-
-/**
- * Read file and return data as a base64 encoded data url.
- * A data url is of the form:
- * data:[<mediatype>][;base64],<data>
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsDataURL = function(file) {
- if (initRead(this, file)) {
- return this._realReader.readAsDataURL(file);
- }
-
- var me = this;
- var execArgs = [this._fileName, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- // Save result
- me._result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- },
- // Error callback
- function(e) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = null;
-
- // Save error
- me._error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- }, "File", "readAsDataURL", execArgs);
-};
-
-/**
- * Read file and return data as a binary data.
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsBinaryString = function(file) {
- if (initRead(this, file)) {
- return this._realReader.readAsBinaryString(file);
- }
-
- var me = this;
- var execArgs = [this._fileName, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- },
- // Error callback
- function(e) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = null;
-
- // Save error
- me._error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- }, "File", "readAsBinaryString", execArgs);
-};
-
-/**
- * Read file and return data as a binary data.
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsArrayBuffer = function(file) {
- if (initRead(this, file)) {
- return this._realReader.readAsArrayBuffer(file);
- }
-
- var me = this;
- var execArgs = [this._fileName, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- },
- // Error callback
- function(e) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- me._result = null;
-
- // Save error
- me._error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", {target:me}));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", {target:me}));
- }
- }, "File", "readAsArrayBuffer", execArgs);
-};
-
-module.exports = FileReader;
-
-});
-
-// file: lib/common/plugin/FileSystem.js
-define("cordova/plugin/FileSystem", function(require, exports, module) {
-
-var DirectoryEntry = require('cordova/plugin/DirectoryEntry');
-
-/**
- * An interface representing a file system
- *
- * @constructor
- * {DOMString} name the unique name of the file system (readonly)
- * {DirectoryEntry} root directory of the file system (readonly)
- */
-var FileSystem = function(name, root) {
- this.name = name || null;
- if (root) {
- this.root = new DirectoryEntry(root.name, root.fullPath);
- }
-};
-
-module.exports = FileSystem;
-
-});
-
-// file: lib/common/plugin/FileTransfer.js
-define("cordova/plugin/FileTransfer", function(require, exports, module) {
-
-var argscheck = require('cordova/argscheck'),
- exec = require('cordova/exec'),
- FileTransferError = require('cordova/plugin/FileTransferError'),
- ProgressEvent = require('cordova/plugin/ProgressEvent');
-
-function newProgressEvent(result) {
- var pe = new ProgressEvent();
- pe.lengthComputable = result.lengthComputable;
- pe.loaded = result.loaded;
- pe.total = result.total;
- return pe;
-}
-
-function getBasicAuthHeader(urlString) {
- var header = null;
-
- if (window.btoa) {
- // parse the url using the Location object
- var url = document.createElement('a');
- url.href = urlString;
-
- var credentials = null;
- var protocol = url.protocol + "//";
- var origin = protocol + url.host;
-
- // check whether there are the username:password credentials in the url
- if (url.href.indexOf(origin) !== 0) { // credentials found
- var atIndex = url.href.indexOf("@");
- credentials = url.href.substring(protocol.length, atIndex);
- }
-
- if (credentials) {
- var authHeader = "Authorization";
- var authHeaderValue = "Basic " + window.btoa(credentials);
-
- header = {
- name : authHeader,
- value : authHeaderValue
- };
- }
- }
-
- return header;
-}
-
-var idCounter = 0;
-
-/**
- * FileTransfer uploads a file to a remote server.
- * @constructor
- */
-var FileTransfer = function() {
- this._id = ++idCounter;
- this.onprogress = null; // optional callback
-};
-
-/**
-* Given an absolute file path, uploads a file on the device to a remote server
-* using a multipart HTTP request.
-* @param filePath {String} Full path of the file on the device
-* @param server {String} URL of the server to receive the file
-* @param successCallback (Function} Callback to be invoked when upload has completed
-* @param errorCallback {Function} Callback to be invoked upon error
-* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
-* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
-*/
-FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
- argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
- // check for options
- var fileKey = null;
- var fileName = null;
- var mimeType = null;
- var params = null;
- var chunkedMode = true;
- var headers = null;
- var httpMethod = null;
- var basicAuthHeader = getBasicAuthHeader(server);
- if (basicAuthHeader) {
- options = options || {};
- options.headers = options.headers || {};
- options.headers[basicAuthHeader.name] = basicAuthHeader.value;
- }
-
- if (options) {
- fileKey = options.fileKey;
- fileName = options.fileName;
- mimeType = options.mimeType;
- headers = options.headers;
- httpMethod = options.httpMethod || "POST";
- if (httpMethod.toUpperCase() == "PUT"){
- httpMethod = "PUT";
- } else {
- httpMethod = "POST";
- }
- if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
- chunkedMode = options.chunkedMode;
- }
- if (options.params) {
- params = options.params;
- }
- else {
- params = {};
- }
- }
-
- var fail = errorCallback && function(e) {
- var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body);
- errorCallback(error);
- };
-
- var self = this;
- var win = function(result) {
- if (typeof result.lengthComputable != "undefined") {
- if (self.onprogress) {
- self.onprogress(newProgressEvent(result));
- }
- } else {
- successCallback && successCallback(result);
- }
- };
- exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
-};
-
-/**
- * Downloads a file form a given URL and saves it to the specified directory.
- * @param source {String} URL of the server to receive the file
- * @param target {String} Full path of the file on the device
- * @param successCallback (Function} Callback to be invoked when upload has completed
- * @param errorCallback {Function} Callback to be invoked upon error
- * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
- * @param options {FileDownloadOptions} Optional parameters such as headers
- */
-FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
- argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
- var self = this;
-
- var basicAuthHeader = getBasicAuthHeader(source);
- if (basicAuthHeader) {
- options = options || {};
- options.headers = options.headers || {};
- options.headers[basicAuthHeader.name] = basicAuthHeader.value;
- }
-
- var headers = null;
- if (options) {
- headers = options.headers || null;
- }
-
- var win = function(result) {
- if (typeof result.lengthComputable != "undefined") {
- if (self.onprogress) {
- return self.onprogress(newProgressEvent(result));
- }
- } else if (successCallback) {
- var entry = null;
- if (result.isDirectory) {
- entry = new (require('cordova/plugin/DirectoryEntry'))();
- }
- else if (result.isFile) {
- entry = new (require('cordova/plugin/FileEntry'))();
- }
- entry.isDirectory = result.isDirectory;
- entry.isFile = result.isFile;
- entry.name = result.name;
- entry.fullPath = result.fullPath;
- successCallback(entry);
- }
- };
-
- var fail = errorCallback && function(e) {
- var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body);
-
<TRUNCATED>
[27/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/run
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/run b/lib/cordova-blackberry/bin/templates/project/cordova/lib/run
new file mode 100755
index 0000000..d6b4b9c
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/run
@@ -0,0 +1,204 @@
+#!/usr/bin/env node
+
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var childProcess = require("child_process"),
+ fs = require("fs"),
+ path = require("path"),
+ util = require("util"),
+ wrench = require("wrench"),
+ conf = require("./conf"),
+ localize = require("./localize"),
+ pkgrUtils = require("./packager-utils"),
+ properties = require('../../project.json'),
+ program = require('commander'),
+ xml2js = require('xml2js'),
+ target,
+ ip,
+ password,
+ workingdir,
+ barPath;
+
+function generateOptions(uninstall) {
+ var options = [];
+
+ workingdir = path.normalize(__dirname + "/.."),
+ barPath = path.normalize(__dirname + "/../../build/" + properties.targets[target].type + "/" + properties.barName + ".bar");
+
+ options.push("-device");
+ options.push(ip);
+
+ if (password) {
+ options.push("-password");
+ options.push(password);
+ }
+
+ options.push("-package");
+ options.push(barPath);
+
+ if (uninstall) {
+ options.push("-uninstallApp");
+ return options;
+ } else {
+
+ options.push("-installApp");
+
+ if (program.launch) {
+ options.push("-launchApp");
+ }
+
+ return options;
+ }
+}
+
+function execNativeDeploy(optionsArray, callback) {
+ var script = "/bin/blackberry-deploy",
+ nativeDeploy;
+ options = optionsArray.join(" ");
+
+ if (pkgrUtils.isWindows()) {
+ script += ".bat";
+ }
+
+ if (fs.existsSync(conf.DEPENDENCIES_TOOLS)) {
+ nativeDeploy = childProcess.exec(path.normalize(conf.DEPENDENCIES_TOOLS + script +" "+ options), {
+ "cwd": workingdir,
+ "env": process.env
+ });
+
+ nativeDeploy.stdout.on("data", pkgrUtils.handleProcessOutput);
+
+ nativeDeploy.stderr.on("data", pkgrUtils.handleProcessOutput);
+
+ nativeDeploy.on("exit", function (code) {
+ if (callback && typeof callback === "function") {
+ callback(code);
+ }
+ });
+ } else {
+ throw localize.translate("EXCEPTION_MISSING_TOOLS");
+ }
+}
+
+function checkTarget() {
+ if (!target) {
+ console.log("No target exists, to add that target please run target add <name> <ip> [-t | --type <device | simulator>] [-p <password>] [--pin <devicepin>]\n");
+ return false;
+ }
+ if (!properties.targets[target]) {
+ console.log("The target \""+target+"\" does not exist, to add that target please run target add "+target+" <ip> [-t | --type <device | simulator>] [-p <password>] [--pin <devicepin>]\n");
+ return false;
+ }
+ if (properties.targets[target].ip) {
+ ip = properties.targets[target].ip;
+ } else {
+ console.log("IP is not defined in target \""+target+"\"\n");
+ return false;
+ }
+ if (properties.targets[target].password) {
+ password = properties.targets[target].password;
+ }
+ return true;
+
+}
+
+function deployAll(keys) {
+ target = keys[0];
+
+ if (target) {
+ if (checkTarget()) {
+ var options = generateOptions();
+ if (program.uninstall) {
+ uninstall(
+ function() {
+ keys.shift();
+ deployAll(keys);
+ });
+ } else {
+ execNativeDeploy(options,
+ function() {
+ deployAll(keys);
+ });
+ }
+ }
+ }
+}
+
+function uninstall(callback) {
+ var script = "/bin/blackberry-deploy",
+ nativeDeploy;
+
+ if (pkgrUtils.isWindows()) {
+ script += ".bat";
+ }
+
+ if (fs.existsSync(conf.DEPENDENCIES_TOOLS)) {
+ nativeDeploy = childProcess.exec(path.normalize(conf.DEPENDENCIES_TOOLS + script +" -listInstalledApps -device " +ip+ " -password " +password), {
+ "cwd": workingdir,
+ "env": process.env
+ }, function (error, stdout, stderr) {
+ var parser = new xml2js.Parser();
+ fs.readFile(path.join(__dirname + "/../../www/", "config.xml"), function(err, data) {
+ parser.parseString(data, function (err, result) {
+ if (stdout.indexOf(result['@'].id) != -1) {
+ var options = generateOptions(true);
+ execNativeDeploy(options,
+ function(){
+ options = generateOptions(false);
+ execNativeDeploy(options, callback);
+ });
+ } else {
+ options = generateOptions(false);
+ execNativeDeploy(options, callback);
+ }
+ });
+ });
+ });
+ }
+}
+
+function exec(callback) {
+ program
+ .usage('command [<target>] [--no-launch] [--no-uninstall]')
+ .option('--no-uninstall', 'does not uninstall app from device')
+ .option('--no-launch', 'do not launch the app on device')
+
+ program
+ .command('all')
+ .usage('all [--no-launch] [--no-uninstall]')
+ .description(' Deploy the app on all targets')
+ .option('--no-uninstall', 'does not uninstall app from device')
+ .option('--no-launch', 'do not launch the app on device')
+
+ program.parse(process.argv);
+ target = program.args[0] ? program.args[0] : properties.defaultTarget
+
+ if (target === "all") {
+ deployAll(Object.keys(properties.targets));
+ } else {
+ if (checkTarget()) {
+ if (program.uninstall) {
+ uninstall(callback);
+ } else {
+ options = generateOptions(false);
+ execNativeDeploy(options, callback)
+ }
+ }
+ }
+}
+
+exec(null);
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/session.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/session.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/session.js
new file mode 100644
index 0000000..bb9fa06
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/session.js
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var path = require("path"),
+ fs = require("fs"),
+ wrench = require("wrench"),
+ logger = require("./logger"),
+ signingHelper = require("./signing-helper"),
+ barConf = require("./bar-conf"),
+ localize = require("./localize"),
+ params;
+
+function getParams(cmdline, toolName) {
+ if (cmdline.params) {
+ if (!params) {
+ var paramsPath = path.resolve(cmdline.params);
+
+ if (fs.existsSync(paramsPath)) {
+ try {
+ params = require(paramsPath);
+ } catch (e) {
+ throw localize.translate("EXCEPTION_PARAMS_FILE_ERROR", paramsPath);
+ }
+ } else {
+ throw localize.translate("EXCEPTION_PARAMS_FILE_NOT_FOUND", paramsPath);
+ }
+ }
+
+ if (params) {
+ return params[toolName];
+ }
+ }
+
+ return null;
+}
+
+
+module.exports = {
+ initialize: function (cmdline) {
+ var sourceDir,
+ signingPassword,
+ outputDir = cmdline.output,
+ properties = require("../../project.json"),
+ archivePath = path.resolve(cmdline.args[0]),
+ archiveName = properties.barName ? properties.barName : path.basename(archivePath, '.zip'),
+ appdesc,
+ buildId = cmdline.buildId;
+
+ //If -o option was not provided, default output location is the same as .zip
+ outputDir = outputDir || path.dirname(archivePath);
+
+ //Only set signingPassword if it contains a value
+ if (cmdline.password && "string" === typeof cmdline.password) {
+ signingPassword = cmdline.password;
+ }
+
+ if (cmdline.appdesc && "string" === typeof cmdline.appdesc) {
+ appdesc = path.resolve(cmdline.appdesc);
+ }
+
+ //If -s [dir] is provided
+ if (cmdline.source && "string" === typeof cmdline.source) {
+ sourceDir = cmdline.source + "/src";
+ } else {
+ sourceDir = outputDir + "/src";
+ }
+
+ if (!fs.existsSync(sourceDir)) {
+ wrench.mkdirSyncRecursive(sourceDir, "0755");
+ }
+
+ logger.level(cmdline.loglevel || 'verbose');
+
+ return {
+ "conf": require("./conf"),
+ "keepSource": !!cmdline.source,
+ "sourceDir": path.resolve(sourceDir),
+ "sourcePaths": {
+ "ROOT": path.resolve(sourceDir),
+ "CHROME": path.normalize(path.resolve(sourceDir) + barConf.CHROME),
+ "LIB": path.normalize(path.resolve(sourceDir) + barConf.LIB),
+ "EXT": path.normalize(path.resolve(sourceDir) + barConf.EXT),
+ "UI": path.normalize(path.resolve(sourceDir) + barConf.UI),
+ "PLUGINS": path.normalize(path.resolve(sourceDir) + barConf.PLUGINS),
+ "JNEXT_PLUGINS": path.normalize(path.resolve(sourceDir) + barConf.JNEXT_PLUGINS)
+ },
+ "outputDir": path.resolve(outputDir),
+ "archivePath": archivePath,
+ "archiveName": archiveName,
+ "barPath": outputDir + "/%s/" + archiveName + ".bar",
+ "debug": !!cmdline.debug,
+ "keystore": signingHelper.getKeyStorePath(),
+ "keystoreCsk": signingHelper.getCskPath(),
+ "keystoreDb": signingHelper.getDbPath(),
+ "storepass": signingPassword,
+ "buildId": buildId,
+ "appdesc" : appdesc,
+ getParams: function (toolName) {
+ return getParams(cmdline, toolName);
+ },
+ isSigningRequired: function (config) {
+ return signingHelper.getKeyStorePath() && signingPassword && config.buildId;
+ },
+ "targets": ["simulator", "device"]
+ };
+ }
+};
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/signing-helper.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/signing-helper.js b/lib/cordova-blackberry/bin/templates/project/cordova/lib/signing-helper.js
new file mode 100644
index 0000000..d0daafd
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/signing-helper.js
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var path = require('path'),
+ fs = require("fs"),
+ os = require('os'),
+ childProcess = require("child_process"),
+ util = require("util"),
+ conf = require("./conf"),
+ pkgrUtils = require("./packager-utils"),
+ logger = require("./logger"),
+ AUTHOR_P12 = "author.p12",
+ CSK = "barsigner.csk",
+ DB = "barsigner.db",
+ _self;
+
+function getDefaultPath(file) {
+ // The default location where signing key files are stored will vary based on the OS:
+ // Windows XP: %HOMEPATH%\Local Settings\Application Data\Research In Motion
+ // Windows Vista and Windows 7: %HOMEPATH%\AppData\Local\Research In Motion
+ // Mac OS: ~/Library/Research In Motion
+ // UNIX or Linux: ~/.rim
+ var p = "";
+ if (os.type().toLowerCase().indexOf("windows") >= 0) {
+ // Try Windows XP location
+ p = process.env.HOMEDRIVE + process.env.HOMEPATH + "\\Local Settings\\Application Data\\Research In Motion\\" + file;
+ if (fs.existsSync(p)) {
+ return p;
+ }
+
+ // Try Windows Vista and Windows 7 location
+ p = process.env.HOMEDRIVE + process.env.HOMEPATH + "\\AppData\\Local\\Research In Motion\\" + file;
+ if (fs.existsSync(p)) {
+ return p;
+ }
+ } else if (os.type().toLowerCase().indexOf("darwin") >= 0) {
+ // Try Mac OS location
+ p = process.env.HOME + "/Library/Research In Motion/" + file;
+ if (fs.existsSync(p)) {
+ return p;
+ }
+ } else if (os.type().toLowerCase().indexOf("linux") >= 0) {
+ // Try Linux location
+ p = process.env.HOME + "/.rim/" + file;
+ if (fs.existsSync(p)) {
+ return p;
+ }
+ }
+}
+
+function execSigner(session, target, callback) {
+ var script = "blackberry-signer",
+ cwd = path.normalize(conf.DEPENDENCIES_TOOLS + "/bin/"),
+ signer,
+ params = session.getParams("blackberry-signer"),
+ args = [];
+
+ if (pkgrUtils.isWindows()) {
+ script += ".bat";
+ } else {
+ // add path to executable to work around issue with node
+ script = cwd + script;
+ }
+
+ args.push("-keystore");
+ args.push(session.keystore);
+ args.push("-storepass");
+ args.push(session.storepass);
+
+ if (params) {
+ Object.getOwnPropertyNames(params).forEach(function (p) {
+ args.push(p);
+
+ if (params[p]) {
+ args.push(params[p]);
+ }
+ });
+ }
+
+ args.push(path.resolve(util.format(session.barPath, target)));
+
+ signer = childProcess.spawn(script, args, {
+ "cwd": cwd,
+ "env": process.env
+ });
+
+ signer.stdout.on("data", pkgrUtils.handleProcessOutput);
+
+ signer.stderr.on("data", pkgrUtils.handleProcessOutput);
+
+ signer.on("exit", function (code) {
+ if (callback && typeof callback === "function") {
+ callback(code);
+ }
+ });
+}
+
+_self = {
+ getKeyStorePath : function () {
+ // Todo: decide where to put sigtool.p12 which is genereated and used in WebWorks SDK for Tablet OS
+ return getDefaultPath(AUTHOR_P12);
+ },
+
+ getCskPath : function () {
+ return getDefaultPath(CSK);
+ },
+
+ getDbPath : function () {
+ return getDefaultPath(DB);
+ },
+
+ execSigner: execSigner
+};
+
+module.exports = _self;
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/lib/target
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/lib/target b/lib/cordova-blackberry/bin/templates/project/cordova/lib/target
new file mode 100644
index 0000000..c21e6c7
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/lib/target
@@ -0,0 +1,189 @@
+#!/usr/bin/env node
+/*
+ * Copyright 2013 Research In Motion Limited.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var path = require('path'),
+ propertiesFile = path.resolve(path.join(__dirname, '..', '..', 'project.json')),
+ properties = require(propertiesFile),
+ fs = require('fs'),
+ commander = require('commander'),
+ command,
+ name,
+ ip,
+ type,
+ password,
+ pin,
+ pinRegex = new RegExp("[0-9A-Fa-f]{8}");
+
+function writeProjectFile(contents, file) {
+ fs.writeFile(file, contents, 'utf-8', function (err) {
+ if (err) console.log("Error updating project.json :(\n" + err);
+ process.exit();
+ });
+}
+
+function isValidIp(ip) {
+ var num,
+ result = true,
+ ipArray;
+
+ if (typeof ip !== 'string') {
+ throw "IP is required";
+ } else {
+ ipArray = ip.split('.');
+ if (ipArray.length !== 4) {
+ result = false;
+ }
+ ipArray.forEach(function (quadrant) {
+ num = Number(quadrant);
+ if (isNaN(num) || (num < 0) || (num > 255)) {
+ result = false;
+ }
+ });
+ }
+ return result;
+}
+
+function isValidType(type) {
+ var result = true;
+
+ if (typeof type !== 'string') {
+ throw "target type is required";
+ }
+ else if (!(type === 'device' || type === 'simulator')) {
+ result = false;
+ }
+ return result;
+}
+
+function isValidPin(pin) {
+ var result = true;
+ if (typeof pin !== 'undefined' && !pinRegex.test(pin)) {
+ result = false;
+ }
+ return result;
+}
+
+commander
+ .usage('[command] [params]')
+ .option('-p, --password <password>', 'Specifies password for this target')
+ .option('--pin <devicepin>', 'Specifies PIN for this device')
+ .option('-t, --type <device | simulator>', 'Specifies the target type');
+
+commander
+ .on('--help', function () {
+ console.log(' Synopsis:');
+ console.log(' $ target');
+ console.log(' $ target add <name> <ip> [-t | --type <device | simulator>] [-p | --password <password>] [--pin <devicepin>]');
+ console.log(' $ target remove <name>');
+ console.log(' $ target default [name]');
+ console.log(' ');
+ });
+
+commander
+ .command('add')
+ .description("Add specified target")
+ .action(function () {
+ if (commander.args.length === 1) {
+ throw "Target details not specified";
+ }
+ name = commander.args[0];
+ ip = commander.args[1];
+ type = commander.type ? commander.type : "device";
+ if (commander.password && typeof commander.password === 'string') {
+ password = commander.password;
+ }
+ if (commander.pin && typeof commander.pin === 'string') {
+ pin = commander.pin;
+ }
+ if (!isValidIp(ip)) {
+ throw "Invalid IP: " + ip;
+ }
+ if (!isValidType(type)) {
+ throw "Invalid target type: " + type;
+ }
+ if (!isValidPin(pin)) {
+ throw "Invalid PIN: " + pin;
+ }
+ if (properties.targets.hasOwnProperty(name)) {
+ console.log("Overwriting target: " + name);
+ }
+ properties.targets[name] = {"ip": ip, "type": type, "password": password, "pin": pin};
+ });
+
+commander
+ .command('remove')
+ .description("Remove specified target")
+ .action(function () {
+ if (commander.args.length === 1) {
+ throw 'No target specified';
+ }
+ name = commander.args[0];
+ if (!properties.targets.hasOwnProperty(name)) {
+ throw "Target: '" + name + "' not found";
+ }
+ if (name === properties.defaultTarget) {
+ console.log("Deleting default target, please set a new default target");
+ properties.defaultTarget = "";
+ }
+ delete properties.targets[name];
+ });
+
+commander
+ .command('default')
+ .description("Get or set default target")
+ .action(function () {
+ if (commander.args.length === 1) {
+ console.log(properties.defaultTarget);
+ process.exit();
+ }
+ name = commander.args[0];
+ if (properties.targets.hasOwnProperty(name)) {
+ properties.defaultTarget = name;
+ } else {
+ throw "Target '" + name + "' not found";
+ }
+ });
+
+commander
+ .command('*')
+ .action(function () {
+ throw 'Unrecognized command';
+ });
+
+
+try {
+ commander.parse(process.argv);
+
+ if (commander.args.length === 0) {
+ Object.keys(properties.targets).forEach(function (target) {
+ if (target === properties.defaultTarget) {
+ console.log('* ' + target);
+ } else {
+ console.log(' ' + target);
+ }
+ });
+ process.exit();
+ }
+ if (Object.keys(properties.targets).length === 1) {
+ properties.defaultTarget = Object.keys(properties.targets)[0];
+ }
+
+ writeProjectFile(JSON.stringify(properties, null, 4) + "\n", propertiesFile);
+} catch (e) {
+ console.log(e);
+ process.exit();
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/plugin
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/plugin b/lib/cordova-blackberry/bin/templates/project/cordova/plugin
new file mode 100755
index 0000000..010649b
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/plugin
@@ -0,0 +1,23 @@
+#!/usr/bin/env node
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+require(require("path").join(__dirname, "lib", "plugin.js")).cli();
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/plugin.bat
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/plugin.bat b/lib/cordova-blackberry/bin/templates/project/cordova/plugin.bat
new file mode 100755
index 0000000..54245e0
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/plugin.bat
@@ -0,0 +1,21 @@
+@ECHO OFF
+goto comment
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+:comment
+
+@node.exe %~dp0\plugin %*
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/run
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/run b/lib/cordova-blackberry/bin/templates/project/cordova/run
index 260ff24..44d3334 100755
--- a/lib/cordova-blackberry/bin/templates/project/cordova/run
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/run
@@ -1,41 +1,3 @@
-#! /bin/sh
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
+#!/bin/sh
-ANT=$(which ant)
-
-if [ -z "$1" ]
-then
- echo 'usage: run <platform>'
- echo 'where <platform> can be one of "blackberry", "playbook" or "qnx"'
- echo 'NOTE: please customize the project.properties file first before using this command!'
- exit 0
-fi
-
-if [ "$1" == "blackberry" -o "$1" == "playbook" -o "$1" == "qnx" ]
-then
- echo 'Do you have a BlackBerry device connected to your computer? (y/n)'
- read DEVICE
- if [ $DEVICE == "y" ]
- then
- $ANT $1 debug-device
- else
- $ANT $1 load-simulator
- fi
-else
- echo 'Platform not recognized! Please use one of "blackberry", "playbook", or "qnx" for the platform parameter.'
-fi
+node $( dirname "$0")"/lib/run" "$@"
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/run.bat
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/run.bat b/lib/cordova-blackberry/bin/templates/project/cordova/run.bat
new file mode 100755
index 0000000..0f5da0a
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/run.bat
@@ -0,0 +1,21 @@
+@ECHO OFF
+goto comment
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+:comment
+
+@node.exe %~dp0\lib\run %*
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/target
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/target b/lib/cordova-blackberry/bin/templates/project/cordova/target
new file mode 100755
index 0000000..6a28219
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/target
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+node $( dirname "$0")"/lib/target" "$@"
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/target.bat
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/target.bat b/lib/cordova-blackberry/bin/templates/project/cordova/target.bat
new file mode 100755
index 0000000..545b79e
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/target.bat
@@ -0,0 +1,21 @@
+@ECHO OFF
+goto comment
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+:comment
+
+@node.exe %~dp0\lib\target %*
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/third_party/data2xml/data2xml.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/third_party/data2xml/data2xml.js b/lib/cordova-blackberry/bin/templates/project/cordova/third_party/data2xml/data2xml.js
new file mode 100644
index 0000000..8223d12
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/third_party/data2xml/data2xml.js
@@ -0,0 +1,86 @@
+// --------------------------------------------------------------------------------------------------------------------
+//
+// data2xml.js - A data to XML converter with a nice interface (for NodeJS).
+//
+// Copyright (c) 2011 AppsAttic Ltd - http://www.appsattic.com/
+// Written by Andrew Chilton <ch...@appsattic.com>
+//
+// License: http://opensource.org/licenses/MIT
+//
+// --------------------------------------------------------------------------------------------------------------------
+
+var xmlHeader = '<?xml version="1.0" encoding="utf-8"?>\n';
+
+function entitify(str) {
+ str = '' + str;
+ str = str
+ .replace(/&/g, '&')
+ .replace(/</g,'<')
+ .replace(/>/g,'>')
+ .replace(/'/g, ''')
+ .replace(/"/g, '"');
+ return str;
+}
+
+function makeStartTag(name, attr) {
+ attr = attr || {};
+ var tag = '<' + name;
+ for(var a in attr) {
+ tag += ' ' + a + '="' + entitify(attr[a]) + '"';
+ }
+ tag += '>';
+ return tag;
+}
+
+function makeEndTag(name) {
+ return '</' + name + '>';
+}
+
+function makeElement(name, data) {
+ var element = '';
+ if ( Array.isArray(data) ) {
+ data.forEach(function(v) {
+ element += makeElement(name, v);
+ });
+ return element;
+ }
+ else if ( typeof data === 'object' ) {
+ element += makeStartTag(name, data._attr);
+ if ( data._value ) {
+ element += entitify(data._value);
+ }
+/************** MODIFICATION [always execute else condition] ***************/
+ for (var el in data) {
+ /**************** MODIFICATION {if condition altered} **********************/
+ if ( el === '_attr' || el === '_value') {
+ continue;
+ }
+ element += makeElement(el, data[el]);
+ }
+ element += makeEndTag(name);
+ return element;
+/***************************** END MODIFICATION ***************************/
+ }
+ else {
+ // a piece of data on it's own can't have attributes
+ return makeStartTag(name) + entitify(data) + makeEndTag(name);
+ }
+ throw "Unknown data " + data;
+}
+
+var data2xml = function(name, data) {
+ var xml = xmlHeader;
+ xml += makeElement(name, data);
+ return xml;
+};
+
+// --------------------------------------------------------------------------------------------------------------------
+
+data2xml.entitify = entitify;
+data2xml.makeStartTag = makeStartTag;
+data2xml.makeEndTag = makeEndTag;
+data2xml.makeElement = makeElement;
+
+module.exports = data2xml;
+
+// --------------------------------------------------------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/cordova/third_party/wrench/wrench.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/cordova/third_party/wrench/wrench.js b/lib/cordova-blackberry/bin/templates/project/cordova/third_party/wrench/wrench.js
new file mode 100644
index 0000000..8c3d746
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/cordova/third_party/wrench/wrench.js
@@ -0,0 +1,78 @@
+/* wrench.js
+ *
+ * A collection of various utility functions I've found myself in need of
+ * for use with Node.js (http://nodejs.org/). This includes things like:
+ *
+ * - Recursively deleting directories in Node.js (Sync, not Async)
+ * - Recursively copying directories in Node.js (Sync, not Async)
+ * - Recursively chmoding a directory structure from Node.js (Sync, not Async)
+ * - Other things that I'll add here as time goes on. Shhhh...
+ *
+ * ~ Ryan McGrath (ryan [at] venodesigns.net)
+ */
+
+/* This file is originally licensed under https://raw.github.com/ryanmcgrath/wrench-js/master/LICENSE
+ * This code has been copied from https://raw.github.com/ryanmcgrath/wrench-js and modified
+ * add the functionality for a callback to the copyDirSyncRecursive method.
+ * Modifications have been clearly marked.
+ * The callback acts like a filter and you must return true/false from it to include/exclude a file
+ */
+
+var wrench = require('wrench'),
+ fs = require("fs"),
+ _path = require("path");
+/* wrench.copyDirSyncRecursive("directory_to_copy", "new_directory_location", opts);
+ *
+ * Recursively dives through a directory and moves all its files to a new location. This is a
+ * Synchronous function, which blocks things until it's done. If you need/want to do this in
+ * an Asynchronous manner, look at wrench.copyDirRecursively() below.
+ *
+ * Note: Directories should be passed to this function without a trailing slash.
+ */
+wrench.copyDirSyncRecursive = function(sourceDir, newDirLocation, opts, callback) {
+
+ /**************************Modification*****************************************/
+ if (typeof opts === "function") {
+ callback = opts;
+ opts = {};
+ }
+ /**************************Modification End*****************************************/
+
+ if (!opts || !opts.preserve) {
+ try {
+ if(fs.statSync(newDirLocation).isDirectory()) wrench.rmdirSyncRecursive(newDirLocation);
+ } catch(e) { }
+ }
+
+ /* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */
+ var checkDir = fs.statSync(sourceDir);
+ try {
+ fs.mkdirSync(newDirLocation, checkDir.mode);
+ } catch (e) {
+ //if the directory already exists, that's okay
+ if (e.code !== 'EEXIST') throw e;
+ }
+
+ var files = fs.readdirSync(sourceDir);
+
+ for(var i = 0; i < files.length; i++) {
+ var currFile = fs.lstatSync(sourceDir + "/" + files[i]);
+ /**************************Modified to add if statement*****************************************/
+ if (callback && !callback(sourceDir + "/" + files[i], currFile)) {
+ continue;
+ }
+ if(currFile.isDirectory()) {
+ /* recursion this thing right on back. */
+ wrench.copyDirSyncRecursive(sourceDir + "/" + files[i], newDirLocation + "/" + files[i], opts, callback);
+ } else if(currFile.isSymbolicLink()) {
+ var symlinkFull = fs.readlinkSync(sourceDir + "/" + files[i]);
+ fs.symlinkSync(symlinkFull, newDirLocation + "/" + files[i]);
+ } else {
+ /* At this point, we've hit a file actually worth copying... so copy it on over. */
+ var contents = fs.readFileSync(sourceDir + "/" + files[i]);
+ fs.writeFileSync(newDirLocation + "/" + files[i], contents);
+ }
+ }
+};
+
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/native/device/plugins/jnext/auth.txt
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/native/device/plugins/jnext/auth.txt b/lib/cordova-blackberry/bin/templates/project/native/device/plugins/jnext/auth.txt
new file mode 100644
index 0000000..0983f4f
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/native/device/plugins/jnext/auth.txt
@@ -0,0 +1,3 @@
+local:/// *
+file:// *
+http:// *
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/native/device/wwe
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/native/device/wwe b/lib/cordova-blackberry/bin/templates/project/native/device/wwe
new file mode 100644
index 0000000..0e48b92
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/native/device/wwe
@@ -0,0 +1,2 @@
+#!/bin/sh
+exec weblauncher "$@"
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/native/simulator/plugins/jnext/auth.txt
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/native/simulator/plugins/jnext/auth.txt b/lib/cordova-blackberry/bin/templates/project/native/simulator/plugins/jnext/auth.txt
new file mode 100644
index 0000000..0983f4f
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/native/simulator/plugins/jnext/auth.txt
@@ -0,0 +1,3 @@
+local:/// *
+file:// *
+http:// *
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/native/simulator/wwe
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/native/simulator/wwe b/lib/cordova-blackberry/bin/templates/project/native/simulator/wwe
new file mode 100644
index 0000000..0e48b92
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/native/simulator/wwe
@@ -0,0 +1,2 @@
+#!/bin/sh
+exec weblauncher "$@"
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/playbook.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/playbook.xml b/lib/cordova-blackberry/bin/templates/project/playbook.xml
deleted file mode 100644
index 7250cbc..0000000
--- a/lib/cordova-blackberry/bin/templates/project/playbook.xml
+++ /dev/null
@@ -1,338 +0,0 @@
-<project default="help">
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
- <!-- LOAD PROPERTIES -->
-
- <property prefix="properties" file="project.properties" />
- <property name="build.dir" location="build" />
- <property name="widget.dir" location="${build.dir}/widget" />
- <property name="code.sign" value="false" />
- <property name="generate.ext" value="cod" />
- <property name="build.num.file" value="buildId.txt" />
-
- <!-- BlackBerry WebWorks Packager for Tablets directory is required. -->
- <fail unless="properties.playbook.bbwp.dir" message="Please specify BlackBerry WebWorks Packager directory using 'playbook.bbwp.dir' in your 'project.properties' file." />
-
- <!-- OS identification -->
- <condition property="isMacOSX" else="false">
- <and>
- <os family="mac" />
- <os family="unix" />
- </and>
- </condition>
-
- <condition property="bbwp" value="${properties.playbook.bbwp.dir}/bbwp" else="${properties.playbook.bbwp.dir}/bbwp.exe">
- <equals arg1="${isMacOSX}" arg2="true" />
- </condition>
-
- <condition property="blackberry-deploy" value="${properties.playbook.bbwp.dir}/blackberry-tablet-sdk/bin/blackberry-deploy" else="${properties.playbook.bbwp.dir}/blackberry-tablet-sdk/bin/blackberry-deploy.bat">
- <equals arg1="${isMacOSX}" arg2="true" />
- </condition>
-
- <condition property="blackberry-debugtokenrequest" value="${properties.playbook.bbwp.dir}/blackberry-tablet-sdk/bin/blackberry-debugtokenrequest" else="${properties.playbook.bbwp.dir}/blackberry-tablet-sdk/bin/blackberry-debugtokenrequest.bat">
- <equals arg1="${isMacOSX}" arg2="true" />
- </condition>
-
- <!-- LOAD DEVICE -->
-
- <target name="load-device" depends="package-app">
- <bbwp code-sign="true" />
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-launchApp" />
- <arg value="-device" />
- <arg value="${properties.playbook.device.ip}" />
- <arg value="-password" />
- <arg value="${properties.playbook.device.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/${cod.name}.bar" />
- </exec>
- </target>
-
- <!-- DEBUG-LOAD DEVICE -->
-
- <target name="debug-device" depends="package-app">
- <if>
- <equals arg1="${properties.playbook.device.pin}" arg2="" />
- <then>
- <echo>
- If you fill in the playbook.device.pin value you can use debug tokens!
- This means you won't have to worry about having a unique version in config.xml every time.
- </echo>
- <bbwp code-sign="true" debug="true" />
- </then>
- <else>
- <generate-debug-token />
- <bbwp code-sign="false" debug="true" />
- </else>
- </if>
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-launchApp" />
- <arg value="-device" />
- <arg value="${properties.playbook.device.ip}" />
- <arg value="-password" />
- <arg value="${properties.playbook.device.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/${cod.name}.bar" />
- </exec>
- </target>
-
- <!-- LOAD SIMULATOR -->
-
- <target name="load-simulator" depends="build">
-
- <echo>This tool will not open the simulator for you </echo>
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-launchApp" />
- <arg value="-device" />
- <arg value="${properties.playbook.sim.ip}" />
- <arg value="-password" />
- <arg value="${properties.playbook.sim.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/${cod.name}.bar" />
- </exec>
- </target>
-
- <target name="debug-simulator" depends="package-app">
- <bbwp code-sign="false" debug="true" />
- <echo>This tool will not open the simulator for you </echo>
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-launchApp" />
- <arg value="-device" />
- <arg value="${properties.playbook.sim.ip}" />
- <arg value="-password" />
- <arg value="${properties.playbook.sim.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/${cod.name}.bar" />
- </exec>
- </target>
- <!-- PACKAGE-APP -->
-
- <target name="package-app" depends="generate-cod-name, clean">
- <!-- Copy the WebWorks application -->
- <mkdir dir="${widget.dir}" />
- <copy todir="${widget.dir}" overwrite="true">
- <fileset dir="www" >
- <exclude name="ext/**"/>
- <exclude name="ext-air/**"/>
- <exclude name="res/resourceBundles/**"/>
- </fileset>
- </copy>
-
- <!-- Update WebWorks Packager with the AIR APIs -->
- <copy todir="${properties.playbook.bbwp.dir}\ext" overwrite="true">
- <fileset dir="www/ext-air" excludes="README.md" />
- </copy>
-
- <!-- Package the WebWorks app by zipping the widget dir. -->
- <mkdir dir="${build.dir}" />
- <zip compress="false" destfile="${build.dir}/${cod.name}.zip" basedir="${widget.dir}" excludes="**/build/**,**/.settings/**,**/.project" />
- </target>
-
- <!-- BUILD -->
-
- <target name="build" depends="package-app">
- <bbwp code-sign="${code.sign}" />
- </target>
-
- <!-- BBWP MACRO -->
-
- <macrodef name="bbwp">
- <attribute name="code-sign" default="false" />
- <attribute name="debug" default="false" />
- <sequential>
- <!-- check if debug flag was passed in and set an appropriate flag for CLI exec of bbwp -->
- <if>
- <equals arg1="@{debug}" arg2="true" />
- <then>
- <property name="debug.flag" value="-d" />
- </then>
- <else>
- <property name="debug.flag" value="" />
- </else>
- </if>
- <buildnumber file="${build.num.file}" />
- <if>
- <equals arg1="@{code-sign}" arg2="true" />
- <then>
- <exec executable="${bbwp}">
- <arg file="${build.dir}/${cod.name}.zip" />
- <arg value="-gcsk" />
- <arg value="${properties.playbook.sigtool.csk.password}" />
- <arg value="-gp12" />
- <arg value="${properties.playbook.sigtool.p12.password}" />
- <arg value="-o" />
- <arg file="${build.dir}" />
- <arg line="${debug.flag} -buildId" />
- <arg value="${build.number}" />
- </exec>
- </then>
- <else>
- <exec executable="${bbwp}">
- <arg file="${build.dir}/${cod.name}.zip" />
- <arg value="-o" />
- <arg file="${build.dir}" />
- <arg line="${debug.flag} -buildId" />
- <arg value="${build.number}" />
- </exec>
- </else>
- </if>
- </sequential>
- </macrodef>
-
- <!-- install debug token" -->
- <macrodef name="generate-debug-token">
- <sequential>
- <exec executable="${blackberry-debugtokenrequest}" dir="." failonerror="true">
- <arg value="-storepass" />
- <arg value="${properties.playbook.sigtool.csk.password}" />
- <arg value="-deviceID" />
- <arg value="0x${properties.playbook.device.pin}" />
- <arg file="${properties.playbook.bbwp.dir}/debugtoken.bar" />
- </exec>
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-launchApp" />
- <arg value="-device" />
- <arg value="${properties.playbook.device.ip}" />
- <arg value="-password" />
- <arg value="${properties.playbook.device.password}" />
- <arg value="-package" />
- <arg file="${properties.playbook.bbwp.dir}/debugtoken.bar" />
- </exec>
-
- <replaceregexp
- file="${properties.playbook.bbwp.dir}/bin/bbwp.properties"
- match='<debug_token>.*<\/debug_token>'
- replace='<debug_token>${properties.playbook.bbwp.dir}/debugtoken.bar</debug_token>'
- byline='true'/>
- </sequential>
- </macrodef>
-
- <!-- CLEAN -->
-
- <target name="clean">
- <delete dir="${build.dir}" />
- <delete dir="${widget.dir}" />
- </target>
-
- <!-- CLEAN DEVICE -->
-
- <target name="clean-device" depends="generate-cod-name">
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-uninstallApp" />
- <arg value="-device" />
- <arg value="${properties.playbook.device.ip}" />
- <arg value="-password" />
- <arg value="${properties.playbook.device.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/${cod.name}.bar" />
- </exec>
- </target>
-
- <!-- CLEAN SIMULATOR -->
-
- <target name="clean-simulator" depends="generate-cod-name">
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-uninstallApp" />
- <arg value="-device" />
- <arg value="${properties.playbook.sim.ip}" />
- <arg value="-password" />
- <arg value="${properties.playbook.sim.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/${cod.name}.bar" />
- </exec>
- </target>
-
- <!-- HELPER TASKS -->
-
- <target name="generate-cod-name">
- <xmlproperty file="www/config.xml" prefix="config.xml" />
- <propertyregex property="cod.name"
- input="${config.xml.widget.name}"
- regexp="(\W+)"
- replace=""
- casesensitive="false"
- global="true"
- defaultValue="${config.xml.widget.name}" />
- <echo message="Generated name: ${cod.name}.bar" />
- </target>
-
- <!-- HELP -->
-
- <target name="help">
- <echo>
-NAME
- ${ant.project.name}
-
-SYNOPSIS
- ant TARGET COMMAND [-D<argument>=<value>]...
-
-DESCRIPTION
- You can build and deploy your project to a device or simulator.
-
-TARGETS
- blackberry ........ Builds a cod file and deploys to a device or simulator
-
- playbook .......... Builds a bar file and deploys to a device or simulator
-
-COMMANDS
- help .............. Show this help menu.
- ant, ant help
-
- load-device ....... Builds and deploys project to a connected USB device.
- ant load-device
-
- load-simulator .... Builds and deploys project to default simulator.
- ant load-simulator
-
- build ............. Compiles and packages the project for deployment.
- ant build
-
- clean ............. Remove all files from the build/ directory.
- ant clean
-
- clean-device ...... Remove this project from the connected USB device.
- ant clean-device
-
- clean-simulator ... Remove this project from the simulator (takes a while).
- ant clean-simulator
-
-GETTING STARTED
- 1. Edit project.properties
-
- 2. <ant <TARGET> load-simulator> to run the project on the simulator
-
- 3. Customize your project by editing www/config.xml
-
- 4. To run the project on a BlackBerry device, you will need to obtain
- code signing keys from RIM. Once you have the key, a project is
- installed by connecting a BlackBerry via USB and running
- <ant <TARGET> load-device>.
- </echo>
- </target>
-</project>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/project.json
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/project.json b/lib/cordova-blackberry/bin/templates/project/project.json
new file mode 100644
index 0000000..97bbb24
--- /dev/null
+++ b/lib/cordova-blackberry/bin/templates/project/project.json
@@ -0,0 +1,6 @@
+{
+ "barName": "cordova-BB10-app",
+ "keystorepass": "password",
+ "defaultTarget": "",
+ "targets": {}
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/project.properties
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/project.properties b/lib/cordova-blackberry/bin/templates/project/project.properties
deleted file mode 100644
index 71e5bc1..0000000
--- a/lib/cordova-blackberry/bin/templates/project/project.properties
+++ /dev/null
@@ -1,137 +0,0 @@
-# BlackBerry WebWorks Packager Directory
-#
-# The BlackBerry WebWorks Packager (bbwp) is required for compiling and packaging
-# BlackBerry WebWorks applications for deployment to a BlackBerry device
-# or simulator. The bbwp utility is installed with the standalone BlackBerry
-# WebWorks SDK, and as part of the BlackBerry Web Plugin for Eclipse.
-#
-# Please specify the location of the BlackBerry WebWorks Packager in your
-# environment.
-#
-# Typical location of bbwp for standalone BlackBerry WebWorks SDK installation:
-# C:\Program Files (x86)\Research In Motion\BlackBerry Widget Packager
-#
-# Typical location of bbwp for BlackBerry Web Plugin for Eclipse installation:
-# C:\Eclipse-3.5.2\plugins\net.rim.browser.tools.wcpc_1.0.0.201003191451-126\wcpc
-#
-# The ANT script is brittle and requires you to escape the backslashes.
-# e.g. C:\some\path must be C:\\some\\path
-#
-# Please remember to:
-# - Double escape your backslahses (i.e. \ must be \\)
-# - Do not add a trailing slash (e.g. C:\some\path)
-#
-blackberry.bbwp.dir=C:\\Program Files\\Research In Motion\\BlackBerry WebWorks Packager
-playbook.bbwp.dir=C:\\Program Files\\Research In Motion\\BlackBerry WebWorks SDK for TabletOS 2.1.0.6\\bbwp
-qnx.bbwp.dir=/Developer/SDKs/Research In Motion/BlackBerry 10 WebWorks SDK 1.0.4.7
-
-# (Optional) Simulator Directory
-#
-# If sim.dir is not specified, the build script will use the simulator directory
-# within the BlackBerry WebWorks Packager.
-#
-blackberry.sim.dir=C:\\Program Files\\Research In Motion\BlackBerry WebWorks Packager\\simpack\\6.0.0.227
-
-# (Optional) Simulator Binary
-#
-# If sim.bin is not specified, the build script will attempt to use the default
-# simulator in the simulator directory.
-#
-#blackberry.sim.bin=9700.bat
-
-# (Optional) MDS Directory
-#
-# If mds.dir is not specified, the build script will attempt to use the MDS that
-# is installed with the BlackBerry WebWorks Packager.
-#
-blackberry.mds.dir=C:\\Program Files\\Research In Motion\\BlackBerry WebWorks Packager\\mds
-
-# BlackBerry Code Signing Password
-#
-# If you leave this field blank, then
-# the signing tool will prompt you each time
-#
-blackberry.sigtool.password=
-
-# Playbook Code Signing Password
-#
-# If you leave these fields blank, then
-# signing will fail
-#
-playbook.sigtool.csk.password=
-playbook.sigtool.p12.password=
-
-# BB10 Code Signing Password
-qnx.sigtool.password=
-
-# BlackBerry Simulator Password
-#
-# If you leave this field blank, then
-# you cannot deploy to simulator
-#
-blackberry.sim.password=
-
-# Playbook Simulator IP
-#
-# If you leave this field blank, then
-# you cannot deploy to simulator
-#
-playbook.sim.ip=
-
-# Playbook Simulator Password
-#
-# If you leave this field blank, then
-# you cannot deploy to simulator
-#
-playbook.sim.password=
-
-# Playbook Device IP
-#
-# If you leave this field blank, then
-# you cannot deploy to device
-#
-playbook.device.ip=
-
-# Playbook Device Password
-#
-# If you leave this field blank, then
-# you cannot deploy to device
-#
-playbook.device.password=
-# PlayBook Device PIN
-#
-# Fill this value in to use debug tokens when debuging on the device
-playbook.device.pin=
-
-# QNX Simulator IP
-#
-# If you leave this field blank, then
-# you cannot deploy to simulator
-#
-qnx.sim.ip=
-
-# QNX Simulator Password
-#
-# If you leave this field blank, then
-# you cannot deploy to simulator
-#
-qnx.sim.password=
-
-# QNX Device IP
-#
-# If you leave this field blank, then
-# you cannot deploy to device
-#
-qnx.device.ip=
-
-# QNX Device Password
-#
-# If you leave this field blank, then
-# you cannot deploy to device
-#
-qnx.device.password=
-
-# QNX Device PIN
-#
-# Fill this value in to use debug tokens when debuging on the device
-qnx.device.pin=
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/qnx.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/qnx.xml b/lib/cordova-blackberry/bin/templates/project/qnx.xml
deleted file mode 100644
index d2e2de7..0000000
--- a/lib/cordova-blackberry/bin/templates/project/qnx.xml
+++ /dev/null
@@ -1,336 +0,0 @@
-<project default="help">
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
- <!-- LOAD PROPERTIES -->
-
- <property prefix="properties" file="project.properties" />
- <property name="build.dir" location="build" />
- <property name="widget.dir" location="${build.dir}/widget" />
- <property name="code.sign" value="false" />
- <property name="generate.ext" value="cod" />
- <property name="build.num.file" value="buildId.txt" />
-
- <!-- BlackBerry WebWorks Packager for Tablets directory is required. -->
- <fail unless="properties.qnx.bbwp.dir" message="Please specify BlackBerry WebWorks Packager directory using 'qnx.bbwp.dir' in your 'project.properties' file." />
-
- <!-- OS identification -->
- <condition property="isMacOSX" else="false">
- <and>
- <os family="mac" />
- <os family="unix" />
- </and>
- </condition>
-
- <condition property="bbwp" value="${properties.qnx.bbwp.dir}/bbwp" else="${properties.qnx.bbwp.dir}/bbwp.bat">
- <equals arg1="${isMacOSX}" arg2="true" />
- </condition>
-
- <condition property="blackberry-deploy" value="${properties.qnx.bbwp.dir}/dependencies/tools/bin/blackberry-deploy" else="${properties.qnx.bbwp.dir}/dependencies/tools/bin/blackberry-deploy.bat">
- <equals arg1="${isMacOSX}" arg2="true" />
- </condition>
-
- <condition property="blackberry-debugtokenrequest" value="${properties.qnx.bbwp.dir}/dependencies/tools/bin/blackberry-debugtokenrequest" else="${properties.qnx.bbwp.dir}/dependencies/tools/bin/blackberry-debugtokenrequest.bat">
- <equals arg1="${isMacOSX}" arg2="true" />
- </condition>
-
- <!-- LOAD DEVICE -->
-
- <target name="load-device" depends="package-app">
- <bbwp code-sign="true" />
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-launchApp" />
- <arg value="-device" />
- <arg value="${properties.qnx.device.ip}" />
- <arg value="-password" />
- <arg value="${properties.qnx.device.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/device/${cod.name}.bar" />
- </exec>
- </target>
-
- <!-- DEBUG-LOAD DEVICE -->
-
- <target name="debug-device" depends="package-app">
- <if>
- <equals arg1="${properties.qnx.device.pin}" arg2="" />
- <then>
- <echo>
- If you fill in the qnx.device.pin value you can use debug tokens!
- This means you won't have to worry about having a unique version in config.xml every time.
- </echo>
- <bbwp code-sign="true" debug="true" />
- </then>
- <else>
- <generate-debug-token />
- <bbwp code-sign="false" debug="true" />
- </else>
- </if>
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-launchApp" />
- <arg value="-device" />
- <arg value="${properties.qnx.device.ip}" />
- <arg value="-password" />
- <arg value="${properties.qnx.device.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/device/${cod.name}.bar" />
- </exec>
- </target>
-
- <!-- LOAD SIMULATOR -->
-
- <target name="load-simulator" depends="build">
-
- <echo>This tool will not open the simulator for you </echo>
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-launchApp" />
- <arg value="-device" />
- <arg value="${properties.qnx.sim.ip}" />
- <arg value="-password" />
- <arg value="${properties.qnx.sim.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/simulator/${cod.name}.bar" />
- </exec>
- </target>
-
- <target name="debug-simulator" depends="package-app">
-
- <bbwp code-sign="false" debug="true" />
- <echo>This tool will not open the simulator for you </echo>
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-launchApp" />
- <arg value="-device" />
- <arg value="${properties.qnx.sim.ip}" />
- <arg value="-password" />
- <arg value="${properties.qnx.sim.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/simulator/${cod.name}.bar" />
- </exec>
- </target>
-
- <!-- PACKAGE-APP -->
-
- <target name="package-app" depends="generate-cod-name, clean">
- <!-- Copy the WebWorks application -->
- <mkdir dir="${widget.dir}" />
- <copy todir="${widget.dir}" overwrite="true">
- <fileset dir="www" >
- <exclude name="ext/**"/>
- <exclude name="ext-air/**"/>
- <exclude name="res/resourceBundles/**"/>
- </fileset>
- </copy>
-
- <!-- Update WebWorks Packager with the QNX APIs -->
- <copy todir="${properties.qnx.bbwp.dir}\Framework\ext" overwrite="true">
- <fileset dir="www/ext-qnx" excludes="readme.md" />
- </copy>
-
- <!-- Package the WebWorks app by zipping the widget dir. -->
- <mkdir dir="${build.dir}" />
- <zip compress="false" destfile="${build.dir}/${cod.name}.zip" basedir="${widget.dir}" excludes="**/build/**,**/.settings/**,**/.project" />
- </target>
-
- <!-- BUILD -->
-
- <target name="build" depends="package-app">
- <bbwp code-sign="${code.sign}" />
- </target>
-
- <!-- BBWP MACRO -->
-
- <macrodef name="bbwp">
- <attribute name="code-sign" default="false" />
- <attribute name="debug" default="false" />
- <sequential>
- <!-- check if debug flag was passed in and set an appropriate flag for CLI exec of bbwp -->
- <if>
- <equals arg1="@{debug}" arg2="true" />
- <then>
- <property name="debug.flag" value="-d" />
- </then>
- <else>
- <property name="debug.flag" value="" />
- </else>
- </if>
- <buildnumber file="${build.num.file}" />
- <if>
- <equals arg1="@{code-sign}" arg2="true" />
- <then>
- <exec executable="${bbwp}">
- <arg file="${build.dir}/${cod.name}.zip" />
- <arg value="-g" />
- <arg value="${properties.qnx.sigtool.password}" />
- <arg value="-o" />
- <arg file="${build.dir}" />
- <arg line="${debug.flag} -b" />
- <arg value="${build.number}" />
- <arg value="--loglevel" />
- <arg value="error" />
- </exec>
- </then>
- <else>
- <exec executable="${bbwp}">
- <arg file="${build.dir}/${cod.name}.zip" />
- <arg value="-o" />
- <arg file="${build.dir}" />
- <arg line="${debug.flag}" />
- <arg value="--loglevel" />
- <arg value="error" />
- </exec>
- </else>
- </if>
- </sequential>
- </macrodef>
-
- <!-- install debug token" -->
- <macrodef name="generate-debug-token">
- <sequential>
- <exec executable="${blackberry-debugtokenrequest}" dir="." failonerror="true">
- <arg value="-storepass" />
- <arg value="${properties.qnx.sigtool.password}" />
- <arg value="-deviceID" />
- <arg value="0x${properties.qnx.device.pin}" />
- <arg file="${properties.qnx.bbwp.dir}/debugtoken.bar" />
- </exec>
-
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-installApp" />
- <arg value="-device" />
- <arg value="${properties.qnx.device.ip}" />
- <arg value="-password" />
- <arg value="${properties.qnx.device.password}" />
- <arg value="-package" />
- <arg file="${properties.qnx.bbwp.dir}/debugtoken.bar" />
- </exec>
- </sequential>
- </macrodef>
-
-
- <!-- CLEAN -->
-
- <target name="clean">
- <delete dir="${build.dir}" />
- <delete dir="${widget.dir}" />
- </target>
-
- <!-- CLEAN DEVICE -->
-
- <target name="clean-device" depends="generate-cod-name">
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-uninstallApp" />
- <arg value="-device" />
- <arg value="${properties.qnx.device.ip}" />
- <arg value="-password" />
- <arg value="${properties.qnx.device.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/device/${cod.name}.bar" />
- </exec>
- </target>
-
- <!-- CLEAN SIMULATOR -->
-
- <target name="clean-simulator" depends="generate-cod-name">
- <exec executable="${blackberry-deploy}" dir="." failonerror="true">
- <arg value="-uninstallApp" />
- <arg value="-device" />
- <arg value="${properties.qnx.sim.ip}" />
- <arg value="-password" />
- <arg value="${properties.qnx.sim.password}" />
- <arg value="-package" />
- <arg file="${build.dir}/simulator/${cod.name}.bar" />
- </exec>
- </target>
-
- <!-- HELPER TASKS -->
-
- <target name="generate-cod-name">
- <xmlproperty file="www/config.xml" prefix="config.xml" />
- <propertyregex property="cod.name"
- input="${config.xml.widget.name}"
- regexp="(\W+)"
- replace=""
- casesensitive="false"
- global="true"
- defaultValue="${config.xml.widget.name}" />
- <echo message="Generated name: ${cod.name}.bar" />
- </target>
-
-
- <!-- HELP -->
-
- <target name="help">
- <echo>
-NAME
- ${ant.project.name}
-
-SYNOPSIS
- ant TARGET COMMAND [-D<argument>=<value>]...
-
-DESCRIPTION
- You can build and deploy your project to a device or simulator.
-
-TARGETS
- blackberry ........ Builds a cod file and deploys to a device or simulator
-
- playbook .......... Builds a bar file and deploys to a device or simulator
-
-COMMANDS
- help .............. Show this help menu.
- ant, ant help
-
- load-device ....... Builds and deploys project to a connected USB device.
- ant load-device
-
- load-simulator .... Builds and deploys project to default simulator.
- ant load-simulator
-
- build ............. Compiles and packages the project for deployment.
- ant build
-
- clean ............. Remove all files from the build/ directory.
- ant clean
-
- clean-device ...... Remove this project from the connected USB device.
- ant clean-device
-
- clean-simulator ... Remove this project from the simulator (takes a while).
- ant clean-simulator
-
-GETTING STARTED
- 1. Edit project.properties
-
- 2. <ant <TARGET> load-simulator> to run the project on the simulator
-
- 3. Customize your project by editing www/config.xml
-
- 4. To run the project on a BlackBerry device, you will need to obtain
- code signing keys from RIM. Once you have the key, a project is
- installed by connecting a BlackBerry via USB and running
- <ant <TARGET> load-device>.
- </echo>
- </target>
-</project>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/www/VERSION
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/www/VERSION b/lib/cordova-blackberry/bin/templates/project/www/VERSION
index 24ba9a3..38f8e88 100644
--- a/lib/cordova-blackberry/bin/templates/project/www/VERSION
+++ b/lib/cordova-blackberry/bin/templates/project/www/VERSION
@@ -1 +1 @@
-2.7.0
+dev
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/www/config.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/www/config.xml b/lib/cordova-blackberry/bin/templates/project/www/config.xml
index 0de8bb5..3edc941 100644
--- a/lib/cordova-blackberry/bin/templates/project/www/config.xml
+++ b/lib/cordova-blackberry/bin/templates/project/www/config.xml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
-<!--
+<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
@@ -24,63 +24,28 @@
<widget xmlns="http://www.w3.org/ns/widgets"
xmlns:rim="http://www.blackberry.com/ns/widgets"
- version="1.0.0.0" id="__PACKAGE__">
+ version="1.0.0" id="default.app.id">
- <name>__NAME__</name>
+ <name>Webworks Application</name>
<author>Your Name Here</author>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
-
+
<license href="http://opensource.org/licenses/alphabetical">
</license>
- <!-- Cordova API -->
- <feature id="blackberry.system" required="true" version="1.0.0.0" />
- <feature id="org.apache.cordova" required="true" version="1.0.0" />
- <feature id="blackberry.find" required="true" version="1.0.0.0" />
- <feature id="blackberry.identity" required="true" version="1.0.0.0" />
- <feature id="blackberry.identity.phone" required="true" version="1.0.0.0" />
- <feature id="blackberry.pim.Address" required="true" version="1.0.0.0" />
- <feature id="blackberry.pim.Contact" required="true" version="1.0.0.0" />
- <feature id="blackberry.io.file" required="true" version="1.0.0.0" />
- <feature id="blackberry.utils" required="true" version="1.0.0.0" />
- <feature id="blackberry.io.dir" required="true" version="1.0.0.0" />
- <feature id="blackberry.app" required="true" version="1.0.0.0" />
- <feature id="blackberry.app.event" required="true" version="1.0.0.0" />
- <feature id="blackberry.system.event" required="true" version="1.0.0.0"/>
- <feature id="blackberry.widgetcache" required="true" version="1.0.0.0"/>
- <feature id="blackberry.media.camera" />
- <feature id="blackberry.ui.dialog" />
- <feature id="blackberry.connection" />
- <feature id="blackberry.bbm.platform" />
- <feature id="blackberry.invoke.card" />
- <feature id="blackberry.pim.contacts" />
- <feature id="blackberry.ui.contextmenu" />
- <feature id="blackberry.io.filetransfer" />
- <feature id="blackberry.io" />
- <feature id="blackberry.invoke" />
- <feature id="blackberry.invoked" />
- <feature id="blackberry.push" />
- <feature id="blackberry.media.microphone" required="true" version="1.0.0.0"/>
-
- <!-- Cordova API -->
+ <!-- Expose access to all URIs, including the file and http protocols -->
<access subdomains="true" uri="file:///store/home" />
<access subdomains="true" uri="file:///SDCard" />
-
- <!-- Expose access to all URIs, including the file and http protocols -->
<access subdomains="true" uri="*" />
- <icon rim:hover="false" src="res/icon/blackberry/icon-80.png" />
- <icon rim:hover="true" src="res/icon/blackberry/icon-80.png" />
-
- <rim:loadingScreen backgroundColor="#CFCFCF"
- foregroundImage="res/screen/blackberry/screen-225.png"
- onFirstLaunch="true">
- <rim:transitionEffect type="fadeOut" />
- </rim:loadingScreen>
+ <icon src="res/icon/blackberry/icon-80.png" />
+ <rim:splash src="res/screen/blackberry/splash-1280x768.png" />
+ <rim:splash src="res/screen/blackberry/splash-720x720.png" />
+ <rim:splash src="res/screen/blackberry/splash-768x1280.png" />
<content src="index.html" />
@@ -89,8 +54,8 @@
<rim:permit>read_device_identifying_information</rim:permit>
<rim:permit>access_shared</rim:permit>
<rim:permit>read_geolocation</rim:permit>
- <rim:permit>record_audio</rim:permit>
- <rim:permit>access_pimdomain_contacts</rim:permit>
+ <rim:permit>record_audio</rim:permit>
+ <rim:permit>access_pimdomain_contacts</rim:permit>
</rim:permissions>
</widget>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/www/index.html
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/www/index.html b/lib/cordova-blackberry/bin/templates/project/www/index.html
index 564ce18..ce767eb 100644
--- a/lib/cordova-blackberry/bin/templates/project/www/index.html
+++ b/lib/cordova-blackberry/bin/templates/project/www/index.html
@@ -33,7 +33,7 @@
<p class="event received">Device is Ready</p>
</div>
</div>
- <script type="text/javascript" src="cordova-2.7.0.js"></script>
+ <script type="text/javascript" src="cordova-dev.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/www/plugins.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/www/plugins.xml b/lib/cordova-blackberry/bin/templates/project/www/plugins.xml
deleted file mode 100644
index 3d41236..0000000
--- a/lib/cordova-blackberry/bin/templates/project/www/plugins.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-<plugins>
- <plugin name="App" value="org.apache.cordova.app.App"/>
- <plugin name="Device" value="org.apache.cordova.device.Device"/>
- <plugin name="Camera" value="org.apache.cordova.camera.Camera"/>
- <plugin name="NetworkStatus" value="org.apache.cordova.network.Network"/>
- <plugin name="Notification" value="org.apache.cordova.notification.Notification"/>
- <plugin name="Accelerometer" value="org.apache.cordova.accelerometer.Accelerometer"/>
- <plugin name="Geolocation" value="org.apache.cordova.geolocation.Geolocation"/>
- <plugin name="File" value="org.apache.cordova.file.FileManager"/>
- <plugin name="FileTransfer" value="org.apache.cordova.http.FileTransfer"/>
- <plugin name="Contacts" value="org.apache.cordova.pim.Contact"/>
- <plugin name="Capture" value="org.apache.cordova.capture.MediaCapture"/>
- <plugin name="Battery" value="org.apache.cordova.battery.Battery"/>
- <plugin name="Media" value="org.apache.cordova.media.Media"/>
- <plugin name="Globalization" value="org.apache.cordova.globalization.Globalization"/>
-</plugins>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/screen-225.png
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/screen-225.png b/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/screen-225.png
deleted file mode 100644
index 29873e9..0000000
Binary files a/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/screen-225.png and /dev/null differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-1280x768.png
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-1280x768.png b/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-1280x768.png
new file mode 100644
index 0000000..5f4bca9
Binary files /dev/null and b/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-1280x768.png differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-720x720.png
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-720x720.png b/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-720x720.png
new file mode 100644
index 0000000..fe1756f
Binary files /dev/null and b/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-720x720.png differ
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-768x1280.png
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-768x1280.png b/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-768x1280.png
new file mode 100644
index 0000000..0fb9c1b
Binary files /dev/null and b/lib/cordova-blackberry/bin/templates/project/www/res/screen/blackberry/splash-768x1280.png differ
[37/38] git commit: updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
updated android, ios, bb libraries to 2.8.x branch. fixed a few assertions with project changes. removed blackberry support until create script can be finalized.
Project: http://git-wip-us.apache.org/repos/asf/cordova-cli/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-cli/commit/88ad654c
Tree: http://git-wip-us.apache.org/repos/asf/cordova-cli/tree/88ad654c
Diff: http://git-wip-us.apache.org/repos/asf/cordova-cli/diff/88ad654c
Branch: refs/heads/master2
Commit: 88ad654c85719dd9d83f16b9995a5cd295166e7b
Parents: d00f202
Author: Fil Maj <ma...@gmail.com>
Authored: Thu May 23 16:31:44 2013 -0700
Committer: Fil Maj <ma...@gmail.com>
Committed: Thu May 23 16:31:44 2013 -0700
----------------------------------------------------------------------
lib/cordova-android/.reviewboardrc | 8 +
lib/cordova-android/NOTICE | 14 +-
lib/cordova-android/README.md | 34 +-
lib/cordova-android/VERSION | 2 +-
.../bin/templates/project/assets/www/index.html | 2 +-
lib/cordova-android/bin/update | 19 +-
lib/cordova-android/bin/update.js | 8 +-
lib/cordova-android/framework/AndroidManifest.xml | 9 +-
.../framework/assets/www/cordova.js | 156 +-
.../framework/assets/www/index.html | 2 +-
lib/cordova-android/framework/default.properties | 14 -
lib/cordova-android/framework/project.properties | 2 +-
lib/cordova-android/framework/res/xml/config.xml | 146 +-
.../framework/src/com/squareup/okhttp/Address.java | 111 +
.../src/com/squareup/okhttp/Connection.java | 291 +
.../src/com/squareup/okhttp/ConnectionPool.java | 273 +
.../src/com/squareup/okhttp/HttpResponseCache.java | 693 +
.../src/com/squareup/okhttp/OkHttpClient.java | 216 +
.../src/com/squareup/okhttp/OkResponseCache.java | 38 +
.../src/com/squareup/okhttp/ResponseSource.java | 37 +
.../framework/src/com/squareup/okhttp/Route.java | 91 +
.../src/com/squareup/okhttp/TunnelRequest.java | 75 +
.../okhttp/internal/AbstractOutputStream.java | 45 +
.../src/com/squareup/okhttp/internal/Base64.java | 164 +
.../com/squareup/okhttp/internal/DiskLruCache.java | 926 ++
.../src/com/squareup/okhttp/internal/Dns.java | 33 +
.../internal/FaultRecoveringOutputStream.java | 163 +
.../squareup/okhttp/internal/NamedRunnable.java | 40 +
.../src/com/squareup/okhttp/internal/Platform.java | 389 +
.../squareup/okhttp/internal/StrictLineReader.java | 208 +
.../src/com/squareup/okhttp/internal/Util.java | 327 +
.../internal/http/AbstractHttpInputStream.java | 107 +
.../internal/http/AbstractHttpOutputStream.java | 40 +
.../okhttp/internal/http/HeaderParser.java | 112 +
.../okhttp/internal/http/HttpAuthenticator.java | 175 +
.../squareup/okhttp/internal/http/HttpDate.java | 82 +
.../squareup/okhttp/internal/http/HttpEngine.java | 664 +
.../okhttp/internal/http/HttpResponseCache.java | 608 +
.../okhttp/internal/http/HttpTransport.java | 485 +
.../internal/http/HttpURLConnectionImpl.java | 556 +
.../internal/http/HttpsURLConnectionImpl.java | 461 +
.../okhttp/internal/http/OkResponseCache.java | 55 +
.../internal/http/OkResponseCacheAdapter.java | 53 +
.../squareup/okhttp/internal/http/RawHeaders.java | 424 +
.../okhttp/internal/http/RequestHeaders.java | 290 +
.../okhttp/internal/http/ResponseHeaders.java | 497 +
.../internal/http/RetryableOutputStream.java | 75 +
.../okhttp/internal/http/RouteSelector.java | 275 +
.../okhttp/internal/http/SpdyTransport.java | 96 +
.../squareup/okhttp/internal/http/Transport.java | 64 +
.../http/UnknownLengthHttpInputStream.java | 63 +
.../internal/spdy/IncomingStreamHandler.java | 36 +
.../com/squareup/okhttp/internal/spdy/Ping.java | 71 +
.../squareup/okhttp/internal/spdy/Settings.java | 174 +
.../okhttp/internal/spdy/SpdyConnection.java | 579 +
.../squareup/okhttp/internal/spdy/SpdyReader.java | 326 +
.../squareup/okhttp/internal/spdy/SpdyStream.java | 733 +
.../squareup/okhttp/internal/spdy/SpdyWriter.java | 176 +
.../src/org/apache/cordova/AudioHandler.java | 13 +-
.../src/org/apache/cordova/CameraLauncher.java | 61 +-
.../framework/src/org/apache/cordova/Capture.java | 13 +-
.../framework/src/org/apache/cordova/Config.java | 23 +-
.../src/org/apache/cordova/CordovaActivity.java | 1158 ++
.../org/apache/cordova/CordovaChromeClient.java | 4 +-
.../src/org/apache/cordova/CordovaWebView.java | 4 +-
.../framework/src/org/apache/cordova/Device.java | 2 +-
.../framework/src/org/apache/cordova/DroidGap.java | 1136 +--
.../src/org/apache/cordova/FileHelper.java | 56 +-
.../src/org/apache/cordova/FileTransfer.java | 55 +-
.../src/org/apache/cordova/FileUtils.java | 121 +-
.../cordova/IceCreamCordovaWebViewClient.java | 48 +-
.../cordova/LinearLayoutSoftKeyboardDetect.java | 4 +-
.../src/org/apache/cordova/Notification.java | 146 +-
.../src/org/apache/cordova/StandAlone.java | 32 -
.../src/org/apache/cordova/api/CordovaPlugin.java | 14 +
.../src/org/apache/cordova/api/DataResource.java | 141 +
.../apache/cordova/api/DataResourceContext.java | 31 +
.../src/org/apache/cordova/api/PluginManager.java | 70 +-
lib/cordova-android/test/proguard.cfg | 40 -
lib/cordova-android/test/res/xml/config.xml | 135 +-
lib/cordova-blackberry/.jshint | 3 +
lib/cordova-blackberry/.jshintignore | 1 +
lib/cordova-blackberry/.npmignore | 2 +
lib/cordova-blackberry/Jakefile | 148 +
lib/cordova-blackberry/README.md | 193 +-
lib/cordova-blackberry/VERSION | 2 +-
lib/cordova-blackberry/bin/check_reqs | 28 +
lib/cordova-blackberry/bin/check_reqs.bat | 21 +
lib/cordova-blackberry/bin/create | 89 +-
lib/cordova-blackberry/bin/create.bat | 14 +-
lib/cordova-blackberry/bin/create.js | 251 +-
lib/cordova-blackberry/bin/lib/localize.js | 26 +
lib/cordova-blackberry/bin/lib/utils.js | 167 +
.../bin/templates/dist/README.md | 90 -
.../bin/templates/project/blackberry.xml | 456 -
.../bin/templates/project/build.xml | 160 -
.../bin/templates/project/cordova/build | 35 +-
.../bin/templates/project/cordova/build.bat | 21 +
.../bin/templates/project/cordova/clean | 3 +
.../bin/templates/project/cordova/clean.bat | 21 +
.../templates/project/cordova/lib/bar-builder.js | 98 +
.../bin/templates/project/cordova/lib/bar-conf.js | 27 +
.../templates/project/cordova/lib/bbwpignore.js | 129 +
.../bin/templates/project/cordova/lib/build | 174 +
.../bin/templates/project/cordova/lib/clean | 24 +
.../bin/templates/project/cordova/lib/cmdline.js | 67 +
.../bin/templates/project/cordova/lib/conf.js | 47 +
.../templates/project/cordova/lib/config-parser.js | 670 +
.../project/cordova/lib/debugtoken-helper.js | 211 +
.../templates/project/cordova/lib/file-manager.js | 208 +
.../templates/project/cordova/lib/i18n-manager.js | 146 +
.../bin/templates/project/cordova/lib/localize.js | 207 +
.../bin/templates/project/cordova/lib/logger.js | 38 +
.../project/cordova/lib/native-packager.js | 288 +
.../project/cordova/lib/packager-utils.js | 176 +
.../project/cordova/lib/packager-validator.js | 110 +
.../bin/templates/project/cordova/lib/packager.js | 73 +
.../bin/templates/project/cordova/lib/plugin.js | 197 +
.../bin/templates/project/cordova/lib/run | 204 +
.../bin/templates/project/cordova/lib/session.js | 120 +
.../project/cordova/lib/signing-helper.js | 127 +
.../bin/templates/project/cordova/lib/target | 189 +
.../bin/templates/project/cordova/plugin | 23 +
.../bin/templates/project/cordova/plugin.bat | 21 +
.../bin/templates/project/cordova/run | 42 +-
.../bin/templates/project/cordova/run.bat | 21 +
.../bin/templates/project/cordova/target | 3 +
.../bin/templates/project/cordova/target.bat | 21 +
.../cordova/third_party/data2xml/data2xml.js | 86 +
.../project/cordova/third_party/wrench/wrench.js | 78 +
.../project/native/device/plugins/jnext/auth.txt | 3 +
.../bin/templates/project/native/device/wwe | 2 +
.../native/simulator/plugins/jnext/auth.txt | 3 +
.../bin/templates/project/native/simulator/wwe | 2 +
.../bin/templates/project/playbook.xml | 338 -
.../bin/templates/project/project.json | 6 +
.../bin/templates/project/project.properties | 137 -
.../bin/templates/project/qnx.xml | 336 -
.../bin/templates/project/www/VERSION | 2 +-
.../bin/templates/project/www/config.xml | 57 +-
.../bin/templates/project/www/index.html | 2 +-
.../bin/templates/project/www/plugins.xml | 35 -
.../www/res/screen/blackberry/screen-225.png | Bin 16776 -> 0 bytes
.../www/res/screen/blackberry/splash-1280x768.png | Bin 0 -> 60771 bytes
.../www/res/screen/blackberry/splash-720x720.png | Bin 0 -> 50431 bytes
.../www/res/screen/blackberry/splash-768x1280.png | Bin 0 -> 57145 bytes
.../test/cordova/functional/debugtoken-helper.js | 377 +
.../bin/test/cordova/integration/create.js | 158 +
.../bin/test/cordova/integration/target.js | 237 +
.../bin/test/cordova/unit/config-bare-minimum.xml | 21 +
.../bin/test/cordova/unit/config-license.xml | 10 +
.../bin/test/cordova/unit/config.xml | 53 +
.../bin/test/cordova/unit/data/ascii_text.txt | 1 +
.../bin/test/cordova/unit/data/ucs2be_text.txt | Bin 0 -> 24 bytes
.../bin/test/cordova/unit/data/ucs2le_text.txt | Bin 0 -> 24 bytes
.../bin/test/cordova/unit/data/utf8_text.txt | 1 +
.../bin/test/cordova/unit/params-bad.json | 10 +
.../bin/test/cordova/unit/params.json | 9 +
.../bin/test/cordova/unit/spec/lib/bar-builder.js | 34 +
.../bin/test/cordova/unit/spec/lib/bbwpignore.js | 135 +
.../bin/test/cordova/unit/spec/lib/cmdline.js | 77 +
.../test/cordova/unit/spec/lib/config-parser.js | 1411 ++
.../bin/test/cordova/unit/spec/lib/file-manager.js | 67 +
.../bin/test/cordova/unit/spec/lib/i18n-manager.js | 298 +
.../bin/test/cordova/unit/spec/lib/logger.js | 101 +
.../test/cordova/unit/spec/lib/native-packager.js | 347 +
.../test/cordova/unit/spec/lib/packager-utils.js | 65 +
.../cordova/unit/spec/lib/packager-validator.js | 277 +
.../bin/test/cordova/unit/spec/lib/session.js | 209 +
.../test/cordova/unit/spec/lib/signing-helper.js | 420 +
.../bin/test/cordova/unit/spec/lib/test-data.js | 87 +
.../test/cordova/unit/spec/lib/test-utilities.js | 82 +
.../bin/test/cordova/unit/test.zip | Bin 0 -> 4984 bytes
.../bin/test/plugins/Accelerometer/index.js | 81 +
.../bin/test/plugins/Battery/index.js | 103 +
.../bin/test/plugins/Camera/index.js | 298 +
.../bin/test/plugins/Contacts/index.js | 197 +
.../bin/test/plugins/Device/index.js | 76 +
.../bin/test/plugins/Logger/index.js | 51 +
.../bin/test/plugins/NetworkStatus/index.js | 118 +
.../bin/test/plugins/Notification/index.js | 119 +
.../bin/test/plugins/SplashScreen/index.js | 82 +
lib/cordova-blackberry/build.xml | 342 -
.../framework/bootstrap/index.html | 23 +
.../framework/bootstrap/require.js | 251 +
lib/cordova-blackberry/framework/bootstrap/ui.html | 73 +
.../framework/ext-air/Cordova_Network/library.xml | 40 -
.../src/org/apache/cordova/network/Network.as | 88 -
.../framework/ext-qnx/org.apache.cordova/client.js | 16 -
.../framework/ext-qnx/org.apache.cordova/index.js | 34 -
.../ext-qnx/org.apache.cordova/manifest.json | 5 -
lib/cordova-blackberry/framework/ext-qnx/readme.md | 1 -
lib/cordova-blackberry/framework/ext/.classpath | 7 -
lib/cordova-blackberry/framework/ext/.project | 29 -
.../net.rim.browser.tools.debug.widget.prefs | 3 -
.../ext/.settings/org.eclipse.jdt.core.prefs | 12 -
.../framework/ext/BlackBerry_App_Descriptor.xml | 36 -
.../framework/ext/src/library.xml | 35 -
.../src/org/apache/cordova/CordovaExtension.java | 208 -
.../cordova/accelerometer/Accelerometer.java | 228 -
.../ext/src/org/apache/cordova/api/IPlugin.java | 71 -
.../ext/src/org/apache/cordova/api/Plugin.java | 114 -
.../src/org/apache/cordova/api/PluginManager.java | 168 -
.../apache/cordova/api/PluginManagerFunction.java | 240 -
.../src/org/apache/cordova/api/PluginResult.java | 152 -
.../ext/src/org/apache/cordova/app/App.java | 147 -
.../src/org/apache/cordova/battery/Battery.java | 210 -
.../ext/src/org/apache/cordova/camera/Camera.java | 470 -
.../org/apache/cordova/camera/CameraOptions.java | 193 -
.../org/apache/cordova/camera/PhotoListener.java | 107 -
.../cordova/capture/AudioCaptureListener.java | 80 -
.../cordova/capture/AudioCaptureOperation.java | 173 -
.../org/apache/cordova/capture/AudioControl.java | 75 -
.../org/apache/cordova/capture/CameraControl.java | 87 -
.../org/apache/cordova/capture/CaptureControl.java | 169 -
.../org/apache/cordova/capture/CaptureMode.java | 87 -
.../apache/cordova/capture/CaptureOperation.java | 202 -
.../cordova/capture/ImageCaptureListener.java | 84 -
.../cordova/capture/ImageCaptureOperation.java | 161 -
.../org/apache/cordova/capture/MediaCapture.java | 502 -
.../src/org/apache/cordova/capture/MediaQueue.java | 44 -
.../cordova/capture/VideoCaptureListener.java | 107 -
.../cordova/capture/VideoCaptureOperation.java | 124 -
.../ext/src/org/apache/cordova/device/Device.java | 70 -
.../ext/src/org/apache/cordova/file/Entry.java | 66 -
.../ext/src/org/apache/cordova/file/File.java | 84 -
.../src/org/apache/cordova/file/FileManager.java | 1051 --
.../apache/cordova/geolocation/Geolocation.java | 372 -
.../cordova/geolocation/GeolocationListener.java | 133 -
.../cordova/geolocation/GeolocationResult.java | 73 -
.../cordova/geolocation/GeolocationStatus.java | 36 -
.../org/apache/cordova/geolocation/Position.java | 133 -
.../cordova/geolocation/PositionOptions.java | 42 -
.../cordova/globalization/Globalization.java | 558 -
.../cordova/globalization/GlobalizationError.java | 115 -
.../apache/cordova/globalization/Resources.java | 99 -
.../src/org/apache/cordova/globalization/Util.java | 721 -
.../src/org/apache/cordova/http/FileTransfer.java | 473 -
.../org/apache/cordova/http/FileUploadResult.java | 63 -
.../src/org/apache/cordova/http/FileUploader.java | 280 -
.../ext/src/org/apache/cordova/http/HttpUtils.java | 66 -
.../ext/src/org/apache/cordova/json4j/JSON.java | 208 -
.../src/org/apache/cordova/json4j/JSONArray.java | 1123 --
.../org/apache/cordova/json4j/JSONArtifact.java | 118 -
.../org/apache/cordova/json4j/JSONException.java | 55 -
.../src/org/apache/cordova/json4j/JSONObject.java | 1367 --
.../src/org/apache/cordova/json4j/JSONString.java | 32 -
.../org/apache/cordova/json4j/JSONStringer.java | 58 -
.../src/org/apache/cordova/json4j/JSONWriter.java | 586 -
.../cordova/json4j/internal/JSON4JNumber.java | 22 -
.../cordova/json4j/internal/JSON4JPBackReader.java | 47 -
.../json4j/internal/JSON4JStringReader.java | 54 -
.../json4j/internal/JSON4JStringWriter.java | 68 -
.../apache/cordova/json4j/internal/NumberUtil.java | 109 -
.../org/apache/cordova/json4j/internal/Parser.java | 338 -
.../apache/cordova/json4j/internal/Serializer.java | 353 -
.../cordova/json4j/internal/SerializerVerbose.java | 102 -
.../org/apache/cordova/json4j/internal/Token.java | 115 -
.../apache/cordova/json4j/internal/Tokenizer.java | 619 -
.../src/org/apache/cordova/media/AudioPlayer.java | 654 -
.../ext/src/org/apache/cordova/media/Media.java | 344 -
.../cordova/network/ConnectionInfoAction.java | 355 -
.../src/org/apache/cordova/network/Network.java | 66 -
.../cordova/notification/ActivityDialog.java | 146 -
.../apache/cordova/notification/AlertAction.java | 83 -
.../apache/cordova/notification/AlertDialog.java | 68 -
.../apache/cordova/notification/BeepAction.java | 160 -
.../apache/cordova/notification/ConfirmAction.java | 85 -
.../apache/cordova/notification/ConfirmDialog.java | 100 -
.../apache/cordova/notification/Notification.java | 135 -
.../cordova/notification/ProgressDialog.java | 182 -
.../apache/cordova/notification/VibrateAction.java | 64 -
.../ext/src/org/apache/cordova/pim/Contact.java | 430 -
.../ext/src/org/apache/cordova/ui/SpacerField.java | 71 -
.../org/apache/cordova/util/ApplicationUtils.java | 108 -
.../ext/src/org/apache/cordova/util/FileUtils.java | 730 -
.../ext/src/org/apache/cordova/util/Log.java | 83 -
.../src/org/apache/cordova/util/LogFunction.java | 41 -
.../ext/src/org/apache/cordova/util/Logger.java | 155 -
.../src/org/apache/cordova/util/StringUtils.java | 103 -
.../framework/lib/PluginResult.js | 55 +
lib/cordova-blackberry/framework/lib/config.js | 22 +
.../framework/lib/config/default.js | 76 +
.../framework/lib/config/user.js | 49 +
.../framework/lib/controllerWebView.js | 72 +
lib/cordova-blackberry/framework/lib/event.js | 84 +
.../framework/lib/events/applicationEvents.js | 34 +
.../framework/lib/events/deviceEvents.js | 34 +
lib/cordova-blackberry/framework/lib/exception.js | 69 +
lib/cordova-blackberry/framework/lib/framework.js | 172 +
lib/cordova-blackberry/framework/lib/jnext.js | 185 +
.../framework/lib/overlayWebView.js | 143 +
.../framework/lib/plugins/default.js | 71 +
.../framework/lib/plugins/event.js | 42 +
.../framework/lib/policy/folderAccess.js | 175 +
.../framework/lib/policy/webkitOriginAccess.js | 123 +
.../framework/lib/policy/whitelist.js | 317 +
lib/cordova-blackberry/framework/lib/server.js | 121 +
lib/cordova-blackberry/framework/lib/utils.js | 549 +
.../framework/lib/webkitEvent.js | 87 +
.../lib/webkitHandlers/networkResourceRequested.js | 126 +
lib/cordova-blackberry/framework/lib/webview.js | 271 +
.../framework/test/unit/lib/config.js | 30 +
.../framework/test/unit/lib/controllerWebView.js | 107 +
.../framework/test/unit/lib/event.js | 139 +
.../test/unit/lib/events/applicationEvents.js | 82 +
.../framework/test/unit/lib/events/deviceEvents.js | 77 +
.../framework/test/unit/lib/framework.js | 429 +
.../framework/test/unit/lib/overlayWebView.js | 187 +
.../framework/test/unit/lib/plugins/default.js | 154 +
.../framework/test/unit/lib/plugins/event.js | 78 +
.../test/unit/lib/policy/webkitOriginAccess.js | 194 +
.../framework/test/unit/lib/policy/whitelist.js | 859 ++
.../framework/test/unit/lib/server.js | 293 +
.../framework/test/unit/lib/utils.js | 280 +
.../lib/webkitHandlers/networkResourceRequested.js | 167 +
.../framework/test/unit/lib/webview.js | 334 +
.../javascript/cordova.blackberry.js |10904 ---------------
.../javascript/cordova.blackberry10.js | 6891 +++++++++
lib/cordova-blackberry/package.json | 33 +
.../plugins/Accelerometer/plugin.xml | 30 +
.../Accelerometer/src/blackberry10/index.js | 45 +
lib/cordova-blackberry/plugins/Battery/plugin.xml | 30 +
.../plugins/Battery/src/blackberry10/index.js | 58 +
lib/cordova-blackberry/plugins/Camera/plugin.xml | 30 +
.../plugins/Camera/src/blackberry10/index.js | 124 +
lib/cordova-blackberry/plugins/Contacts/plugin.xml | 41 +
.../Contacts/src/blackberry10/ContactActivity.js | 26 +
.../Contacts/src/blackberry10/ContactAddress.js | 30 +
.../Contacts/src/blackberry10/ContactError.js | 30 +
.../Contacts/src/blackberry10/ContactField.js | 27 +
.../src/blackberry10/ContactFindOptions.js | 50 +
.../Contacts/src/blackberry10/ContactName.js | 39 +
.../Contacts/src/blackberry10/ContactNews.js | 26 +
.../src/blackberry10/ContactOrganization.js | 22 +
.../Contacts/src/blackberry10/ContactPhoto.js | 23 +
.../Contacts/src/blackberry10/contactConsts.js | 225 +
.../Contacts/src/blackberry10/contactUtils.js | 223 +
.../plugins/Contacts/src/blackberry10/index.js | 374 +
lib/cordova-blackberry/plugins/Device/plugin.xml | 30 +
.../plugins/Device/src/blackberry10/index.js | 60 +
lib/cordova-blackberry/plugins/Logger/plugin.xml | 30 +
.../plugins/Logger/src/blackberry10/index.js | 25 +
.../plugins/NetworkStatus/plugin.xml | 30 +
.../NetworkStatus/src/blackberry10/index.js | 59 +
.../plugins/Notification/plugin.xml | 30 +
.../plugins/Notification/src/blackberry10/index.js | 91 +
.../plugins/SplashScreen/plugin.xml | 30 +
.../plugins/SplashScreen/src/blackberry10/index.js | 28 +
.../plugins/com.blackberry.jpps/plugin.xml | 30 +
.../src/blackberry10/native/device/libjpps.so | Bin 0 -> 138046 bytes
.../src/blackberry10/native/simulator/libjpps.so | Bin 0 -> 224392 bytes
.../plugins/com.blackberry.utils/plugin.xml | 30 +
.../src/blackberry10/native/device/libutils.so | Bin 0 -> 130206 bytes
.../src/blackberry10/native/simulator/libutils.so | Bin 0 -> 183184 bytes
.../plugin.xml | 31 +
.../src/blackberry10/native/Makefile | 8 +
.../src/blackberry10/native/arm/Makefile | 8 +
.../src/blackberry10/native/arm/so.le-v7/Makefile | 1 +
.../native/arm/so.le-v7/libpimcontacts.so | Bin 0 -> 170350 bytes
.../src/blackberry10/native/common.mk | 18 +
.../src/blackberry10/native/contact_account.cpp | 74 +
.../src/blackberry10/native/contact_account.hpp | 54 +
.../blackberry10/native/device/libpimcontacts.so | Bin 0 -> 170350 bytes
.../src/blackberry10/native/pim_contacts_js.cpp | 174 +
.../src/blackberry10/native/pim_contacts_js.hpp | 45 +
.../src/blackberry10/native/pim_contacts_qt.cpp | 1611 +++
.../src/blackberry10/native/pim_contacts_qt.hpp | 148 +
.../native/simulator/libpimcontacts.so | Bin 0 -> 265964 bytes
.../src/blackberry10/native/x86/Makefile | 8 +
.../src/blackberry10/native/x86/so/Makefile | 1 +
.../blackberry10/native/x86/so/libpimcontacts.so | Bin 0 -> 265964 bytes
lib/cordova-blackberry/scripts/lib/conf.js | 21 +
lib/cordova-blackberry/scripts/lib/utils.js | 127 +
lib/cordova-blackberry/scripts/test.js | 58 +
lib/cordova-ios/.reviewboardrc | 8 +
lib/cordova-ios/CordovaLib/.gitignore | 6 -
lib/cordova-ios/CordovaLib/Classes/CDVCamera.h | 12 +-
lib/cordova-ios/CordovaLib/Classes/CDVCamera.m | 181 +-
lib/cordova-ios/CordovaLib/Classes/CDVCapture.m | 2 -
.../CordovaLib/Classes/CDVConfigParser.h | 5 +-
.../CordovaLib/Classes/CDVConfigParser.m | 26 +
.../CordovaLib/Classes/CDVInAppBrowser.h | 5 +
.../CordovaLib/Classes/CDVInAppBrowser.m | 158 +-
.../CordovaLib/Classes/CDVNotification.m | 12 +-
.../CordovaLib/Classes/CDVSplashScreen.m | 7 +-
lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.h | 1 +
lib/cordova-ios/CordovaLib/Classes/CDVWhitelist.m | 21 +-
lib/cordova-ios/CordovaLib/VERSION | 2 +-
lib/cordova-ios/CordovaLib/cordova.ios.js | 6419 ---------
lib/cordova-ios/CordovaLib/cordova.js | 6453 +++++++++
.../CordovaLibTests/CDVWhitelistTests.m | 18 +
.../CordovaLibTests/CordovaLibApp/config.xml | 117 +-
.../CordovaLibTests/CordovaLibApp/www/index.html | 2 +-
.../CordovaTests.xcodeproj/project.pbxproj | 14 +-
lib/cordova-ios/FirstRun.md | 2 +-
lib/cordova-ios/bin/create | 4 +-
.../project/__TESTING__.xcodeproj/project.pbxproj | 14 +-
.../bin/templates/project/__TESTING__/.gitignore | 6 -
.../Resources/de.lproj/Localizable.strings | 2 +
.../Resources/en.lproj/Localizable.strings | 2 +
.../Resources/es.lproj/Localizable.strings | 2 +
.../Resources/se.lproj/Localizable.strings | 2 +
.../bin/templates/project/__TESTING__/config.xml | 119 +-
.../bin/templates/project/cordova/build | 51 -
.../bin/templates/project/cordova/clean | 44 +
.../bin/templates/project/cordova/emulate | 20 +-
.../templates/project/cordova/lib/install-device | 30 +
.../templates/project/cordova/lib/install-emulator | 130 +
.../bin/templates/project/cordova/lib/list-devices | 22 +
.../project/cordova/lib/list-emulator-images | 34 +
.../project/cordova/lib/list-started-emulators | 36 +
.../templates/project/cordova/lib/sim.applescript | 14 +
.../templates/project/cordova/lib/start-emulator | 35 +
.../bin/templates/project/cordova/release | 51 -
lib/cordova-ios/bin/templates/project/cordova/run | 97 +-
.../bin/templates/project/cordova/version | 40 +
.../bin/templates/project/www/index.html | 2 +-
platforms.js | 2 +-
spec/cordova-cli/platform.spec.js | 7 +-
spec/cordova-cli/plugin.spec.js | 18 -
.../platform-script/android/android_parser.spec.js | 2 +-
spec/platform-script/ios/ios_parser.spec.js | 2 +-
src/plugin.js | 3 +-
424 files changed, 48895 insertions(+), 40176 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/.reviewboardrc
----------------------------------------------------------------------
diff --git a/lib/cordova-android/.reviewboardrc b/lib/cordova-android/.reviewboardrc
new file mode 100644
index 0000000..30e9587
--- /dev/null
+++ b/lib/cordova-android/.reviewboardrc
@@ -0,0 +1,8 @@
+#
+# Settings for post-review (used for uploading diffs to reviews.apache.org).
+#
+GUESS_FIELDS = True
+OPEN_BROWSER = True
+TARGET_GROUPS = 'cordova'
+REVIEWBOARD_URL = 'http://reviews.apache.org'
+
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/NOTICE
----------------------------------------------------------------------
diff --git a/lib/cordova-android/NOTICE b/lib/cordova-android/NOTICE
index b2157b6..b8172a6 100644
--- a/lib/cordova-android/NOTICE
+++ b/lib/cordova-android/NOTICE
@@ -1,5 +1,17 @@
Apache Cordova
Copyright 2012 The Apache Software Foundation
-This product includes software developed by
+This product includes software developed at
The Apache Software Foundation (http://www.apache.org)
+
+=========================================================================
+== NOTICE file corresponding to the section 4 d of ==
+== the Apache License, Version 2.0, ==
+== in this case for the Android-specific code. ==
+=========================================================================
+
+Android Code
+Copyright 2005-2008 The Android Open Source Project
+
+This product includes software developed as part of
+The Android Open Source Project (http://source.android.com).
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/README.md
----------------------------------------------------------------------
diff --git a/lib/cordova-android/README.md b/lib/cordova-android/README.md
index 5d2f7de..a785943 100755
--- a/lib/cordova-android/README.md
+++ b/lib/cordova-android/README.md
@@ -16,23 +16,7 @@ Requires
- Android SDK [http://developer.android.com](http://developer.android.com)
- Apache Commons Codec [http://commons.apache.org/codec/](http://commons.apache.org/codec/)
-Test Requirements
----
-- JUnit - [https://github.com/KentBeck/junit](https://github.com/KentBeck/junit)
-Building
----
-
-To create your `cordova.jar` file, copy the commons codec:
-
- mv commons-codec-1.7.jar framework/libs
-
-then run in the framework directory:
-
- android update project -p . -t android-17
- ant jar
-
-
Cordova Android Developer Tools
---
@@ -93,6 +77,22 @@ Importing a Cordova Android Project into Eclipse
5. Right click on the project root: Run as > Run Configurations
6. Click on the Target tab and select Manual (this way you can choose the emulator or device to build to)
+Building without the Tooling
+---
+Note: The Developer Tools handle this. This is only to be done if the tooling fails, or if
+you are developing directly against the framework.
+
+
+To create your `cordova.jar` file, copy the commons codec:
+
+ mv commons-codec-1.7.jar framework/libs
+
+then run in the framework directory:
+
+ android update project -p . -t android-17
+ ant jar
+
+
Running Tests
----
Please see details under test/README.md.
@@ -101,5 +101,5 @@ Further Reading
---
- [http://developer.android.com](http://developer.android.com)
-- [http://incubator.apache.org/cordova/](http://incubator.apache.org/cordova/)
+- [http://cordova.apache.org/](http://cordova.apache.org)
- [http://wiki.apache.org/cordova/](http://wiki.apache.org/cordova/)
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/VERSION
----------------------------------------------------------------------
diff --git a/lib/cordova-android/VERSION b/lib/cordova-android/VERSION
index 24ba9a3..1277c83 100644
--- a/lib/cordova-android/VERSION
+++ b/lib/cordova-android/VERSION
@@ -1 +1 @@
-2.7.0
+2.8.0rc1
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/templates/cordova/lib/cordova
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/templates/cordova/lib/cordova b/lib/cordova-android/bin/templates/cordova/lib/cordova
old mode 100644
new mode 100755
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/templates/cordova/lib/install-device
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/templates/cordova/lib/install-device b/lib/cordova-android/bin/templates/cordova/lib/install-device
old mode 100644
new mode 100755
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/templates/cordova/lib/install-emulator
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/templates/cordova/lib/install-emulator b/lib/cordova-android/bin/templates/cordova/lib/install-emulator
old mode 100644
new mode 100755
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/templates/cordova/lib/list-devices
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/templates/cordova/lib/list-devices b/lib/cordova-android/bin/templates/cordova/lib/list-devices
old mode 100644
new mode 100755
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/templates/cordova/lib/list-emulator-images
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/templates/cordova/lib/list-emulator-images b/lib/cordova-android/bin/templates/cordova/lib/list-emulator-images
old mode 100644
new mode 100755
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/templates/cordova/lib/list-started-emulators
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/templates/cordova/lib/list-started-emulators b/lib/cordova-android/bin/templates/cordova/lib/list-started-emulators
old mode 100644
new mode 100755
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/templates/cordova/lib/start-emulator
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/templates/cordova/lib/start-emulator b/lib/cordova-android/bin/templates/cordova/lib/start-emulator
old mode 100644
new mode 100755
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/templates/cordova/version
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/templates/cordova/version b/lib/cordova-android/bin/templates/cordova/version
old mode 100644
new mode 100755
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/templates/project/assets/www/index.html
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/templates/project/assets/www/index.html b/lib/cordova-android/bin/templates/project/assets/www/index.html
index 564ce18..e84fbd7 100644
--- a/lib/cordova-android/bin/templates/project/assets/www/index.html
+++ b/lib/cordova-android/bin/templates/project/assets/www/index.html
@@ -33,7 +33,7 @@
<p class="event received">Device is Ready</p>
</div>
</div>
- <script type="text/javascript" src="cordova-2.7.0.js"></script>
+ <script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/update
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/update b/lib/cordova-android/bin/update
index 0e86886..9a968b1 100755
--- a/lib/cordova-android/bin/update
+++ b/lib/cordova-android/bin/update
@@ -45,9 +45,9 @@ fi
# cleanup after exit and/or on error
function on_exit {
- if [ -f "$BUILD_PATH"/framework/assets/www/cordova-$VERSION.js ]
+ if [ -f "$BUILD_PATH"/framework/assets/www/cordova.js ]
then
- rm "$BUILD_PATH"/framework/assets/www/cordova-$VERSION.js
+ rm "$BUILD_PATH"/framework/assets/www/cordova.js
fi
if [ -f "$BUILD_PATH"/framework/cordova-$VERSION.jar ]
then
@@ -122,18 +122,25 @@ fi
# copy cordova.js, cordova.jar and res/xml
if [ -d "$BUILD_PATH"/framework ]
then
- cp "$BUILD_PATH"/framework/assets/www/cordova-$VERSION.js "$PROJECT_PATH"/assets/www/cordova-$VERSION.js
+ cp "$BUILD_PATH"/framework/assets/www/cordova.js "$PROJECT_PATH"/assets/www/cordova.js
cp "$BUILD_PATH"/framework/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
else
- cp "$BUILD_PATH"/cordova-$VERSION.js "$PROJECT_PATH"/assets/www/cordova-$VERSION.js
+ cp "$BUILD_PATH"/cordova.js "$PROJECT_PATH"/assets/www/cordova.js
cp "$BUILD_PATH"/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
fi
# creating cordova folder and copying run/build/log/launch scripts
+mkdir "$PROJECT_PATH"/cordova
+mkdir "$PROJECT_PATH"/cordova/lib
cp "$BUILD_PATH"/bin/templates/cordova/appinfo.jar "$PROJECT_PATH"/cordova/appinfo.jar
-cp "$BUILD_PATH"/bin/templates/cordova/cordova "$PROJECT_PATH"/cordova/cordova
cp "$BUILD_PATH"/bin/templates/cordova/build "$PROJECT_PATH"/cordova/build
-cp "$BUILD_PATH"/bin/templates/cordova/release "$PROJECT_PATH"/cordova/release
cp "$BUILD_PATH"/bin/templates/cordova/clean "$PROJECT_PATH"/cordova/clean
cp "$BUILD_PATH"/bin/templates/cordova/log "$PROJECT_PATH"/cordova/log
cp "$BUILD_PATH"/bin/templates/cordova/run "$PROJECT_PATH"/cordova/run
+cp "$BUILD_PATH"/bin/templates/cordova/lib/cordova "$PROJECT_PATH"/cordova/lib/cordova
+cp "$BUILD_PATH"/bin/templates/cordova/lib/install-device "$PROJECT_PATH"/cordova/lib/install-device
+cp "$BUILD_PATH"/bin/templates/cordova/lib/install-emulator "$PROJECT_PATH"/cordova/lib/install-emulator
+cp "$BUILD_PATH"/bin/templates/cordova/lib/list-devices "$PROJECT_PATH"/cordova/lib/list-devices
+cp "$BUILD_PATH"/bin/templates/cordova/lib/list-emulator-images "$PROJECT_PATH"/cordova/lib/list-emulator-images
+cp "$BUILD_PATH"/bin/templates/cordova/lib/list-started-emulators "$PROJECT_PATH"/cordova/lib/list-started-emulators
+cp "$BUILD_PATH"/bin/templates/cordova/lib/start-emulator "$PROJECT_PATH"/cordova/lib/start-emulator
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/bin/update.js
----------------------------------------------------------------------
diff --git a/lib/cordova-android/bin/update.js b/lib/cordova-android/bin/update.js
index 244dcc1..748d602 100644
--- a/lib/cordova-android/bin/update.js
+++ b/lib/cordova-android/bin/update.js
@@ -183,11 +183,17 @@ if(fso.FolderExists(ROOT + '\\framework')) {
createAppInfoJar();
WScript.Echo("Copying cordova command tools...");
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\appinfo.jar ' + PROJECT_PATH + '\\cordova\\appinfo.jar /Y');
-exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\cordova.js ' + PROJECT_PATH + '\\cordova\\cordova.js /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\cordova.bat ' + PROJECT_PATH + '\\cordova\\cordova.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\clean.bat ' + PROJECT_PATH + '\\cordova\\clean.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\build.bat ' + PROJECT_PATH + '\\cordova\\build.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\log.bat ' + PROJECT_PATH + '\\cordova\\log.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\run.bat ' + PROJECT_PATH + '\\cordova\\run.bat /Y');
+exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\cordova.js ' + PROJECT_PATH + '\\cordova\\lib\\cordova.js /Y');
+exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\install-device.bat ' + PROJECT_PATH + '\\cordova\\lib\\install-device.bat /Y');
+exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\install-emulator.bat ' + PROJECT_PATH + '\\cordova\\lib\\install-emulator.bat /Y');
+exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\list-emulator-images.bat ' + PROJECT_PATH + '\\cordova\\lib\\list-emulator-images.bat /Y');
+exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\list-devices.bat ' + PROJECT_PATH + '\\cordova\\lib\\list-devices.bat /Y');
+exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\list-started-emulators.bat ' + PROJECT_PATH + '\\cordova\\lib\\list-started-emulators.bat /Y');
+exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\start-emulator.bat ' + PROJECT_PATH + '\\cordova\\lib\\start-emulator.bat /Y');
cleanup();
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/AndroidManifest.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/AndroidManifest.xml b/lib/cordova-android/framework/AndroidManifest.xml
index 8405172..f1336ea 100755
--- a/lib/cordova-android/framework/AndroidManifest.xml
+++ b/lib/cordova-android/framework/AndroidManifest.xml
@@ -50,16 +50,11 @@
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:debuggable="true">
- <activity android:name=".StandAlone" android:windowSoftInputMode="adjustPan"
- android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
<activity android:name="org.apache.cordova.DroidGap" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/assets/www/cordova.js
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/assets/www/cordova.js b/lib/cordova-android/framework/assets/www/cordova.js
index 2941307..3730047 100644
--- a/lib/cordova-android/framework/assets/www/cordova.js
+++ b/lib/cordova-android/framework/assets/www/cordova.js
@@ -1,9 +1,5 @@
// Platform: android
-
-// commit d0ffb852378ff018bac2f3b12c38098a19b8ce00
-
-// File generated at :: Thu Apr 18 2013 15:10:54 GMT-0400 (EDT)
-
+// 2.8.0rc1-0-g22bc4d8
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
@@ -22,26 +18,36 @@
specific language governing permissions and limitations
under the License.
*/
-
;(function() {
-
+var CORDOVA_JS_BUILD_LABEL = '2.8.0rc1-0-g22bc4d8';
// file: lib/scripts/require.js
var require,
define;
(function () {
- var modules = {};
+ var modules = {},
// Stack of moduleIds currently being built.
- var requireStack = [];
+ requireStack = [],
// Map of module ID -> index into requireStack of modules currently being built.
- var inProgressModules = {};
+ inProgressModules = {},
+ SEPERATOR = ".";
+
+
function build(module) {
- var factory = module.factory;
+ var factory = module.factory,
+ localRequire = function (id) {
+ var resultantId = id;
+ //Its a relative path, so lop off the last portion and add the id (minus "./")
+ if (id.charAt(0) === ".") {
+ resultantId = module.id.slice(0, module.id.lastIndexOf(SEPERATOR)) + SEPERATOR + id.slice(2);
+ }
+ return require(resultantId);
+ };
module.exports = {};
delete module.factory;
- factory(require, module.exports, module);
+ factory(localRequire, module.exports, module);
return module.exports;
}
@@ -1314,8 +1320,6 @@ var CaptureAudioOptions = function(){
this.limit = 1;
// Maximum duration of a single sound clip in seconds.
this.duration = 0;
- // The selected audio mode. Must match with one of the elements in supportedAudioModes array.
- this.mode = null;
};
module.exports = CaptureAudioOptions;
@@ -1356,8 +1360,6 @@ define("cordova/plugin/CaptureImageOptions", function(require, exports, module)
var CaptureImageOptions = function(){
// Upper limit of images user can take. Value must be equal or greater than 1.
this.limit = 1;
- // The selected image mode. Must match with one of the elements in supportedImageModes array.
- this.mode = null;
};
module.exports = CaptureImageOptions;
@@ -1375,8 +1377,6 @@ var CaptureVideoOptions = function(){
this.limit = 1;
// Maximum duration of a single video clip in seconds.
this.duration = 0;
- // The selected video mode. Must match with one of the elements in supportedVideoModes array.
- this.mode = null;
};
module.exports = CaptureVideoOptions;
@@ -5081,12 +5081,16 @@ function Device() {
channel.onCordovaReady.subscribe(function() {
me.getInfo(function(info) {
+ var buildLabel = info.cordova;
+ if (buildLabel != CORDOVA_JS_BUILD_LABEL) {
+ buildLabel += ' JS=' + CORDOVA_JS_BUILD_LABEL;
+ }
me.available = true;
me.platform = info.platform;
me.version = info.version;
me.name = info.name;
me.uuid = info.uuid;
- me.cordova = info.cordova;
+ me.cordova = buildLabel;
me.model = info.model;
channel.onCordovaInfoReady.fire();
},function(e) {
@@ -5843,10 +5847,13 @@ var exec = require('cordova/exec');
var utils = require('cordova/utils');
var UseConsole = true;
+var UseLogger = true;
var Queued = [];
var DeviceReady = false;
var CurrentLevel;
+var originalConsole = console;
+
/**
* Logging levels
*/
@@ -5907,8 +5914,7 @@ logger.level = function (value) {
* Getter/Setter for the useConsole functionality
*
* When useConsole is true, the logger will log via the
- * browser 'console' object. Otherwise, it will use the
- * native Logger plugin.
+ * browser 'console' object.
*/
logger.useConsole = function (value) {
if (arguments.length) UseConsole = !!value;
@@ -5933,6 +5939,18 @@ logger.useConsole = function (value) {
};
/**
+ * Getter/Setter for the useLogger functionality
+ *
+ * When useLogger is true, the logger will log via the
+ * native Logger plugin.
+ */
+logger.useLogger = function (value) {
+ // Enforce boolean
+ if (arguments.length) UseLogger = !!value;
+ return UseLogger;
+};
+
+/**
* Logs a message at the LOG level.
*
* Parameters passed after message are used applied to
@@ -6001,24 +6019,26 @@ logger.logLevel = function(level /* , ... */) {
return;
}
- // if not using the console, use the native logger
- if (!UseConsole) {
+ // Log using the native logger if that is enabled
+ if (UseLogger) {
exec(null, null, "Logger", "logLevel", [level, message]);
- return;
}
- // make sure console is not using logger
- if (console.__usingCordovaLogger) {
- throw new Error("console and logger are too intertwingly");
- }
+ // Log using the console if that is enabled
+ if (UseConsole) {
+ // make sure console is not using logger
+ if (console.__usingCordovaLogger) {
+ throw new Error("console and logger are too intertwingly");
+ }
- // log to the console
- switch (level) {
- case logger.LOG: console.log(message); break;
- case logger.ERROR: console.log("ERROR: " + message); break;
- case logger.WARN: console.log("WARN: " + message); break;
- case logger.INFO: console.log("INFO: " + message); break;
- case logger.DEBUG: console.log("DEBUG: " + message); break;
+ // log to the console
+ switch (level) {
+ case logger.LOG: originalConsole.log(message); break;
+ case logger.ERROR: originalConsole.log("ERROR: " + message); break;
+ case logger.WARN: originalConsole.log("WARN: " + message); break;
+ case logger.INFO: originalConsole.log("INFO: " + message); break;
+ case logger.DEBUG: originalConsole.log("DEBUG: " + message); break;
+ }
}
};
@@ -6279,7 +6299,7 @@ module.exports = {
// Some platforms take an array of button label names.
// Other platforms take a comma separated list.
// For compatibility, we convert to the desired type based on the platform.
- if (platform.id == "android" || platform.id == "ios" || platform.id == "windowsphone") {
+ if (platform.id == "android" || platform.id == "ios" || platform.id == "windowsphone" || platform.id == "blackberry10") {
if (typeof _buttonLabels === 'string') {
var buttonLabelString = _buttonLabels;
_buttonLabels = _buttonLabels.split(","); // not crazy about changing the var type here
@@ -6303,12 +6323,14 @@ module.exports = {
* @param {Function} resultCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the dialog (default: "Prompt")
* @param {Array} buttonLabels Array of strings for the button labels (default: ["OK","Cancel"])
+ * @param {String} defaultText Textbox input value (default: "Default text")
*/
- prompt: function(message, resultCallback, title, buttonLabels) {
+ prompt: function(message, resultCallback, title, buttonLabels, defaultText) {
var _message = (message || "Prompt message");
var _title = (title || "Prompt");
var _buttonLabels = (buttonLabels || ["OK","Cancel"]);
- exec(resultCallback, null, "Notification", "prompt", [_message, _title, _buttonLabels]);
+ var _defaultText = (defaultText || "Default text");
+ exec(resultCallback, null, "Notification", "prompt", [_message, _title, _buttonLabels, _defaultText]);
},
/**
@@ -6650,9 +6672,7 @@ function UUIDcreatePart(length) {
});
-
window.cordova = require('cordova');
-
// file: lib/scripts/bootstrap.js
(function (context) {
@@ -6768,7 +6788,7 @@ require('cordova/channel').onNativeReady.fire();
// See plugman's plugin_loader.js for the details of this object.
// This function is only called if the really is a plugins array that isn't empty.
// Otherwise the XHR response handler will just call finishPluginLoading().
- function handlePluginsObject(modules) {
+ function handlePluginsObject(modules, path) {
// First create the callback for when all plugins are loaded.
var mapper = context.cordova.require('cordova/modulemapper');
onScriptLoadingComplete = function() {
@@ -6802,35 +6822,49 @@ require('cordova/channel').onNativeReady.fire();
// Now inject the scripts.
for (var i = 0; i < modules.length; i++) {
- injectScript(modules[i].file);
+ injectScript(path + modules[i].file);
}
}
-
+ // Find the root of the app
+ var path = '';
+ var scripts = document.getElementsByTagName('script');
+ var term = 'cordova.js';
+ for (var n = scripts.length-1; n>-1; n--) {
+ var src = scripts[n].src;
+ if (src.indexOf(term) == (src.length - term.length)) {
+ path = src.substring(0, src.length - term.length);
+ break;
+ }
+ }
// Try to XHR the cordova_plugins.json file asynchronously.
- try { // we commented we were going to try, so let us actually try and catch
- var xhr = new context.XMLHttpRequest();
- xhr.onload = function() {
- // If the response is a JSON string which composes an array, call handlePluginsObject.
- // If the request fails, or the response is not a JSON array, just call finishPluginLoading.
- var obj = JSON.parse(this.responseText);
- if (obj && obj instanceof Array && obj.length > 0) {
- handlePluginsObject(obj);
- } else {
- finishPluginLoading();
- }
- };
- xhr.onerror = function() {
+ var xhr = new XMLHttpRequest();
+ xhr.onload = function() {
+ // If the response is a JSON string which composes an array, call handlePluginsObject.
+ // If the request fails, or the response is not a JSON array, just call finishPluginLoading.
+ var obj;
+ try {
+ obj = (this.status == 0 || this.status == 200) && this.responseText && JSON.parse(this.responseText);
+ } catch (err) {
+ // obj will be undefined.
+ }
+ if (Array.isArray(obj) && obj.length > 0) {
+ handlePluginsObject(obj, path);
+ } else {
finishPluginLoading();
- };
- xhr.open('GET', 'cordova_plugins.json', true); // Async
+ }
+ };
+ xhr.onerror = function() {
+ finishPluginLoading();
+ };
+ var plugins_json = path + 'cordova_plugins.json';
+ try { // we commented we were going to try, so let us actually try and catch
+ xhr.open('GET', plugins_json, true); // Async
xhr.send();
- }
- catch(err){
+ } catch(err){
finishPluginLoading();
}
}(window));
-
})();
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/assets/www/index.html
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/assets/www/index.html b/lib/cordova-android/framework/assets/www/index.html
index 7723a7b..57ad752 100644
--- a/lib/cordova-android/framework/assets/www/index.html
+++ b/lib/cordova-android/framework/assets/www/index.html
@@ -19,7 +19,7 @@
<html>
<head>
<title></title>
- <script src="cordova-2.7.0.js"></script>
+ <script src="cordova.js"></script>
</head>
<body>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/default.properties
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/default.properties b/lib/cordova-android/framework/default.properties
deleted file mode 100644
index d4e24dc..0000000
--- a/lib/cordova-android/framework/default.properties
+++ /dev/null
@@ -1,14 +0,0 @@
-# This file is automatically generated by Android Tools.
-# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
-#
-# This file must be checked in Version Control Systems.
-#
-# To customize properties used by the Ant build system use,
-# "build.properties", and override values to adapt the script to your
-# project structure.
-
-# Indicates whether an apk should be generated for each density.
-split.density=false
-# Project target.
-target=android-14
-apk-configurations=
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/project.properties
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/project.properties b/lib/cordova-android/framework/project.properties
index d556741..2f39d91 100644
--- a/lib/cordova-android/framework/project.properties
+++ b/lib/cordova-android/framework/project.properties
@@ -10,7 +10,7 @@
# Indicates whether an apk should be generated for each density.
split.density=false
# Project target.
-target=Google Inc.:Google APIs:17
+target=android-17
apk-configurations=
renderscript.opt.level=O0
android.library=true
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/res/xml/config.xml
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/res/xml/config.xml b/lib/cordova-android/framework/res/xml/config.xml
index bc6ca0c..935eda4 100644
--- a/lib/cordova-android/framework/res/xml/config.xml
+++ b/lib/cordova-android/framework/res/xml/config.xml
@@ -1,60 +1,104 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="UTF-8"?>
<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
-->
-<cordova>
- <!--
- access elements control the Android whitelist.
- Domains are assumed blocked unless set otherwise
- -->
+<widget xmlns = "http://www.w3.org/ns/widgets"
+ id = "io.cordova.helloCordova"
+ version = "2.0.0">
+ <name>Hello Cordova</name>
- <access origin="http://127.0.0.1*"/> <!-- allow local pages -->
+ <description>
+ A sample Apache Cordova application that responds to the deviceready event.
+ </description>
- <!-- <access origin="https://example.com" /> allow any secure requests to example.com -->
- <!-- <access origin="https://example.com" subdomains="true" /> such as above, but including subdomains, such as www -->
- <access origin=".*"/>
+ <author href="http://cordova.io" email="dev@cordova.apache.org">
+ Apache Cordova Team
+ </author>
+
+ <access origin="*"/>
<!-- <content src="http://mysite.com/myapp.html" /> for external pages -->
<content src="index.html" />
- <log level="DEBUG"/>
- <preference name="useBrowserHistory" value="true" />
- <preference name="exit-on-suspend" value="false" />
-<plugins>
- <plugin name="App" value="org.apache.cordova.App"/>
- <plugin name="Geolocation" value="org.apache.cordova.GeoBroker"/>
- <plugin name="Device" value="org.apache.cordova.Device"/>
- <plugin name="Accelerometer" value="org.apache.cordova.AccelListener"/>
- <plugin name="Compass" value="org.apache.cordova.CompassListener"/>
- <plugin name="Media" value="org.apache.cordova.AudioHandler"/>
- <plugin name="Camera" value="org.apache.cordova.CameraLauncher"/>
- <plugin name="Contacts" value="org.apache.cordova.ContactManager"/>
- <plugin name="File" value="org.apache.cordova.FileUtils"/>
- <plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager"/>
- <plugin name="Notification" value="org.apache.cordova.Notification"/>
- <plugin name="Storage" value="org.apache.cordova.Storage"/>
- <plugin name="FileTransfer" value="org.apache.cordova.FileTransfer"/>
- <plugin name="Capture" value="org.apache.cordova.Capture"/>
- <plugin name="Battery" value="org.apache.cordova.BatteryListener"/>
- <plugin name="SplashScreen" value="org.apache.cordova.SplashScreen"/>
- <plugin name="Echo" value="org.apache.cordova.Echo" />
- <plugin name="Globalization" value="org.apache.cordova.Globalization"/>
- <plugin name="InAppBrowser" value="org.apache.cordova.InAppBrowser"/>
-</plugins>
-</cordova>
+ <preference name="loglevel" value="DEBUG" />
+ <!--
+ <preference name="splashscreen" value="resourceName" />
+ <preference name="backgroundColor" value="0xFFF" />
+ <preference name="loadUrlTimeoutValue" value="20000" />
+ <preference name="InAppBrowserStorageEnabled" value="true" />
+ <preference name="disallowOverscroll" value="true" />
+ -->
+ <feature name="App">
+ <param name="android-package" value="org.apache.cordova.App"/>
+ </feature>
+ <feature name="Geolocation">
+ <param name="android-package" value="org.apache.cordova.GeoBroker"/>
+ </feature>
+ <feature name="Device">
+ <param name="android-package" value="org.apache.cordova.Device"/>
+ </feature>
+ <feature name="Accelerometer">
+ <param name="android-package" value="org.apache.cordova.AccelListener"/>
+ </feature>
+ <feature name="Compass">
+ <param name="android-package" value="org.apache.cordova.CompassListener"/>
+ </feature>
+ <feature name="Media">
+ <param name="android-package" value="org.apache.cordova.AudioHandler"/>
+ </feature>
+ <feature name="Camera">
+ <param name="android-package" value="org.apache.cordova.CameraLauncher"/>
+ </feature>
+ <feature name="Contacts">
+ <param name="android-package" value="org.apache.cordova.ContactManager"/>
+ </feature>
+ <feature name="File">
+ <param name="android-package" value="org.apache.cordova.FileUtils"/>
+ </feature>
+ <feature name="NetworkStatus">
+ <param name="android-package" value="org.apache.cordova.NetworkManager"/>
+ </feature>
+ <feature name="Notification">
+ <param name="android-package" value="org.apache.cordova.Notification"/>
+ </feature>
+ <feature name="Storage">
+ <param name="android-package" value="org.apache.cordova.Storage"/>
+ </feature>
+ <feature name="FileTransfer">
+ <param name="android-package" value="org.apache.cordova.FileTransfer"/>
+ </feature>
+ <feature name="Capture">
+ <param name="android-package" value="org.apache.cordova.Capture"/>
+ </feature>
+ <feature name="Battery">
+ <param name="android-package" value="org.apache.cordova.BatteryListener"/>
+ </feature>
+ <feature name="SplashScreen">
+ <param name="android-package" value="org.apache.cordova.SplashScreen"/>
+ </feature>
+ <feature name="Echo">
+ <param name="android-package" value="org.apache.cordova.Echo"/>
+ </feature>
+ <feature name="Globalization">
+ <param name="android-package" value="org.apache.cordova.Globalization"/>
+ </feature>
+ <feature name="InAppBrowser">
+ <param name="android-package" value="org.apache.cordova.InAppBrowser"/>
+ </feature>
+ <!-- Deprecated plugins element. Remove in 3.0 -->
+ <plugins>
+ </plugins>
+</widget>
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/Address.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/Address.java b/lib/cordova-android/framework/src/com/squareup/okhttp/Address.java
new file mode 100644
index 0000000..cd41ac9
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/Address.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import java.net.Proxy;
+import java.net.UnknownHostException;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.SSLSocketFactory;
+
+import static com.squareup.okhttp.internal.Util.equal;
+
+/**
+ * A specification for a connection to an origin server. For simple connections,
+ * this is the server's hostname and port. If an explicit proxy is requested (or
+ * {@link Proxy#NO_PROXY no proxy} is explicitly requested), this also includes
+ * that proxy information. For secure connections the address also includes the
+ * SSL socket factory and hostname verifier.
+ *
+ * <p>HTTP requests that share the same {@code Address} may also share the same
+ * {@link Connection}.
+ */
+public final class Address {
+ final Proxy proxy;
+ final String uriHost;
+ final int uriPort;
+ final SSLSocketFactory sslSocketFactory;
+ final HostnameVerifier hostnameVerifier;
+
+ public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
+ HostnameVerifier hostnameVerifier, Proxy proxy) throws UnknownHostException {
+ if (uriHost == null) throw new NullPointerException("uriHost == null");
+ if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
+ this.proxy = proxy;
+ this.uriHost = uriHost;
+ this.uriPort = uriPort;
+ this.sslSocketFactory = sslSocketFactory;
+ this.hostnameVerifier = hostnameVerifier;
+ }
+
+ /** Returns the hostname of the origin server. */
+ public String getUriHost() {
+ return uriHost;
+ }
+
+ /**
+ * Returns the port of the origin server; typically 80 or 443. Unlike
+ * may {@code getPort()} accessors, this method never returns -1.
+ */
+ public int getUriPort() {
+ return uriPort;
+ }
+
+ /**
+ * Returns the SSL socket factory, or null if this is not an HTTPS
+ * address.
+ */
+ public SSLSocketFactory getSslSocketFactory() {
+ return sslSocketFactory;
+ }
+
+ /**
+ * Returns the hostname verifier, or null if this is not an HTTPS
+ * address.
+ */
+ public HostnameVerifier getHostnameVerifier() {
+ return hostnameVerifier;
+ }
+
+ /**
+ * Returns this address's explicitly-specified HTTP proxy, or null to
+ * delegate to the HTTP client's proxy selector.
+ */
+ public Proxy getProxy() {
+ return proxy;
+ }
+
+ @Override public boolean equals(Object other) {
+ if (other instanceof Address) {
+ Address that = (Address) other;
+ return equal(this.proxy, that.proxy)
+ && this.uriHost.equals(that.uriHost)
+ && this.uriPort == that.uriPort
+ && equal(this.sslSocketFactory, that.sslSocketFactory)
+ && equal(this.hostnameVerifier, that.hostnameVerifier);
+ }
+ return false;
+ }
+
+ @Override public int hashCode() {
+ int result = 17;
+ result = 31 * result + uriHost.hashCode();
+ result = 31 * result + uriPort;
+ result = 31 * result + (sslSocketFactory != null ? sslSocketFactory.hashCode() : 0);
+ result = 31 * result + (hostnameVerifier != null ? hostnameVerifier.hashCode() : 0);
+ result = 31 * result + (proxy != null ? proxy.hashCode() : 0);
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/Connection.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/Connection.java b/lib/cordova-android/framework/src/com/squareup/okhttp/Connection.java
new file mode 100644
index 0000000..6a6c84d
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/Connection.java
@@ -0,0 +1,291 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import com.squareup.okhttp.internal.Platform;
+import com.squareup.okhttp.internal.http.HttpAuthenticator;
+import com.squareup.okhttp.internal.http.HttpEngine;
+import com.squareup.okhttp.internal.http.HttpTransport;
+import com.squareup.okhttp.internal.http.RawHeaders;
+import com.squareup.okhttp.internal.http.SpdyTransport;
+import com.squareup.okhttp.internal.spdy.SpdyConnection;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Proxy;
+import java.net.Socket;
+import java.net.URL;
+import java.util.Arrays;
+import javax.net.ssl.SSLSocket;
+
+import static java.net.HttpURLConnection.HTTP_OK;
+import static java.net.HttpURLConnection.HTTP_PROXY_AUTH;
+
+/**
+ * Holds the sockets and streams of an HTTP, HTTPS, or HTTPS+SPDY connection,
+ * which may be used for multiple HTTP request/response exchanges. Connections
+ * may be direct to the origin server or via a proxy.
+ *
+ * <p>Typically instances of this class are created, connected and exercised
+ * automatically by the HTTP client. Applications may use this class to monitor
+ * HTTP connections as members of a {@link ConnectionPool connection pool}.
+ *
+ * <p>Do not confuse this class with the misnamed {@code HttpURLConnection},
+ * which isn't so much a connection as a single request/response exchange.
+ *
+ * <h3>Modern TLS</h3>
+ * There are tradeoffs when selecting which options to include when negotiating
+ * a secure connection to a remote host. Newer TLS options are quite useful:
+ * <ul>
+ * <li>Server Name Indication (SNI) enables one IP address to negotiate secure
+ * connections for multiple domain names.
+ * <li>Next Protocol Negotiation (NPN) enables the HTTPS port (443) to be used
+ * for both HTTP and SPDY transports.
+ * </ul>
+ * Unfortunately, older HTTPS servers refuse to connect when such options are
+ * presented. Rather than avoiding these options entirely, this class allows a
+ * connection to be attempted with modern options and then retried without them
+ * should the attempt fail.
+ */
+public final class Connection implements Closeable {
+ private static final byte[] NPN_PROTOCOLS = new byte[] {
+ 6, 's', 'p', 'd', 'y', '/', '3',
+ 8, 'h', 't', 't', 'p', '/', '1', '.', '1'
+ };
+ private static final byte[] SPDY3 = new byte[] {
+ 's', 'p', 'd', 'y', '/', '3'
+ };
+ private static final byte[] HTTP_11 = new byte[] {
+ 'h', 't', 't', 'p', '/', '1', '.', '1'
+ };
+
+ private final Route route;
+
+ private Socket socket;
+ private InputStream in;
+ private OutputStream out;
+ private boolean connected = false;
+ private SpdyConnection spdyConnection;
+ private int httpMinorVersion = 1; // Assume HTTP/1.1
+ private long idleStartTimeNs;
+
+ public Connection(Route route) {
+ this.route = route;
+ }
+
+ public void connect(int connectTimeout, int readTimeout, TunnelRequest tunnelRequest)
+ throws IOException {
+ if (connected) {
+ throw new IllegalStateException("already connected");
+ }
+ connected = true;
+ socket = (route.proxy.type() != Proxy.Type.HTTP) ? new Socket(route.proxy) : new Socket();
+ socket.connect(route.inetSocketAddress, connectTimeout);
+ socket.setSoTimeout(readTimeout);
+ in = socket.getInputStream();
+ out = socket.getOutputStream();
+
+ if (route.address.sslSocketFactory != null) {
+ upgradeToTls(tunnelRequest);
+ }
+
+ // Use MTU-sized buffers to send fewer packets.
+ int mtu = Platform.get().getMtu(socket);
+ in = new BufferedInputStream(in, mtu);
+ out = new BufferedOutputStream(out, mtu);
+ }
+
+ /**
+ * Create an {@code SSLSocket} and perform the TLS handshake and certificate
+ * validation.
+ */
+ private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException {
+ Platform platform = Platform.get();
+
+ // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
+ if (requiresTunnel()) {
+ makeTunnel(tunnelRequest);
+ }
+
+ // Create the wrapper over connected socket.
+ socket = route.address.sslSocketFactory
+ .createSocket(socket, route.address.uriHost, route.address.uriPort, true /* autoClose */);
+ SSLSocket sslSocket = (SSLSocket) socket;
+ if (route.modernTls) {
+ platform.enableTlsExtensions(sslSocket, route.address.uriHost);
+ } else {
+ platform.supportTlsIntolerantServer(sslSocket);
+ }
+
+ if (route.modernTls) {
+ platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS);
+ }
+
+ // Force handshake. This can throw!
+ sslSocket.startHandshake();
+
+ // Verify that the socket's certificates are acceptable for the target host.
+ if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) {
+ throw new IOException("Hostname '" + route.address.uriHost + "' was not verified");
+ }
+
+ out = sslSocket.getOutputStream();
+ in = sslSocket.getInputStream();
+
+ byte[] selectedProtocol;
+ if (route.modernTls
+ && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
+ if (Arrays.equals(selectedProtocol, SPDY3)) {
+ sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
+ spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out)
+ .build();
+ } else if (!Arrays.equals(selectedProtocol, HTTP_11)) {
+ throw new IOException(
+ "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1"));
+ }
+ }
+ }
+
+ /** Returns true if {@link #connect} has been attempted on this connection. */
+ public boolean isConnected() {
+ return connected;
+ }
+
+ @Override public void close() throws IOException {
+ socket.close();
+ }
+
+ /** Returns the route used by this connection. */
+ public Route getRoute() {
+ return route;
+ }
+
+ /**
+ * Returns the socket that this connection uses, or null if the connection
+ * is not currently connected.
+ */
+ public Socket getSocket() {
+ return socket;
+ }
+
+ /** Returns true if this connection is alive. */
+ public boolean isAlive() {
+ return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown();
+ }
+
+ public void resetIdleStartTime() {
+ if (spdyConnection != null) {
+ throw new IllegalStateException("spdyConnection != null");
+ }
+ this.idleStartTimeNs = System.nanoTime();
+ }
+
+ /** Returns true if this connection is idle. */
+ public boolean isIdle() {
+ return spdyConnection == null || spdyConnection.isIdle();
+ }
+
+ /**
+ * Returns true if this connection has been idle for longer than
+ * {@code keepAliveDurationNs}.
+ */
+ public boolean isExpired(long keepAliveDurationNs) {
+ return isIdle() && System.nanoTime() - getIdleStartTimeNs() > keepAliveDurationNs;
+ }
+
+ /**
+ * Returns the time in ns when this connection became idle. Undefined if
+ * this connection is not idle.
+ */
+ public long getIdleStartTimeNs() {
+ return spdyConnection == null ? idleStartTimeNs : spdyConnection.getIdleStartTimeNs();
+ }
+
+ /** Returns the transport appropriate for this connection. */
+ public Object newTransport(HttpEngine httpEngine) throws IOException {
+ return (spdyConnection != null) ? new SpdyTransport(httpEngine, spdyConnection)
+ : new HttpTransport(httpEngine, out, in);
+ }
+
+ /**
+ * Returns true if this is a SPDY connection. Such connections can be used
+ * in multiple HTTP requests simultaneously.
+ */
+ public boolean isSpdy() {
+ return spdyConnection != null;
+ }
+
+ public SpdyConnection getSpdyConnection() {
+ return spdyConnection;
+ }
+
+ /**
+ * Returns the minor HTTP version that should be used for future requests on
+ * this connection. Either 0 for HTTP/1.0, or 1 for HTTP/1.1. The default
+ * value is 1 for new connections.
+ */
+ public int getHttpMinorVersion() {
+ return httpMinorVersion;
+ }
+
+ public void setHttpMinorVersion(int httpMinorVersion) {
+ this.httpMinorVersion = httpMinorVersion;
+ }
+
+ /**
+ * Returns true if the HTTP connection needs to tunnel one protocol over
+ * another, such as when using HTTPS through an HTTP proxy. When doing so,
+ * we must avoid buffering bytes intended for the higher-level protocol.
+ */
+ public boolean requiresTunnel() {
+ return route.address.sslSocketFactory != null && route.proxy.type() == Proxy.Type.HTTP;
+ }
+
+ /**
+ * To make an HTTPS connection over an HTTP proxy, send an unencrypted
+ * CONNECT request to create the proxy connection. This may need to be
+ * retried if the proxy requires authorization.
+ */
+ private void makeTunnel(TunnelRequest tunnelRequest) throws IOException {
+ RawHeaders requestHeaders = tunnelRequest.getRequestHeaders();
+ while (true) {
+ out.write(requestHeaders.toBytes());
+ RawHeaders responseHeaders = RawHeaders.fromBytes(in);
+
+ switch (responseHeaders.getResponseCode()) {
+ case HTTP_OK:
+ return;
+ case HTTP_PROXY_AUTH:
+ requestHeaders = new RawHeaders(requestHeaders);
+ URL url = new URL("https", tunnelRequest.host, tunnelRequest.port, "/");
+ boolean credentialsFound = HttpAuthenticator.processAuthHeader(HTTP_PROXY_AUTH,
+ responseHeaders, requestHeaders, route.proxy, url);
+ if (credentialsFound) {
+ continue;
+ } else {
+ throw new IOException("Failed to authenticate with proxy");
+ }
+ default:
+ throw new IOException(
+ "Unexpected response code for CONNECT: " + responseHeaders.getResponseCode());
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-android/framework/src/com/squareup/okhttp/ConnectionPool.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/ConnectionPool.java b/lib/cordova-android/framework/src/com/squareup/okhttp/ConnectionPool.java
new file mode 100644
index 0000000..933bd73
--- /dev/null
+++ b/lib/cordova-android/framework/src/com/squareup/okhttp/ConnectionPool.java
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import com.squareup.okhttp.internal.Platform;
+import com.squareup.okhttp.internal.Util;
+import java.net.SocketException;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Manages reuse of HTTP and SPDY connections for reduced network latency. HTTP
+ * requests that share the same {@link com.squareup.okhttp.Address} may share a
+ * {@link com.squareup.okhttp.Connection}. This class implements the policy of
+ * which connections to keep open for future use.
+ *
+ * <p>The {@link #getDefault() system-wide default} uses system properties for
+ * tuning parameters:
+ * <ul>
+ * <li>{@code http.keepAlive} true if HTTP and SPDY connections should be
+ * pooled at all. Default is true.
+ * <li>{@code http.maxConnections} maximum number of idle connections to
+ * each to keep in the pool. Default is 5.
+ * <li>{@code http.keepAliveDuration} Time in milliseconds to keep the
+ * connection alive in the pool before closing it. Default is 5 minutes.
+ * This property isn't used by {@code HttpURLConnection}.
+ * </ul>
+ *
+ * <p>The default instance <i>doesn't</i> adjust its configuration as system
+ * properties are changed. This assumes that the applications that set these
+ * parameters do so before making HTTP connections, and that this class is
+ * initialized lazily.
+ */
+public class ConnectionPool {
+ private static final int MAX_CONNECTIONS_TO_CLEANUP = 2;
+ private static final long DEFAULT_KEEP_ALIVE_DURATION_MS = 5 * 60 * 1000; // 5 min
+
+ private static final ConnectionPool systemDefault;
+
+ static {
+ String keepAlive = System.getProperty("http.keepAlive");
+ String keepAliveDuration = System.getProperty("http.keepAliveDuration");
+ String maxIdleConnections = System.getProperty("http.maxConnections");
+ long keepAliveDurationMs = keepAliveDuration != null ? Long.parseLong(keepAliveDuration)
+ : DEFAULT_KEEP_ALIVE_DURATION_MS;
+ if (keepAlive != null && !Boolean.parseBoolean(keepAlive)) {
+ systemDefault = new ConnectionPool(0, keepAliveDurationMs);
+ } else if (maxIdleConnections != null) {
+ systemDefault = new ConnectionPool(Integer.parseInt(maxIdleConnections), keepAliveDurationMs);
+ } else {
+ systemDefault = new ConnectionPool(5, keepAliveDurationMs);
+ }
+ }
+
+ /** The maximum number of idle connections for each address. */
+ private final int maxIdleConnections;
+ private final long keepAliveDurationNs;
+
+ private final LinkedList<Connection> connections = new LinkedList<Connection>();
+
+ /** We use a single background thread to cleanup expired connections. */
+ private final ExecutorService executorService =
+ new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
+ private final Callable<Void> connectionsCleanupCallable = new Callable<Void>() {
+ @Override public Void call() throws Exception {
+ List<Connection> expiredConnections = new ArrayList<Connection>(MAX_CONNECTIONS_TO_CLEANUP);
+ int idleConnectionCount = 0;
+ synchronized (ConnectionPool.this) {
+ for (ListIterator<Connection> i = connections.listIterator(connections.size());
+ i.hasPrevious(); ) {
+ Connection connection = i.previous();
+ if (!connection.isAlive() || connection.isExpired(keepAliveDurationNs)) {
+ i.remove();
+ expiredConnections.add(connection);
+ if (expiredConnections.size() == MAX_CONNECTIONS_TO_CLEANUP) break;
+ } else if (connection.isIdle()) {
+ idleConnectionCount++;
+ }
+ }
+
+ for (ListIterator<Connection> i = connections.listIterator(connections.size());
+ i.hasPrevious() && idleConnectionCount > maxIdleConnections; ) {
+ Connection connection = i.previous();
+ if (connection.isIdle()) {
+ expiredConnections.add(connection);
+ i.remove();
+ --idleConnectionCount;
+ }
+ }
+ }
+ for (Connection expiredConnection : expiredConnections) {
+ Util.closeQuietly(expiredConnection);
+ }
+ return null;
+ }
+ };
+
+ public ConnectionPool(int maxIdleConnections, long keepAliveDurationMs) {
+ this.maxIdleConnections = maxIdleConnections;
+ this.keepAliveDurationNs = keepAliveDurationMs * 1000 * 1000;
+ }
+
+ /**
+ * Returns a snapshot of the connections in this pool, ordered from newest to
+ * oldest. Waits for the cleanup callable to run if it is currently scheduled.
+ */
+ List<Connection> getConnections() {
+ waitForCleanupCallableToRun();
+ synchronized (this) {
+ return new ArrayList<Connection>(connections);
+ }
+ }
+
+ /**
+ * Blocks until the executor service has processed all currently enqueued
+ * jobs.
+ */
+ private void waitForCleanupCallableToRun() {
+ try {
+ executorService.submit(new Runnable() {
+ @Override public void run() {
+ }
+ }).get();
+ } catch (Exception e) {
+ throw new AssertionError();
+ }
+ }
+
+ public static ConnectionPool getDefault() {
+ return systemDefault;
+ }
+
+ /** Returns total number of connections in the pool. */
+ public synchronized int getConnectionCount() {
+ return connections.size();
+ }
+
+ /** Returns total number of spdy connections in the pool. */
+ public synchronized int getSpdyConnectionCount() {
+ int total = 0;
+ for (Connection connection : connections) {
+ if (connection.isSpdy()) total++;
+ }
+ return total;
+ }
+
+ /** Returns total number of http connections in the pool. */
+ public synchronized int getHttpConnectionCount() {
+ int total = 0;
+ for (Connection connection : connections) {
+ if (!connection.isSpdy()) total++;
+ }
+ return total;
+ }
+
+ /** Returns a recycled connection to {@code address}, or null if no such connection exists. */
+ public synchronized Connection get(Address address) {
+ Connection foundConnection = null;
+ for (ListIterator<Connection> i = connections.listIterator(connections.size());
+ i.hasPrevious(); ) {
+ Connection connection = i.previous();
+ if (!connection.getRoute().getAddress().equals(address)
+ || !connection.isAlive()
+ || System.nanoTime() - connection.getIdleStartTimeNs() >= keepAliveDurationNs) {
+ continue;
+ }
+ i.remove();
+ if (!connection.isSpdy()) {
+ try {
+ Platform.get().tagSocket(connection.getSocket());
+ } catch (SocketException e) {
+ Util.closeQuietly(connection);
+ // When unable to tag, skip recycling and close
+ Platform.get().logW("Unable to tagSocket(): " + e);
+ continue;
+ }
+ }
+ foundConnection = connection;
+ break;
+ }
+
+ if (foundConnection != null && foundConnection.isSpdy()) {
+ connections.addFirst(foundConnection); // Add it back after iteration.
+ }
+
+ executorService.submit(connectionsCleanupCallable);
+ return foundConnection;
+ }
+
+ /**
+ * Gives {@code connection} to the pool. The pool may store the connection,
+ * or close it, as its policy describes.
+ *
+ * <p>It is an error to use {@code connection} after calling this method.
+ */
+ public void recycle(Connection connection) {
+ executorService.submit(connectionsCleanupCallable);
+
+ if (connection.isSpdy()) {
+ return;
+ }
+
+ if (!connection.isAlive()) {
+ Util.closeQuietly(connection);
+ return;
+ }
+
+ try {
+ Platform.get().untagSocket(connection.getSocket());
+ } catch (SocketException e) {
+ // When unable to remove tagging, skip recycling and close.
+ Platform.get().logW("Unable to untagSocket(): " + e);
+ Util.closeQuietly(connection);
+ return;
+ }
+
+ synchronized (this) {
+ connections.addFirst(connection);
+ connection.resetIdleStartTime();
+ }
+ }
+
+ /**
+ * Shares the SPDY connection with the pool. Callers to this method may
+ * continue to use {@code connection}.
+ */
+ public void maybeShare(Connection connection) {
+ executorService.submit(connectionsCleanupCallable);
+ if (!connection.isSpdy()) {
+ // Only SPDY connections are sharable.
+ return;
+ }
+ if (connection.isAlive()) {
+ synchronized (this) {
+ connections.addFirst(connection);
+ }
+ }
+ }
+
+ /** Close and remove all connections in the pool. */
+ public void evictAll() {
+ List<Connection> connections;
+ synchronized (this) {
+ connections = new ArrayList<Connection>(this.connections);
+ this.connections.clear();
+ }
+
+ for (Connection connection : connections) {
+ Util.closeQuietly(connection);
+ }
+ }
+}
[19/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Util.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Util.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Util.java
deleted file mode 100644
index 340876e..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/globalization/Util.java
+++ /dev/null
@@ -1,721 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.globalization;
-
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Hashtable;
-import java.util.TimeZone;
-
-import net.rim.device.api.i18n.DateFormat;
-import net.rim.device.api.i18n.Locale;
-import net.rim.device.api.i18n.SimpleDateFormat;
-import net.rim.device.api.system.NonPersistableObjectException;
-import net.rim.device.api.system.PersistentObject;
-import net.rim.device.api.system.PersistentStore;
-import net.rim.device.api.util.StringMatch;
-import net.rim.device.api.util.StringUtilities;
-import net.rim.device.api.compress.GZIPInputStream;
-
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.json4j.internal.Parser;
-import org.apache.cordova.util.StringUtils;
-import org.apache.cordova.util.Logger;
-
-public class Util {
-
- /**
- * Provides manual date string parsing
- *
- * @param d
- * Date string
- * @param p
- * Pattern string
- * @return Calendar
- */
- public static Calendar dateParserBB(String d, String p) {
- String time = "";
- String date = d;
- String delimiter = Resources.DATEDELIMITER; // "-"
- try {
- // replace '/' with '-' (to compensate for delimiters '/' and '-' in
- // string)
- date = date.replace('/', '-');
-
- // extract time first
- if (date.indexOf(':') > 0) {
- time = date.substring(date.indexOf(':') - 2, date.length())
- .trim();
- date = date.substring(0, date.indexOf(':') - 2).trim();
- }
-
- // determine string delimiter
- if (date.indexOf(delimiter) == -1) { // is not in short format
- delimiter = Resources.SPACE; // " "
- }
-
- // split date into sections
- JSONArray str = Util.split(date, delimiter);
- if (str == null) {
- throw new Exception(); // incorrect format
- }
-
- // remove day of week and other unwanted characters -- will
- // automatically be set in calendar object
- str = Util.removeDayOfWeek(str);
-
- // convert month string into integer: if applicable
- str = Util.convertMonthString(str);
-
- // use pattern to determine order of dd, mm, yyyy. If no pattern
- // will use Locale Default order
- Hashtable patternFmt = Util.getDatePattern(p);
-
- // create calendar object
- Calendar c = Calendar.getInstance(TimeZone.getDefault());
-
- // set calendar instance:
- c.set(Calendar.YEAR, Integer.parseInt(removeSymbols(str
- .getString(Integer.parseInt(patternFmt.get("year")
- .toString())))));
- c.set(Calendar.MONTH, Integer.parseInt(removeSymbols(str
- .getString(Integer.parseInt(patternFmt.get("month")
- .toString())))));
- c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(removeSymbols(str
- .getString(Integer.parseInt(patternFmt.get("day")
- .toString())))));
-
- // set time if applicable
- if (time.length() > 0) {
- JSONArray t = Util.split(time, Resources.TIMEDELIMITER);
- // determine if 12hour or 24hour clock
- int am_pm = getAmPm(t.getString(t.length() - 1).toString());
- if (!t.isNull(0)) {
- c.set(Calendar.HOUR,
- Integer.parseInt(removeSymbols(t.getString(0))));
- }
- if (!t.isNull(1)) {
- c.set(Calendar.MINUTE,
- Integer.parseInt(removeSymbols(t.getString(1))));
- }
- if (!t.isNull(2)) {
- c.set(Calendar.SECOND,
- Integer.parseInt(removeSymbols(t.getString(2))));
- }
- if (am_pm != -1) {
- c.set(Calendar.AM_PM, am_pm);
- }
- }
- return c;
- } catch (Exception e) {
- }
- return null;
- }
-
- /**
- * Returns a pattern string for formatting and parsing dates according to
- * the client's user preferences.
- *
- * @param options
- * JSONArray options (user pattern)
- *
- * @return String (String}: The date and time pattern for formatting and
- * parsing dates. The patterns follow Unicode Technical Standard #35
- * http://unicode.org/reports/tr35/tr35-4.html
- *
- * @throws GlobalizationError
- */
- public static String getBlackBerryDatePattern(JSONArray options)
- throws GlobalizationError {
-
- try {
- // default user preference for date
- String fmtDate = ((SimpleDateFormat) DateFormat
- .getInstance(DateFormat.DATE_SHORT)).toPattern();
- // default user preference for time
- String fmtTime = ((SimpleDateFormat) DateFormat
- .getInstance(DateFormat.TIME_SHORT)).toPattern();
- // default SHORT date/time format. ex. dd/MM/yyyy h:mma
- String fmt = fmtDate + Resources.SPACE + fmtTime;
-
- // get Date value + options (if available)
- if (options.getJSONObject(0).length() > 1) {
- // options were included. get formatLength option
- if (!((JSONObject) options.getJSONObject(0).get(
- Resources.OPTIONS)).isNull(Resources.FORMATLENGTH)) {
- String fmtOpt = (String) ((JSONObject) options
- .getJSONObject(0).get(Resources.OPTIONS))
- .get(Resources.FORMATLENGTH);
- // medium
- if (fmtOpt.equalsIgnoreCase(Resources.MEDIUM)) {
- // default user preference for date
- fmtDate = ((SimpleDateFormat) DateFormat
- .getInstance(DateFormat.DATE_MEDIUM))
- .toPattern();
- // default user preference for time
- fmtTime = ((SimpleDateFormat) DateFormat
- .getInstance(DateFormat.TIME_MEDIUM))
- .toPattern();
- } else if (fmtOpt.equalsIgnoreCase(Resources.LONG)) { // long/full
- // default user preference for date
- fmtDate = ((SimpleDateFormat) DateFormat
- .getInstance(DateFormat.DATE_LONG)).toPattern();
- // default user preference for time
- fmtTime = ((SimpleDateFormat) DateFormat
- .getInstance(DateFormat.TIME_LONG)).toPattern();
- } else if (fmtOpt.equalsIgnoreCase(Resources.FULL)) { // long/full
- // default user preference for date
- fmtDate = ((SimpleDateFormat) DateFormat
- .getInstance(DateFormat.DATE_FULL)).toPattern();
- // default user preference for time
- fmtTime = ((SimpleDateFormat) DateFormat
- .getInstance(DateFormat.TIME_FULL)).toPattern();
- }
- }
-
- // return pattern type
- fmt = fmtDate + Resources.SPACE + fmtTime;
- if (!((JSONObject) options.getJSONObject(0).get(
- Resources.OPTIONS)).isNull(Resources.SELECTOR)) {
- String selOpt = (String) ((JSONObject) options
- .getJSONObject(0).get(Resources.OPTIONS))
- .get(Resources.SELECTOR);
- if (selOpt.equalsIgnoreCase(Resources.DATE)) {
- fmt = fmtDate;
- } else if (selOpt.equalsIgnoreCase(Resources.TIME)) {
- fmt = fmtTime;
- }
- }
- }
- return fmt;
- } catch (Exception ge) {
- }
- return null;
- }
-
- /**
- * Returns a JSONArray of either the names of the months or days of the week
- * according to the client's user preferences and calendar. Note: Months
- * will be in order from Jan - Dec, while days of week will begin on random
- * day due to Locale time differences of defined long date values
- *
- * @param item
- * String item (days of week or months)
- * @param pattern
- * String pattern (pattern to parse item)
- * @return JSONArray The array of names starting from either the first month
- * in the year or the first day of the week.
- */
- public static JSONArray getDateNameString(String item, String pattern) {
- JSONArray value = new JSONArray();
-
- // multipliers
- long day = 1000 * 60 * 60 * 24; // 86,400,000
- long startDay = day * 3; // starting three days in to avoid locale
- // differences
- long month = day * 31; // 2,678,400,000
-
- SimpleDateFormat fmt = new SimpleDateFormat(pattern,
- Locale.getDefault());
- Date d = new Date();
- try {
- if (item.equalsIgnoreCase(Resources.MONTHS)) {
- for (int x = 0; x < 13; x++) {
- d = new Date(startDay + (month * x));
- // testing short Month first
- if (!value.contains(fmt.format(d).toString())
- && !value.isEmpty()) {
- // add day into array
- value.put(fmt.format(d).toString());
- } else if (value.isEmpty()) {
- // Initialize array
- value.put(fmt.format(d).toString());
- }
- }
- } else { // Days
- for (int x = 3; x < 11; x++) {
- d = new Date(day * x);
- // testing short day first
- if (!value.contains(fmt.format(d).toString())
- && !value.isEmpty()) {
- // add day into array
- value.put(fmt.format(d).toString());
- } else if (value.isEmpty()) {
- // Initialize array
- value.put(fmt.format(d).toString());
- }
- }
- }
- return value;
- } catch (Exception e) {
- }
- return null;
- }
-
- /**
- * Parses a String formatted as a percent or currency removing the symbol
- * returns the corresponding number.
- *
- * @return String Corresponding number
- *
- * @throws Exception
- */
- public static String removeSymbols(String s) throws Exception {
- StringBuffer sb = new StringBuffer(s.trim());
- try {
- // begin removing all characters before string
- for (int x = 0; x < sb.length(); x++) {
- if (Character.isDigit(sb.charAt(x))) {
- x = sb.length() - 1; // end loop
- } else {
- sb.deleteCharAt(x);
- }
- }
- // begin removing all characters after string
- for (int x = sb.length() - 1; x > -1; x--) {
- if (Character.isDigit(sb.charAt(x))) {
- x = 0; // end loop
- } else {
- sb.deleteCharAt(x);
- }
- }
- return sb.toString().trim();
- } catch (Exception e) {
- }
- return null;
- }
-
- /**
- * Splits string into a JSONArray Note: Other options are to use
- * org.apache.cordova.util.StringUtils.split(String strString, String
- * strDelimiter)
- *
- * @param s
- * String s (String to split)
- * @param delimiter
- * String delimiter (String used to split s)
- * @return JSONArray: String objects
- */
- public static JSONArray split(String s, String delimiter) {
- JSONArray result = new JSONArray();
- String str = s;
- try {
- int p = s.indexOf(delimiter);
- if (p != -1) {
- while (p != -1) {
- result.put(str.substring(0, p).trim());
- if (p + 1 <= str.length()) {
- str = str.substring(p + 1);
- } else {
- // delimiter is the last character in the string
- str = "";
- break;
- }
- p = str.indexOf(delimiter);
- }
- // add remaining characters if any
- if (str.length() > 0) {
- result.put(str);
- }
- return result;
- }
- return null; // incorrect delimiter
- } catch (Exception e) {
- }
- return null; // error thrown
- }
-
- /**
- * If applicable; removes day of week and other unwanted characters from
- * JSONArray
- *
- * @param s
- * JSONArray s (List of date properties)
- *
- * @return JSONArray:
- * [key: day], [int: position]
- * [key: month], [int: position]
- * [key: year], [int: position]
- */
- public static JSONArray removeDayOfWeek(JSONArray s) {
- JSONArray str = s;
- JSONArray list;
- try {
- // get week names in short format //$NON-NLS-1$
- list = getDateNameString(Resources.DAYS, "EEE");
-
- // remove day of week from JSONArray
- for (int x = 0; x < str.length(); x++) {
- // do manual checking due to short or long version of week
- // validate entry is not already an int
- if (!Character.isDigit(str.getString(x).charAt(0))) {
- // run though short weeks to get match and remove
- StringMatch sm;
- for (int y = 0; y < list.length(); y++) {
- sm = new StringMatch(list.getString(y));
- if (sm.indexOf(str.getString(x)) != -1) {// week found
- str.removeElementAt(x); // remove day of week
- return str;
- }
- // if end of list reached, load long version of names
- // and rerun loop
- if (y == list.length() - 1) {
- y = -1;
- // get week names in long format//$NON-NLS-1$
- list = getDateNameString(Resources.DAYS, "EEEE");
- }
- }
- }
- }
- } catch (Exception e) {
- }// exception caught, return initial JSONArray
- return s;
- }
-
- /**
- * If applicable; converts Month String into number
- *
- * @param s
- * JSONArray s (List of date properties)
- *
- * @return JSONArray:
- * [key: day], [int: position]
- * [key: month], [int: position]
- * [key: year], [int: position]
- */
- public static JSONArray convertMonthString(JSONArray s) {
- JSONArray str = s;
- JSONArray list;
- try {
- // get month names in short format
- list = getDateNameString(Resources.MONTHS, "MMM");
-
- // convert month string into integer if applicable
- for (int x = 0; x < str.length(); x++) {
- // do manual checking due to short or long version of months
- // validate entry is not already an int
- if (!Character.isDigit(str.getString(x).charAt(0))) {
- // run though short format months to get index number
- StringMatch sm;
- for (int y = 0; y < list.length(); y++) {
- sm = new StringMatch(list.getString(y));
- if (sm.indexOf(str.getString(x)) != -1) {// month found
- // replace string with integer
- str.setElementAt(String.valueOf(y), x);
- return str;
- }
- // if end of list reached load long version of names and
- // rerun loop
- if (y == list.length() - 1) {
- y = -1;
- // get month names in long format
- list = getDateNameString(Resources.MONTHS, "MMMM");
- }
- }
- }
- }
- return str;
- } catch (Exception e) {
- }// exception caught, return initial JSONArray
- return s;
- }
-
- /**
- * Determine if am_pm present and return value. if not return -1
- *
- * @param time
- * String time (time string of date object)
- *
- * @return int
- * -1 = am_pm not present
- * 0 = am
- * 1 = pm
- */
- public static int getAmPm(String time) {
- // multipliers
- long am_pm = 0; // pm
- long am_pm_12 = 43200000; // am
- int value = 1;
- boolean reloop = true;
-
- Date d = new Date(am_pm);
-
- for (int x = 0; x < Resources.AM_PMFORMATS.length; x++) {
- SimpleDateFormat fmt = new SimpleDateFormat(
- Resources.AM_PMFORMATS[x], Locale.getDefault());
-
- StringMatch sm = new StringMatch(fmt.format(d).toString());
-
- if (sm.indexOf(time) != -1) {
- return value;
- }
-
- if (x == Resources.AM_PMFORMATS.length - 1 && reloop) {
- d = new Date(am_pm_12);
- value = 0;
- x = -1;
- reloop = false;
- }
- }
- return -1;
- }
-
- /**
- * Returns Hashtable indicating position of dd, MM, and yyyy in string.
- * Position will either be 0, 1, or 2
- *
- * @param p
- * String pattern
- *
- * @return Hashtable:
- * [key: day], [int: position]
- * [key: month], [int: position]
- * [key: year], [int: position]
- *
- * @throws Exception
- */
- public static Hashtable getDatePattern(String p) {
- Hashtable result = new Hashtable();
-
- if (p.length() <= 0) {
- // default device preference for date
- p = ((SimpleDateFormat) DateFormat
- .getInstance(DateFormat.DATE_SHORT)).toPattern();
- }
-
- // get positions
- int day = p.indexOf('d'); //$NON-NLS-1$
- int month = p.indexOf('M'); //$NON-NLS-1$
- int year = p.indexOf('y'); //$NON-NLS-1$
- // int weekDay = p.indexOf('E'); //removed in removeDayOfWeek()
-
- if (year < day && day < month) { // yyyy/dd/mmmm
- year = 0;
- day = 1;
- month = 2;
- } else if (day < month && month < year) { // dd/mm/yyyy
- year = 2;
- day = 0;
- month = 1;
- } else if (year < month && month < day) {// yyyy/mm/dd
- year = 0;
- day = 2;
- month = 1;
- } else if (month < day && day < year) { // mm/dd/yyyy
- year = 2;
- day = 1;
- month = 0;
- } else if (month < year && year < day) { // mm/yyyy/dd
- year = 1;
- day = 2;
- month = 0;
- } else if (day < year && year < month) { // dd/yyyy/mm
- year = 1;
- day = 0;
- month = 2;
- } else {
- return null; // an error has occurred
- }
- result.put("day", String.valueOf(day)); //$NON-NLS-1$
- result.put("month", String.valueOf(month)); //$NON-NLS-1$
- result.put("year", String.valueOf(year)); //$NON-NLS-1$
- return result;
- }
-
- /**
- * Returns JSONObject of returnType('currency')
- *
- * @param _locale
- * String _locale (user supplied Locale.toString())
- * @param code
- * String code (The ISO 4217 currency code)
- *
- * @return JSONObject: 'currency':
- * [key: currencyCodes], [String]
- * [key: currencyPattern], [String]
- * [key: currencyDecimal], [String]
- * [key: currencyFraction], [String]
- * [key: currencyGrouping], [String]
- * [key: currencyRounding], [String]
- *
- * @throws: Exception
- */
- public static JSONObject getCurrencyData(String _locale, String code) {
- JSONObject result = null;
- try {
- JSONArray jsonArray;
- result = getPersistentResourceBundle(_locale);
- if (result == null) {
- jsonArray = getResourceBundle(_locale).getJSONArray(
- Resources.JSON_CURRENCY);
- } else {
- jsonArray = result.getJSONArray(Resources.JSON_CURRENCY);
- }
-
- for (int x = 0; x < jsonArray.length(); x++) {
- JSONObject temp = jsonArray.getJSONObject(x);
- if (temp.get(Resources.CURRENCYCODE).toString()
- .equalsIgnoreCase(code)) {
- result = temp;
- }
- }
- } catch (Exception e) {
-
- }
- return result;
- }
-
- /**
- * Returns JSONObject of returnType('locale')
- *
- * @param _locale
- * String _locale (user supplied Locale.toString())
- *
- * @return JSONObject: 'locale':
- * [key: displayName], [String]
- * [key: firstDayOfWeek], [String]
- * [key: pattern], [String]
- * [key: decimalSymbol], [String]
- * [key: currencySymbol], [String]
- * [key: percentSymbol], [String]
- *
- * @throws Exception
- */
- public static JSONObject getLocaleData(String _locale) {
- JSONObject result = null;
- try {
- result = getPersistentResourceBundle(_locale);
- if (result == null) {
- result = getResourceBundle(_locale).getJSONObject(
- Resources.JSON_LOCALE);
- } else {
- result = result.getJSONObject(Resources.JSON_LOCALE);
- }
- } catch (Exception e) {
- }
- return result;
- }
-
- /**
- * Returns resourceBundle JSONObject cached in PersistentStore
- *
- * Note: Recursively searches JSONObject from persistentStore using
- * Resources.PERSISTENTSTORE_ID for locale by removing sub-parts (separated
- * by '_')
- *
- * @param _locale
- * String _locale (user supplied Locale.toString())
- *
- * @return JSONObject
- */
- private static JSONObject getPersistentResourceBundle(String _locale) {
- JSONObject result = null;
- try {
- // load object
- result = (JSONObject) PersistentStore.getPersistentObject(
- Resources.PERSISTENTSTORE_ID).getContents();
- } catch (Exception e) {
- if (StringUtilities.indexOf(_locale, '_', 0, _locale.length()) > 0) {
- result = getPersistentResourceBundle(removeSubPart(StringUtils
- .split(_locale, "_"))); //$NON-NLS-1$
- } else {
- result = null;
- }
- }
- return result;
- }
-
- /**
- * Returns resourceBundle File as JSONObject from
- * /resource/resourceBundles/<Locale.toString()>.js.gz
- *
- * Note: Recursively searches for locale by removing sub-parts (separated by
- * '_')
- *
- * @param _locale
- * String _locale (user supplied Locale.toString())
- *
- * @return JSONObject
- */
- private static JSONObject getResourceBundle(String _locale) {
- JSONObject result = null;
-
- try {
- if (_locale == null || _locale.length() <= 0) {
- return null;
- }
-
- InputStream is = Util.class.getClass().getResourceAsStream(
- Resources.LOCALEINFOPATH + _locale
- + Resources.LOCALEINFOPATHEND);
- Parser parser = new Parser(new InputStreamReader(
- new GZIPInputStream(is), "UTF-8"));
- result = parser.parse();
-
- // cache resourceBundle as JSONOBJECT
- // store new object
- PersistentObject persist = PersistentStore
- .getPersistentObject(Resources.PERSISTENTSTORE_ID);
- // Synchronize on the PersistentObject so that no other object can
- // acquire the lock before we finish our commit operation.
- synchronized (persist) {
- persist.setContents((Hashtable) result);
- persist.commit();
- }
- } catch (NonPersistableObjectException npoe) {
- Logger.log("Globalization: Failed to persist locale: "
- + npoe.getMessage());
- } catch (Exception e) {
- // if resourceBundle not found, recursively search for file by
- // removing substrings from name
- if (StringUtilities.indexOf(_locale, '_', 0, _locale.length()) > 0) {
- result = getResourceBundle(removeSubPart(StringUtils.split(
- _locale, "_"))); //$NON-NLS-1$
- } else {
- result = null;
- }
- }
- return result;
- }
-
- /**
- * Returns substring of resourceBundle with the last section removed. Ex.
- * cs_CZ_PREEURO -> cs_CZ
- *
- * @param s
- * String[] s (Array of locale split by '_')
- *
- * @return JSONObject
- */
- private static String removeSubPart(String[] s) {
- String result = "";
- for (int x = 0; x < s.length - 1; x++) {
- result += s[x];
- if (x != s.length - 2) {// length - 2 to account for starting at
- // zero
- result += "_"; //$NON-NLS-1$
- }
- }
- return result;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileTransfer.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileTransfer.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileTransfer.java
deleted file mode 100644
index b0f089c..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileTransfer.java
+++ /dev/null
@@ -1,473 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.http;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.HttpConnection;
-import javax.microedition.io.file.FileConnection;
-
-import org.apache.cordova.api.Plugin;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.file.Entry;
-import org.apache.cordova.json4j.JSONArray;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.io.FileNotFoundException;
-import net.rim.device.api.io.http.HttpProtocolConstants;
-
-/**
- * The FileTransfer plugin can be used to transfer files between the device and
- * a remote server. The following actions are supported:
- *
- * download - Download a file from a server to the device.
- * upload - Upload a file from the device to a server.
- */
-public class FileTransfer extends Plugin {
- private static final String LOG_TAG = "FileTransfer: ";
-
- /**
- * Error codes
- */
- static int FILE_NOT_FOUND_ERR = 1;
- static int INVALID_URL_ERR = 2;
- static int CONNECTION_ERR = 3;
-
- /**
- * Possible actions
- */
- private static final String ACTION_DOWNLOAD = "download";
- private static final String ACTION_UPLOAD = "upload";
-
- private static final char SEPARATOR = '/';
-
- /**
- * Executes the requested action and returns a PluginResult.
- *
- * @param action
- * The action to execute.
- * @param callbackId
- * The callback ID to be invoked upon action completion.
- * @param args
- * JSONArry of arguments for the action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- String source = null;
- String target = null;
- PluginResult result = null;
-
- try {
- // Retrieve the source and target locations from the argument array.
- source = args.isNull(0) ? null : args.getString(0).trim();
- target = args.isNull(1) ? null : args.getString(1).trim();
-
- if (source == null || source.length() == 0 || target == null
- || target.length() == 0) {
- Logger.log(LOG_TAG + "Missing source or target");
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "Missing source or target");
- }
- } catch (JSONException e) {
- Logger.log(LOG_TAG + e.getMessage());
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "Invalid or missing parameter");
- }
-
- if (ACTION_UPLOAD.equals(action)) {
- // Source needs to follow the file URI protocol so add "file:///"
- // prefix if it doesn't exist.
- if (!source.startsWith("file:///")) {
- if (source.indexOf(SEPARATOR) != 0) {
- source = "file://" + SEPARATOR + source;
- } else {
- source = "file://" + source;
- }
- }
-
- FileUploader uploader = null;
- try {
- // Setup the options
- String fileKey = getArgument(args, 2, "file");
- String fileName = getArgument(args, 3, "image.jpg");
- String mimeType = getArgument(args, 4, null);
- JSONObject params = null;
- JSONObject headers = null;
-
- if (args.length() > 5 && !args.isNull(5)) {
- params = args.getJSONObject(5);
- }
-
- if(args.length() > 8 && !args.isNull(8)){
- headers = args.getJSONObject(8);
- }
- uploader = new FileUploader();
- FileUploadResult r = uploader.upload(source, target, fileKey,
- fileName, mimeType, params, headers);
-
- int status = r.getResponseCode();
- if (status < 200 || status > 399) {
- Logger.log(LOG_TAG + "HTTP Status " + status);
- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, new Integer(status));
- return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
- }
-
- result = new PluginResult(PluginResult.Status.OK,
- r.toJSONObject());
- } catch (FileNotFoundException e) {
- Logger.log(LOG_TAG + e.getMessage());
- JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR,
- source, target, uploader);
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- error);
- } catch (IllegalArgumentException e) {
- Logger.log(LOG_TAG + e.getMessage());
- JSONObject error = createFileTransferError(INVALID_URL_ERR,
- source, target, uploader);
- result = new PluginResult(
- PluginResult.Status.MALFORMED_URL_EXCEPTION, error);
- } catch (IOException e) {
- Logger.log(LOG_TAG + e.getMessage());
- JSONObject error = createFileTransferError(CONNECTION_ERR,
- source, target, uploader);
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION,
- error);
- } catch (JSONException e) {
- Logger.log(LOG_TAG + e.getMessage());
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "Invalid or missing parameter");
- }
- } else if (ACTION_DOWNLOAD.equals(action)) {
- result = download(source, target);
- } else {
- // invalid action
- result = new PluginResult(PluginResult.Status.INVALID_ACTION,
- LOG_TAG + "invalid action " + action);
- }
-
- return result;
- }
-
- /**
- * Create an error object based on the passed in errorCode
- *
- * @param errorCode
- * the error
- * @return JSONObject containing the error
- */
- private JSONObject createFileTransferError(int errorCode, String source,
- String target) {
- return createFileTransferError(errorCode, source, target,
- (Integer) null);
- }
-
- /**
- * Create an error object based on the passed in errorCode
- *
- * @param errorCode
- * the error
- * @return JSONObject containing the error
- */
- private JSONObject createFileTransferError(int errorCode, String source,
- String target, FileUploader fileUploader) {
-
- Integer httpStatus = null;
-
- if (fileUploader != null) {
- httpStatus = fileUploader.getResponseCode();
- }
- return createFileTransferError(errorCode, source, target, httpStatus);
- }
-
- /**
- * Create an error object based on the passed in errorCode
- *
- * @param errorCode
- * the error
- * @return JSONObject containing the error
- */
- private JSONObject createFileTransferError(int errorCode, String source,
- String target, HttpConnection connection) {
-
- Integer httpStatus = null;
-
- if (connection != null) {
- try {
- httpStatus = new Integer(connection.getResponseCode());
- } catch (IOException e) {
- Logger.log(LOG_TAG + " exception getting http response code "
- + e.toString());
- }
- }
-
- return createFileTransferError(errorCode, source, target, httpStatus);
- }
-
- /**
- * Create an error object based on the passed in errorCode
- *
- * @param errorCode
- * the error
- * @return JSONObject containing the error
- */
- private JSONObject createFileTransferError(int errorCode, String source,
- String target, Integer httpStatus) {
- JSONObject error = null;
- try {
- error = new JSONObject();
- error.put("code", errorCode);
- error.put("source", source);
- error.put("target", target);
- if (httpStatus != null) {
- error.put("http_status", httpStatus);
- }
- } catch (JSONException e) {
- Logger.log(LOG_TAG + e.getMessage());
- }
- return error;
- }
-
- /**
- * Recurse through a specified path and create any directories that do not
- * already exist.
- *
- * @param path
- * directory path to recurse
- * @throws IOException
- */
- private void createSubDirs(String path) throws IOException {
- FileConnection outputStream = null;
-
- try {
- outputStream = (FileConnection) Connector.open(path,
- Connector.READ_WRITE);
- if (!outputStream.exists()) {
- int dirIndex = path.lastIndexOf(SEPARATOR, path.length() - 2);
- // This code assumes file protocol is specified so stop
- // recursion once "file:///" is hit.
- if (dirIndex != -1 && dirIndex > 7) {
- createSubDirs(path.substring(0, dirIndex + 1));
- }
- outputStream.mkdir();
- }
- } finally {
- try {
- if (outputStream != null) {
- outputStream.close();
- }
- } catch (IOException e) {
- Logger.log(LOG_TAG + e.getMessage());
- }
- }
- }
-
- /**
- * Download a file from a given URL and save it to the specified location.
- *
- * @param source
- * URL of the server to receive the file
- * @param target
- * Full path of the file on the file system
- * @return JSONObject a file entry object in JSON form describing the
- * downloaded file.
- */
- private PluginResult download(String source, String target) {
- HttpConnection httpConn = null;
- FileConnection fileConn = null;
- OutputStream outputStream = null;
- String filename = null;
- String path = null;
-
- Logger.debug(LOG_TAG + "downloading " + source + " to " + target);
-
- // Target needs to follow the file URI protocol so add "file:///"
- // prefix if it doesn't exist.
- if (!target.startsWith("file:///")) {
- if (target.indexOf(SEPARATOR) != 0) {
- target = "file://" + SEPARATOR + target;
- } else {
- target = "file://" + target;
- }
- }
-
- // Parse the target filename and directory path. If the target does not
- // specify a file name (only directory), try to get the file name from
- // the source.
- int dirIndex = target.lastIndexOf(SEPARATOR);
- if (dirIndex == (target.length() - 1)) {
- int srcdirIndex = source.lastIndexOf(SEPARATOR);
- if (srcdirIndex != (source.length() - 1)) {
- path = target;
- filename = source.substring(srcdirIndex + 1);
- target = path + filename;
- }
- } else if (dirIndex != -1) {
- filename = target.substring(dirIndex + 1);
- path = target.substring(0, dirIndex + 1);
- }
-
- // If no filename or path could be determined for the target, error out.
- if (filename == null || path == null) {
- Logger.log(LOG_TAG + "Target filename could not be determined.");
- JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR,
- source, target);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, error);
- }
-
- try {
- try {
- // Create any directories in the path that do not already exist.
- createSubDirs(path);
-
- // Open connection to the target file.
- fileConn = (FileConnection) Connector.open(target,
- Connector.READ_WRITE);
- } catch (IOException e) {
- Logger.log(LOG_TAG + "Failed to open target file: " + target);
- JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source,
- target, httpConn);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
- }
-
- // Create the target file if it doesn't exist, otherwise truncate.
- if (!fileConn.exists()) {
- fileConn.create();
- } else {
- fileConn.truncate(0);
- }
-
- // Open the http connection to the server.
- try {
- httpConn = HttpUtils.getHttpConnection(source);
- } catch (IllegalArgumentException e) {
- JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, httpConn);
- return new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, error);
- }
- if (httpConn == null) {
- Logger.log(LOG_TAG + "Failed to create http connection.");
- // TODO separate malformed url from actual connection error
- JSONObject error = createFileTransferError(CONNECTION_ERR,
- source, target);
- return new PluginResult(
- PluginResult.Status.IO_EXCEPTION, error);
- }
-
- // Set the request headers
- httpConn.setRequestMethod(HttpConnection.GET);
- httpConn.setRequestProperty(
- HttpProtocolConstants.HEADER_USER_AGENT,
- System.getProperty("browser.useragent"));
- httpConn.setRequestProperty(
- HttpProtocolConstants.HEADER_KEEP_ALIVE, "300");
- httpConn.setRequestProperty(
- HttpProtocolConstants.HEADER_CONNECTION, "keep-alive");
-
- // Set the cookie
- String cookie = HttpUtils.getCookie(source);
- if (cookie != null) {
- httpConn.setRequestProperty(
- HttpProtocolConstants.HEADER_COOKIE, cookie);
- }
-
- InputStream inputStream = httpConn.openInputStream();
- int status = httpConn.getResponseCode();
- if (status < 200 || status > 399) {
- Logger.log(LOG_TAG + "HTTP Status " + status);
- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, httpConn);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
- }
-
- outputStream = fileConn.openOutputStream();
-
- // Read from the connection and write bytes to the file.
- byte[] buffer = new byte[1024];
- int bytesRead = 0;
- while ((bytesRead = inputStream.read(buffer)) > 0) {
- outputStream.write(buffer, 0, bytesRead);
- }
- } catch (IOException e) {
- Logger.log(LOG_TAG + e.getMessage());
- JSONObject error = createFileTransferError(CONNECTION_ERR, source,
- target, httpConn);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
- } catch (ClassCastException e) {
- // in case something really funky gets passed in
- Logger.log(LOG_TAG + e.getMessage());
- JSONObject error = createFileTransferError(INVALID_URL_ERR, source,
- target, httpConn);
- return new PluginResult(
- PluginResult.Status.MALFORMED_URL_EXCEPTION, error);
- } catch (Throwable t) {
- Logger.log(LOG_TAG + t.toString());
- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, httpConn);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
- } finally {
- try {
- if (httpConn != null) {
- httpConn.close();
- }
- if (outputStream != null) {
- outputStream.close();
- }
- if (fileConn != null) {
- fileConn.close();
- }
- } catch (IOException e) {
- Logger.log(LOG_TAG + "IOException in finally: "
- + e.getMessage());
- }
- }
-
- // create a new Entry
- Entry entry = new Entry();
- entry.setDirectory(false);
- entry.setName(filename);
- entry.setFullPath(target);
-
- return new PluginResult(PluginResult.Status.OK, entry.toJSONObject());
- }
-
- /**
- * Convenience method to read a parameter from the list of JSON args.
- *
- * @param args
- * the args passed to the Plugin
- * @param position
- * the position to retrieve the arg from
- * @param defaultString
- * the default to be used if the arg does not exist
- * @return String with the retrieved value
- */
- private String getArgument(JSONArray args, int position,
- String defaultString) {
- String arg = defaultString;
- if (args.length() >= position) {
- arg = args.optString(position);
- if (arg == null || "null".equals(arg)) {
- arg = defaultString;
- }
- }
- return arg;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileUploadResult.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileUploadResult.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileUploadResult.java
deleted file mode 100644
index 4b00159..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileUploadResult.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.http;
-
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-
-/**
- * Encapsulates the result and/or status of uploading a file to a remote server.
- */
-public class FileUploadResult {
-
- private long bytesSent = 0; // bytes sent
- private int responseCode = -1; // HTTP response code
- private String response = null; // HTTP response
-
- public long getBytesSent() {
- return bytesSent;
- }
-
- public void setBytesSent(long bytes) {
- this.bytesSent = bytes;
- }
-
- public int getResponseCode() {
- return responseCode;
- }
-
- public void setResponseCode(int responseCode) {
- this.responseCode = responseCode;
- }
-
- public String getResponse() {
- return response;
- }
-
- public void setResponse(String response) {
- this.response = response;
- }
-
- public JSONObject toJSONObject() throws JSONException {
- return new JSONObject(
- "{bytesSent:" + bytesSent +
- ",responseCode:" + responseCode +
- ",response:" + JSONObject.quote(response) + "}");
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileUploader.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileUploader.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileUploader.java
deleted file mode 100644
index 75645c7..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/FileUploader.java
+++ /dev/null
@@ -1,280 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.http;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Enumeration;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.HttpConnection;
-import javax.microedition.io.file.FileConnection;
-
-import org.apache.cordova.CordovaExtension;
-import org.apache.cordova.api.PluginResult;
-import org.apache.cordova.json4j.JSONException;
-import org.apache.cordova.json4j.JSONObject;
-import org.apache.cordova.util.Logger;
-
-import net.rim.device.api.io.FileNotFoundException;
-import net.rim.device.api.io.IOUtilities;
-import net.rim.device.api.io.MIMETypeAssociations;
-import net.rim.device.api.io.http.HttpProtocolConstants;
-import net.rim.device.api.ui.UiApplication;
-
-/**
- * The FileUploader uses an HTTP multipart request to upload files on the
- * device to a remote server. It currently supports a single file per HTTP
- * request.
- */
-public class FileUploader {
-
- /**
- * Constants
- */
- private static final String BOUNDARY = "----0x2fc1b3ef7cecbf14L";
- private static final String LINE_END = "\r\n";
- private static final String TD = "--";
-
- private Integer responseCode = null;
-
- /**
- * Uploads the specified file to the server URL provided using an HTTP
- * multipart request.
- * @param filePath Full path of the file on the file system
- * @param server URL of the server to receive the file
- * @param fileKey Name of file request parameter
- * @param fileName File name to be used on server
- * @param mimeType Describes file content type
- * @param params key:value pairs of user-defined parameters
- * @return FileUploadResult containing result of upload request
- */
- public FileUploadResult upload(String filePath, String server, String fileKey,
- String fileName, String mimeType, JSONObject params, JSONObject headers)
- throws FileNotFoundException, IllegalArgumentException, IOException {
-
- Logger.log(this.getClass().getName() + ": uploading " + filePath + " to " + server);
- FileUploadResult result = new FileUploadResult();
-
- InputStream in = null;
- OutputStream out = null;
- FileConnection fconn = null;
- HttpConnection httpConn = null;
- try {
- // open connection to the file
- try {
- fconn = (FileConnection)Connector.open(filePath, Connector.READ);
- } catch (ClassCastException e) {
- // in case something really funky gets passed in
- throw new IllegalArgumentException("Invalid file path");
- } catch (IOException e) {
- throw new FileNotFoundException("Failed to open source file: " + filePath);
- }
- if (!fconn.exists()) {
- throw new FileNotFoundException(filePath + " not found");
- }
-
- // determine mime type by
- // 1) user-provided type
- // 2) retrieve from file system
- // 3) default to JPEG
- if (mimeType == null) {
- mimeType = MIMETypeAssociations.getMIMEType(filePath);
- if (mimeType == null) {
- mimeType = HttpProtocolConstants.CONTENT_TYPE_IMAGE_JPEG;
- }
- }
-
- // boundary messages
- String boundaryMsg = getBoundaryMessage(fileKey, fileName, mimeType);
- String lastBoundary = getEndBoundary();
-
- // user-defined request parameters
- String customParams = (params != null) ? getParameterContent(params) : "";
- Logger.log(this.getClass().getName() + ": params=" + customParams);
-
- // determine content length
- long fileSize = fconn.fileSize();
- Logger.log(this.getClass().getName() + ": " + filePath + " size=" + fileSize + " bytes");
- long contentLength = fileSize +
- (long)boundaryMsg.length() +
- (long)lastBoundary.length() +
- (long)customParams.length();
-
- // get HttpConnection
- httpConn = HttpUtils.getHttpConnection(server);
- if (httpConn == null) {
- throw new IOException("Failed to connect to " + server);
- }
- Logger.log(this.getClass().getName() + ": server URL=" + httpConn.getURL());
-
- // set request headers
- httpConn.setRequestMethod(HttpConnection.POST);
- httpConn.setRequestProperty(
- HttpProtocolConstants.HEADER_USER_AGENT,
- System.getProperty("browser.useragent"));
- httpConn.setRequestProperty(
- HttpProtocolConstants.HEADER_KEEP_ALIVE, "300");
- httpConn.setRequestProperty(
- HttpProtocolConstants.HEADER_CONNECTION, "keep-alive");
- httpConn.setRequestProperty(
- HttpProtocolConstants.HEADER_CONTENT_TYPE,
- HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
- httpConn.setRequestProperty(
- HttpProtocolConstants.HEADER_CONTENT_LENGTH,
- Long.toString(contentLength));
-
- if(headers != null){
- for(Enumeration e = headers.keys(); e.hasMoreElements();){
- String key = e.nextElement().toString();
- String value = headers.optString(key);
- Logger.log(this.getClass().getName() + ": key=" + key + " value=" + value);
- httpConn.setRequestProperty(key, value);
- }
- }
-
- // set cookie
- String cookie = HttpUtils.getCookie(server);
- if (cookie != null) {
- httpConn.setRequestProperty(HttpProtocolConstants.HEADER_COOKIE, cookie);
- Logger.log(this.getClass().getName() + ": cookie=" + cookie);
- }
-
- // write...
- out = httpConn.openDataOutputStream();
-
- // parameters
- out.write(customParams.getBytes());
-
- // boundary
- out.write(boundaryMsg.getBytes());
-
- // file data
- in = fconn.openInputStream();
- byte[] data = IOUtilities.streamToBytes(in);
- out.write(data);
- in.close();
-
- // end boundary
- out.write(lastBoundary.getBytes());
-
- // send request and get response
- in = httpConn.openDataInputStream();
- //int rc = httpConn.getResponseCode();
- result.setResponse(new String(IOUtilities.streamToBytes(in)));
- //result.setResponseCode(rc);
- result.setBytesSent(contentLength);
- Logger.log(this.getClass().getName() + ": sent " + contentLength + " bytes");
- }
- finally {
-
- if (httpConn != null) {
- result.setResponseCode(httpConn.getResponseCode());
- responseCode = new Integer(httpConn.getResponseCode());
- }
-
- try {
- if (fconn != null) fconn.close();
- if (in != null) in.close();
- if (out != null) out.close();
- if (httpConn != null) httpConn.close();
- }
- catch (IOException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- }
- }
-
- return result;
- }
-
- /**
- * Sends an upload progress notification back to JavaScript engine.
- * @param result FileUploadResult containing bytes sent of total
- * @param callbackId identifier of callback function to invoke
- */
- protected void sendProgress(FileUploadResult result, final String callbackId) {
- JSONObject o = null;
- try {
- o = result.toJSONObject();
- }
- catch (JSONException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return;
- }
-
- // send a progress result
- final PluginResult r = new PluginResult(PluginResult.Status.OK, o);
- r.setKeepCallback(true);
- UiApplication.getUiApplication().invokeAndWait(
- new Runnable() {
- public void run() {
- CordovaExtension.invokeSuccessCallback(callbackId, r);
- }
- }
- );
- }
-
- /**
- * Returns the boundary string that represents the beginning of a file
- * in a multipart HTTP request.
- * @param fileKey Name of file request parameter
- * @param fileName File name to be used on server
- * @param mimeType Describes file content type
- * @return string representing the boundary message in a multipart HTTP request
- */
- protected String getBoundaryMessage(String fileKey, String fileName, String mimeType) {
- return (new StringBuffer())
- .append(TD).append(BOUNDARY).append(LINE_END)
- .append("Content-Disposition: form-data; name=\"").append(fileKey)
- .append("\"; filename=\"").append(fileName).append("\"").append(LINE_END)
- .append("Content-Type: ").append(mimeType).append(LINE_END)
- .append(LINE_END)
- .toString();
- }
-
- /**
- * Returns the boundary string that represents the end of a file in a
- * multipart HTTP request.
- * @return string representing the end boundary message in a multipart HTTP request
- */
- protected String getEndBoundary() {
- return LINE_END + TD + BOUNDARY + TD + LINE_END;
- }
-
- /**
- * Returns HTTP form content containing specified parameters.
- */
- protected String getParameterContent(JSONObject params) {
- StringBuffer buf = new StringBuffer();
- for (Enumeration e = params.keys(); e.hasMoreElements();) {
- String key = e.nextElement().toString();
- String value = params.optString(key);
- buf.append(TD).append(BOUNDARY).append(LINE_END)
- .append("Content-Disposition: form-data; name=\"").append(key).append("\"")
- .append(LINE_END).append(LINE_END)
- .append(value).append(LINE_END);
- }
- return buf.toString();
- }
-
- Integer getResponseCode() {
- return responseCode;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/HttpUtils.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/HttpUtils.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/HttpUtils.java
deleted file mode 100644
index af6ada6..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/http/HttpUtils.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.http;
-
-import javax.microedition.io.HttpConnection;
-
-import org.apache.cordova.CordovaExtension;
-
-import net.rim.device.api.io.transport.ConnectionDescriptor;
-import net.rim.device.api.io.transport.ConnectionFactory;
-
-/**
- * BlackBerry devices can connect to the network using a variety of transport
- * types, such as: WI-FI, BES/MDS, BIS, WAP (cellular). A connection URL must
- * have the appropriate suffix to match the transport type. This class contains
- * utility methods to retrieve the correct URL for the appropriate transport.
- */
-public class HttpUtils
-{
- /**
- * This method will open an HTTP connection over the best available transport type.
- * @param url Connection URL
- */
- public static HttpConnection getHttpConnection(String url)
- {
- HttpConnection httpConn = null;
-
- // Create ConnectionFactory
- ConnectionFactory factory = new ConnectionFactory();
-
- // use the factory to get a connection
- ConnectionDescriptor conDescriptor = factory.getConnection(url);
-
- if (conDescriptor != null) {
- // using the connection
- httpConn = (HttpConnection) conDescriptor.getConnection();
- }
-
- return httpConn;
- }
-
- /**
- * Retrieves the cookie from the application browser instance for the specified URL.
- * @param url Connection URL
- */
- public static String getCookie(String url)
- {
- return CordovaExtension.getBrowserField().getCookieManager().getCookie(url);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSON.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSON.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSON.java
deleted file mode 100644
index adbe514..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSON.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-
-import org.apache.cordova.json4j.internal.JSON4JPBackReader;
-
-/**
- * Helper class that does generic parsing of a JSON stream and returns the appropriate
- * JSON structure (JSONArray or JSONObject). Note that it is slightly more efficient to directly
- * parse with the appropriate object than to use this class to do a generalized parse.
- */
-public class JSON {
-
- /**
- * A constant for representing null.
- * In this case, it is just null.
- */
- public static final Object NULL = null;
-
- /**
- * Parse a Reader of JSON text into a JSONArtifact.
- * @param reader The character reader to read the JSON data from.
- * @param order Boolean flag indicating if the order of the JSON data should be preserved. This parameter only has an effect if the stream is JSON Object { ... } formatted data.
- * Note: The provided reader is not closed on completion of read; that is left to the caller.
- * Note: This is the same as calling parse(reader, order, false);
- *
- * @return Returns an instance of JSONArtifact (JSONObject, OrderedJSONObject, or JSONArray), corrisponding to if the input stream was Object or Array notation.
- *
- * @throws JSONException Thrown on errors during parse.
- * @throws NullPointerException Thrown if reader is null
- */
- public static JSONArtifact parse(Reader reader, boolean order) throws JSONException, NullPointerException {
- return parse(reader,order,false);
- }
-
- /**
- * Parse a Reader of JSON text into a JSONArtifact.
- * @param reader The character reader to read the JSON data from.
- * @param order Boolean flag indicating if the order of the JSON data should be preserved. This parameter only has an effect if the stream is JSON Object { ... } formatted data.
- * @param strict Boolean flag to indicate if the content should be parsed in strict mode or not, meaning comments and unquoted strings are not allowed.
- * Note: The provided reader is not closed on completion of read; that is left to the caller.
- *
- * @return Returns an instance of JSONArtifact (JSONObject, OrderedJSONObject, or JSONArray), corrisponding to if the input stream was Object or Array notation.
- *
- * @throws JSONException Thrown on errors during parse.
- * @throws NullPointerException Thrown if reader is null
- */
- public static JSONArtifact parse(Reader reader, boolean order, boolean strict) throws JSONException, NullPointerException {
-
- try {
- if (reader != null) {
-
- JSON4JPBackReader pReader = null;
-
- //Determine if we should buffer-wrap the reader before passing it on
- //to the appropriate parser.
- //boolean bufferIt = false;
-
- Class readerClass = reader.getClass();
-
- /* if (!StringReader.class.isAssignableFrom(readerClass) &&
- !CharArrayReader.class.isAssignableFrom(readerClass) &&
- !PushbackReader.class.isAssignableFrom(readerClass) &&
- !BufferedReader.class.isAssignableFrom(readerClass)) {
- bufferIt = true;
- } */
-
- //MSN IMPLEMENT PUSHBACKREADER!!
- if (JSON4JPBackReader.class.isAssignableFrom(readerClass)) {
- pReader = (JSON4JPBackReader) reader;
- } else {
- pReader = new JSON4JPBackReader(reader);
- }
-
- Reader rdr = pReader;
- int ch = pReader.read();
- while (ch != -1) {
- switch (ch) {
- case '{':
- pReader.unread(ch);
- /* if (bufferIt) {
- rdr = new BufferedReader(pReader);
- } */
- return new JSONObject(rdr,strict);
- case '[':
- pReader.unread(ch);
- /*if (bufferIt) {
- rdr = new BufferedReader(pReader);
- } */
- return new JSONArray(rdr, strict);
- case ' ':
- case '\t':
- case '\f':
- case '\r':
- case '\n':
- case '\b':
- ch = pReader.read();
- break;
- default:
- throw new JSONException("Unexpected character: [" + (char)ch + "] while scanning JSON String for JSON type. Invalid JSON.");
- }
- }
- throw new JSONException("Encountered end of stream before JSON data was read. Invalid JSON");
- } else {
- throw new NullPointerException("reader cannot be null.");
- }
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- }
-
- /**
- * Parse a Reader of JSON text into a JSONArtifact.
- * This call is the same as JSON.parse(reader, false, false).
- * Note that the provided reader is not closed on completion of read; that is left to the caller.
- * @param reader The character reader to read the JSON data from.
- *
- * @return Returns an instance of JSONArtifact (JSONObject, OrderedJSONObject, or JSONArray), corrisponding to if the input stream was Object or Array notation.
- *
- * @throws JSONException Thrown on errors during parse.
- * @throws NullPointerException Thrown if reader is null
- */
- public static JSONArtifact parse(Reader reader) throws JSONException, NullPointerException {
- return parse(reader,false, false);
- }
-
- /**
- * Parse a InputStream of JSON text into a JSONArtifact.
- * Note: The provided InputStream is not closed on completion of read; that is left to the caller.
- * @param is The input stream to read from. The content is assumed to be UTF-8 encoded and handled as such.
- * @param order Boolean flag indicating if the order of the JSON data should be preserved. This parameter only has an effect if the stream is JSON Object { ... } formatted data.
- *
- * @return Returns an instance of JSONArtifact (JSONObject or JSONArray), corrisponding to if the input stream was Object or Array notation.
- *
- * @throws JSONException Thrown on errors during parse.
- * @throws NullPointerException Thrown if reader is null
- */
- public static JSONArtifact parse(InputStream is, boolean order) throws JSONException, NullPointerException {
- return parse(is,order, false);
- }
-
- /**
- * Parse a InputStream of JSON text into a JSONArtifact.
- * Note that the provided InputStream is not closed on completion of read; that is left to the caller.
- * @param is The input stream to read from. The content is assumed to be UTF-8 encoded and handled as such.
- * @param order Boolean flag indicating if the order of the JSON data should be preserved. This parameter only has an effect if the stream is JSON Object { ... } formatted data.
- * @param strict Boolean flag to indicate if the content should be parsed in strict mode or not, meaning comments and unquoted strings are not allowed.
- *
- * @return Returns an instance of JSONArtifact (JSONObject or JSONArray), corrisponding to if the input stream was Object or Array notation.
- *
- * @throws JSONException Thrown on errors during parse.
- * @throws NullPointerException Thrown if reader is null
- */
- public static JSONArtifact parse(InputStream is, boolean order, boolean strict) throws JSONException, NullPointerException {
- if (is != null) {
- //BufferedReader reader = null;
- InputStreamReader reader = null;
- try {
- reader = new InputStreamReader(is, "UTF-8");
- } catch (Exception ex) {
- JSONException iox = new JSONException("Could not construct UTF-8 character reader for the InputStream");
- iox.setCause(ex);
- throw iox;
- }
- return parse(reader,order);
- } else {
- throw new NullPointerException("is cannot be null");
- }
- }
-
- /**
- * Parse an InputStream of JSON text into a JSONArtifact.
- * This call is the same as JSON.parse(is, false, false).
- * Note that the provided InputStream is not closed on completion of read; that is left to the caller.
- * @param is The input stream to read from. The content is assumed to be UTF-8 encoded and handled as such.
- *
- * @return Returns an instance of JSONArtifact (JSONObject, OrderedJSONObject, or JSONArray), corrisponding to if the input stream was Object or Array notation.
- *
- * @throws JSONException Thrown on errors during parse.
- * @throws NullPointerException Thrown if reader is null
- */
- public static JSONArtifact parse(InputStream is) throws JSONException, NullPointerException {
- return parse(is,false, false);
- }
-}
[09/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/javascript/cordova.blackberry10.js
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/javascript/cordova.blackberry10.js b/lib/cordova-blackberry/javascript/cordova.blackberry10.js
new file mode 100644
index 0000000..ebe8a46
--- /dev/null
+++ b/lib/cordova-blackberry/javascript/cordova.blackberry10.js
@@ -0,0 +1,6891 @@
+// Platform: blackberry10
+// 2.7.0rc1-73-g0bca505
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+*/
+;(function() {
+var CORDOVA_JS_BUILD_LABEL = '2.7.0rc1-73-g0bca505';
+// file: lib/scripts/require.js
+
+var require,
+ define;
+
+(function () {
+ var modules = {},
+ // Stack of moduleIds currently being built.
+ requireStack = [],
+ // Map of module ID -> index into requireStack of modules currently being built.
+ inProgressModules = {},
+ SEPERATOR = ".";
+
+
+
+ function build(module) {
+ var factory = module.factory,
+ localRequire = function (id) {
+ var resultantId = id;
+ //Its a relative path, so lop off the last portion and add the id (minus "./")
+ if (id.charAt(0) === ".") {
+ resultantId = module.id.slice(0, module.id.lastIndexOf(SEPERATOR)) + SEPERATOR + id.slice(2);
+ }
+ return require(resultantId);
+ };
+ module.exports = {};
+ delete module.factory;
+ factory(localRequire, module.exports, module);
+ return module.exports;
+ }
+
+ require = function (id) {
+ if (!modules[id]) {
+ throw "module " + id + " not found";
+ } else if (id in inProgressModules) {
+ var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;
+ throw "Cycle in require graph: " + cycle;
+ }
+ if (modules[id].factory) {
+ try {
+ inProgressModules[id] = requireStack.length;
+ requireStack.push(id);
+ return build(modules[id]);
+ } finally {
+ delete inProgressModules[id];
+ requireStack.pop();
+ }
+ }
+ return modules[id].exports;
+ };
+
+ define = function (id, factory) {
+ if (modules[id]) {
+ throw "module " + id + " already defined";
+ }
+
+ modules[id] = {
+ id: id,
+ factory: factory
+ };
+ };
+
+ define.remove = function (id) {
+ delete modules[id];
+ };
+
+ define.moduleMap = modules;
+})();
+
+//Export for use in node
+if (typeof module === "object" && typeof require === "function") {
+ module.exports.require = require;
+ module.exports.define = define;
+}
+
+// file: lib/cordova.js
+define("cordova", function(require, exports, module) {
+
+
+var channel = require('cordova/channel');
+
+/**
+ * Listen for DOMContentLoaded and notify our channel subscribers.
+ */
+document.addEventListener('DOMContentLoaded', function() {
+ channel.onDOMContentLoaded.fire();
+}, false);
+if (document.readyState == 'complete' || document.readyState == 'interactive') {
+ channel.onDOMContentLoaded.fire();
+}
+
+/**
+ * Intercept calls to addEventListener + removeEventListener and handle deviceready,
+ * resume, and pause events.
+ */
+var m_document_addEventListener = document.addEventListener;
+var m_document_removeEventListener = document.removeEventListener;
+var m_window_addEventListener = window.addEventListener;
+var m_window_removeEventListener = window.removeEventListener;
+
+/**
+ * Houses custom event handlers to intercept on document + window event listeners.
+ */
+var documentEventHandlers = {},
+ windowEventHandlers = {};
+
+document.addEventListener = function(evt, handler, capture) {
+ var e = evt.toLowerCase();
+ if (typeof documentEventHandlers[e] != 'undefined') {
+ documentEventHandlers[e].subscribe(handler);
+ } else {
+ m_document_addEventListener.call(document, evt, handler, capture);
+ }
+};
+
+window.addEventListener = function(evt, handler, capture) {
+ var e = evt.toLowerCase();
+ if (typeof windowEventHandlers[e] != 'undefined') {
+ windowEventHandlers[e].subscribe(handler);
+ } else {
+ m_window_addEventListener.call(window, evt, handler, capture);
+ }
+};
+
+document.removeEventListener = function(evt, handler, capture) {
+ var e = evt.toLowerCase();
+ // If unsubscribing from an event that is handled by a plugin
+ if (typeof documentEventHandlers[e] != "undefined") {
+ documentEventHandlers[e].unsubscribe(handler);
+ } else {
+ m_document_removeEventListener.call(document, evt, handler, capture);
+ }
+};
+
+window.removeEventListener = function(evt, handler, capture) {
+ var e = evt.toLowerCase();
+ // If unsubscribing from an event that is handled by a plugin
+ if (typeof windowEventHandlers[e] != "undefined") {
+ windowEventHandlers[e].unsubscribe(handler);
+ } else {
+ m_window_removeEventListener.call(window, evt, handler, capture);
+ }
+};
+
+function createEvent(type, data) {
+ var event = document.createEvent('Events');
+ event.initEvent(type, false, false);
+ if (data) {
+ for (var i in data) {
+ if (data.hasOwnProperty(i)) {
+ event[i] = data[i];
+ }
+ }
+ }
+ return event;
+}
+
+if(typeof window.console === "undefined") {
+ window.console = {
+ log:function(){}
+ };
+}
+
+var cordova = {
+ define:define,
+ require:require,
+ /**
+ * Methods to add/remove your own addEventListener hijacking on document + window.
+ */
+ addWindowEventHandler:function(event) {
+ return (windowEventHandlers[event] = channel.create(event));
+ },
+ addStickyDocumentEventHandler:function(event) {
+ return (documentEventHandlers[event] = channel.createSticky(event));
+ },
+ addDocumentEventHandler:function(event) {
+ return (documentEventHandlers[event] = channel.create(event));
+ },
+ removeWindowEventHandler:function(event) {
+ delete windowEventHandlers[event];
+ },
+ removeDocumentEventHandler:function(event) {
+ delete documentEventHandlers[event];
+ },
+ /**
+ * Retrieve original event handlers that were replaced by Cordova
+ *
+ * @return object
+ */
+ getOriginalHandlers: function() {
+ return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},
+ 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};
+ },
+ /**
+ * Method to fire event from native code
+ * bNoDetach is required for events which cause an exception which needs to be caught in native code
+ */
+ fireDocumentEvent: function(type, data, bNoDetach) {
+ var evt = createEvent(type, data);
+ if (typeof documentEventHandlers[type] != 'undefined') {
+ if( bNoDetach ) {
+ documentEventHandlers[type].fire(evt);
+ }
+ else {
+ setTimeout(function() {
+ // Fire deviceready on listeners that were registered before cordova.js was loaded.
+ if (type == 'deviceready') {
+ document.dispatchEvent(evt);
+ }
+ documentEventHandlers[type].fire(evt);
+ }, 0);
+ }
+ } else {
+ document.dispatchEvent(evt);
+ }
+ },
+ fireWindowEvent: function(type, data) {
+ var evt = createEvent(type,data);
+ if (typeof windowEventHandlers[type] != 'undefined') {
+ setTimeout(function() {
+ windowEventHandlers[type].fire(evt);
+ }, 0);
+ } else {
+ window.dispatchEvent(evt);
+ }
+ },
+
+ /**
+ * Plugin callback mechanism.
+ */
+ // Randomize the starting callbackId to avoid collisions after refreshing or navigating.
+ // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.
+ callbackId: Math.floor(Math.random() * 2000000000),
+ callbacks: {},
+ callbackStatus: {
+ NO_RESULT: 0,
+ OK: 1,
+ CLASS_NOT_FOUND_EXCEPTION: 2,
+ ILLEGAL_ACCESS_EXCEPTION: 3,
+ INSTANTIATION_EXCEPTION: 4,
+ MALFORMED_URL_EXCEPTION: 5,
+ IO_EXCEPTION: 6,
+ INVALID_ACTION: 7,
+ JSON_EXCEPTION: 8,
+ ERROR: 9
+ },
+
+ /**
+ * Called by native code when returning successful result from an action.
+ */
+ callbackSuccess: function(callbackId, args) {
+ try {
+ cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
+ } catch (e) {
+ console.log("Error in error callback: " + callbackId + " = "+e);
+ }
+ },
+
+ /**
+ * Called by native code when returning error result from an action.
+ */
+ callbackError: function(callbackId, args) {
+ // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
+ // Derive success from status.
+ try {
+ cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
+ } catch (e) {
+ console.log("Error in error callback: " + callbackId + " = "+e);
+ }
+ },
+
+ /**
+ * Called by native code when returning the result from an action.
+ */
+ callbackFromNative: function(callbackId, success, status, args, keepCallback) {
+ var callback = cordova.callbacks[callbackId];
+ if (callback) {
+ if (success && status == cordova.callbackStatus.OK) {
+ callback.success && callback.success.apply(null, args);
+ } else if (!success) {
+ callback.fail && callback.fail.apply(null, args);
+ }
+
+ // Clear callback if not expecting any more results
+ if (!keepCallback) {
+ delete cordova.callbacks[callbackId];
+ }
+ }
+ },
+ addConstructor: function(func) {
+ channel.onCordovaReady.subscribe(function() {
+ try {
+ func();
+ } catch(e) {
+ console.log("Failed to run constructor: " + e);
+ }
+ });
+ }
+};
+
+// Register pause, resume and deviceready channels as events on document.
+channel.onPause = cordova.addDocumentEventHandler('pause');
+channel.onResume = cordova.addDocumentEventHandler('resume');
+channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');
+
+module.exports = cordova;
+
+});
+
+// file: lib/common/argscheck.js
+define("cordova/argscheck", function(require, exports, module) {
+
+var exec = require('cordova/exec');
+var utils = require('cordova/utils');
+
+var moduleExports = module.exports;
+
+var typeMap = {
+ 'A': 'Array',
+ 'D': 'Date',
+ 'N': 'Number',
+ 'S': 'String',
+ 'F': 'Function',
+ 'O': 'Object'
+};
+
+function extractParamName(callee, argIndex) {
+ return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex];
+}
+
+function checkArgs(spec, functionName, args, opt_callee) {
+ if (!moduleExports.enableChecks) {
+ return;
+ }
+ var errMsg = null;
+ var typeName;
+ for (var i = 0; i < spec.length; ++i) {
+ var c = spec.charAt(i),
+ cUpper = c.toUpperCase(),
+ arg = args[i];
+ // Asterix means allow anything.
+ if (c == '*') {
+ continue;
+ }
+ typeName = utils.typeName(arg);
+ if ((arg === null || arg === undefined) && c == cUpper) {
+ continue;
+ }
+ if (typeName != typeMap[cUpper]) {
+ errMsg = 'Expected ' + typeMap[cUpper];
+ break;
+ }
+ }
+ if (errMsg) {
+ errMsg += ', but got ' + typeName + '.';
+ errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;
+ // Don't log when running jake test.
+ if (typeof jasmine == 'undefined') {
+ console.error(errMsg);
+ }
+ throw TypeError(errMsg);
+ }
+}
+
+function getValue(value, defaultValue) {
+ return value === undefined ? defaultValue : value;
+}
+
+moduleExports.checkArgs = checkArgs;
+moduleExports.getValue = getValue;
+moduleExports.enableChecks = true;
+
+
+});
+
+// file: lib/common/builder.js
+define("cordova/builder", function(require, exports, module) {
+
+var utils = require('cordova/utils');
+
+function each(objects, func, context) {
+ for (var prop in objects) {
+ if (objects.hasOwnProperty(prop)) {
+ func.apply(context, [objects[prop], prop]);
+ }
+ }
+}
+
+function clobber(obj, key, value) {
+ exports.replaceHookForTesting(obj, key);
+ obj[key] = value;
+ // Getters can only be overridden by getters.
+ if (obj[key] !== value) {
+ utils.defineGetter(obj, key, function() {
+ return value;
+ });
+ }
+}
+
+function assignOrWrapInDeprecateGetter(obj, key, value, message) {
+ if (message) {
+ utils.defineGetter(obj, key, function() {
+ console.log(message);
+ delete obj[key];
+ clobber(obj, key, value);
+ return value;
+ });
+ } else {
+ clobber(obj, key, value);
+ }
+}
+
+function include(parent, objects, clobber, merge) {
+ each(objects, function (obj, key) {
+ try {
+ var result = obj.path ? require(obj.path) : {};
+
+ if (clobber) {
+ // Clobber if it doesn't exist.
+ if (typeof parent[key] === 'undefined') {
+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
+ } else if (typeof obj.path !== 'undefined') {
+ // If merging, merge properties onto parent, otherwise, clobber.
+ if (merge) {
+ recursiveMerge(parent[key], result);
+ } else {
+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
+ }
+ }
+ result = parent[key];
+ } else {
+ // Overwrite if not currently defined.
+ if (typeof parent[key] == 'undefined') {
+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
+ } else {
+ // Set result to what already exists, so we can build children into it if they exist.
+ result = parent[key];
+ }
+ }
+
+ if (obj.children) {
+ include(result, obj.children, clobber, merge);
+ }
+ } catch(e) {
+ utils.alert('Exception building cordova JS globals: ' + e + ' for key "' + key + '"');
+ }
+ });
+}
+
+/**
+ * Merge properties from one object onto another recursively. Properties from
+ * the src object will overwrite existing target property.
+ *
+ * @param target Object to merge properties into.
+ * @param src Object to merge properties from.
+ */
+function recursiveMerge(target, src) {
+ for (var prop in src) {
+ if (src.hasOwnProperty(prop)) {
+ if (target.prototype && target.prototype.constructor === target) {
+ // If the target object is a constructor override off prototype.
+ clobber(target.prototype, prop, src[prop]);
+ } else {
+ if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
+ recursiveMerge(target[prop], src[prop]);
+ } else {
+ clobber(target, prop, src[prop]);
+ }
+ }
+ }
+ }
+}
+
+exports.buildIntoButDoNotClobber = function(objects, target) {
+ include(target, objects, false, false);
+};
+exports.buildIntoAndClobber = function(objects, target) {
+ include(target, objects, true, false);
+};
+exports.buildIntoAndMerge = function(objects, target) {
+ include(target, objects, true, true);
+};
+exports.recursiveMerge = recursiveMerge;
+exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;
+exports.replaceHookForTesting = function() {};
+
+});
+
+// file: lib/common/channel.js
+define("cordova/channel", function(require, exports, module) {
+
+var utils = require('cordova/utils'),
+ nextGuid = 1;
+
+/**
+ * Custom pub-sub "channel" that can have functions subscribed to it
+ * This object is used to define and control firing of events for
+ * cordova initialization, as well as for custom events thereafter.
+ *
+ * The order of events during page load and Cordova startup is as follows:
+ *
+ * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.
+ * onNativeReady* Internal event that indicates the Cordova native side is ready.
+ * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.
+ * onCordovaInfoReady* Internal event fired when device properties are available.
+ * onCordovaConnectionReady* Internal event fired when the connection property has been set.
+ * onDeviceReady* User event fired to indicate that Cordova is ready
+ * onResume User event fired to indicate a start/resume lifecycle event
+ * onPause User event fired to indicate a pause lifecycle event
+ * onDestroy* Internal event fired when app is being destroyed (User should use window.onunload event, not this one).
+ *
+ * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.
+ * All listeners that subscribe after the event is fired will be executed right away.
+ *
+ * The only Cordova events that user code should register for are:
+ * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript
+ * pause App has moved to background
+ * resume App has returned to foreground
+ *
+ * Listeners can be registered as:
+ * document.addEventListener("deviceready", myDeviceReadyListener, false);
+ * document.addEventListener("resume", myResumeListener, false);
+ * document.addEventListener("pause", myPauseListener, false);
+ *
+ * The DOM lifecycle events should be used for saving and restoring state
+ * window.onload
+ * window.onunload
+ *
+ */
+
+/**
+ * Channel
+ * @constructor
+ * @param type String the channel name
+ */
+var Channel = function(type, sticky) {
+ this.type = type;
+ // Map of guid -> function.
+ this.handlers = {};
+ // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
+ this.state = sticky ? 1 : 0;
+ // Used in sticky mode to remember args passed to fire().
+ this.fireArgs = null;
+ // Used by onHasSubscribersChange to know if there are any listeners.
+ this.numHandlers = 0;
+ // Function that is called when the first listener is subscribed, or when
+ // the last listener is unsubscribed.
+ this.onHasSubscribersChange = null;
+},
+ channel = {
+ /**
+ * Calls the provided function only after all of the channels specified
+ * have been fired. All channels must be sticky channels.
+ */
+ join: function(h, c) {
+ var len = c.length,
+ i = len,
+ f = function() {
+ if (!(--i)) h();
+ };
+ for (var j=0; j<len; j++) {
+ if (c[j].state === 0) {
+ throw Error('Can only use join with sticky channels.');
+ }
+ c[j].subscribe(f);
+ }
+ if (!len) h();
+ },
+ create: function(type) {
+ return channel[type] = new Channel(type, false);
+ },
+ createSticky: function(type) {
+ return channel[type] = new Channel(type, true);
+ },
+
+ /**
+ * cordova Channels that must fire before "deviceready" is fired.
+ */
+ deviceReadyChannelsArray: [],
+ deviceReadyChannelsMap: {},
+
+ /**
+ * Indicate that a feature needs to be initialized before it is ready to be used.
+ * This holds up Cordova's "deviceready" event until the feature has been initialized
+ * and Cordova.initComplete(feature) is called.
+ *
+ * @param feature {String} The unique feature name
+ */
+ waitForInitialization: function(feature) {
+ if (feature) {
+ var c = channel[feature] || this.createSticky(feature);
+ this.deviceReadyChannelsMap[feature] = c;
+ this.deviceReadyChannelsArray.push(c);
+ }
+ },
+
+ /**
+ * Indicate that initialization code has completed and the feature is ready to be used.
+ *
+ * @param feature {String} The unique feature name
+ */
+ initializationComplete: function(feature) {
+ var c = this.deviceReadyChannelsMap[feature];
+ if (c) {
+ c.fire();
+ }
+ }
+ };
+
+function forceFunction(f) {
+ if (typeof f != 'function') throw "Function required as first argument!";
+}
+
+/**
+ * Subscribes the given function to the channel. Any time that
+ * Channel.fire is called so too will the function.
+ * Optionally specify an execution context for the function
+ * and a guid that can be used to stop subscribing to the channel.
+ * Returns the guid.
+ */
+Channel.prototype.subscribe = function(f, c) {
+ // need a function to call
+ forceFunction(f);
+ if (this.state == 2) {
+ f.apply(c || this, this.fireArgs);
+ return;
+ }
+
+ var func = f,
+ guid = f.observer_guid;
+ if (typeof c == "object") { func = utils.close(c, f); }
+
+ if (!guid) {
+ // first time any channel has seen this subscriber
+ guid = '' + nextGuid++;
+ }
+ func.observer_guid = guid;
+ f.observer_guid = guid;
+
+ // Don't add the same handler more than once.
+ if (!this.handlers[guid]) {
+ this.handlers[guid] = func;
+ this.numHandlers++;
+ if (this.numHandlers == 1) {
+ this.onHasSubscribersChange && this.onHasSubscribersChange();
+ }
+ }
+};
+
+/**
+ * Unsubscribes the function with the given guid from the channel.
+ */
+Channel.prototype.unsubscribe = function(f) {
+ // need a function to unsubscribe
+ forceFunction(f);
+
+ var guid = f.observer_guid,
+ handler = this.handlers[guid];
+ if (handler) {
+ delete this.handlers[guid];
+ this.numHandlers--;
+ if (this.numHandlers === 0) {
+ this.onHasSubscribersChange && this.onHasSubscribersChange();
+ }
+ }
+};
+
+/**
+ * Calls all functions subscribed to this channel.
+ */
+Channel.prototype.fire = function(e) {
+ var fail = false,
+ fireArgs = Array.prototype.slice.call(arguments);
+ // Apply stickiness.
+ if (this.state == 1) {
+ this.state = 2;
+ this.fireArgs = fireArgs;
+ }
+ if (this.numHandlers) {
+ // Copy the values first so that it is safe to modify it from within
+ // callbacks.
+ var toCall = [];
+ for (var item in this.handlers) {
+ toCall.push(this.handlers[item]);
+ }
+ for (var i = 0; i < toCall.length; ++i) {
+ toCall[i].apply(this, fireArgs);
+ }
+ if (this.state == 2 && this.numHandlers) {
+ this.numHandlers = 0;
+ this.handlers = {};
+ this.onHasSubscribersChange && this.onHasSubscribersChange();
+ }
+ }
+};
+
+
+// defining them here so they are ready super fast!
+// DOM event that is received when the web page is loaded and parsed.
+channel.createSticky('onDOMContentLoaded');
+
+// Event to indicate the Cordova native side is ready.
+channel.createSticky('onNativeReady');
+
+// Event to indicate that all Cordova JavaScript objects have been created
+// and it's time to run plugin constructors.
+channel.createSticky('onCordovaReady');
+
+// Event to indicate that device properties are available
+channel.createSticky('onCordovaInfoReady');
+
+// Event to indicate that the connection property has been set.
+channel.createSticky('onCordovaConnectionReady');
+
+// Event to indicate that all automatically loaded JS plugins are loaded and ready.
+channel.createSticky('onPluginsReady');
+
+// Event to indicate that Cordova is ready
+channel.createSticky('onDeviceReady');
+
+// Event to indicate a resume lifecycle event
+channel.create('onResume');
+
+// Event to indicate a pause lifecycle event
+channel.create('onPause');
+
+// Event to indicate a destroy lifecycle event
+channel.createSticky('onDestroy');
+
+// Channels that must fire before "deviceready" is fired.
+channel.waitForInitialization('onCordovaReady');
+channel.waitForInitialization('onCordovaConnectionReady');
+channel.waitForInitialization('onDOMContentLoaded');
+
+module.exports = channel;
+
+});
+
+// file: lib/common/commandProxy.js
+define("cordova/commandProxy", function(require, exports, module) {
+
+
+// internal map of proxy function
+var CommandProxyMap = {};
+
+module.exports = {
+
+ // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);
+ add:function(id,proxyObj) {
+ console.log("adding proxy for " + id);
+ CommandProxyMap[id] = proxyObj;
+ return proxyObj;
+ },
+
+ // cordova.commandProxy.remove("Accelerometer");
+ remove:function(id) {
+ var proxy = CommandProxyMap[id];
+ delete CommandProxyMap[id];
+ CommandProxyMap[id] = null;
+ return proxy;
+ },
+
+ get:function(service,action) {
+ return ( CommandProxyMap[service] ? CommandProxyMap[service][action] : null );
+ }
+};
+});
+
+// file: lib/blackberry10/exec.js
+define("cordova/exec", function(require, exports, module) {
+
+var cordova = require('cordova'),
+ plugins = {
+ 'Compass' : require('cordova/plugin/blackberry10/magnetometer'),
+ 'Capture' : require('cordova/plugin/blackberry10/capture'),
+ 'Media': require('cordova/plugin/blackberry10/media'),
+ 'FileTransfer': require('cordova/plugin/blackberry10/fileTransfer')
+ };
+
+/**
+ * Execute a cordova command. It is up to the native side whether this action
+ * is synchronous or asynchronous. The native side can return:
+ * Synchronous: PluginResult object as a JSON string
+ * Asynchronous: Empty string ""
+ * If async, the native side will cordova.callbackSuccess or cordova.callbackError,
+ * depending upon the result of the action.
+ *
+ * @param {Function} success The success callback
+ * @param {Function} fail The fail callback
+ * @param {String} service The name of the service to use
+ * @param {String} action Action to be run in cordova
+ * @param {String[]} [args] Zero or more arguments to pass to the method
+ */
+module.exports = function (success, fail, service, action, args) {
+ if (plugins[service] && plugins[service][action]) {
+ return plugins[service][action](args, success, fail);
+ }
+ return webworks.exec(success, fail, service, action, args);
+};
+
+});
+
+// file: lib/common/modulemapper.js
+define("cordova/modulemapper", function(require, exports, module) {
+
+var builder = require('cordova/builder'),
+ moduleMap = define.moduleMap,
+ symbolList,
+ deprecationMap;
+
+exports.reset = function() {
+ symbolList = [];
+ deprecationMap = {};
+};
+
+function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) {
+ if (!(moduleName in moduleMap)) {
+ throw new Error('Module ' + moduleName + ' does not exist.');
+ }
+ symbolList.push(strategy, moduleName, symbolPath);
+ if (opt_deprecationMessage) {
+ deprecationMap[symbolPath] = opt_deprecationMessage;
+ }
+}
+
+// Note: Android 2.3 does have Function.bind().
+exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) {
+ addEntry('c', moduleName, symbolPath, opt_deprecationMessage);
+};
+
+exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) {
+ addEntry('m', moduleName, symbolPath, opt_deprecationMessage);
+};
+
+exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) {
+ addEntry('d', moduleName, symbolPath, opt_deprecationMessage);
+};
+
+function prepareNamespace(symbolPath, context) {
+ if (!symbolPath) {
+ return context;
+ }
+ var parts = symbolPath.split('.');
+ var cur = context;
+ for (var i = 0, part; part = parts[i]; ++i) {
+ cur = cur[part] = cur[part] || {};
+ }
+ return cur;
+}
+
+exports.mapModules = function(context) {
+ var origSymbols = {};
+ context.CDV_origSymbols = origSymbols;
+ for (var i = 0, len = symbolList.length; i < len; i += 3) {
+ var strategy = symbolList[i];
+ var moduleName = symbolList[i + 1];
+ var symbolPath = symbolList[i + 2];
+ var lastDot = symbolPath.lastIndexOf('.');
+ var namespace = symbolPath.substr(0, lastDot);
+ var lastName = symbolPath.substr(lastDot + 1);
+
+ var module = require(moduleName);
+ var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;
+ var parentObj = prepareNamespace(namespace, context);
+ var target = parentObj[lastName];
+
+ if (strategy == 'm' && target) {
+ builder.recursiveMerge(target, module);
+ } else if ((strategy == 'd' && !target) || (strategy != 'd')) {
+ if (!(symbolPath in origSymbols)) {
+ origSymbols[symbolPath] = target;
+ }
+ builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);
+ }
+ }
+};
+
+exports.getOriginalSymbol = function(context, symbolPath) {
+ var origSymbols = context.CDV_origSymbols;
+ if (origSymbols && (symbolPath in origSymbols)) {
+ return origSymbols[symbolPath];
+ }
+ var parts = symbolPath.split('.');
+ var obj = context;
+ for (var i = 0; i < parts.length; ++i) {
+ obj = obj && obj[parts[i]];
+ }
+ return obj;
+};
+
+exports.loadMatchingModules = function(matchingRegExp) {
+ for (var k in moduleMap) {
+ if (matchingRegExp.exec(k)) {
+ require(k);
+ }
+ }
+};
+
+exports.reset();
+
+
+});
+
+// file: lib/blackberry10/platform.js
+define("cordova/platform", function(require, exports, module) {
+
+module.exports = {
+ id: "blackberry10",
+ initialize: function() {
+ var modulemapper = require('cordova/modulemapper'),
+ cordova = require('cordova'),
+ addDocumentEventListener = document.addEventListener;
+
+ modulemapper.loadMatchingModules(/cordova.*\/symbols$/);
+ modulemapper.loadMatchingModules(new RegExp('cordova/blackberry10/.*bbsymbols$'));
+
+ modulemapper.clobbers('cordova/plugin/blackberry10/vibrate', 'navigator.notification.vibrate');
+ modulemapper.clobbers('cordova/plugin/File', 'File');
+ modulemapper.merges('cordova/plugin/blackberry10/compass', 'navigator.compass');
+
+ modulemapper.mapModules(window);
+
+ //override to pass online/offline events to window
+ document.addEventListener = function (type) {
+ if (type === "online" || type === "offline") {
+ window.addEventListener.apply(window, arguments);
+ } else {
+ addDocumentEventListener.apply(document, arguments);
+ }
+ }
+ }
+};
+
+});
+
+// file: lib/common/plugin/Acceleration.js
+define("cordova/plugin/Acceleration", function(require, exports, module) {
+
+var Acceleration = function(x, y, z, timestamp) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.timestamp = timestamp || (new Date()).getTime();
+};
+
+module.exports = Acceleration;
+
+});
+
+// file: lib/common/plugin/Camera.js
+define("cordova/plugin/Camera", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ Camera = require('cordova/plugin/CameraConstants'),
+ CameraPopoverHandle = require('cordova/plugin/CameraPopoverHandle');
+
+var cameraExport = {};
+
+// Tack on the Camera Constants to the base camera plugin.
+for (var key in Camera) {
+ cameraExport[key] = Camera[key];
+}
+
+/**
+ * Gets a picture from source defined by "options.sourceType", and returns the
+ * image as defined by the "options.destinationType" option.
+
+ * The defaults are sourceType=CAMERA and destinationType=FILE_URI.
+ *
+ * @param {Function} successCallback
+ * @param {Function} errorCallback
+ * @param {Object} options
+ */
+cameraExport.getPicture = function(successCallback, errorCallback, options) {
+ argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);
+ options = options || {};
+ var getValue = argscheck.getValue;
+
+ var quality = getValue(options.quality, 50);
+ var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);
+ var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);
+ var targetWidth = getValue(options.targetWidth, -1);
+ var targetHeight = getValue(options.targetHeight, -1);
+ var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);
+ var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);
+ var allowEdit = !!options.allowEdit;
+ var correctOrientation = !!options.correctOrientation;
+ var saveToPhotoAlbum = !!options.saveToPhotoAlbum;
+ var popoverOptions = getValue(options.popoverOptions, null);
+ var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
+
+ var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,
+ mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];
+
+ exec(successCallback, errorCallback, "Camera", "takePicture", args);
+ return new CameraPopoverHandle();
+};
+
+cameraExport.cleanup = function(successCallback, errorCallback) {
+ exec(successCallback, errorCallback, "Camera", "cleanup", []);
+};
+
+module.exports = cameraExport;
+
+});
+
+// file: lib/common/plugin/CameraConstants.js
+define("cordova/plugin/CameraConstants", function(require, exports, module) {
+
+module.exports = {
+ DestinationType:{
+ DATA_URL: 0, // Return base64 encoded string
+ FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
+ NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
+ },
+ EncodingType:{
+ JPEG: 0, // Return JPEG encoded image
+ PNG: 1 // Return PNG encoded image
+ },
+ MediaType:{
+ PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
+ VIDEO: 1, // allow selection of video only, ONLY RETURNS URL
+ ALLMEDIA : 2 // allow selection from all media types
+ },
+ PictureSourceType:{
+ PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
+ CAMERA : 1, // Take picture from camera
+ SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
+ },
+ PopoverArrowDirection:{
+ ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants to specify arrow location on popover
+ ARROW_DOWN : 2,
+ ARROW_LEFT : 4,
+ ARROW_RIGHT : 8,
+ ARROW_ANY : 15
+ },
+ Direction:{
+ BACK: 0,
+ FRONT: 1
+ }
+};
+
+});
+
+// file: lib/common/plugin/CameraPopoverHandle.js
+define("cordova/plugin/CameraPopoverHandle", function(require, exports, module) {
+
+var exec = require('cordova/exec');
+
+/**
+ * A handle to an image picker popover.
+ */
+var CameraPopoverHandle = function() {
+ this.setPosition = function(popoverOptions) {
+ console.log('CameraPopoverHandle.setPosition is only supported on iOS.');
+ };
+};
+
+module.exports = CameraPopoverHandle;
+
+});
+
+// file: lib/common/plugin/CameraPopoverOptions.js
+define("cordova/plugin/CameraPopoverOptions", function(require, exports, module) {
+
+var Camera = require('cordova/plugin/CameraConstants');
+
+/**
+ * Encapsulates options for iOS Popover image picker
+ */
+var CameraPopoverOptions = function(x,y,width,height,arrowDir){
+ // information of rectangle that popover should be anchored to
+ this.x = x || 0;
+ this.y = y || 32;
+ this.width = width || 320;
+ this.height = height || 480;
+ // The direction of the popover arrow
+ this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY;
+};
+
+module.exports = CameraPopoverOptions;
+
+});
+
+// file: lib/common/plugin/CaptureAudioOptions.js
+define("cordova/plugin/CaptureAudioOptions", function(require, exports, module) {
+
+/**
+ * Encapsulates all audio capture operation configuration options.
+ */
+var CaptureAudioOptions = function(){
+ // Upper limit of sound clips user can record. Value must be equal or greater than 1.
+ this.limit = 1;
+ // Maximum duration of a single sound clip in seconds.
+ this.duration = 0;
+};
+
+module.exports = CaptureAudioOptions;
+
+});
+
+// file: lib/common/plugin/CaptureError.js
+define("cordova/plugin/CaptureError", function(require, exports, module) {
+
+/**
+ * The CaptureError interface encapsulates all errors in the Capture API.
+ */
+var CaptureError = function(c) {
+ this.code = c || null;
+};
+
+// Camera or microphone failed to capture image or sound.
+CaptureError.CAPTURE_INTERNAL_ERR = 0;
+// Camera application or audio capture application is currently serving other capture request.
+CaptureError.CAPTURE_APPLICATION_BUSY = 1;
+// Invalid use of the API (e.g. limit parameter has value less than one).
+CaptureError.CAPTURE_INVALID_ARGUMENT = 2;
+// User exited camera application or audio capture application before capturing anything.
+CaptureError.CAPTURE_NO_MEDIA_FILES = 3;
+// The requested capture operation is not supported.
+CaptureError.CAPTURE_NOT_SUPPORTED = 20;
+
+module.exports = CaptureError;
+
+});
+
+// file: lib/common/plugin/CaptureImageOptions.js
+define("cordova/plugin/CaptureImageOptions", function(require, exports, module) {
+
+/**
+ * Encapsulates all image capture operation configuration options.
+ */
+var CaptureImageOptions = function(){
+ // Upper limit of images user can take. Value must be equal or greater than 1.
+ this.limit = 1;
+};
+
+module.exports = CaptureImageOptions;
+
+});
+
+// file: lib/common/plugin/CaptureVideoOptions.js
+define("cordova/plugin/CaptureVideoOptions", function(require, exports, module) {
+
+/**
+ * Encapsulates all video capture operation configuration options.
+ */
+var CaptureVideoOptions = function(){
+ // Upper limit of videos user can record. Value must be equal or greater than 1.
+ this.limit = 1;
+ // Maximum duration of a single video clip in seconds.
+ this.duration = 0;
+};
+
+module.exports = CaptureVideoOptions;
+
+});
+
+// file: lib/common/plugin/CompassError.js
+define("cordova/plugin/CompassError", function(require, exports, module) {
+
+/**
+ * CompassError.
+ * An error code assigned by an implementation when an error has occurred
+ * @constructor
+ */
+var CompassError = function(err) {
+ this.code = (err !== undefined ? err : null);
+};
+
+CompassError.COMPASS_INTERNAL_ERR = 0;
+CompassError.COMPASS_NOT_SUPPORTED = 20;
+
+module.exports = CompassError;
+
+});
+
+// file: lib/common/plugin/CompassHeading.js
+define("cordova/plugin/CompassHeading", function(require, exports, module) {
+
+var CompassHeading = function(magneticHeading, trueHeading, headingAccuracy, timestamp) {
+ this.magneticHeading = magneticHeading;
+ this.trueHeading = trueHeading;
+ this.headingAccuracy = headingAccuracy;
+ this.timestamp = timestamp || new Date().getTime();
+};
+
+module.exports = CompassHeading;
+
+});
+
+// file: lib/common/plugin/ConfigurationData.js
+define("cordova/plugin/ConfigurationData", function(require, exports, module) {
+
+/**
+ * Encapsulates a set of parameters that the capture device supports.
+ */
+function ConfigurationData() {
+ // The ASCII-encoded string in lower case representing the media type.
+ this.type = null;
+ // The height attribute represents height of the image or video in pixels.
+ // In the case of a sound clip this attribute has value 0.
+ this.height = 0;
+ // The width attribute represents width of the image or video in pixels.
+ // In the case of a sound clip this attribute has value 0
+ this.width = 0;
+}
+
+module.exports = ConfigurationData;
+
+});
+
+// file: lib/common/plugin/Connection.js
+define("cordova/plugin/Connection", function(require, exports, module) {
+
+/**
+ * Network status
+ */
+module.exports = {
+ UNKNOWN: "unknown",
+ ETHERNET: "ethernet",
+ WIFI: "wifi",
+ CELL_2G: "2g",
+ CELL_3G: "3g",
+ CELL_4G: "4g",
+ CELL:"cellular",
+ NONE: "none"
+};
+
+});
+
+// file: lib/common/plugin/Contact.js
+define("cordova/plugin/Contact", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ ContactError = require('cordova/plugin/ContactError'),
+ utils = require('cordova/utils');
+
+/**
+* Converts primitives into Complex Object
+* Currently only used for Date fields
+*/
+function convertIn(contact) {
+ var value = contact.birthday;
+ try {
+ contact.birthday = new Date(parseFloat(value));
+ } catch (exception){
+ console.log("Cordova Contact convertIn error: exception creating date.");
+ }
+ return contact;
+}
+
+/**
+* Converts Complex objects into primitives
+* Only conversion at present is for Dates.
+**/
+
+function convertOut(contact) {
+ var value = contact.birthday;
+ if (value !== null) {
+ // try to make it a Date object if it is not already
+ if (!utils.isDate(value)){
+ try {
+ value = new Date(value);
+ } catch(exception){
+ value = null;
+ }
+ }
+ if (utils.isDate(value)){
+ value = value.valueOf(); // convert to milliseconds
+ }
+ contact.birthday = value;
+ }
+ return contact;
+}
+
+/**
+* Contains information about a single contact.
+* @constructor
+* @param {DOMString} id unique identifier
+* @param {DOMString} displayName
+* @param {ContactName} name
+* @param {DOMString} nickname
+* @param {Array.<ContactField>} phoneNumbers array of phone numbers
+* @param {Array.<ContactField>} emails array of email addresses
+* @param {Array.<ContactAddress>} addresses array of addresses
+* @param {Array.<ContactField>} ims instant messaging user ids
+* @param {Array.<ContactOrganization>} organizations
+* @param {DOMString} birthday contact's birthday
+* @param {DOMString} note user notes about contact
+* @param {Array.<ContactField>} photos
+* @param {Array.<ContactField>} categories
+* @param {Array.<ContactField>} urls contact's web sites
+*/
+var Contact = function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
+ ims, organizations, birthday, note, photos, categories, urls) {
+ this.id = id || null;
+ this.rawId = null;
+ this.displayName = displayName || null;
+ this.name = name || null; // ContactName
+ this.nickname = nickname || null;
+ this.phoneNumbers = phoneNumbers || null; // ContactField[]
+ this.emails = emails || null; // ContactField[]
+ this.addresses = addresses || null; // ContactAddress[]
+ this.ims = ims || null; // ContactField[]
+ this.organizations = organizations || null; // ContactOrganization[]
+ this.birthday = birthday || null;
+ this.note = note || null;
+ this.photos = photos || null; // ContactField[]
+ this.categories = categories || null; // ContactField[]
+ this.urls = urls || null; // ContactField[]
+};
+
+/**
+* Removes contact from device storage.
+* @param successCB success callback
+* @param errorCB error callback
+*/
+Contact.prototype.remove = function(successCB, errorCB) {
+ argscheck.checkArgs('FF', 'Contact.remove', arguments);
+ var fail = errorCB && function(code) {
+ errorCB(new ContactError(code));
+ };
+ if (this.id === null) {
+ fail(ContactError.UNKNOWN_ERROR);
+ }
+ else {
+ exec(successCB, fail, "Contacts", "remove", [this.id]);
+ }
+};
+
+/**
+* Creates a deep copy of this Contact.
+* With the contact ID set to null.
+* @return copy of this Contact
+*/
+Contact.prototype.clone = function() {
+ var clonedContact = utils.clone(this);
+ clonedContact.id = null;
+ clonedContact.rawId = null;
+
+ function nullIds(arr) {
+ if (arr) {
+ for (var i = 0; i < arr.length; ++i) {
+ arr[i].id = null;
+ }
+ }
+ }
+
+ // Loop through and clear out any id's in phones, emails, etc.
+ nullIds(clonedContact.phoneNumbers);
+ nullIds(clonedContact.emails);
+ nullIds(clonedContact.addresses);
+ nullIds(clonedContact.ims);
+ nullIds(clonedContact.organizations);
+ nullIds(clonedContact.categories);
+ nullIds(clonedContact.photos);
+ nullIds(clonedContact.urls);
+ return clonedContact;
+};
+
+/**
+* Persists contact to device storage.
+* @param successCB success callback
+* @param errorCB error callback
+*/
+Contact.prototype.save = function(successCB, errorCB) {
+ argscheck.checkArgs('FFO', 'Contact.save', arguments);
+ var fail = errorCB && function(code) {
+ errorCB(new ContactError(code));
+ };
+ var success = function(result) {
+ if (result) {
+ if (successCB) {
+ var fullContact = require('cordova/plugin/contacts').create(result);
+ successCB(convertIn(fullContact));
+ }
+ }
+ else {
+ // no Entry object returned
+ fail(ContactError.UNKNOWN_ERROR);
+ }
+ };
+ var dupContact = convertOut(utils.clone(this));
+ exec(success, fail, "Contacts", "save", [dupContact]);
+};
+
+
+module.exports = Contact;
+
+});
+
+// file: lib/common/plugin/ContactAddress.js
+define("cordova/plugin/ContactAddress", function(require, exports, module) {
+
+/**
+* Contact address.
+* @constructor
+* @param {DOMString} id unique identifier, should only be set by native code
+* @param formatted // NOTE: not a W3C standard
+* @param streetAddress
+* @param locality
+* @param region
+* @param postalCode
+* @param country
+*/
+
+var ContactAddress = function(pref, type, formatted, streetAddress, locality, region, postalCode, country) {
+ this.id = null;
+ this.pref = (typeof pref != 'undefined' ? pref : false);
+ this.type = type || null;
+ this.formatted = formatted || null;
+ this.streetAddress = streetAddress || null;
+ this.locality = locality || null;
+ this.region = region || null;
+ this.postalCode = postalCode || null;
+ this.country = country || null;
+};
+
+module.exports = ContactAddress;
+
+});
+
+// file: lib/common/plugin/ContactError.js
+define("cordova/plugin/ContactError", function(require, exports, module) {
+
+/**
+ * ContactError.
+ * An error code assigned by an implementation when an error has occurred
+ * @constructor
+ */
+var ContactError = function(err) {
+ this.code = (typeof err != 'undefined' ? err : null);
+};
+
+/**
+ * Error codes
+ */
+ContactError.UNKNOWN_ERROR = 0;
+ContactError.INVALID_ARGUMENT_ERROR = 1;
+ContactError.TIMEOUT_ERROR = 2;
+ContactError.PENDING_OPERATION_ERROR = 3;
+ContactError.IO_ERROR = 4;
+ContactError.NOT_SUPPORTED_ERROR = 5;
+ContactError.PERMISSION_DENIED_ERROR = 20;
+
+module.exports = ContactError;
+
+});
+
+// file: lib/common/plugin/ContactField.js
+define("cordova/plugin/ContactField", function(require, exports, module) {
+
+/**
+* Generic contact field.
+* @constructor
+* @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard
+* @param type
+* @param value
+* @param pref
+*/
+var ContactField = function(type, value, pref) {
+ this.id = null;
+ this.type = (type && type.toString()) || null;
+ this.value = (value && value.toString()) || null;
+ this.pref = (typeof pref != 'undefined' ? pref : false);
+};
+
+module.exports = ContactField;
+
+});
+
+// file: lib/common/plugin/ContactFindOptions.js
+define("cordova/plugin/ContactFindOptions", function(require, exports, module) {
+
+/**
+ * ContactFindOptions.
+ * @constructor
+ * @param filter used to match contacts against
+ * @param multiple boolean used to determine if more than one contact should be returned
+ */
+
+var ContactFindOptions = function(filter, multiple) {
+ this.filter = filter || '';
+ this.multiple = (typeof multiple != 'undefined' ? multiple : false);
+};
+
+module.exports = ContactFindOptions;
+
+});
+
+// file: lib/common/plugin/ContactName.js
+define("cordova/plugin/ContactName", function(require, exports, module) {
+
+/**
+* Contact name.
+* @constructor
+* @param formatted // NOTE: not part of W3C standard
+* @param familyName
+* @param givenName
+* @param middle
+* @param prefix
+* @param suffix
+*/
+var ContactName = function(formatted, familyName, givenName, middle, prefix, suffix) {
+ this.formatted = formatted || null;
+ this.familyName = familyName || null;
+ this.givenName = givenName || null;
+ this.middleName = middle || null;
+ this.honorificPrefix = prefix || null;
+ this.honorificSuffix = suffix || null;
+};
+
+module.exports = ContactName;
+
+});
+
+// file: lib/common/plugin/ContactOrganization.js
+define("cordova/plugin/ContactOrganization", function(require, exports, module) {
+
+/**
+* Contact organization.
+* @constructor
+* @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard
+* @param name
+* @param dept
+* @param title
+* @param startDate
+* @param endDate
+* @param location
+* @param desc
+*/
+
+var ContactOrganization = function(pref, type, name, dept, title) {
+ this.id = null;
+ this.pref = (typeof pref != 'undefined' ? pref : false);
+ this.type = type || null;
+ this.name = name || null;
+ this.department = dept || null;
+ this.title = title || null;
+};
+
+module.exports = ContactOrganization;
+
+});
+
+// file: lib/common/plugin/Coordinates.js
+define("cordova/plugin/Coordinates", function(require, exports, module) {
+
+/**
+ * This class contains position information.
+ * @param {Object} lat
+ * @param {Object} lng
+ * @param {Object} alt
+ * @param {Object} acc
+ * @param {Object} head
+ * @param {Object} vel
+ * @param {Object} altacc
+ * @constructor
+ */
+var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
+ /**
+ * The latitude of the position.
+ */
+ this.latitude = lat;
+ /**
+ * The longitude of the position,
+ */
+ this.longitude = lng;
+ /**
+ * The accuracy of the position.
+ */
+ this.accuracy = acc;
+ /**
+ * The altitude of the position.
+ */
+ this.altitude = (alt !== undefined ? alt : null);
+ /**
+ * The direction the device is moving at the position.
+ */
+ this.heading = (head !== undefined ? head : null);
+ /**
+ * The velocity with which the device is moving at the position.
+ */
+ this.speed = (vel !== undefined ? vel : null);
+
+ if (this.speed === 0 || this.speed === null) {
+ this.heading = NaN;
+ }
+
+ /**
+ * The altitude accuracy of the position.
+ */
+ this.altitudeAccuracy = (altacc !== undefined) ? altacc : null;
+};
+
+module.exports = Coordinates;
+
+});
+
+// file: lib/blackberry10/plugin/DirectoryEntry.js
+define("cordova/plugin/DirectoryEntry", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ utils = require('cordova/utils'),
+ Entry = require('cordova/plugin/Entry'),
+ FileError = require('cordova/plugin/FileError'),
+ DirectoryReader = require('cordova/plugin/DirectoryReader'),
+ fileUtils = require('cordova/plugin/blackberry10/fileUtils'),
+ DirectoryEntry = function (name, fullPath) {
+ DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath);
+ };
+
+utils.extend(DirectoryEntry, Entry);
+
+DirectoryEntry.prototype.createReader = function () {
+ return new DirectoryReader(this.fullPath);
+};
+
+DirectoryEntry.prototype.getDirectory = function (path, options, successCallback, errorCallback) {
+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
+ this.nativeEntry.getDirectory(path, options, function (entry) {
+ successCallback(fileUtils.createEntry(entry));
+ }, errorCallback);
+};
+
+DirectoryEntry.prototype.removeRecursively = function (successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
+ this.nativeEntry.removeRecursively(successCallback, errorCallback);
+};
+
+DirectoryEntry.prototype.getFile = function (path, options, successCallback, errorCallback) {
+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
+ this.nativeEntry.getFile(path, options, function (entry) {
+ successCallback(fileUtils.createEntry(entry));
+ }, errorCallback);
+};
+
+module.exports = DirectoryEntry;
+
+});
+
+// file: lib/blackberry10/plugin/DirectoryReader.js
+define("cordova/plugin/DirectoryReader", function(require, exports, module) {
+
+var FileError = require('cordova/plugin/FileError'),
+ fileUtils = require('cordova/plugin/blackberry10/fileUtils');
+
+function DirectoryReader(path) {
+ this.path = path;
+}
+
+DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
+ var win = typeof successCallback !== 'function' ? null : function(result) {
+ var retVal = [];
+ for (var i=0; i<result.length; i++) {
+ retVal.push(fileUtils.createEntry(result[i]));
+ }
+ successCallback(retVal);
+ },
+ fail = typeof errorCallback !== 'function' ? null : function(code) {
+ errorCallback(new FileError(code));
+ };
+ fileUtils.getEntryForURI(this.path, function (entry) {
+ entry.nativeEntry.createReader().readEntries(win, fail);
+ }, function () {
+ fail(FileError.NOT_FOUND_ERR);
+ });
+};
+
+module.exports = DirectoryReader;
+
+});
+
+// file: lib/blackberry10/plugin/Entry.js
+define("cordova/plugin/Entry", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ FileError = require('cordova/plugin/FileError'),
+ Metadata = require('cordova/plugin/Metadata'),
+ fileUtils = require('cordova/plugin/blackberry10/fileUtils');
+
+function Entry(isFile, isDirectory, name, fullPath, fileSystem) {
+ this.isFile = !!isFile;
+ this.isDirectory = !!isDirectory;
+ this.name = name || '';
+ this.fullPath = fullPath || '';
+ this.filesystem = fileSystem || null;
+}
+
+Entry.prototype.getMetadata = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.getMetadata', arguments);
+ var success = function(lastModified) {
+ var metadata = new Metadata(lastModified);
+ if (typeof successCallback === 'function') {
+ successCallback(metadata);
+ }
+ };
+ this.nativeEntry.getMetadata(success, errorCallback);
+};
+
+Entry.prototype.setMetadata = function(successCallback, errorCallback, metadataObject) {
+ argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments);
+ errorCallback("Not supported by platform");
+};
+
+Entry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
+ argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments);
+ var srcPath = this.fullPath,
+ name = newName || this.name,
+ success = function(entry) {
+ if (entry) {
+ if (typeof successCallback === 'function') {
+ successCallback(fileUtils.createEntry(entry));
+ }
+ }
+ else {
+ if (typeof errorCallback === 'function') {
+ errorCallback(new FileError(FileError.NOT_FOUND_ERR));
+ }
+ }
+ };
+ this.nativeEntry.moveTo(parent.nativeEntry, newName, success, errorCallback);
+};
+
+
+Entry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
+ argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments);
+ var srcPath = this.fullPath,
+ name = newName || this.name,
+ success = function(entry) {
+ if (entry) {
+ if (typeof successCallback === 'function') {
+ successCallback(fileUtils.createEntry(entry));
+ }
+ }
+ else {
+ if (typeof errorCallback === 'function') {
+ errorCallback(new FileError(FileError.NOT_FOUND_ERR));
+ }
+ }
+ };
+ this.nativeEntry.copyTo(parent.nativeEntry, newName, success, errorCallback);
+};
+
+Entry.prototype.toURL = function() {
+ return this.fullPath;
+};
+
+Entry.prototype.toURI = function(mimeType) {
+ console.log("DEPRECATED: Update your code to use 'toURL'");
+ return this.toURL();
+};
+
+Entry.prototype.remove = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.remove', arguments);
+ this.nativeEntry.remove(successCallback, errorCallback);
+};
+
+Entry.prototype.getParent = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.getParent', arguments);
+ var win = successCallback && function(result) {
+ successCallback(fileUtils.createEntry(result));
+ };
+ this.nativeEntry.getParent(win, errorCallback);
+};
+
+module.exports = Entry;
+
+});
+
+// file: lib/common/plugin/File.js
+define("cordova/plugin/File", function(require, exports, module) {
+
+/**
+ * Constructor.
+ * name {DOMString} name of the file, without path information
+ * fullPath {DOMString} the full path of the file, including the name
+ * type {DOMString} mime type
+ * lastModifiedDate {Date} last modified date
+ * size {Number} size of the file in bytes
+ */
+
+var File = function(name, fullPath, type, lastModifiedDate, size){
+ this.name = name || '';
+ this.fullPath = fullPath || null;
+ this.type = type || null;
+ this.lastModifiedDate = lastModifiedDate || null;
+ this.size = size || 0;
+
+ // These store the absolute start and end for slicing the file.
+ this.start = 0;
+ this.end = this.size;
+};
+
+/**
+ * Returns a "slice" of the file. Since Cordova Files don't contain the actual
+ * content, this really returns a File with adjusted start and end.
+ * Slices of slices are supported.
+ * start {Number} The index at which to start the slice (inclusive).
+ * end {Number} The index at which to end the slice (exclusive).
+ */
+File.prototype.slice = function(start, end) {
+ var size = this.end - this.start;
+ var newStart = 0;
+ var newEnd = size;
+ if (arguments.length) {
+ if (start < 0) {
+ newStart = Math.max(size + start, 0);
+ } else {
+ newStart = Math.min(size, start);
+ }
+ }
+
+ if (arguments.length >= 2) {
+ if (end < 0) {
+ newEnd = Math.max(size + end, 0);
+ } else {
+ newEnd = Math.min(end, size);
+ }
+ }
+
+ var newFile = new File(this.name, this.fullPath, this.type, this.lastModifiedData, this.size);
+ newFile.start = this.start + newStart;
+ newFile.end = this.start + newEnd;
+ return newFile;
+};
+
+
+module.exports = File;
+
+});
+
+// file: lib/blackberry10/plugin/FileEntry.js
+define("cordova/plugin/FileEntry", function(require, exports, module) {
+
+var utils = require('cordova/utils'),
+ Entry = require('cordova/plugin/Entry'),
+ FileWriter = require('cordova/plugin/FileWriter'),
+ File = require('cordova/plugin/File'),
+ FileError = require('cordova/plugin/FileError'),
+ FileEntry = function (name, fullPath) {
+ FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath]);
+ };
+
+utils.extend(FileEntry, Entry);
+
+FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
+ this.file(function (file) {
+ successCallback(new FileWriter(file));
+ }, errorCallback);
+};
+
+FileEntry.prototype.file = function(successCallback, errorCallback) {
+ var fullPath = this.fullPath,
+ success = function (file) {
+ successCallback(new File(file.name, fullPath, file.type, file.lastModifiedDate, file.size));
+ };
+ this.nativeEntry.file(success, errorCallback);
+};
+
+module.exports = FileEntry;
+
+});
+
+// file: lib/common/plugin/FileError.js
+define("cordova/plugin/FileError", function(require, exports, module) {
+
+/**
+ * FileError
+ */
+function FileError(error) {
+ this.code = error || null;
+}
+
+// File error codes
+// Found in DOMException
+FileError.NOT_FOUND_ERR = 1;
+FileError.SECURITY_ERR = 2;
+FileError.ABORT_ERR = 3;
+
+// Added by File API specification
+FileError.NOT_READABLE_ERR = 4;
+FileError.ENCODING_ERR = 5;
+FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
+FileError.INVALID_STATE_ERR = 7;
+FileError.SYNTAX_ERR = 8;
+FileError.INVALID_MODIFICATION_ERR = 9;
+FileError.QUOTA_EXCEEDED_ERR = 10;
+FileError.TYPE_MISMATCH_ERR = 11;
+FileError.PATH_EXISTS_ERR = 12;
+
+module.exports = FileError;
+
+});
+
+// file: lib/blackberry10/plugin/FileReader.js
+define("cordova/plugin/FileReader", function(require, exports, module) {
+
+var origFileReader = window.FileReader,
+ fileUtils = require('cordova/plugin/blackberry10/fileUtils'),
+ utils = require('cordova/utils');
+
+var FileReader = function() {
+ this.nativeReader = new origFileReader();
+};
+
+utils.defineGetter(FileReader.prototype, 'readyState', function() {
+ return this.nativeReader.readyState;
+});
+
+utils.defineGetter(FileReader.prototype, 'error', function() {
+ return this.nativeReader.error;
+});
+
+utils.defineGetter(FileReader.prototype, 'result', function() {
+ return this.nativeReader.result;
+});
+
+function defineEvent(eventName) {
+ utils.defineGetterSetter(FileReader.prototype, eventName, function() {
+ return this.nativeReader[eventName] || null;
+ }, function(value) {
+ this.nativeReader[eventName] = value;
+ });
+}
+
+defineEvent('onabort');
+defineEvent('onerror');
+defineEvent('onload');
+defineEvent('onloadend');
+defineEvent('onloadstart');
+defineEvent('onprogress');
+
+FileReader.prototype.abort = function() {
+ return this.nativeReader.abort();
+};
+
+function read(method, context, file, encoding) {
+ if (file.fullPath) {
+ fileUtils.getEntryForURI(file.fullPath, function (entry) {
+ entry.nativeEntry.file(function (nativeFile) {
+ context.nativeReader[method].call(context.nativeReader, nativeFile, encoding);
+ }, context.onerror);
+ }, context.onerror);
+ } else {
+ context.nativeReader[method](file, encoding);
+ }
+}
+
+FileReader.prototype.readAsText = function(file, encoding) {
+ read("readAsText", this, file, encoding);
+};
+
+FileReader.prototype.readAsDataURL = function(file) {
+ read("readAsDataURL", this, file);
+};
+
+FileReader.prototype.readAsBinaryString = function(file) {
+ read("readAsBinaryString", this, file);
+};
+
+FileReader.prototype.readAsArrayBuffer = function(file) {
+ read("readAsArrayBuffer", this, file);
+};
+
+window.FileReader = FileReader;
+module.exports = FileReader;
+
+});
+
+// file: lib/blackberry10/plugin/FileSystem.js
+define("cordova/plugin/FileSystem", function(require, exports, module) {
+
+module.exports = function(name, root) {
+ this.name = name || null;
+ if (root) {
+ this.root = root;
+ }
+};
+
+});
+
+// file: lib/blackberry10/plugin/FileTransfer.js
+define("cordova/plugin/FileTransfer", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ FileTransferError = require('cordova/plugin/FileTransferError');
+
+function getBasicAuthHeader(urlString) {
+ var header = null;
+
+ if (window.btoa) {
+ // parse the url using the Location object
+ var url = document.createElement('a');
+ url.href = urlString;
+
+ var credentials = null;
+ var protocol = url.protocol + "//";
+ var origin = protocol + url.host;
+
+ // check whether there are the username:password credentials in the url
+ if (url.href.indexOf(origin) !== 0) { // credentials found
+ var atIndex = url.href.indexOf("@");
+ credentials = url.href.substring(protocol.length, atIndex);
+ }
+
+ if (credentials) {
+ var authHeader = "Authorization";
+ var authHeaderValue = "Basic " + window.btoa(credentials);
+
+ header = {
+ name : authHeader,
+ value : authHeaderValue
+ };
+ }
+ }
+
+ return header;
+}
+
+var idCounter = 0;
+
+/**
+ * FileTransfer uploads a file to a remote server.
+ * @constructor
+ */
+var FileTransfer = function() {
+ this._id = ++idCounter;
+ this.onprogress = null; // optional callback
+};
+
+/**
+* Given an absolute file path, uploads a file on the device to a remote server
+* using a multipart HTTP request.
+* @param filePath {String} Full path of the file on the device
+* @param server {String} URL of the server to receive the file
+* @param successCallback (Function} Callback to be invoked when upload has completed
+* @param errorCallback {Function} Callback to be invoked upon error
+* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
+* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+*/
+FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
+ argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
+ // check for options
+ var fileKey = null;
+ var fileName = null;
+ var mimeType = null;
+ var params = null;
+ var chunkedMode = true;
+ var headers = null;
+ var httpMethod = null;
+ var basicAuthHeader = getBasicAuthHeader(server);
+ if (basicAuthHeader) {
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ if (options) {
+ fileKey = options.fileKey;
+ fileName = options.fileName;
+ mimeType = options.mimeType;
+ headers = options.headers;
+ httpMethod = options.httpMethod || "POST";
+ if (httpMethod.toUpperCase() == "PUT"){
+ httpMethod = "PUT";
+ } else {
+ httpMethod = "POST";
+ }
+ if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
+ chunkedMode = options.chunkedMode;
+ }
+ if (options.params) {
+ params = options.params;
+ }
+ else {
+ params = {};
+ }
+ }
+
+ var fail = errorCallback && function(e) {
+ var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body);
+ errorCallback(error);
+ };
+
+ var self = this;
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ self.onprogress(result);
+ }
+ } else {
+ successCallback && successCallback(result);
+ }
+ };
+ exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
+};
+
+/**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ * @param source {String} URL of the server to receive the file
+ * @param target {String} Full path of the file on the device
+ * @param successCallback (Function} Callback to be invoked when upload has completed
+ * @param errorCallback {Function} Callback to be invoked upon error
+ * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+ * @param options {FileDownloadOptions} Optional parameters such as headers
+ */
+FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
+ argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
+ var self = this;
+
+ var basicAuthHeader = getBasicAuthHeader(source);
+ if (basicAuthHeader) {
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ var headers = null;
+ if (options) {
+ headers = options.headers || null;
+ }
+
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ return self.onprogress(result);
+ }
+ } else if (successCallback) {
+ successCallback(result);
+ }
+ };
+
+ var fail = errorCallback && function(e) {
+ var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body);
+ errorCallback(error);
+ };
+
+ exec(win, fail, 'FileTransfer', 'download', [source, target, trustAllHosts, this._id, headers]);
+};
+
+/**
+ * Aborts the ongoing file transfer on this object. The original error
+ * callback for the file transfer will be called if necessary.
+ */
+FileTransfer.prototype.abort = function() {
+ exec(null, null, 'FileTransfer', 'abort', [this._id]);
+};
+
+module.exports = FileTransfer;
+
+});
+
+// file: lib/common/plugin/FileTransferError.js
+define("cordova/plugin/FileTransferError", function(require, exports, module) {
+
+/**
+ * FileTransferError
+ * @constructor
+ */
+var FileTransferError = function(code, source, target, status, body) {
+ this.code = code || null;
+ this.source = source || null;
+ this.target = target || null;
+ this.http_status = status || null;
+ this.body = body || null;
+};
+
+FileTransferError.FILE_NOT_FOUND_ERR = 1;
+FileTransferError.INVALID_URL_ERR = 2;
+FileTransferError.CONNECTION_ERR = 3;
+FileTransferError.ABORT_ERR = 4;
+
+module.exports = FileTransferError;
+
+});
+
+// file: lib/common/plugin/FileUploadOptions.js
+define("cordova/plugin/FileUploadOptions", function(require, exports, module) {
+
+/**
+ * Options to customize the HTTP request used to upload files.
+ * @constructor
+ * @param fileKey {String} Name of file request parameter.
+ * @param fileName {String} Filename to be used by the server. Defaults to image.jpg.
+ * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg.
+ * @param params {Object} Object with key: value params to send to the server.
+ * @param headers {Object} Keys are header names, values are header values. Multiple
+ * headers of the same name are not supported.
+ */
+var FileUploadOptions = function(fileKey, fileName, mimeType, params, headers, httpMethod) {
+ this.fileKey = fileKey || null;
+ this.fileName = fileName || null;
+ this.mimeType = mimeType || null;
+ this.params = params || null;
+ this.headers = headers || null;
+ this.httpMethod = httpMethod || null;
+};
+
+module.exports = FileUploadOptions;
+
+});
+
+// file: lib/common/plugin/FileUploadResult.js
+define("cordova/plugin/FileUploadResult", function(require, exports, module) {
+
+/**
+ * FileUploadResult
+ * @constructor
+ */
+var FileUploadResult = function() {
+ this.bytesSent = 0;
+ this.responseCode = null;
+ this.response = null;
+};
+
+module.exports = FileUploadResult;
+
+});
+
+// file: lib/blackberry10/plugin/FileWriter.js
+define("cordova/plugin/FileWriter", function(require, exports, module) {
+
+var FileError = require('cordova/plugin/FileError'),
+ ProgressEvent = require('cordova/plugin/ProgressEvent'),
+ fileUtils = require('cordova/plugin/blackberry10/fileUtils'),
+ utils = require('cordova/utils');
+
+function FileWriter (file) {
+ var that = this;
+ this.file = file;
+ this.events = {};
+ this.pending = [];
+ fileUtils.getEntryForURI(file.fullPath, function (entry) {
+ entry.nativeEntry.createWriter(function (writer) {
+ var i,
+ event;
+ that.nativeWriter = writer;
+ for (event in that.events) {
+ if (that.events.hasOwnProperty(event)) {
+ that.nativeWriter[event] = that.events[event];
+ }
+ }
+ for (i = 0; i < that.pending.length; i++) {
+ that.pending[i]();
+ }
+ });
+ });
+ this.events = {};
+ this.pending = [];
+}
+
+utils.defineGetter(FileWriter.prototype, 'error', function() {
+ return this.nativeWriter ? this.nativeWriter.error : null;
+});
+
+utils.defineGetter(FileWriter.prototype, 'fileName', function() {
+ return this.nativeWriter ? this.nativeWriter.fileName : this.file.name;
+});
+
+utils.defineGetter(FileWriter.prototype, 'length', function() {
+ return this.nativeWriter ? this.nativeWriter.length : this.file.size;
+});
+
+utils.defineGetter(FileWriter.prototype, 'position', function() {
+ return this.nativeWriter ? this.nativeWriter.position : 0;
+});
+
+utils.defineGetter(FileWriter.prototype, 'readyState', function() {
+ return this.nativeWriter ? this.nativeWriter.readyState : 0;
+});
+
+function defineEvent(eventName) {
+ utils.defineGetterSetter(FileWriter.prototype, eventName, function() {
+ return this.nativeWriter ? this.nativeWriter[eventName] || null : this.events[eventName] || null;
+ }, function(value) {
+ if (this.nativeWriter) {
+ this.nativeWriter[eventName] = value;
+ }
+ else {
+ this.events[eventName] = value;
+ }
+ });
+}
+
+defineEvent('onabort');
+defineEvent('onerror');
+defineEvent('onprogress');
+defineEvent('onwrite');
+defineEvent('onwriteend');
+defineEvent('onwritestart');
+
+FileWriter.prototype.abort = function() {
+ this.nativeWriter.abort();
+};
+
+FileWriter.prototype.write = function(text) {
+ var that = this,
+ op = function () {
+ that.nativeWriter.write(new Blob([text]));
+ };
+ this.nativeWriter ? op() : this.pending.push(op);
+
+};
+
+FileWriter.prototype.seek = function(offset) {
+ var that = this,
+ op = function () {
+ that.nativeWriter.seek(offset);
+ };
+ this.nativeWriter ? op() : this.pending.push(op);
+};
+
+FileWriter.prototype.truncate = function(size) {
+ var that = this,
+ op = function () {
+ that.nativeWriter.truncate(size);
+ };
+ this.nativeWriter ? op() : this.pending.push(op);
+};
+
+module.exports = FileWriter;
+
+});
+
+// file: lib/common/plugin/Flags.js
+define("cordova/plugin/Flags", function(require, exports, module) {
+
+/**
+ * Supplies arguments to methods that lookup or create files and directories.
+ *
+ * @param create
+ * {boolean} file or directory if it doesn't exist
+ * @param exclusive
+ * {boolean} used with create; if true the command will fail if
+ * target path exists
+ */
+function Flags(create, exclusive) {
+ this.create = create || false;
+ this.exclusive = exclusive || false;
+}
+
+module.exports = Flags;
+
+});
+
+// file: lib/common/plugin/GlobalizationError.js
+define("cordova/plugin/GlobalizationError", function(require, exports, module) {
+
+
+/**
+ * Globalization error object
+ *
+ * @constructor
+ * @param code
+ * @param message
+ */
+var GlobalizationError = function(code, message) {
+ this.code = code || null;
+ this.message = message || '';
+};
+
+// Globalization error codes
+GlobalizationError.UNKNOWN_ERROR = 0;
+GlobalizationError.FORMATTING_ERROR = 1;
+GlobalizationError.PARSING_ERROR = 2;
+GlobalizationError.PATTERN_ERROR = 3;
+
+module.exports = GlobalizationError;
+
+});
+
+// file: lib/common/plugin/InAppBrowser.js
+define("cordova/plugin/InAppBrowser", function(require, exports, module) {
+
+var exec = require('cordova/exec');
+var channel = require('cordova/channel');
+var modulemapper = require('cordova/modulemapper');
+
+function InAppBrowser() {
+ this.channels = {
+ 'loadstart': channel.create('loadstart'),
+ 'loadstop' : channel.create('loadstop'),
+ 'loaderror' : channel.create('loaderror'),
+ 'exit' : channel.create('exit')
+ };
+}
+
+InAppBrowser.prototype = {
+ _eventHandler: function (event) {
+ if (event.type in this.channels) {
+ this.channels[event.type].fire(event);
+ }
+ },
+ close: function (eventname) {
+ exec(null, null, "InAppBrowser", "close", []);
+ },
+ addEventListener: function (eventname,f) {
+ if (eventname in this.channels) {
+ this.channels[eventname].subscribe(f);
+ }
+ },
+ removeEventListener: function(eventname, f) {
+ if (eventname in this.channels) {
+ this.channels[eventname].unsubscribe(f);
+ }
+ },
+
+ executeScript: function(injectDetails, cb) {
+ if (injectDetails.code) {
+ exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
+ } else if (injectDetails.file) {
+ exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
+ } else {
+ throw new Error('executeScript requires exactly one of code or file to be specified');
+ }
+ },
+
+ insertCSS: function(injectDetails, cb) {
+ if (injectDetails.code) {
+ exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
+ } else if (injectDetails.file) {
+ exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
+ } else {
+ throw new Error('insertCSS requires exactly one of code or file to be specified');
+ }
+ }
+};
+
+module.exports = function(strUrl, strWindowName, strWindowFeatures) {
+ var iab = new InAppBrowser();
+ var cb = function(eventname) {
+ iab._eventHandler(eventname);
+ };
+
+ // Don't catch calls that write to existing frames (e.g. named iframes).
+ if (window.frames && window.frames[strWindowName]) {
+ var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
+ return origOpenFunc.apply(window, arguments);
+ }
+
+ exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
+ return iab;
+};
+
+
+});
+
+// file: lib/common/plugin/LocalFileSystem.js
+define("cordova/plugin/LocalFileSystem", function(require, exports, module) {
+
+var exec = require('cordova/exec');
+
+/**
+ * Represents a local file system.
+ */
+var LocalFileSystem = function() {
+
+};
+
+LocalFileSystem.TEMPORARY = 0; //temporary, with no guarantee of persistence
+LocalFileSystem.PERSISTENT = 1; //persistent
+
+module.exports = LocalFileSystem;
+
+});
+
+// file: lib/common/plugin/Media.js
+define("cordova/plugin/Media", function(require, exports, module) {
+
+var argscheck = require('cordova/argscheck'),
+ utils = require('cordova/utils'),
+ exec = require('cordova/exec');
+
+var mediaObjects = {};
+
+/**
+ * This class provides access to the device media, interfaces to both sound and video
+ *
+ * @constructor
+ * @param src The file name or url to play
+ * @param successCallback The callback to be called when the file is done playing or recording.
+ * successCallback()
+ * @param errorCallback The callback to be called if there is an error.
+ * errorCallback(int errorCode) - OPTIONAL
+ * @param statusCallback The callback to be called when media status has changed.
+ * statusCallback(int statusCode) - OPTIONAL
+ */
+var Media = function(src, successCallback, errorCallback, statusCallback) {
+ argscheck.checkArgs('SFFF', 'Media', arguments);
+ this.id = utils.createUUID();
+ mediaObjects[this.id] = this;
+ this.src = src;
+ this.successCallback = successCallback;
+ this.errorCallback = errorCallback;
+ this.statusCallback = statusCallback;
+ this._duration = -1;
+ this._position = -1;
+ exec(null, this.errorCallback, "Media", "create", [this.id, this.src]);
+};
+
+// Media messages
+Media.MEDIA_STATE = 1;
+Media.MEDIA_DURATION = 2;
+Media.MEDIA_POSITION = 3;
+Media.MEDIA_ERROR = 9;
+
+// Media states
+Media.MEDIA_NONE = 0;
+Media.MEDIA_STARTING = 1;
+Media.MEDIA_RUNNING = 2;
+Media.MEDIA_PAUSED = 3;
+Media.MEDIA_STOPPED = 4;
+Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"];
+
+// "static" function to return existing objs.
+Media.get = function(id) {
+ return mediaObjects[id];
+};
+
+/**
+ * Start or resume playing audio file.
+ */
+Media.prototype.play = function(options) {
+ exec(null, null, "Media", "startPlayingAudio", [this.id, this.src, options]);
+};
+
+/**
+ * Stop playing audio file.
+ */
+Media.prototype.stop = function() {
+ var me = this;
+ exec(function() {
+ me._position = 0;
+ }, this.errorCallback, "Media", "stopPlayingAudio", [this.id]);
+};
+
+/**
+ * Seek or jump to a new time in the track..
+ */
+Media.prototype.seekTo = function(milliseconds) {
+ var me = this;
+ exec(function(p) {
+ me._position = p;
+ }, this.errorCallback, "Media", "seekToAudio", [this.id, milliseconds]);
+};
+
+/**
+ * Pause playing audio file.
+ */
+Media.prototype.pause = function() {
+ exec(null, this.errorCallback, "Media", "pausePlayingAudio", [this.id]);
+};
+
+/**
+ * Get duration of an audio file.
+ * The duration is only set for audio that is playing, paused or stopped.
+ *
+ * @return duration or -1 if not known.
+ */
+Media.prototype.getDuration = function() {
+ return this._duration;
+};
+
+/**
+ * Get position of audio.
+ */
+Media.prototype.getCurrentPosition = function(success, fail) {
+ var me = this;
+ exec(function(p) {
+ me._position = p;
+ success(p);
+ }, fail, "Media", "getCurrentPositionAudio", [this.id]);
+};
+
+/**
+ * Start recording audio file.
+ */
+Media.prototype.startRecord = function() {
+ exec(null, this.errorCallback, "Media", "startRecordingAudio", [this.id, this.src]);
+};
+
+/**
+ * Stop recording audio file.
+ */
+Media.prototype.stopRecord = function() {
+ exec(null, this.errorCallback, "Media", "stopRecordingAudio", [this.id]);
+};
+
+/**
+ * Release the resources.
+ */
+Media.prototype.release = function() {
+ exec(null, this.errorCallback, "Media", "release", [this.id]);
+};
+
+/**
+ * Adjust the volume.
+ */
+Media.prototype.setVolume = function(volume) {
+ exec(null, null, "Media", "setVolume", [this.id, volume]);
+};
+
+/**
+ * Audio has status update.
+ * PRIVATE
+ *
+ * @param id The media object id (string)
+ * @param msgType The 'type' of update this is
+ * @param value Use of value is determined by the msgType
+ */
+Media.onStatus = function(id, msgType, value) {
+
+ var media = mediaObjects[id];
+
+ if(media) {
+ switch(msgType) {
+ case Media.MEDIA_STATE :
+ media.statusCallback && media.statusCallback(value);
+ if(value == Media.MEDIA_STOPPED) {
+ media.successCallback && media.successCallback();
+ }
+ break;
+ case Media.MEDIA_DURATION :
+ media._duration = value;
+ break;
+ case Media.MEDIA_ERROR :
+ media.errorCallback && media.errorCallback(value);
+ break;
+ case Media.MEDIA_POSITION :
+ media._position = Number(value);
+ break;
+ default :
+ console.error && console.error("Unhandled Media.onStatus :: " + msgType);
+ break;
+ }
+ }
+ else {
+ console.error && console.error("Received Media.onStatus callback for unknown media :: " + id);
+ }
+
+};
+
+module.exports = Media;
+
+});
+
+// file: lib/common/plugin/MediaError.js
+define("cordova/plugin/MediaError", function(require, exports, module) {
+
+/**
+ * This class contains information about any Media errors.
+*/
+/*
+ According to :: http://dev.w3.org/html5/spec-author-view/video.html#mediaerror
+ We should never be creating these objects, we should just implement the interface
+ which has 1 property for an instance, 'code'
+
+ instead of doing :
+ errorCallbackFunction( new MediaError(3,'msg') );
+we should simply use a literal :
+ errorCallbackFunction( {'code':3} );
+ */
+
+ var _MediaError = window.MediaError;
+
+
+if(!_MediaError) {
+ window.MediaError = _MediaError = function(code, msg) {
+ this.code = (typeof code != 'undefined') ? code : null;
+ this.message = msg || ""; // message is NON-standard! do not use!
+ };
+}
+
+_MediaError.MEDIA_ERR_NONE_ACTIVE = _MediaError.MEDIA_ERR_NONE_ACTIVE || 0;
+_MediaError.MEDIA_ERR_ABORTED = _MediaError.MEDIA_ERR_ABORTED || 1;
+_MediaError.MEDIA_ERR_NETWORK = _MediaError.MEDIA_ERR_NETWORK || 2;
+_MediaError.MEDIA_ERR_DECODE = _MediaError.MEDIA_ERR_DECODE || 3;
+_MediaError.MEDIA_ERR_NONE_SUPPORTED = _MediaError.MEDIA_ERR_NONE_SUPPORTED || 4;
+// TODO: MediaError.MEDIA_ERR_NONE_SUPPORTED is legacy, the W3 spec now defines it as below.
+// as defined by http://dev.w3.org/html5/spec-author-view/video.html#error-codes
+_MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = _MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED || 4;
+
+module.exports = _MediaError;
+
+});
+
+// file: lib/common/plugin/MediaFile.js
+define("cordova/plugin/MediaFile", function(require, exports, module) {
+
+var utils = require('cordova/utils'),
+ exec = require('cordova/exec'),
+ File = require('cordova/plugin/File'),
+ CaptureError = require('cordova/plugin/CaptureError');
+/**
+ * Represents a single file.
+ *
+ * name {DOMString} name of the file, without path information
+ * fullPath {DOMString} the full path of the file, including the name
+ * type {DOMString} mime type
+ * lastModifiedDate {Date} last modified date
+ * size {Number} size of the file in bytes
+ */
+var MediaFile = function(name, fullPath, type, lastModifiedDate, size){
+ MediaFile.__super__.constructor.apply(this, arguments);
+};
+
+utils.extend(MediaFile, File);
+
+/**
+ * Request capture format data for a specific file and type
+ *
+ * @param {Function} successCB
+ * @param {Function} errorCB
+ */
+MediaFile.prototype.getFormatData = function(successCallback, errorCallback) {
+ if (typeof this.fullPath === "undefined" || this.fullPath === null) {
+ errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT));
+ } else {
+ exec(successCallback, errorCallback, "Capture", "getFormatData", [this.fullPath, this.type]);
+ }
+};
+
+module.exports = MediaFile;
+
+});
+
+// file: lib/common/plugin/MediaFileData.js
+define("cordova/plugin/MediaFileData", function(require, exports, module) {
+
+/**
+ * MediaFileData encapsulates format information of a media file.
+ *
+ * @param {DOMString} codecs
+ * @param {long} bitrate
+ * @param {long} height
+ * @param {long} width
+ * @param {float} duration
+ */
+var MediaFileData = function(codecs, bitrate, height, width, duration){
+ this.codecs = codecs || null;
+ this.bitrate = bitrate || 0;
+ this.height = height || 0;
+ this.width = width || 0;
+ this.duration = duration || 0;
+};
+
<TRUNCATED>
[18/38] updated android, ios,
bb libraries to 2.8.x branch. fixed a few assertions with project
changes. removed blackberry support until create script can be finalized.
Posted by fi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONArray.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONArray.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONArray.java
deleted file mode 100644
index 87362c8..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONArray.java
+++ /dev/null
@@ -1,1123 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-import java.io.UnsupportedEncodingException;
-import java.io.Writer;
-import java.util.Vector;
-
-import org.apache.cordova.json4j.internal.JSON4JStringReader;
-import org.apache.cordova.json4j.internal.JSON4JStringWriter;
-import org.apache.cordova.json4j.internal.NumberUtil;
-import org.apache.cordova.json4j.internal.Parser;
-import org.apache.cordova.json4j.internal.Serializer;
-import org.apache.cordova.json4j.internal.SerializerVerbose;
-
-/**
- * Extension of ArrayList that only allows values which are JSON-able.
- * See JSONObject for a list of valid values.
- *
- * Instances of this class are not thread-safe.
- */
-public class JSONArray extends Vector implements JSONArtifact {
-
- /**
- * Serial UID for serialization checking.
- */
- private static final long serialVersionUID = 9076798781015779954L;
-
- /**
- * Create a new instance of this class.
- */
- public JSONArray() {
- super();
- }
-
- /**
- * Create a new instance of this class with the specified initial capacity.
- * @param initialCapacity The initial size to define the array as.
- */
- public JSONArray(int initialCapacity) {
- super(initialCapacity);
- }
-
- /**
- * Create a new instance of this class based off the contents of the passed object array.
- * @param elems The strings to add to a new JSONArray
- * @throws JSONException Thrown when objects in the array are not JSONable.
- */
- public JSONArray(Object[] elems) throws JSONException {
- if(elems != null){
- for(int i = 0; i < elems.length; i++){
- this.add(elems[i]);
- }
- }
- }
-
- /**
- * Create a new instance of this class based off the contents of the passed object array.
- * @param elems The strings to add to a new JSONArray
- * @param includeSuperclass For JavaBeans, include all superclass info.
- * @throws JSONException Thrown when objects in the array are not JSONable.
- */
- public JSONArray(Object[] elems, boolean includeSuperclass) throws JSONException {
- if(elems != null){
- for(int i = 0; i < elems.length; i++){
- this.add(elems[i]);
- }
- }
- }
-
- /**
- * Create a new instance of this class from the provided JSON object string.
- * Note: This is the same as calling new JSONArray(str, false); Parsing in non-strict mode.
- * @param str The JSON array string to parse.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONArray(String str) throws JSONException {
- super();
- JSON4JStringReader reader = new JSON4JStringReader(str);
- (new Parser(reader)).parse(this);
- }
-
- /**
- * Create a new instance of this class from the provided JSON object string.
- * @param str The JSON array string to parse.
- * @param strict Boolean denoting if the JSON should be parsed n strict mode, meaning unquoted strings and comments are not allowed.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONArray(String str, boolean strict) throws JSONException {
- super();
- JSON4JStringReader reader = new JSON4JStringReader(str);
- (new Parser(reader, strict)).parse(this);
- }
-
- /**
- * Create a new instance of this class from the data provided from the reader. The reader content must be a JSON array string.
- * Note: The reader will not be closed, that is left to the caller.
- * Note: This is the same as calling new JSONArray(rdr, false); Parsing in non-strict mode.
- * @param rdr The Reader from which to read the JSON array string to parse.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONArray(Reader rdr) throws JSONException {
- (new Parser(rdr)).parse(this);
- }
-
- /**
- * Create a new instance of this class from the data provided from the reader. The reader content must be a JSON array string.
- * Note: The reader will not be closed, that is left to the caller.
- * @param rdr The Reader from which to read the JSON array string to parse.
- * @param strict Boolean denoting if the JSON should be parsed n strict mode, meaning unquoted strings and comments are not allowed.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONArray(Reader rdr, boolean strict) throws JSONException {
- (new Parser(rdr, strict)).parse(this);
- }
-
- /**
- * Create a new instance of this class from the data provided from the input stream. The stream content must be a JSON array string.
- * Note: The input stream content is assumed to be UTF-8 encoded.
- * Note: The InputStream will not be closed, that is left to the caller.
- * @param is The InputStream from which to read the JSON array string to parse.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONArray(InputStream is) throws JSONException {
- InputStreamReader isr = null;
- if (is != null) {
- try {
- isr = new InputStreamReader(is, "UTF-8");
- } catch (Exception ex) {
- isr = new InputStreamReader(is);
- }
- } else {
- throw new JSONException("Inputstream cannot be null");
- }
- (new Parser(isr)).parse(true, this);
- }
-
- /**
- * Create a new instance of this class from the data provided from the input stream. The stream content must be a JSON array string.
- * Note: The input stream content is assumed to be UTF-8 encoded.
- * Note: The InputStream will not be closed, that is left to the caller.
- * @param is The InputStream from which to read the JSON array string to parse.
- * @param strict Boolean denoting if the JSON should be parsed n strict mode, meaning unquoted strings and comments are not allowed.
- * @throws JSONException Thrown when the string passed is null, or malformed JSON..
- */
- public JSONArray(InputStream is, boolean strict) throws JSONException {
- InputStreamReader isr = null;
- if (is != null) {
- try {
- isr = new InputStreamReader(is, "UTF-8");
- } catch (Exception ex) {
- isr = new InputStreamReader(is);
- }
- } else {
- throw new JSONException("InputStream cannot be null");
- }
- (new Parser(isr, strict)).parse(true, this);
- }
-
- /**
- * Function to get a JSONArray entry at a specified index.
- * @param index The position in the rray to fetch the object from
- * @throws JSONException Thrown if the index is outside the array bounds.
- */
- public Object getIndex(int index) throws JSONException {
- try{
- return super.elementAt(index);
- }catch (Exception ex) {
- JSONException jex = new JSONException("Error occurred trying to access element at: " + index);
- jex.setCause(ex);
- throw jex;
- }
- }
-
- /*
- * (non-Javadoc)
- * @see java.util.ArrayList#add(int, java.lang.Object)
- */
- public void add(int index, Object element) {
- if(index > this.size() - 1){
- expandArray(index);
- }
- if (!JSONObject.isValidObject(element)) {
- throw new IllegalArgumentException("Object of type: [" + element.getClass().getName() + "] could not be converted to a JSON representation.");
- }
- super.insertElementAt(element, index);
- }
-
- /*
- * (non-Javadoc)
- * @see java.util.ArrayList#add(java.lang.Object)
- */
- public boolean add(Object element, boolean includeSuperclass) {
- if (!JSONObject.isValidObject(element)) {
- throw new IllegalArgumentException("Object of type: [" + element.getClass().getName() + "] could not be converted to a JSON representation.");
- }
- super.addElement(element);
- return true;
- }
-
- /*
- * (non-Javadoc)
- * @see java.util.ArrayList#add(java.lang.Object)
- */
- public boolean add(Object element) {
- return this.add(element, true);
- }
-
- /*
- * (non-Javadoc)
- * @see java.util.ArrayList#set(int, java.lang.Object)
- */
- public Object set(int index, Object element) {
- if(index > this.size() - 1){
- expandArray(index);
- }
- if (!JSONObject.isValidObject(element)) {
- throw new IllegalArgumentException("Object of type: [" + element.getClass().getName() + "] could not be converted to a JSON representation.");
- }
- Object obj = super.elementAt(index);
- super.setElementAt(element, index);
- return obj;
- }
-
- /**
- * Internal function to pad-out the array list
- * Added to mimic expansion behavior of other JSON models.
- * @param toIndex Increase the array so that it has up to 'toIndex' as indexable slots.
- */
- private void expandArray(int toIndex){
- int maxIndex = this.size();
- toIndex = toIndex - maxIndex;
- if(toIndex > 0){
- for(int i = 0; i < toIndex; i++){
- super.addElement(null);
- }
- }
- }
-
- /**************************************************************/
- /* Maps of add to put, for API compatibility to other parsers.*/
- /**************************************************************/
-
- /**
- * Map of java.util.ArrayList.add(int, java.lang.Object), for compatibility to other JSON parsers.
- * @see java.util.ArrayList#add(int, java.lang.Object)
- * @throws JSONException in the case of index out of bounds, etc.
- * @return A reference to this array instance.
- */
- public JSONArray put(int index, Object element) throws JSONException {
- if (!JSONObject.isValidObject(element)) {
- throw new IllegalArgumentException("Object of type: [" + element.getClass().getName() + "] could not be converted to a JSON representation.");
- }
- try {
- super.insertElementAt(element, index);
- } catch (Exception ex) {
- JSONException jex = new JSONException("Exception occurred while placing element.");
- jex.setCause(ex);
- throw jex;
- }
- return this;
- }
-
- /**
- * Map of java.util.ArrayList.add(java.lang.Object), for compatibility to other JSON parsers.
- * @see java.util.ArrayList#add(java.lang.Object)
- * @return A reference to this array instance.
- */
- public JSONArray put(Object element) throws JSONException {
- return put(element, true);
- }
-
- /**
- * Map of java.util.ArrayList.add(java.lang.Object), for compatibility to other JSON parsers.
- * @see java.util.ArrayList#add(java.lang.Object)
- * @return A reference to this array instance.
- */
- public JSONArray put(Object element, boolean includeSuperclass) throws JSONException {
- if (!JSONObject.isValidObject(element)) {
- throw new IllegalArgumentException("Object of type: [" + element.getClass().getName() + "] could not be converted to a JSON representation.");
-
- }
- try {
- super.addElement(element);
- } catch (Exception ex) {
- JSONException jex = new JSONException("Exception occurred while placing element.");
- jex.setCause(ex);
- throw jex;
- }
- return this;
- }
-
- /**
- * Method to place a long into the array.
- * @param value A long
- * @return A reference to this array instance.
- */
- public JSONArray put(long value) {
- this.add(new Long(value));
- return this;
- }
-
- /**
- * Method to place a long into the array.
- * @param index The position in the array to place the long.
- * @param value A long
- * @return A reference to this array instance.
- */
- public JSONArray put(int index, long value) {
- this.add(index, new Long(value));
- return this;
- }
-
- /**
- * Method to place a int into the array.
- * @param value An int
- * @return A reference to this array instance.
- */
- public JSONArray put(int value) {
- this.add(new Integer(value));
- return this;
- }
-
- /**
- * Method to place an int into the array.
- * @param index The position in the array to place the int.
- * @param value An int
- * @return A reference to this array instance.
- */
- public JSONArray put(int index, int value) {
- this.add(index, new Integer(value));
- return this;
- }
-
- /**
- * Method to place a short into the array.
- * @param value A short
- * @return A reference to this array instance.
- */
- public JSONArray put(short value) {
- this.add(new Short(value));
- return this;
- }
-
- /**
- * Method to place a short into the array.
- * @param index The position in the array to place the short.
- * @param value A short
- * @return A reference to this array instance.
- */
- public JSONArray put(int index, short value) {
- this.add(index, new Short(value));
- return this;
- }
-
- /**
- * Method to place a double into the array.
- * @param value A double
- * @return A reference to this array instance.
- */
- public JSONArray put(double value) {
- this.add(new Double(value));
- return this;
- }
-
- /**
- * Method to place a double into the array.
- * @param index The position in the array to place the double.
- * @param value A double
- * @return A reference to this array instance.
- */
- public JSONArray put(int index, double value) {
- this.add(index, new Double(value));
- return this;
- }
-
- /**
- * Method to place a int into the array.
- * @param value A boolean
- * @return A reference to this array instance.
- */
- public JSONArray put(boolean value) {
- this.add(new Boolean(value));
- return this;
- }
-
- /**
- * Method to place a boolean into the array.
- * @param index The position in the array to place the int.
- * @param value A boolean
- * @return A reference to this array instance.
- */
- public JSONArray put(int index, boolean value) {
- this.add(index, new Boolean(value));
- return this;
- }
-
- /*****************/
- /* End of mapping*/
- /*****************/
-
- /********************/
- /* Utility functions*/
- /********************/
-
- /**
- * Function to obtain a value at the specified index as a boolean.
- * @param index The index of the item to retrieve.
- * @return boolean value.
- * @throws JSONException if the index is outside the range or if the type at the position was not Boolean or a string of 'true' or 'false'
- */
- public boolean getBoolean(int index) throws JSONException {
- try {
- Object val = this.elementAt(index);
- if (val != null) {
- if (Boolean.class.isAssignableFrom(val.getClass())) {
- return((Boolean)val).booleanValue();
- } else if (NumberUtil.isNumber(val.getClass())) {
- throw new JSONException("Value at index: [" + index + "] was not a boolean or string value of 'true' or 'false'.");
- } else if (String.class.isAssignableFrom(val.getClass())) {
- String str = (String)val;
- if (str.equals("true")) {
- return true;
- } else if (str.equals("false")) {
- return false;
- } else {
- throw new JSONException("Value at index: [" + index + "] was not a boolean or string value of 'true' or 'false'.");
- }
- }
- } else {
- throw new JSONException("Value at index: [" + index + "] was null");
- }
- } catch (java.lang.IndexOutOfBoundsException iobe) {
- JSONException jex = new JSONException("The specified index was outside of the array boundries");
- jex.setCause(iobe);
- throw jex;
- }
- return false;
- }
-
- /**
- * Function to obtain a value at the specified index as a double.
- * @param index The index of the item to retrieve.
- * @return double value.
- * @throws JSONException if the index is outside the range or if the type at the position was not Number.
- */
- public double getDouble(int index) throws JSONException {
- try {
- Object val = this.elementAt(index);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getDouble(val);
- }
- else {
- throw new JSONException("Value at index: [" + index + "] was not a number.");
- }
- } else {
- throw new JSONException("Value at index: [" + index + "] was null");
- }
-
- } catch (java.lang.IndexOutOfBoundsException iobe) {
- JSONException jex = new JSONException("The specified index was outside of the array boundries");
- jex.setCause(iobe);
- throw jex;
- }
- }
-
- /**
- * Function to obtain a value at the specified index as a long.
- * @param index The index of the item to retrieve.
- * @return long value.
- * @throws JSONException if the index is outside the range or if the type at the position was not Number.
- */
- public long getLong(int index) throws JSONException {
- try {
- Object val = this.elementAt(index);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getLong(val);
- } else {
- throw new JSONException("Value at index: [" + index + "] was not a number.");
- }
- } else {
- throw new JSONException("Value at index: [" + index + "] was null");
- }
-
- } catch (java.lang.IndexOutOfBoundsException iobe) {
- JSONException jex = new JSONException("The specified index was outside of the array boundries");
- jex.setCause(iobe);
- throw jex;
- }
- }
-
- /**
- * Function to obtain a value at the specified index as an int.
- * @param index The index of the item to retrieve.
- * @return int value.
- * @throws JSONException if the index is outside the range or if the type at the position was not Number.
- */
- public int getInt(int index) throws JSONException {
- try {
- Object val = this.elementAt(index);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getInt(val);
- }else {
- throw new JSONException("Value at index: [" + index + "] was not a number.");
- }
- } else {
- throw new JSONException("Value at index: [" + index + "] was null");
- }
-
- } catch (java.lang.IndexOutOfBoundsException iobe) {
- JSONException jex = new JSONException("The specified index was outside of the array boundries");
- jex.setCause(iobe);
- throw jex;
- }
- }
-
- /**
- * Function to obtain a value at the specified index as a short.
- * @param index The index of the item to retrieve.
- * @return short value.
- * @throws JSONException if the index is outside the range or if the type at the position was not Number.
- */
- public short getShort(int index) throws JSONException {
- try {
- Object val = this.elementAt(index);
- if (val != null) {
- if (NumberUtil.isNumber(val.getClass())) {
- return NumberUtil.getShort(val);
- }
- else {
- throw new JSONException("Value at index: [" + index + "] was not a number.");
- }
- } else {
- throw new JSONException("Value at index: [" + index + "] was null");
- }
- } catch (java.lang.IndexOutOfBoundsException iobe) {
- JSONException jex = new JSONException("The specified index was outside of the array boundries");
- jex.setCause(iobe);
- throw jex;
- }
- }
-
- /**
- * Function to obtain a value at the specified index as a string.
- * @param index The index of the item to retrieve.
- * @return string value.
- * @throws JSONException if the index is outside the range or if the type at the position was not an object with a toString() function..
- */
- public String getString(int index) throws JSONException {
- try {
- Object val = this.elementAt(index);
- if (val != null) {
- return val.toString();
- } else {
- throw new JSONException("The value at index: [" + index + "] was null.");
- }
- } catch (java.lang.IndexOutOfBoundsException iobe) {
- JSONException jex = new JSONException("The specified index was outside of the array boundries");
- jex.setCause(iobe);
- throw jex;
- }
- }
-
- /**
- * Utility method to obtain the specified key as a JSONObject
- * Only values that are instances of JSONObject will be returned. A null will generate an exception.
- * @param index The index to look up.
- * throws JSONException Thrown when the type returned by get(key) is not a JSONObject instance.
- * @return A JSONObject value if the value stored for key is an instance or subclass of JSONObject.
- */
- public JSONObject getJSONObject(int index) throws JSONException {
- try {
- Object val = this.elementAt(index);
- if (val != null) {
- if (JSONObject.class.isAssignableFrom(val.getClass())) {
- return(JSONObject)val;
- } else {
- throw new JSONException("The value for index: [" + index + "] was not a JSONObject");
- }
- } else {
- throw new JSONException("The value for index: [" + index + "] was null. Object required.");
- }
- } catch (java.lang.IndexOutOfBoundsException iobe) {
- JSONException jex = new JSONException("The specified index was outside of the array boundries");
- jex.setCause(iobe);
- throw jex;
- }
- }
-
- /**
- * Utility method to obtain the specified index as a JSONArray
- * Only values that are instances of JSONArray will be returned. A null will generate an exception.
- * @param index The index to look up.
- * throws JSONException Thrown when the type returned by get(key) is not a Long instance, or cannot be converted to a long..
- * @return A JSONArray value if the value stored for key is an instance or subclass of JSONArray.
- */
- public JSONArray getJSONArray(int index) throws JSONException {
- try {
- Object val = this.elementAt(index);
- if (val != null) {
- if (JSONArray.class.isAssignableFrom(val.getClass())) {
- return(JSONArray)val;
- } else {
- throw new JSONException("The value index key: [" + index + "] was not a JSONObject");
- }
- } else {
- throw new JSONException("The value for index: [" + index + "] was null. Object required.");
- }
- } catch (java.lang.IndexOutOfBoundsException iobe) {
- JSONException jex = new JSONException("The specified index was outside of the array boundries");
- jex.setCause(iobe);
- throw jex;
- }
- }
-
- /**
- * Utility function for testing if an element at index 'idx' is null or not.
- * @return boolean indicating if an index is null or not. Will also return true for indexes outside the size of the array.
- */
- public boolean isNull(int index) {
- try {
- Object obj = this.elementAt(index);
- return JSONObject.NULL.equals(obj);
- } catch (java.lang.IndexOutOfBoundsException iobe) {
- return true;
- }
- }
-
- /**
- * Utility function that maps ArrayList.size() to length, for compatibility to other JSON parsers.
- * @return The number of elements in this JSONArray.
- */
- public int length() {
- return this.size();
- }
-
- /***************************/
- /* End of Utility functions*/
- /***************************/
-
- /**
- * Convert this object into a stream of JSON text. Same as calling write(os,false);
- * @param os The output stream to write data to.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public OutputStream write(OutputStream os) throws JSONException {
- write(os,false);
- return os;
- }
-
- /**
- * Convert this object into a stream of JSON text. Same as calling write(writer,false);
- * @param os The output stream to write data to. Output stream characters will be serialized as UTF-8.
- * @param verbose Whether or not to write the JSON text in a verbose format.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public OutputStream write(OutputStream os, boolean verbose) throws JSONException {
- Writer writer = null;
- try {
- //MSN reimplement BUFFERED
- writer = new OutputStreamWriter(os, "UTF-8");
- } catch (UnsupportedEncodingException uex) {
- JSONException jex = new JSONException(uex.toString());
- jex.setCause(uex);
- throw jex;
- }
- write(writer, verbose);
- return os;
- }
-
- /**
- * Convert this object into a String of JSON text, specifying how many spaces should
- * be used for each indent level. Output stream characters will be serialized as UTF-8.
- * @param indentDepth How many spaces to use for each indent level. Should be one to eight.
- * Less than one means no intending, greater than 8 and it will just use tab.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public OutputStream write(OutputStream os, int indentDepth) throws JSONException {
- Writer writer = null;
- try {
- //MSN reimplement BUFFERED
- writer = new OutputStreamWriter(os, "UTF-8");
- } catch (UnsupportedEncodingException uex) {
- JSONException jex = new JSONException(uex.toString());
- jex.setCause(uex);
- throw jex;
- }
- write(writer, indentDepth);
- return os;
- }
-
- /**
- * Convert this object into a stream of JSON text. Same as calling write(writer,false);
- * @param writer The writer which to write the JSON text to.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public Writer write(Writer writer) throws JSONException {
- write(writer, false);
- return writer;
- }
-
- /**
- * Convert this object into a stream of JSON text, specifying verbosity.
- * @param writer The writer which to write the JSON text to.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public Writer write(Writer writer, boolean verbose) throws JSONException {
- Serializer serializer;
-
- //Try to avoid double-buffering or buffering in-memory
- //writers.
- //Class writerClass = writer.getClass();
- boolean flushIt = false;
-
- //MSN reimplement BUFFERED
- /*if (!StringWriter.class.isAssignableFrom(writerClass) &&
- !CharArrayWriter.class.isAssignableFrom(writerClass) &&
- !BufferedWriter.class.isAssignableFrom(writerClass)) {
- writer = new BufferedWriter(writer);
- flushIt = true;
- } */
-
- if (verbose) {
- serializer = new SerializerVerbose(writer);
- } else {
- serializer = new Serializer(writer);
- }
-
- try {
- serializer.writeArray(this);
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- if (flushIt) {
- try {
- writer.flush();
- } catch (Exception ex) {
- JSONException jex = new JSONException("Error during buffer flush");
- jex.setCause(ex);
- throw jex;
- }
- }
- return writer;
- }
-
- /**
- * Convert this array into a stream of JSON text, specifying verbosity.
- * @param writer The writer which to write the JSON text to.
- * @param indentDepth How many spaces to use for each indent level. Should be one to eight.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public Writer write(Writer writer, int indentDepth) throws JSONException {
- Serializer serializer;
-
- if (indentDepth < 1) {
- indentDepth = 0;
- } else if (indentDepth > 8) {
- indentDepth = 9;
- }
-
- //Try to avoid double-buffering or buffering in-memory
- //writers.
- //MSN reimplement BUFFERED
-// Class writerClass = writer.getClass();
-// if (!StringWriter.class.isAssignableFrom(writerClass) &&
-// !CharArrayWriter.class.isAssignableFrom(writerClass) &&
-// !BufferedWriter.class.isAssignableFrom(writerClass)) {
-// writer = new BufferedWriter(writer);
-// }
-
- if (indentDepth > 0) {
- serializer = new SerializerVerbose(writer, indentDepth);
- } else {
- serializer = new Serializer(writer);
- }
- try {
- serializer.writeArray(this);
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- return writer;
- }
-
- /**
- * Convert this object into a String of JSON text, specifying verbosity.
- * @param verbose Whether or not to write in compressed for formatted Strings.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public String write(boolean verbose) throws JSONException {
- Serializer serializer;
- JSON4JStringWriter writer = new JSON4JStringWriter();
-
- if (verbose) {
- serializer = new SerializerVerbose(writer);
- } else {
- serializer = new Serializer(writer);
- }
- try {
- serializer.writeArray(this).flush();
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- return writer.toString();
- }
-
- /**
- * Convert this array into a String of JSON text, specifying verbosity.
- * @param indentDepth How many spaces to use for each indent level. Should be one to eight.
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public String write(int indentDepth) throws JSONException {
- Serializer serializer;
- JSON4JStringWriter writer = new JSON4JStringWriter();
-
- if (indentDepth < 1) {
- indentDepth = 0;
- } else if (indentDepth > 8) {
- indentDepth = 9;
- }
-
- if (indentDepth > 0) {
- serializer = new SerializerVerbose(writer, indentDepth);
- } else {
- serializer = new Serializer(writer);
- }
- try {
- serializer.writeArray(this).flush();
- } catch (IOException iox) {
- JSONException jex = new JSONException("Error occurred during input read.");
- jex.setCause(iox);
- throw jex;
- }
- return writer.toString();
- }
-
- /**
- * Convert this object into a String of JSON text. Same as write(false);
- *
- * @throws JSONException Thrown on IO errors during serialization.
- */
- public String write() throws JSONException {
- return write(false);
- }
-
- /**
- * Over-ridden toString() method. Returns the same value as write(), which is a compact JSON String.
- * If an error occurs in the serialization, the return will be of format: JSON Generation Error: [<some error>]
- */
- public String toString() {
- String str = null;
- try {
- str = write(false);
- } catch (JSONException jex) {
- str = "JSON Generation Error: [" + jex.toString() + "]";
- }
- return str;
- }
-
- /**
- * Function to return a string of JSON text with specified indention. Returns the same value as write(indentDepth).
- * If an error occurs in the serialization, the return will be of format: JSON Generation Error: [<some error>]
- * @throws JSONException Thrown if an error occurs during JSON generation.
- */
- public String toString(int indentDepth) throws JSONException {
- return write(indentDepth);
- }
-
- /**
- * Method to mimic the behavior of the JavaScript array join function
- * @param str The string delimiter to place between joined array elements in the output string.
- * @return A string of all the elements joined together.
- */
- public String join(String str) {
- if (str == null) {
- str = "";
- }
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < this.size(); i++) {
- if (i > 0) {
- buf.append(str);
- }
- Object obj = this.elementAt(i);
- if (obj == null) {
- buf.append("null");
- } else {
- buf.append(obj.toString());
- }
- }
- return buf.toString();
- }
-
- /**
- * Methods added for compatibility to other models.
- */
-
- /**
- * Method to get the object at that position, or null if outside the array range.
- * @param index the array index to get
- * @return - value or null
- */
- public Object opt(int index) {
- try{
- return elementAt(index);
- } catch (Throwable th){
- return null;
- }
- }
-
- /**
- * Method to get the object at that position, or null if outside the array range.
- * @param index the array index to get
- * @param defaultValue the value to return if index is outside the array.
- * @return - value or defaultValue
- */
- public Object opt(int index, Object defaultValue) {
- try{
- return elementAt(index);
- } catch (Throwable th){
- return defaultValue;
- }
- }
-
- /**
- * Method to obtain the value at index as an boolean, or 'false' if outside the array.
- * @param index the array index to get
- * @return - value or false
- */
- public boolean optBoolean(int index) {
- try{
- return getBoolean(index);
- } catch (Throwable th){
- return false;
- }
- }
-
- /**
- * Method to obtain the value at index as an boolean, or 'defaultValue' if outside the array.
- * @param index The array index to get.
- * @param defaultValue the value to return if index is outside the array.
- * @return - value or false
- */
- public boolean optBoolean(int index, boolean defaultValue) {
- try{
- return getBoolean(index);
- } catch (Throwable th){
- return defaultValue;
- }
- }
-
- /**
- * Method to obtain the value at index as an int, or '0' if outside the array.
- * @param index the array index to get
- * @return - value or 0
- */
- public int optInt(int index) {
- try{
- return getInt(index);
- } catch (Throwable th){
- return 0;
- }
- }
-
- /**
- * Method to obtain the value at index as an int, or defaultValue if outside the array.
- * @param index the array index to get
- * @param defaultValue the value to return if index is outside the array.
- * @return - value or 0
- */
- public int optInt(int index, int defaultValue) {
- try{
- return getInt(index);
- } catch (Throwable th){
- return defaultValue;
- }
- }
-
- /**
- * Method to obtain the value at index as a long, or '0' if outside the array.
- * @param index the array index to get
- * @return - value or 0
- */
- public long optLong(int index) {
- try{
- return getLong(index);
- } catch (Throwable th){
- return (long)0;
- }
- }
-
- /**
- * Method to obtain the value at index as a long, or defaultValue if outside the array.
- * @param index the array index to get
- * @param defaultValue the value to return if index is outside the array.
- v* @return - value or defaultValue
- */
- public long optLong(int index, long defaultValue) {
- try{
- return getLong(index);
- } catch (Throwable th){
- return defaultValue;
- }
- }
-
- /**
- * Method to obtain the value at index as a short, or '0' if outside the array.
- * @param index the array index to get
- * @return - value or 0
- */
- public short optShort(int index) {
- try{
- return getShort(index);
- } catch (Throwable th){
- return (short)0;
- }
- }
-
- /**
- * Method to obtain the value at index as a short, or '0' if outside the array.
- * @param index the array index to get
- * @param defaultValue the value to return if index is outside the array.
- * @return - value or defaultValue
- */
- public short optShort(int index, short defaultValue) {
- try{
- return getShort(index);
- } catch (Throwable th){
- return defaultValue;
- }
- }
-
- /**
- * Method to obtain the value at index as a double, or Double.NaN if outside the array.
- * @param index the array index to get
- * @return - value or Double.NaN
- */
- public double optDouble(int index) {
- try{
- return getDouble(index);
- } catch (Throwable th){
- return Double.NaN;
- }
- }
-
- /**
- * Method to obtain the value at index as a double, or Double.NaN if outside the array.
- * @param index the array index to get
- * @param defaultValue the value to return if index is outside the array.
- * @return - value or defaultValue
- */
- public double optDouble(int index, double defaultValue) {
- try{
- return getDouble(index);
- } catch (Throwable th){
- return Double.NaN;
- }
- }
-
- /**
- * Method to obtain the value at index as a String, or null if outside the array.
- * @param index the array index to get
- * @return - value or null
- */
- public String optString(int index) {
- try{
- return getString(index);
- } catch (Exception th){
- return null;
- }
- }
-
- /**
- * Method to obtain the value at index as a String, or defaultValue if outside the array.
- * @param index the array index to get
- * @param defaultValue the value to return if index is outside the array.
- * @return - value or defaultValue
- */
- public String optString(int index, String defaultValue) {
- try{
- return getString(index);
- } catch (Throwable th){
- return defaultValue;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONArtifact.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONArtifact.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONArtifact.java
deleted file mode 100644
index 4e8ff0c..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONArtifact.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j;
-
-import java.io.OutputStream;
-import java.io.Writer;
-
-/**
- * Interface class to define a set of generic APIs both JSONObject and JSONArray implement.
- * This is namely so that functions such as write, which are common between the two, can be easily
- * invoked without knowing the object type.
- */
-public interface JSONArtifact
-{
- /**
- * Write this object to the stream as JSON text in UTF-8 encoding. Same as calling write(os,false);
- * Note that encoding is always written as UTF-8, as per JSON spec.
- * @param os The output stream to write data to.
- * @return The passed in OutputStream.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public OutputStream write(OutputStream os) throws JSONException;
-
- /**
- * Write this object to the stream as JSON text in UTF-8 encoding, specifying whether to use verbose (tab-indented) output or not.
- * Note that encoding is always written as UTF-8, as per JSON spec.
- * @param os The output stream to write data to.
- * @param verbose Whether or not to write the JSON text in a verbose format. If true, will indent via tab.
- * @return The passed in OutputStream.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public OutputStream write(OutputStream os, boolean verbose) throws JSONException;
-
- /**
- * Write this object to the stream as JSON text in UTF-8 encoding, specifying how many spaces should be used for each indent.
- * This is an alternate indent style to using tabs.
- * @param indentDepth How many spaces to use for each indent. The value should be between one to eight.
- * Less than one means no indenting, greater than 8 and it will just use tab.
- * @return The passed in OutputStream.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public OutputStream write(OutputStream os, int indentDepth) throws JSONException;
-
- /**
- * Write this object to the writer as JSON text. Same as calling write(writer,false);
- * @param writer The writer which to write the JSON text to.
- * @return The passed in writer.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public Writer write(Writer writer) throws JSONException;
-
- /**
- * Writer this object to the writer as JSON text, specifying whether to use verbose (tab-indented) output or not.
- * be used for each indent. This is an alternate indent style to using tabs.
- * @param writer The writer which to write the JSON text to.
- * @return The passed in writer.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public Writer write(Writer writer, boolean verbose) throws JSONException;
-
- /**
- * Write this object to the writer as JSON text, specifying how many spaces should be used for each indent.
- * This is an alternate indent style to using tabs.
- * @param writer The writer which to write the JSON text to.
- * @param indentDepth How many spaces to use for each indent. The value should be between one to eight.
- * @return The passed in writer.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public Writer write(Writer writer, int indentDepth) throws JSONException;
-
- /**
- * Convert this object into a String of JSON text, specifying whether to use verbose (tab-indented) output or not.
- * @param verbose Whether or not to write in compressed format.
- * Less than one means no indenting, greater than 8 and it will just use tab.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public String write(boolean verbose) throws JSONException;
-
- /**
- * Convert this object into a String of JSON text, specifying how many spaces should be used for each indent.
- * This is an alternate indent style to using tabs.
- * @param indentDepth How many spaces to use for each indent. The value should be between one to eight.
- * Less than one means no indenting, greater than 8 and it will just use tab.
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public String write(int indentDepth) throws JSONException;
-
- /**
- * Convert this object into a String of JSON text. Same as write(false);
- *
- * @throws JSONException Thrown on errors during serialization.
- */
- public String write() throws JSONException;
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/88ad654c/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONException.java
----------------------------------------------------------------------
diff --git a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONException.java b/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONException.java
deleted file mode 100644
index d79f419..0000000
--- a/lib/cordova-blackberry/framework/ext/src/org/apache/cordova/json4j/JSONException.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cordova.json4j;
-
-/**
- * Class that implements an exception type thrown by all JSON classes
- * as a common exception when JSON handling errors occur.
- */
-public class JSONException extends Exception {
-
- private Throwable cause;
-
- /**
- * Constructor for JSON Exception
- * @param message The error that generated the exception.
- */
- public JSONException(String message) {
- super(message);
- }
-
- /**
- * Constructor for JSON Exception
- * @param t The exception that generated this exception.
- */
- public JSONException(Throwable t) {
- cause = t;
- }
-
- public void setCause(Throwable t) {
- cause = t;
- }
-
- /**
- * Method to get the underlying cause of the JSONException
- */
- public Throwable getCause() {
- return cause;
- }
-}