├── .github └── workflows │ └── gradle.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── nexusConfig.gradle ├── settings.gradle └── sun-dependencies ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src ├── main ├── java │ ├── com │ │ └── sun │ │ │ └── script │ │ │ ├── javascript │ │ │ ├── ExternalScriptable.java │ │ │ ├── JSAdapter.java │ │ │ ├── JavaAdapter.java │ │ │ ├── RhinoClassShutter.java │ │ │ ├── RhinoCompiledScript.java │ │ │ ├── RhinoScriptEngine.java │ │ │ ├── RhinoScriptEngineFactory.java │ │ │ ├── RhinoTopLevel.java │ │ │ └── RhinoWrapFactory.java │ │ │ └── util │ │ │ ├── InterfaceImplementor.java │ │ │ └── ScriptEngineFactoryBase.java │ └── sun │ │ ├── misc │ │ ├── Service.java │ │ ├── ServiceConfigurationError.java │ │ └── VM.java │ │ ├── reflect │ │ └── Reflection.java │ │ └── security │ │ ├── action │ │ └── GetPropertyAction.java │ │ └── util │ │ ├── PermissionFactory.java │ │ └── SecurityConstants.java └── resources │ └── META-INF │ └── services │ └── javax.script.ScriptEngineFactory └── test └── java └── io └── apisense └── scriptengine └── RhinoTests.java /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | # This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time 6 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle 7 | 8 | name: Java CI with Gradle 9 | on: 10 | push: 11 | tags: 12 | - 'v*' 13 | jobs: 14 | build: 15 | environment: maven 16 | runs-on: ubuntu-latest 17 | permissions: 18 | contents: read 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: Set up JDK 8 22 | uses: actions/setup-java@v4 23 | with: 24 | java-version: '8' 25 | distribution: 'temurin' 26 | # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. 27 | # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md 28 | - name: Setup Gradle 29 | uses: gradle/actions/setup-gradle@af1da67850ed9a4cedd57bfd976089dd991e2582 # v4.0.0 30 | - name: setup push config 31 | run: | 32 | echo "nexusUrl=${{ vars.NEXUSURL }}" > local.properties 33 | echo "nexusUsername=${{ secrets.NEXUSUSERNAME }}" >> local.properties 34 | echo "nexusPassword=${{ secrets.NEXUSPASSWORD }}" >> local.properties 35 | - name: Build with Gradle Wrapper 36 | run: ./gradlew uploadArchive 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Intellij 2 | *.iml 3 | .idea 4 | 5 | # Build 6 | .gradle 7 | /gradle.properties 8 | /local.properties 9 | /build 10 | /captures 11 | 12 | # OS Specific 13 | .DS_Store 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | dist: trusty 3 | jdk: 4 | - oraclejdk8 5 | after_success: 6 | - bash <(curl -s https://codecov.io/bash) 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The GNU General Public License (GPL) 2 | 3 | Version 2, June 1991 4 | 5 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 6 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this license 9 | document, but changing it is not allowed. 10 | 11 | Preamble 12 | 13 | The licenses for most software are designed to take away your freedom to share 14 | and change it. By contrast, the GNU General Public License is intended to 15 | guarantee your freedom to share and change free software--to make sure the 16 | software is free for all its users. This General Public License applies to 17 | most of the Free Software Foundation's software and to any other program whose 18 | authors commit to using it. (Some other Free Software Foundation software is 19 | covered by the GNU Library General Public License instead.) You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not price. Our 23 | General Public Licenses are designed to make sure that you have the freedom to 24 | distribute copies of free software (and charge for this service if you wish), 25 | that you receive source code or can get it if you want it, that you can change 26 | the software or use pieces of it in new free programs; and that you know you 27 | can do these things. 28 | 29 | To protect your rights, we need to make restrictions that forbid anyone to deny 30 | you these rights or to ask you to surrender the rights. These restrictions 31 | translate to certain responsibilities for you if you distribute copies of the 32 | software, or if you modify it. 33 | 34 | For example, if you distribute copies of such a program, whether gratis or for 35 | a fee, you must give the recipients all the rights that you have. You must 36 | make sure that they, too, receive or can get the source code. And you must 37 | show them these terms so they know their rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and (2) 40 | offer you this license which gives you legal permission to copy, distribute 41 | and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain that 44 | everyone understands that there is no warranty for this free software. If the 45 | software is modified by someone else and passed on, we want its recipients to 46 | know that what they have is not the original, so that any problems introduced 47 | by others will not reflect on the original authors' reputations. 48 | 49 | Finally, any free program is threatened constantly by software patents. We 50 | wish to avoid the danger that redistributors of a free program will 51 | individually obtain patent licenses, in effect making the program proprietary. 52 | To prevent this, we have made it clear that any patent must be licensed for 53 | everyone's free use or not licensed at all. 54 | 55 | The precise terms and conditions for copying, distribution and modification 56 | follow. 57 | 58 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 59 | 60 | 0. This License applies to any program or other work which contains a notice 61 | placed by the copyright holder saying it may be distributed under the terms of 62 | this General Public License. The "Program", below, refers to any such program 63 | or work, and a "work based on the Program" means either the Program or any 64 | derivative work under copyright law: that is to say, a work containing the 65 | Program or a portion of it, either verbatim or with modifications and/or 66 | translated into another language. (Hereinafter, translation is included 67 | without limitation in the term "modification".) Each licensee is addressed as 68 | "you". 69 | 70 | Activities other than copying, distribution and modification are not covered by 71 | this License; they are outside its scope. The act of running the Program is 72 | not restricted, and the output from the Program is covered only if its contents 73 | constitute a work based on the Program (independent of having been made by 74 | running the Program). Whether that is true depends on what the Program does. 75 | 76 | 1. You may copy and distribute verbatim copies of the Program's source code as 77 | you receive it, in any medium, provided that you conspicuously and 78 | appropriately publish on each copy an appropriate copyright notice and 79 | disclaimer of warranty; keep intact all the notices that refer to this License 80 | and to the absence of any warranty; and give any other recipients of the 81 | Program a copy of this License along with the Program. 82 | 83 | You may charge a fee for the physical act of transferring a copy, and you may 84 | at your option offer warranty protection in exchange for a fee. 85 | 86 | 2. You may modify your copy or copies of the Program or any portion of it, thus 87 | forming a work based on the Program, and copy and distribute such modifications 88 | or work under the terms of Section 1 above, provided that you also meet all of 89 | these conditions: 90 | 91 | a) You must cause the modified files to carry prominent notices stating 92 | that you changed the files and the date of any change. 93 | 94 | b) You must cause any work that you distribute or publish, that in whole or 95 | in part contains or is derived from the Program or any part thereof, to be 96 | licensed as a whole at no charge to all third parties under the terms of 97 | this License. 98 | 99 | c) If the modified program normally reads commands interactively when run, 100 | you must cause it, when started running for such interactive use in the 101 | most ordinary way, to print or display an announcement including an 102 | appropriate copyright notice and a notice that there is no warranty (or 103 | else, saying that you provide a warranty) and that users may redistribute 104 | the program under these conditions, and telling the user how to view a copy 105 | of this License. (Exception: if the Program itself is interactive but does 106 | not normally print such an announcement, your work based on the Program is 107 | not required to print an announcement.) 108 | 109 | These requirements apply to the modified work as a whole. If identifiable 110 | sections of that work are not derived from the Program, and can be reasonably 111 | considered independent and separate works in themselves, then this License, and 112 | its terms, do not apply to those sections when you distribute them as separate 113 | works. But when you distribute the same sections as part of a whole which is a 114 | work based on the Program, the distribution of the whole must be on the terms 115 | of this License, whose permissions for other licensees extend to the entire 116 | whole, and thus to each and every part regardless of who wrote it. 117 | 118 | Thus, it is not the intent of this section to claim rights or contest your 119 | rights to work written entirely by you; rather, the intent is to exercise the 120 | right to control the distribution of derivative or collective works based on 121 | the Program. 122 | 123 | In addition, mere aggregation of another work not based on the Program with the 124 | Program (or with a work based on the Program) on a volume of a storage or 125 | distribution medium does not bring the other work under the scope of this 126 | License. 127 | 128 | 3. You may copy and distribute the Program (or a work based on it, under 129 | Section 2) in object code or executable form under the terms of Sections 1 and 130 | 2 above provided that you also do one of the following: 131 | 132 | a) Accompany it with the complete corresponding machine-readable source 133 | code, which must be distributed under the terms of Sections 1 and 2 above 134 | on a medium customarily used for software interchange; or, 135 | 136 | b) Accompany it with a written offer, valid for at least three years, to 137 | give any third party, for a charge no more than your cost of physically 138 | performing source distribution, a complete machine-readable copy of the 139 | corresponding source code, to be distributed under the terms of Sections 1 140 | and 2 above on a medium customarily used for software interchange; or, 141 | 142 | c) Accompany it with the information you received as to the offer to 143 | distribute corresponding source code. (This alternative is allowed only 144 | for noncommercial distribution and only if you received the program in 145 | object code or executable form with such an offer, in accord with 146 | Subsection b above.) 147 | 148 | The source code for a work means the preferred form of the work for making 149 | modifications to it. For an executable work, complete source code means all 150 | the source code for all modules it contains, plus any associated interface 151 | definition files, plus the scripts used to control compilation and installation 152 | of the executable. However, as a special exception, the source code 153 | distributed need not include anything that is normally distributed (in either 154 | source or binary form) with the major components (compiler, kernel, and so on) 155 | of the operating system on which the executable runs, unless that component 156 | itself accompanies the executable. 157 | 158 | If distribution of executable or object code is made by offering access to copy 159 | from a designated place, then offering equivalent access to copy the source 160 | code from the same place counts as distribution of the source code, even though 161 | third parties are not compelled to copy the source along with the object code. 162 | 163 | 4. You may not copy, modify, sublicense, or distribute the Program except as 164 | expressly provided under this License. Any attempt otherwise to copy, modify, 165 | sublicense or distribute the Program is void, and will automatically terminate 166 | your rights under this License. However, parties who have received copies, or 167 | rights, from you under this License will not have their licenses terminated so 168 | long as such parties remain in full compliance. 169 | 170 | 5. You are not required to accept this License, since you have not signed it. 171 | However, nothing else grants you permission to modify or distribute the Program 172 | or its derivative works. These actions are prohibited by law if you do not 173 | accept this License. Therefore, by modifying or distributing the Program (or 174 | any work based on the Program), you indicate your acceptance of this License to 175 | do so, and all its terms and conditions for copying, distributing or modifying 176 | the Program or works based on it. 177 | 178 | 6. Each time you redistribute the Program (or any work based on the Program), 179 | the recipient automatically receives a license from the original licensor to 180 | copy, distribute or modify the Program subject to these terms and conditions. 181 | You may not impose any further restrictions on the recipients' exercise of the 182 | rights granted herein. You are not responsible for enforcing compliance by 183 | third parties to this License. 184 | 185 | 7. If, as a consequence of a court judgment or allegation of patent 186 | infringement or for any other reason (not limited to patent issues), conditions 187 | are imposed on you (whether by court order, agreement or otherwise) that 188 | contradict the conditions of this License, they do not excuse you from the 189 | conditions of this License. If you cannot distribute so as to satisfy 190 | simultaneously your obligations under this License and any other pertinent 191 | obligations, then as a consequence you may not distribute the Program at all. 192 | For example, if a patent license would not permit royalty-free redistribution 193 | of the Program by all those who receive copies directly or indirectly through 194 | you, then the only way you could satisfy both it and this License would be to 195 | refrain entirely from distribution of the Program. 196 | 197 | If any portion of this section is held invalid or unenforceable under any 198 | particular circumstance, the balance of the section is intended to apply and 199 | the section as a whole is intended to apply in other circumstances. 200 | 201 | It is not the purpose of this section to induce you to infringe any patents or 202 | other property right claims or to contest validity of any such claims; this 203 | section has the sole purpose of protecting the integrity of the free software 204 | distribution system, which is implemented by public license practices. Many 205 | people have made generous contributions to the wide range of software 206 | distributed through that system in reliance on consistent application of that 207 | system; it is up to the author/donor to decide if he or she is willing to 208 | distribute software through any other system and a licensee cannot impose that 209 | choice. 210 | 211 | This section is intended to make thoroughly clear what is believed to be a 212 | consequence of the rest of this License. 213 | 214 | 8. If the distribution and/or use of the Program is restricted in certain 215 | countries either by patents or by copyrighted interfaces, the original 216 | copyright holder who places the Program under this License may add an explicit 217 | geographical distribution limitation excluding those countries, so that 218 | distribution is permitted only in or among countries not thus excluded. In 219 | such case, this License incorporates the limitation as if written in the body 220 | of this License. 221 | 222 | 9. The Free Software Foundation may publish revised and/or new versions of the 223 | General Public License from time to time. Such new versions will be similar in 224 | spirit to the present version, but may differ in detail to address new problems 225 | or concerns. 226 | 227 | Each version is given a distinguishing version number. If the Program 228 | specifies a version number of this License which applies to it and "any later 229 | version", you have the option of following the terms and conditions either of 230 | that version or of any later version published by the Free Software Foundation. 231 | If the Program does not specify a version number of this License, you may 232 | choose any version ever published by the Free Software Foundation. 233 | 234 | 10. If you wish to incorporate parts of the Program into other free programs 235 | whose distribution conditions are different, write to the author to ask for 236 | permission. For software which is copyrighted by the Free Software Foundation, 237 | write to the Free Software Foundation; we sometimes make exceptions for this. 238 | Our decision will be guided by the two goals of preserving the free status of 239 | all derivatives of our free software and of promoting the sharing and reuse of 240 | software generally. 241 | 242 | NO WARRANTY 243 | 244 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR 245 | THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE 246 | STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE 247 | PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, 248 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 249 | FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 250 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, 251 | YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 252 | 253 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL 254 | ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE 255 | PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 256 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR 257 | INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA 258 | BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 259 | FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER 260 | OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 261 | 262 | END OF TERMS AND CONDITIONS 263 | 264 | How to Apply These Terms to Your New Programs 265 | 266 | If you develop a new program, and you want it to be of the greatest possible 267 | use to the public, the best way to achieve this is to make it free software 268 | which everyone can redistribute and change under these terms. 269 | 270 | To do so, attach the following notices to the program. It is safest to attach 271 | them to the start of each source file to most effectively convey the exclusion 272 | of warranty; and each file should have at least the "copyright" line and a 273 | pointer to where the full notice is found. 274 | 275 | One line to give the program's name and a brief idea of what it does. 276 | 277 | Copyright (C) 278 | 279 | This program is free software; you can redistribute it and/or modify it 280 | under the terms of the GNU General Public License as published by the Free 281 | Software Foundation; either version 2 of the License, or (at your option) 282 | any later version. 283 | 284 | This program is distributed in the hope that it will be useful, but WITHOUT 285 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 286 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 287 | more details. 288 | 289 | You should have received a copy of the GNU General Public License along 290 | with this program; if not, write to the Free Software Foundation, Inc., 59 291 | Temple Place, Suite 330, Boston, MA 02111-1307 USA 292 | 293 | Also add information on how to contact you by electronic and paper mail. 294 | 295 | If the program is interactive, make it output a short notice like this when it 296 | starts in an interactive mode: 297 | 298 | Gnomovision version 69, Copyright (C) year name of author Gnomovision comes 299 | with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free 300 | software, and you are welcome to redistribute it under certain conditions; 301 | type 'show c' for details. 302 | 303 | The hypothetical commands 'show w' and 'show c' should show the appropriate 304 | parts of the General Public License. Of course, the commands you use may be 305 | called something other than 'show w' and 'show c'; they could even be 306 | mouse-clicks or menu items--whatever suits your program. 307 | 308 | You should also get your employer (if you work as a programmer) or your school, 309 | if any, to sign a "copyright disclaimer" for the program, if necessary. Here 310 | is a sample; alter the names: 311 | 312 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 313 | 'Gnomovision' (which makes passes at compilers) written by James Hacker. 314 | 315 | signature of Ty Coon, 1 April 1989 316 | 317 | Ty Coon, President of Vice 318 | 319 | This General Public License does not permit incorporating your program into 320 | proprietary programs. If your program is a subroutine library, you may 321 | consider it more useful to permit linking proprietary applications with the 322 | library. If this is what you want to do, use the GNU Library General Public 323 | License instead of this License. 324 | 325 | 326 | "CLASSPATH" EXCEPTION TO THE GPL 327 | 328 | Certain source files distributed by Oracle America and/or its affiliates are 329 | subject to the following clarification and special exception to the GPL, but 330 | only where Oracle has expressly included in the particular source file's header 331 | the words "Oracle designates this particular file as subject to the "Classpath" 332 | exception as provided by Oracle in the LICENSE file that accompanied this code." 333 | 334 | Linking this library statically or dynamically with other modules is making 335 | a combined work based on this library. Thus, the terms and conditions of 336 | the GNU General Public License cover the whole combination. 337 | 338 | As a special exception, the copyright holders of this library give you 339 | permission to link this library with independent modules to produce an 340 | executable, regardless of the license terms of these independent modules, 341 | and to copy and distribute the resulting executable under terms of your 342 | choice, provided that you also meet, for each linked independent module, 343 | the terms and conditions of the license of that module. An independent 344 | module is a module which is not derived from or based on this library. If 345 | you modify this library, you may extend this exception to your version of 346 | the library, but you are not obligated to do so. If you do not wish to do 347 | so, delete this exception statement from your version. 348 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Travis](https://img.shields.io/travis/APISENSE/rhino-android.svg)](https://travis-ci.org/APISENSE/rhino-android) 2 | [![Codecov](https://img.shields.io/codecov/c/github/APISENSE/rhino-android.svg)](https://codecov.io/gh/APISENSE/rhino-android) 3 | [![Maven Central](https://img.shields.io/maven-central/v/io.apisense/rhino-android.svg)](http://search.maven.org/#artifactdetails%7Cio.apisense%7Crhino-android%7C1.0%7Cjar) 4 | 5 | 6 | # Rhino script engine 7 | 8 | This project aims to package a minimal Rhino script engine for Android. 9 | 10 | The script engine source code is imported from openjdk implementation, version _7u40-b43_. 11 | 12 | ## Installation 13 | 14 | Add the following repository and dependency to your `build.gradle`: 15 | 16 | ``` 17 | dependencies { 18 | compile 'io.apisense:rhino-android:1.3.0' 19 | } 20 | ``` 21 | 22 | ## Usage 23 | 24 | You can now call the Rhino script engine by using the jsr223, i.e.: 25 | 26 | ``` 27 | ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino"); 28 | ``` 29 | 30 | ## Configuration 31 | 32 | The `ScriptEngine` feature relies on reflection to instanciate the engines. 33 | This will cause trouble while shrinking your code using Proguard or R8. 34 | 35 | To ease the integration of `rhino-android` in your project, you can find a sample project with up-to-date configuration for minification here: https://github.com/aveuiller/RhinoSampleApp 36 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | } 5 | dependencies { 6 | classpath 'com.android.tools.build:gradle:2.1.2' 7 | } 8 | } 9 | 10 | apply from: 'nexusConfig.gradle' 11 | 12 | ext.commonLicense = { 13 | name 'The GNU General Public License (GPL)' 14 | url 'https://www.gnu.org/licenses/gpl-2.0.txt' 15 | } 16 | 17 | ext.devs = [ 18 | { 19 | id 'aveuiller' 20 | name 'Antoine Veuiller' 21 | email 'aveuiller@gmail.com' 22 | } 23 | ] 24 | 25 | allprojects { 26 | repositories { 27 | mavenCentral() 28 | } 29 | 30 | group = "io.apisense" 31 | version = "1.3.0" 32 | } 33 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/APISENSE/rhino-android/68017450aeb6de838a239d978937426af451f30f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /nexusConfig.gradle: -------------------------------------------------------------------------------- 1 | Properties properties = new Properties() 2 | if (project.rootProject.file('gradle.properties').canRead()) { 3 | properties.load(project.rootProject.file("gradle.properties").newDataInputStream()) 4 | } 5 | 6 | // Default parameters 7 | ext.nexusUrl = properties.getProperty("nexusUrl", "file:///tmp/sdkRepo") 8 | ext.nexusUsername = properties.getProperty("nexusUsername", "") 9 | ext.nexusPassword = properties.getProperty("nexusPassword", "") 10 | 11 | ext.nexusRelease = "${nexusUrl}/service/local/staging/deploy/maven2/" 12 | ext.nexusSnapshot = "${nexusUrl}/content/repositories/snapshots/" 13 | 14 | private boolean signingConfigured() { 15 | return project.hasProperty("signing.keyId") \ 16 | && project.hasProperty("signing.password") \ 17 | && project.hasProperty("signing.secretKeyRingFile") 18 | } 19 | 20 | allprojects { 21 | apply plugin: 'maven' 22 | if (signingConfigured()) { 23 | apply plugin: 'signing' 24 | signing { 25 | sign configurations.archives 26 | } 27 | } 28 | 29 | uploadArchives.repositories.mavenDeployer { 30 | if (signingConfigured()) { 31 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 32 | } 33 | repository(url: nexusRelease) { 34 | authentication(userName: nexusUsername, password: nexusPassword) 35 | } 36 | 37 | snapshotRepository(url: nexusSnapshot) { 38 | authentication(userName: nexusUsername, password: nexusPassword) 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':sun-dependencies' 2 | -------------------------------------------------------------------------------- /sun-dependencies/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sun-dependencies/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | 3 | sourceCompatibility = JavaVersion.VERSION_1_7 4 | targetCompatibility = JavaVersion.VERSION_1_7 5 | 6 | dependencies { 7 | testCompile 'junit:junit:4.12' 8 | 9 | // JSR 223 (javax.script package) 10 | compile 'com.sun.phobos:jsr223-api:1.0' 11 | // Rhino engine implementation by Mozilla 12 | compile 'org.mozilla:rhino:1.7.15' 13 | } 14 | 15 | task javadocJar(type: Jar) { 16 | classifier = 'javadoc' 17 | from javadoc 18 | } 19 | 20 | task sourcesJar(type: Jar) { 21 | classifier = 'sources' 22 | from sourceSets.main.allSource 23 | } 24 | 25 | artifacts { 26 | archives javadocJar, sourcesJar 27 | } 28 | 29 | uploadArchives { 30 | repositories.mavenDeployer { 31 | pom.project { 32 | name 'Rhino for Android' 33 | artifactId 'rhino-android' 34 | packaging 'jar' 35 | description 'Give access to RhinoScriptEngine from the JSR223 interfaces on Android JRE.' 36 | url 'https://apisense.io' 37 | 38 | scm { 39 | connection 'scm:git:https://github.com/APISENSE/rhino-android.git' 40 | developerConnection 'scm:git:https://github.com/APISENSE/rhino-android' 41 | url 'https://github.com/APISENSE/rhino-android' 42 | } 43 | 44 | licenses { 45 | license commonLicense 46 | } 47 | developers { 48 | devs.collect({ developer it }) 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /sun-dependencies/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/antoine/Software/Android-SDK/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/javascript/ExternalScriptable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.javascript; 27 | 28 | import org.mozilla.javascript.Context; 29 | import org.mozilla.javascript.Function; 30 | import org.mozilla.javascript.NativeJavaClass; 31 | import org.mozilla.javascript.ScriptRuntime; 32 | import org.mozilla.javascript.Scriptable; 33 | import org.mozilla.javascript.ScriptableObject; 34 | import org.mozilla.javascript.Wrapper; 35 | 36 | import java.util.ArrayList; 37 | import java.util.HashMap; 38 | import java.util.Map; 39 | 40 | import javax.script.Bindings; 41 | import javax.script.ScriptContext; 42 | 43 | /** 44 | * ExternalScriptable is an implementation of Scriptable 45 | * backed by a JSR 223 ScriptContext instance. 46 | * 47 | * @author Mike Grogan 48 | * @author A. Sundararajan 49 | * @since 1.6 50 | */ 51 | 52 | final class ExternalScriptable implements Scriptable { 53 | /* Underlying ScriptContext that we use to store 54 | * named variables of this scope. 55 | */ 56 | private ScriptContext context; 57 | 58 | /* JavaScript allows variables to be named as numbers (indexed 59 | * properties). This way arrays, objects (scopes) are treated uniformly. 60 | * Note that JSR 223 API supports only String named variables and 61 | * so we can't store these in Bindings. Also, JavaScript allows name 62 | * of the property name to be even empty String! Again, JSR 223 API 63 | * does not support empty name. So, we use the following fallback map 64 | * to store such variables of this scope. This map is not exposed to 65 | * JSR 223 API. We can just script objects "as is" and need not convert. 66 | */ 67 | private Map indexedProps; 68 | 69 | // my prototype 70 | private Scriptable prototype; 71 | // my parent scope, if any 72 | private Scriptable parent; 73 | 74 | ExternalScriptable(ScriptContext context) { 75 | this(context, new HashMap()); 76 | } 77 | 78 | ExternalScriptable(ScriptContext context, Map indexedProps) { 79 | if (context == null) { 80 | throw new NullPointerException("context is null"); 81 | } 82 | this.context = context; 83 | this.indexedProps = indexedProps; 84 | } 85 | 86 | ScriptContext getContext() { 87 | return context; 88 | } 89 | 90 | private boolean isEmpty(String name) { 91 | return name.equals(""); 92 | } 93 | 94 | /** 95 | * Return the name of the class. 96 | */ 97 | public String getClassName() { 98 | return "Global"; 99 | } 100 | 101 | /** 102 | * Returns the value of the named property or NOT_FOUND. 103 | * 104 | * If the property was created using defineProperty, the 105 | * appropriate getter method is called. 106 | * 107 | * @param name the name of the property 108 | * @param start the object in which the lookup began 109 | * @return the value of the property (may be null), or NOT_FOUND 110 | */ 111 | public synchronized Object get(String name, Scriptable start) { 112 | if (isEmpty(name)) { 113 | if (indexedProps.containsKey(name)) { 114 | return indexedProps.get(name); 115 | } else { 116 | return NOT_FOUND; 117 | } 118 | } else { 119 | synchronized (context) { 120 | int scope = context.getAttributesScope(name); 121 | if (scope != -1) { 122 | Object value = context.getAttribute(name, scope); 123 | return Context.javaToJS(value, this); 124 | } else { 125 | return NOT_FOUND; 126 | } 127 | } 128 | } 129 | } 130 | 131 | /** 132 | * Returns the value of the indexed property or NOT_FOUND. 133 | * 134 | * @param index the numeric index for the property 135 | * @param start the object in which the lookup began 136 | * @return the value of the property (may be null), or NOT_FOUND 137 | */ 138 | public synchronized Object get(int index, Scriptable start) { 139 | Integer key = new Integer(index); 140 | if (indexedProps.containsKey(index)) { 141 | return indexedProps.get(key); 142 | } else { 143 | return NOT_FOUND; 144 | } 145 | } 146 | 147 | /** 148 | * Returns true if the named property is defined. 149 | * 150 | * @param name the name of the property 151 | * @param start the object in which the lookup began 152 | * @return true if and only if the property was found in the object 153 | */ 154 | public synchronized boolean has(String name, Scriptable start) { 155 | if (isEmpty(name)) { 156 | return indexedProps.containsKey(name); 157 | } else { 158 | synchronized (context) { 159 | return context.getAttributesScope(name) != -1; 160 | } 161 | } 162 | } 163 | 164 | /** 165 | * Returns true if the property index is defined. 166 | * 167 | * @param index the numeric index for the property 168 | * @param start the object in which the lookup began 169 | * @return true if and only if the property was found in the object 170 | */ 171 | public synchronized boolean has(int index, Scriptable start) { 172 | Integer key = new Integer(index); 173 | return indexedProps.containsKey(key); 174 | } 175 | 176 | /** 177 | * Sets the value of the named property, creating it if need be. 178 | * 179 | * @param name the name of the property 180 | * @param start the object whose property is being set 181 | * @param value value to set the property to 182 | */ 183 | public void put(String name, Scriptable start, Object value) { 184 | if (start == this) { 185 | synchronized (this) { 186 | if (isEmpty(name)) { 187 | indexedProps.put(name, value); 188 | } else { 189 | synchronized (context) { 190 | int scope = context.getAttributesScope(name); 191 | if (scope == -1) { 192 | scope = ScriptContext.ENGINE_SCOPE; 193 | } 194 | context.setAttribute(name, jsToJava(value), scope); 195 | } 196 | } 197 | } 198 | } else { 199 | start.put(name, start, value); 200 | } 201 | } 202 | 203 | /** 204 | * Sets the value of the indexed property, creating it if need be. 205 | * 206 | * @param index the numeric index for the property 207 | * @param start the object whose property is being set 208 | * @param value value to set the property to 209 | */ 210 | public void put(int index, Scriptable start, Object value) { 211 | if (start == this) { 212 | synchronized (this) { 213 | indexedProps.put(new Integer(index), value); 214 | } 215 | } else { 216 | start.put(index, start, value); 217 | } 218 | } 219 | 220 | /** 221 | * Removes a named property from the object. 222 | * 223 | * If the property is not found, no action is taken. 224 | * 225 | * @param name the name of the property 226 | */ 227 | public synchronized void delete(String name) { 228 | if (isEmpty(name)) { 229 | indexedProps.remove(name); 230 | } else { 231 | synchronized (context) { 232 | int scope = context.getAttributesScope(name); 233 | if (scope != -1) { 234 | context.removeAttribute(name, scope); 235 | } 236 | } 237 | } 238 | } 239 | 240 | /** 241 | * Removes the indexed property from the object. 242 | * 243 | * If the property is not found, no action is taken. 244 | * 245 | * @param index the numeric index for the property 246 | */ 247 | public void delete(int index) { 248 | indexedProps.remove(new Integer(index)); 249 | } 250 | 251 | /** 252 | * Get the prototype of the object. 253 | * @return the prototype 254 | */ 255 | public Scriptable getPrototype() { 256 | return prototype; 257 | } 258 | 259 | /** 260 | * Set the prototype of the object. 261 | * @param prototype the prototype to set 262 | */ 263 | public void setPrototype(Scriptable prototype) { 264 | this.prototype = prototype; 265 | } 266 | 267 | /** 268 | * Get the parent scope of the object. 269 | * @return the parent scope 270 | */ 271 | public Scriptable getParentScope() { 272 | return parent; 273 | } 274 | 275 | /** 276 | * Set the parent scope of the object. 277 | * @param parent the parent scope to set 278 | */ 279 | public void setParentScope(Scriptable parent) { 280 | this.parent = parent; 281 | } 282 | 283 | /** 284 | * Get an array of property ids. 285 | * 286 | * Not all property ids need be returned. Those properties 287 | * whose ids are not returned are considered non-enumerable. 288 | * 289 | * @return an array of Objects. Each entry in the array is either 290 | * a java.lang.String or a java.lang.Number 291 | */ 292 | public synchronized Object[] getIds() { 293 | String[] keys = getAllKeys(); 294 | int size = keys.length + indexedProps.size(); 295 | Object[] res = new Object[size]; 296 | System.arraycopy(keys, 0, res, 0, keys.length); 297 | int i = keys.length; 298 | // now add all indexed properties 299 | for (Object index : indexedProps.keySet()) { 300 | res[i++] = index; 301 | } 302 | return res; 303 | } 304 | 305 | /** 306 | * Get the default value of the object with a given hint. 307 | * The hints are String.class for type String, Number.class for type 308 | * Number, Scriptable.class for type Object, and Boolean.class for 309 | * type Boolean.

