*
*/
public abstract class Browser {
-
+
/**
* @return true if ie6
*/
* @return true if webkit
*/
public final boolean webkit = isWebkit();
-
+
protected abstract boolean isIe6();
protected abstract boolean isIe8();
protected abstract boolean isIe9();
*/
package com.google.gwt.query.client;
-
/**
* This interface represents the Window.console object.
*/
private Event event = null;
private int index = -1;
protected Object[] arguments = new Object[0];
-
+
/**
* Utility method to get a string representation with the content
* of the arguments array. It recursively visits arrays and inspect
protected String dumpArguments() {
return dumpArguments(arguments, "\n");
}
-
+
private String dumpArguments(Object[] arguments, String sep) {
StringBuilder b = new StringBuilder();
for (int i = 0, l = arguments.length; i < l; i++ ) {
index = i;
return this;
}
-
+
/**
* @deprecated use getArguments instead.
*/
public Object[] getArguments() {
return arguments;
}
-
+
/**
* Set the list of arguments to be passed to the function
*/
public <T extends JavaScriptObject> T getArgumentJSO(int argIdx, int pos) {
return (T)getArgument(argIdx, pos, JavaScriptObject.class);
}
-
+
/**
* Utility method for safety getting a JavaScriptObject present at a certain
* position in the list of arguments.
public <T extends JavaScriptObject> T getArgumentJSO(int idx) {
return getArgumentJSO(-1, idx);
}
-
+
/**
* Utility method for safety getting an array present at a certain
* position in the list of arguments.
public <T> T arguments(int idx) {
return getArgument(idx);
}
-
+
/**
* Convenience alias for the getArguments(argIdx, pos) method;
*/
public <T> T arguments(int argIdx, int pos) {
return getArgument(argIdx, pos);
}
-
+
/**
* Safety return the argument in the position idx.
*
public <T> T getArgument(int argIdx, int pos) {
return getArgument(argIdx, pos, null);
}
-
+
/**
* Safety return the argument in the position idx.
*
return null;
}
-
/**
* @deprecated use: getArgument()
*/
public void setData(double b) {
setArguments(b);
}
-
+
/**
* @deprecated use use setArguments instead
*/
}
}
-
/**
* Return a lazy version of the GQuery interface. Lazy function calls are simply queued up and not
* executed immediately.
*
* NOTE: The ability of animating attribute values is only available in gquery but not jquery
*
- *
* Example:
*
* <pre class="code">
*
* NOTE: The ability of animating attribute values is only available in gquery but not jquery
*
- *
* Example:
*
* <pre class="code">
*
* NOTE: The ability of animating attribute values is only available in gquery but not jquery
*
- *
* Example:
*
* <pre class="code">
* });
* </pre>
*
- *
* For color css properties, values can be specified via hexadecimal or rgb or literal values.
*
* Example:
* $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)', 1000");
* </pre>
*
- *
* @param prop the property to animate : "cssName:'value'"
* @param funcs an array of {@link Function} called once the animation is complete
* @param duration the duration in milliseconds of the animation
* The event handlers are passed as Functions that you can use to prevent default behavior. To
* stop both default action and event bubbling, the function event handler has to return false.
*
- *
*/
public GQuery bind(int eventbits, final Function... funcs) {
return as(Events).bind(eventbits, null, funcs);
* The event handlers are passed as Functions that you can use to prevent default behavior. To
* stop both default action and event bubbling, the function event handler has to return false.
*
- *
*/
public GQuery bind(String eventType, final Function... funcs) {
return as(Events).bind(eventType, null, funcs);
* property defined in {@link CSS} class and call the {@link TakesCssValue#with(HasCssName)}
* method on it.
*
- *
* ex :
*
* <pre class="code">
* Attach a handler for this event to all elements which match the current selector, now and in
* the future.
* <p>
- * <p>
* Ex :
*
* <pre>
* Attach a handler for this event to all elements which match the current selector, now and in
* the future. The <code>data</code> parameter allows us to pass data to the handler.
* <p>
- * <p>
* Ex :
*
* <pre>
return as(Events).trigger(eventbits, keys);
}
-
/**
* Trigger a event in all matched elements.
*
import com.google.gwt.query.client.builders.JsonBuilder;
-
/**
* Interface using for Data Binders valid for JVM and JS.
*/
* and a Json implementation in the JVM.
*/
<T> T getDataImpl();
-
+
/**
* Return the Object with the given key.
*/
<T> T get(Object key);
-
+
/**
* Set an Object with the given key.
*/
* Example {"user":{"name":"manolo","surname":"carrasco"}}
*/
String toJsonWithName();
-
+
/**
* return a string which represents the object in a queryString format.
*/
* return the name for this type
*/
String getJsonName();
-
-
+
/**
* converts a JsonBuilder instance into another JsonBuilder type but
* preserving the underlying data object.
*
* NOTE: The ability of animating attribute values is only available in gquery but not jquery
*
- *
* Example:
*
* <pre class="code">
*
* NOTE: The ability of animating attribute values is only available in gquery but not jquery
*
- *
* Example:
*
* <pre class="code">
*
* NOTE: The ability of animating attribute values is only available in gquery but not jquery
*
- *
* Example:
*
* <pre class="code">
* });
* </pre>
*
- *
* For color css properties, values can be specified via hexadecimal or rgb or literal values.
*
* Example:
* $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)', 1000");
* </pre>
*
- *
* @param prop the property to animate : "cssName:'value'"
* @param funcs an array of {@link Function} called once the animation is complete
* @param duration the duration in milliseconds of the animation
* The event handlers are passed as Functions that you can use to prevent default behavior. To
* stop both default action and event bubbling, the function event handler has to return false.
*
- *
*/
LazyGQuery<T> bind(int eventbits, Function... funcs);
* The event handlers are passed as Functions that you can use to prevent default behavior. To
* stop both default action and event bubbling, the function event handler has to return false.
*
- *
*/
LazyGQuery<T> bind(String eventType, Function... funcs);
* property defined in {@link CSS} class and call the {@link TakesCssValue#with(HasCssName)}
* method on it.
*
- *
* ex :
*
* <pre class="code">
* Attach a handler for this event to all elements which match the current selector, now and in
* the future.
* <p>
- * <p>
* Ex :
*
* <pre>
* Attach a handler for this event to all elements which match the current selector, now and in
* the future. The <code>data</code> parameter allows us to pass data to the handler.
* <p>
- * <p>
* Ex :
*
* <pre>
* Definition of jquery Promise interface used in gquery.
*/
public interface Promise {
-
+
/**
* Definition of jquery Deferred interface used in gquery.
*/
* Call the progressCallbacks on a Deferred object with the given args.
*/
Deferred notify(Object... o);
-
+
/**
* Return a Deferred’s Promise object.
*/
Promise promise();
-
+
/**
* Reject a Deferred object and call any failCallbacks with the given args.
*/
Deferred reject(Object... o);
-
+
/**
* Resolve a Deferred object and call any doneCallbacks with the given args.
*/
* 3rd one will be called when progress notifications are sent.
*/
Promise then(Function... f);
-
+
/**
* Add filters to be called just in case the Deferred object is rejected returning
* a new valid promise so as we can continue the flow control of the chain.
* Determine whether a Deferred object has been resolved.
*/
boolean isResolved();
-
+
/**
* Determine whether a Deferred object has been rejected.
*/
public final Object getObject(Object name) {
return c().get(String.valueOf(name));
}
-
+
public final Properties getProperties(Object name) {
return getJavaScriptObject(name);
}
public final String toJson() {
return toJsonString();
}
-
+
public final String toJsonWithName() {
return toJsonWithName(getJsonName());
}
-
+
public final String toJsonWithName(String name) {
return "{\"" + name + "\":{" + toJson() + "}";
}
import com.google.gwt.query.client.IsProperties;
-
/**
* Tagging interface used to generate JsonBuilder classes.
*/
public String toJson() {
return p.tostring();
}
-
+
public String toJsonWithName() {
return "{\"" + getJsonName() + "\":" + p.tostring() + "}";
}
public Properties getProperties() {
return p;
}
-
+
@Override
public String toQueryString() {
return p.toQueryString();
}
-
+
@SuppressWarnings("unchecked")
@Override
public Properties getDataImpl() {
return p;
}
-
+
public <T> T get(Object key) {
return p.get(key);
}
-
+
@SuppressWarnings("unchecked")
public <T extends IsProperties> T set(Object key, Object val) {
if (val instanceof IsProperties) {
}
return (T)this;
}
-
+
public <T extends JsonBuilder> T as(Class<T> clz) {
return p.as(clz);
}
private static final String CSS_PROPERTY = "backgroundRepeat";
-
public static void init() {
CSS.BACKGROUND_REPEAT = new BackgroundRepeatProperty();
}
* cannot set different values on the four borders. To do so, one or more of the
* other border properties must be used.
*
- *
*/
public class BorderProperty implements HasCssValue {
*/
THIN;
-
public String getCssName() {
return name().toLowerCase();
}
* This property takes a {@link UriValue} object as value.
* </p>
*
- *
*/
public static BackgroundImageProperty BACKGROUND_IMAGE;
}
-}
\ No newline at end of file
+}
*/
package com.google.gwt.query.client.css;
-
/**
* Specify position of element's edges.
*/
public class MultipleValueCssSetter extends SimpleCssSetter {
-
public MultipleValueCssSetter(String cssPropertyName, HasCssName... values) {
super(cssPropertyName, computeValue(values));
}
return valueBuilder.toString().trim();
}
-
private static String notNull(HasCssName value) {
return value != null ? value.getCssName() + " " : "";
}
CSS.OUTLINE_COLOR = new OutlineColorProperty();
}
-
private OutlineColorProperty() {
super(CSS_PROPERTY);
}
return new MultipleValueCssSetter(CSS_PROPERTY, outlineColor, outlineStyle, outlineWidth);
}
-
}
return value;
}
-}
\ No newline at end of file
+}
private ZIndexProperty() {
}
-
public String getCssName() {
return CSS_PROPERTY;
}
private static final RegExp cssNumberRegex = RegExp.compile("^(fillOpacity|fontWeight|lineHeight|opacity|orphans|widows|zIndex|zoom)$", "i");
private static final RegExp sizeRegex = RegExp.compile("^(client|offset|)(width|height)$", "i");
-
/**
* Returns the numeric value of a css property.
*
private Element attachTemporary(Element elem) {
Element lastParent = $(elem).parents().last().get(0);
-
+
if (lastParent == null){
//the element itself is detached
lastParent = elem;
}
-
+
Document.get().getBody().appendChild(lastParent);
-
+
return lastParent;
}
e.style.removeAttribute(prop);
}-*/;
-
/**
* Set the value of a style property of an element.
* IE needs a special workaround to handle opacity
e.getStyle().setProperty("filter",
"alpha(opacity=" + (int) (Double.valueOf(val) * 100) + ")");
}
-}
\ No newline at end of file
+}
*/
public abstract class SelectorEngineImpl implements HasSelector {
-
}
*/
package com.google.gwt.query.client.impl;
-
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Element;
*/
public class SelectorEngineSizzle extends SelectorEngineImpl {
-
public static native void initialize() /*-{
(function(){
}-*/;
-
private static native JsArray<Element> select(String selector, Node context, JsArray<Element> results, JsArray<Element> seed) /*-{
return $wnd.GQS(selector, context, results, seed);
}-*/;
*/
package com.google.gwt.query.client.impl;
-
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Element;
*/
public class SelectorEngineSizzleIE extends SelectorEngineImpl {
-
public static native void initialize() /*-{
(function(){
}-*/;
-
private static native JsArray<Element> select(String selector, Node context, JsArray<Element> results, JsArray<Element> seed) /*-{
return $wnd.IES(selector, context, results, seed);
}-*/;
*/
public class SelectorEngineJS extends SelectorEngineImpl {
-
/**
* Internal class.
*/
*/
package com.google.gwt.query.client.impl.research;
-
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Element;
import com.google.gwt.query.client.js.JsRegexp;
import com.google.gwt.query.client.js.JsUtils;
-
/**
* Runtime selector engine implementation which translates selectors to XPath
* and delegates to document.evaluate().
public final native void delete(Object name) /*-{
delete this[name];
}-*/;
-
+
public final void clear() {
for (String k : keys()) {
delete(k);
public final native void invoke() /*-{
return this();
}-*/;
-}
\ No newline at end of file
+}
import com.google.gwt.core.client.JavaScriptObject;
-
/**
* Lightweight JSO backed implemented of a Map, using Object.hashCode() as key.
*/
import com.google.gwt.core.client.JavaScriptObject;
-
/**
* Lightweight JSO backed implemented of a named array
*/
public void pushAll(JavaScriptObject prevElem) {
c().pushAll(prevElem);
}
-
+
public boolean contains(Object o) {
return c().contains(o);
}
c().remove(o);
}
}
-
+
public Object[] elements() {
return c().elements();
}
return a
}-*/;
-
/**
* Call via jsni any arbitrary function present in a Javascript object.
*
* });
* </pre>
*
- *
* For color css properties, values can be specified via hexadecimal or rgb or
* literal values.
*
* $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)', 1000");
* </pre>
*
- *
* @param prop the property to animate : "cssName:'value'"
* @param funcs an array of {@link Function} called once the animation is
* complete
return this;
}
-
public GQuery die(int eventbits, String nameSpace) {
EventsListener.getInstance(Element.is(currentContext) ? (Element) currentContext : body).die(
eventbits, nameSpace, null, null, currentSelector);
return this;
}
-
public GQuery die(int eventbits) {
return die(eventbits, null);
}
* });
* </pre>
*
- *
* For color css properties, values can be specified via hexadecimal or rgb or
* literal values.
*
* $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)', 1000");
* </pre>
*
- *
* @param prop the property to animate : "cssName:'value'"
* @param funcs an array of {@link Function} called once the animation is
* complete
public Promise promise() {
return promise(DEFAULT_NAME);
}
-
+
/**
* Returns a dynamically generated Promise that is resolved once all actions
* in the named queue have ended.
}
}
}
-
+
public void f() {
if (--count == 0) {
dfd.resolve(QueuePlugin.this);
}
}
};
-
+
// Run the function and resolve it in case there are not elements with active queue
resolve.f(this, name);
-
+
return dfd.promise();
}
runNext(elem, name, q);
}
}
-
+
private void runNext(Element elem, String name, Queue<? extends Function> q) {
assert q != null;
Function f = q.peek();
data(elem, name, queue);
}
}
-
+
private Callbacks emptyHooks(Element elem, String name) {
String key = name + EMPTY_HOOKS;
Callbacks c = (Callbacks)data(elem, key, null);
super(gq);
}
-
/**
* Return the immediate scrolling parent.
*/
super(gq);
}
-
/**
* Try to create a widget using the given factory and the given options for
* each element of the query. Returns a new gquery set of elements with the
public Widgets label() {
return widgets(new LabelWidgetFactory(), null);
}
-
+
/**
* Create a {@link Label} widget for each selected element. The
* <code>initializers</code> will be called on each new {@link Label} created
return widgets(new PasswordTextBoxWidgetFactory(), initializers);
}
-
/**
* Create a {@link TextBox} widget for each selected element. The
* <code>initializers</code> will be called on each new {@link TextBox}
public static final String JSON_CONTENT_TYPE = "application/json";
public static final String JSON_CONTENT_TYPE_UTF8 = JSON_CONTENT_TYPE + "; charset=utf-8";
-
+
public static interface AjaxTransport {
Promise getJsonP(Settings settings);
Promise getXhr(Settings settings);
}
-
+
/**
* Ajax Settings object
*/
/**
* Perform an ajax request to the server.
*
- *
* Example:
*
* <pre>
*/
public static Promise ajax(Settings settings) {
resolveSettings(settings);
-
+
final Function onSuccess = settings.getSuccess();
if (onSuccess != null) {
onSuccess.setElement(settings.getContext());
}
return ret;
}
-
+
private static void resolveSettings(Settings settings) {
String url = settings.getUrl();
assert settings != null && settings.getUrl() != null: "no url found in settings";
-
+
String type = "POST";
if (settings.getType() != null) {
type = settings.getType().toUpperCase();
settings.setUrl(url);
}
}
-
+
public static Promise ajax(String url, Function onSuccess, Function onError) {
return ajax(url, onSuccess, onError, (Settings) null);
}
public Ajax load(String url, IsProperties data) {
return load(url, data);
}
-
+
public Ajax load(String url, IsProperties data, final Function onSuccess) {
Settings s = createSettings();
final String filter = url.contains(" ") ? url.replaceFirst("^[^\\s]+\\s+", "") : "";
* Ajax transport for Client side.
*/
public class AjaxTransportJs implements AjaxTransport {
-
+
@Override
public Promise getJsonP(Settings settings) {
return new PromiseReqBuilderJSONP(settings.getUrl(), settings.getTimeout());
}
-
+
@Override
public Promise getLoadScript(final Settings settings) {
return new PromiseFunction() {
public Promise getXhr(Settings settings) {
return new PromiseReqBuilder(settings);
}
-
+
}
* Implementation of jQuery.Callbacks for gwtquery.
*/
public class Callbacks {
-
+
/**
* Iterface used for callbacks which could cancel the execution
* when returning false;
*/
boolean f(Object ...objects);
}
-
+
private List<Object> stack = new ArrayList<Object>();
-
+
private boolean done = false;
-
+
private List<Object> memory = null;
-
+
private boolean isOnce, isMemory, isUnique, stopOnFalse;
-
+
public Callbacks() {
this("");
}
-
+
/**
* Create a new Callbacks object with options given as a space delimited string.
*
isUnique = options.contains("unique");
stopOnFalse = options.contains("stopOnFalse");
}
-
+
/**
* Add a Callback or a collection of callbacks to a callback list.
*
addAll((Object[])c);
return this;
}
-
+
/**
* Add a Callback or a collection of callbacks to a callback list.
*/
addAll((Object[])f);
return this;
}
-
+
/**
* Disable a callback list from doing anything more.
*/
done = true;
return this;
}
-
+
/**
* lock
*/
}
return this;
}
-
+
/**
* Remove a callback or a collection of callbacks from a callback list.
*/
stack.removeAll(Arrays.asList(o));
return this;
}
-
+
private void addAll(Object...o) {
for (Object c : o) {
if (!done && stack != null && c != null && (!isUnique || !stack.contains(c))) {
}
return true;
}
-
+
public String status() {
return "stack=" + (stack == null ? "null" : stack.size()) + " " + done;
}
cache = type;
return this;
}
-
+
/**
* Reset the cache so as a new invocation to this function will
* execute it instead of restoring old values from cache.
public PromiseFunction() {
f(dfd);
}
-
+
/**
* This function is called once when the promise is created and the
* new deferred is available.
* </pre>
*/
public class PromiseReqBuilderJSONP extends DeferredPromiseImpl {
-
+
private static final RegExp callbackRegex = RegExp.compile("^(.+[\\?&])([^=]+)=\\?(.*)$");
-
+
public PromiseReqBuilderJSONP(String url) {
this(url, null, 0);
}
* [2] http://dxr.mozilla.org/mozilla-central/source/content/smil/nsSMILKeySpline.cpp
*/
public class Bezier {
-
+
private double x1, y1 , x2, y2;
-
+
public Bezier(double x1, double y1, double x2, double y2) {
this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
}
-
+
private double a(double a1, double a2) {
return 1.0 - 3.0 * a2 + 3.0 * a1;
}
private double c(double a1){
return 3.0 * a1;
}
-
+
private double calcBezier(double t, double a1, double a2) {
return ((a(a1, a2)*t + b(a1, a2))*t + c(a1))*t;
}
-
+
private double calcSlope(double t, double a1, double a2) {
return 3.0 * a(a1, a2)*t*t + 2.0 * b(a1, a2) * t + c(a1);
}
-
+
private double getTForX(double x) {
double t = x;
for (double i = 0; i < 4; ++i) {
}
return t;
}
-
+
public double f (double x) {
return calcBezier(getTForX(x), y1, y2);
}
-
+
public String toString() {
return x1 + "," + y1 + "," + x2 + "," + y2;
}
die(b, nameSpace, eventName, originalEventName, cssSelector);
}
-
}
public void die(int eventbits, String nameSpace, String eventName, String originalEventName,
String nameSpace = null;
String eventName = event;
-
String[] subparts = event.split("\\.", 2);
if (subparts.length == 2) {
public void unbind(int eventbits, String namespace, String eventName, String originalEventType,
Function f) {
-
+
JsObjectArray<BindFunction> newList = JsObjectArray.createArray().cast();
for (int i = 0; i < elementEvents.length(); i++) {
BindFunction listener = elementEvents.get(i);
* element. So, we cannot keep a copy of the MouseDownEvent during a dragging
* for example.
*
- *
- *
* Be Careful : the methods preventDefault() and stopPropagation must be called directly on the
* original event.
*
- *
*/
public class GqEvent extends Event {
gQueryEvent.originalEvent = originalEvent;
}-*/;
-
protected GqEvent() {
}
*/
package com.google.gwt.query.client.plugins.widgets;
-
import com.google.gwt.dom.client.ButtonElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.query.client.plugins.widgets.WidgetFactory;
destination.setName(source.getName());
destination.setValue(source.getValue());
}
-}
\ No newline at end of file
+}
return new WidgetsHtmlPanel(e);
}
-}
\ No newline at end of file
+}
return label;
}
-}
\ No newline at end of file
+}
return "textarea";
}
-
protected TextArea createWidget() {
return new TextArea();
}
-}
\ No newline at end of file
+}
import com.google.gwt.user.client.ui.TextBoxBase;
/**
- *
*
*/
public abstract class TextBoxBaseWidgetFactory<T extends TextBoxBase>
}
protected abstract T createWidget();
-}
\ No newline at end of file
+}
protected TextBox createWidget() {
return new TextBox();
}
-}
\ No newline at end of file
+}
*/
public interface WidgetFactory<W extends Widget> {
public W create(Element e);
- }
\ No newline at end of file
+ }
static final String[] appendingTags = {
"td", "th", "li"};
-
/**
* Append a widget to a dom element, and hide it.
* Element classes will be copied to the new widget.
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
TypeOracle oracle = context.getTypeOracle();
PropertyOracle propOracle = context.getPropertyOracle();
-
+
String ua = null;
try {
ua = propOracle.getSelectionProperty(logger, "user.agent").getCurrentValue();
logger.log(TreeLogger.ERROR, "Can not resolve user.agent property", e);
throw new UnableToCompleteException();
}
-
+
JClassType clz = oracle.findType(typeName);
String pName = clz.getPackage().getName();
String cName = clz.getName() + "_" + ua;
-
+
PrintWriter pWriter = context.tryCreate(logger, pName, cName);
-
+
if (pWriter != null) {
ClassSourceFileComposerFactory cFact = new ClassSourceFileComposerFactory(pName, cName);
cFact.setSuperclass(pName + "." + clz.getName());
-
+
SourceWriter writer = cFact.createSourceWriter(context, pWriter);
-
+
writer.println("protected boolean isWebkit() {return " + "safari".equals(ua) + ";}");
writer.println("protected boolean isSafari() {return " + "safari".equals(ua) + ";}");
writer.println("protected boolean isOpera() {return " + "opera".equals(ua) + ";}");
";}");
writer.commit(logger);
}
-
+
return pName + "." + cName;
}
}
static JClassType stringType;
static JClassType jsonFactoryType;
-
public static String capitalize(String s) {
if (s.length() == 0)
return s;
break;
}
}
-
+
if (targetType == null) return null;
assert targetType != null : "Parameter of Lazy<T> not found";
protected boolean hasGetElementsByClassName() {
return true;
}
-}
\ No newline at end of file
+}
protected boolean hasGetElementsByClassName() {
return false;
}
-}
\ No newline at end of file
+}
protected boolean hasGetElementsByClassName() {
return false;
}
-}
\ No newline at end of file
+}
*
*/
public class AjaxTransportJre implements AjaxTransport {
-
+
private static String localDomain = null;
-
+
private static CookieManager cookieManager = CookieManager.getInstance();
private static boolean debugOutput = false;
-
+
private static boolean followRedirections = true;
-
+
public static void enableCORS(String domain) {
localDomain = domain;
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
-
+
public static void enableDebug(boolean b) {
debugOutput = b;
}
-
+
public static void enableCookies(boolean b) {
cookieManager = b ? CookieManager.getInstance() : null;
}
-
+
public static void enableRedirections(boolean b) {
followRedirections = b;
}
-
+
private final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:26.0) Gecko/20100101 Firefox/26.0";
private final String jsonpCbRexp = "(?ms)^.*jre_callback\\((.*)\\).*$";
String url = settings.getUrl().replaceFirst("callback=[^&]*", "");
url += (url.contains("?") ? "&" : "?") + "callback=jre_callback";
settings.setUrl(url);
-
+
if (settings.getTimeout() < 1) {
settings.setTimeout(10000);
}
-
+
return getXhr(settings, false)
.then(new Function() {
public Object f(Object... args) {
public Promise getLoadScript(Settings settings) {
return getXhr(settings, false);
}
-
+
public Promise getXhr(final Settings settings) {
return getXhr(settings, true);
}
private Response httpClient(Settings s, boolean cors) throws Exception {
String url = s.getUrl();
assert url.toLowerCase().startsWith("http");
-
+
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
-
+
c.setInstanceFollowRedirects(followRedirections);
-
+
c.setRequestMethod(s.getType());
c.setRequestProperty("User-Agent", USER_AGENT);
if (s.getUsername() != null && s.getPassword() != null) {
if (cookieManager != null) {
cookieManager.setCookies(c);
}
-
+
boolean isCORS = cors && localDomain != null && !s.getUrl().contains(localDomain);
if (isCORS) {
// TODO: fetch options previously to the request
// Access-Control-Allow-Credentials: true
c.setRequestProperty("Origin", localDomain);
}
-
+
if (s.getTimeout() > 0) {
c.setConnectTimeout(s.getTimeout());
c.setReadTimeout(s.getTimeout());
}
-
+
IsProperties headers = s.getHeaders();
if (headers != null) {
for (String h : headers.getFieldNames()) {
c.setRequestProperty(h, "" + headers.get(h));
}
}
-
+
if (s.getType().matches("POST|PUT")) {
c.setRequestProperty("Content-Type", s.getContentType());
-
+
debugRequest(c, s.getDataString());
-
+
c.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(c.getOutputStream());
wr.writeBytes(s.getDataString());
} else {
debugRequest(c, null);
}
-
+
int code = c.getResponseCode();
if (isCORS) {
if (!localDomain.equals(c.getHeaderField("Access-Control-Allow-Origin"))) {
code = 0;
}
}
-
+
String payload = "";
-
+
InputStream is = code >= 400 ? c.getErrorStream() : c.getInputStream();
if (is != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
in.close();
payload = response.toString();
}
-
+
if (cookieManager != null) {
cookieManager.storeCookies(c);
}
return new ResponseJre(code, c.getResponseMessage(), payload, c.getHeaderFields());
}
-
+
private void debugRequest(HttpURLConnection c, String payload) {
if (debugOutput) {
System.out.println(c.getRequestMethod() + " " + c.getURL().getPath());
private static final char DOT = '.';
private DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);;
-
+
private static CookieManager cookieManager = new CookieManager();
public static CookieManager getInstance() {
return cookieManager;
}
-
+
public void clear() {
store.clear();
}
-
+
public void removeDomainCookies(String domain) {
store.remove(domain);
}
-
+
public void removeDomainCookie(String domain, String... cookies) {
Map<String, Map<String, String>> domainStore = store.get(domain);
if (domainStore != null) {
}
}
}
-
+
public void setDomcainCookie(String host, String name, String value) {
setDomcainCookieProperty(host, name, name, value);
}
-
+
public void setDomcainCookieProperty(String host, String name, String prop, String value) {
String domain = getDomainFromHost(host);
Map<String, Map<String, String>> domainStore = store.get(domain);
private Map<String,List<String>> headers;
private String responseText;
private String statusText;
-
+
public ResponseJre(int status, String statusText, String text, Map<String,List<String>> headers) {
this.status = status;
this.headers = headers;
this.responseText = text;
this.statusText = statusText;
}
-
+
public String getHeader(String header) {
List<String> l = headers.get(header);
if (l != null && !l.isEmpty()) {
public String getText() {
return responseText;
}
-}
\ No newline at end of file
+}
private int total = 0;
private List<Object> responses = new ArrayList<Object>();
private List<RequestContext> contexts = new ArrayList<RequestContext>();
-
+
/**
* Fire a RF Request.
*/