提交 2c93d30e 编写于 作者: M mduigou

Merge

...@@ -31,13 +31,6 @@ BUILDDIR = ../.. ...@@ -31,13 +31,6 @@ BUILDDIR = ../..
PRODUCT = sun PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk include $(BUILDDIR)/common/Defs.gmk
ifndef OPENJDK
ORG_EXISTS := $(call DirExists,$(CLOSED_SRC)/share/classes/sun/org,,)
ifneq ("$(ORG_EXISTS)", "")
SCRIPT_SUBDIR = script
endif
endif
# jarsigner is part of JRE # jarsigner is part of JRE
SUBDIRS = java security net/ssl jarsigner SUBDIRS = java security net/ssl jarsigner
......
#
# Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
BUILDDIR = ../../..
PACKAGE = com.sun.script
PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk
AUTO_FILES_JAVA_DIRS = com/sun/script
#
# Files that need to be copied
#
SERVICEDIR = $(CLASSBINDIR)/META-INF/services
FILES_copy = \
$(SERVICEDIR)/javax.script.ScriptEngineFactory
include $(BUILDDIR)/common/Classes.gmk
all: classes copy-files
#
# Copy the service provider configuration file into the resource
# directory.
#
copy-files: $(FILES_copy)
$(SERVICEDIR)/%: $(SHARE_SRC)/classes/com/sun/script/javascript/META-INF/services/%
$(install-file)
.PHONY: copy-files
clean::
$(RM) -r $(CLASSDESTDIR)/com/sun/script/javascript
$(RM) $(FILES_copy)
...@@ -31,12 +31,6 @@ BUILDDIR = .. ...@@ -31,12 +31,6 @@ BUILDDIR = ..
PRODUCT = sun PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk include $(BUILDDIR)/common/Defs.gmk
# Rhino/Mozilla java sources
ORG_EXISTS := $(call DirExists,$(CLOSED_SRC)/share/classes/sun/org,,)
ifneq ("$(ORG_EXISTS)", "")
ORG_SUBDIR = org
endif
# Non windows subdirs # Non windows subdirs
ifneq ($(PLATFORM), windows) ifneq ($(PLATFORM), windows)
ifndef OPENJDK ifndef OPENJDK
...@@ -83,7 +77,7 @@ SUBDIRS_desktop = audio $(RENDER_SUBDIR) image \ ...@@ -83,7 +77,7 @@ SUBDIRS_desktop = audio $(RENDER_SUBDIR) image \
$(LWAWT_PRE_SUBDIR) $(DISPLAY_LIBS) $(DGA_SUBDIR) $(LWAWT_SUBDIR) \ $(LWAWT_PRE_SUBDIR) $(DISPLAY_LIBS) $(DGA_SUBDIR) $(LWAWT_SUBDIR) \
jawt font jpeg cmm $(DISPLAY_TOOLS) jawt font jpeg cmm $(DISPLAY_TOOLS)
SUBDIRS_management = management SUBDIRS_management = management
SUBDIRS_misc = $(ORG_SUBDIR) rmi tracing SUBDIRS_misc = rmi tracing
SUBDIRS_tools = native2ascii serialver tools jconsole SUBDIRS_tools = native2ascii serialver tools jconsole
ifndef OPENJDK ifndef OPENJDK
......
#
# Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
#
# Makefile for building Mozilla modules
#
BUILDDIR = ../..
PRODUCT = org
include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = mozilla
include $(BUILDDIR)/common/Subdirs.gmk
all build clean clobber::
$(SUBDIRS-loop)
#
# Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
#
# Makefile for building Mozilla JavaScript modules
#
BUILDDIR = ../../..
PRODUCT = org
include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = javascript
include $(BUILDDIR)/common/Subdirs.gmk
all build clean clobber::
$(SUBDIRS-loop)
#
# Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
#
# Makefile for building all of sun.org.mozilla.javascript.internal.*
#
BUILDDIR = ../../../..
PACKAGE = sun.org.mozilla.javascript.internal
PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk
AUTO_FILES_JAVA_DIRS = sun/org/mozilla/javascript/internal
RESOURCEDIR = \
$(CLASSDESTDIR)/sun/org/mozilla/javascript/internal/resources
FILES_copy = \
$(RESOURCEDIR)/Messages.properties \
$(RESOURCEDIR)/Messages_fr.properties
#
# Rules
#
include $(BUILDDIR)/common/Classes.gmk
all: classes copy-files
#
# Copy resource messages file for Rhino JavaScript interpreter
#
copy-files: $(FILES_copy)
$(RESOURCEDIR)/%: $(CLOSED_SRC)/share/classes/sun/org/mozilla/javascript/internal/resources/%
$(install-file)
.PHONY: copy-files
clean clobber::
$(RM) -rf $(CLASSDESTDIR)/sun/org/mozilla/javascript
...@@ -30,7 +30,5 @@ sun.security.krb5.Realm=sun.security.ssl.krb5.KerberosClientKeyExchangeImpl,comp ...@@ -30,7 +30,5 @@ sun.security.krb5.Realm=sun.security.ssl.krb5.KerberosClientKeyExchangeImpl,comp
# Residual references to java.beans. # Residual references to java.beans.
# The RemoveMethods tool does not yet purge the constant pool. # The RemoveMethods tool does not yet purge the constant pool.
# Rhino is due to be replaced so not worth addressing this dependency now.
# #
java.beans.PropertyChangeListener=java.util.logging.LogManager,sun.org.mozilla.javascript.internal.Context,compact1,compact2,compact3 java.beans.PropertyChangeListener=java.util.logging.LogManager,compact1,compact2,compact3
java.beans.PropertyChangeEvent=sun.org.mozilla.javascript.internal.Context,compact3
...@@ -458,24 +458,6 @@ endif # OPENJDK ...@@ -458,24 +458,6 @@ endif # OPENJDK
ifndef OPENJDK ifndef OPENJDK
JS_RESOURCES_FILES := Messages.properties Messages_fr.properties
JS_RESOURCES_SRC_DIR := $(JDK_TOPDIR)/src/closed/share/classes/sun/org/mozilla/javascript/internal/resources
JS_RESOURCES_DST_DIR := $(JDK_OUTPUTDIR)/classes/sun/org/mozilla/javascript/internal/resources
JS_RESOURCES_SRC := $(foreach F,$(JS_RESOURCES_FILES),$(JS_RESOURCES_SRC_DIR)/$(F))
JS_RESOURCES_DST := $(foreach F,$(JS_RESOURCES_FILES),$(JS_RESOURCES_DST_DIR)/$(F))
$(JS_RESOURCES_DST_DIR)/% : $(JS_RESOURCES_SRC_DIR)/%
$(call install-file)
COPY_FILES += $(JS_RESOURCES_DST)
endif
##########################################################################################
ifndef OPENJDK
# #
# Solaris X11 Direct Graphics Access library # Solaris X11 Direct Graphics Access library
# #
......
...@@ -172,10 +172,6 @@ ifneq ($(ALL_META-INF_DIRS_targetapi),) ...@@ -172,10 +172,6 @@ ifneq ($(ALL_META-INF_DIRS_targetapi),)
else else
ALL_META-INF_DIRS:=$(ALL_META-INF_DIRS_share) ALL_META-INF_DIRS:=$(ALL_META-INF_DIRS_share)
endif endif
# Filter out META-INF dirs that shouldn't be included
ifdef OPENJDK
ALL_META-INF_DIRS:=$(filter-out %com/sun/script/javascript/META-INF,$(ALL_META-INF_DIRS))
endif
ifndef OPENJDK ifndef OPENJDK
ALL_META-INF_DIRS += $(JDK_TOPDIR)/src/closed/share/classes/sun/java2d/cmm/kcms/META-INF ALL_META-INF_DIRS += $(JDK_TOPDIR)/src/closed/share/classes/sun/java2d/cmm/kcms/META-INF
......
...@@ -112,7 +112,6 @@ PROFILE_3_RTJAR_INCLUDE_PACKAGES := \ ...@@ -112,7 +112,6 @@ PROFILE_3_RTJAR_INCLUDE_PACKAGES := \
com/sun/nio/sctp \ com/sun/nio/sctp \
com/sun/org/apache/xml/internal/security \ com/sun/org/apache/xml/internal/security \
com/sun/rowset \ com/sun/rowset \
com/sun/script \
com/sun/security/auth \ com/sun/security/auth \
com/sun/security/jgss \ com/sun/security/jgss \
com/sun/security/ntlm \ com/sun/security/ntlm \
...@@ -140,7 +139,6 @@ PROFILE_3_RTJAR_INCLUDE_PACKAGES := \ ...@@ -140,7 +139,6 @@ PROFILE_3_RTJAR_INCLUDE_PACKAGES := \
sun/net/www/protocol/http/ntlm \ sun/net/www/protocol/http/ntlm \
sun/net/www/protocol/http/spnego \ sun/net/www/protocol/http/spnego \
sun/nio/ch/sctp \ sun/nio/ch/sctp \
sun/org/mozilla \
sun/security/acl \ sun/security/acl \
sun/security/jgss \ sun/security/jgss \
sun/security/krb5 \ sun/security/krb5 \
...@@ -161,10 +159,6 @@ PROFILE_3_RTJAR_EXCLUDE_TYPES := \ ...@@ -161,10 +159,6 @@ PROFILE_3_RTJAR_EXCLUDE_TYPES := \
javax/management/remote/rmi/_RMIServerImpl_Tie.class \ javax/management/remote/rmi/_RMIServerImpl_Tie.class \
javax/management/remote/rmi/_RMIServer_Stub.class javax/management/remote/rmi/_RMIServer_Stub.class
PROFILE_3_INCLUDE_METAINF_SERVICES := \
META-INF/services/javax.script.ScriptEngineFactory
FULL_JRE_RTJAR_INCLUDE_PACKAGES := \ FULL_JRE_RTJAR_INCLUDE_PACKAGES := \
com/oracle \ com/oracle \
com/sun/accessibility/internal/resources \ com/sun/accessibility/internal/resources \
......
...@@ -102,7 +102,7 @@ public class DnsContext extends ComponentDirContext { ...@@ -102,7 +102,7 @@ public class DnsContext extends ComponentDirContext {
this.domain = new DnsName(domain.endsWith(".") this.domain = new DnsName(domain.endsWith(".")
? domain ? domain
: domain + "."); : domain + ".");
this.servers = servers; this.servers = (servers == null) ? null : servers.clone();
this.environment = (Hashtable<Object,Object>) environment.clone(); this.environment = (Hashtable<Object,Object>) environment.clone();
envShared = false; envShared = false;
parentIsDns = false; parentIsDns = false;
...@@ -129,11 +129,11 @@ public class DnsContext extends ComponentDirContext { ...@@ -129,11 +129,11 @@ public class DnsContext extends ComponentDirContext {
* no conflict. * no conflict.
*/ */
private DnsContext(DnsContext ctx) { private DnsContext(DnsContext ctx) {
environment = ctx.environment; environment = ctx.environment; // shared environment, copy-on-write
envShared = ctx.envShared = true; envShared = ctx.envShared = true;
parentIsDns = ctx.parentIsDns; parentIsDns = ctx.parentIsDns;
domain = ctx.domain; domain = ctx.domain;
servers = ctx.servers; servers = ctx.servers; // shared servers, no write operation
resolver = ctx.resolver; resolver = ctx.resolver;
authoritative = ctx.authoritative; authoritative = ctx.authoritative;
recursion = ctx.recursion; recursion = ctx.recursion;
......
...@@ -81,7 +81,7 @@ public class BasicControl implements Control { ...@@ -81,7 +81,7 @@ public class BasicControl implements Control {
this.id = id; this.id = id;
this.criticality = criticality; this.criticality = criticality;
if (value != null) { if (value != null) {
this.value = value; this.value = value.clone();
} }
} }
......
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.javascript;
import sun.org.mozilla.javascript.internal.*;
import javax.script.*;
import java.util.*;
/**
* ExternalScriptable is an implementation of Scriptable
* backed by a JSR 223 ScriptContext instance.
*
* @author Mike Grogan
* @author A. Sundararajan
* @since 1.6
*/
final class ExternalScriptable implements Scriptable {
/* Underlying ScriptContext that we use to store
* named variables of this scope.
*/
private ScriptContext context;
/* JavaScript allows variables to be named as numbers (indexed
* properties). This way arrays, objects (scopes) are treated uniformly.
* Note that JSR 223 API supports only String named variables and
* so we can't store these in Bindings. Also, JavaScript allows name
* of the property name to be even empty String! Again, JSR 223 API
* does not support empty name. So, we use the following fallback map
* to store such variables of this scope. This map is not exposed to
* JSR 223 API. We can just script objects "as is" and need not convert.
*/
private Map<Object, Object> indexedProps;
// my prototype
private Scriptable prototype;
// my parent scope, if any
private Scriptable parent;
ExternalScriptable(ScriptContext context) {
this(context, new HashMap<Object, Object>());
}
ExternalScriptable(ScriptContext context, Map<Object, Object> indexedProps) {
if (context == null) {
throw new NullPointerException("context is null");
}
this.context = context;
this.indexedProps = indexedProps;
}
ScriptContext getContext() {
return context;
}
private boolean isEmpty(String name) {
return name.equals("");
}
/**
* Return the name of the class.
*/
public String getClassName() {
return "Global";
}
/**
* Returns the value of the named property or NOT_FOUND.
*
* If the property was created using defineProperty, the
* appropriate getter method is called.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
public synchronized Object get(String name, Scriptable start) {
if (isEmpty(name)) {
if (indexedProps.containsKey(name)) {
return indexedProps.get(name);
} else {
return NOT_FOUND;
}
} else {
synchronized (context) {
int scope = context.getAttributesScope(name);
if (scope != -1) {
Object value = context.getAttribute(name, scope);
return Context.javaToJS(value, this);
} else {
return NOT_FOUND;
}
}
}
}
/**
* Returns the value of the indexed property or NOT_FOUND.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
public synchronized Object get(int index, Scriptable start) {
Integer key = new Integer(index);
if (indexedProps.containsKey(index)) {
return indexedProps.get(key);
} else {
return NOT_FOUND;
}
}
/**
* Returns true if the named property is defined.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
public synchronized boolean has(String name, Scriptable start) {
if (isEmpty(name)) {
return indexedProps.containsKey(name);
} else {
synchronized (context) {
return context.getAttributesScope(name) != -1;
}
}
}
/**
* Returns true if the property index is defined.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
public synchronized boolean has(int index, Scriptable start) {
Integer key = new Integer(index);
return indexedProps.containsKey(key);
}
/**
* Sets the value of the named property, creating it if need be.
*
* @param name the name of the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void put(String name, Scriptable start, Object value) {
if (start == this) {
synchronized (this) {
if (isEmpty(name)) {
indexedProps.put(name, value);
} else {
synchronized (context) {
int scope = context.getAttributesScope(name);
if (scope == -1) {
scope = ScriptContext.ENGINE_SCOPE;
}
context.setAttribute(name, jsToJava(value), scope);
}
}
}
} else {
start.put(name, start, value);
}
}
/**
* Sets the value of the indexed property, creating it if need be.
*
* @param index the numeric index for the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void put(int index, Scriptable start, Object value) {
if (start == this) {
synchronized (this) {
indexedProps.put(new Integer(index), value);
}
} else {
start.put(index, start, value);
}
}
/**
* Removes a named property from the object.
*
* If the property is not found, no action is taken.
*
* @param name the name of the property
*/
public synchronized void delete(String name) {
if (isEmpty(name)) {
indexedProps.remove(name);
} else {
synchronized (context) {
int scope = context.getAttributesScope(name);
if (scope != -1) {
context.removeAttribute(name, scope);
}
}
}
}
/**
* Removes the indexed property from the object.
*
* If the property is not found, no action is taken.
*
* @param index the numeric index for the property
*/
public void delete(int index) {
indexedProps.remove(new Integer(index));
}
/**
* Get the prototype of the object.
* @return the prototype
*/
public Scriptable getPrototype() {
return prototype;
}
/**
* Set the prototype of the object.
* @param prototype the prototype to set
*/
public void setPrototype(Scriptable prototype) {
this.prototype = prototype;
}
/**
* Get the parent scope of the object.
* @return the parent scope
*/
public Scriptable getParentScope() {
return parent;
}
/**
* Set the parent scope of the object.
* @param parent the parent scope to set
*/
public void setParentScope(Scriptable parent) {
this.parent = parent;
}
/**
* Get an array of property ids.
*
* Not all property ids need be returned. Those properties
* whose ids are not returned are considered non-enumerable.
*
* @return an array of Objects. Each entry in the array is either
* a java.lang.String or a java.lang.Number
*/
public synchronized Object[] getIds() {
String[] keys = getAllKeys();
int size = keys.length + indexedProps.size();
Object[] res = new Object[size];
System.arraycopy(keys, 0, res, 0, keys.length);
int i = keys.length;
// now add all indexed properties
for (Object index : indexedProps.keySet()) {
res[i++] = index;
}
return res;
}
/**
* Get the default value of the object with a given hint.
* The hints are String.class for type String, Number.class for type
* Number, Scriptable.class for type Object, and Boolean.class for
* type Boolean. <p>
*
* A <code>hint</code> of null means "no hint".
*
* See ECMA 8.6.2.6.
*
* @param hint the type hint
* @return the default value
*/
public Object getDefaultValue(Class typeHint) {
for (int i=0; i < 2; i++) {
boolean tryToString;
if (typeHint == ScriptRuntime.StringClass) {
tryToString = (i == 0);
} else {
tryToString = (i == 1);
}
String methodName;
Object[] args;
if (tryToString) {
methodName = "toString";
args = ScriptRuntime.emptyArgs;
} else {
methodName = "valueOf";
args = new Object[1];
String hint;
if (typeHint == null) {
hint = "undefined";
} else if (typeHint == ScriptRuntime.StringClass) {
hint = "string";
} else if (typeHint == ScriptRuntime.ScriptableClass) {
hint = "object";
} else if (typeHint == ScriptRuntime.FunctionClass) {
hint = "function";
} else if (typeHint == ScriptRuntime.BooleanClass
|| typeHint == Boolean.TYPE)
{
hint = "boolean";
} else if (typeHint == ScriptRuntime.NumberClass ||
typeHint == ScriptRuntime.ByteClass ||
typeHint == Byte.TYPE ||
typeHint == ScriptRuntime.ShortClass ||
typeHint == Short.TYPE ||
typeHint == ScriptRuntime.IntegerClass ||
typeHint == Integer.TYPE ||
typeHint == ScriptRuntime.FloatClass ||
typeHint == Float.TYPE ||
typeHint == ScriptRuntime.DoubleClass ||
typeHint == Double.TYPE)
{
hint = "number";
} else {
throw Context.reportRuntimeError(
"Invalid JavaScript value of type " +
typeHint.toString());
}
args[0] = hint;
}
Object v = ScriptableObject.getProperty(this, methodName);
if (!(v instanceof Function))
continue;
Function fun = (Function) v;
Context cx = RhinoScriptEngine.enterContext();
try {
v = fun.call(cx, fun.getParentScope(), this, args);
} finally {
cx.exit();
}
if (v != null) {
if (!(v instanceof Scriptable)) {
return v;
}
if (typeHint == ScriptRuntime.ScriptableClass
|| typeHint == ScriptRuntime.FunctionClass)
{
return v;
}
if (tryToString && v instanceof Wrapper) {
// Let a wrapped java.lang.String pass for a primitive
// string.
Object u = ((Wrapper)v).unwrap();
if (u instanceof String)
return u;
}
}
}
// fall through to error
String arg = (typeHint == null) ? "undefined" : typeHint.getName();
throw Context.reportRuntimeError(
"Cannot find default value for object " + arg);
}
/**
* Implements the instanceof operator.
*
* @param instance The value that appeared on the LHS of the instanceof
* operator
* @return true if "this" appears in value's prototype chain
*
*/
public boolean hasInstance(Scriptable instance) {
// Default for JS objects (other than Function) is to do prototype
// chasing.
Scriptable proto = instance.getPrototype();
while (proto != null) {
if (proto.equals(this)) return true;
proto = proto.getPrototype();
}
return false;
}
private String[] getAllKeys() {
ArrayList<String> list = new ArrayList<String>();
synchronized (context) {
for (int scope : context.getScopes()) {
Bindings bindings = context.getBindings(scope);
if (bindings != null) {
list.ensureCapacity(bindings.size());
for (String key : bindings.keySet()) {
list.add(key);
}
}
}
}
String[] res = new String[list.size()];
list.toArray(res);
return res;
}
/**
* We convert script values to the nearest Java value.
* We unwrap wrapped Java objects so that access from
* Bindings.get() would return "workable" value for Java.
* But, at the same time, we need to make few special cases
* and hence the following function is used.
*/
private Object jsToJava(Object jsObj) {
if (jsObj instanceof Wrapper) {
Wrapper njb = (Wrapper) jsObj;
/* importClass feature of ImporterTopLevel puts
* NativeJavaClass in global scope. If we unwrap
* it, importClass won't work.
*/
if (njb instanceof NativeJavaClass) {
return njb;
}
/* script may use Java primitive wrapper type objects
* (such as java.lang.Integer, java.lang.Boolean etc)
* explicitly. If we unwrap, then these script objects
* will become script primitive types. For example,
*
* var x = new java.lang.Double(3.0); print(typeof x);
*
* will print 'number'. We don't want that to happen.
*/
Object obj = njb.unwrap();
if (obj instanceof Number || obj instanceof String ||
obj instanceof Boolean || obj instanceof Character) {
// special type wrapped -- we just leave it as is.
return njb;
} else {
// return unwrapped object for any other object.
return obj;
}
} else { // not-a-Java-wrapper
return jsObj;
}
}
}
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.javascript;
import sun.org.mozilla.javascript.internal.*;
import java.util.*;
/**
* JSAdapter is java.lang.reflect.Proxy equivalent for JavaScript. JSAdapter
* calls specially named JavaScript methods on an adaptee object when property
* access is attempted on it.
*
* Example:
*
* var y = {
* __get__ : function (name) { ... }
* __has__ : function (name) { ... }
* __put__ : function (name, value) {...}
* __delete__ : function (name) { ... }
* __getIds__ : function () { ... }
* };
*
* var x = new JSAdapter(y);
*
* x.i; // calls y.__get__
* i in x; // calls y.__has__
* x.p = 10; // calls y.__put__
* delete x.p; // calls y.__delete__
* for (i in x) { print(i); } // calls y.__getIds__
*
* If a special JavaScript method is not found in the adaptee, then JSAdapter
* forwards the property access to the adaptee itself.
*
* JavaScript caller of adapter object is isolated from the fact that
* the property access/mutation/deletion are really calls to
* JavaScript methods on adaptee. Use cases include 'smart'
* properties, property access tracing/debugging, encaptulation with
* easy client access - in short JavaScript becomes more "Self" like.
*
* Note that Rhino already supports special properties like __proto__
* (to set, get prototype), __parent__ (to set, get parent scope). We
* follow the same double underscore nameing convention here. Similarly
* the name JSAdapter is derived from JavaAdapter -- which is a facility
* to extend, implement Java classes/interfaces by JavaScript.
*
* @author A. Sundararajan
* @since 1.6
*/
public final class JSAdapter implements Scriptable, Function {
private JSAdapter(Scriptable obj) {
setAdaptee(obj);
}
// initializer to setup JSAdapter prototype in the given scope
public static void init(Context cx, Scriptable scope, boolean sealed)
throws RhinoException {
JSAdapter obj = new JSAdapter(cx.newObject(scope));
obj.setParentScope(scope);
obj.setPrototype(getFunctionPrototype(scope));
obj.isPrototype = true;
ScriptableObject.defineProperty(scope, "JSAdapter", obj,
ScriptableObject.DONTENUM);
}
public String getClassName() {
return "JSAdapter";
}
public Object get(String name, Scriptable start) {
Function func = getAdapteeFunction(GET_PROP);
if (func != null) {
return call(func, new Object[] { name });
} else {
start = getAdaptee();
return start.get(name, start);
}
}
public Object get(int index, Scriptable start) {
Function func = getAdapteeFunction(GET_PROP);
if (func != null) {
return call(func, new Object[] { new Integer(index) });
} else {
start = getAdaptee();
return start.get(index, start);
}
}
public boolean has(String name, Scriptable start) {
Function func = getAdapteeFunction(HAS_PROP);
if (func != null) {
Object res = call(func, new Object[] { name });
return Context.toBoolean(res);
} else {
start = getAdaptee();
return start.has(name, start);
}
}
public boolean has(int index, Scriptable start) {
Function func = getAdapteeFunction(HAS_PROP);
if (func != null) {
Object res = call(func, new Object[] { new Integer(index) });
return Context.toBoolean(res);
} else {
start = getAdaptee();
return start.has(index, start);
}
}
public void put(String name, Scriptable start, Object value) {
if (start == this) {
Function func = getAdapteeFunction(PUT_PROP);
if (func != null) {
call(func, new Object[] { name, value });
} else {
start = getAdaptee();
start.put(name, start, value);
}
} else {
start.put(name, start, value);
}
}
public void put(int index, Scriptable start, Object value) {
if (start == this) {
Function func = getAdapteeFunction(PUT_PROP);
if( func != null) {
call(func, new Object[] { new Integer(index), value });
} else {
start = getAdaptee();
start.put(index, start, value);
}
} else {
start.put(index, start, value);
}
}
public void delete(String name) {
Function func = getAdapteeFunction(DEL_PROP);
if (func != null) {
call(func, new Object[] { name });
} else {
getAdaptee().delete(name);
}
}
public void delete(int index) {
Function func = getAdapteeFunction(DEL_PROP);
if (func != null) {
call(func, new Object[] { new Integer(index) });
} else {
getAdaptee().delete(index);
}
}
public Scriptable getPrototype() {
return prototype;
}
public void setPrototype(Scriptable prototype) {
this.prototype = prototype;
}
public Scriptable getParentScope() {
return parent;
}
public void setParentScope(Scriptable parent) {
this.parent = parent;
}
public Object[] getIds() {
Function func = getAdapteeFunction(GET_PROPIDS);
if (func != null) {
Object val = call(func, new Object[0]);
// in most cases, adaptee would return native JS array
if (val instanceof NativeArray) {
NativeArray array = (NativeArray) val;
Object[] res = new Object[(int)array.getLength()];
for (int index = 0; index < res.length; index++) {
res[index] = mapToId(array.get(index, array));
}
return res;
} else if (val instanceof NativeJavaArray) {
// may be attempt wrapped Java array
Object tmp = ((NativeJavaArray)val).unwrap();
Object[] res;
if (tmp.getClass() == Object[].class) {
Object[] array = (Object[]) tmp;
res = new Object[array.length];
for (int index = 0; index < array.length; index++) {
res[index] = mapToId(array[index]);
}
} else {
// just return an empty array
res = Context.emptyArgs;
}
return res;
} else {
// some other return type, just return empty array
return Context.emptyArgs;
}
} else {
return getAdaptee().getIds();
}
}
public boolean hasInstance(Scriptable scriptable) {
if (scriptable instanceof JSAdapter) {
return true;
} else {
Scriptable proto = scriptable.getPrototype();
while (proto != null) {
if (proto.equals(this)) return true;
proto = proto.getPrototype();
}
return false;
}
}
public Object getDefaultValue(Class hint) {
return getAdaptee().getDefaultValue(hint);
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
throws RhinoException {
if (isPrototype) {
return construct(cx, scope, args);
} else {
Scriptable tmp = getAdaptee();
if (tmp instanceof Function) {
return ((Function)tmp).call(cx, scope, tmp, args);
} else {
throw Context.reportRuntimeError("TypeError: not a function");
}
}
}
public Scriptable construct(Context cx, Scriptable scope, Object[] args)
throws RhinoException {
if (isPrototype) {
Scriptable topLevel = ScriptableObject.getTopLevelScope(scope);
JSAdapter newObj;
if (args.length > 0) {
newObj = new JSAdapter(Context.toObject(args[0], topLevel));
} else {
throw Context.reportRuntimeError("JSAdapter requires adaptee");
}
return newObj;
} else {
Scriptable tmp = getAdaptee();
if (tmp instanceof Function) {
return ((Function)tmp).construct(cx, scope, args);
} else {
throw Context.reportRuntimeError("TypeError: not a constructor");
}
}
}
public Scriptable getAdaptee() {
return adaptee;
}
public void setAdaptee(Scriptable adaptee) {
if (adaptee == null) {
throw new NullPointerException("adaptee can not be null");
}
this.adaptee = adaptee;
}
//-- internals only below this point
// map a property id. Property id can only be an Integer or String
private Object mapToId(Object tmp) {
if (tmp instanceof Double) {
return new Integer(((Double)tmp).intValue());
} else {
return Context.toString(tmp);
}
}
private static Scriptable getFunctionPrototype(Scriptable scope) {
return ScriptableObject.getFunctionPrototype(scope);
}
private Function getAdapteeFunction(String name) {
Object o = ScriptableObject.getProperty(getAdaptee(), name);
return (o instanceof Function)? (Function)o : null;
}
private Object call(Function func, Object[] args) {
Context cx = Context.getCurrentContext();
Scriptable thisObj = getAdaptee();
Scriptable scope = func.getParentScope();
try {
return func.call(cx, scope, thisObj, args);
} catch (RhinoException re) {
throw Context.reportRuntimeError(re.getMessage());
}
}
private Scriptable prototype;
private Scriptable parent;
private Scriptable adaptee;
private boolean isPrototype;
// names of adaptee JavaScript functions
private static final String GET_PROP = "__get__";
private static final String HAS_PROP = "__has__";
private static final String PUT_PROP = "__put__";
private static final String DEL_PROP = "__delete__";
private static final String GET_PROPIDS = "__getIds__";
}
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.javascript;
import javax.script.Invocable;
import sun.org.mozilla.javascript.internal.*;
/**
* This class implements Rhino-like JavaAdapter to help implement a Java
* interface in JavaScript. We support this using Invocable.getInterface.
* Using this JavaAdapter, script author could write:
*
* var r = new java.lang.Runnable() {
* run: function() { script... }
* };
*
* r.run();
* new java.lang.Thread(r).start();
*
* Note that Rhino's JavaAdapter support allows extending a Java class and/or
* implementing one or more interfaces. This JavaAdapter implementation does
* not support these.
*
* @author A. Sundararajan
* @since 1.6
*/
final class JavaAdapter extends ScriptableObject implements Function {
private JavaAdapter(Invocable engine) {
this.engine = engine;
}
static void init(Context cx, Scriptable scope, boolean sealed)
throws RhinoException {
RhinoTopLevel topLevel = (RhinoTopLevel) scope;
Invocable engine = topLevel.getScriptEngine();
JavaAdapter obj = new JavaAdapter(engine);
obj.setParentScope(scope);
obj.setPrototype(getFunctionPrototype(scope));
/*
* Note that we can't use defineProperty. A property of this
* name is already defined in Context.initStandardObjects. We
* simply overwrite the property value!
*/
ScriptableObject.putProperty(topLevel, "JavaAdapter", obj);
}
public String getClassName() {
return "JavaAdapter";
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args) throws RhinoException {
return construct(cx, scope, args);
}
public Scriptable construct(Context cx, Scriptable scope, Object[] args)
throws RhinoException {
if (args.length == 2) {
Class<?> clazz = null;
Object obj1 = args[0];
if (obj1 instanceof Wrapper) {
Object o = ((Wrapper)obj1).unwrap();
if (o instanceof Class && ((Class)o).isInterface()) {
clazz = (Class) o;
}
} else if (obj1 instanceof Class) {
if (((Class)obj1).isInterface()) {
clazz = (Class) obj1;
}
}
if (clazz == null) {
throw Context.reportRuntimeError("JavaAdapter: first arg should be interface Class");
}
Scriptable topLevel = ScriptableObject.getTopLevelScope(scope);
return cx.toObject(engine.getInterface(args[1], clazz), topLevel);
} else {
throw Context.reportRuntimeError("JavaAdapter requires two arguments");
}
}
private Invocable engine;
}
#script engines supported
com.sun.script.javascript.RhinoScriptEngineFactory #javascript
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.javascript;
import javax.script.*;
import sun.org.mozilla.javascript.internal.*;
/**
* Represents compiled JavaScript code.
*
* @author Mike Grogan
* @since 1.6
*/
final class RhinoCompiledScript extends CompiledScript {
private RhinoScriptEngine engine;
private Script script;
RhinoCompiledScript(RhinoScriptEngine engine, Script script) {
this.engine = engine;
this.script = script;
}
public Object eval(ScriptContext context) throws ScriptException {
Object result = null;
Context cx = RhinoScriptEngine.enterContext();
try {
Scriptable scope = engine.getRuntimeScope(context);
Object ret = script.exec(cx, scope);
result = engine.unwrapReturnValue(ret);
} catch (RhinoException re) {
int line = (line = re.lineNumber()) == 0 ? -1 : line;
String msg;
if (re instanceof JavaScriptException) {
msg = String.valueOf(((JavaScriptException)re).getValue());
} else {
msg = re.toString();
}
ScriptException se = new ScriptException(msg, re.sourceName(), line);
se.initCause(re);
throw se;
} finally {
Context.exit();
}
return result;
}
public ScriptEngine getEngine() {
return engine;
}
}
/*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.javascript;
import com.sun.script.util.*;
import javax.script.*;
import sun.org.mozilla.javascript.internal.*;
import java.lang.reflect.Method;
import java.io.*;
import java.util.*;
/**
* Implementation of <code>ScriptEngine</code> using the Mozilla Rhino
* interpreter.
*
* @author Mike Grogan
* @author A. Sundararajan
* @since 1.6
*/
public final class RhinoScriptEngine extends AbstractScriptEngine
implements Invocable, Compilable {
private static final boolean DEBUG = false;
/* Scope where standard JavaScript objects and our
* extensions to it are stored. Note that these are not
* user defined engine level global variables. These are
* variables have to be there on all compliant ECMAScript
* scopes. We put these standard objects in this top level.
*/
private RhinoTopLevel topLevel;
/* map used to store indexed properties in engine scope
* refer to comment on 'indexedProps' in ExternalScriptable.java.
*/
private Map<Object, Object> indexedProps;
private ScriptEngineFactory factory;
private InterfaceImplementor implementor;
private static final int languageVersion = getLanguageVersion();
private static final int optimizationLevel = getOptimizationLevel();
static {
ContextFactory.initGlobal(new ContextFactory() {
protected Context makeContext() {
Context cx = super.makeContext();
cx.setLanguageVersion(languageVersion);
cx.setOptimizationLevel(optimizationLevel);
cx.setClassShutter(RhinoClassShutter.getInstance());
cx.setWrapFactory(RhinoWrapFactory.getInstance());
return cx;
}
});
}
private static final String RHINO_JS_VERSION = "rhino.js.version";
private static int getLanguageVersion() {
int version;
String tmp = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(RHINO_JS_VERSION));
if (tmp != null) {
version = Integer.parseInt((String)tmp);
} else {
version = Context.VERSION_1_8;
}
return version;
}
private static final String RHINO_OPT_LEVEL = "rhino.opt.level";
private static int getOptimizationLevel() {
int optLevel = -1;
// disable optimizer under security manager, for now.
if (System.getSecurityManager() == null) {
optLevel = Integer.getInteger(RHINO_OPT_LEVEL, -1);
}
return optLevel;
}
/**
* Creates a new instance of RhinoScriptEngine
*/
public RhinoScriptEngine() {
Context cx = enterContext();
try {
topLevel = new RhinoTopLevel(cx, this);
} finally {
cx.exit();
}
indexedProps = new HashMap<Object, Object>();
//construct object used to implement getInterface
implementor = new InterfaceImplementor(this) {
protected boolean isImplemented(Object thiz, Class<?> iface) {
Context cx = enterContext();
try {
if (thiz != null && !(thiz instanceof Scriptable)) {
thiz = cx.toObject(thiz, topLevel);
}
Scriptable engineScope = getRuntimeScope(context);
Scriptable localScope = (thiz != null)? (Scriptable) thiz :
engineScope;
for (Method method : iface.getMethods()) {
// ignore methods of java.lang.Object class
if (method.getDeclaringClass() == Object.class) {
continue;
}
Object obj = ScriptableObject.getProperty(localScope, method.getName());
if (! (obj instanceof Function)) {
return false;
}
}
return true;
} finally {
cx.exit();
}
}
protected Object convertResult(Method method, Object res)
throws ScriptException {
Class desiredType = method.getReturnType();
if (desiredType == Void.TYPE) {
return null;
} else {
return Context.jsToJava(res, desiredType);
}
}
};
}
public Object eval(Reader reader, ScriptContext ctxt)
throws ScriptException {
Object ret;
Context cx = enterContext();
try {
Scriptable scope = getRuntimeScope(ctxt);
String filename = (String) get(ScriptEngine.FILENAME);
filename = filename == null ? "<Unknown source>" : filename;
ret = cx.evaluateReader(scope, reader, filename , 1, null);
} catch (RhinoException re) {
if (DEBUG) re.printStackTrace();
int line = (line = re.lineNumber()) == 0 ? -1 : line;
String msg;
if (re instanceof JavaScriptException) {
msg = String.valueOf(((JavaScriptException)re).getValue());
} else {
msg = re.toString();
}
ScriptException se = new ScriptException(msg, re.sourceName(), line);
se.initCause(re);
throw se;
} catch (IOException ee) {
throw new ScriptException(ee);
} finally {
cx.exit();
}
return unwrapReturnValue(ret);
}
public Object eval(String script, ScriptContext ctxt) throws ScriptException {
if (script == null) {
throw new NullPointerException("null script");
}
return eval(new StringReader(script) , ctxt);
}
public ScriptEngineFactory getFactory() {
if (factory != null) {
return factory;
} else {
return new RhinoScriptEngineFactory();
}
}
public Bindings createBindings() {
return new SimpleBindings();
}
//Invocable methods
public Object invokeFunction(String name, Object... args)
throws ScriptException, NoSuchMethodException {
return invoke(null, name, args);
}
public Object invokeMethod(Object thiz, String name, Object... args)
throws ScriptException, NoSuchMethodException {
if (thiz == null) {
throw new IllegalArgumentException("script object can not be null");
}
return invoke(thiz, name, args);
}
private Object invoke(Object thiz, String name, Object... args)
throws ScriptException, NoSuchMethodException {
Context cx = enterContext();
try {
if (name == null) {
throw new NullPointerException("method name is null");
}
if (thiz != null && !(thiz instanceof Scriptable)) {
thiz = cx.toObject(thiz, topLevel);
}
Scriptable engineScope = getRuntimeScope(context);
Scriptable localScope = (thiz != null)? (Scriptable) thiz :
engineScope;
Object obj = ScriptableObject.getProperty(localScope, name);
if (! (obj instanceof Function)) {
throw new NoSuchMethodException("no such method: " + name);
}
Function func = (Function) obj;
Scriptable scope = func.getParentScope();
if (scope == null) {
scope = engineScope;
}
Object result = func.call(cx, scope, localScope,
wrapArguments(args));
return unwrapReturnValue(result);
} catch (RhinoException re) {
if (DEBUG) re.printStackTrace();
int line = (line = re.lineNumber()) == 0 ? -1 : line;
ScriptException se = new ScriptException(re.toString(), re.sourceName(), line);
se.initCause(re);
throw se;
} finally {
cx.exit();
}
}
public <T> T getInterface(Class<T> clasz) {
try {
return implementor.getInterface(null, clasz);
} catch (ScriptException e) {
return null;
}
}
public <T> T getInterface(Object thiz, Class<T> clasz) {
if (thiz == null) {
throw new IllegalArgumentException("script object can not be null");
}
try {
return implementor.getInterface(thiz, clasz);
} catch (ScriptException e) {
return null;
}
}
private static final String printSource =
"function print(str, newline) { \n" +
" if (typeof(str) == 'undefined') { \n" +
" str = 'undefined'; \n" +
" } else if (str == null) { \n" +
" str = 'null'; \n" +
" } \n" +
" var out = context.getWriter(); \n" +
" if (!(out instanceof java.io.PrintWriter))\n" +
" out = new java.io.PrintWriter(out); \n" +
" out.print(String(str)); \n" +
" if (newline) out.print('\\n'); \n" +
" out.flush(); \n" +
"}\n" +
"function println(str) { \n" +
" print(str, true); \n" +
"}";
Scriptable getRuntimeScope(ScriptContext ctxt) {
if (ctxt == null) {
throw new NullPointerException("null script context");
}
// we create a scope for the given ScriptContext
Scriptable newScope = new ExternalScriptable(ctxt, indexedProps);
// Set the prototype of newScope to be 'topLevel' so that
// JavaScript standard objects are visible from the scope.
newScope.setPrototype(topLevel);
// define "context" variable in the new scope
newScope.put("context", newScope, ctxt);
// define "print", "println" functions in the new scope
Context cx = enterContext();
try {
cx.evaluateString(newScope, printSource, "print", 1, null);
} finally {
cx.exit();
}
return newScope;
}
//Compilable methods
public CompiledScript compile(String script) throws ScriptException {
return compile(new StringReader(script));
}
public CompiledScript compile(java.io.Reader script) throws ScriptException {
CompiledScript ret = null;
Context cx = enterContext();
try {
String fileName = (String) get(ScriptEngine.FILENAME);
if (fileName == null) {
fileName = "<Unknown Source>";
}
Scriptable scope = getRuntimeScope(context);
Script scr = cx.compileReader(scope, script, fileName, 1, null);
ret = new RhinoCompiledScript(this, scr);
} catch (Exception e) {
if (DEBUG) e.printStackTrace();
throw new ScriptException(e);
} finally {
cx.exit();
}
return ret;
}
//package-private helpers
static Context enterContext() {
// call this always so that initializer of this class runs
// and initializes custom wrap factory and class shutter.
return Context.enter();
}
void setEngineFactory(ScriptEngineFactory fac) {
factory = fac;
}
Object[] wrapArguments(Object[] args) {
if (args == null) {
return Context.emptyArgs;
}
Object[] res = new Object[args.length];
for (int i = 0; i < res.length; i++) {
res[i] = Context.javaToJS(args[i], topLevel);
}
return res;
}
Object unwrapReturnValue(Object result) {
if (result instanceof Wrapper) {
result = ( (Wrapper) result).unwrap();
}
return result instanceof Undefined ? null : result;
}
/*
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("No file specified");
return;
}
InputStreamReader r = new InputStreamReader(new FileInputStream(args[0]));
ScriptEngine engine = new RhinoScriptEngine();
engine.put("x", "y");
engine.put(ScriptEngine.FILENAME, args[0]);
engine.eval(r);
System.out.println(engine.get("x"));
}
*/
}
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.javascript;
import javax.script.*;
import java.util.*;
import sun.org.mozilla.javascript.internal.*;
import com.sun.script.util.*;
/**
* Factory to create RhinoScriptEngine
*
* @author Mike Grogan
* @since 1.6
*/
public class RhinoScriptEngineFactory extends ScriptEngineFactoryBase {
public RhinoScriptEngineFactory() {
}
public List<String> getExtensions() {
return extensions;
}
public List<String> getMimeTypes() {
return mimeTypes;
}
public List<String> getNames() {
return names;
}
public Object getParameter(String key) {
if (key.equals(ScriptEngine.NAME)) {
return "javascript";
} else if (key.equals(ScriptEngine.ENGINE)) {
return "Mozilla Rhino";
} else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
return "1.7 release 3 PRERELEASE";
} else if (key.equals(ScriptEngine.LANGUAGE)) {
return "ECMAScript";
} else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
return "1.8";
} else if (key.equals("THREADING")) {
return "MULTITHREADED";
} else {
throw new IllegalArgumentException("Invalid key");
}
}
public ScriptEngine getScriptEngine() {
RhinoScriptEngine ret = new RhinoScriptEngine();
ret.setEngineFactory(this);
return ret;
}
public String getMethodCallSyntax(String obj, String method, String... args) {
String ret = obj + "." + method + "(";
int len = args.length;
if (len == 0) {
ret += ")";
return ret;
}
for (int i = 0; i < len; i++) {
ret += args[i];
if (i != len - 1) {
ret += ",";
} else {
ret += ")";
}
}
return ret;
}
public String getOutputStatement(String toDisplay) {
StringBuffer buf = new StringBuffer();
int len = toDisplay.length();
buf.append("print(\"");
for (int i = 0; i < len; i++) {
char ch = toDisplay.charAt(i);
switch (ch) {
case '"':
buf.append("\\\"");
break;
case '\\':
buf.append("\\\\");
break;
default:
buf.append(ch);
break;
}
}
buf.append("\")");
return buf.toString();
}
public String getProgram(String... statements) {
int len = statements.length;
String ret = "";
for (int i = 0; i < len; i++) {
ret += statements[i] + ";";
}
return ret;
}
/*
public static void main(String[] args) {
RhinoScriptEngineFactory fact = new RhinoScriptEngineFactory();
System.out.println(fact.getParameter(ScriptEngine.ENGINE_VERSION));
}
*/
private static List<String> names;
private static List<String> mimeTypes;
private static List<String> extensions;
static {
names = new ArrayList<String>(6);
names.add("js");
names.add("rhino");
names.add("JavaScript");
names.add("javascript");
names.add("ECMAScript");
names.add("ecmascript");
names = Collections.unmodifiableList(names);
mimeTypes = new ArrayList<String>(4);
mimeTypes.add("application/javascript");
mimeTypes.add("application/ecmascript");
mimeTypes.add("text/javascript");
mimeTypes.add("text/ecmascript");
mimeTypes = Collections.unmodifiableList(mimeTypes);
extensions = new ArrayList<String>(1);
extensions.add("js");
extensions = Collections.unmodifiableList(extensions);
}
}
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.javascript;
import sun.org.mozilla.javascript.internal.*;
import javax.script.*;
/**
* This class serves as top level scope for Rhino. This class adds
* 3 top level functions (bindings, scope, sync) and two constructors
* (JSAdapter, JavaAdapter).
*
* @author A. Sundararajan
* @since 1.6
*/
public final class RhinoTopLevel extends ImporterTopLevel {
RhinoTopLevel(Context cx, RhinoScriptEngine engine) {
super(cx);
this.engine = engine;
// initialize JSAdapter lazily. Reduces footprint & startup time.
new LazilyLoadedCtor(this, "JSAdapter",
"com.sun.script.javascript.JSAdapter",
false);
/*
* initialize JavaAdapter. We can't lazy initialize this because
* lazy initializer attempts to define a new property. But, JavaAdapter
* is an exisiting property that we overwrite.
*/
JavaAdapter.init(cx, this, false);
// add top level functions
String names[] = { "bindings", "scope", "sync" };
defineFunctionProperties(names, RhinoTopLevel.class,
ScriptableObject.DONTENUM);
}
/**
* The bindings function takes a JavaScript scope object
* of type ExternalScriptable and returns the underlying Bindings
* instance.
*
* var page = scope(pageBindings);
* with (page) {
* // code that uses page scope
* }
* var b = bindings(page);
* // operate on bindings here.
*/
public static Object bindings(Context cx, Scriptable thisObj, Object[] args,
Function funObj) {
if (args.length == 1) {
Object arg = args[0];
if (arg instanceof Wrapper) {
arg = ((Wrapper)arg).unwrap();
}
if (arg instanceof ExternalScriptable) {
ScriptContext ctx = ((ExternalScriptable)arg).getContext();
Bindings bind = ctx.getBindings(ScriptContext.ENGINE_SCOPE);
return Context.javaToJS(bind,
ScriptableObject.getTopLevelScope(thisObj));
}
}
return cx.getUndefinedValue();
}
/**
* The scope function creates a new JavaScript scope object
* with given Bindings object as backing store. This can be used
* to create a script scope based on arbitrary Bindings instance.
* For example, in webapp scenario, a 'page' level Bindings instance
* may be wrapped as a scope and code can be run in JavaScripe 'with'
* statement:
*
* var page = scope(pageBindings);
* with (page) {
* // code that uses page scope
* }
*/
public static Object scope(Context cx, Scriptable thisObj, Object[] args,
Function funObj) {
if (args.length == 1) {
Object arg = args[0];
if (arg instanceof Wrapper) {
arg = ((Wrapper)arg).unwrap();
}
if (arg instanceof Bindings) {
ScriptContext ctx = new SimpleScriptContext();
ctx.setBindings((Bindings)arg, ScriptContext.ENGINE_SCOPE);
Scriptable res = new ExternalScriptable(ctx);
res.setPrototype(ScriptableObject.getObjectPrototype(thisObj));
res.setParentScope(ScriptableObject.getTopLevelScope(thisObj));
return res;
}
}
return cx.getUndefinedValue();
}
/**
* The sync function creates a synchronized function (in the sense
* of a Java synchronized method) from an existing function. The
* new function synchronizes on the <code>this</code> object of
* its invocation.
* js> var o = { f : sync(function(x) {
* print("entry");
* Packages.java.lang.Thread.sleep(x*1000);
* print("exit");
* })};
* js> thread(function() {o.f(5);});
* entry
* js> thread(function() {o.f(5);});
* js>
* exit
* entry
* exit
*/
public static Object sync(Context cx, Scriptable thisObj, Object[] args,
Function funObj) {
if (args.length == 1 && args[0] instanceof Function) {
return new Synchronizer((Function)args[0]);
} else {
throw Context.reportRuntimeError("wrong argument(s) for sync");
}
}
RhinoScriptEngine getScriptEngine() {
return engine;
}
private RhinoScriptEngine engine;
}
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.javascript;
import java.lang.reflect.*;
import static sun.security.util.SecurityConstants.*;
import sun.org.mozilla.javascript.internal.*;
/**
* This wrap factory is used for security reasons. JSR 223 script
* engine interface and JavaScript engine classes are run as bootstrap
* classes. For example, java.lang.Class.forName method (when called without
* class loader) uses caller's class loader. This may be exploited by script
* authors to access classes otherwise not accessible. For example,
* classes in sun.* namespace are normally not accessible to untrusted
* code and hence should not be accessible to JavaScript run from
* untrusted code.
*
* @author A. Sundararajan
* @since 1.6
*/
final class RhinoWrapFactory extends WrapFactory {
private RhinoWrapFactory() {}
private static RhinoWrapFactory theInstance;
static synchronized WrapFactory getInstance() {
if (theInstance == null) {
theInstance = new RhinoWrapFactory();
}
return theInstance;
}
// We use instance of this class to wrap security sensitive
// Java object. Please refer below.
private static class RhinoJavaObject extends NativeJavaObject {
RhinoJavaObject(Scriptable scope, Object obj, Class type) {
// we pass 'null' to object. NativeJavaObject uses
// passed 'type' to reflect fields and methods when
// object is null.
super(scope, null, type);
// Now, we set actual object. 'javaObject' is protected
// field of NativeJavaObject.
javaObject = obj;
}
}
public Scriptable wrapAsJavaObject(Context cx, Scriptable scope,
Object javaObject, Class staticType) {
SecurityManager sm = System.getSecurityManager();
ClassShutter classShutter = RhinoClassShutter.getInstance();
if (javaObject instanceof ClassLoader) {
// Check with Security Manager whether we can expose a
// ClassLoader...
if (sm != null) {
sm.checkPermission(GET_CLASSLOADER_PERMISSION);
}
// if we fall through here, check permission succeeded.
return super.wrapAsJavaObject(cx, scope, javaObject, staticType);
} else {
String name = null;
if (javaObject instanceof Class) {
name = ((Class)javaObject).getName();
} else if (javaObject instanceof Member) {
Member member = (Member) javaObject;
// Check member access. Don't allow reflective access to
// non-public members. Note that we can't call checkMemberAccess
// because that expects exact stack depth!
if (sm != null && !Modifier.isPublic(member.getModifiers())) {
return null;
}
name = member.getDeclaringClass().getName();
}
// Now, make sure that no ClassShutter prevented Class or Member
// of it is accessed reflectively. Note that ClassShutter may
// prevent access to a class, even though SecurityManager permit.
if (name != null) {
if (!classShutter.visibleToScripts(name)) {
return null;
} else {
return super.wrapAsJavaObject(cx, scope, javaObject, staticType);
}
}
}
// we have got some non-reflective object.
Class dynamicType = javaObject.getClass();
String name = dynamicType.getName();
if (!classShutter.visibleToScripts(name)) {
// Object of some sensitive class (such as sun.net.www.*
// objects returned from public method of java.net.URL class.
// We expose this object as though it is an object of some
// super class that is safe for access.
Class type = null;
// Whenever a Java Object is wrapped, we are passed with a
// staticType which is the type found from environment. For
// example, method return type known from signature. The dynamic
// type would be the actual Class of the actual returned object.
// If the staticType is an interface, we just use that type.
if (staticType != null && staticType.isInterface()) {
type = staticType;
} else {
// dynamicType is always a class type and never an interface.
// find an accessible super class of the dynamic type.
while (dynamicType != null) {
dynamicType = dynamicType.getSuperclass();
name = dynamicType.getName();
if (classShutter.visibleToScripts(name)) {
type = dynamicType; break;
}
}
// atleast java.lang.Object has to be accessible. So, when
// we reach here, type variable should not be null.
assert type != null:
"even java.lang.Object is not accessible?";
}
// create custom wrapper with the 'safe' type.
return new RhinoJavaObject(scope, javaObject, type);
} else {
return super.wrapAsJavaObject(cx, scope, javaObject, staticType);
}
}
}
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.util;
import javax.script.Bindings;
import java.util.Map;
import java.util.AbstractMap;
/**
* Abstract super class for Bindings implementations
*
* @author Mike Grogan
* @since 1.6
*/
public abstract class BindingsBase extends AbstractMap<String, Object>
implements Bindings {
//AbstractMap methods
public Object get(Object name) {
checkKey(name);
return getImpl((String)name);
}
public Object remove(Object key) {
checkKey(key);
return removeImpl((String)key);
}
public Object put(String key, Object value) {
checkKey(key);
return putImpl(key, value);
}
public void putAll(Map<? extends String, ? extends Object> toMerge) {
for (Map.Entry<? extends String, ? extends Object> entry : toMerge.entrySet()) {
String key = entry.getKey();
checkKey(key);
putImpl(entry.getKey(), entry.getValue());
}
}
//BindingsBase methods
public abstract Object putImpl(String name, Object value);
public abstract Object getImpl(String name);
public abstract Object removeImpl(String name);
public abstract String[] getNames();
protected void checkKey(Object key) {
if (key == null) {
throw new NullPointerException("key can not be null");
}
if (!(key instanceof String)) {
throw new ClassCastException("key should be String");
}
if (key.equals("")) {
throw new IllegalArgumentException("key can not be empty");
}
}
}
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.util;
import java.util.*;
/**
* Entry set implementation for Bindings implementations
*
* @author Mike Grogan
* @since 1.6
*/
public class BindingsEntrySet extends AbstractSet<Map.Entry<String, Object>> {
private BindingsBase base;
private String[] keys;
public BindingsEntrySet(BindingsBase base) {
this.base = base;
keys = base.getNames();
}
public int size() {
return keys.length;
}
public Iterator<Map.Entry<String, Object>> iterator() {
return new BindingsIterator();
}
public class BindingsEntry implements Map.Entry<String, Object> {
private String key;
public BindingsEntry(String key) {
this.key = key;
}
public Object setValue(Object value) {
throw new UnsupportedOperationException();
}
public String getKey() {
return key;
}
public Object getValue() {
return base.get(key);
}
}
public class BindingsIterator implements Iterator<Map.Entry<String, Object>> {
private int current = 0;
private boolean stale = false;
public boolean hasNext() {
return (current < keys.length);
}
public BindingsEntry next() {
stale = false;
return new BindingsEntry(keys[current++]);
}
public void remove() {
if (stale || current == 0) {
throw new IllegalStateException();
}
stale = true;
base.remove(keys[current - 1]);
}
}
}
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.util;
import java.util.*;
import javax.script.Bindings;
/*
* Abstract super class for Bindings implementations. Handles
* global and local scopes.
*
* @author Mike Grogan
* @since 1.6
*/
public abstract class BindingsImpl extends BindingsBase {
//get method delegates to global if key is not defined in
//base class or local scope
protected Bindings global = null;
//get delegates to local scope
protected Bindings local = null;
public void setGlobal(Bindings n) {
global = n;
}
public void setLocal(Bindings n) {
local = n;
}
public Set<Map.Entry<String, Object>> entrySet() {
return new BindingsEntrySet(this);
}
public Object get(Object key) {
checkKey(key);
Object ret = null;
if ((local != null) && (null != (ret = local.get(key)))) {
return ret;
}
ret = getImpl((String)key);
if (ret != null) {
return ret;
} else if (global != null) {
return global.get(key);
} else {
return null;
}
}
public Object remove(Object key) {
checkKey(key);
Object ret = get(key);
if (ret != null) {
removeImpl((String)key);
}
return ret;
}
}
/*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.util;
import javax.script.*;
import java.lang.reflect.*;
import java.security.*;
/*
* java.lang.reflect.Proxy based interface implementor. This is meant
* to be used to implement Invocable.getInterface.
*
* @author Mike Grogan
* @since 1.6
*/
public class InterfaceImplementor {
private Invocable engine;
/** Creates a new instance of Invocable */
public InterfaceImplementor(Invocable engine) {
this.engine = engine;
}
private final class InterfaceImplementorInvocationHandler
implements InvocationHandler {
private Object thiz;
private AccessControlContext accCtxt;
public InterfaceImplementorInvocationHandler(Object thiz,
AccessControlContext accCtxt) {
this.thiz = thiz;
this.accCtxt = accCtxt;
}
public Object invoke(Object proxy , Method method, Object[] args)
throws java.lang.Throwable {
// give chance to convert input args
args = convertArguments(method, args);
Object result;
final Method m = method;
final Object[] a = args;
result = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
if (thiz == null) {
return engine.invokeFunction(m.getName(), a);
} else {
return engine.invokeMethod(thiz, m.getName(), a);
}
}
}, accCtxt);
// give chance to convert the method result
return convertResult(method, result);
}
}
public <T> T getInterface(Object thiz, Class<T> iface)
throws ScriptException {
if (iface == null || !iface.isInterface()) {
throw new IllegalArgumentException("interface Class expected");
}
if (! isImplemented(thiz, iface)) {
return null;
}
AccessControlContext accCtxt = AccessController.getContext();
return iface.cast(Proxy.newProxyInstance(iface.getClassLoader(),
new Class[]{iface},
new InterfaceImplementorInvocationHandler(thiz, accCtxt)));
}
protected boolean isImplemented(Object thiz, Class<?> iface) {
return true;
}
// called to convert method result after invoke
protected Object convertResult(Method method, Object res)
throws ScriptException {
// default is identity conversion
return res;
}
// called to convert method arguments before invoke
protected Object[] convertArguments(Method method, Object[] args)
throws ScriptException {
// default is identity conversion
return args;
}
}
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.script.util;
import javax.script.*;
/*
* Abstract super class for factory implementations.
*
* @author Mike Grogan
* @since 1.6
*/
public abstract class ScriptEngineFactoryBase implements ScriptEngineFactory {
public String getName() {
return (String)getParameter(ScriptEngine.NAME);
}
public String getEngineName() {
return (String)getParameter(ScriptEngine.ENGINE);
}
public String getEngineVersion() {
return (String)getParameter(ScriptEngine.ENGINE_VERSION);
}
public String getLanguageName() {
return (String)getParameter(ScriptEngine.LANGUAGE);
}
public String getLanguageVersion() {
return (String)getParameter(ScriptEngine.LANGUAGE_VERSION);
}
}
/* /*
* Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -27,6 +27,7 @@ package java.util.zip; ...@@ -27,6 +27,7 @@ package java.util.zip;
import java.io.SequenceInputStream; import java.io.SequenceInputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.IOException; import java.io.IOException;
import java.io.EOFException; import java.io.EOFException;
...@@ -212,7 +213,10 @@ class GZIPInputStream extends InflaterInputStream { ...@@ -212,7 +213,10 @@ class GZIPInputStream extends InflaterInputStream {
int n = inf.getRemaining(); int n = inf.getRemaining();
if (n > 0) { if (n > 0) {
in = new SequenceInputStream( in = new SequenceInputStream(
new ByteArrayInputStream(buf, len - n, n), in); new ByteArrayInputStream(buf, len - n, n),
new FilterInputStream(in) {
public void close() throws IOException {}
});
} }
// Uses left-to-right evaluation order // Uses left-to-right evaluation order
if ((readUInt(in) != crc.getValue()) || if ((readUInt(in) != crc.getValue()) ||
......
/* /*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -27,7 +27,7 @@ package sun.reflect.generics.reflectiveObjects; ...@@ -27,7 +27,7 @@ package sun.reflect.generics.reflectiveObjects;
import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Objects;
/** /**
* Implementation of GenericArrayType interface for core reflection. * Implementation of GenericArrayType interface for core reflection.
...@@ -81,18 +81,13 @@ public class GenericArrayTypeImpl ...@@ -81,18 +81,13 @@ public class GenericArrayTypeImpl
if (o instanceof GenericArrayType) { if (o instanceof GenericArrayType) {
GenericArrayType that = (GenericArrayType) o; GenericArrayType that = (GenericArrayType) o;
Type thatComponentType = that.getGenericComponentType(); return Objects.equals(genericComponentType, that.getGenericComponentType());
return genericComponentType == null ?
thatComponentType == null :
genericComponentType.equals(thatComponentType);
} else } else
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return (genericComponentType == null) ? return Objects.hashCode(genericComponentType);
0:
genericComponentType.hashCode();
} }
} }
/* /*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -33,7 +33,7 @@ import java.lang.reflect.ParameterizedType; ...@@ -33,7 +33,7 @@ import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable; import java.lang.reflect.TypeVariable;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects;
/** Implementing class for ParameterizedType interface. */ /** Implementing class for ParameterizedType interface. */
...@@ -47,9 +47,7 @@ public class ParameterizedTypeImpl implements ParameterizedType { ...@@ -47,9 +47,7 @@ public class ParameterizedTypeImpl implements ParameterizedType {
Type ownerType) { Type ownerType) {
this.actualTypeArguments = actualTypeArguments; this.actualTypeArguments = actualTypeArguments;
this.rawType = rawType; this.rawType = rawType;
if (ownerType != null) { this.ownerType = (ownerType != null) ? ownerType : rawType.getDeclaringClass();
this.ownerType = ownerType;
} else { this.ownerType = rawType.getDeclaringClass();}
validateConstructorArguments(); validateConstructorArguments();
} }
...@@ -62,7 +60,6 @@ public class ParameterizedTypeImpl implements ParameterizedType { ...@@ -62,7 +60,6 @@ public class ParameterizedTypeImpl implements ParameterizedType {
for (int i = 0; i < actualTypeArguments.length; i++) { for (int i = 0; i < actualTypeArguments.length; i++) {
// check actuals against formals' bounds // check actuals against formals' bounds
} }
} }
/** /**
...@@ -189,14 +186,9 @@ public class ParameterizedTypeImpl implements ParameterizedType { ...@@ -189,14 +186,9 @@ public class ParameterizedTypeImpl implements ParameterizedType {
return ownerEquality && rawEquality && typeArgEquality; return ownerEquality && rawEquality && typeArgEquality;
} }
return return
(ownerType == null ? Objects.equals(ownerType, thatOwner) &&
thatOwner == null : Objects.equals(rawType, thatRawType) &&
ownerType.equals(thatOwner)) &&
(rawType == null ?
thatRawType == null :
rawType.equals(thatRawType)) &&
Arrays.equals(actualTypeArguments, // avoid clone Arrays.equals(actualTypeArguments, // avoid clone
that.getActualTypeArguments()); that.getActualTypeArguments());
} else } else
...@@ -207,8 +199,8 @@ public class ParameterizedTypeImpl implements ParameterizedType { ...@@ -207,8 +199,8 @@ public class ParameterizedTypeImpl implements ParameterizedType {
public int hashCode() { public int hashCode() {
return return
Arrays.hashCode(actualTypeArguments) ^ Arrays.hashCode(actualTypeArguments) ^
(ownerType == null ? 0 : ownerType.hashCode() ) ^ Objects.hashCode(ownerType) ^
(rawType == null ? 0 : rawType.hashCode() ); Objects.hashCode(rawType);
} }
public String toString() { public String toString() {
...@@ -239,10 +231,7 @@ public class ParameterizedTypeImpl implements ParameterizedType { ...@@ -239,10 +231,7 @@ public class ParameterizedTypeImpl implements ParameterizedType {
for(Type t: actualTypeArguments) { for(Type t: actualTypeArguments) {
if (!first) if (!first)
sb.append(", "); sb.append(", ");
if (t instanceof Class) sb.append(t.getTypeName());
sb.append(((Class)t).getName());
else
sb.append(t.toString());
first = false; first = false;
} }
sb.append(">"); sb.append(">");
......
...@@ -170,13 +170,8 @@ public class TypeVariableImpl<D extends GenericDeclaration> ...@@ -170,13 +170,8 @@ public class TypeVariableImpl<D extends GenericDeclaration>
GenericDeclaration thatDecl = that.getGenericDeclaration(); GenericDeclaration thatDecl = that.getGenericDeclaration();
String thatName = that.getName(); String thatName = that.getName();
return return Objects.equals(genericDeclaration, thatDecl) &&
(genericDeclaration == null ? Objects.equals(name, thatName);
thatDecl == null :
genericDeclaration.equals(thatDecl)) &&
(name == null ?
thatName == null :
name.equals(thatName));
} else } else
return false; return false;
......
/* /*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -203,10 +203,7 @@ public class WildcardTypeImpl extends LazyReflectiveObjectGenerator ...@@ -203,10 +203,7 @@ public class WildcardTypeImpl extends LazyReflectiveObjectGenerator
sb.append(" & "); sb.append(" & ");
first = false; first = false;
if (bound instanceof Class) sb.append(bound.getTypeName());
sb.append(((Class)bound).getName() );
else
sb.append(bound.toString());
} }
return sb.toString(); return sb.toString();
} }
......
/* /*
* Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -822,7 +822,7 @@ final class SSLSessionImpl extends ExtendedSSLSession { ...@@ -822,7 +822,7 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* them are removed. * them are removed.
*/ */
@Override @Override
public void finalize() { protected void finalize() throws Throwable {
String[] names = getValueNames(); String[] names = getValueNames();
for (int i = 0; i < names.length; i++) { for (int i = 0; i < names.length; i++) {
removeValue(names[i]); removeValue(names[i]);
......
/* /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as * under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this * published by the Free Software Foundation.
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
* *
* This code is distributed in the hope that it will be useful, but WITHOUT * This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
...@@ -23,53 +21,76 @@ ...@@ -23,53 +21,76 @@
* questions. * questions.
*/ */
package com.sun.script.javascript; /* @test
* @bug 7021870
* @summary Reading last gzip chain member must not close the input stream
*/
import java.io.*;
import java.util.*; import java.util.*;
import sun.org.mozilla.javascript.internal.*; import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* This class prevents script access to certain sensitive classes.
* Note that this class checks over and above SecurityManager. i.e., although
* a SecurityManager would pass, class shutter may still prevent access.
*
* @author A. Sundararajan
* @since 1.6
*/
final class RhinoClassShutter implements ClassShutter {
private static Map<String, Boolean> protectedClasses;
private static RhinoClassShutter theInstance;
private RhinoClassShutter() { public class GZIPInZip {
}
static synchronized ClassShutter getInstance() { private static volatile Throwable trouble;
if (theInstance == null) {
theInstance = new RhinoClassShutter(); public static void main(String[] args) throws Throwable {
protectedClasses = new HashMap<String, Boolean>();
final PipedOutputStream pos = new PipedOutputStream();
// For now, we just have AccessController. Allowing scripts final PipedInputStream pis = new PipedInputStream(pos);
// to this class will allow it to execute doPrivileged in
// bootstrap context. We can add more classes for other reasons. Thread compressor = new Thread() {
protectedClasses.put("java.security.AccessController", Boolean.TRUE); public void run() {
} final byte[] xbuf = { 'x' };
return theInstance; try {
} ZipOutputStream zos = new ZipOutputStream(pos);
public boolean visibleToScripts(String fullClassName) { zos.putNextEntry(new ZipEntry("a.gz"));
// first do the security check. GZIPOutputStream gos1 = new GZIPOutputStream(zos);
SecurityManager sm = System.getSecurityManager(); gos1.write(xbuf); gos1.finish();
if (sm != null) { zos.closeEntry();
int i = fullClassName.lastIndexOf(".");
if (i != -1) { zos.putNextEntry(new ZipEntry("b.gz"));
GZIPOutputStream gos2 = new GZIPOutputStream(zos);
gos2.write(xbuf); gos2.finish();
zos.closeEntry();
} catch (Throwable t) {
trouble = t;
}
}
};
Thread uncompressor = new Thread() {
public void run() {
try { try {
sm.checkPackageAccess(fullClassName.substring(0, i)); ZipInputStream zis = new ZipInputStream(pis);
} catch (SecurityException se) { zis.getNextEntry();
return false; InputStream gis = new GZIPInputStream(zis);
// try to read more than the entry has
gis.skip(2);
try {
zis.getNextEntry();
} catch (IOException e) {
throw new AssertionError("ZIP stream was prematurely closed");
}
} catch (Throwable t) {
trouble = t;
} }
} }
} };
// now, check is it a protected class.
return protectedClasses.get(fullClassName) == null; compressor.start(); uncompressor.start();
compressor.join(); uncompressor.join();
if (trouble != null)
throw trouble;
} }
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册