310 | * 311 | * A hint of null means "no hint". 312 | * 313 | * See ECMA 8.6.2.6. 314 | * 315 | * @param typeHint the type hint 316 | * @return the default value 317 | */ 318 | public Object getDefaultValue(Class typeHint) { 319 | for (int i=0; i < 2; i++) { 320 | boolean tryToString; 321 | if (typeHint == ScriptRuntime.StringClass) { 322 | tryToString = (i == 0); 323 | } else { 324 | tryToString = (i == 1); 325 | } 326 | 327 | String methodName; 328 | Object[] args; 329 | if (tryToString) { 330 | methodName = "toString"; 331 | args = ScriptRuntime.emptyArgs; 332 | } else { 333 | methodName = "valueOf"; 334 | args = new Object[1]; 335 | String hint; 336 | if (typeHint == null) { 337 | hint = "undefined"; 338 | } else if (typeHint == ScriptRuntime.StringClass) { 339 | hint = "string"; 340 | } else if (typeHint == ScriptRuntime.ScriptableClass) { 341 | hint = "object"; 342 | } else if (typeHint == ScriptRuntime.FunctionClass) { 343 | hint = "function"; 344 | } else if (typeHint == ScriptRuntime.BooleanClass 345 | || typeHint == Boolean.TYPE) 346 | { 347 | hint = "boolean"; 348 | } else if (typeHint == ScriptRuntime.NumberClass || 349 | typeHint == ScriptRuntime.ByteClass || 350 | typeHint == Byte.TYPE || 351 | typeHint == ScriptRuntime.ShortClass || 352 | typeHint == Short.TYPE || 353 | typeHint == ScriptRuntime.IntegerClass || 354 | typeHint == Integer.TYPE || 355 | typeHint == ScriptRuntime.FloatClass || 356 | typeHint == Float.TYPE || 357 | typeHint == ScriptRuntime.DoubleClass || 358 | typeHint == Double.TYPE) 359 | { 360 | hint = "number"; 361 | } else { 362 | throw Context.reportRuntimeError( 363 | "Invalid JavaScript value of type " + 364 | typeHint.toString()); 365 | } 366 | args[0] = hint; 367 | } 368 | Object v = ScriptableObject.getProperty(this, methodName); 369 | if (!(v instanceof Function)) 370 | continue; 371 | Function fun = (Function) v; 372 | Context cx = RhinoScriptEngine.enterContext(); 373 | try { 374 | v = fun.call(cx, fun.getParentScope(), this, args); 375 | } finally { 376 | cx.exit(); 377 | } 378 | if (v != null) { 379 | if (!(v instanceof Scriptable)) { 380 | return v; 381 | } 382 | if (typeHint == ScriptRuntime.ScriptableClass 383 | || typeHint == ScriptRuntime.FunctionClass) 384 | { 385 | return v; 386 | } 387 | if (tryToString && v instanceof Wrapper) { 388 | // Let a wrapped java.lang.String pass for a primitive 389 | // string. 390 | Object u = ((Wrapper)v).unwrap(); 391 | if (u instanceof String) 392 | return u; 393 | } 394 | } 395 | } 396 | // fall through to error 397 | String arg = (typeHint == null) ? "undefined" : typeHint.getName(); 398 | throw Context.reportRuntimeError( 399 | "Cannot find default value for object " + arg); 400 | } 401 | 402 | /** 403 | * Implements the instanceof operator. 404 | * 405 | * @param instance The value that appeared on the LHS of the instanceof 406 | * operator 407 | * @return true if "this" appears in value's prototype chain 408 | * 409 | */ 410 | public boolean hasInstance(Scriptable instance) { 411 | // Default for JS objects (other than Function) is to do prototype 412 | // chasing. 413 | Scriptable proto = instance.getPrototype(); 414 | while (proto != null) { 415 | if (proto.equals(this)) return true; 416 | proto = proto.getPrototype(); 417 | } 418 | return false; 419 | } 420 | 421 | private String[] getAllKeys() { 422 | ArrayList list = new ArrayList(); 423 | synchronized (context) { 424 | for (int scope : context.getScopes()) { 425 | Bindings bindings = context.getBindings(scope); 426 | if (bindings != null) { 427 | list.ensureCapacity(bindings.size()); 428 | for (String key : bindings.keySet()) { 429 | list.add(key); 430 | } 431 | } 432 | } 433 | } 434 | String[] res = new String[list.size()]; 435 | list.toArray(res); 436 | return res; 437 | } 438 | 439 | /** 440 | * We convert script values to the nearest Java value. 441 | * We unwrap wrapped Java objects so that access from 442 | * Bindings.get() would return "workable" value for Java. 443 | * But, at the same time, we need to make few special cases 444 | * and hence the following function is used. 445 | */ 446 | private Object jsToJava(Object jsObj) { 447 | if (jsObj instanceof Wrapper) { 448 | Wrapper njb = (Wrapper) jsObj; 449 | /* importClass feature of ImporterTopLevel puts 450 | * NativeJavaClass in global scope. If we unwrap 451 | * it, importClass won't work. 452 | */ 453 | if (njb instanceof NativeJavaClass) { 454 | return njb; 455 | } 456 | 457 | /* script may use Java primitive wrapper type objects 458 | * (such as java.lang.Integer, java.lang.Boolean etc) 459 | * explicitly. If we unwrap, then these script objects 460 | * will become script primitive types. For example, 461 | * 462 | * var x = new java.lang.Double(3.0); print(typeof x); 463 | * 464 | * will print 'number'. We don't want that to happen. 465 | */ 466 | Object obj = njb.unwrap(); 467 | if (obj instanceof Number || obj instanceof String || 468 | obj instanceof Boolean || obj instanceof Character) { 469 | // special type wrapped -- we just leave it as is. 470 | return njb; 471 | } else { 472 | // return unwrapped object for any other object. 473 | return obj; 474 | } 475 | } else { // not-a-Java-wrapper 476 | return jsObj; 477 | } 478 | } 479 | } 480 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/javascript/JSAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.javascript; 27 | 28 | import org.mozilla.javascript.Context; 29 | import org.mozilla.javascript.Function; 30 | import org.mozilla.javascript.NativeArray; 31 | import org.mozilla.javascript.NativeJavaArray; 32 | import org.mozilla.javascript.RhinoException; 33 | import org.mozilla.javascript.Scriptable; 34 | import org.mozilla.javascript.ScriptableObject; 35 | 36 | /** 37 | * JSAdapter is java.lang.reflect.Proxy equivalent for JavaScript. JSAdapter 38 | * calls specially named JavaScript methods on an adaptee object when property 39 | * access is attempted on it. 40 | * 41 | * Example: 42 | * 43 | * var y = { 44 | * __get__ : function (name) { ... } 45 | * __has__ : function (name) { ... } 46 | * __put__ : function (name, value) {...} 47 | * __delete__ : function (name) { ... } 48 | * __getIds__ : function () { ... } 49 | * }; 50 | * 51 | * var x = new JSAdapter(y); 52 | * 53 | * x.i; // calls y.__get__ 54 | * i in x; // calls y.__has__ 55 | * x.p = 10; // calls y.__put__ 56 | * delete x.p; // calls y.__delete__ 57 | * for (i in x) { print(i); } // calls y.__getIds__ 58 | * 59 | * If a special JavaScript method is not found in the adaptee, then JSAdapter 60 | * forwards the property access to the adaptee itself. 61 | * 62 | * JavaScript caller of adapter object is isolated from the fact that 63 | * the property access/mutation/deletion are really calls to 64 | * JavaScript methods on adaptee. Use cases include 'smart' 65 | * properties, property access tracing/debugging, encaptulation with 66 | * easy client access - in short JavaScript becomes more "Self" like. 67 | * 68 | * Note that Rhino already supports special properties like __proto__ 69 | * (to set, get prototype), __parent__ (to set, get parent scope). We 70 | * follow the same double underscore nameing convention here. Similarly 71 | * the name JSAdapter is derived from JavaAdapter -- which is a facility 72 | * to extend, implement Java classes/interfaces by JavaScript. 73 | * 74 | * @author A. Sundararajan 75 | * @since 1.6 76 | */ 77 | public final class JSAdapter implements Scriptable, Function { 78 | private JSAdapter(Scriptable obj) { 79 | setAdaptee(obj); 80 | } 81 | 82 | // initializer to setup JSAdapter prototype in the given scope 83 | public static void init(Context cx, Scriptable scope, boolean sealed) 84 | throws RhinoException { 85 | JSAdapter obj = new JSAdapter(cx.newObject(scope)); 86 | obj.setParentScope(scope); 87 | obj.setPrototype(getFunctionPrototype(scope)); 88 | obj.isPrototype = true; 89 | ScriptableObject.defineProperty(scope, "JSAdapter", obj, 90 | ScriptableObject.DONTENUM); 91 | } 92 | 93 | public String getClassName() { 94 | return "JSAdapter"; 95 | } 96 | 97 | public Object get(String name, Scriptable start) { 98 | Function func = getAdapteeFunction(GET_PROP); 99 | if (func != null) { 100 | return call(func, new Object[] { name }); 101 | } else { 102 | start = getAdaptee(); 103 | return start.get(name, start); 104 | } 105 | } 106 | 107 | public Object get(int index, Scriptable start) { 108 | Function func = getAdapteeFunction(GET_PROP); 109 | if (func != null) { 110 | return call(func, new Object[] { new Integer(index) }); 111 | } else { 112 | start = getAdaptee(); 113 | return start.get(index, start); 114 | } 115 | } 116 | 117 | public boolean has(String name, Scriptable start) { 118 | Function func = getAdapteeFunction(HAS_PROP); 119 | if (func != null) { 120 | Object res = call(func, new Object[] { name }); 121 | return Context.toBoolean(res); 122 | } else { 123 | start = getAdaptee(); 124 | return start.has(name, start); 125 | } 126 | } 127 | 128 | public boolean has(int index, Scriptable start) { 129 | Function func = getAdapteeFunction(HAS_PROP); 130 | if (func != null) { 131 | Object res = call(func, new Object[] { new Integer(index) }); 132 | return Context.toBoolean(res); 133 | } else { 134 | start = getAdaptee(); 135 | return start.has(index, start); 136 | } 137 | } 138 | 139 | public void put(String name, Scriptable start, Object value) { 140 | if (start == this) { 141 | Function func = getAdapteeFunction(PUT_PROP); 142 | if (func != null) { 143 | call(func, new Object[] { name, value }); 144 | } else { 145 | start = getAdaptee(); 146 | start.put(name, start, value); 147 | } 148 | } else { 149 | start.put(name, start, value); 150 | } 151 | } 152 | 153 | public void put(int index, Scriptable start, Object value) { 154 | if (start == this) { 155 | Function func = getAdapteeFunction(PUT_PROP); 156 | if( func != null) { 157 | call(func, new Object[] { new Integer(index), value }); 158 | } else { 159 | start = getAdaptee(); 160 | start.put(index, start, value); 161 | } 162 | } else { 163 | start.put(index, start, value); 164 | } 165 | } 166 | 167 | public void delete(String name) { 168 | Function func = getAdapteeFunction(DEL_PROP); 169 | if (func != null) { 170 | call(func, new Object[] { name }); 171 | } else { 172 | getAdaptee().delete(name); 173 | } 174 | } 175 | 176 | public void delete(int index) { 177 | Function func = getAdapteeFunction(DEL_PROP); 178 | if (func != null) { 179 | call(func, new Object[] { new Integer(index) }); 180 | } else { 181 | getAdaptee().delete(index); 182 | } 183 | } 184 | 185 | public Scriptable getPrototype() { 186 | return prototype; 187 | } 188 | 189 | public void setPrototype(Scriptable prototype) { 190 | this.prototype = prototype; 191 | } 192 | 193 | public Scriptable getParentScope() { 194 | return parent; 195 | } 196 | 197 | public void setParentScope(Scriptable parent) { 198 | this.parent = parent; 199 | } 200 | 201 | public Object[] getIds() { 202 | Function func = getAdapteeFunction(GET_PROPIDS); 203 | if (func != null) { 204 | Object val = call(func, new Object[0]); 205 | // in most cases, adaptee would return native JS array 206 | if (val instanceof NativeArray) { 207 | NativeArray array = (NativeArray) val; 208 | Object[] res = new Object[(int)array.getLength()]; 209 | for (int index = 0; index < res.length; index++) { 210 | res[index] = mapToId(array.get(index, array)); 211 | } 212 | return res; 213 | } else if (val instanceof NativeJavaArray) { 214 | // may be attempt wrapped Java array 215 | Object tmp = ((NativeJavaArray)val).unwrap(); 216 | Object[] res; 217 | if (tmp.getClass() == Object[].class) { 218 | Object[] array = (Object[]) tmp; 219 | res = new Object[array.length]; 220 | for (int index = 0; index < array.length; index++) { 221 | res[index] = mapToId(array[index]); 222 | } 223 | } else { 224 | // just return an empty array 225 | res = Context.emptyArgs; 226 | } 227 | return res; 228 | } else { 229 | // some other return type, just return empty array 230 | return Context.emptyArgs; 231 | } 232 | } else { 233 | return getAdaptee().getIds(); 234 | } 235 | } 236 | 237 | public boolean hasInstance(Scriptable scriptable) { 238 | if (scriptable instanceof JSAdapter) { 239 | return true; 240 | } else { 241 | Scriptable proto = scriptable.getPrototype(); 242 | while (proto != null) { 243 | if (proto.equals(this)) return true; 244 | proto = proto.getPrototype(); 245 | } 246 | return false; 247 | } 248 | } 249 | 250 | public Object getDefaultValue(Class hint) { 251 | return getAdaptee().getDefaultValue(hint); 252 | } 253 | 254 | public Object call(Context cx, Scriptable scope, Scriptable thisObj, 255 | Object[] args) 256 | throws RhinoException { 257 | if (isPrototype) { 258 | return construct(cx, scope, args); 259 | } else { 260 | Scriptable tmp = getAdaptee(); 261 | if (tmp instanceof Function) { 262 | return ((Function)tmp).call(cx, scope, tmp, args); 263 | } else { 264 | throw Context.reportRuntimeError("TypeError: not a function"); 265 | } 266 | } 267 | } 268 | 269 | public Scriptable construct(Context cx, Scriptable scope, Object[] args) 270 | throws RhinoException { 271 | if (isPrototype) { 272 | Scriptable topLevel = ScriptableObject.getTopLevelScope(scope); 273 | JSAdapter newObj; 274 | if (args.length > 0) { 275 | newObj = new JSAdapter(Context.toObject(args[0], topLevel)); 276 | } else { 277 | throw Context.reportRuntimeError("JSAdapter requires adaptee"); 278 | } 279 | return newObj; 280 | } else { 281 | Scriptable tmp = getAdaptee(); 282 | if (tmp instanceof Function) { 283 | return ((Function)tmp).construct(cx, scope, args); 284 | } else { 285 | throw Context.reportRuntimeError("TypeError: not a constructor"); 286 | } 287 | } 288 | } 289 | 290 | public Scriptable getAdaptee() { 291 | return adaptee; 292 | } 293 | 294 | public void setAdaptee(Scriptable adaptee) { 295 | if (adaptee == null) { 296 | throw new NullPointerException("adaptee can not be null"); 297 | } 298 | this.adaptee = adaptee; 299 | } 300 | 301 | //-- internals only below this point 302 | 303 | // map a property id. Property id can only be an Integer or String 304 | private Object mapToId(Object tmp) { 305 | if (tmp instanceof Double) { 306 | return new Integer(((Double)tmp).intValue()); 307 | } else { 308 | return Context.toString(tmp); 309 | } 310 | } 311 | 312 | private static Scriptable getFunctionPrototype(Scriptable scope) { 313 | return ScriptableObject.getFunctionPrototype(scope); 314 | } 315 | 316 | private Function getAdapteeFunction(String name) { 317 | Object o = ScriptableObject.getProperty(getAdaptee(), name); 318 | return (o instanceof Function)? (Function)o : null; 319 | } 320 | 321 | private Object call(Function func, Object[] args) { 322 | Context cx = Context.getCurrentContext(); 323 | Scriptable thisObj = getAdaptee(); 324 | Scriptable scope = func.getParentScope(); 325 | try { 326 | return func.call(cx, scope, thisObj, args); 327 | } catch (RhinoException re) { 328 | throw Context.reportRuntimeError(re.getMessage()); 329 | } 330 | } 331 | 332 | private Scriptable prototype; 333 | private Scriptable parent; 334 | private Scriptable adaptee; 335 | private boolean isPrototype; 336 | 337 | // names of adaptee JavaScript functions 338 | private static final String GET_PROP = "__get__"; 339 | private static final String HAS_PROP = "__has__"; 340 | private static final String PUT_PROP = "__put__"; 341 | private static final String DEL_PROP = "__delete__"; 342 | private static final String GET_PROPIDS = "__getIds__"; 343 | } 344 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/javascript/JavaAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.javascript; 27 | 28 | import org.mozilla.javascript.Context; 29 | import org.mozilla.javascript.Function; 30 | import org.mozilla.javascript.RhinoException; 31 | import org.mozilla.javascript.Scriptable; 32 | import org.mozilla.javascript.ScriptableObject; 33 | import org.mozilla.javascript.Wrapper; 34 | 35 | import javax.script.Invocable; 36 | 37 | /** 38 | * This class implements Rhino-like JavaAdapter to help implement a Java 39 | * interface in JavaScript. We support this using Invocable.getInterface. 40 | * Using this JavaAdapter, script author could write: 41 | * 42 | * var r = new java.lang.Runnable() { 43 | * run: function() { script... } 44 | * }; 45 | * 46 | * r.run(); 47 | * new java.lang.Thread(r).start(); 48 | * 49 | * Note that Rhino's JavaAdapter support allows extending a Java class and/or 50 | * implementing one or more interfaces. This JavaAdapter implementation does 51 | * not support these. 52 | * 53 | * @author A. Sundararajan 54 | * @since 1.6 55 | */ 56 | final class JavaAdapter extends ScriptableObject implements Function { 57 | private JavaAdapter(Invocable engine) { 58 | this.engine = engine; 59 | } 60 | 61 | static void init(Context cx, Scriptable scope, boolean sealed) 62 | throws RhinoException { 63 | RhinoTopLevel topLevel = (RhinoTopLevel) scope; 64 | Invocable engine = topLevel.getScriptEngine(); 65 | JavaAdapter obj = new JavaAdapter(engine); 66 | obj.setParentScope(scope); 67 | obj.setPrototype(getFunctionPrototype(scope)); 68 | /* 69 | * Note that we can't use defineProperty. A property of this 70 | * name is already defined in Context.initStandardObjects. We 71 | * simply overwrite the property value! 72 | */ 73 | ScriptableObject.putProperty(topLevel, "JavaAdapter", obj); 74 | } 75 | 76 | public String getClassName() { 77 | return "JavaAdapter"; 78 | } 79 | 80 | public Object call(Context cx, Scriptable scope, Scriptable thisObj, 81 | Object[] args) throws RhinoException { 82 | return construct(cx, scope, args); 83 | } 84 | 85 | public Scriptable construct(Context cx, Scriptable scope, Object[] args) 86 | throws RhinoException { 87 | if (args.length == 2) { 88 | Class clazz = null; 89 | Object obj1 = args[0]; 90 | if (obj1 instanceof Wrapper) { 91 | Object o = ((Wrapper)obj1).unwrap(); 92 | if (o instanceof Class && ((Class)o).isInterface()) { 93 | clazz = (Class) o; 94 | } 95 | } else if (obj1 instanceof Class) { 96 | if (((Class)obj1).isInterface()) { 97 | clazz = (Class) obj1; 98 | } 99 | } 100 | if (clazz == null) { 101 | throw Context.reportRuntimeError("JavaAdapter: first arg should be interface Class"); 102 | } 103 | 104 | Scriptable topLevel = ScriptableObject.getTopLevelScope(scope); 105 | return cx.toObject(engine.getInterface(args[1], clazz), topLevel); 106 | } else { 107 | throw Context.reportRuntimeError("JavaAdapter requires two arguments"); 108 | } 109 | } 110 | 111 | private Invocable engine; 112 | } 113 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/javascript/RhinoClassShutter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.javascript; 27 | 28 | import org.mozilla.javascript.ClassShutter; 29 | 30 | import java.util.HashMap; 31 | import java.util.Map; 32 | 33 | /** 34 | * This class prevents script access to certain sensitive classes. 35 | * Note that this class checks over and above SecurityManager. i.e., although 36 | * a SecurityManager would pass, class shutter may still prevent access. 37 | * 38 | * @author A. Sundararajan 39 | * @since 1.6 40 | */ 41 | final class RhinoClassShutter implements ClassShutter { 42 | private static Map protectedClasses; 43 | private static RhinoClassShutter theInstance; 44 | 45 | private RhinoClassShutter() { 46 | } 47 | 48 | static synchronized ClassShutter getInstance() { 49 | if (theInstance == null) { 50 | theInstance = new RhinoClassShutter(); 51 | protectedClasses = new HashMap(); 52 | 53 | // For now, we just have AccessController. Allowing scripts 54 | // to this class will allow it to execute doPrivileged in 55 | // bootstrap context. We can add more classes for other reasons. 56 | protectedClasses.put("java.security.AccessController", Boolean.TRUE); 57 | } 58 | return theInstance; 59 | } 60 | 61 | public boolean visibleToScripts(String fullClassName) { 62 | // first do the security check. 63 | SecurityManager sm = System.getSecurityManager(); 64 | if (sm != null) { 65 | int i = fullClassName.lastIndexOf("."); 66 | if (i != -1) { 67 | try { 68 | sm.checkPackageAccess(fullClassName.substring(0, i)); 69 | } catch (SecurityException se) { 70 | return false; 71 | } 72 | } 73 | } 74 | // now, check is it a protected class. 75 | return protectedClasses.get(fullClassName) == null; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/javascript/RhinoCompiledScript.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.javascript; 27 | 28 | import org.mozilla.javascript.Context; 29 | import org.mozilla.javascript.JavaScriptException; 30 | import org.mozilla.javascript.RhinoException; 31 | import org.mozilla.javascript.Script; 32 | import org.mozilla.javascript.Scriptable; 33 | 34 | import javax.script.CompiledScript; 35 | import javax.script.ScriptContext; 36 | import javax.script.ScriptEngine; 37 | import javax.script.ScriptException; 38 | 39 | /** 40 | * Represents compiled JavaScript code. 41 | * 42 | * @author Mike Grogan 43 | * @since 1.6 44 | */ 45 | final class RhinoCompiledScript extends CompiledScript { 46 | 47 | private RhinoScriptEngine engine; 48 | private Script script; 49 | 50 | 51 | RhinoCompiledScript(RhinoScriptEngine engine, Script script) { 52 | this.engine = engine; 53 | this.script = script; 54 | } 55 | 56 | public Object eval(ScriptContext context) throws ScriptException { 57 | 58 | Object result = null; 59 | Context cx = RhinoScriptEngine.enterContext(); 60 | try { 61 | 62 | Scriptable scope = engine.getRuntimeScope(context); 63 | Object ret = script.exec(cx, scope); 64 | result = engine.unwrapReturnValue(ret); 65 | } catch (RhinoException re) { 66 | int line = (line = re.lineNumber()) == 0 ? -1 : line; 67 | String msg; 68 | if (re instanceof JavaScriptException) { 69 | msg = String.valueOf(((JavaScriptException)re).getValue()); 70 | } else { 71 | msg = re.toString(); 72 | } 73 | ScriptException se = new ScriptException(msg, re.sourceName(), line); 74 | se.initCause(re); 75 | throw se; 76 | } finally { 77 | Context.exit(); 78 | } 79 | 80 | return result; 81 | } 82 | 83 | public ScriptEngine getEngine() { 84 | return engine; 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/javascript/RhinoScriptEngine.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.javascript; 27 | 28 | import com.sun.script.util.InterfaceImplementor; 29 | 30 | import org.mozilla.javascript.Callable; 31 | import org.mozilla.javascript.Context; 32 | import org.mozilla.javascript.ContextFactory; 33 | import org.mozilla.javascript.Function; 34 | import org.mozilla.javascript.JavaScriptException; 35 | import org.mozilla.javascript.RhinoException; 36 | import org.mozilla.javascript.Script; 37 | import org.mozilla.javascript.Scriptable; 38 | import org.mozilla.javascript.ScriptableObject; 39 | import org.mozilla.javascript.Undefined; 40 | import org.mozilla.javascript.Wrapper; 41 | 42 | import java.io.IOException; 43 | import java.io.Reader; 44 | import java.io.StringReader; 45 | import java.lang.reflect.Method; 46 | import java.security.AccessControlContext; 47 | import java.security.AccessControlException; 48 | import java.security.AccessController; 49 | import java.security.AllPermission; 50 | import java.security.PrivilegedAction; 51 | import java.util.HashMap; 52 | import java.util.Map; 53 | 54 | import javax.script.AbstractScriptEngine; 55 | import javax.script.Bindings; 56 | import javax.script.Compilable; 57 | import javax.script.CompiledScript; 58 | import javax.script.Invocable; 59 | import javax.script.ScriptContext; 60 | import javax.script.ScriptEngine; 61 | import javax.script.ScriptEngineFactory; 62 | import javax.script.ScriptException; 63 | import javax.script.SimpleBindings; 64 | 65 | 66 | /** 67 | * Implementation of ScriptEngine using the Mozilla Rhino 68 | * interpreter. 69 | * 70 | * @author Mike Grogan 71 | * @author A. Sundararajan 72 | * @since 1.6 73 | */ 74 | public final class RhinoScriptEngine extends AbstractScriptEngine 75 | implements Invocable, Compilable { 76 | 77 | private static final boolean DEBUG = false; 78 | 79 | private AccessControlContext accCtxt; 80 | 81 | /* Scope where standard JavaScript objects and our 82 | * extensions to it are stored. Note that these are not 83 | * user defined engine level global variables. These are 84 | * variables have to be there on all compliant ECMAScript 85 | * scopes. We put these standard objects in this top level. 86 | */ 87 | private RhinoTopLevel topLevel; 88 | 89 | /* map used to store indexed properties in engine scope 90 | * refer to comment on 'indexedProps' in ExternalScriptable.java. 91 | */ 92 | private Map indexedProps; 93 | 94 | private ScriptEngineFactory factory; 95 | private InterfaceImplementor implementor; 96 | 97 | private static final int languageVersion = getLanguageVersion(); 98 | private static final int optimizationLevel = getOptimizationLevel(); 99 | 100 | static { 101 | ContextFactory.initGlobal(new ContextFactory() { 102 | /** 103 | * Create new Context instance to be associated with the current thread. 104 | */ 105 | @Override 106 | protected Context makeContext() { 107 | Context cx = super.makeContext(); 108 | cx.setLanguageVersion(languageVersion); 109 | cx.setOptimizationLevel(optimizationLevel); 110 | cx.setClassShutter(RhinoClassShutter.getInstance()); 111 | cx.setWrapFactory(RhinoWrapFactory.getInstance()); 112 | return cx; 113 | } 114 | 115 | /** 116 | * Execute top call to script or function. When the runtime is about to 117 | * execute a script or function that will create the first stack frame 118 | * with scriptable code, it calls this method to perform the real call. 119 | * In this way execution of any script happens inside this function. 120 | */ 121 | @Override 122 | protected Object doTopCall(final Callable callable, 123 | final Context cx, final Scriptable scope, 124 | final Scriptable thisObj, final Object[] args) { 125 | AccessControlContext accCtxt = null; 126 | Scriptable global = ScriptableObject.getTopLevelScope(scope); 127 | Scriptable globalProto = global.getPrototype(); 128 | if (globalProto instanceof RhinoTopLevel) { 129 | accCtxt = ((RhinoTopLevel)globalProto).getAccessContext(); 130 | } 131 | 132 | if (accCtxt != null) { 133 | return AccessController.doPrivileged(new PrivilegedAction() { 134 | public Object run() { 135 | return superDoTopCall(callable, cx, scope, thisObj, args); 136 | } 137 | }, accCtxt); 138 | } else { 139 | return superDoTopCall(callable, cx, scope, thisObj, args); 140 | } 141 | } 142 | 143 | private Object superDoTopCall(Callable callable, 144 | Context cx, Scriptable scope, 145 | Scriptable thisObj, Object[] args) { 146 | return super.doTopCall(callable, cx, scope, thisObj, args); 147 | } 148 | }); 149 | } 150 | 151 | private static final String RHINO_JS_VERSION = "rhino.js.version"; 152 | private static int getLanguageVersion() { 153 | int version; 154 | String tmp = java.security.AccessController.doPrivileged( 155 | new sun.security.action.GetPropertyAction(RHINO_JS_VERSION)); 156 | if (tmp != null) { 157 | version = Integer.parseInt((String)tmp); 158 | } else { 159 | version = Context.VERSION_1_8; 160 | } 161 | return version; 162 | } 163 | 164 | private static final String RHINO_OPT_LEVEL = "rhino.opt.level"; 165 | private static int getOptimizationLevel() { 166 | int optLevel = -1; 167 | // disable optimizer under security manager, for now. 168 | if (System.getSecurityManager() == null) { 169 | optLevel = Integer.getInteger(RHINO_OPT_LEVEL, -1); 170 | } 171 | return optLevel; 172 | } 173 | 174 | /** 175 | * Creates a new instance of RhinoScriptEngine 176 | */ 177 | public RhinoScriptEngine() { 178 | if (System.getSecurityManager() != null) { 179 | try { 180 | AccessController.checkPermission(new AllPermission()); 181 | } catch (AccessControlException ace) { 182 | accCtxt = AccessController.getContext(); 183 | } 184 | } 185 | 186 | Context cx = enterContext(); 187 | try { 188 | topLevel = new RhinoTopLevel(cx, this); 189 | } finally { 190 | cx.exit(); 191 | } 192 | 193 | indexedProps = new HashMap(); 194 | 195 | //construct object used to implement getInterface 196 | implementor = new InterfaceImplementor(this) { 197 | protected boolean isImplemented(Object thiz, Class iface) { 198 | Context cx = enterContext(); 199 | try { 200 | if (thiz != null && !(thiz instanceof Scriptable)) { 201 | thiz = cx.toObject(thiz, topLevel); 202 | } 203 | Scriptable engineScope = getRuntimeScope(context); 204 | Scriptable localScope = (thiz != null)? (Scriptable) thiz : 205 | engineScope; 206 | for (Method method : iface.getMethods()) { 207 | // ignore methods of java.lang.Object class 208 | if (method.getDeclaringClass() == Object.class) { 209 | continue; 210 | } 211 | Object obj = ScriptableObject.getProperty(localScope, method.getName()); 212 | if (! (obj instanceof Function)) { 213 | return false; 214 | } 215 | } 216 | return true; 217 | } finally { 218 | cx.exit(); 219 | } 220 | } 221 | 222 | protected Object convertResult(Method method, Object res) 223 | throws ScriptException { 224 | Class desiredType = method.getReturnType(); 225 | if (desiredType == Void.TYPE) { 226 | return null; 227 | } else { 228 | return Context.jsToJava(res, desiredType); 229 | } 230 | } 231 | }; 232 | } 233 | 234 | public Object eval(Reader reader, ScriptContext ctxt) 235 | throws ScriptException { 236 | Object ret; 237 | 238 | Context cx = enterContext(); 239 | try { 240 | Scriptable scope = getRuntimeScope(ctxt); 241 | String filename = (String) get(ScriptEngine.FILENAME); 242 | filename = filename == null ? "" : filename; 243 | 244 | ret = cx.evaluateReader(scope, reader, filename , 1, null); 245 | } catch (RhinoException re) { 246 | if (DEBUG) re.printStackTrace(); 247 | int line = (line = re.lineNumber()) == 0 ? -1 : line; 248 | String msg; 249 | if (re instanceof JavaScriptException) { 250 | msg = String.valueOf(((JavaScriptException)re).getValue()); 251 | } else { 252 | msg = re.toString(); 253 | } 254 | ScriptException se = new ScriptException(msg, re.sourceName(), line); 255 | se.initCause(re); 256 | throw se; 257 | } catch (IOException ee) { 258 | throw new ScriptException(ee); 259 | } finally { 260 | cx.exit(); 261 | } 262 | 263 | return unwrapReturnValue(ret); 264 | } 265 | 266 | public Object eval(String script, ScriptContext ctxt) throws ScriptException { 267 | if (script == null) { 268 | throw new NullPointerException("null script"); 269 | } 270 | return eval(new StringReader(script) , ctxt); 271 | } 272 | 273 | public ScriptEngineFactory getFactory() { 274 | if (factory != null) { 275 | return factory; 276 | } else { 277 | return new RhinoScriptEngineFactory(); 278 | } 279 | } 280 | 281 | public Bindings createBindings() { 282 | return new SimpleBindings(); 283 | } 284 | 285 | //Invocable methods 286 | public Object invokeFunction(String name, Object... args) 287 | throws ScriptException, NoSuchMethodException { 288 | return invoke(null, name, args); 289 | } 290 | 291 | public Object invokeMethod(Object thiz, String name, Object... args) 292 | throws ScriptException, NoSuchMethodException { 293 | if (thiz == null) { 294 | throw new IllegalArgumentException("script object can not be null"); 295 | } 296 | return invoke(thiz, name, args); 297 | } 298 | 299 | private Object invoke(Object thiz, String name, Object... args) 300 | throws ScriptException, NoSuchMethodException { 301 | Context cx = enterContext(); 302 | try { 303 | if (name == null) { 304 | throw new NullPointerException("method name is null"); 305 | } 306 | 307 | if (thiz != null && !(thiz instanceof Scriptable)) { 308 | thiz = cx.toObject(thiz, topLevel); 309 | } 310 | 311 | Scriptable engineScope = getRuntimeScope(context); 312 | Scriptable localScope = (thiz != null)? (Scriptable) thiz : 313 | engineScope; 314 | Object obj = ScriptableObject.getProperty(localScope, name); 315 | if (! (obj instanceof Function)) { 316 | throw new NoSuchMethodException("no such method: " + name); 317 | } 318 | 319 | Function func = (Function) obj; 320 | Scriptable scope = func.getParentScope(); 321 | if (scope == null) { 322 | scope = engineScope; 323 | } 324 | Object result = func.call(cx, scope, localScope, 325 | wrapArguments(args)); 326 | return unwrapReturnValue(result); 327 | } catch (RhinoException re) { 328 | if (DEBUG) re.printStackTrace(); 329 | int line = (line = re.lineNumber()) == 0 ? -1 : line; 330 | ScriptException se = new ScriptException(re.toString(), re.sourceName(), line); 331 | se.initCause(re); 332 | throw se; 333 | } finally { 334 | cx.exit(); 335 | } 336 | } 337 | 338 | public T getInterface(Class clasz) { 339 | try { 340 | return implementor.getInterface(null, clasz); 341 | } catch (ScriptException e) { 342 | return null; 343 | } 344 | } 345 | 346 | public T getInterface(Object thiz, Class clasz) { 347 | if (thiz == null) { 348 | throw new IllegalArgumentException("script object can not be null"); 349 | } 350 | 351 | try { 352 | return implementor.getInterface(thiz, clasz); 353 | } catch (ScriptException e) { 354 | return null; 355 | } 356 | } 357 | 358 | private static final String printSource = 359 | "function print(str, newline) { \n" + 360 | " if (typeof(str) == 'undefined') { \n" + 361 | " str = 'undefined'; \n" + 362 | " } else if (str == null) { \n" + 363 | " str = 'null'; \n" + 364 | " } \n" + 365 | " var out = context.getWriter(); \n" + 366 | " if (!(out instanceof java.io.PrintWriter))\n" + 367 | " out = new java.io.PrintWriter(out); \n" + 368 | " out.print(String(str)); \n" + 369 | " if (newline) out.print('\\n'); \n" + 370 | " out.flush(); \n" + 371 | "}\n" + 372 | "function println(str) { \n" + 373 | " print(str, true); \n" + 374 | "}"; 375 | 376 | Scriptable getRuntimeScope(ScriptContext ctxt) { 377 | if (ctxt == null) { 378 | throw new NullPointerException("null script context"); 379 | } 380 | 381 | // we create a scope for the given ScriptContext 382 | Scriptable newScope = new ExternalScriptable(ctxt, indexedProps); 383 | 384 | // Set the prototype of newScope to be 'topLevel' so that 385 | // JavaScript standard objects are visible from the scope. 386 | newScope.setPrototype(topLevel); 387 | 388 | // define "context" variable in the new scope 389 | newScope.put("context", newScope, ctxt); 390 | 391 | // define "print", "println" functions in the new scope 392 | Context cx = enterContext(); 393 | try { 394 | cx.evaluateString(newScope, printSource, "print", 1, null); 395 | } finally { 396 | cx.exit(); 397 | } 398 | return newScope; 399 | } 400 | 401 | 402 | //Compilable methods 403 | public CompiledScript compile(String script) throws ScriptException { 404 | return compile(new StringReader(script)); 405 | } 406 | 407 | public CompiledScript compile(java.io.Reader script) throws ScriptException { 408 | CompiledScript ret = null; 409 | Context cx = enterContext(); 410 | 411 | try { 412 | String fileName = (String) get(ScriptEngine.FILENAME); 413 | if (fileName == null) { 414 | fileName = ""; 415 | } 416 | 417 | Scriptable scope = getRuntimeScope(context); 418 | Script scr = cx.compileReader(scope, script, fileName, 1, null); 419 | ret = new RhinoCompiledScript(this, scr); 420 | } catch (Exception e) { 421 | if (DEBUG) e.printStackTrace(); 422 | throw new ScriptException(e); 423 | } finally { 424 | cx.exit(); 425 | } 426 | return ret; 427 | } 428 | 429 | 430 | //package-private helpers 431 | 432 | static Context enterContext() { 433 | // call this always so that initializer of this class runs 434 | // and initializes custom wrap factory and class shutter. 435 | return Context.enter(); 436 | } 437 | 438 | void setEngineFactory(ScriptEngineFactory fac) { 439 | factory = fac; 440 | } 441 | 442 | AccessControlContext getAccessContext() { 443 | return accCtxt; 444 | } 445 | 446 | Object[] wrapArguments(Object[] args) { 447 | if (args == null) { 448 | return Context.emptyArgs; 449 | } 450 | Object[] res = new Object[args.length]; 451 | for (int i = 0; i < res.length; i++) { 452 | res[i] = Context.javaToJS(args[i], topLevel); 453 | } 454 | return res; 455 | } 456 | 457 | Object unwrapReturnValue(Object result) { 458 | if (result instanceof Wrapper) { 459 | result = ( (Wrapper) result).unwrap(); 460 | } 461 | 462 | return result instanceof Undefined ? null : result; 463 | } 464 | 465 | /* 466 | public static void main(String[] args) throws Exception { 467 | if (args.length == 0) { 468 | System.out.println("No file specified"); 469 | return; 470 | } 471 | 472 | InputStreamReader r = new InputStreamReader(new FileInputStream(args[0])); 473 | ScriptEngine engine = new RhinoScriptEngine(); 474 | 475 | engine.put("x", "y"); 476 | engine.put(ScriptEngine.FILENAME, args[0]); 477 | engine.eval(r); 478 | System.out.println(engine.get("x")); 479 | } 480 | */ 481 | } 482 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/javascript/RhinoScriptEngineFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.javascript; 27 | 28 | import com.sun.script.util.ScriptEngineFactoryBase; 29 | 30 | import java.util.ArrayList; 31 | import java.util.Collections; 32 | import java.util.List; 33 | 34 | import javax.script.ScriptEngine; 35 | 36 | /** 37 | * Factory to create RhinoScriptEngine 38 | * 39 | * @author Mike Grogan 40 | * @since 1.6 41 | */ 42 | public class RhinoScriptEngineFactory extends ScriptEngineFactoryBase { 43 | 44 | public RhinoScriptEngineFactory() { 45 | } 46 | 47 | public List getExtensions() { 48 | return extensions; 49 | } 50 | 51 | public List getMimeTypes() { 52 | return mimeTypes; 53 | } 54 | 55 | public List getNames() { 56 | return names; 57 | } 58 | 59 | public Object getParameter(String key) { 60 | if (key.equals(ScriptEngine.NAME)) { 61 | return "javascript"; 62 | } else if (key.equals(ScriptEngine.ENGINE)) { 63 | return "Mozilla Rhino"; 64 | } else if (key.equals(ScriptEngine.ENGINE_VERSION)) { 65 | return "1.7.7"; 66 | } else if (key.equals(ScriptEngine.LANGUAGE)) { 67 | return "ECMAScript"; 68 | } else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) { 69 | return "1.8"; 70 | } else if (key.equals("THREADING")) { 71 | return "MULTITHREADED"; 72 | } else { 73 | throw new IllegalArgumentException("Invalid key"); 74 | } 75 | } 76 | 77 | public ScriptEngine getScriptEngine() { 78 | RhinoScriptEngine ret = new RhinoScriptEngine(); 79 | ret.setEngineFactory(this); 80 | return ret; 81 | } 82 | 83 | public String getMethodCallSyntax(String obj, String method, String... args) { 84 | 85 | String ret = obj + "." + method + "("; 86 | int len = args.length; 87 | if (len == 0) { 88 | ret += ")"; 89 | return ret; 90 | } 91 | 92 | for (int i = 0; i < len; i++) { 93 | ret += args[i]; 94 | if (i != len - 1) { 95 | ret += ","; 96 | } else { 97 | ret += ")"; 98 | } 99 | } 100 | return ret; 101 | } 102 | 103 | public String getOutputStatement(String toDisplay) { 104 | StringBuffer buf = new StringBuffer(); 105 | int len = toDisplay.length(); 106 | buf.append("print(\""); 107 | for (int i = 0; i < len; i++) { 108 | char ch = toDisplay.charAt(i); 109 | switch (ch) { 110 | case '"': 111 | buf.append("\\\""); 112 | break; 113 | case '\\': 114 | buf.append("\\\\"); 115 | break; 116 | default: 117 | buf.append(ch); 118 | break; 119 | } 120 | } 121 | buf.append("\")"); 122 | return buf.toString(); 123 | } 124 | 125 | public String getProgram(String... statements) { 126 | int len = statements.length; 127 | String ret = ""; 128 | for (int i = 0; i < len; i++) { 129 | ret += statements[i] + ";"; 130 | } 131 | 132 | return ret; 133 | } 134 | 135 | /* 136 | public static void main(String[] args) { 137 | RhinoScriptEngineFactory fact = new RhinoScriptEngineFactory(); 138 | System.out.println(fact.getParameter(ScriptEngine.ENGINE_VERSION)); 139 | } 140 | */ 141 | 142 | private static List names; 143 | private static List mimeTypes; 144 | private static List extensions; 145 | 146 | static { 147 | names = new ArrayList(6); 148 | names.add("js"); 149 | names.add("rhino"); 150 | names.add("mozilla.rhino"); 151 | names.add("javascript"); 152 | names.add("ECMAScript"); 153 | names.add("ecmascript"); 154 | names = Collections.unmodifiableList(names); 155 | 156 | mimeTypes = new ArrayList(4); 157 | mimeTypes.add("application/javascript"); 158 | mimeTypes.add("application/ecmascript"); 159 | mimeTypes.add("text/javascript"); 160 | mimeTypes.add("text/ecmascript"); 161 | mimeTypes = Collections.unmodifiableList(mimeTypes); 162 | 163 | extensions = new ArrayList(1); 164 | extensions.add("js"); 165 | extensions = Collections.unmodifiableList(extensions); 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/javascript/RhinoTopLevel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.javascript; 27 | 28 | import org.mozilla.javascript.Context; 29 | import org.mozilla.javascript.Function; 30 | import org.mozilla.javascript.ImporterTopLevel; 31 | import org.mozilla.javascript.LazilyLoadedCtor; 32 | import org.mozilla.javascript.Scriptable; 33 | import org.mozilla.javascript.ScriptableObject; 34 | import org.mozilla.javascript.Synchronizer; 35 | import org.mozilla.javascript.Wrapper; 36 | 37 | import java.security.AccessControlContext; 38 | 39 | import javax.script.Bindings; 40 | import javax.script.ScriptContext; 41 | import javax.script.SimpleScriptContext; 42 | 43 | /** 44 | * This class serves as top level scope for Rhino. This class adds 45 | * 3 top level functions (bindings, scope, sync) and two constructors 46 | * (JSAdapter, JavaAdapter). 47 | * 48 | * @author A. Sundararajan 49 | * @since 1.6 50 | */ 51 | public final class RhinoTopLevel extends ImporterTopLevel { 52 | RhinoTopLevel(Context cx, RhinoScriptEngine engine) { 53 | // second boolean parameter to super constructor tells whether 54 | // to seal standard JavaScript objects or not. If security manager 55 | // is present, we seal the standard objects. 56 | super(cx, System.getSecurityManager() != null); 57 | this.engine = engine; 58 | 59 | // initialize JSAdapter lazily. Reduces footprint & startup time. 60 | new LazilyLoadedCtor(this, "JSAdapter", 61 | "com.sun.script.javascript.JSAdapter", 62 | false); 63 | 64 | /* 65 | * initialize JavaAdapter. We can't lazy initialize this because 66 | * lazy initializer attempts to define a new property. But, JavaAdapter 67 | * is an exisiting property that we overwrite. 68 | */ 69 | JavaAdapter.init(cx, this, false); 70 | 71 | // add top level functions 72 | String names[] = { "bindings", "scope", "sync" }; 73 | defineFunctionProperties(names, RhinoTopLevel.class, 74 | ScriptableObject.DONTENUM); 75 | } 76 | 77 | /** 78 | * The bindings function takes a JavaScript scope object 79 | * of type ExternalScriptable and returns the underlying Bindings 80 | * instance. 81 | * 82 | * var page = scope(pageBindings); 83 | * with (page) { 84 | * // code that uses page scope 85 | * } 86 | * var b = bindings(page); 87 | * // operate on bindings here. 88 | */ 89 | public static Object bindings(Context cx, Scriptable thisObj, Object[] args, 90 | Function funObj) { 91 | if (args.length == 1) { 92 | Object arg = args[0]; 93 | if (arg instanceof Wrapper) { 94 | arg = ((Wrapper)arg).unwrap(); 95 | } 96 | if (arg instanceof ExternalScriptable) { 97 | ScriptContext ctx = ((ExternalScriptable)arg).getContext(); 98 | Bindings bind = ctx.getBindings(ScriptContext.ENGINE_SCOPE); 99 | return Context.javaToJS(bind, 100 | ScriptableObject.getTopLevelScope(thisObj)); 101 | } 102 | } 103 | return cx.getUndefinedValue(); 104 | } 105 | 106 | /** 107 | * The scope function creates a new JavaScript scope object 108 | * with given Bindings object as backing store. This can be used 109 | * to create a script scope based on arbitrary Bindings instance. 110 | * For example, in webapp scenario, a 'page' level Bindings instance 111 | * may be wrapped as a scope and code can be run in JavaScripe 'with' 112 | * statement: 113 | * 114 | * var page = scope(pageBindings); 115 | * with (page) { 116 | * // code that uses page scope 117 | * } 118 | */ 119 | public static Object scope(Context cx, Scriptable thisObj, Object[] args, 120 | Function funObj) { 121 | if (args.length == 1) { 122 | Object arg = args[0]; 123 | if (arg instanceof Wrapper) { 124 | arg = ((Wrapper)arg).unwrap(); 125 | } 126 | if (arg instanceof Bindings) { 127 | ScriptContext ctx = new SimpleScriptContext(); 128 | ctx.setBindings((Bindings)arg, ScriptContext.ENGINE_SCOPE); 129 | Scriptable res = new ExternalScriptable(ctx); 130 | res.setPrototype(ScriptableObject.getObjectPrototype(thisObj)); 131 | res.setParentScope(ScriptableObject.getTopLevelScope(thisObj)); 132 | return res; 133 | } 134 | } 135 | return cx.getUndefinedValue(); 136 | } 137 | 138 | /** 139 | * The sync function creates a synchronized function (in the sense 140 | * of a Java synchronized method) from an existing function. The 141 | * new function synchronizes on the this object of 142 | * its invocation. 143 | * {@code 144 | * js> var o = { f : sync(function(x) { 145 | * print("entry"); 146 | * Packages.java.lang.Thread.sleep(x*1000); 147 | * print("exit"); 148 | * })}; 149 | * js> thread(function() {o.f(5);}); 150 | * entry 151 | * js> thread(function() {o.f(5);}); 152 | * js> 153 | * exit 154 | * entry 155 | * exit 156 | * } 157 | */ 158 | public static Object sync(Context cx, Scriptable thisObj, Object[] args, 159 | Function funObj) { 160 | if (args.length == 1 && args[0] instanceof Function) { 161 | return new Synchronizer((Function)args[0]); 162 | } else { 163 | throw Context.reportRuntimeError("wrong argument(s) for sync"); 164 | } 165 | } 166 | 167 | RhinoScriptEngine getScriptEngine() { 168 | return engine; 169 | } 170 | 171 | AccessControlContext getAccessContext() { 172 | return engine.getAccessContext(); 173 | } 174 | 175 | private RhinoScriptEngine engine; 176 | } 177 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/javascript/RhinoWrapFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.javascript; 27 | 28 | import org.mozilla.javascript.ClassShutter; 29 | import org.mozilla.javascript.Context; 30 | import org.mozilla.javascript.NativeJavaObject; 31 | import org.mozilla.javascript.Scriptable; 32 | import org.mozilla.javascript.WrapFactory; 33 | 34 | import java.lang.reflect.Member; 35 | import java.lang.reflect.Modifier; 36 | 37 | import static sun.security.util.SecurityConstants.GET_CLASSLOADER_PERMISSION; 38 | 39 | /** 40 | * This wrap factory is used for security reasons. JSR 223 script 41 | * engine interface and JavaScript engine classes are run as bootstrap 42 | * classes. For example, java.lang.Class.forName method (when called without 43 | * class loader) uses caller's class loader. This may be exploited by script 44 | * authors to access classes otherwise not accessible. For example, 45 | * classes in sun.* namespace are normally not accessible to untrusted 46 | * code and hence should not be accessible to JavaScript run from 47 | * untrusted code. 48 | * 49 | * @author A. Sundararajan 50 | * @since 1.6 51 | */ 52 | final class RhinoWrapFactory extends WrapFactory { 53 | private RhinoWrapFactory() {} 54 | private static RhinoWrapFactory theInstance; 55 | 56 | static synchronized WrapFactory getInstance() { 57 | if (theInstance == null) { 58 | theInstance = new RhinoWrapFactory(); 59 | } 60 | return theInstance; 61 | } 62 | 63 | // We use instance of this class to wrap security sensitive 64 | // Java object. Please refer below. 65 | private static class RhinoJavaObject extends NativeJavaObject { 66 | RhinoJavaObject(Scriptable scope, Object obj, Class type) { 67 | // we pass 'null' to object. NativeJavaObject uses 68 | // passed 'type' to reflect fields and methods when 69 | // object is null. 70 | super(scope, null, type); 71 | 72 | // Now, we set actual object. 'javaObject' is protected 73 | // field of NativeJavaObject. 74 | javaObject = obj; 75 | } 76 | } 77 | 78 | public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, 79 | Object javaObject, Class staticType) { 80 | SecurityManager sm = System.getSecurityManager(); 81 | ClassShutter classShutter = RhinoClassShutter.getInstance(); 82 | if (javaObject instanceof ClassLoader) { 83 | // Check with Security Manager whether we can expose a 84 | // ClassLoader... 85 | if (sm != null) { 86 | sm.checkPermission(GET_CLASSLOADER_PERMISSION); 87 | } 88 | // if we fall through here, check permission succeeded. 89 | return super.wrapAsJavaObject(cx, scope, javaObject, staticType); 90 | } else { 91 | String name = null; 92 | if (javaObject instanceof Class) { 93 | name = ((Class)javaObject).getName(); 94 | } else if (javaObject instanceof Member) { 95 | Member member = (Member) javaObject; 96 | // Check member access. Don't allow reflective access to 97 | // non-public members. Note that we can't call checkMemberAccess 98 | // because that expects exact stack depth! 99 | if (sm != null && !Modifier.isPublic(member.getModifiers())) { 100 | return null; 101 | } 102 | name = member.getDeclaringClass().getName(); 103 | } 104 | // Now, make sure that no ClassShutter prevented Class or Member 105 | // of it is accessed reflectively. Note that ClassShutter may 106 | // prevent access to a class, even though SecurityManager permit. 107 | if (name != null) { 108 | if (!classShutter.visibleToScripts(name)) { 109 | return null; 110 | } else { 111 | return super.wrapAsJavaObject(cx, scope, javaObject, staticType); 112 | } 113 | } 114 | } 115 | 116 | // we have got some non-reflective object. 117 | Class dynamicType = javaObject.getClass(); 118 | String name = dynamicType.getName(); 119 | if (!classShutter.visibleToScripts(name)) { 120 | // Object of some sensitive class (such as sun.net.www.* 121 | // objects returned from public method of java.net.URL class. 122 | // We expose this object as though it is an object of some 123 | // super class that is safe for access. 124 | 125 | Class type = null; 126 | 127 | // Whenever a Java Object is wrapped, we are passed with a 128 | // staticType which is the type found from environment. For 129 | // example, method return type known from signature. The dynamic 130 | // type would be the actual Class of the actual returned object. 131 | // If the staticType is an interface, we just use that type. 132 | if (staticType != null && staticType.isInterface()) { 133 | type = staticType; 134 | } else { 135 | // dynamicType is always a class type and never an interface. 136 | // find an accessible super class of the dynamic type. 137 | while (dynamicType != null) { 138 | dynamicType = dynamicType.getSuperclass(); 139 | name = dynamicType.getName(); 140 | if (classShutter.visibleToScripts(name)) { 141 | type = dynamicType; break; 142 | } 143 | } 144 | // atleast java.lang.Object has to be accessible. So, when 145 | // we reach here, type variable should not be null. 146 | assert type != null: 147 | "even java.lang.Object is not accessible?"; 148 | } 149 | // create custom wrapper with the 'safe' type. 150 | return new RhinoJavaObject(scope, javaObject, type); 151 | } else { 152 | return super.wrapAsJavaObject(cx, scope, javaObject, staticType); 153 | } 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/util/InterfaceImplementor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.util; 27 | 28 | import java.lang.reflect.InvocationHandler; 29 | import java.lang.reflect.Method; 30 | import java.lang.reflect.Proxy; 31 | import java.security.AccessControlContext; 32 | import java.security.AccessController; 33 | import java.security.PrivilegedExceptionAction; 34 | 35 | import javax.script.Invocable; 36 | import javax.script.ScriptException; 37 | 38 | /* 39 | * java.lang.reflect.Proxy based interface implementor. This is meant 40 | * to be used to implement Invocable.getInterface. 41 | * 42 | * @author Mike Grogan 43 | * @since 1.6 44 | */ 45 | public class InterfaceImplementor { 46 | 47 | private Invocable engine; 48 | 49 | /** Creates a new instance of Invocable */ 50 | public InterfaceImplementor(Invocable engine) { 51 | this.engine = engine; 52 | } 53 | 54 | private final class InterfaceImplementorInvocationHandler 55 | implements InvocationHandler { 56 | private Object thiz; 57 | private AccessControlContext accCtxt; 58 | 59 | public InterfaceImplementorInvocationHandler(Object thiz, 60 | AccessControlContext accCtxt) { 61 | this.thiz = thiz; 62 | this.accCtxt = accCtxt; 63 | } 64 | 65 | public Object invoke(Object proxy , Method method, Object[] args) 66 | throws java.lang.Throwable { 67 | // give chance to convert input args 68 | args = convertArguments(method, args); 69 | Object result; 70 | final Method m = method; 71 | final Object[] a = args; 72 | result = AccessController.doPrivileged(new PrivilegedExceptionAction() { 73 | public Object run() throws Exception { 74 | if (thiz == null) { 75 | return engine.invokeFunction(m.getName(), a); 76 | } else { 77 | return engine.invokeMethod(thiz, m.getName(), a); 78 | } 79 | } 80 | }, accCtxt); 81 | // give chance to convert the method result 82 | return convertResult(method, result); 83 | } 84 | } 85 | 86 | public T getInterface(Object thiz, Class iface) 87 | throws ScriptException { 88 | if (iface == null || !iface.isInterface()) { 89 | throw new IllegalArgumentException("interface Class expected"); 90 | } 91 | if (! isImplemented(thiz, iface)) { 92 | return null; 93 | } 94 | AccessControlContext accCtxt = AccessController.getContext(); 95 | return iface.cast(Proxy.newProxyInstance(iface.getClassLoader(), 96 | new Class[]{iface}, 97 | new InterfaceImplementorInvocationHandler(thiz, accCtxt))); 98 | } 99 | 100 | protected boolean isImplemented(Object thiz, Class iface) { 101 | return true; 102 | } 103 | 104 | // called to convert method result after invoke 105 | protected Object convertResult(Method method, Object res) 106 | throws ScriptException { 107 | // default is identity conversion 108 | return res; 109 | } 110 | 111 | // called to convert method arguments before invoke 112 | protected Object[] convertArguments(Method method, Object[] args) 113 | throws ScriptException { 114 | // default is identity conversion 115 | return args; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/com/sun/script/util/ScriptEngineFactoryBase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package com.sun.script.util; 27 | 28 | import javax.script.ScriptEngine; 29 | import javax.script.ScriptEngineFactory; 30 | 31 | /* 32 | * Abstract super class for factory implementations. 33 | * 34 | * @author Mike Grogan 35 | * @since 1.6 36 | */ 37 | public abstract class ScriptEngineFactoryBase implements ScriptEngineFactory { 38 | 39 | public String getName() { 40 | return (String)getParameter(ScriptEngine.NAME); 41 | } 42 | 43 | public String getEngineName() { 44 | return (String)getParameter(ScriptEngine.ENGINE); 45 | } 46 | 47 | public String getEngineVersion() { 48 | return (String)getParameter(ScriptEngine.ENGINE_VERSION); 49 | } 50 | 51 | public String getLanguageName() { 52 | return (String)getParameter(ScriptEngine.LANGUAGE); 53 | } 54 | 55 | public String getLanguageVersion() { 56 | return (String)getParameter(ScriptEngine.LANGUAGE_VERSION); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/sun/misc/Service.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package sun.misc; 27 | 28 | import java.io.BufferedReader; 29 | import java.io.IOException; 30 | import java.io.InputStream; 31 | import java.io.InputStreamReader; 32 | import java.net.URL; 33 | import java.util.ArrayList; 34 | import java.util.Enumeration; 35 | import java.util.Iterator; 36 | import java.util.List; 37 | import java.util.NoSuchElementException; 38 | import java.util.Set; 39 | import java.util.TreeSet; 40 | 41 | 42 | /** 43 | * A simple service-provider lookup mechanism. A service is a 44 | * well-known set of interfaces and (usually abstract) classes. A service 45 | * provider is a specific implementation of a service. The classes in a 46 | * provider typically implement the interfaces and subclass the classes defined 47 | * in the service itself. Service providers may be installed in an 48 | * implementation of the Java platform in the form of extensions, that is, jar 49 | * files placed into any of the usual extension directories. Providers may 50 | * also be made available by adding them to the applet or application class 51 | * path or by some other platform-specific means. 52 | * 53 | *

In this lookup mechanism a service is represented by an interface or an 54 | * abstract class. (A concrete class may be used, but this is not 55 | * recommended.) A provider of a given service contains one or more concrete 56 | * classes that extend this service class with data and code specific to 57 | * the provider. This provider class will typically not be the entire 58 | * provider itself but rather a proxy that contains enough information to 59 | * decide whether the provider is able to satisfy a particular request together 60 | * with code that can create the actual provider on demand. The details of 61 | * provider classes tend to be highly service-specific; no single class or 62 | * interface could possibly unify them, so no such class has been defined. The 63 | * only requirement enforced here is that provider classes must have a 64 | * zero-argument constructor so that they may be instantiated during lookup. 65 | * 66 | *

A service provider identifies itself by placing a provider-configuration 67 | * file in the resource directory META-INF/services. The file's name 68 | * should consist of the fully-qualified name of the abstract service class. 69 | * The file should contain a list of fully-qualified concrete provider-class 70 | * names, one per line. Space and tab characters surrounding each name, as 71 | * well as blank lines, are ignored. The comment character is '#' 72 | * (0x23); on each line all characters following the first comment 73 | * character are ignored. The file must be encoded in UTF-8. 74 | * 75 | *

If a particular concrete provider class is named in more than one 76 | * configuration file, or is named in the same configuration file more than 77 | * once, then the duplicates will be ignored. The configuration file naming a 78 | * particular provider need not be in the same jar file or other distribution 79 | * unit as the provider itself. The provider must be accessible from the same 80 | * class loader that was initially queried to locate the configuration file; 81 | * note that this is not necessarily the class loader that found the file. 82 | * 83 | *

Example: Suppose we have a service class named 84 | * java.io.spi.CharCodec. It has two abstract methods: 85 | * 86 | *

 87 |  *   public abstract CharEncoder getEncoder(String encodingName);
 88 |  *   public abstract CharDecoder getDecoder(String encodingName);
 89 |  * 
90 | * 91 | * Each method returns an appropriate object or null if it cannot 92 | * translate the given encoding. Typical CharCodec providers will 93 | * support more than one encoding. 94 | * 95 | *

If sun.io.StandardCodec is a provider of the CharCodec 96 | * service then its jar file would contain the file 97 | * META-INF/services/java.io.spi.CharCodec. This file would contain 98 | * the single line: 99 | * 100 | *

101 |  *   sun.io.StandardCodec    # Standard codecs for the platform
102 |  * 
103 | * 104 | * To locate an encoder for a given encoding name, the internal I/O code would 105 | * do something like this: 106 | * 107 | *
108 |  *   CharEncoder getEncoder(String encodingName) {
109 |  *       Iterator ps = Service.providers(CharCodec.class);
110 |  *       while (ps.hasNext()) {
111 |  *           CharCodec cc = (CharCodec)ps.next();
112 |  *           CharEncoder ce = cc.getEncoder(encodingName);
113 |  *           if (ce != null)
114 |  *               return ce;
115 |  *       }
116 |  *       return null;
117 |  *   }
118 |  * 
119 | * 120 | * The provider-lookup mechanism always executes in the security context of the 121 | * caller. Trusted system code should typically invoke the methods in this 122 | * class from within a privileged security context. 123 | * 124 | * @author Mark Reinhold 125 | * @since 1.3 126 | */ 127 | 128 | public final class Service { 129 | 130 | private static final String prefix = "META-INF/services/"; 131 | 132 | private Service() { } 133 | 134 | private static void fail(Class service, String msg, Throwable cause) 135 | throws ServiceConfigurationError 136 | { 137 | ServiceConfigurationError sce 138 | = new ServiceConfigurationError(service.getName() + ": " + msg); 139 | sce.initCause(cause); 140 | throw sce; 141 | } 142 | 143 | private static void fail(Class service, String msg) 144 | throws ServiceConfigurationError 145 | { 146 | throw new ServiceConfigurationError(service.getName() + ": " + msg); 147 | } 148 | 149 | private static void fail(Class service, URL u, int line, String msg) 150 | throws ServiceConfigurationError 151 | { 152 | fail(service, u + ":" + line + ": " + msg); 153 | } 154 | 155 | /** 156 | * Parse a single line from the given configuration file, adding the name 157 | * on the line to both the names list and the returned set iff the name is 158 | * not already a member of the returned set. 159 | */ 160 | private static int parseLine(Class service, URL u, BufferedReader r, int lc, 161 | List names, Set returned) 162 | throws IOException, ServiceConfigurationError 163 | { 164 | String ln = r.readLine(); 165 | if (ln == null) { 166 | return -1; 167 | } 168 | int ci = ln.indexOf('#'); 169 | if (ci >= 0) ln = ln.substring(0, ci); 170 | ln = ln.trim(); 171 | int n = ln.length(); 172 | if (n != 0) { 173 | if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0)) 174 | fail(service, u, lc, "Illegal configuration-file syntax"); 175 | int cp = ln.codePointAt(0); 176 | if (!Character.isJavaIdentifierStart(cp)) 177 | fail(service, u, lc, "Illegal provider-class name: " + ln); 178 | for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) { 179 | cp = ln.codePointAt(i); 180 | if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) 181 | fail(service, u, lc, "Illegal provider-class name: " + ln); 182 | } 183 | if (!returned.contains(ln)) { 184 | names.add(ln); 185 | returned.add(ln); 186 | } 187 | } 188 | return lc + 1; 189 | } 190 | 191 | /** 192 | * Parse the content of the given URL as a provider-configuration file. 193 | * 194 | * @param service 195 | * The service class for which providers are being sought; 196 | * used to construct error detail strings 197 | * 198 | * @param url 199 | * The URL naming the configuration file to be parsed 200 | * 201 | * @param returned 202 | * A Set containing the names of provider classes that have already 203 | * been returned. This set will be updated to contain the names 204 | * that will be yielded from the returned Iterator. 205 | * 206 | * @return A (possibly empty) Iterator that will yield the 207 | * provider-class names in the given configuration file that are 208 | * not yet members of the returned set 209 | * 210 | * @throws ServiceConfigurationError 211 | * If an I/O error occurs while reading from the given URL, or 212 | * if a configuration-file format error is detected 213 | */ 214 | private static Iterator parse(Class service, URL u, Set returned) 215 | throws ServiceConfigurationError 216 | { 217 | InputStream in = null; 218 | BufferedReader r = null; 219 | ArrayList names = new ArrayList(); 220 | try { 221 | in = u.openStream(); 222 | r = new BufferedReader(new InputStreamReader(in, "utf-8")); 223 | int lc = 1; 224 | while ((lc = parseLine(service, u, r, lc, names, returned)) >= 0); 225 | } catch (IOException x) { 226 | fail(service, ": " + x); 227 | } finally { 228 | try { 229 | if (r != null) r.close(); 230 | if (in != null) in.close(); 231 | } catch (IOException y) { 232 | fail(service, ": " + y); 233 | } 234 | } 235 | return names.iterator(); 236 | } 237 | 238 | 239 | /** 240 | * Private inner class implementing fully-lazy provider lookup 241 | */ 242 | private static class LazyIterator implements Iterator { 243 | 244 | Class service; 245 | ClassLoader loader; 246 | Enumeration configs = null; 247 | Iterator pending = null; 248 | Set returned = new TreeSet(); 249 | String nextName = null; 250 | 251 | private LazyIterator(Class service, ClassLoader loader) { 252 | this.service = service; 253 | this.loader = loader; 254 | } 255 | 256 | public boolean hasNext() throws ServiceConfigurationError { 257 | if (nextName != null) { 258 | return true; 259 | } 260 | if (configs == null) { 261 | try { 262 | String fullName = prefix + service.getName(); 263 | if (loader == null) 264 | configs = ClassLoader.getSystemResources(fullName); 265 | else 266 | configs = loader.getResources(fullName); 267 | } catch (IOException x) { 268 | fail(service, ": " + x); 269 | } 270 | } 271 | while ((pending == null) || !pending.hasNext()) { 272 | if (!configs.hasMoreElements()) { 273 | return false; 274 | } 275 | pending = parse(service, (URL)configs.nextElement(), returned); 276 | } 277 | nextName = (String)pending.next(); 278 | return true; 279 | } 280 | 281 | public Object next() throws ServiceConfigurationError { 282 | if (!hasNext()) { 283 | throw new NoSuchElementException(); 284 | } 285 | String cn = nextName; 286 | nextName = null; 287 | Class c = null; 288 | try { 289 | c = Class.forName(cn, false, loader); 290 | } catch (ClassNotFoundException x) { 291 | fail(service, 292 | "Provider " + cn + " not found"); 293 | } 294 | if (!service.isAssignableFrom(c)) { 295 | fail(service, 296 | "Provider " + cn + " not a subtype"); 297 | } 298 | try { 299 | return service.cast(c.newInstance()); 300 | } catch (Throwable x) { 301 | fail(service, 302 | "Provider " + cn + " could not be instantiated: " + x, 303 | x); 304 | } 305 | return null; /* This cannot happen */ 306 | } 307 | 308 | public void remove() { 309 | throw new UnsupportedOperationException(); 310 | } 311 | 312 | } 313 | 314 | 315 | /** 316 | * Locates and incrementally instantiates the available providers of a 317 | * given service using the given class loader. 318 | * 319 | *

This method transforms the name of the given service class into a 320 | * provider-configuration filename as described above and then uses the 321 | * getResources method of the given class loader to find all 322 | * available files with that name. These files are then read and parsed to 323 | * produce a list of provider-class names. The iterator that is returned 324 | * uses the given class loader to lookup and then instantiate each element 325 | * of the list. 326 | * 327 | *

Because it is possible for extensions to be installed into a running 328 | * Java virtual machine, this method may return different results each time 329 | * it is invoked.

330 | * 331 | * @param service 332 | * The service's abstract service class 333 | * 334 | * @param loader 335 | * The class loader to be used to load provider-configuration files 336 | * and instantiate provider classes, or null if the system 337 | * class loader (or, failing that the bootstrap class loader) is to 338 | * be used 339 | * 340 | * @return An Iterator that yields provider objects for the given 341 | * service, in some arbitrary order. The iterator will throw a 342 | * ServiceConfigurationError if a provider-configuration 343 | * file violates the specified format or if a provider class cannot 344 | * be found and instantiated. 345 | * 346 | * @throws ServiceConfigurationError 347 | * If a provider-configuration file violates the specified format 348 | * or names a provider class that cannot be found and instantiated 349 | * 350 | * @see #providers(java.lang.Class) 351 | * @see #installedProviders(java.lang.Class) 352 | */ 353 | public static Iterator providers(Class service, ClassLoader loader) 354 | throws ServiceConfigurationError 355 | { 356 | return new LazyIterator(service, loader); 357 | } 358 | 359 | 360 | /** 361 | * Locates and incrementally instantiates the available providers of a 362 | * given service using the context class loader. This convenience method 363 | * is equivalent to 364 | * 365 | *

366 |      *   ClassLoader cl = Thread.currentThread().getContextClassLoader();
367 |      *   return Service.providers(service, cl);
368 |      * 
369 | * 370 | * @param service 371 | * The service's abstract service class 372 | * 373 | * @return An Iterator that yields provider objects for the given 374 | * service, in some arbitrary order. The iterator will throw a 375 | * ServiceConfigurationError if a provider-configuration 376 | * file violates the specified format or if a provider class cannot 377 | * be found and instantiated. 378 | * 379 | * @throws ServiceConfigurationError 380 | * If a provider-configuration file violates the specified format 381 | * or names a provider class that cannot be found and instantiated 382 | * 383 | * @see #providers(java.lang.Class, java.lang.ClassLoader) 384 | */ 385 | public static Iterator providers(Class service) 386 | throws ServiceConfigurationError 387 | { 388 | ClassLoader cl = Thread.currentThread().getContextClassLoader(); 389 | return Service.providers(service, cl); 390 | } 391 | 392 | 393 | /** 394 | * Locates and incrementally instantiates the available providers of a 395 | * given service using the extension class loader. This convenience method 396 | * simply locates the extension class loader, call it 397 | * extClassLoader, and then does 398 | * 399 | *
400 |      *   return Service.providers(service, extClassLoader);
401 |      * 
402 | * 403 | * If the extension class loader cannot be found then the system class 404 | * loader is used; if there is no system class loader then the bootstrap 405 | * class loader is used. 406 | * 407 | * @param service 408 | * The service's abstract service class 409 | * 410 | * @return An Iterator that yields provider objects for the given 411 | * service, in some arbitrary order. The iterator will throw a 412 | * ServiceConfigurationError if a provider-configuration 413 | * file violates the specified format or if a provider class cannot 414 | * be found and instantiated. 415 | * 416 | * @throws ServiceConfigurationError 417 | * If a provider-configuration file violates the specified format 418 | * or names a provider class that cannot be found and instantiated 419 | * 420 | * @see #providers(java.lang.Class, java.lang.ClassLoader) 421 | */ 422 | public static Iterator installedProviders(Class service) 423 | throws ServiceConfigurationError 424 | { 425 | ClassLoader cl = ClassLoader.getSystemClassLoader(); 426 | ClassLoader prev = null; 427 | while (cl != null) { 428 | prev = cl; 429 | cl = cl.getParent(); 430 | } 431 | return Service.providers(service, prev); 432 | } 433 | 434 | } 435 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/sun/misc/ServiceConfigurationError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package sun.misc; 27 | 28 | 29 | /** 30 | * Error thrown when something goes wrong while looking up service providers. 31 | * In particular, this error will be thrown in the following situations: 32 | * 33 | *
    34 | *
  • A concrete provider class cannot be found, 35 | *
  • A concrete provider class cannot be instantiated, 36 | *
  • The format of a provider-configuration file is illegal, or 37 | *
  • An IOException occurs while reading a provider-configuration file. 38 | *
39 | * 40 | * @author Mark Reinhold 41 | * @since 1.3 42 | */ 43 | 44 | public class ServiceConfigurationError extends Error { 45 | 46 | /** 47 | * Constructs a new instance with the specified detail string. 48 | */ 49 | public ServiceConfigurationError(String msg) { 50 | super(msg); 51 | } 52 | 53 | /** 54 | * Constructs a new instance that wraps the specified throwable. 55 | */ 56 | public ServiceConfigurationError(Throwable x) { 57 | super(x); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/sun/misc/VM.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package sun.misc; 27 | 28 | import java.util.Properties; 29 | 30 | import static java.lang.Thread.State.BLOCKED; 31 | import static java.lang.Thread.State.NEW; 32 | import static java.lang.Thread.State.RUNNABLE; 33 | import static java.lang.Thread.State.TERMINATED; 34 | import static java.lang.Thread.State.TIMED_WAITING; 35 | import static java.lang.Thread.State.WAITING; 36 | 37 | public class VM { 38 | 39 | /* The following methods used to be native methods that instruct 40 | * the VM to selectively suspend certain threads in low-memory 41 | * situations. They are inherently dangerous and not implementable 42 | * on native threads. We removed them in JDK 1.2. The skeletons 43 | * remain so that existing applications that use these methods 44 | * will still work. 45 | */ 46 | private static boolean suspended = false; 47 | 48 | /** @deprecated */ 49 | @Deprecated 50 | public static boolean threadsSuspended() { 51 | return suspended; 52 | } 53 | 54 | public static boolean allowThreadSuspension(ThreadGroup g, boolean b) { 55 | return g.allowThreadSuspension(b); 56 | } 57 | 58 | /** @deprecated */ 59 | @Deprecated 60 | public static boolean suspendThreads() { 61 | suspended = true; 62 | return true; 63 | } 64 | 65 | // Causes any suspended threadgroups to be resumed. 66 | /** @deprecated */ 67 | @Deprecated 68 | public static void unsuspendThreads() { 69 | suspended = false; 70 | } 71 | 72 | // Causes threadgroups no longer marked suspendable to be resumed. 73 | /** @deprecated */ 74 | @Deprecated 75 | public static void unsuspendSomeThreads() { 76 | } 77 | 78 | /* Deprecated fields and methods -- Memory advice not supported in 1.2 */ 79 | 80 | /** @deprecated */ 81 | @Deprecated 82 | public static final int STATE_GREEN = 1; 83 | 84 | /** @deprecated */ 85 | @Deprecated 86 | public static final int STATE_YELLOW = 2; 87 | 88 | /** @deprecated */ 89 | @Deprecated 90 | public static final int STATE_RED = 3; 91 | 92 | /** @deprecated */ 93 | @Deprecated 94 | public static final int getState() { 95 | return STATE_GREEN; 96 | } 97 | 98 | /** @deprecated */ 99 | @Deprecated 100 | public static void registerVMNotification(VMNotification n) { } 101 | 102 | /** @deprecated */ 103 | @Deprecated 104 | public static void asChange(int as_old, int as_new) { } 105 | 106 | /** @deprecated */ 107 | @Deprecated 108 | public static void asChange_otherthread(int as_old, int as_new) { } 109 | 110 | /* 111 | * Not supported in 1.2 because these will have to be exported as 112 | * JVM functions, and we are not sure we want do that. Leaving 113 | * here so it can be easily resurrected -- just remove the // 114 | * comments. 115 | */ 116 | 117 | /** 118 | * Resume Java profiling. All profiling data is added to any 119 | * earlier profiling, unless resetJavaProfiler is 120 | * called in between. If profiling was not started from the 121 | * command line, resumeJavaProfiler will start it. 122 | *

123 | * 124 | * NOTE: Profiling must be enabled from the command line for a 125 | * java.prof report to be automatically generated on exit; if not, 126 | * writeJavaProfilerReport must be invoked to write a report. 127 | * 128 | * @see resetJavaProfiler 129 | * @see writeJavaProfilerReport 130 | */ 131 | 132 | // public native static void resumeJavaProfiler(); 133 | 134 | /** 135 | * Suspend Java profiling. 136 | */ 137 | // public native static void suspendJavaProfiler(); 138 | 139 | /** 140 | * Initialize Java profiling. Any accumulated profiling 141 | * information is discarded. 142 | */ 143 | // public native static void resetJavaProfiler(); 144 | 145 | /** 146 | * Write the current profiling contents to the file "java.prof". 147 | * If the file already exists, it will be overwritten. 148 | */ 149 | // public native static void writeJavaProfilerReport(); 150 | 151 | 152 | private static volatile boolean booted = false; 153 | 154 | // Invoked by by System.initializeSystemClass just before returning. 155 | // Subsystems that are invoked during initialization can check this 156 | // property in order to avoid doing things that should wait until the 157 | // application class loader has been set up. 158 | // 159 | public static void booted() { 160 | booted = true; 161 | } 162 | 163 | public static boolean isBooted() { 164 | return booted; 165 | } 166 | 167 | // A user-settable upper limit on the maximum amount of allocatable direct 168 | // buffer memory. This value may be changed during VM initialization if 169 | // "java" is launched with "-XX:MaxDirectMemorySize=". 170 | // 171 | // The initial value of this field is arbitrary; during JRE initialization 172 | // it will be reset to the value specified on the command line, if any, 173 | // otherwise to Runtime.getRuntime.maxDirectMemory(). 174 | // 175 | private static long directMemory = 64 * 1024 * 1024; 176 | 177 | // Returns the maximum amount of allocatable direct buffer memory. 178 | // The directMemory variable is initialized during system initialization 179 | // in the saveAndRemoveProperties method. 180 | // 181 | public static long maxDirectMemory() { 182 | return directMemory; 183 | } 184 | 185 | // User-controllable flag that determines if direct buffers should be page 186 | // aligned. The "-XX:+PageAlignDirectMemory" option can be used to force 187 | // buffers, allocated by ByteBuffer.allocateDirect, to be page aligned. 188 | private static boolean pageAlignDirectMemory; 189 | 190 | // Returns {@code true} if the direct buffers should be page aligned. This 191 | // variable is initialized by saveAndRemoveProperties. 192 | public static boolean isDirectMemoryPageAligned() { 193 | return pageAlignDirectMemory; 194 | } 195 | 196 | // A user-settable boolean to determine whether ClassLoader.loadClass should 197 | // accept array syntax. This value may be changed during VM initialization 198 | // via the system property "sun.lang.ClassLoader.allowArraySyntax". 199 | // 200 | // The default for 1.5 is "true", array syntax is allowed. In 1.6, the 201 | // default will be "false". The presence of this system property to 202 | // control array syntax allows applications the ability to preview this new 203 | // behaviour. 204 | // 205 | private static boolean defaultAllowArraySyntax = false; 206 | private static boolean allowArraySyntax = defaultAllowArraySyntax; 207 | 208 | // The allowArraySyntax boolean is initialized during system initialization 209 | // in the saveAndRemoveProperties method. 210 | // 211 | // It is initialized based on the value of the system property 212 | // "sun.lang.ClassLoader.allowArraySyntax". If the system property is not 213 | // provided, the default for 1.5 is "true". In 1.6, the default will be 214 | // "false". If the system property is provided, then the value of 215 | // allowArraySyntax will be equal to "true" if Boolean.parseBoolean() 216 | // returns "true". Otherwise, the field will be set to "false". 217 | // 218 | public static boolean allowArraySyntax() { 219 | return allowArraySyntax; 220 | } 221 | 222 | private static boolean allowGetCallerClass = true; 223 | 224 | // Reflection.getCallerClass(int) is enabled by default. 225 | // It can be disabled by setting the system property 226 | // "jdk.reflect.allowGetCallerClass" to "false". It cannot be 227 | // disabled if the logging stack walk (to find resource bundles) 228 | // is enabled. 229 | public static boolean allowGetCallerClass() { 230 | return allowGetCallerClass; 231 | } 232 | 233 | /** 234 | * Returns the system property of the specified key saved at 235 | * system initialization time. This method should only be used 236 | * for the system properties that are not changed during runtime. 237 | * It accesses a private copy of the system properties so 238 | * that user's locking of the system properties object will not 239 | * cause the library to deadlock. 240 | * 241 | * Note that the saved system properties do not include 242 | * the ones set by sun.misc.Version.init(). 243 | * 244 | */ 245 | public static String getSavedProperty(String key) { 246 | if (savedProps.isEmpty()) 247 | throw new IllegalStateException("Should be non-empty if initialized"); 248 | 249 | return savedProps.getProperty(key); 250 | } 251 | 252 | // TODO: the Property Management needs to be refactored and 253 | // the appropriate prop keys need to be accessible to the 254 | // calling classes to avoid duplication of keys. 255 | private static final Properties savedProps = new Properties(); 256 | 257 | // Save a private copy of the system properties and remove 258 | // the system properties that are not intended for public access. 259 | // 260 | // This method can only be invoked during system initialization. 261 | public static void saveAndRemoveProperties(Properties props) { 262 | if (booted) 263 | throw new IllegalStateException("System initialization has completed"); 264 | 265 | savedProps.putAll(props); 266 | 267 | // Set the maximum amount of direct memory. This value is controlled 268 | // by the vm option -XX:MaxDirectMemorySize=. 269 | // The maximum amount of allocatable direct buffer memory (in bytes) 270 | // from the system property sun.nio.MaxDirectMemorySize set by the VM. 271 | // The system property will be removed. 272 | String s = (String)props.remove("sun.nio.MaxDirectMemorySize"); 273 | if (s != null) { 274 | if (s.equals("-1")) { 275 | // -XX:MaxDirectMemorySize not given, take default 276 | directMemory = Runtime.getRuntime().maxMemory(); 277 | } else { 278 | long l = Long.parseLong(s); 279 | if (l > -1) 280 | directMemory = l; 281 | } 282 | } 283 | 284 | // Check if direct buffers should be page aligned 285 | s = (String)props.remove("sun.nio.PageAlignDirectMemory"); 286 | if ("true".equals(s)) 287 | pageAlignDirectMemory = true; 288 | 289 | // Set a boolean to determine whether ClassLoader.loadClass accepts 290 | // array syntax. This value is controlled by the system property 291 | // "sun.lang.ClassLoader.allowArraySyntax". 292 | s = props.getProperty("sun.lang.ClassLoader.allowArraySyntax"); 293 | allowArraySyntax = (s == null 294 | ? defaultAllowArraySyntax 295 | : Boolean.parseBoolean(s)); 296 | 297 | // Reflection.getCallerClass(int) is enabled by default. 298 | // It can be disabled by setting a system property (but only if 299 | // the logging stack walk is not enabled) 300 | s = props.getProperty("jdk.reflect.allowGetCallerClass"); 301 | allowGetCallerClass = (s != null 302 | ? (s.isEmpty() || Boolean.parseBoolean(s)) 303 | : true) || 304 | Boolean.valueOf(props.getProperty("jdk.logging.allowStackWalkSearch")); 305 | 306 | // Remove other private system properties 307 | // used by java.lang.Integer.IntegerCache 308 | props.remove("java.lang.Integer.IntegerCache.high"); 309 | 310 | // used by java.util.zip.ZipFile 311 | props.remove("sun.zip.disableMemoryMapping"); 312 | 313 | // used by sun.launcher.LauncherHelper 314 | props.remove("sun.java.launcher.diag"); 315 | } 316 | 317 | // Initialize any miscellenous operating system settings that need to be 318 | // set for the class libraries. 319 | // 320 | public static void initializeOSEnvironment() { 321 | if (!booted) { 322 | OSEnvironment.initialize(); 323 | } 324 | } 325 | 326 | /* Current count of objects pending for finalization */ 327 | private static volatile int finalRefCount = 0; 328 | 329 | /* Peak count of objects pending for finalization */ 330 | private static volatile int peakFinalRefCount = 0; 331 | 332 | /* 333 | * Gets the number of objects pending for finalization. 334 | * 335 | * @return the number of objects pending for finalization. 336 | */ 337 | public static int getFinalRefCount() { 338 | return finalRefCount; 339 | } 340 | 341 | /* 342 | * Gets the peak number of objects pending for finalization. 343 | * 344 | * @return the peak number of objects pending for finalization. 345 | */ 346 | public static int getPeakFinalRefCount() { 347 | return peakFinalRefCount; 348 | } 349 | 350 | /* 351 | * Add n to the objects pending for finalization count. 352 | * 353 | * @param n an integer value to be added to the objects pending 354 | * for finalization count 355 | */ 356 | public static void addFinalRefCount(int n) { 357 | // The caller must hold lock to synchronize the update. 358 | 359 | finalRefCount += n; 360 | if (finalRefCount > peakFinalRefCount) { 361 | peakFinalRefCount = finalRefCount; 362 | } 363 | } 364 | 365 | /** 366 | * Returns Thread.State for the given threadStatus 367 | */ 368 | public static Thread.State toThreadState(int threadStatus) { 369 | if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) { 370 | return RUNNABLE; 371 | } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) { 372 | return BLOCKED; 373 | } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) { 374 | return WAITING; 375 | } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) { 376 | return TIMED_WAITING; 377 | } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) { 378 | return TERMINATED; 379 | } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) { 380 | return NEW; 381 | } else { 382 | return RUNNABLE; 383 | } 384 | } 385 | 386 | /* The threadStatus field is set by the VM at state transition 387 | * in the hotspot implementation. Its value is set according to 388 | * the JVM TI specification GetThreadState function. 389 | */ 390 | private final static int JVMTI_THREAD_STATE_ALIVE = 0x0001; 391 | private final static int JVMTI_THREAD_STATE_TERMINATED = 0x0002; 392 | private final static int JVMTI_THREAD_STATE_RUNNABLE = 0x0004; 393 | private final static int JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER = 0x0400; 394 | private final static int JVMTI_THREAD_STATE_WAITING_INDEFINITELY = 0x0010; 395 | private final static int JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT = 0x0020; 396 | 397 | /* 398 | * Returns the first non-null class loader up the execution stack, 399 | * or null if only code from the null class loader is on the stack. 400 | */ 401 | public static native ClassLoader latestUserDefinedLoader(); 402 | 403 | static { 404 | initialize(); 405 | } 406 | private native static void initialize(); 407 | } 408 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/sun/reflect/Reflection.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2001, 2006, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package sun.reflect; 27 | 28 | import java.lang.reflect.Array; 29 | import java.lang.reflect.Field; 30 | import java.lang.reflect.Member; 31 | import java.lang.reflect.Method; 32 | import java.lang.reflect.Modifier; 33 | import java.util.HashMap; 34 | import java.util.Map; 35 | 36 | /** Common utility routines used by both java.lang and 37 | java.lang.reflect */ 38 | 39 | public class Reflection { 40 | 41 | /** Used to filter out fields and methods from certain classes from public 42 | view, where they are sensitive or they may contain VM-internal objects. 43 | These Maps are updated very rarely. Rather than synchronize on 44 | each access, we use copy-on-write */ 45 | private static volatile Map fieldFilterMap; 46 | private static volatile Map methodFilterMap; 47 | 48 | static { 49 | Map map = new HashMap(); 50 | map.put(Reflection.class, 51 | new String[] {"fieldFilterMap", "methodFilterMap"}); 52 | map.put(System.class, new String[] {"security"}); 53 | fieldFilterMap = map; 54 | 55 | methodFilterMap = new HashMap(); 56 | } 57 | 58 | /** Returns the class of the caller of the method calling this method, 59 | ignoring frames associated with java.lang.reflect.Method.invoke() 60 | and its implementation. */ 61 | @CallerSensitive 62 | public static native Class getCallerClass(); 63 | 64 | /** 65 | * @deprecated No replacement. This method will be removed in a future 66 | * release. 67 | */ 68 | @Deprecated 69 | @CallerSensitive 70 | public static Class getCallerClass(int depth) { 71 | if (sun.misc.VM.allowGetCallerClass()) { 72 | return getCallerClass0(depth+1); 73 | } 74 | throw new UnsupportedOperationException("This method has been disabled by a " + 75 | "system property"); 76 | } 77 | 78 | // If the VM enforces getting caller class with @CallerSensitive, 79 | // this will fail anyway. 80 | @CallerSensitive 81 | private static native Class getCallerClass0(int depth); 82 | 83 | /** Retrieves the access flags written to the class file. For 84 | inner classes these flags may differ from those returned by 85 | Class.getModifiers(), which searches the InnerClasses 86 | attribute to find the source-level access flags. This is used 87 | instead of Class.getModifiers() for run-time access checks due 88 | to compatibility reasons; see 4471811. Only the values of the 89 | low 13 bits (i.e., a mask of 0x1FFF) are guaranteed to be 90 | valid. */ 91 | private static native int getClassAccessFlags(Class c); 92 | 93 | /** A quick "fast-path" check to try to avoid getCallerClass() 94 | calls. */ 95 | public static boolean quickCheckMemberAccess(Class memberClass, 96 | int modifiers) 97 | { 98 | return Modifier.isPublic(getClassAccessFlags(memberClass) & modifiers); 99 | } 100 | 101 | public static void ensureMemberAccess(Class currentClass, 102 | Class memberClass, 103 | Object target, 104 | int modifiers) 105 | throws IllegalAccessException 106 | { 107 | if (currentClass == null || memberClass == null) { 108 | throw new InternalError(); 109 | } 110 | 111 | if (!verifyMemberAccess(currentClass, memberClass, target, modifiers)) { 112 | throw new IllegalAccessException("Class " + currentClass.getName() + 113 | " can not access a member of class " + 114 | memberClass.getName() + 115 | " with modifiers \"" + 116 | Modifier.toString(modifiers) + 117 | "\""); 118 | } 119 | } 120 | 121 | public static boolean verifyMemberAccess(Class currentClass, 122 | // Declaring class of field 123 | // or method 124 | Class memberClass, 125 | // May be NULL in case of statics 126 | Object target, 127 | int modifiers) 128 | { 129 | // Verify that currentClass can access a field, method, or 130 | // constructor of memberClass, where that member's access bits are 131 | // "modifiers". 132 | 133 | boolean gotIsSameClassPackage = false; 134 | boolean isSameClassPackage = false; 135 | 136 | if (currentClass == memberClass) { 137 | // Always succeeds 138 | return true; 139 | } 140 | 141 | if (!Modifier.isPublic(getClassAccessFlags(memberClass))) { 142 | isSameClassPackage = isSameClassPackage(currentClass, memberClass); 143 | gotIsSameClassPackage = true; 144 | if (!isSameClassPackage) { 145 | return false; 146 | } 147 | } 148 | 149 | // At this point we know that currentClass can access memberClass. 150 | 151 | if (Modifier.isPublic(modifiers)) { 152 | return true; 153 | } 154 | 155 | boolean successSoFar = false; 156 | 157 | if (Modifier.isProtected(modifiers)) { 158 | // See if currentClass is a subclass of memberClass 159 | if (isSubclassOf(currentClass, memberClass)) { 160 | successSoFar = true; 161 | } 162 | } 163 | 164 | if (!successSoFar && !Modifier.isPrivate(modifiers)) { 165 | if (!gotIsSameClassPackage) { 166 | isSameClassPackage = isSameClassPackage(currentClass, 167 | memberClass); 168 | gotIsSameClassPackage = true; 169 | } 170 | 171 | if (isSameClassPackage) { 172 | successSoFar = true; 173 | } 174 | } 175 | 176 | if (!successSoFar) { 177 | return false; 178 | } 179 | 180 | if (Modifier.isProtected(modifiers)) { 181 | // Additional test for protected members: JLS 6.6.2 182 | Class targetClass = (target == null ? memberClass : target.getClass()); 183 | if (targetClass != currentClass) { 184 | if (!gotIsSameClassPackage) { 185 | isSameClassPackage = isSameClassPackage(currentClass, memberClass); 186 | gotIsSameClassPackage = true; 187 | } 188 | if (!isSameClassPackage) { 189 | if (!isSubclassOf(targetClass, currentClass)) { 190 | return false; 191 | } 192 | } 193 | } 194 | } 195 | 196 | return true; 197 | } 198 | 199 | private static boolean isSameClassPackage(Class c1, Class c2) { 200 | return isSameClassPackage(c1.getClassLoader(), c1.getName(), 201 | c2.getClassLoader(), c2.getName()); 202 | } 203 | 204 | /** Returns true if two classes are in the same package; classloader 205 | and classname information is enough to determine a class's package */ 206 | private static boolean isSameClassPackage(ClassLoader loader1, String name1, 207 | ClassLoader loader2, String name2) 208 | { 209 | if (loader1 != loader2) { 210 | return false; 211 | } else { 212 | int lastDot1 = name1.lastIndexOf('.'); 213 | int lastDot2 = name2.lastIndexOf('.'); 214 | if ((lastDot1 == -1) || (lastDot2 == -1)) { 215 | // One of the two doesn't have a package. Only return true 216 | // if the other one also doesn't have a package. 217 | return (lastDot1 == lastDot2); 218 | } else { 219 | int idx1 = 0; 220 | int idx2 = 0; 221 | 222 | // Skip over '['s 223 | if (name1.charAt(idx1) == '[') { 224 | do { 225 | idx1++; 226 | } while (name1.charAt(idx1) == '['); 227 | if (name1.charAt(idx1) != 'L') { 228 | // Something is terribly wrong. Shouldn't be here. 229 | throw new InternalError("Illegal class name " + name1); 230 | } 231 | } 232 | if (name2.charAt(idx2) == '[') { 233 | do { 234 | idx2++; 235 | } while (name2.charAt(idx2) == '['); 236 | if (name2.charAt(idx2) != 'L') { 237 | // Something is terribly wrong. Shouldn't be here. 238 | throw new InternalError("Illegal class name " + name2); 239 | } 240 | } 241 | 242 | // Check that package part is identical 243 | int length1 = lastDot1 - idx1; 244 | int length2 = lastDot2 - idx2; 245 | 246 | if (length1 != length2) { 247 | return false; 248 | } 249 | return name1.regionMatches(false, idx1, name2, idx2, length1); 250 | } 251 | } 252 | } 253 | 254 | static boolean isSubclassOf(Class queryClass, 255 | Class ofClass) 256 | { 257 | while (queryClass != null) { 258 | if (queryClass == ofClass) { 259 | return true; 260 | } 261 | queryClass = queryClass.getSuperclass(); 262 | } 263 | return false; 264 | } 265 | 266 | // fieldNames must contain only interned Strings 267 | public static synchronized void registerFieldsToFilter(Class containingClass, 268 | String ... fieldNames) { 269 | fieldFilterMap = 270 | registerFilter(fieldFilterMap, containingClass, fieldNames); 271 | } 272 | 273 | // methodNames must contain only interned Strings 274 | public static synchronized void registerMethodsToFilter(Class containingClass, 275 | String ... methodNames) { 276 | methodFilterMap = 277 | registerFilter(methodFilterMap, containingClass, methodNames); 278 | } 279 | 280 | private static Map registerFilter(Map map, 281 | Class containingClass, String ... names) { 282 | if (map.get(containingClass) != null) { 283 | throw new IllegalArgumentException 284 | ("Filter already registered: " + containingClass); 285 | } 286 | map = new HashMap(map); 287 | map.put(containingClass, names); 288 | return map; 289 | } 290 | 291 | public static Field[] filterFields(Class containingClass, 292 | Field[] fields) { 293 | if (fieldFilterMap == null) { 294 | // Bootstrapping 295 | return fields; 296 | } 297 | return (Field[])filter(fields, fieldFilterMap.get(containingClass)); 298 | } 299 | 300 | public static Method[] filterMethods(Class containingClass, Method[] methods) { 301 | if (methodFilterMap == null) { 302 | // Bootstrapping 303 | return methods; 304 | } 305 | return (Method[])filter(methods, methodFilterMap.get(containingClass)); 306 | } 307 | 308 | private static Member[] filter(Member[] members, String[] filteredNames) { 309 | if ((filteredNames == null) || (members.length == 0)) { 310 | return members; 311 | } 312 | int numNewMembers = 0; 313 | for (Member member : members) { 314 | boolean shouldSkip = false; 315 | for (String filteredName : filteredNames) { 316 | if (member.getName() == filteredName) { 317 | shouldSkip = true; 318 | break; 319 | } 320 | } 321 | if (!shouldSkip) { 322 | ++numNewMembers; 323 | } 324 | } 325 | Member[] newMembers = 326 | (Member[])Array.newInstance(members[0].getClass(), numNewMembers); 327 | int destIdx = 0; 328 | for (Member member : members) { 329 | boolean shouldSkip = false; 330 | for (String filteredName : filteredNames) { 331 | if (member.getName() == filteredName) { 332 | shouldSkip = true; 333 | break; 334 | } 335 | } 336 | if (!shouldSkip) { 337 | newMembers[destIdx++] = member; 338 | } 339 | } 340 | return newMembers; 341 | } 342 | 343 | /** 344 | * Tests if the given method is caller-sensitive and the declaring class 345 | * is defined by either the bootstrap class loader or extension class loader. 346 | */ 347 | public static boolean isCallerSensitive(Method m) { 348 | final ClassLoader loader = m.getDeclaringClass().getClassLoader(); 349 | if (loader == null || isExtClassLoader(loader)) { 350 | return m.isAnnotationPresent(CallerSensitive.class); 351 | } 352 | return false; 353 | } 354 | 355 | private static boolean isExtClassLoader(ClassLoader loader) { 356 | ClassLoader cl = ClassLoader.getSystemClassLoader(); 357 | while (cl != null) { 358 | if (cl.getParent() == null && cl == loader) { 359 | return true; 360 | } 361 | cl = cl.getParent(); 362 | } 363 | return false; 364 | } 365 | } 366 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/sun/security/action/GetPropertyAction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package sun.security.action; 27 | 28 | /** 29 | * A convenience class for retrieving the string value of a system 30 | * property as a privileged action. 31 | * 32 | *

An instance of this class can be used as the argument of 33 | * AccessController.doPrivileged. 34 | * 35 | *

The following code retrieves the value of the system 36 | * property named "prop" as a privileged action:

37 | * 38 | *

39 |  * String s = java.security.AccessController.doPrivileged
40 |  *                      (new GetPropertyAction("prop"));
41 |  * 
42 | * 43 | * @author Roland Schemers 44 | * @see java.security.PrivilegedAction 45 | * @see java.security.AccessController 46 | * @since 1.2 47 | */ 48 | 49 | public class GetPropertyAction 50 | implements java.security.PrivilegedAction { 51 | private String theProp; 52 | private String defaultVal; 53 | 54 | /** 55 | * Constructor that takes the name of the system property whose 56 | * string value needs to be determined. 57 | * 58 | * @param theProp the name of the system property. 59 | */ 60 | public GetPropertyAction(String theProp) { 61 | this.theProp = theProp; 62 | } 63 | 64 | /** 65 | * Constructor that takes the name of the system property and the default 66 | * value of that property. 67 | * 68 | * @param theProp the name of the system property. 69 | * @param defaultVal the default value. 70 | */ 71 | public GetPropertyAction(String theProp, String defaultVal) { 72 | this.theProp = theProp; 73 | this.defaultVal = defaultVal; 74 | } 75 | 76 | /** 77 | * Determines the string value of the system property whose 78 | * name was specified in the constructor. 79 | * 80 | * @return the string value of the system property, 81 | * or the default value if there is no property with that key. 82 | */ 83 | public String run() { 84 | String value = System.getProperty(theProp); 85 | return (value == null) ? defaultVal : value; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/sun/security/util/PermissionFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package sun.security.util; 27 | 28 | import java.security.Permission; 29 | 30 | /** 31 | * A factory object that creates Permission objects. 32 | */ 33 | 34 | public interface PermissionFactory { 35 | T newPermission(String name); 36 | } 37 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/java/sun/security/util/SecurityConstants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved. 3 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 | * 5 | * This code is free software; you can redistribute it and/or modify it 6 | * under the terms of the GNU General Public License version 2 only, as 7 | * published by the Free Software Foundation. Oracle designates this 8 | * particular file as subject to the "Classpath" exception as provided 9 | * by Oracle in the LICENSE file that accompanied this code. 10 | * 11 | * This code is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 | * version 2 for more details (a copy is included in the LICENSE file that 15 | * accompanied this code). 16 | * 17 | * You should have received a copy of the GNU General Public License version 18 | * 2 along with this work; if not, write to the Free Software Foundation, 19 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 | * 21 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 | * or visit www.oracle.com if you need additional information or have any 23 | * questions. 24 | */ 25 | 26 | package sun.security.util; 27 | 28 | import java.net.SocketPermission; 29 | import java.net.NetPermission; 30 | import java.security.AccessController; 31 | import java.security.PrivilegedAction; 32 | import java.security.Permission; 33 | import java.security.BasicPermission; 34 | import java.security.SecurityPermission; 35 | import java.security.AllPermission; 36 | 37 | /** 38 | * Permission constants and string constants used to create permissions 39 | * used throughout the JDK. 40 | */ 41 | public final class SecurityConstants { 42 | // Cannot create one of these 43 | private SecurityConstants () { 44 | } 45 | 46 | // Commonly used string constants for permission actions used by 47 | // SecurityManager. Declare here for shortcut when checking permissions 48 | // in FilePermission, SocketPermission, and PropertyPermission. 49 | 50 | public static final String FILE_DELETE_ACTION = "delete"; 51 | public static final String FILE_EXECUTE_ACTION = "execute"; 52 | public static final String FILE_READ_ACTION = "read"; 53 | public static final String FILE_WRITE_ACTION = "write"; 54 | public static final String FILE_READLINK_ACTION = "readlink"; 55 | 56 | public static final String SOCKET_RESOLVE_ACTION = "resolve"; 57 | public static final String SOCKET_CONNECT_ACTION = "connect"; 58 | public static final String SOCKET_LISTEN_ACTION = "listen"; 59 | public static final String SOCKET_ACCEPT_ACTION = "accept"; 60 | public static final String SOCKET_CONNECT_ACCEPT_ACTION = "connect,accept"; 61 | 62 | public static final String PROPERTY_RW_ACTION = "read,write"; 63 | public static final String PROPERTY_READ_ACTION = "read"; 64 | public static final String PROPERTY_WRITE_ACTION = "write"; 65 | 66 | // Permission constants used in the various checkPermission() calls in JDK. 67 | 68 | // java.lang.Class, java.lang.SecurityManager, java.lang.System, 69 | // java.net.URLConnection, java.security.AllPermission, java.security.Policy, 70 | // sun.security.provider.PolicyFile 71 | public static final AllPermission ALL_PERMISSION = new AllPermission(); 72 | 73 | /** 74 | * Permission type used when AWT is not present. 75 | */ 76 | private static class FakeAWTPermission extends BasicPermission { 77 | private static final long serialVersionUID = -1L; 78 | public FakeAWTPermission(String name) { 79 | super(name); 80 | } 81 | public String toString() { 82 | return "(\"java.awt.AWTPermission\" \"" + getName() + "\")"; 83 | } 84 | } 85 | 86 | /** 87 | * Permission factory used when AWT is not present. 88 | */ 89 | private static class FakeAWTPermissionFactory 90 | implements PermissionFactory 91 | { 92 | @Override 93 | public FakeAWTPermission newPermission(String name) { 94 | return new FakeAWTPermission(name); 95 | } 96 | } 97 | 98 | /** 99 | * AWT Permissions used in the JDK. 100 | */ 101 | public static class AWT { 102 | private AWT() { } 103 | 104 | /** 105 | * The class name of the factory to create java.awt.AWTPermission objects. 106 | */ 107 | private static final String AWTFactory = "sun.awt.AWTPermissionFactory"; 108 | 109 | /** 110 | * The PermissionFactory to create AWT permissions (or fake permissions 111 | * if AWT is not present). 112 | */ 113 | private static final PermissionFactory factory = permissionFactory(); 114 | 115 | private static PermissionFactory permissionFactory() { 116 | Class c = AccessController 117 | .doPrivileged(new PrivilegedAction>() { 118 | public Class run() { 119 | try { 120 | return Class.forName(AWTFactory, true, null); 121 | } catch (ClassNotFoundException e) { 122 | // not available 123 | return null; 124 | } 125 | }}); 126 | if (c != null) { 127 | // AWT present 128 | try { 129 | return (PermissionFactory)c.newInstance(); 130 | } catch (InstantiationException x) { 131 | throw new InternalError(x.getMessage()); 132 | } catch (IllegalAccessException x) { 133 | throw new InternalError(x.getMessage()); 134 | } 135 | } else { 136 | // AWT not present 137 | return new FakeAWTPermissionFactory(); 138 | } 139 | } 140 | 141 | private static Permission newAWTPermission(String name) { 142 | return factory.newPermission(name); 143 | } 144 | 145 | // java.lang.SecurityManager 146 | public static final Permission TOPLEVEL_WINDOW_PERMISSION = 147 | newAWTPermission("showWindowWithoutWarningBanner"); 148 | 149 | // java.lang.SecurityManager 150 | public static final Permission ACCESS_CLIPBOARD_PERMISSION = 151 | newAWTPermission("accessClipboard"); 152 | 153 | // java.lang.SecurityManager 154 | public static final Permission CHECK_AWT_EVENTQUEUE_PERMISSION = 155 | newAWTPermission("accessEventQueue"); 156 | 157 | // java.awt.Dialog 158 | public static final Permission TOOLKIT_MODALITY_PERMISSION = 159 | newAWTPermission("toolkitModality"); 160 | 161 | // java.awt.Robot 162 | public static final Permission READ_DISPLAY_PIXELS_PERMISSION = 163 | newAWTPermission("readDisplayPixels"); 164 | 165 | // java.awt.Robot 166 | public static final Permission CREATE_ROBOT_PERMISSION = 167 | newAWTPermission("createRobot"); 168 | 169 | // java.awt.MouseInfo 170 | public static final Permission WATCH_MOUSE_PERMISSION = 171 | newAWTPermission("watchMousePointer"); 172 | 173 | // java.awt.Window 174 | public static final Permission SET_WINDOW_ALWAYS_ON_TOP_PERMISSION = 175 | newAWTPermission("setWindowAlwaysOnTop"); 176 | 177 | // java.awt.Toolkit 178 | public static final Permission ALL_AWT_EVENTS_PERMISSION = 179 | newAWTPermission("listenToAllAWTEvents"); 180 | 181 | // java.awt.SystemTray 182 | public static final Permission ACCESS_SYSTEM_TRAY_PERMISSION = 183 | newAWTPermission("accessSystemTray"); 184 | } 185 | 186 | // java.net.URL 187 | public static final NetPermission SPECIFY_HANDLER_PERMISSION = 188 | new NetPermission("specifyStreamHandler"); 189 | 190 | // java.net.ProxySelector 191 | public static final NetPermission SET_PROXYSELECTOR_PERMISSION = 192 | new NetPermission("setProxySelector"); 193 | 194 | // java.net.ProxySelector 195 | public static final NetPermission GET_PROXYSELECTOR_PERMISSION = 196 | new NetPermission("getProxySelector"); 197 | 198 | // java.net.CookieHandler 199 | public static final NetPermission SET_COOKIEHANDLER_PERMISSION = 200 | new NetPermission("setCookieHandler"); 201 | 202 | // java.net.CookieHandler 203 | public static final NetPermission GET_COOKIEHANDLER_PERMISSION = 204 | new NetPermission("getCookieHandler"); 205 | 206 | // java.net.ResponseCache 207 | public static final NetPermission SET_RESPONSECACHE_PERMISSION = 208 | new NetPermission("setResponseCache"); 209 | 210 | // java.net.ResponseCache 211 | public static final NetPermission GET_RESPONSECACHE_PERMISSION = 212 | new NetPermission("getResponseCache"); 213 | 214 | // java.lang.SecurityManager, sun.applet.AppletPanel, sun.misc.Launcher 215 | public static final RuntimePermission CREATE_CLASSLOADER_PERMISSION = 216 | new RuntimePermission("createClassLoader"); 217 | 218 | // java.lang.SecurityManager 219 | public static final RuntimePermission CHECK_MEMBER_ACCESS_PERMISSION = 220 | new RuntimePermission("accessDeclaredMembers"); 221 | 222 | // java.lang.SecurityManager, sun.applet.AppletSecurity 223 | public static final RuntimePermission MODIFY_THREAD_PERMISSION = 224 | new RuntimePermission("modifyThread"); 225 | 226 | // java.lang.SecurityManager, sun.applet.AppletSecurity 227 | public static final RuntimePermission MODIFY_THREADGROUP_PERMISSION = 228 | new RuntimePermission("modifyThreadGroup"); 229 | 230 | // java.lang.Class 231 | public static final RuntimePermission GET_PD_PERMISSION = 232 | new RuntimePermission("getProtectionDomain"); 233 | 234 | // java.lang.Class, java.lang.ClassLoader, java.lang.Thread 235 | public static final RuntimePermission GET_CLASSLOADER_PERMISSION = 236 | new RuntimePermission("getClassLoader"); 237 | 238 | // java.lang.Thread 239 | public static final RuntimePermission STOP_THREAD_PERMISSION = 240 | new RuntimePermission("stopThread"); 241 | 242 | // java.lang.Thread 243 | public static final RuntimePermission GET_STACK_TRACE_PERMISSION = 244 | new RuntimePermission("getStackTrace"); 245 | 246 | // java.security.AccessControlContext 247 | public static final SecurityPermission CREATE_ACC_PERMISSION = 248 | new SecurityPermission("createAccessControlContext"); 249 | 250 | // java.security.AccessControlContext 251 | public static final SecurityPermission GET_COMBINER_PERMISSION = 252 | new SecurityPermission("getDomainCombiner"); 253 | 254 | // java.security.Policy, java.security.ProtectionDomain 255 | public static final SecurityPermission GET_POLICY_PERMISSION = 256 | new SecurityPermission ("getPolicy"); 257 | 258 | // java.lang.SecurityManager 259 | public static final SocketPermission LOCAL_LISTEN_PERMISSION = 260 | new SocketPermission("localhost:1024-", SOCKET_LISTEN_ACTION); 261 | } 262 | -------------------------------------------------------------------------------- /sun-dependencies/src/main/resources/META-INF/services/javax.script.ScriptEngineFactory: -------------------------------------------------------------------------------- 1 | com.sun.script.javascript.RhinoScriptEngineFactory 2 | -------------------------------------------------------------------------------- /sun-dependencies/src/test/java/io/apisense/scriptengine/RhinoTests.java: -------------------------------------------------------------------------------- 1 | package io.apisense.scriptengine; 2 | 3 | import com.sun.script.javascript.RhinoScriptEngineFactory; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | import javax.script.ScriptEngine; 9 | import javax.script.ScriptEngineManager; 10 | import javax.script.ScriptException; 11 | 12 | import static org.hamcrest.CoreMatchers.is; 13 | import static org.hamcrest.CoreMatchers.notNullValue; 14 | import static org.junit.Assert.assertThat; 15 | 16 | /** 17 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 18 | */ 19 | public class RhinoTests { 20 | 21 | private ScriptEngineManager scriptEngineManager; 22 | 23 | @Before 24 | public void setUp() throws Exception { 25 | scriptEngineManager = new ScriptEngineManager(); 26 | } 27 | 28 | @Test 29 | public void RhinoCanBeCreated() throws Exception { 30 | ScriptEngine rhino = new RhinoScriptEngineFactory().getScriptEngine(); 31 | 32 | testEngine(rhino); 33 | } 34 | 35 | @Test 36 | public void RhinoCanBeRetrievedByEngineName() throws Exception { 37 | ScriptEngine rhino = scriptEngineManager.getEngineByName("mozilla.rhino"); 38 | 39 | testEngine(rhino); 40 | } 41 | 42 | @Test 43 | public void RhinoCanBeRetrievedByShortName() throws Exception { 44 | ScriptEngine rhino = scriptEngineManager.getEngineByName("rhino"); 45 | 46 | testEngine(rhino); 47 | } 48 | 49 | private void testEngine(ScriptEngine rhino) throws ScriptException { 50 | assertThat("Injected engine is not null", rhino, notNullValue()); 51 | assertThat("We use rhino", 52 | rhino.getFactory().getEngineName().toLowerCase().contains("rhino"), is(true)); 53 | assertThat("Injected engine is usable", (Double) rhino.eval("2.5+2"), is(4.5)); 54 | } 55 | 56 | @Test 57 | public void testMathMethods() throws ScriptException { 58 | ScriptEngine rhino = scriptEngineManager.getEngineByName("rhino"); 59 | testEngine(rhino); 60 | assertThat("We can access Math.asinh", (Double) rhino.eval("Math.asinh(0);"), is(0.0)); 61 | } 62 | 63 | } 64 | --------------------------------------------------------------------------------