diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..ea2f10417 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,24 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +tab_width = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.java] +max_line_length = 120 +ij_java_class_brace_style = next_line +ij_java_method_brace_style = next_line +ij_java_block_brace_style = next_line + +[*.xml] +indent_size = 4 +tab_width = 4 + +[*.properties] +indent_size = 4 +tab_width = 4 diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 000000000..3f794d727 --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,38 @@ +# This will build the BCV repo and upload the package as an artifact + +name: Build BCV + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + java: [ '8', '11', '17', '21' ] # LTS versions + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.java }} + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --file pom.xml + - name: Extract Maven project version + run: echo "bcv_version=$(mvn -q -Dexec.executable=echo -Dexec.args='${project.version}' --non-recursive exec:exec)" >> $GITHUB_ENV + id: project + - name: 'Upload Artifact' + uses: actions/upload-artifact@v4 + if: ${{ matrix.java == '8' }} + with: + name: Bytecode-Viewer-${{ env.bcv_version }}-SNAPSHOT + path: target/Bytecode-Viewer-${{ env.bcv_version }}.jar + retention-days: 90 diff --git a/.gitignore b/.gitignore index b64d1edc1..02f8253eb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,13 @@ -/bin/ +.bin/ +.idea/ +.out/ +/out +.gradle/ .classpath .project +.DS_Store *.iml -.idea/ \ No newline at end of file +/out/ +/target/ + +dependency-reduced-pom.xml diff --git a/BytecodeViewer 2.9.8-fatjar.jar b/BytecodeViewer 2.9.8-fatjar.jar deleted file mode 100644 index b80b4dc0b..000000000 Binary files a/BytecodeViewer 2.9.8-fatjar.jar and /dev/null differ diff --git a/BytecodeViewer 2.9.8.jar b/BytecodeViewer 2.9.8.jar deleted file mode 100644 index c275e9ee9..000000000 Binary files a/BytecodeViewer 2.9.8.jar and /dev/null differ diff --git a/BytecodeViewer 3.0.0-preview1.jar b/BytecodeViewer 3.0.0-preview1.jar deleted file mode 100644 index f1146f95c..000000000 Binary files a/BytecodeViewer 3.0.0-preview1.jar and /dev/null differ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..97947e34e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,3 @@ +## Contribution Guide Lines/Coding Conventions +* Packages must start with the.bytecode.club.bytecodeviewer. +* All variables must be at the start of each class. \ No newline at end of file diff --git a/CREDITS.md b/CREDITS.md new file mode 100644 index 000000000..d227fd9b9 --- /dev/null +++ b/CREDITS.md @@ -0,0 +1,34 @@ +## Code from various projects has been used, including but not limited to +* J-RET by WaterWolf +* JHexPane by Sam Koivu +* RSynaxPane by Robert Futrell +* Commons IO by Apache +* ASM by OW2 +* FernFlower by Stiver +* Procyon by Mstrobel +* Luyten by DeathMarine +* CFR by Lee Benfield +* CFIDE by Bibl +* Smali by JesusFreke +* Dex2Jar by pxb1988 & Lanchon +* Krakatau by Storyyeller +* JD GUI/JD Core by The Java-Decompiler Team +* Enjarify by Storyyeller +* JADX by Skylot + +## Contributors +[Full List Of Contributors](https://github.com/Konloch/bytecode-viewer/graphs/contributors) +* Konloch +* Bibl +* Fluke +* Righteous +* sahitya-pavurala +* priav03 +* Afffsdd +* Szperak +* Zooty +* samczsun +* ItzSomebody +* DreamSworK +* HyperSpeeed +* If I missed you, please feel free to contact me @Konloch or konloch@gmail.com diff --git a/LICENSE b/LICENSE index e587591e1..5a43ba9f1 100644 --- a/LICENSE +++ b/LICENSE @@ -618,4 +618,31 @@ an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. - END OF TERMS AND CONDITIONS \ No newline at end of file + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Bytecode Viewer - Java & Android Reverse Engineering Suite + Copyright (C) 2014 Kalen "Konloch" Kinloch - http://bytecodeviewer.com - http://the.bytecode.club + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 000000000..2bbe99b59 --- /dev/null +++ b/README.md @@ -0,0 +1,112 @@ +# Bytecode Viewer + +Bytecode Viewer - a lightweight user-friendly Java/Android Bytecode Viewer, Decompiler & More. + +#### New Features +* Jump to Declaration +* Draggable tabs +* Patched [CVE-2022-21675](https://github.com/Konloch/bytecode-viewer/security/advisories/GHSA-3wq9-j4fc-4wmc) (Make sure to upgrade to v2.11.X) +* Dark mode by default with multiple themes +* Translated into over 30 languages including: Arabic, German, Japanese, Mandarin, Russian, Spanish +* Plugin Writer - create and edit external plugins from within BCV +* Fixed Java & Bytecode editing/compiling +* Tabbed plugin console +* Right-click menus on the resource and search panels +* Javap disassembler +* XAPK support +* Latest dependencies (incl. decompilers like CFR, JD-GUI etc.) +* Added support to Java files compiled using JDK > 13 +* Migrated to Maven + +#### Links +* [BCV Discord](https://discord.gg/aexsYpfMEf) +* [Website](https://bytecodeviewer.com) +* [Source Code](https://github.com/konloch/bytecode-viewer) +* [Bin/Archive](https://github.com/konloch/bytecode-viewer/releases) +* [Java Docs](https://the.bytecode.club/docs/bytecode-viewer/) +* [License (Copyleft)](https://raw.githubusercontent.com/Konloch/bytecode-viewer/master/LICENSE) +* [Credits](https://github.com/Konloch/bytecode-viewer/blob/master/CREDITS.md) +* [Contributing](https://github.com/Konloch/bytecode-viewer/blob/master/CONTRIBUTING.md) +* [Report Bugs](https://github.com/Konloch/bytecode-viewer/issues) +* [Discussion Forum](https://the.bytecode.club/forumdisplay.php?fid=69) + +#### Key Features +* Simply drag and drop to decompile and search Java Jars & Android APKs +* File format support for: Class, Jar, XAPK, APK, DEX, WAR, JSP, Image Resources, Text Resources & More +* 6 Built-in Java decompilers: Krakatau, CFR, Procyon, FernFlower, JADX, JD-GUI +* 3 Built-in Bytecode disassemblers, including 2 assemblers: Krakatau and Smali/BakSmali +* APK/DEX Support from Dex2Jar and Enjarify +* Built-in Java Compiler +* Advanced static-search functionality +* Customizable UI +* Plugins + Script Engine Design +* Malicious code scanning API +* Translated Into over 30 Languages Including: Arabic, German, Japanese, Mandarin, Russian, Spanish) +* Export functionality as Runnable Jar, Zip, APK, Decompile All As Zip, Etc. +* And more! Give it a try for yourself! + +#### Command Line Input +``` + -help Displays the help menu + -clean Deletes the BCV directory + -english Forces English language translations + -list Displays the available decompilers + -decompiler Selects the decompiler, procyon by default + -i Selects the input file (Jar, Class, APK, ZIP, DEX all work automatically) + -o Selects the output file (Java or Java-Bytecode) + -t Must either be the fully qualified classname or "all" to decompile all as zip + -nowait Doesn't wait for the user to read the CLI messages +``` + +## What is Bytecode Viewer? +Bytecode Viewer (BCV) is an Advanced Lightweight Java/Android Reverse Engineering Suite. Powered by several open source tools BCV is designed to aid in the reversing process. + +BCV comes with 6 decompilers, 3 disassemblers, 2 assemblers, 2 APK converters, advanced searching, debugging & more. + +It's written completely in Java, and it's open sourced. It's currently being maintained and developed by Konloch. + +## Is there a demo? +[![BCV Demo](https://img.youtube.com/vi/I5GT6PoTGOw/0.jpg)](https://www.youtube.com/watch?v=I5GT6PoTGOw) + +Please note this demo is from a very old version + +## How do I install BCV? +Download the latest version from https://github.com/konloch/bytecode-viewer/releases and run the Bytecode-Viewer-2.10.x.jar. +You may need to execute it via command line ```java -jar Bytecode-Viewer-2.10.x.jar``` (replace the X with the current minor version) + +## How can I use BCV? +* Starting with a Jar, Zip, ClassFile or Android file (APK, DEX, XAPK, etc) drag it into BCV. It will start the decoding process automatically. +* From here you can select the decompilers you would like to use by selecting the View Pane>View 1, View 2, View 3, etc. +* The view panes are-used to display up to 3 decompilers side by side, you can also toggle edibility here. +* Select the resource you would like to open by navigating using the resource list, BCV will do its best to display it (Decompiling, Disassembling, etc). +* You can use plugins to help you search along with using the search pane in the left-hand bottom corner. + +## How do the plugins work? +There is also a plugin system that will allow you to interact with the loaded classfiles. You could for example write a String deobfuscator, a malicious code searcher, or anything else you can think of. + +You can either use one of the pre-written plugins, or write your own. The plugin system supports java and javascript scripting. + +Once a plugin is activated, it will execute the plugin with a ClassNode ArrayList of every single class loaded in BCV, this allows the user to handle it completely using ASM. + +## Instructions to compile + +Just clone this repo and run ``mvn package``. It's that simple! + +## Working on the source + +Open the Maven project (e.g. in IntelliJ, open the ``pom.xml`` as a project file). + +## UI Is Lagging +Change the theme to your systems. Go into `View->Visual Settings->Window Theme` and select `System Theme`. + +## Java Heap Space Issues (java.lang.OutOfMemoryError) +Start BCV with more RAM, e.g. `java -Xmx3G -jar BCV.jar` + +## File Permission Issues (java.io.FileNotFoundException) +Right click on the jar file, go to Properties, and select Unblock under Security at the bottom of the General tab. + +## APK File Permission Issues (java.io.FileNotFoundException) +Run BCV as administrator. + +#### Are you a Java Reverse Engineer? Do you want to learn? +Join The Bytecode Club Today! - https://the.bytecode.club diff --git a/README.txt b/README.txt deleted file mode 100644 index 1a26d8849..000000000 --- a/README.txt +++ /dev/null @@ -1,420 +0,0 @@ -Bytecode Viewer is an Advanced Lightweight Java Bytecode Viewer, GUI Java Decompiler, GUI Bytecode Editor, GUI Smali, GUI Baksmali, GUI APK Editor, GUI Dex Editor, GUI APK Decompiler, GUI DEX Decompiler, GUI Procyon Java Decompiler, GUI Krakatau, GUI CFR Java Decompiler, GUI FernFlower Java Decompiler, GUI DEX2Jar, GUI Jar2DEX, GUI Jar-Jar, Hex Viewer, Code Searcher, Debugger and more. -It's written completely in Java, and it's open sourced. It's currently being maintained and developed by Konloch. - -There is also a plugin system that will allow you to interact with the loaded classfiles, for example you can write a String deobfuscator, a malicious code searcher, or something else you can think of. -You can either use one of the pre-written plugins, or write your own. It supports groovy scripting. Once a plugin is activated, it will execute the plugin with a ClassNode ArrayList of every single class loaded in BCV, this allows the user to handle it completely using ASM. - -Code from various projects has been used, including but not limited to: - J-RET by WaterWolf - JHexPane by Sam Koivu - RSynaxPane by Robert Futrell - Commons IO by Apache - ASM by OW2 - FernFlower by Stiver - Procyon by Mstrobel - CFR by Lee Benfield - CFIDE by Bibl - Smali by JesusFreke - Dex2Jar by pxb1..? - Krakatau by Storyyeller - JD GUI/JD Core by The Java-Decompiler Team - Enjarify by Storyyeller - -Contributors: - Konloch - Bibl - Fluke - Righteous - sahitya-pavurala - priav03 - Afffsdd - Szperak - Zooty - samczsun - If I missed you, please feel free to contact me @Konloch or konloch@gmail.com - -Contribution Guide Lines/Coding Conventions: - Packages must start with the.bytecode.club.bytecodeviewer - If code you write can throw an exception, handle it using new the.bytecode.club.bytecodeviewer.ExceptionUI(exception, "authors@email.com") - All variables must be at the start of each class. - Brackets are meant to be on the same line, I.E. public void main(String[] args) { not (String[] args) { - -Website: https://bytecodeviewer.com -Source Code: https://github.com/konloch/bytecode-viewer -Bin/Archive: https://github.com/konloch/bytecode-viewer/releases -Java Docs: https://the.bytecode.club/docs/bytecode-viewer/ -License (Copyleft): https://raw.githubusercontent.com/Konloch/bytecode-viewer/master/LICENSE -Report Bugs (or below): https://github.com/Konloch/bytecode-viewer/issues -Discussion Forum: https://the.bytecode.club/forumdisplay.php?fid=69 - -Key Features: - Krakatau Integration for Bytecode assembly/disassembly. - Smali/BakSmali Integration - You can now edit class files/dex files via smali! - APK/DEX Support - Using Dex2Jar and Jar2Dex it's able to load and save APKs with ease! - Java Decompiler - It utilizes FernFlower, Procyon and CFR for decompilation. - Bytecode Decompiler - A modified version of CFIDE's. - Hex Viewer - Powered by JHexPane. - Each Decompiler/Editor/Viewer is toggleable, you can also select what will display on each pane. - Fully Featured Search System - Search through strings, functions, variables and more! - A Plugin System With Built In Plugins - (Show All Strings, Malicious Code Scanner, String Decrypters, etc) - Fully Featured Scripting System That Supports Groovy. - EZ-Inject - Graphically insert hooks and debugging code, invoke main and start the program. - Recent Files & Recent Plugins. - And more! Give it a try for yourself! - -Command Line Input: - -help Displays the help menu - -list Displays the available decompilers - -decompiler Selects the decompiler, procyon by default - -i Selects the input file (Jar, Class, APK, ZIP, DEX all work automatically) - -o Selects the output file (Java or Java-Bytecode) - -t Must either be the fully qualified classname or "all" to decompile all as zip - -nowait Doesn't wait for the user to read the CLI messages - -Are you a Java Reverse Engineer? Do you want to learn? -Join The Bytecode Club Today! -https://the.bytecode.club - -Changelog: ---- Beta 1.0.0 ---: -10/4/2014 - Designed a POC GUI, still needs a lot of work. -10/4/2014 - Started importing J-RET's backend. -10/5/2014 - Finished importing J-RET's backend. -10/6/2014 - Started modifying J-RET's UI. -10/6/2014 - Added several FernFlower options. -10/6/2014 - Fixed the class search function so it doesn't require exact class names. -10/6/2014 - Added save as, it'll save all of the loaded classes into one jar file (GUI Jar-Jar now). -10/6/2014 - Centered the select jar text inside of the file navigator. -10/6/2014 - Properly threaded the open jar function, now fernflower/bytecode decompiler runs in the background. -10/6/2014 - Added a hex viewer (Instead of using Re-Java's, I've decided to use a modified version of JHexEditor). -10/6/2014 - Made all of the viewer (Sourcecode, Bytecode & Hexcode toggleable). -10/7/2014 - Fixed the search function. -10/7/2014 - You can now add new files without it creating a new workspace. -10/7/2014 - Added new workspace button underneath File, this will reset the workspace. -10/7/2014 - Renamed File>Open.. to File>Add.. -10/7/2014 - Added recent files. -10/7/2014 - Did some bitch work, the project has no warnings now. -10/7/2014 - Added waiting cursors to anything that will require waiting or loading. -10/8/2014 - Searching now runs in a background thread. -10/8/2014 - Added File>About. -10/8/2014 - The main GUI now starts in the middle of your screen, same with the about window. -10/8/2014 - Made the File Navigator Pane, Workspace Pane & Search Pane a little sexier. -10/9/2014 - Started on a Plugin system -10/9/2014 - Added a malicious code scanner plugin, based off of the one from J-RET, this searches for a multitude of classes/packages that can be used for malicious purposes. -10/9/2014 - Added a show all strings plugin, this grabs all the declared strings and displays them in a nice little window. -10/9/2014 - Fixed a bug with Bytecode Decompiler, where it would it display \r and \n as return carriages. -10/9/2014 - Fixed the Bytecode Decompiler>Debug Instructions option. -10/9/2014 - Save Class Files As is now renamed to Save Files As. -10/9/2014 - Save Files As now saves jar resources, not just classfiles. -10/9/2014 - Added an 'Are you sure' pane when you click on File>New Workspace. -10/9/2014 - Save Files As is no longer dependent on the File System, now if you're on windows and you have a file called AA, and one called Aa, you're fine. -10/11/2014 - Modified the FernFlower library, it no longer spits out System.out.println's while processing a method, this has sped it up quite a lot. -10/12/2014 - Fix an issue when resizing. -10/12/2014 - Modified the core slighty to no longer have a modularized decompiling system (since there are only 2 decompilers anyways). -10/12/2014 - Fixed an issue with decompiling multiple files at once. -10/12/2014 - The Plugin Console now shows the plugin's name on the title. -10/12/2014 - Debug Helpers will now debug all jump instructions by showing what instruction is on the line it's suppose to goto, example: 90. goto 120 // line 120 is PUTFIELD Animable_Sub4.anInt1593 : I -10/12/2014 - Now when you select an already opened file, it will automatically go to that opened pane. -10/14/2014 - Added the option 'exact' to the class finder. -10/14/2014 - Added the option 'exact' to the searcher, now it'll search for .contains when unselected. -10/14/2014 - Stopped the use of StringBuffer, replaced all instances with StringBuilder. -10/14/2014 - Added Labels and Try-Catch blocks to the Bytecode Decompiler. -10/14/2014 - For panes that are not selected, the corresponding decompiler will not execute. -10/14/2014 - Added plugin Show Main Methods, this will show every single public static void main(String[]). -10/14/2014 - Plugins can no longer be ran when there is no loaded classes. -10/14/2014 - The Malicious Code Scanner now has gui option pane before you run it. -10/14/2014 - Added a java/io option to the Malicious Code Scanner. -10/14/2014 - Added save Java files as. -10/15/2014 - Added save as Jar file. (Export as Jar) -10/15/2014 - Added the option to ASCII only strings in the Bytecode Decompiler. -10/15/2014 - External plugins are now fully functional, same with recent plugins. -10/16/2014 - Removed all refences of 'ClassContainer'. -10/16/2014 - Rewrote the tempfile system. -10/16/2014 - Moved the file import to BytecodeViewer.class. -10/16/2014 - Fixed a jTree updating issue. -10/16/2014 - Now if you try search with an empty string, it won't search. -10/16/2014 - Added Replace Strings plugin. -10/16/2014 - Added a loading icon that displays whenever a background task is being executed. ---- Beta 1.1.0 ---: -10/19/2014 - Fixed harcoded \\. ---- Beta 1.2.0 ---: -10/19/2014 - Started importing Procyon and CFR decompilers. -10/19/2014 - Partially finished importing Procyon and CFR, just need to finish export java files as zip. ---- Beta 1.3.0 ---: -10/22/2014 - Imported Bibl's Bytecode Decompiler from CFIDE. -10/22/2014 - Did some changes to the Bytecode Decompiler. -10/23/2014 - Added CFR settings. -10/23/2014 - Updated FernFlower to Intellij's Open Sourced version of FernFlower. -10/24/2014 - Fixed FernFlower save Java files as zip. -10/29/2014 - Added version checker. -10/29/2014 - Added Procyon settings. -10/29/2014 - When saving as jars or zips, it'll automatically append the file extension if it's not added. -10/29/2014 - All the built in plugins no longer set the cursor to busy. -10/29/2014 - Tried to fix the issue with JSyntaxPane by making it create the object in a background thread, it still freezes the UI. Changes kept for later implementation of another syntax highlighter. -10/29/2014 - Sped up start up time ---- Beta 1.3.1 ---: -10/29/2014 - Replaced JSyntaxPane with RSyntaxArea, this sadly removes the search feature inside of source/bytecode files, I'll implement a search function soon. (This also fixes the JRE 1.8 issue) -10/29/2014 - Added a new decompiler option to append brackets to labels. -10/31/2014 - Fixed an issue with the decompiler still running when the source code pane isn't toggled. ---- Beta 1.4.0 ---: -11/1/2014 - Fixed FernFlower save Java files on Unix. -11/1/2014 - FernFlower now uses the settings for save Java files. -11/1/2014 - Added Procyon save Java files (It uses the settings). -11/1/2014 - Updated CFR to cfr_0_89. -11/1/2014 - Added CFR save Java files (It uses the settings), however it relies on the file system, because of this if there is heavy name obfuscation, it could mess up for windows. ---- Beta 1.5.0 ---: -11/1/2014 - Updated and improved the search function, it now prints out more useful information. -11/1/2014 - Fixed a UI issue with the Replace All Strings plugin. -11/2/2014 - Added search function to the Class Viewer. -11/2/2014 - Updated Procyon to procyon-decompiler-0.5.27. ---- Beta 1.5.1 ---: -11/2/2014 - Fixed a CFR issue with packages. ---- Beta 1.5.2 ---: -11/3/2014 - Fixed Refresh Class. ---- Beta 1.5.3 ---: -11/3/2014 - Settings/Temp file are now in a global directory. -11/3/2014 - The GUI setttings now save. -11/3/2014 - Removed the option to disable syntax highlighting (since it's lightweight now). -11/3/2014 - About window now contains the version number and the BCV directory. -11/3/2014 - Added an option to toggle to outdated status. ---- 2.0.0 ---: //Out of beta, WOO -11/4/2014 - Officially been 1 month of development. -11/4/2014 - Replaced ""+ with String.valueOf (cheers bibl). -11/4/2014 - Changed how the temp directory was created. -11/4/2014 - Put a file.seperator to the end of tempDirectory. -11/4/2014 - Made the exit button work. -11/4/2014 - Added a GUI for all Exception Stack Trace's. -11/4/2014 - The plugin system now shows a message instead of just printing to the console when it's not going to run a plugin. -11/4/2014 - Updated the search function, it's now perfect. -11/5/2014 - Made the Show All Strings plugin instant. -11/5/2014 - Kinda added middle mouse button closes tab (only if you click the exit button). -11/5/2014 - Improved the Malicious Code Scanner, also made it instant. -11/5/2014 - Added icons to the program (cheers Fluke). ---- 2.0.1 ---: -11/7/2014 - Fixed the search function. -11/7/2014 - Removed an unused package containing some unused classes. ---- 2.1.0 ---: -11/5/2014 - Started working on the EZ-Inject plugin. -11/6/2014 - Fixed the ClassNodeDecompiler creating unnessessary objects. (thanks bibl). -11/6/2014 - Finished an alpha version of EZ-Inject. -11/6/2014 - Started working on a basic obfuscator. -11/6/2014 - The Obfuscator now sucessfully renames all field names. -11/6/2014 - Updated CFR to cfr_0_90. -11/8/2014 - Started working on the API for BCV. -11/9/2014 - Decided to make a graphical reflection kit. -11/10/2014 - Made some progress with the obfuscator, almost finished EZ-Injection. -11/14/2014 - Been doing various updates to EZ-Injection, Obfucsation, Reflection Kit and the BCV API. -11/16/2014 - Added the option to launch BCV command line as java -jar bcv.jar C:/test.jar C:/example/whatever.jar -11/17/2014 - Fixed an issue with the out of date checking UI still activating when not selected. -11/19/2014 - Added annotatitons/local variables to the methodnode decompiler (Thanks Bibl). -11/21/2014 - Decided to release it with the obfuscator/reflection kit unfinished, they're currently disabled for future use. ---- 2.1.1 ---: -12/09/2014 - Upated CFR to cfr_0_91. ---- 2.2.0 ---: -12/09/2014 - Added a text search function to the plugin console. -12/09/2014 - When you press enter in the text search bar, it will now search. -12/13/2014 - The Bytecode Decompiler now shows the method's description in a comment. -12/13/2014 - Fixed an issue with the text search function. -12/13/2014 - Search results are now clickable. ---- 2.2.1 ---: -12/13/2014 - Fixed an issue with the Bytecode Decompiler. - Thanks bibl ---- 2.3.0 ---: -12/16/2014 - Started updating the class viewer. -12/18/2014 - Finished a basic concept of the new class viewer. -12/18/2014 - Fixed an error with importing some jars. -12/18/2014 - Fixed the about window. -12/18/2014 - Finished the final concept for the new class viewer. -12/18/2014 - Threaded save Java files as zip, it now runs in a background thread. -12/18/2014 - Save Java files as zip now prompts you to select a decompiler. -12/18/2014 - Removed the cursor waiting for save Java files as zip. -12/18/2014 - Wrapped the save Java files as zip around an exception handler, it will now safely show the exception if any is thrown. -12/18/2014 - Fixed not escaping the Java strings by default for the Bytecode decompiler. - http://i.imgur.com/YrRnZA7.png -12/18/2014 - Used Eclipse's code formatting tool and formatted the code -12/19/2014 - Priav03 fixed the quick class searcher. ---- 2.4.0 ---: -12/19/2014 - Afffsdd made the Bytecode Viewer directory hidden. -12/19/2014 - Added save Java file as, for singular class file decompilation (this is threaded). -12/19/2014 - Removed unused Bytecode Decompiler debug code. -12/20/2014 - Made a new outdated pane - http://i.imgur.com/xMxkwJ9.png -12/20/2014 - Added an expand/collapse the packages in the file navigator. -12/20/2014 - Moved all of the settings to the.bytecode.club.bytecodeviewer.Settings -12/20/2014 - If the class file does not start with CAFEBABE it won't be processed. -12/20/2014 - Properly handled file not found error. -12/21/2014 - Fixed the Refresh Class causing a dupe. ---- 2.5.0 ---: -12/28/2014 - Improved the outdated version pane by including an automatic downloader - http://i.imgur.com/4MXeBGb.png - http://i.imgur.com/v50Pghe.png - http://i.imgur.com/bVZqxZ2.png - http://i.imgur.com/l8nIMzD.png -12/28/2014 - Updated CFR to cfr_0.92.jar -12/31/2014 - Adrianherrera updated the Malicious Code Scanner to detect the security manager being set to null. - **HAPPY NEW YEAR** -01/01/2015 - Added refresh class on decompiler/pane view change -01/01/2015 - Moved all of the settings into a settings pane -01/01/2015 - Added some debug code when you first start it up, it also includes how long it took to fully load up. -01/02/2015 - Cached the busy icon. -01/02/2015 - >> ADDED APK SUPPORT <<, had to downgrade to ASM 3.3, which means losing some annotation debugging for the Bytecode Decompiler. -01/03/2015 - Wrapped the search pane in a JScrollPane. -01/06/2015 - Added save as DEX and import .dex files. ---- 2.5.1 ---: -01/06/2015 - Silenced the error connecting to update server for offline mode. -01/06/2015 - Fixed a search function with Android APKs. ---- 2.5.2 ---: -01/06/2015 - Completely fixed the search function with Android APKs. ---- 2.6.0 ---: -01/06/2015 - Now saves if maximized or not. -01/07/2015 - For all save as functions, it will now append the correct extension if not added by the user. -01/07/2015 - You can no longer use use the save functions if no classes are loaded (fixes a crash issue). -01/07/2015 - Moved the Update Check to the Settings menu. -01/08/2015 - Added an extremely basic code sqeuence diagram plugin. -01/08/2015 - Updated CFR to CFR_0.93.jar -01/08/2015 - Threaded the Add files function. -01/08/2015 - Finally implemented Kontainer's HTTPRequest wrapper now that I've open sourced it. -01/08/2015 - Set the panes to be non-editable. -01/08/2015 - Sexified the view pane selection. -01/08/2015 - Started working on Smali Editing support, finished decompiler so far. -01/09/2015 - Fixed a bug with saving. -01/09/2015 - Added add entire directory. -01/09/2015 - Fixed import .DEX files. -01/10/2015 - Finished Smali Editing. -01/10/2015 - Fixed a class opening issue with synchronization. -01/11/2015 - Threaded all of the save functions. -01/11/2015 - Removed all instances of the setCursor to busy. -01/11/2015 - Added are you sure you wish to overwrite this existing file to all the other save functions. -01/11/2015 - All of the decompiling names are now randomly generated instead of a counting number. -01/11/2015 - Updated CFR to CFR_0.94.jar -01/11/2015 - Updated to the latest version of FernFlower. -01/11/2015 - Fixed an extension appending issue with save Java file. ---- 2.7.0 ---: -01/11/2015 - Improved the Refresh Class function to be used as the default compile function. -01/11/2015 - Implemented better error handling for decompiling class files. -01/15/2015 - CTRL + O will open the add file interface. -01/15/2015 - CTRL + N will open the net workspace interface. -01/15/2015 - It will now save the last directory you opened. -01/15/2015 - Some how the URL for the auto updater change log got changed, this has been fixed. -01/15/2015 - Slightly updated the change log display, it'll now show all the changes since your version. -01/16/2015 - Made EZ-Injection UI look a bit nicer. -01/27/2015 - Decided to scrap the JVM Sandbox POC and use the Security Manager. -01/27/2015 - BCV now blocks exec and won't allow any ports to be bound. ---- 2.7.1 ---: -01/27/2015 - Fixed hide file. ---- 2.8.0 ---: -02/01/2015 - Updated CFR and Proycon to latest versions. -02/01/2015 - Started working on implementing Krakatau. -02/01/2015 - Sexifixed the security manager a little bit. -02/03/2015 - Fully added Krakatau Java decompiler, just disassembly/assembly left. -02/03/2015 - Updated the about window. -02/03/2015 - Dropped JRuby and Jython support (BCV is now roughly 16mb, was 45mb). -02/04/2015 - Added Krakatau Disassembly. -02/04/2015 - Added Krakatau Assembly. ---- 2.8.1 ---: -02/04/2015 - Fixed UI bug with Krakatau/Krakatau Editable view panes. -02/05/2015 - Added CTRL + F. ---- 2.9.0 ---: -02/11/2015 - Added ZStringArray String Decrypter. (Thanks Righteous) -02/20/2015 - Moved the decompilers/disassemblers around. -02/20/2015 - Fixed a resource leak with Krakatau Decompiler/Disassembler/Assembler. -02/21/2015 - Fixed regex searching if your regex search contained a syntax error. -02/21/2015 - Added the compiler/decompiler instances to the BytecodeViewer API class. -02/21/2015 - Sped up the decompilers, each view pane runs its own decompiler thread. -02/21/2015 - Added Janino compiler, you can now compile the decompiled source code inside of BCV. -02/21/2015 - Added the editable option for almost all of the decompilers/disassemblers. -02/21/2015 - Cached the next/previous icons and added a resources class for all resources. -01/21/2015 - Renamed EZ-Injection as File-Run, however kept the plugin named EZ-Injection. -02/21/2015 - Dropped Groovy support, added .Java plugin compilation instead (now only 10mb). -02/21/2015 - Added support for reading resources, including displaying images, detecting pure ascii files and more. -02/21/2015 - Fixed an issue with loading an already selected node in the file navigation pane. -02/22/2015 - Added an error console to the Java compiler -02/22/2015 - Ensured the spawned Python/Krakatau processes are killed when closing BCV. -02/22/2015 - Made it more beginner friendly. -02/22/2015 - Fixed? The file navigation search. -02/22/2015 - Added a shit ton more comments to non-api related classes. -02/23/2015 - Added APK resources. -02/23/2015 - MORE ANDROID LOVE! Added APKTool.jar's decode. (Takes a while so it's a setting, also pumped the jar back to 16MB) -02/23/2015 - Added close all but this tab menu. -02/23/2015 - Not really code related, but added _install.bat and _uninstall.bat for the exe version of BCV. -02/23/2015 - Back to ASM5, packed dex2jar in its own obfuscated jar. -02/23/2015 - Added the annotations back to the Bytecode Decompiler. (Once again, thanks Bibl) -02/23/2015 - It once again works with Java 8 Jars. ---- 2.9.1 ---: -02/24/2015 - Fixed the third pane window not showing the search buttons. -02/24/2015 - Fixed some issues with the compiler functionality. ---- 2.9.2 ---: -02/24/2015 - Actually fixed the compiler, LOL. ---- 2.9.3 ---: -02/28/2015 - Added drag and drop for any file. -02/28/2015 - Added ctrl + w to close the current opened tab. -02/28/2015 - Updated to CFR 0_97.jar -02/28/2015 - Fixed a concurrency issue with the decompilers. -02/28/2015 - Added image resize via scroll on mouse. -02/28/2015 - Added resource refreshing. -02/28/2015 - Im Frizzy started working on Obfuscation. -03/20/2015 - Updated Dex2Jar to 2.0. -03/20/2015 - Updated CFR to 0_98.jar ---- 2.9.4 ---: -04/19/2015 - Added -O to be passed for Krakatau Decompiler/Disassembler/Assembler. (Thanks Storyyeller). -04/19/2015 - Added -skip to be passed for Krakatau Decompiler. (Thanks Storyyeller). -04/19/2015 - Changed the warning window for Python to recommend PyPy. (Thanks Storyyeller). -04/20/2015 - Happy 2015 4/20 (Shoutout to @announce420 for being 2 years old). -04/21/2015 - Started reworking the View Panes. -04/21/2015 - Finished reworking the View Panes - http://i.imgur.com/SqIw4Vj.png - Cheers to whoever's idea this was (I forget sorry <3). -04/21/2015 - Updated CFR to 0_100.jar -04/21/2015 - Added CTRL + R for run. -04/21/2015 - Added CTRL + S for save files as. -04/21/2015 - Added CTRL + T for compile. -04/21/2015 - Added Krakatau optional library. -04/21/2015 - The about pane now provides a lot more up to date information. -04/21/2015 - Changed 'View Panes' to simply 'View'. ---- 2.9.5 ---: -05/01/2015 - Added 'pingback' for statistics (to track how many people globally use BCV) ---- 2.9.6 ---: -05/05/2015 - Fixed a typo in the about window -05/28/2015 - Started importing JD-GUI Decompiler. -05/28/2015 - Compile on refresh and compile on save are now enabled by default. -05/28/2015 - Renamed the File>Save As options to be much more informative. -06/24/2015 - Fixed a logic error with the Field & Method searchers. -06/26/2015 - Updated Procyon & CFR to their latest versions. -07/02/2015 - Added JD-GUI Decompiler. - Huge thanks to the guys behind JD-GUI! <3 (FIVE DECOMPILERS NOW LOL) ---- 2.9.7 ---: -07/02/2015 - Added ajustable font size. -07/05/2015 - Started working on the new Boot Screen. -07/06/2015 - Moved the font size to be under the view menu. -07/06/2015 - Fixed a bug with plugins not being able to grab the currently viewed class. -07/07/2015 - Started adding enjarify as an optional APK converter instead of Dex2Jar. -07/07/2015 - Finished the new Boot Screen -07/09/2015 - Fixed a process leak with krakatau decompiler. -07/09/2015 - Finished adding enjarify. -07/09/2015 - Supressed syntax exceptions due to JD-GUI. -07/09/2015 - Fixed refresh on non-refreshable resources. -07/09/2015 - Fixed opening a class and the name is so big, you cannot close because the [X] does not appear. -07/09/2015 - Added support for smaller screens for the boot screen. -07/16/2015 - Removed the FileFilter classes. -07/16/2015 - Updated the decompiler class to make more sense. -07/16/2015 - Started working on BCV CLI. -07/16/2015 - Finished BCV CLI. ---- 2.9.8 ---: -07/19/2015 - Fixed enjarify. -07/20/2015 - Bibl sexified the boot loading time. -07/20/2015 - Decode APK Resources is selected by default. -07/20/2015 - Made the security manager slightly safer, it can still be targeted but not as obviously now. -07/20/2015 - Added CLI to the boot page. -07/21/2015 - Added support for offline mode in case you cannot connect to github for some reason. (kicks in after 7 seconds) -07/21/2015 - Added fatjar option back, in case anyone wants a 100% portable version. -07/21/2015 - Made it so it now shows the decompiler it's using - http://i.imgur.com/yMEzXwv.png. -07/21/2015 - Rewrote the file system, it now shows the path of the jar it's got loaded. -07/21/2015 - Now it shows if the decompiler is in editable mode or not. -07/21/2015 - Fixed Enjarify bug from new security manager. -07/22/2015 - Fixed a typo (Thanks affffsdsd) -07/22/2015 - Finally added icons to the File Navigator, credits to http://famfamfam.com/lab/icons/silk/ for the icons. -07/22/2015 - JD-GUI is now the default decompiler for GUI. -07/22/2015 - Added Set Python 3.X to the UI. -07/22/2015 - Fixed krakatau/export as jar bug introduced by file system update. -07/22/2015 - Sped up krakatau decompiler/disassembler on big files. -07/22/2015 - Made it so when you press enter on the file navigation pane it opens the class. -07/22/2015 - The Quick file search now opens the files again. -07/23/2015 - Fixed opening single files and file folders into BCV -07/24/2015 - Added File>Reload Resources. -07/26/2015 - Fixed the view pane refresh after toggling a viewer, it's now flawless. -07/26/2015 - Fixed Krakatau Disassembler. -07/26/2015 - Mibbzz is gay once again. -07/30/2015 - Removed Janino Compiler & moved to Javac, it can now compile decompiled classes again. -07/30/2015 - Affssdd fixed the File Navigator Pane's Quick Class Search. -07/30/2015 - Fixed a process leak in KrakatauDisassembler. -07/30/2015 - Started working on converting all the decompilers to launch in their own process in an effort to reduce BCV resources (only for non-fatjar version). \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..39b4c4d37 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,9 @@ +# Security Policy + +## Supported Versions + +All versions of BCV are actively supported for security patches & updates. + +## Reporting a Vulnerability + +E-Mail konloch@gmail.com if you find any issues. diff --git a/VERSION b/VERSION index 8bcbcd5c8..973989ba8 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.9.8 \ No newline at end of file +2.9.10 \ No newline at end of file diff --git a/checkstyle.xml b/checkstyle.xml new file mode 100644 index 000000000..a61ca81d5 --- /dev/null +++ b/checkstyle.xml @@ -0,0 +1,115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/checkstyle_suppression.xml b/checkstyle_suppression.xml new file mode 100644 index 000000000..6c2c53ce0 --- /dev/null +++ b/checkstyle_suppression.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/dependency-reduced-pom.xml b/dependency-reduced-pom.xml deleted file mode 100644 index c7f07f1f9..000000000 --- a/dependency-reduced-pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - 4.0.0 - the.bytecode.club - bytecode-viewer - 3.0.0 - - src/main/java - - - src/main/resources - - - - - maven-compiler-plugin - 3.3 - - 1.7 - 1.7 - true - - - - maven-jar-plugin - 2.6 - - - maven-shade-plugin - 2.3 - - - package - - shade - - - - - the.bytecode.club.bytecodeviewer.BytecodeViewer - - - - - *:* - - META-INF/* - - - - com.fifesoft:rsyntaxtextarea - - ** - - - - true - - - - - - - - - bytecode-viewer - Bytecode Viewer Repository - http://repo.samczsun.com/content/repositories/bytecode-viewer/ - - - - UTF-8 - - - diff --git a/install/launch4j_config.xml b/install/launch4j_config.xml index 5bfb07cdd..a4af59204 100644 --- a/install/launch4j_config.xml +++ b/install/launch4j_config.xml @@ -14,35 +14,35 @@ w32api/libshell32.a H:\Repo\BCV\bytecode-viewer\BytecodeViewer 2.9.8.jar H:\Repo\BCV\bytecode-viewer\BytecodeViewer.exe - - + + . normal - http://java.com/download - + https://java.com/de/download/ + false false - + H:\Repo\BCV\bytecode-viewer\BCV Icon.ico - + false false 1.7.0_00 - + preferJre 64/32 0.2.9.7 - http://the.bytecode.club + https://the.bytecode.club/ Bytecode Viewer - http://bytecodeviewer.com + https://bytecodeviewer.com/ 0.2.9.6 - http://the.bytecode.club + https://the.bytecode.club/ Bytecode Viewer - + BCV Bytecode_Viewer.exe - \ No newline at end of file + diff --git a/libs/Krakatau-11.zip b/libs/Krakatau-11.zip new file mode 100644 index 000000000..47cee1236 Binary files /dev/null and b/libs/Krakatau-11.zip differ diff --git a/libs/Krakatau-8.zip b/libs/Krakatau-8.zip deleted file mode 100644 index 02e1d3512..000000000 Binary files a/libs/Krakatau-8.zip and /dev/null differ diff --git a/libs/README.md b/libs/README.md new file mode 100644 index 000000000..8112e98b8 --- /dev/null +++ b/libs/README.md @@ -0,0 +1,24 @@ +### Welcome! You have reached the `libs` folder! + +#### Adding new dependencies + +Run the following command (replacing the placeholders first of course!): +```console +mvn deploy:deploy-file -DgroupId=[GROUP-ID] -DartifactId=[ARTIFACT-ID] -Dversion=[VERSION] -Durl=file:./libs -DrepositoryId=local-maven-repo -DupdateReleaseInfo=true -Dfile=[THE-JAR-FILE] +``` + +#### Updating dependencies + +Just do the same procedure as in "Adding new dependencies", but with a new version number! + +You can also safely delete the old version of the dependency, as nothing will depend on it anymore. + +#### Why the suffix `bcv`? + +Some dependencies may have been modified or could be released by their author in the future. To avoid confusion and dependency clashes in the local repository, the suffix is a nice way to ensure, the right dependency is used in every project (`bcv` = `ByteCode Viewer` btw). + +#### Modifications + + - `ByteAnalysis`: Compiled from source with the newest dependency versions + - `APKTool`: Added the `apktool-cli` subproject, compiled without changes from source + - `JD-GUI`: Removed ASM, RSyntaxTextArea, ANTLR, and TreeLayout diff --git a/libs/apktool_2.0.1_obf-2.jar b/libs/apktool_2.0.1_obf-2.jar deleted file mode 100644 index 31c1e118a..000000000 Binary files a/libs/apktool_2.0.1_obf-2.jar and /dev/null differ diff --git a/libs/baksmali-2.0.3_obf.jar b/libs/baksmali-2.0.3_obf.jar deleted file mode 100644 index b29ded5d9..000000000 Binary files a/libs/baksmali-2.0.3_obf.jar and /dev/null differ diff --git a/libs/baksmali-license.txt b/libs/baksmali-license.txt deleted file mode 100644 index 9df4ca687..000000000 --- a/libs/baksmali-license.txt +++ /dev/null @@ -1 +0,0 @@ -http://opensource.org/licenses/BSD-3-Clause \ No newline at end of file diff --git a/libs/byteanalysis-license.txt b/libs/byteanalysis-license.txt deleted file mode 100644 index 6f942c081..000000000 --- a/libs/byteanalysis-license.txt +++ /dev/null @@ -1 +0,0 @@ -NONE WHAT THE FUCK BIBL > https://github.com/TheBiblMan/Byte-Engineer-2 \ No newline at end of file diff --git a/libs/cfr_0_110.jar b/libs/cfr_0_110.jar deleted file mode 100644 index b859d9a2d..000000000 Binary files a/libs/cfr_0_110.jar and /dev/null differ diff --git a/libs/commons-codec-1.9.jar b/libs/commons-codec-1.9.jar deleted file mode 100644 index ef35f1c50..000000000 Binary files a/libs/commons-codec-1.9.jar and /dev/null differ diff --git a/libs/commons-compiler.jar b/libs/commons-compiler.jar deleted file mode 100644 index 46cd66308..000000000 Binary files a/libs/commons-compiler.jar and /dev/null differ diff --git a/libs/commons-io-2.4.jar b/libs/commons-io-2.4.jar deleted file mode 100644 index 90035a4fe..000000000 Binary files a/libs/commons-io-2.4.jar and /dev/null differ diff --git a/libs/commons-lang3-3.3.2.jar b/libs/commons-lang3-3.3.2.jar deleted file mode 100644 index bb069797f..000000000 Binary files a/libs/commons-lang3-3.3.2.jar and /dev/null differ diff --git a/libs/dex_obf.jar b/libs/dex_obf.jar deleted file mode 100644 index 01bb7e9db..000000000 Binary files a/libs/dex_obf.jar and /dev/null differ diff --git a/libs/enjarify-2.zip b/libs/enjarify-2.zip deleted file mode 100644 index 1d0b3cd6d..000000000 Binary files a/libs/enjarify-2.zip and /dev/null differ diff --git a/libs/enjarify-4.zip b/libs/enjarify-4.zip new file mode 100644 index 000000000..066107dcc Binary files /dev/null and b/libs/enjarify-4.zip differ diff --git a/libs/byteanalysis-1.0.jar b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.jar similarity index 100% rename from libs/byteanalysis-1.0.jar rename to libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.jar diff --git a/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.jar.md5 b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.jar.md5 new file mode 100644 index 000000000..0f9a5a398 --- /dev/null +++ b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.jar.md5 @@ -0,0 +1 @@ +577771e809d7208659fa9536da1a1f1d \ No newline at end of file diff --git a/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.jar.sha1 b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.jar.sha1 new file mode 100644 index 000000000..9beac4ee9 --- /dev/null +++ b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.jar.sha1 @@ -0,0 +1 @@ +cc4f751caa6c3fbb6d159b5b4fc772fc78d09faa \ No newline at end of file diff --git a/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.pom b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.pom new file mode 100644 index 000000000..e2c17c5a4 --- /dev/null +++ b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.pom @@ -0,0 +1,8 @@ + + + 4.0.0 + eu.bibl.banalysis + byteanalysis + 1.0bcv + diff --git a/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.pom.md5 b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.pom.md5 new file mode 100644 index 000000000..6c81aee8b --- /dev/null +++ b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.pom.md5 @@ -0,0 +1 @@ +24ece026db49446067a87df4147fb22e \ No newline at end of file diff --git a/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.pom.sha1 b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.pom.sha1 new file mode 100644 index 000000000..ebe8d50bc --- /dev/null +++ b/libs/eu/bibl/banalysis/byteanalysis/1.0bcv/byteanalysis-1.0bcv.pom.sha1 @@ -0,0 +1 @@ +91deca562ba5dae7996327e35d9d4ca5d793e4cf \ No newline at end of file diff --git a/libs/eu/bibl/banalysis/byteanalysis/maven-metadata.xml b/libs/eu/bibl/banalysis/byteanalysis/maven-metadata.xml new file mode 100644 index 000000000..540cdf4ce --- /dev/null +++ b/libs/eu/bibl/banalysis/byteanalysis/maven-metadata.xml @@ -0,0 +1,12 @@ + + + eu.bibl.banalysis + byteanalysis + + 1.0bcv + + 1.0bcv + + 20210622184952 + + diff --git a/libs/eu/bibl/banalysis/byteanalysis/maven-metadata.xml.md5 b/libs/eu/bibl/banalysis/byteanalysis/maven-metadata.xml.md5 new file mode 100644 index 000000000..3b4c69388 --- /dev/null +++ b/libs/eu/bibl/banalysis/byteanalysis/maven-metadata.xml.md5 @@ -0,0 +1 @@ +06e2d8072d6732e85afce26be23c2a49 \ No newline at end of file diff --git a/libs/eu/bibl/banalysis/byteanalysis/maven-metadata.xml.sha1 b/libs/eu/bibl/banalysis/byteanalysis/maven-metadata.xml.sha1 new file mode 100644 index 000000000..03b3ffadb --- /dev/null +++ b/libs/eu/bibl/banalysis/byteanalysis/maven-metadata.xml.sha1 @@ -0,0 +1 @@ +f28f7af3dedb25b5d112a263bf5c6b596010206e \ No newline at end of file diff --git a/libs/fernflower2015-1.jar b/libs/fernflower2015-1.jar deleted file mode 100644 index 681b3b957..000000000 Binary files a/libs/fernflower2015-1.jar and /dev/null differ diff --git a/libs/imgscalr-lib-4.2.jar b/libs/imgscalr-lib-4.2.jar deleted file mode 100644 index bb7a406b6..000000000 Binary files a/libs/imgscalr-lib-4.2.jar and /dev/null differ diff --git a/libs/janino-license.txt b/libs/janino-license.txt deleted file mode 100644 index 9df4ca687..000000000 --- a/libs/janino-license.txt +++ /dev/null @@ -1 +0,0 @@ -http://opensource.org/licenses/BSD-3-Clause \ No newline at end of file diff --git a/libs/janino.jar b/libs/janino.jar deleted file mode 100644 index 79b946dff..000000000 Binary files a/libs/janino.jar and /dev/null differ diff --git a/libs/jar-rename-1.6.jar b/libs/jar-rename-1.6.jar deleted file mode 100644 index dacd67309..000000000 Binary files a/libs/jar-rename-1.6.jar and /dev/null differ diff --git a/libs/jarrenamer-license.txt b/libs/jarrenamer-license.txt deleted file mode 100644 index d955a86d7..000000000 --- a/libs/jarrenamer-license.txt +++ /dev/null @@ -1,11 +0,0 @@ -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file diff --git a/libs/jasmin-license.txt b/libs/jasmin-license.txt deleted file mode 100644 index a92f080e4..000000000 --- a/libs/jasmin-license.txt +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 1996-2004, Jon Meyer - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided - * that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list of conditions - * and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions - * and the following disclaimer in the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of the Jon Meyer nor the names of its contributors may be used to - * endorse or promote products derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Jasmin was written by Jon Meyer, www.cybergrain.com - * The Jasmin website is jasmin.sourceforge.net. - */ - \ No newline at end of file diff --git a/libs/jasmin-p2.5.jar b/libs/jasmin-p2.5.jar deleted file mode 100644 index 37a3248ae..000000000 Binary files a/libs/jasmin-p2.5.jar and /dev/null differ diff --git a/libs/jd-gui-1.0.0-RC4.jar b/libs/jd-gui-1.0.0-RC4.jar deleted file mode 100644 index 57b6acea3..000000000 Binary files a/libs/jd-gui-1.0.0-RC4.jar and /dev/null differ diff --git a/libs/jgraphx.jar b/libs/jgraphx.jar deleted file mode 100644 index e70d4c82c..000000000 Binary files a/libs/jgraphx.jar and /dev/null differ diff --git a/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.jar b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.jar new file mode 100644 index 000000000..b0d841196 Binary files /dev/null and b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.jar differ diff --git a/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.jar.md5 b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.jar.md5 new file mode 100644 index 000000000..61815c23c --- /dev/null +++ b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.jar.md5 @@ -0,0 +1 @@ +27038a07a27a96680c00ce9bc2e7ecf9 \ No newline at end of file diff --git a/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.jar.sha1 b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.jar.sha1 new file mode 100644 index 000000000..35a861cc5 --- /dev/null +++ b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.jar.sha1 @@ -0,0 +1 @@ +d2e0687046e7e343b1150f23976c718b8f05d017 \ No newline at end of file diff --git a/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.pom b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.pom new file mode 100644 index 000000000..885c5a7a7 --- /dev/null +++ b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.pom @@ -0,0 +1,8 @@ + + + 4.0.0 + org.jd + jd-gui + 1.6.6bcv + diff --git a/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.pom.md5 b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.pom.md5 new file mode 100644 index 000000000..0b4bea1af --- /dev/null +++ b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.pom.md5 @@ -0,0 +1 @@ +746c99600f2e54d10b6edadf901583ae \ No newline at end of file diff --git a/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.pom.sha1 b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.pom.sha1 new file mode 100644 index 000000000..d66b52579 --- /dev/null +++ b/libs/org/jd/jd-gui/1.6.6bcv/jd-gui-1.6.6bcv.pom.sha1 @@ -0,0 +1 @@ +a66b8df4397ea3f2985e811de4f1a6b06d2899b6 \ No newline at end of file diff --git a/libs/org/jd/jd-gui/maven-metadata.xml b/libs/org/jd/jd-gui/maven-metadata.xml new file mode 100644 index 000000000..c15a53dfd --- /dev/null +++ b/libs/org/jd/jd-gui/maven-metadata.xml @@ -0,0 +1,12 @@ + + + org.jd + jd-gui + + 1.6.6bcv + + 1.6.6bcv + + 20210810090109 + + diff --git a/libs/org/jd/jd-gui/maven-metadata.xml.md5 b/libs/org/jd/jd-gui/maven-metadata.xml.md5 new file mode 100644 index 000000000..40f1dfc08 --- /dev/null +++ b/libs/org/jd/jd-gui/maven-metadata.xml.md5 @@ -0,0 +1 @@ +3bacc3a2d75ec55b4a342685c525a242 \ No newline at end of file diff --git a/libs/org/jd/jd-gui/maven-metadata.xml.sha1 b/libs/org/jd/jd-gui/maven-metadata.xml.sha1 new file mode 100644 index 000000000..539aade4f --- /dev/null +++ b/libs/org/jd/jd-gui/maven-metadata.xml.sha1 @@ -0,0 +1 @@ +7ccb5c6496569cac765190873996c27dc28361f0 \ No newline at end of file diff --git a/libs/procyon-decompiler-0.5.30.jar b/libs/procyon-decompiler-0.5.30.jar deleted file mode 100644 index 5dc8b1dd7..000000000 Binary files a/libs/procyon-decompiler-0.5.30.jar and /dev/null differ diff --git a/libs/rsyntaxtextarea.jar b/libs/rsyntaxtextarea.jar deleted file mode 100644 index e6f415ce2..000000000 Binary files a/libs/rsyntaxtextarea.jar and /dev/null differ diff --git a/libs/smali-2.0.3-obf-patched.jar b/libs/smali-2.0.3-obf-patched.jar deleted file mode 100644 index 81322e79f..000000000 Binary files a/libs/smali-2.0.3-obf-patched.jar and /dev/null differ diff --git a/libs/smali-license.txt b/libs/smali-license.txt deleted file mode 100644 index 9df4ca687..000000000 --- a/libs/smali-license.txt +++ /dev/null @@ -1 +0,0 @@ -http://opensource.org/licenses/BSD-3-Clause \ No newline at end of file diff --git a/libs/zt-zip-1.8.jar b/libs/zt-zip-1.8.jar deleted file mode 100644 index f3347d0ec..000000000 Binary files a/libs/zt-zip-1.8.jar and /dev/null differ diff --git a/plugins/Skeleton.gy b/plugins/Skeleton.gy deleted file mode 100644 index c9d45583f..000000000 --- a/plugins/Skeleton.gy +++ /dev/null @@ -1,14 +0,0 @@ -import the.bytecode.club.bytecodeviewer.api.*; -import java.util.ArrayList; -import org.objectweb.asm.tree.ClassNode; -import the.bytecode.club.bytecodeviewer.decompilers.*; - -public class Skeleton extends Plugin { - - @Override - public void execute(ArrayList classNodesList) { - PluginConsole gui = new PluginConsole("Skeleton"); - gui.setVisible(true); - gui.appendText("executed skeleton"); - } -} \ No newline at end of file diff --git a/plugins/Skeleton.java b/plugins/Skeleton.java deleted file mode 100644 index b3e8d3b89..000000000 --- a/plugins/Skeleton.java +++ /dev/null @@ -1,13 +0,0 @@ -import the.bytecode.club.bytecodeviewer.api.*; -import java.util.ArrayList; -import org.objectweb.asm.tree.ClassNode; - -public class Skeleton extends Plugin { - - @Override - public void execute(ArrayList classNodesList) { - PluginConsole gui = new PluginConsole("Skeleton"); - gui.setVisible(true); - gui.appendText("executed skeleton"); - } -} \ No newline at end of file diff --git a/plugins/Skeleton.rb b/plugins/Skeleton.rb deleted file mode 100644 index e69de29bb..000000000 diff --git a/plugins/groovy/ExampleStringDecrypter.gy b/plugins/groovy/ExampleStringDecrypter.gy new file mode 100644 index 000000000..bc4815299 --- /dev/null +++ b/plugins/groovy/ExampleStringDecrypter.gy @@ -0,0 +1,51 @@ +import org.objectweb.asm.tree.ClassNode +import org.objectweb.asm.tree.FieldNode +import the.bytecode.club.bytecodeviewer.api.BCV +import the.bytecode.club.bytecodeviewer.api.Plugin +import the.bytecode.club.bytecodeviewer.api.PluginConsole +import the.bytecode.club.bytecodeviewer.gui.components.MultipleChoiceDialog + +import java.lang.reflect.Field + +import static the.bytecode.club.bytecodeviewer.Constants.NL + +/** + ** This is an example of a String Decrypter Groovy Plugin for BCV. + ** + ** @author [Your-Name-Goes-Here] + **/ +class ExampleStringDecrypter extends Plugin { + + @Override + void execute(List classNodesList) { + PluginConsole gui = new PluginConsole("Example String Decrypter Groovy Edition") + + MultipleChoiceDialog dialog = new MultipleChoiceDialog("Bytecode Viewer - WARNING", + "WARNING: This will load the classes into the JVM and execute the initialize function" + + NL + "for each class. IF THE FILE YOU'RE LOADING IS MALICIOUS, DO NOT CONTINUE.", + new String[]{"Continue", "Cancel"}) + + if (dialog.promptChoice() == 0) { + for (ClassNode cn : classNodesList) { + BCV.getClassNodeLoader().addClass(cn) + + for (Object o : cn.fields.toArray()) { + FieldNode f = (FieldNode) o + if (f.name == "z") {// && f.desc.equals("([Ljava/lang/String;)V")) { + try { + for (Field f2 : BCV.getClassNodeLoader().nodeToClass(cn).getFields()) { + String s = f2.get(null) + if (s != null && !s.empty) + gui.appendText(cn + ":" + s) + } + } catch (Exception | StackOverflowError ignored) { + } + } + } + + } + gui.setVisible(true) + } + } + +} diff --git a/plugins/groovy/Skeleton.gy b/plugins/groovy/Skeleton.gy new file mode 100644 index 000000000..fcc74d056 --- /dev/null +++ b/plugins/groovy/Skeleton.gy @@ -0,0 +1,18 @@ +import org.objectweb.asm.tree.ClassNode +import the.bytecode.club.bytecodeviewer.api.* + +/** + ** This is a skeleton template for BCV's Groovy Plugin System + ** + ** @author [Your Name Goes Here] + **/ + +class Skeleton extends Plugin { + + @Override + void execute(List classNodesList) { + PluginConsole gui = new PluginConsole("Skeleton Title") + gui.setVisible(true) + gui.appendText("executed skeleton example") + } +} \ No newline at end of file diff --git a/plugins/java/ClassParser.java b/plugins/java/ClassParser.java new file mode 100644 index 000000000..f5aefe2de --- /dev/null +++ b/plugins/java/ClassParser.java @@ -0,0 +1,347 @@ +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.tree.ClassNode; +import the.bytecode.club.bytecodeviewer.BytecodeViewer; +import the.bytecode.club.bytecodeviewer.api.Plugin; +import the.bytecode.club.bytecodeviewer.api.PluginConsole; +import the.bytecode.club.bytecodeviewer.translation.TranslatedStrings; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Class Parser + * + * @author Damir37 + */ +public class ClassParser extends Plugin +{ + + private PluginConsole pluginConsole; + + @Override + public void execute(List list) + { + if(!BytecodeViewer.isActiveClassActive()) + { + BytecodeViewer.showMessage("Open A Classfile First"); + return; + } + + ClassNode c = BytecodeViewer.getCurrentlyOpenedClassNode(); + + ClassFileParser classFileParser = new ClassFileParser(classNodeToByte(c)); + + pluginConsole = new PluginConsole("ClassParser"); + pluginConsole.setVisible(true); + + print("Parsing class: " + c.name + ".class"); + print("MAGIC VALUE: " + classFileParser.parseMagicValue()); + print("Class version: " + classFileParser.parseVersionClass()); + print("Constant pool count: " + classFileParser.parseConstantPoolCount() + + " If not all constants were parsed, most likely the constant is not used in the bytecode."); + print("Then use the javap utility to view the constant pool of a class file."); + print("Last modified class: " + classFileParser.parseClassModificationDate()); + print("Hash sum class md5: " + classFileParser.getHash("MD5")); + print("Hash sum class sha1: " + classFileParser.getHash("SHA-1")); + print("Hash sum class sha256: " + classFileParser.getHash("SHA-256")); + print("Hash sum class sha512: " + classFileParser.getHash("SHA-512")); + print("Constant pool ->"); + + classFileParser.getConstantPool().parseConstantPool(); + + if (classFileParser.getConstantPool().getCpList() != null && !classFileParser.getConstantPool().getCpList().isEmpty()) + { + for (String s : classFileParser.getConstantPool().getCpList()) + { + print(s); + } + } + } + + private byte[] classNodeToByte(ClassNode classNode) + { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + classNode.accept(cw); + return cw.toByteArray(); + } + + public void print(String text) + { + pluginConsole.appendText(text); + pluginConsole.repaint(); + } + + private static class ClassFileParser + { + private final ByteBuffer buffer; + private final ConstantParser cpParser; + + public ClassFileParser(byte[] classBytes) + { + this.buffer = ByteBuffer.wrap(classBytes); + cpParser = new ConstantParser(buffer, parseConstantPoolCount()); + } + + public String parseMagicValue() + { + buffer.position(0); + int magicValue = buffer.getInt(); + return "0x" + Integer.toHexString(magicValue).toUpperCase(); + } + + public ClassVersion parseVersionClass() + { + buffer.position(4); + int minor = buffer.getShort() & 0xFFFF; + int major = buffer.getShort() & 0xFFFF; + return ClassVersion.check(major, minor); + } + + public Date parseClassModificationDate() + { + buffer.position(8); + long modificationTime = buffer.getInt() & 0xFFFFFFFFL; + return new Date(modificationTime * 1000L); + } + + public int parseConstantPoolCount() + { + buffer.position(8); + return buffer.getShort() & 0xFFFF; + } + + public String getHash(String algorithm) + { + try + { + MessageDigest md = MessageDigest.getInstance(algorithm); + md.update(buffer.array()); + byte[] digest = md.digest(); + return convertToHex(digest); + } + catch (NoSuchAlgorithmException e) + { + e.printStackTrace(); + } + + return "null"; + } + + private String convertToHex(byte[] bytes) + { + StringBuilder hexString = new StringBuilder(); + + for (byte b : bytes) + { + hexString.append(String.format("%02X", b)); + } + + return hexString.toString(); + } + + public ConstantParser getConstantPool() + { + return cpParser; + } + } + + private enum ClassVersion + { + UNKNOWN(0, 0), + JAVA_1_1(45, 3), + JAVA_1_2(46, 0), + JAVA_1_3(47, 0), + JAVA_1_4(48, 0), + JAVA_5(49, 0), + JAVA_6(50, 0), + JAVA_7(51, 0), + JAVA_8(52, 0), + JAVA_9(53, 0), + JAVA_10(54, 0), + AVA_11(55, 0), + JAVA_12(56, 0), + JAVA_13(57, 0), + JAVA_14(58, 0), + JAVA_15(59, 0), + JAVA_16(60, 0), + JAVA_17(61, 0), + JAVA_18(62, 0), + JAVA_19(63, 0), + JAVA_20(64, 0), + JAVA_21(65, 0), + JAVA_22(66, 0), + JAVA_23(67, 0), + JAVA_24(68, 0), + JAVA_25(69, 0), + JAVA_26(70, 0), + JAVA_27(71, 0), + JAVA_28(72, 0), + JAVA_29(73, 0), + JAVA_30(74, 0); + + public final int major; + public final int minor; + + ClassVersion(int major, int minor) + { + this.major = major; + this.minor = minor; + } + + public static ClassVersion check(int major, int minor) + { + for (ClassVersion v : ClassVersion.values()) + { + if (v.major == major && v.minor == minor) + return v; + } + + return UNKNOWN; + } + } + + private static class ConstantParser + { + private final ByteBuffer buffer; + private final int constantPoolCount; + private final List cpList = new ArrayList(); + + public ConstantParser(ByteBuffer buffer, int constantPoolCount) + { + this.buffer = buffer; + this.constantPoolCount = constantPoolCount; + } + + public void parseConstantPool() + { + buffer.position(10); + + for (int i = 1; i < constantPoolCount; i++) + { + int tag = buffer.get() & 0xFF; + switch (tag) + { + case ConstantType.CONSTANT_Utf8: + int length = buffer.getShort() & 0xFFFF; + byte[] bytes = new byte[length]; + buffer.get(bytes); + String string = new String(bytes); + cpList.add("[" + i + "] CONSTANT_Utf8: " + string); + break; + + case ConstantType.CONSTANT_Integer: + int value = buffer.getInt(); + cpList.add("[" + i + "] CONSTANT_Integer: " + value); + break; + + case ConstantType.CONSTANT_Float: + float floatValue = buffer.getFloat(); + cpList.add("[" + i + "] CONSTANT_Float: " + floatValue); + break; + + case ConstantType.CONSTANT_Long: + long longValue = buffer.getLong(); + cpList.add("[" + i + "] CONSTANT_Long: " + longValue); + i++; + break; + + case ConstantType.CONSTANT_Double: + double doubleValue = buffer.getDouble(); + cpList.add("[" + i + "] CONSTANT_Double: " + doubleValue); + i++; + break; + + case ConstantType.CONSTANT_Class: + int nameIndex = buffer.getShort() & 0xFFFF; + cpList.add("[" + i + "] CONSTANT_Class: #" + nameIndex); + break; + + case ConstantType.CONSTANT_String: + int stringIndex = buffer.getShort() & 0xFFFF; + cpList.add("[" + i + "] CONSTANT_String: #" + stringIndex); + break; + + case ConstantType.CONSTANT_Fieldref: + case ConstantType.CONSTANT_Methodref: + case ConstantType.CONSTANT_InterfaceMethodref: + int classIndex = buffer.getShort() & 0xFFFF; + int nameAndTypeIndex = buffer.getShort() & 0xFFFF; + cpList.add("[" + i + "] CONSTANT_" + getRefTypeName(tag) + ": #" + classIndex + ".#" + nameAndTypeIndex); + break; + + case ConstantType.CONSTANT_NameAndType: + int nameIndex1 = buffer.getShort() & 0xFFFF; + int descriptorIndex = buffer.getShort() & 0xFFFF; + cpList.add("[" + i + "] CONSTANT_NameAndType: #" + nameIndex1 + ":#" + descriptorIndex); + break; + + case ConstantType.CONSTANT_MethodHandle: + int referenceKind = buffer.get() & 0xFF; + int referenceIndex = buffer.getShort() & 0xFFFF; + cpList.add("[" + i + "] CONSTANT_MethodHandle: " + referenceKind + ":#" + referenceIndex); + break; + + case ConstantType.CONSTANT_MethodType: + int descriptorIndex1 = buffer.getShort() & 0xFFFF; + cpList.add("[" + i + "] CONSTANT_MethodType: #" + descriptorIndex1); + break; + + case ConstantType.CONSTANT_InvokeDynamic: + int bootstrapMethodAttrIndex = buffer.getShort() & 0xFFFF; + int nameAndTypeIndex3 = buffer.getShort() & 0xFFFF; + cpList.add("[" + i + "] CONSTANT_InvokeDynamic: #" + bootstrapMethodAttrIndex + ":#" + nameAndTypeIndex3); + break; + + default: + throw new IllegalArgumentException("Unknown constant pool tag " + tag); + } + } + } + + private String getRefTypeName(int tag) + { + switch (tag) + { + case ConstantType.CONSTANT_Fieldref: + return "Fieldref"; + case ConstantType.CONSTANT_Methodref: + return "Methodref"; + case ConstantType.CONSTANT_InterfaceMethodref: + return "InterfaceMethodref"; + default: + return "Unknown"; + } + } + + public List getCpList() + { + return cpList; + } + } + + private interface ConstantType + { + public static final byte CONSTANT_Utf8 = 1; + public static final byte CONSTANT_Class = 7; + public static final byte CONSTANT_Fieldref = 9; + public static final byte CONSTANT_Methodref = 10; + public static final byte CONSTANT_InterfaceMethodref = 11; + public static final byte CONSTANT_String = 8; + public static final byte CONSTANT_Integer = 3; + public static final byte CONSTANT_Float = 4; + public static final byte CONSTANT_Long = 5; + public static final byte CONSTANT_Double = 6; + public static final byte CONSTANT_NameAndType = 12; + public static final byte CONSTANT_MethodHandle = 15; + public static final byte CONSTANT_MethodType = 16; + public static final byte CONSTANT_InvokeDynamic = 18; + } +} diff --git a/plugins/java/ExampleStringDecrypter.java b/plugins/java/ExampleStringDecrypter.java new file mode 100644 index 000000000..8e71a3b43 --- /dev/null +++ b/plugins/java/ExampleStringDecrypter.java @@ -0,0 +1,82 @@ +import java.lang.reflect.Field; +import java.util.List; + +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldNode; +import the.bytecode.club.bytecodeviewer.*; +import the.bytecode.club.bytecodeviewer.api.*; +import the.bytecode.club.bytecodeviewer.gui.components.MultipleChoiceDialog; + +import static the.bytecode.club.bytecodeviewer.Constants.NL; + +/** + * * This is an example of a String Decrypter Java Plugin for BCV. + * * + * * @author [Your-Name-Goes-Here] + **/ + +public class ExampleStringDecrypter extends Plugin +{ + + @Override + public void execute(List classNodesList) + { + PluginConsole gui = new PluginConsole("Example String Decrypter Java Edition"); + + MultipleChoiceDialog dialog = new MultipleChoiceDialog("Bytecode Viewer - WARNING", "WARNING: This will load the classes into the JVM and execute the initialize function" + NL + + "for each class. IF THE FILE YOU'RE LOADING IS MALICIOUS, DO NOT CONTINUE.", new String[]{"Continue", "Cancel"}); + + if (dialog.promptChoice() == 0) + { + boolean needsWarning = false; + + for (ClassNode cn : classNodesList) + { + try + { + //load the class node into the classloader + BCV.getClassNodeLoader().addClass(cn); + + for (Object o : cn.fields.toArray()) + { + FieldNode f = (FieldNode) o; + + //if the class contains the field z, get the class object from the class node + //then print out the value of the fields inside the class + //if the strings get decrypted on init, this allows you to dump the current values + if (f.name.equals("z")) + { + try + { + for (Field f2 : BCV.getClassNodeLoader().nodeToClass(cn).getFields()) + { + String s = (String) f2.get(null); + if (s != null && !s.isEmpty()) + gui.appendText(cn + ":" + s); + } + } + catch (Exception ignored) + { + } + } + } + } + catch (Exception e) + { + gui.appendText("Failed loading class " + cn.name); + e.printStackTrace(); + needsWarning = true; + } + } + + if (needsWarning) + { + BytecodeViewer.showMessage("Some classes failed to decrypt, if you'd like to decrypt all of them" + NL + + "makes sure you include ALL the libraries it requires."); + } + + gui.setVisible(true); + } + } + +} diff --git a/plugins/java/Skeleton.java b/plugins/java/Skeleton.java new file mode 100644 index 000000000..324444102 --- /dev/null +++ b/plugins/java/Skeleton.java @@ -0,0 +1,22 @@ +import java.util.List; +import org.objectweb.asm.tree.ClassNode; +import the.bytecode.club.bytecodeviewer.api.*; + +/** + ** This is a skeleton template for BCV's Java Plugin System + ** + ** @author [Your Name Goes Here] + **/ + +public class Skeleton extends Plugin +{ + + @Override + public void execute(List classNodesList) + { + PluginConsole gui = new PluginConsole("Skeleton Title"); + gui.setVisible(true); + gui.appendText("executed skeleton example"); + } + +} diff --git a/plugins/java/XposedGenerator.java b/plugins/java/XposedGenerator.java new file mode 100644 index 000000000..70c44eed5 --- /dev/null +++ b/plugins/java/XposedGenerator.java @@ -0,0 +1,331 @@ +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.Box; +import javax.swing.JComboBox; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +import org.objectweb.asm.tree.ClassNode; +import the.bytecode.club.bytecodeviewer.*; +import the.bytecode.club.bytecodeviewer.api.*; +import the.bytecode.club.bytecodeviewer.decompilers.impl.FernFlowerDecompiler; +import the.bytecode.club.bytecodeviewer.gui.resourceviewer.viewer.ResourceViewer; + +/** + * * This is an Xposed Generator Plugin, used to aid Reverse-Engineering. + * * + * * @author jowasp + **/ + +public class XposedGenerator extends Plugin +{ + + private static final List methodsNames = new ArrayList<>(); + private static final List cleanMethodsNames = new ArrayList<>(); + private static String foundPckg; + + @Override + public void execute(List classNodeList) + { + //Get actual file class content + ResourceViewer viewer = BytecodeViewer.getActiveResource(); + + if (viewer == null) + { + BytecodeViewer.showMessage("Open A Classfile First"); + return; + } + + String className = viewer.getName(); + ClassNode classnode = BytecodeViewer.getCurrentlyOpenedClassNode(); + + if (classnode == null) + { + BytecodeViewer.showMessage("Open A Classfile First"); + return; + } + + //Call XposedGenerator class + parseChosenFileContent(className, classnode); + } + + public static void parseChosenFileContent(String classname, ClassNode classNode) + { + try + { + //Parse content - Extract methods after APK /JAR has been extracted + byte[] cont = ASMUtil.nodeToBytes(classNode); + + //Use one of the decompilers + //TODO:Allow users to select other decompilers? + FernFlowerDecompiler decompilefern = new FernFlowerDecompiler(); + + //Decompile using Fern + String decomp = decompilefern.decompileClassNode(classNode, cont); + String[] xposedTemplateTypes = {"Empty", "Parameters", "Helper"}; + @SuppressWarnings({"unchecked", "rawtypes"}) + JComboBox xposedTemplateList = new JComboBox(xposedTemplateTypes); + + //Set results of parsed methods into a list + List methodsExtracted = ProcessContentExtractedClass(decomp); + String packgExtracted = ProcessContentExtractedPackage(decomp); + + //Get a clean list + List cleanMethods; + //clear list + cleanMethods = ProcessCleanMethodsAll(methodsExtracted); + if (!cleanMethods.isEmpty()) + { + JComboBox cb = new JComboBox<>(cleanMethods.toArray(new String[0])); + + //Add Panel elements + //Start Panel + JPanel myPanel = new JPanel(); + myPanel.add(Box.createHorizontalStrut(15)); + myPanel.add(xposedTemplateList); + myPanel.add(cb); + + //output methods to pane box + int result = JOptionPane.showConfirmDialog(null, myPanel, "Choose Template and Method for Xposed Module", JOptionPane.OK_CANCEL_OPTION); + myPanel.remove(); + + if (result == JOptionPane.OK_OPTION) + { + //Read Chosen Class + Object cbItem = cb.getSelectedItem(); + Object xPosedItem = xposedTemplateList.getSelectedItem(); + System.out.println("SELECTED CLASS is" + cbItem); + if (cbItem != null && xPosedItem != null) + { + String selectedClass = cbItem.toString(); + String selectedXposedTemplate = xPosedItem.toString(); + + //WriteXposed Class with extracted data + try + { + WriteXposedModule(selectedClass, packgExtracted, classname, selectedXposedTemplate); + } + catch (IllegalArgumentException e) + { + e.printStackTrace(); + JOptionPane.showMessageDialog(null, "Error" + e); + } + } + } + } + else + { + JOptionPane.showMessageDialog(null, "Class Not Suitable"); + } + } + catch (IllegalArgumentException e) + { + e.printStackTrace(); + JOptionPane.showMessageDialog(null, "Error" + e); + } + } + + public static void WriteXposedModule(String functionToHook, String packageName, String classToHook, String template) + { + if (template != null && !template.equals("Empty")) + { + try + { + //Extract the package name only + String packageNameOnly = packageName.substring(8, packageName.length() - 2).trim(); + String classToHookNameOnly = classToHook; + if (classToHookNameOnly.endsWith(".class")) + classToHookNameOnly = classToHook.substring(0, classToHookNameOnly.length() - 6); + + String[] classClean = classToHookNameOnly.split("/"); + String[] functionSplitValues = functionToHook.split("\\s+"); + + //select + String onlyClass = classClean[classClean.length - 1]; + + String onlyFunction = CleanUpFunction(functionSplitValues); + + //Write Xposed Class + String XposedClassText = "package androidpentesting.com.xposedmodule;" + "\r\n" + + "import de.robv.android.xposed.IXposedHookLoadPackage;" + "\r\n" + "\r\n" + + "import de.robv.android.xposed.XC_MethodHook;" + "\r\n" + + "import de.robv.android.xposed.XposedBridge;" + "\r\n" + + "import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;" + "\r\n" + + "import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;" + "\r\n" + "\r\n" + + "public class XposedClassTest implements IXposedHookLoadPackage {" + "\r\n" + "\r\n" + + " public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {" + "\r\n" + "\r\n" + + " String classToHook = " + "\"" + packageNameOnly + "." + onlyClass + "\";" + "\r\n" + + " String functionToHook = " + "\"" + onlyFunction + "\";" + "\r\n" + "\r\n" + + " if (lpparam.packageName.equals(" + "\"" + packageNameOnly + "\"" + ")){" + "\r\n" + + " XposedBridge.log(" + "\" Loaded app: \" " + " + lpparam.packageName);" + "\r\n" + "\r\n" + + " findAndHookMethod(" + "\"" + onlyClass + "\"" + ", lpparam.classLoader, " + " \"" + onlyFunction + "\"" + ", int.class," + "\r\n" + + " new XC_MethodHook() {" + "\r\n" + + " @Override" + "\r\n" + + " protected void beforeHookedMethod(MethodHookParam param) throws Throwable {" + "\r\n" + + " //TO BE FILLED BY ANALYST" + "\r\n" + + " }" + "\r\n" + + " });" + "\r\n" + + " }" + "\r\n" + + " }" + "\r\n" + + "}" + "\r\n"; + + PluginConsole gui = new PluginConsole("Xposed Code Generation"); + gui.appendText(XposedClassText); + gui.setVisible(true); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + else + { + JOptionPane.showMessageDialog(null, "Empty Template Chosen, Did Not Generate"); + } + } + + private static List ProcessContentExtractedClass(String contentFile) + { + Scanner scanner = null; + try + { + scanner = new Scanner(contentFile); + //@TODO : Improve patterns to match other excepts 'public' + + String regexclass = "public"; + Pattern pattern = Pattern.compile(regexclass, Pattern.CASE_INSENSITIVE); + + while (scanner.hasNextLine()) + { + String line = scanner.nextLine(); + + // process the line + Matcher matcher = pattern.matcher(line); + while (matcher.find()) + { + if (matcher.group() != null) + { + System.out.println("find() found the pattern \"" + quote(line.trim())); + System.out.println("Function: " + CleanUpFunction(line.trim().split("\\s+"))); + methodsNames.add(quote(line.trim())); + } + else + { + methodsNames.add("No methods found"); + } + } + } + + if (methodsNames.isEmpty()) + methodsNames.add("No methods found"); + else + return methodsNames; + + return methodsNames; + } + finally + { + if (scanner != null) + scanner.close(); + } + } + + private static List ProcessCleanMethodsAll(List rawMethods) + { + for (String m : rawMethods) + { + //Exclude class declaration + //TODO:add a list containing all possible types + if (!m.contains("extends") && (!m.contains("implements") && (m.contains("(")))) + { + cleanMethodsNames.add(m); + } + } + + return cleanMethodsNames; + } + + private static String CleanUpFunction(String[] rawFunction) + { + String onlyFunc = "functiondummy"; + for (String m : rawFunction) + { + if (m.contains("(")) + { + String[] split = m.split("\\(")[0].split(" "); + return split[split.length - 1]; + } + } + + return onlyFunc; + } + + private static String ProcessContentExtractedPackage(String contentFile) + { + Scanner scanner = null; + try + { + scanner = new Scanner(contentFile); + String regexPkg = "package"; + Pattern patternPkg = Pattern.compile(regexPkg, Pattern.CASE_INSENSITIVE); + String line = scanner.nextLine(); + + // process the line + Matcher matcher = patternPkg.matcher(line); + while (matcher.find()) + { + if (matcher.group() != null) + { + System.out.println("find() found the pattern \"" + quote(line.trim())); + foundPckg = quote(line.trim()); + } + else + { + foundPckg = ""; + } + } + + try + { + if (foundPckg == null || foundPckg.isEmpty()) + foundPckg = "No Package Found"; + + } + catch (NullPointerException e) + { + JOptionPane.showMessageDialog(null, "Error - no package was found in the selected class: " + e); + } + finally + { + scanner.close(); + } + } + catch (IllegalArgumentException e) + { + JOptionPane.showMessageDialog(null, "Error" + e); + if (scanner != null) + scanner.close(); + } + finally + { + if (scanner != null) + scanner.close(); + } + + return foundPckg; + } + + private static String quote(String aText) + { + String QUOTE = "'"; + return QUOTE + aText + QUOTE; + } + +} diff --git a/plugins/javascript/ExamplePrintClassesPlugin.js b/plugins/javascript/ExamplePrintClassesPlugin.js new file mode 100644 index 000000000..3bd8de730 --- /dev/null +++ b/plugins/javascript/ExamplePrintClassesPlugin.js @@ -0,0 +1,20 @@ + +/** + ** An example BCV Javascript Plugin. + ** This is used to display all of loaded classnodes that have been imported into BCV. + ** + ** @author [Your-Name-Goes-Here] + **/ + +var PluginConsole = Java.type("the.bytecode.club.bytecodeviewer.api.PluginConsole"); + +var gui = new PluginConsole("Example Plugin Print Loaded Classes Javascript Edition"); + +function execute(classNodeList) { + for (index = 0; index < classNodeList.length; index++) { + var cn = classNodeList[index]; + gui.appendText("Resource: " + cn.name + ".class"); + } + + gui.setVisible(true); +} \ No newline at end of file diff --git a/plugins/javascript/ExampleStringDecrypter.js b/plugins/javascript/ExampleStringDecrypter.js new file mode 100644 index 000000000..3e907db53 --- /dev/null +++ b/plugins/javascript/ExampleStringDecrypter.js @@ -0,0 +1,69 @@ + +/** + ** This is an example of a String Decrypter Javascript Plugin for BCV. + ** + ** @author [Your-Name-Goes-Here] + **/ + +var PluginConsole = Java.type("the.bytecode.club.bytecodeviewer.api.PluginConsole"); +var MultipleChoiceDialog = Java.type("the.bytecode.club.bytecodeviewer.gui.components.MultipleChoiceDialog") +var BytecodeViewer = Java.type("the.bytecode.club.bytecodeviewer.api.BCV") + +var dialog = new MultipleChoiceDialog("Bytecode Viewer - WARNING", + "WARNING: This will load the classes into the JVM and execute the initialize function" + + "\nfor each class. IF THE FILE YOU'RE LOADING IS MALICIOUS, DO NOT CONTINUE.", + ["Continue", "Cancel"]); +var gui; + +function execute(classNodeList) { + gui = new PluginConsole("Example String Decrypter Javascript Edition"); + + if (dialog.promptChoice() == 0) { + var needsWarning = false; + + for (cnIndex = 0; cnIndex < classNodeList.length; cnIndex++) { + try { + var cn = classNodeList[cnIndex]; + + //load the class node into the classloader + BytecodeViewer.getClassNodeLoader().addClass(cn); + + var fields = cn.fields.toArray(); + for (fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) { + var field = fields[fieldIndex]; + + //if the class contains the field z, get the class object from the class node + //then print out the value of the fields inside the class + //if the strings get decrypted on init, this allows you to dump the current values + + if (field.name.equals("z")) { + try { + var loadedClass = BytecodeViewer.getClassNodeLoader().nodeToClass(cn); + var reflectedFields = loadedClass.getFields(); + + for (reflectedFieldIndex = 0; reflectedFieldIndex < reflectedFields.length; reflectedFieldIndex++) { + var reflectedField = reflectedFields[fieldIndex]; + var s = reflectedField.get(null); + + if (s != null && !s.empty()) + gui.appendText(cn + "->" + s); + } + } catch (ignored) { + } + } + } + } catch (e) { + gui.appendText("Failed loading class " + cn.name); + e.printStackTrace(); + needsWarning = true; + } + } + + if (needsWarning) { + BytecodeViewer.showMessage("Some classes failed to decrypt, if you'd like to decrypt all of them\n" + + "makes sure you include ALL the libraries it requires."); + } + + gui.setVisible(true); + } +} diff --git a/plugins/javascript/Skeleton.js b/plugins/javascript/Skeleton.js new file mode 100644 index 000000000..7c955cd9f --- /dev/null +++ b/plugins/javascript/Skeleton.js @@ -0,0 +1,13 @@ + +/** + ** This is a skeleton template for BCV's Javascript Plugin System + ** + ** @author [Your Name Goes Here] + **/ + +function execute(classNodeList) { + var PluginConsole = Java.type("the.bytecode.club.bytecodeviewer.api.PluginConsole"); + var gui = new PluginConsole("Skeleton Title"); + gui.setVisible(true); + gui.appendText("executed skeleton example"); +} \ No newline at end of file diff --git a/plugins/skeleton.py b/plugins/python/skeleton.py similarity index 54% rename from plugins/skeleton.py rename to plugins/python/skeleton.py index 99c3a3a67..6f7e0b421 100644 --- a/plugins/skeleton.py +++ b/plugins/python/skeleton.py @@ -5,9 +5,14 @@ from java.util import ArrayList from org.objectweb.asm.tree import ClassNode -class skeleton(Plugin): +# +# This is a skeleton template for BCV's Ruby Plugin System +# +# @author [Your Name Goes Here] +# - def execute(classNodeList, poop): #for some reason it requires a second arg - gui = PluginConsole("Skeleton") +class skeleton(Plugin): + def execute(classNodeList, notUsed): #for some reason it requires a second arg + gui = PluginConsole("Skeleton Title") gui.setVisible(Boolean.TRUE) - gui.appendText("exceuted skeleton") \ No newline at end of file + gui.appendText("executed skeleton example") \ No newline at end of file diff --git a/plugins/ruby/Skeleton.rb b/plugins/ruby/Skeleton.rb new file mode 100644 index 000000000..ae7623fbf --- /dev/null +++ b/plugins/ruby/Skeleton.rb @@ -0,0 +1,21 @@ +require 'java' + +java_import 'the.bytecode.club.bytecodeviewer.api.Plugin' +java_import 'the.bytecode.club.bytecodeviewer.api.PluginConsole' +java_import 'java.lang.System' +java_import 'java.util.ArrayList' +java_import 'org.objectweb.asm.tree.ClassNode' + +# +# This is a skeleton template for BCV's Ruby Plugin System +# +# @author [Your Name Goes Here] +# + +class Skeleton < Plugin + def execute(classNodeList) + gui = PluginConsole.new "Skeleton Title" + gui.setVisible(true) + gui.appendText("executed skeleton example") + end +end \ No newline at end of file diff --git a/pom.xml b/pom.xml index 4dd32ce4c..1f6ece39b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,185 +1,512 @@ - - + 4.0.0 the.bytecode.club - bytecode-viewer - 3.0.0 + Bytecode-Viewer + 2.13.1 + + + 1.8 + ${java.version} + ${java.version} UTF-8 + + + 24.1.0 + 2.11.0 + 9.7 + 0.2.2 + 1.0bcv + 0.152 + 1.9.12 + 1.9.0 + 1.17.1 + 3.1.12 + 1.27.1 + 2.16.1 + 3.17.0 + 1.12.0 + 3.0.2 + 0.4.1 + 6.3.9.Final + 2.4.22 + e0d44f4 + 2.11.0 + 33.3.0-jre + 2.2.0 + 4.2 + 1.4.7 + 1.6.6bcv + 3.4.1.3 + 21.2.0 + 3.4 + 0.2.2 + 0.6.0 + 3.5.2 + 2.1.1 + 2.0.16 + 3.0.8 + 1.34.1 + 1.0.3 + a8f700b + 1.1.4c + 3.26.2 + 1.0.1 + 1.7 + 1.2.0 - - src/main/java - - - src/main/resources - - - - - maven-compiler-plugin - 3.3 - - 1.7 - 1.7 - true - - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 - - - maven-shade-plugin - 2.3 - - - package - - shade - - - - - the.bytecode.club.bytecodeviewer.BytecodeViewer - - - - - *:* - - META-INF/* - - - - com.fifesoft:rsyntaxtextarea - - ** - - - - true - - - - - - - bytecode-viewer - Bytecode Viewer Repository - http://repo.samczsun.com/content/repositories/bytecode-viewer/ + google + https://maven.google.com/ + + + local-maven-repo + file:///${project.basedir}/libs + + + jitpack.io + https://jitpack.io + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots/ - org.imgscalr - imgscalr-lib - 4.2 + com.konloch + HTTPRequest + ${httprequest.version} + + + org.jetbrains + annotations + ${annotations.version} + + + org.apktool + apktool-cli + ${apktool.version} + + + org.apktool + apktool-lib + ${apktool.version} + + + org.yaml + snakeyaml + + + + + org.ow2.asm + asm + ${asm.version} + + + org.ow2.asm + asm-analysis + ${asm.version} + + + org.ow2.asm + asm-commons + ${asm.version} + + + org.ow2.asm + asm-tree + ${asm.version} + + + org.ow2.asm + asm-util + ${asm.version} + + + org.exbin.bined + bined-core + ${bined.version} + + + org.exbin.bined + bined-swing + ${bined.version} + + + org.exbin.bined + bined-highlight-swing + ${bined.version} + + + org.benf + cfr + ${cfr.version} + + + uk.com.robust-it + cloning + ${cloning.version} commons-cli commons-cli - 1.3.1 + ${commons-cli.version} commons-codec commons-codec - 1.10 + ${commons-codec.version} org.codehaus.janino - janino - 2.7.8 + commons-compiler + ${commons-compiler.version} org.apache.commons - commons-lang3 - 3.4 + commons-compress + ${commons-compress.version} commons-io commons-io - 2.4 + ${commons-io.version} - com.fifesoft - rsyntaxtextarea - 2.5.8 + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + org.jboss.windup.decompiler + decompiler-fernflower + ${decompiler-fernflower.version} + + + org.jboss.windup.decompiler.fernflower + windup-fernflower + + + + + com.github.ThexXTURBOXx + fernflower + ${fernflower.version} + + + com.google.guava + guava + ${guava.version} + + + com.google.code.gson + gson + ${gson.version} + + + org.imgscalr + imgscalr-lib + ${imgscalr-lib.version} + + + org.codehaus.janino + janino + ${commons-compiler.version} + + + org.jd + jd-gui + ${jd-gui.version} + + + eu.bibl.banalysis + byteanalysis + ${byteanalysis.version} org.tinyjee.jgraphx jgraphx - 2.3.0.5 + ${jgraphx.version} - com.googlecode.mp4parser - isoparser - 1.1.9 + org.objenesis + objenesis + ${objenesis.version} - org.ow2.asm - asm-all - 5.0.4 + org.exbin.auxiliary + binary_data + ${binary-data.version} - org.zeroturnaround - zt-zip - 1.8 + org.exbin.auxiliary + binary_data-array + ${binary-data.version} - - com.strobel - procyon - 0.5.30 + org.bitbucket.mstrobel + procyon-core + ${procyon.version} - org.benf - cfr - 0.108 + org.bitbucket.mstrobel + procyon-expressions + ${procyon.version} - ca.benow - jd - 1.4.0 + org.bitbucket.mstrobel + procyon-reflection + ${procyon.version} - eu.bibl - byteanalysis - 1.0 + org.bitbucket.mstrobel + procyon-compilertools + ${procyon.version} - brut - apktool - 2.0.1 + com.fifesoft + rsyntaxtextarea + ${rsyntaxtextarea.version} - org.jetbrains.java - decompiler - 2015-1 + org.slf4j + slf4j-api + ${slf4j.version} - dex2jar + com.android.tools.smali + smali + ${smali.version} + + + com.android.tools.smali + smali-baksmali + ${smali.version} + + + com.konloch + safeyaml + ${safeyaml.version} + + + xpp3 + xpp3 + ${xpp3.version} + + + io.github.skylot + jadx-core + ${jadx.version} + + + io.github.skylot + jadx-java-convert + ${jadx.version} + + + com.android.tools + r8 + + + com.jakewharton.android.repackaged + dalvik-dx + + + + + io.github.skylot + jadx-dex-input + ${jadx.version} + + + org.smali + baksmali + + + + + io.github.skylot + jadx-smali-input + ${jadx.version} + + + org.smali + smali + + + + + de.femtopedia.dex2jar dex2jar - 0.0.1 + ${dex2jar.version} - org.jf - smali - patched - 2.0.3 + com.github.weisj + darklaf-core + ${darklaf.version} + + + com.github.weisj + darklaf-extensions-rsyntaxarea + ${darklaf-extensions-rsta.version} - org.jf - baksmali - 2.0.3 + com.github.ThexXTURBOXx + webp-imageio + ${webp-imageio.version} + + de.skuzzle + semantic-version + ${semantic-version.version} + + + org.abego.treelayout + org.abego.treelayout.core + ${treelayout.version} + + + com.github.javaparser + javaparser-core + ${java-parser.version} + + + com.github.javaparser + javaparser-symbol-solver-core + ${java-parser.version} + + + com.konloch + TaskManager + ${taskmanager.version} + + + com.google.googlejavaformat + google-java-format + ${google-java-format.version} + + + com.konloch + DiskLib + ${disk-lib.version} + + + + - \ No newline at end of file + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.5.0 + + checkstyle.xml + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + ${maven.compiler.source} + ${maven.compiler.target} + true + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.0 + + ${maven.compiler.source} + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + + shade + + + + + + + *:* + + **/module-info.class + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + META-INF/*LICENSE* + META-INF/*NOTICE* + META-INF/MANIFEST.MF + LICENSE + license.txt + NOTICE + + + + + de.femtopedia.dex2jar:d2j-external + true + + com/android/** + api_database/** + META-INF/services/** + LICENSE + r8-version.properties + org/objectweb/asm/MethodWriter.class + + + + + org.ow2.asm:asm + + org/objectweb/asm/MethodWriter.class + + + + + + the.bytecode.club.bytecodeviewer.BytecodeViewer + + ${project.version} + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + + + diff --git a/src/main/java/com/eclipsesource/json/Json.java b/src/main/java/com/eclipsesource/json/Json.java deleted file mode 100644 index 275b3e60e..000000000 --- a/src/main/java/com/eclipsesource/json/Json.java +++ /dev/null @@ -1,333 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; -import java.io.Reader; - - -/** - * This class serves as the entry point to the minimal-json API. - *

- * To parse a given JSON input, use the parse() methods like in this - * example: - *

- *
- * JsonObject object = Json.parse(string).asObject();
- * 
- *

- * To create a JSON data structure to be serialized, use the methods - * value(), array(), and object(). For example, the following - * snippet will produce the JSON string {"foo": 23, "bar": true}: - *

- *
- * String string = Json.object().add("foo", 23).add("bar", true).toString();
- * 
- *

- * To create a JSON array from a given Java array, you can use one of the array() - * methods with varargs parameters: - *

- *
- * String[] names = ...
- * JsonArray array = Json.array(names);
- * 
- */ -public final class Json { - - private Json() { - // not meant to be instantiated - } - - /** - * Represents the JSON literal null. - */ - public static final JsonValue NULL = new JsonLiteral("null"); - - /** - * Represents the JSON literal true. - */ - public static final JsonValue TRUE = new JsonLiteral("true"); - - /** - * Represents the JSON literal false. - */ - public static final JsonValue FALSE = new JsonLiteral("false"); - - /** - * Returns a JsonValue instance that represents the given int value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - */ - public static JsonValue value(int value) { - return new JsonNumber(Integer.toString(value, 10)); - } - - /** - * Returns a JsonValue instance that represents the given long value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - */ - public static JsonValue value(long value) { - return new JsonNumber(Long.toString(value, 10)); - } - - /** - * Returns a JsonValue instance that represents the given float value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - */ - public static JsonValue value(float value) { - if (Float.isInfinite(value) || Float.isNaN(value)) { - throw new IllegalArgumentException("Infinite and NaN values not permitted in JSON"); - } - return new JsonNumber(cutOffPointZero(Float.toString(value))); - } - - /** - * Returns a JsonValue instance that represents the given double value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - */ - public static JsonValue value(double value) { - if (Double.isInfinite(value) || Double.isNaN(value)) { - throw new IllegalArgumentException("Infinite and NaN values not permitted in JSON"); - } - return new JsonNumber(cutOffPointZero(Double.toString(value))); - } - - /** - * Returns a JsonValue instance that represents the given string. - * - * @param string - * the string to get a JSON representation for - * @return a JSON value that represents the given string - */ - public static JsonValue value(String string) { - return string == null ? NULL : new JsonString(string); - } - - /** - * Returns a JsonValue instance that represents the given boolean value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - */ - public static JsonValue value(boolean value) { - return value ? TRUE : FALSE; - } - - /** - * Creates a new empty JsonArray. This is equivalent to creating a new JsonArray using the - * constructor. - * - * @return a new empty JSON array - */ - public static JsonValue array() { - return new JsonArray(); - } - - /** - * Creates a new JsonArray that contains the JSON representations of the given int - * values. - * - * @param values - * the values to be included in the new JSON array - * @return a new JSON array that contains the given values - */ - public static JsonArray array(int... values) { - if (values == null) { - throw new NullPointerException("values is null"); - } - JsonArray array = new JsonArray(); - for (int value : values) { - array.add(value); - } - return array; - } - - /** - * Creates a new JsonArray that contains the JSON representations of the given long - * values. - * - * @param values - * the values to be included in the new JSON array - * @return a new JSON array that contains the given values - */ - public static JsonArray array(long... values) { - if (values == null) { - throw new NullPointerException("values is null"); - } - JsonArray array = new JsonArray(); - for (long value : values) { - array.add(value); - } - return array; - } - - /** - * Creates a new JsonArray that contains the JSON representations of the given float - * values. - * - * @param values - * the values to be included in the new JSON array - * @return a new JSON array that contains the given values - */ - public static JsonArray array(float... values) { - if (values == null) { - throw new NullPointerException("values is null"); - } - JsonArray array = new JsonArray(); - for (float value : values) { - array.add(value); - } - return array; - } - - /** - * Creates a new JsonArray that contains the JSON representations of the given double - * values. - * - * @param values - * the values to be included in the new JSON array - * @return a new JSON array that contains the given values - */ - public static JsonArray array(double... values) { - if (values == null) { - throw new NullPointerException("values is null"); - } - JsonArray array = new JsonArray(); - for (double value : values) { - array.add(value); - } - return array; - } - - /** - * Creates a new JsonArray that contains the JSON representations of the given - * boolean values. - * - * @param values - * the values to be included in the new JSON array - * @return a new JSON array that contains the given values - */ - public static JsonArray array(boolean... values) { - if (values == null) { - throw new NullPointerException("values is null"); - } - JsonArray array = new JsonArray(); - for (boolean value : values) { - array.add(value); - } - return array; - } - - /** - * Creates a new JsonArray that contains the JSON representations of the given strings. - * - * @param strings - * the strings to be included in the new JSON array - * @return a new JSON array that contains the given strings - */ - public static JsonArray array(String... strings) { - if (strings == null) { - throw new NullPointerException("values is null"); - } - JsonArray array = new JsonArray(); - for (String value : strings) { - array.add(value); - } - return array; - } - - /** - * Creates a new empty JsonObject. This is equivalent to creating a new JsonObject using the - * constructor. - * - * @return a new empty JSON object - */ - public static JsonObject object() { - return new JsonObject(); - } - - /** - * Parses the given input string as JSON. The input must contain a valid JSON value, optionally - * padded with whitespace. - * - * @param string - * the input string, must be valid JSON - * @return a value that represents the parsed JSON - * @throws ParseException - * if the input is not valid JSON - */ - public static JsonValue parse(String string) { - if (string == null) { - throw new NullPointerException("string is null"); - } - try { - return new JsonParser(string).parse(); - } catch (IOException exception) { - // JsonParser does not throw IOException for String - throw new RuntimeException(exception); - } - } - - /** - * Reads the entire input stream from the given reader and parses it as JSON. The input must - * contain a valid JSON value, optionally padded with whitespace. - *

- * Characters are read in chunks and buffered internally, therefore wrapping an existing reader in - * an additional BufferedReader does not improve reading - * performance. - *

- * - * @param reader - * the reader to read the JSON value from - * @return a value that represents the parsed JSON - * @throws IOException - * if an I/O error occurs in the reader - * @throws ParseException - * if the input is not valid JSON - */ - public static JsonValue parse(Reader reader) throws IOException { - if (reader == null) { - throw new NullPointerException("reader is null"); - } - return new JsonParser( reader ).parse(); - } - - private static String cutOffPointZero(String string) { - if (string.endsWith(".0")) { - return string.substring(0, string.length() - 2); - } - return string; - } - -} diff --git a/src/main/java/com/eclipsesource/json/JsonArray.java b/src/main/java/com/eclipsesource/json/JsonArray.java deleted file mode 100644 index c4b30cf2e..000000000 --- a/src/main/java/com/eclipsesource/json/JsonArray.java +++ /dev/null @@ -1,499 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; -import java.io.Reader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - - -/** - * Represents a JSON array, an ordered collection of JSON values. - *

- * Elements can be added using the add(...) methods which accept instances of - * {@link JsonValue}, strings, primitive numbers, and boolean values. To replace an element of an - * array, use the set(int, ...) methods. - *

- *

- * Elements can be accessed by their index using {@link #get(int)}. This class also supports - * iterating over the elements in document order using an {@link #iterator()} or an enhanced for - * loop: - *

- *
- * for (JsonValue value : jsonArray) {
- *   ...
- * }
- * 
- *

- * An equivalent {@link List} can be obtained from the method {@link #values()}. - *

- *

- * Note that this class is not thread-safe. If multiple threads access a - * JsonArray instance concurrently, while at least one of these threads modifies the - * contents of this array, access to the instance must be synchronized externally. Failure to do so - * may lead to an inconsistent state. - *

- *

- * This class is not supposed to be extended by clients. - *

- */ -@SuppressWarnings("serial") // use default serial UID -public class JsonArray extends JsonValue implements Iterable { - - private final List values; - - /** - * Creates a new empty JsonArray. - */ - public JsonArray() { - values = new ArrayList(); - } - - /** - * Creates a new JsonArray with the contents of the specified JSON array. - * - * @param array - * the JsonArray to get the initial contents from, must not be null - */ - public JsonArray(JsonArray array) { - this(array, false); - } - - private JsonArray(JsonArray array, boolean unmodifiable) { - if (array == null) { - throw new NullPointerException("array is null"); - } - if (unmodifiable) { - values = Collections.unmodifiableList(array.values); - } else { - values = new ArrayList(array.values); - } - } - - /** - * Reads a JSON array from the given reader. - *

- * Characters are read in chunks and buffered internally, therefore wrapping an existing reader in - * an additional BufferedReader does not improve reading - * performance. - *

- * - * @param reader - * the reader to read the JSON array from - * @return the JSON array that has been read - * @throws IOException - * if an I/O error occurs in the reader - * @throws ParseException - * if the input is not valid JSON - * @throws UnsupportedOperationException - * if the input does not contain a JSON array - * @deprecated Use {@link Json#parse(Reader)}{@link JsonValue#asArray() .asArray()} instead - */ - @Deprecated - public static JsonArray readFrom(Reader reader) throws IOException { - return JsonValue.readFrom(reader).asArray(); - } - - /** - * Reads a JSON array from the given string. - * - * @param string - * the string that contains the JSON array - * @return the JSON array that has been read - * @throws ParseException - * if the input is not valid JSON - * @throws UnsupportedOperationException - * if the input does not contain a JSON array - * @deprecated Use {@link Json#parse(String)}{@link JsonValue#asArray() .asArray()} instead - */ - @Deprecated - public static JsonArray readFrom(String string) { - return JsonValue.readFrom(string).asArray(); - } - - /** - * Returns an unmodifiable wrapper for the specified JsonArray. This method allows to provide - * read-only access to a JsonArray. - *

- * The returned JsonArray is backed by the given array and reflects subsequent changes. Attempts - * to modify the returned JsonArray result in an UnsupportedOperationException. - *

- * - * @param array - * the JsonArray for which an unmodifiable JsonArray is to be returned - * @return an unmodifiable view of the specified JsonArray - */ - public static JsonArray unmodifiableArray(JsonArray array) { - return new JsonArray(array, true); - } - - /** - * Appends the JSON representation of the specified int value to the end of this - * array. - * - * @param value - * the value to add to the array - * @return the array itself, to enable method chaining - */ - public JsonArray add(int value) { - values.add(Json.value(value)); - return this; - } - - /** - * Appends the JSON representation of the specified long value to the end of this - * array. - * - * @param value - * the value to add to the array - * @return the array itself, to enable method chaining - */ - public JsonArray add(long value) { - values.add(Json.value(value)); - return this; - } - - /** - * Appends the JSON representation of the specified float value to the end of this - * array. - * - * @param value - * the value to add to the array - * @return the array itself, to enable method chaining - */ - public JsonArray add(float value) { - values.add(Json.value(value)); - return this; - } - - /** - * Appends the JSON representation of the specified double value to the end of this - * array. - * - * @param value - * the value to add to the array - * @return the array itself, to enable method chaining - */ - public JsonArray add(double value) { - values.add(Json.value(value)); - return this; - } - - /** - * Appends the JSON representation of the specified boolean value to the end of this - * array. - * - * @param value - * the value to add to the array - * @return the array itself, to enable method chaining - */ - public JsonArray add(boolean value) { - values.add(Json.value(value)); - return this; - } - - /** - * Appends the JSON representation of the specified string to the end of this array. - * - * @param value - * the string to add to the array - * @return the array itself, to enable method chaining - */ - public JsonArray add(String value) { - values.add(Json.value(value)); - return this; - } - - /** - * Appends the specified JSON value to the end of this array. - * - * @param value - * the JsonValue to add to the array, must not be null - * @return the array itself, to enable method chaining - */ - public JsonArray add(JsonValue value) { - if (value == null) { - throw new NullPointerException("value is null"); - } - values.add(value); - return this; - } - - /** - * Replaces the element at the specified position in this array with the JSON representation of - * the specified int value. - * - * @param index - * the index of the array element to replace - * @param value - * the value to be stored at the specified array position - * @return the array itself, to enable method chaining - * @throws IndexOutOfBoundsException - * if the index is out of range, i.e. index < 0 or - * index >= size - */ - public JsonArray set(int index, int value) { - values.set(index, Json.value(value)); - return this; - } - - /** - * Replaces the element at the specified position in this array with the JSON representation of - * the specified long value. - * - * @param index - * the index of the array element to replace - * @param value - * the value to be stored at the specified array position - * @return the array itself, to enable method chaining - * @throws IndexOutOfBoundsException - * if the index is out of range, i.e. index < 0 or - * index >= size - */ - public JsonArray set(int index, long value) { - values.set(index, Json.value(value)); - return this; - } - - /** - * Replaces the element at the specified position in this array with the JSON representation of - * the specified float value. - * - * @param index - * the index of the array element to replace - * @param value - * the value to be stored at the specified array position - * @return the array itself, to enable method chaining - * @throws IndexOutOfBoundsException - * if the index is out of range, i.e. index < 0 or - * index >= size - */ - public JsonArray set(int index, float value) { - values.set(index, Json.value(value)); - return this; - } - - /** - * Replaces the element at the specified position in this array with the JSON representation of - * the specified double value. - * - * @param index - * the index of the array element to replace - * @param value - * the value to be stored at the specified array position - * @return the array itself, to enable method chaining - * @throws IndexOutOfBoundsException - * if the index is out of range, i.e. index < 0 or - * index >= size - */ - public JsonArray set(int index, double value) { - values.set(index, Json.value(value)); - return this; - } - - /** - * Replaces the element at the specified position in this array with the JSON representation of - * the specified boolean value. - * - * @param index - * the index of the array element to replace - * @param value - * the value to be stored at the specified array position - * @return the array itself, to enable method chaining - * @throws IndexOutOfBoundsException - * if the index is out of range, i.e. index < 0 or - * index >= size - */ - public JsonArray set(int index, boolean value) { - values.set(index, Json.value(value)); - return this; - } - - /** - * Replaces the element at the specified position in this array with the JSON representation of - * the specified string. - * - * @param index - * the index of the array element to replace - * @param value - * the string to be stored at the specified array position - * @return the array itself, to enable method chaining - * @throws IndexOutOfBoundsException - * if the index is out of range, i.e. index < 0 or - * index >= size - */ - public JsonArray set(int index, String value) { - values.set(index, Json.value(value)); - return this; - } - - /** - * Replaces the element at the specified position in this array with the specified JSON value. - * - * @param index - * the index of the array element to replace - * @param value - * the value to be stored at the specified array position, must not be null - * @return the array itself, to enable method chaining - * @throws IndexOutOfBoundsException - * if the index is out of range, i.e. index < 0 or - * index >= size - */ - public JsonArray set(int index, JsonValue value) { - if (value == null) { - throw new NullPointerException("value is null"); - } - values.set(index, value); - return this; - } - - /** - * Removes the element at the specified index from this array. - * - * @param index - * the index of the element to remove - * @return the array itself, to enable method chaining - * @throws IndexOutOfBoundsException - * if the index is out of range, i.e. index < 0 or - * index >= size - */ - public JsonArray remove(int index) { - values.remove(index); - return this; - } - - /** - * Returns the number of elements in this array. - * - * @return the number of elements in this array - */ - public int size() { - return values.size(); - } - - /** - * Returns true if this array contains no elements. - * - * @return true if this array contains no elements - */ - public boolean isEmpty() { - return values.isEmpty(); - } - - /** - * Returns the value of the element at the specified position in this array. - * - * @param index - * the index of the array element to return - * @return the value of the element at the specified position - * @throws IndexOutOfBoundsException - * if the index is out of range, i.e. index < 0 or - * index >= size - */ - public JsonValue get(int index) { - return values.get(index); - } - - /** - * Returns a list of the values in this array in document order. The returned list is backed by - * this array and will reflect subsequent changes. It cannot be used to modify this array. - * Attempts to modify the returned list will result in an exception. - * - * @return a list of the values in this array - */ - public List values() { - return Collections.unmodifiableList(values); - } - - /** - * Returns an iterator over the values of this array in document order. The returned iterator - * cannot be used to modify this array. - * - * @return an iterator over the values of this array - */ - public Iterator iterator() { - final Iterator iterator = values.iterator(); - return new Iterator() { - - public boolean hasNext() { - return iterator.hasNext(); - } - - public JsonValue next() { - return iterator.next(); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - - @Override - void write(JsonWriter writer) throws IOException { - writer.writeArrayOpen(); - Iterator iterator = iterator(); - boolean first = true; - while (iterator.hasNext()) { - if (!first) { - writer.writeArraySeparator(); - } - iterator.next().write(writer); - first = false; - } - writer.writeArrayClose(); - } - - @Override - public boolean isArray() { - return true; - } - - @Override - public JsonArray asArray() { - return this; - } - - @Override - public int hashCode() { - return values.hashCode(); - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object == null) { - return false; - } - if (getClass() != object.getClass()) { - return false; - } - JsonArray other = (JsonArray)object; - return values.equals(other.values); - } - -} diff --git a/src/main/java/com/eclipsesource/json/JsonLiteral.java b/src/main/java/com/eclipsesource/json/JsonLiteral.java deleted file mode 100644 index 7762689e1..000000000 --- a/src/main/java/com/eclipsesource/json/JsonLiteral.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; - - -@SuppressWarnings("serial") // use default serial UID -class JsonLiteral extends JsonValue { - - private final String value; - private final boolean isNull; - private final boolean isTrue; - private final boolean isFalse; - - JsonLiteral(String value) { - this.value = value; - isNull = "null".equals(value); - isTrue = "true".equals(value); - isFalse = "false".equals(value); - } - - @Override - void write(JsonWriter writer) throws IOException { - writer.writeLiteral(value); - } - - @Override - public String toString() { - return value; - } - - @Override - public int hashCode() { - return value.hashCode(); - } - - @Override - public boolean isNull() { - return isNull; - } - - @Override - public boolean isTrue() { - return isTrue; - } - - @Override - public boolean isFalse() { - return isFalse; - } - - @Override - public boolean isBoolean() { - return isTrue || isFalse; - } - - @Override - public boolean asBoolean() { - return isNull ? super.asBoolean() : isTrue; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object == null) { - return false; - } - if (getClass() != object.getClass()) { - return false; - } - JsonLiteral other = (JsonLiteral)object; - return value.equals(other.value); - } - -} diff --git a/src/main/java/com/eclipsesource/json/JsonNumber.java b/src/main/java/com/eclipsesource/json/JsonNumber.java deleted file mode 100644 index 74ba958d1..000000000 --- a/src/main/java/com/eclipsesource/json/JsonNumber.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; - - -@SuppressWarnings("serial") // use default serial UID -class JsonNumber extends JsonValue { - - private final String string; - - JsonNumber(String string) { - if (string == null) { - throw new NullPointerException("string is null"); - } - this.string = string; - } - - @Override - public String toString() { - return string; - } - - @Override - void write(JsonWriter writer) throws IOException { - writer.writeNumber(string); - } - - @Override - public boolean isNumber() { - return true; - } - - @Override - public int asInt() { - return Integer.parseInt(string, 10); - } - - @Override - public long asLong() { - return Long.parseLong(string, 10); - } - - @Override - public float asFloat() { - return Float.parseFloat(string); - } - - @Override - public double asDouble() { - return Double.parseDouble(string); - } - - @Override - public int hashCode() { - return string.hashCode(); - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object == null) { - return false; - } - if (getClass() != object.getClass()) { - return false; - } - JsonNumber other = (JsonNumber)object; - return string.equals(other.string); - } - -} diff --git a/src/main/java/com/eclipsesource/json/JsonObject.java b/src/main/java/com/eclipsesource/json/JsonObject.java deleted file mode 100644 index 3f580a84f..000000000 --- a/src/main/java/com/eclipsesource/json/JsonObject.java +++ /dev/null @@ -1,907 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Reader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import com.eclipsesource.json.JsonObject.Member; - - -/** - * Represents a JSON object, a set of name/value pairs, where the names are strings and the values - * are JSON values. - *

- * Members can be added using the add(String, ...) methods which accept instances of - * {@link JsonValue}, strings, primitive numbers, and boolean values. To modify certain values of an - * object, use the set(String, ...) methods. Please note that the add - * methods are faster than set as they do not search for existing members. On the other - * hand, the add methods do not prevent adding multiple members with the same name. - * Duplicate names are discouraged but not prohibited by JSON. - *

- *

- * Members can be accessed by their name using {@link #get(String)}. A list of all names can be - * obtained from the method {@link #names()}. This class also supports iterating over the members in - * document order using an {@link #iterator()} or an enhanced for loop: - *

- *
- * for (Member member : jsonObject) {
- *   String name = member.getName();
- *   JsonValue value = member.getValue();
- *   ...
- * }
- * 
- *

- * Even though JSON objects are unordered by definition, instances of this class preserve the order - * of members to allow processing in document order and to guarantee a predictable output. - *

- *

- * Note that this class is not thread-safe. If multiple threads access a - * JsonObject instance concurrently, while at least one of these threads modifies the - * contents of this object, access to the instance must be synchronized externally. Failure to do so - * may lead to an inconsistent state. - *

- *

- * This class is not supposed to be extended by clients. - *

- */ -@SuppressWarnings("serial") // use default serial UID -public class JsonObject extends JsonValue implements Iterable { - - private final List names; - private final List values; - private transient HashIndexTable table; - - /** - * Creates a new empty JsonObject. - */ - public JsonObject() { - names = new ArrayList(); - values = new ArrayList(); - table = new HashIndexTable(); - } - - /** - * Creates a new JsonObject, initialized with the contents of the specified JSON object. - * - * @param object - * the JSON object to get the initial contents from, must not be null - */ - public JsonObject(JsonObject object) { - this(object, false); - } - - private JsonObject(JsonObject object, boolean unmodifiable) { - if (object == null) { - throw new NullPointerException("object is null"); - } - if (unmodifiable) { - names = Collections.unmodifiableList(object.names); - values = Collections.unmodifiableList(object.values); - } else { - names = new ArrayList(object.names); - values = new ArrayList(object.values); - } - table = new HashIndexTable(); - updateHashIndex(); - } - - /** - * Reads a JSON object from the given reader. - *

- * Characters are read in chunks and buffered internally, therefore wrapping an existing reader in - * an additional BufferedReader does not improve reading - * performance. - *

- * - * @param reader - * the reader to read the JSON object from - * @return the JSON object that has been read - * @throws IOException - * if an I/O error occurs in the reader - * @throws ParseException - * if the input is not valid JSON - * @throws UnsupportedOperationException - * if the input does not contain a JSON object - * @deprecated Use {@link Json#parse(Reader)}{@link JsonValue#asObject() .asObject()} instead - */ - @Deprecated - public static JsonObject readFrom(Reader reader) throws IOException { - return JsonValue.readFrom(reader).asObject(); - } - - /** - * Reads a JSON object from the given string. - * - * @param string - * the string that contains the JSON object - * @return the JSON object that has been read - * @throws ParseException - * if the input is not valid JSON - * @throws UnsupportedOperationException - * if the input does not contain a JSON object - * @deprecated Use {@link Json#parse(String)}{@link JsonValue#asObject() .asObject()} instead - */ - @Deprecated - public static JsonObject readFrom(String string) { - return JsonValue.readFrom(string).asObject(); - } - - /** - * Returns an unmodifiable JsonObject for the specified one. This method allows to provide - * read-only access to a JsonObject. - *

- * The returned JsonObject is backed by the given object and reflect changes that happen to it. - * Attempts to modify the returned JsonObject result in an - * UnsupportedOperationException. - *

- * - * @param object - * the JsonObject for which an unmodifiable JsonObject is to be returned - * @return an unmodifiable view of the specified JsonObject - */ - public static JsonObject unmodifiableObject(JsonObject object) { - return new JsonObject(object, true); - } - - /** - * Appends a new member to the end of this object, with the specified name and the JSON - * representation of the specified int value. - *

- * This method does not prevent duplicate names. Calling this method with a name - * that already exists in the object will append another member with the same name. In order to - * replace existing members, use the method set(name, value) instead. However, - * add is much faster than set (because it does not need to - * search for existing members). Therefore add should be preferred when constructing new - * objects. - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject add(String name, int value) { - add(name, Json.value(value)); - return this; - } - - /** - * Appends a new member to the end of this object, with the specified name and the JSON - * representation of the specified long value. - *

- * This method does not prevent duplicate names. Calling this method with a name - * that already exists in the object will append another member with the same name. In order to - * replace existing members, use the method set(name, value) instead. However, - * add is much faster than set (because it does not need to - * search for existing members). Therefore add should be preferred when constructing new - * objects. - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject add(String name, long value) { - add(name, Json.value(value)); - return this; - } - - /** - * Appends a new member to the end of this object, with the specified name and the JSON - * representation of the specified float value. - *

- * This method does not prevent duplicate names. Calling this method with a name - * that already exists in the object will append another member with the same name. In order to - * replace existing members, use the method set(name, value) instead. However, - * add is much faster than set (because it does not need to - * search for existing members). Therefore add should be preferred when constructing new - * objects. - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject add(String name, float value) { - add(name, Json.value(value)); - return this; - } - - /** - * Appends a new member to the end of this object, with the specified name and the JSON - * representation of the specified double value. - *

- * This method does not prevent duplicate names. Calling this method with a name - * that already exists in the object will append another member with the same name. In order to - * replace existing members, use the method set(name, value) instead. However, - * add is much faster than set (because it does not need to - * search for existing members). Therefore add should be preferred when constructing new - * objects. - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject add(String name, double value) { - add(name, Json.value(value)); - return this; - } - - /** - * Appends a new member to the end of this object, with the specified name and the JSON - * representation of the specified boolean value. - *

- * This method does not prevent duplicate names. Calling this method with a name - * that already exists in the object will append another member with the same name. In order to - * replace existing members, use the method set(name, value) instead. However, - * add is much faster than set (because it does not need to - * search for existing members). Therefore add should be preferred when constructing new - * objects. - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject add(String name, boolean value) { - add(name, Json.value(value)); - return this; - } - - /** - * Appends a new member to the end of this object, with the specified name and the JSON - * representation of the specified string. - *

- * This method does not prevent duplicate names. Calling this method with a name - * that already exists in the object will append another member with the same name. In order to - * replace existing members, use the method set(name, value) instead. However, - * add is much faster than set (because it does not need to - * search for existing members). Therefore add should be preferred when constructing new - * objects. - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject add(String name, String value) { - add(name, Json.value(value)); - return this; - } - - /** - * Appends a new member to the end of this object, with the specified name and the specified JSON - * value. - *

- * This method does not prevent duplicate names. Calling this method with a name - * that already exists in the object will append another member with the same name. In order to - * replace existing members, use the method set(name, value) instead. However, - * add is much faster than set (because it does not need to - * search for existing members). Therefore add should be preferred when constructing new - * objects. - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add, must not be null - * @return the object itself, to enable method chaining - */ - public JsonObject add(String name, JsonValue value) { - if (name == null) { - throw new NullPointerException("name is null"); - } - if (value == null) { - throw new NullPointerException("value is null"); - } - table.add(name, names.size()); - names.add(name); - values.add(value); - return this; - } - - /** - * Sets the value of the member with the specified name to the JSON representation of the - * specified int value. If this object does not contain a member with this name, a - * new member is added at the end of the object. If this object contains multiple members with - * this name, only the last one is changed. - *

- * This method should only be used to modify existing objects. To fill a new - * object with members, the method add(name, value) should be preferred which is much - * faster (as it does not need to search for existing members). - *

- * - * @param name - * the name of the member to replace - * @param value - * the value to set to the member - * @return the object itself, to enable method chaining - */ - public JsonObject set(String name, int value) { - set(name, Json.value(value)); - return this; - } - - /** - * Sets the value of the member with the specified name to the JSON representation of the - * specified long value. If this object does not contain a member with this name, a - * new member is added at the end of the object. If this object contains multiple members with - * this name, only the last one is changed. - *

- * This method should only be used to modify existing objects. To fill a new - * object with members, the method add(name, value) should be preferred which is much - * faster (as it does not need to search for existing members). - *

- * - * @param name - * the name of the member to replace - * @param value - * the value to set to the member - * @return the object itself, to enable method chaining - */ - public JsonObject set(String name, long value) { - set(name, Json.value(value)); - return this; - } - - /** - * Sets the value of the member with the specified name to the JSON representation of the - * specified float value. If this object does not contain a member with this name, a - * new member is added at the end of the object. If this object contains multiple members with - * this name, only the last one is changed. - *

- * This method should only be used to modify existing objects. To fill a new - * object with members, the method add(name, value) should be preferred which is much - * faster (as it does not need to search for existing members). - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject set(String name, float value) { - set(name, Json.value(value)); - return this; - } - - /** - * Sets the value of the member with the specified name to the JSON representation of the - * specified double value. If this object does not contain a member with this name, a - * new member is added at the end of the object. If this object contains multiple members with - * this name, only the last one is changed. - *

- * This method should only be used to modify existing objects. To fill a new - * object with members, the method add(name, value) should be preferred which is much - * faster (as it does not need to search for existing members). - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject set(String name, double value) { - set(name, Json.value(value)); - return this; - } - - /** - * Sets the value of the member with the specified name to the JSON representation of the - * specified boolean value. If this object does not contain a member with this name, - * a new member is added at the end of the object. If this object contains multiple members with - * this name, only the last one is changed. - *

- * This method should only be used to modify existing objects. To fill a new - * object with members, the method add(name, value) should be preferred which is much - * faster (as it does not need to search for existing members). - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject set(String name, boolean value) { - set(name, Json.value(value)); - return this; - } - - /** - * Sets the value of the member with the specified name to the JSON representation of the - * specified string. If this object does not contain a member with this name, a new member is - * added at the end of the object. If this object contains multiple members with this name, only - * the last one is changed. - *

- * This method should only be used to modify existing objects. To fill a new - * object with members, the method add(name, value) should be preferred which is much - * faster (as it does not need to search for existing members). - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add - * @return the object itself, to enable method chaining - */ - public JsonObject set(String name, String value) { - set(name, Json.value(value)); - return this; - } - - /** - * Sets the value of the member with the specified name to the specified JSON value. If this - * object does not contain a member with this name, a new member is added at the end of the - * object. If this object contains multiple members with this name, only the last one is changed. - *

- * This method should only be used to modify existing objects. To fill a new - * object with members, the method add(name, value) should be preferred which is much - * faster (as it does not need to search for existing members). - *

- * - * @param name - * the name of the member to add - * @param value - * the value of the member to add, must not be null - * @return the object itself, to enable method chaining - */ - public JsonObject set(String name, JsonValue value) { - if (name == null) { - throw new NullPointerException("name is null"); - } - if (value == null) { - throw new NullPointerException("value is null"); - } - int index = indexOf(name); - if (index != -1) { - values.set(index, value); - } else { - table.add(name, names.size()); - names.add(name); - values.add(value); - } - return this; - } - - /** - * Removes a member with the specified name from this object. If this object contains multiple - * members with the given name, only the last one is removed. If this object does not contain a - * member with the specified name, the object is not modified. - * - * @param name - * the name of the member to remove - * @return the object itself, to enable method chaining - */ - public JsonObject remove(String name) { - if (name == null) { - throw new NullPointerException("name is null"); - } - int index = indexOf(name); - if (index != -1) { - table.remove(index); - names.remove(index); - values.remove(index); - } - return this; - } - - /** - * Copies all members of the specified object into this object. When the specified object contains - * members with names that also exist in this object, the existing values in this object will be - * replaced by the corresponding values in the specified object. - * - * @param object - * the object to merge - * @return the object itself, to enable method chaining - */ - public JsonObject merge(JsonObject object) { - if (object == null) { - throw new NullPointerException("object is null"); - } - for (Member member : object) { - this.set(member.name, member.value); - } - return this; - } - - /** - * Returns the value of the member with the specified name in this object. If this object contains - * multiple members with the given name, this method will return the last one. - * - * @param name - * the name of the member whose value is to be returned - * @return the value of the last member with the specified name, or null if this - * object does not contain a member with that name - */ - public JsonValue get(String name) { - if (name == null) { - throw new NullPointerException("name is null"); - } - int index = indexOf(name); - return index != -1 ? values.get(index) : null; - } - - /** - * Returns the int value of the member with the specified name in this object. If - * this object does not contain a member with this name, the given default value is returned. If - * this object contains multiple members with the given name, the last one will be picked. If this - * member's value does not represent a JSON number or if it cannot be interpreted as Java - * int, an exception is thrown. - * - * @param name - * the name of the member whose value is to be returned - * @param defaultValue - * the value to be returned if the requested member is missing - * @return the value of the last member with the specified name, or the given default value if - * this object does not contain a member with that name - */ - public int getInt(String name, int defaultValue) { - JsonValue value = get(name); - return value != null ? value.asInt() : defaultValue; - } - - /** - * Returns the long value of the member with the specified name in this object. If - * this object does not contain a member with this name, the given default value is returned. If - * this object contains multiple members with the given name, the last one will be picked. If this - * member's value does not represent a JSON number or if it cannot be interpreted as Java - * long, an exception is thrown. - * - * @param name - * the name of the member whose value is to be returned - * @param defaultValue - * the value to be returned if the requested member is missing - * @return the value of the last member with the specified name, or the given default value if - * this object does not contain a member with that name - */ - public long getLong(String name, long defaultValue) { - JsonValue value = get(name); - return value != null ? value.asLong() : defaultValue; - } - - /** - * Returns the float value of the member with the specified name in this object. If - * this object does not contain a member with this name, the given default value is returned. If - * this object contains multiple members with the given name, the last one will be picked. If this - * member's value does not represent a JSON number or if it cannot be interpreted as Java - * float, an exception is thrown. - * - * @param name - * the name of the member whose value is to be returned - * @param defaultValue - * the value to be returned if the requested member is missing - * @return the value of the last member with the specified name, or the given default value if - * this object does not contain a member with that name - */ - public float getFloat(String name, float defaultValue) { - JsonValue value = get(name); - return value != null ? value.asFloat() : defaultValue; - } - - /** - * Returns the double value of the member with the specified name in this object. If - * this object does not contain a member with this name, the given default value is returned. If - * this object contains multiple members with the given name, the last one will be picked. If this - * member's value does not represent a JSON number or if it cannot be interpreted as Java - * double, an exception is thrown. - * - * @param name - * the name of the member whose value is to be returned - * @param defaultValue - * the value to be returned if the requested member is missing - * @return the value of the last member with the specified name, or the given default value if - * this object does not contain a member with that name - */ - public double getDouble(String name, double defaultValue) { - JsonValue value = get(name); - return value != null ? value.asDouble() : defaultValue; - } - - /** - * Returns the boolean value of the member with the specified name in this object. If - * this object does not contain a member with this name, the given default value is returned. If - * this object contains multiple members with the given name, the last one will be picked. If this - * member's value does not represent a JSON true or false value, an - * exception is thrown. - * - * @param name - * the name of the member whose value is to be returned - * @param defaultValue - * the value to be returned if the requested member is missing - * @return the value of the last member with the specified name, or the given default value if - * this object does not contain a member with that name - */ - public boolean getBoolean(String name, boolean defaultValue) { - JsonValue value = get(name); - return value != null ? value.asBoolean() : defaultValue; - } - - /** - * Returns the String value of the member with the specified name in this object. If - * this object does not contain a member with this name, the given default value is returned. If - * this object contains multiple members with the given name, the last one is picked. If this - * member's value does not represent a JSON string, an exception is thrown. - * - * @param name - * the name of the member whose value is to be returned - * @param defaultValue - * the value to be returned if the requested member is missing - * @return the value of the last member with the specified name, or the given default value if - * this object does not contain a member with that name - */ - public String getString(String name, String defaultValue) { - JsonValue value = get(name); - return value != null ? value.asString() : defaultValue; - } - - /** - * Returns the number of members (name/value pairs) in this object. - * - * @return the number of members in this object - */ - public int size() { - return names.size(); - } - - /** - * Returns true if this object contains no members. - * - * @return true if this object contains no members - */ - public boolean isEmpty() { - return names.isEmpty(); - } - - /** - * Returns a list of the names in this object in document order. The returned list is backed by - * this object and will reflect subsequent changes. It cannot be used to modify this object. - * Attempts to modify the returned list will result in an exception. - * - * @return a list of the names in this object - */ - public List names() { - return Collections.unmodifiableList(names); - } - - /** - * Returns an iterator over the members of this object in document order. The returned iterator - * cannot be used to modify this object. - * - * @return an iterator over the members of this object - */ - public Iterator iterator() { - final Iterator namesIterator = names.iterator(); - final Iterator valuesIterator = values.iterator(); - return new Iterator() { - - public boolean hasNext() { - return namesIterator.hasNext(); - } - - public Member next() { - String name = namesIterator.next(); - JsonValue value = valuesIterator.next(); - return new Member(name, value); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - - }; - } - - @Override - void write(JsonWriter writer) throws IOException { - writer.writeObjectOpen(); - Iterator namesIterator = names.iterator(); - Iterator valuesIterator = values.iterator(); - boolean first = true; - while (namesIterator.hasNext()) { - if (!first) { - writer.writeObjectSeparator(); - } - writer.writeMemberName(namesIterator.next()); - writer.writeMemberSeparator(); - valuesIterator.next().write(writer); - first = false; - } - writer.writeObjectClose(); - } - - @Override - public boolean isObject() { - return true; - } - - @Override - public JsonObject asObject() { - return this; - } - - @Override - public int hashCode() { - int result = 1; - result = 31 * result + names.hashCode(); - result = 31 * result + values.hashCode(); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - JsonObject other = (JsonObject)obj; - return names.equals(other.names) && values.equals(other.values); - } - - int indexOf(String name) { - int index = table.get(name); - if (index != -1 && name.equals(names.get(index))) { - return index; - } - return names.lastIndexOf(name); - } - - private synchronized void readObject(ObjectInputStream inputStream) - throws IOException, ClassNotFoundException - { - inputStream.defaultReadObject(); - table = new HashIndexTable(); - updateHashIndex(); - } - - private void updateHashIndex() { - int size = names.size(); - for (int i = 0; i < size; i++) { - table.add(names.get(i), i); - } - } - - /** - * Represents a member of a JSON object, a pair of a name and a value. - */ - public static class Member { - - private final String name; - private final JsonValue value; - - Member(String name, JsonValue value) { - this.name = name; - this.value = value; - } - - /** - * Returns the name of this member. - * - * @return the name of this member, never null - */ - public String getName() { - return name; - } - - /** - * Returns the value of this member. - * - * @return the value of this member, never null - */ - public JsonValue getValue() { - return value; - } - - @Override - public int hashCode() { - int result = 1; - result = 31 * result + name.hashCode(); - result = 31 * result + value.hashCode(); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Member other = (Member)obj; - return name.equals(other.name) && value.equals(other.value); - } - - } - - static class HashIndexTable { - - private final byte[] hashTable = new byte[32]; // must be a power of two - - public HashIndexTable() { - } - - public HashIndexTable(HashIndexTable original) { - System.arraycopy(original.hashTable, 0, hashTable, 0, hashTable.length); - } - - void add(String name, int index) { - int slot = hashSlotFor(name); - if (index < 0xff) { - // increment by 1, 0 stands for empty - hashTable[slot] = (byte)(index + 1); - } else { - hashTable[slot] = 0; - } - } - - void remove(int index) { - for (int i = 0; i < hashTable.length; i++) { - if (hashTable[i] == index + 1) { - hashTable[i] = 0; - } else if (hashTable[i] > index + 1) { - hashTable[i]--; - } - } - } - - int get(Object name) { - int slot = hashSlotFor(name); - // subtract 1, 0 stands for empty - return (hashTable[slot] & 0xff) - 1; - } - - private int hashSlotFor(Object element) { - return element.hashCode() & hashTable.length - 1; - } - - } - -} diff --git a/src/main/java/com/eclipsesource/json/JsonParser.java b/src/main/java/com/eclipsesource/json/JsonParser.java deleted file mode 100644 index 64afeb43e..000000000 --- a/src/main/java/com/eclipsesource/json/JsonParser.java +++ /dev/null @@ -1,400 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; - - -class JsonParser { - - private static final int MIN_BUFFER_SIZE = 10; - private static final int DEFAULT_BUFFER_SIZE = 1024; - - private final Reader reader; - private final char[] buffer; - private int bufferOffset; - private int index; - private int fill; - private int line; - private int lineOffset; - private int current; - private StringBuilder captureBuffer; - private int captureStart; - - /* - * | bufferOffset - * v - * [a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t] < input - * [l|m|n|o|p|q|r|s|t|?|?] < buffer - * ^ ^ - * | index fill - */ - - JsonParser(String string) { - this(new StringReader(string), - Math.max(MIN_BUFFER_SIZE, Math.min(DEFAULT_BUFFER_SIZE, string.length()))); - } - - JsonParser(Reader reader) { - this(reader, DEFAULT_BUFFER_SIZE); - } - - JsonParser(Reader reader, int buffersize) { - this.reader = reader; - buffer = new char[buffersize]; - line = 1; - captureStart = -1; - } - - JsonValue parse() throws IOException { - read(); - skipWhiteSpace(); - JsonValue result = readValue(); - skipWhiteSpace(); - if (!isEndOfText()) { - throw error("Unexpected character"); - } - return result; - } - - private JsonValue readValue() throws IOException { - switch (current) { - case 'n': - return readNull(); - case 't': - return readTrue(); - case 'f': - return readFalse(); - case '"': - return readString(); - case '[': - return readArray(); - case '{': - return readObject(); - case '-': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - return readNumber(); - default: - throw expected("value"); - } - } - - private JsonArray readArray() throws IOException { - read(); - JsonArray array = new JsonArray(); - skipWhiteSpace(); - if (readChar(']')) { - return array; - } - do { - skipWhiteSpace(); - array.add(readValue()); - skipWhiteSpace(); - } while (readChar(',')); - if (!readChar(']')) { - throw expected("',' or ']'"); - } - return array; - } - - private JsonObject readObject() throws IOException { - read(); - JsonObject object = new JsonObject(); - skipWhiteSpace(); - if (readChar('}')) { - return object; - } - do { - skipWhiteSpace(); - String name = readName(); - skipWhiteSpace(); - if (!readChar(':')) { - throw expected("':'"); - } - skipWhiteSpace(); - object.add(name, readValue()); - skipWhiteSpace(); - } while (readChar(',')); - if (!readChar('}')) { - throw expected("',' or '}'"); - } - return object; - } - - private String readName() throws IOException { - if (current != '"') { - throw expected("name"); - } - return readStringInternal(); - } - - private JsonValue readNull() throws IOException { - read(); - readRequiredChar('u'); - readRequiredChar('l'); - readRequiredChar('l'); - return Json.NULL; - } - - private JsonValue readTrue() throws IOException { - read(); - readRequiredChar('r'); - readRequiredChar('u'); - readRequiredChar('e'); - return Json.TRUE; - } - - private JsonValue readFalse() throws IOException { - read(); - readRequiredChar('a'); - readRequiredChar('l'); - readRequiredChar('s'); - readRequiredChar('e'); - return Json.FALSE; - } - - private void readRequiredChar(char ch) throws IOException { - if (!readChar(ch)) { - throw expected("'" + ch + "'"); - } - } - - private JsonValue readString() throws IOException { - return new JsonString(readStringInternal()); - } - - private String readStringInternal() throws IOException { - read(); - startCapture(); - while (current != '"') { - if (current == '\\') { - pauseCapture(); - readEscape(); - startCapture(); - } else if (current < 0x20) { - throw expected("valid string character"); - } else { - read(); - } - } - String string = endCapture(); - read(); - return string; - } - - private void readEscape() throws IOException { - read(); - switch (current) { - case '"': - case '/': - case '\\': - captureBuffer.append((char)current); - break; - case 'b': - captureBuffer.append('\b'); - break; - case 'f': - captureBuffer.append('\f'); - break; - case 'n': - captureBuffer.append('\n'); - break; - case 'r': - captureBuffer.append('\r'); - break; - case 't': - captureBuffer.append('\t'); - break; - case 'u': - char[] hexChars = new char[4]; - for (int i = 0; i < 4; i++) { - read(); - if (!isHexDigit()) { - throw expected("hexadecimal digit"); - } - hexChars[i] = (char)current; - } - captureBuffer.append((char)Integer.parseInt(new String(hexChars), 16)); - break; - default: - throw expected("valid escape sequence"); - } - read(); - } - - private JsonValue readNumber() throws IOException { - startCapture(); - readChar('-'); - int firstDigit = current; - if (!readDigit()) { - throw expected("digit"); - } - if (firstDigit != '0') { - while (readDigit()) { - } - } - readFraction(); - readExponent(); - return new JsonNumber(endCapture()); - } - - private boolean readFraction() throws IOException { - if (!readChar('.')) { - return false; - } - if (!readDigit()) { - throw expected("digit"); - } - while (readDigit()) { - } - return true; - } - - private boolean readExponent() throws IOException { - if (!readChar('e') && !readChar('E')) { - return false; - } - if (!readChar('+')) { - readChar('-'); - } - if (!readDigit()) { - throw expected("digit"); - } - while (readDigit()) { - } - return true; - } - - private boolean readChar(char ch) throws IOException { - if (current != ch) { - return false; - } - read(); - return true; - } - - private boolean readDigit() throws IOException { - if (!isDigit()) { - return false; - } - read(); - return true; - } - - private void skipWhiteSpace() throws IOException { - while (isWhiteSpace()) { - read(); - } - } - - private void read() throws IOException { - if (index == fill) { - if (captureStart != -1) { - captureBuffer.append(buffer, captureStart, fill - captureStart); - captureStart = 0; - } - bufferOffset += fill; - fill = reader.read(buffer, 0, buffer.length); - index = 0; - if (fill == -1) { - current = -1; - return; - } - } - if (current == '\n') { - line++; - lineOffset = bufferOffset + index; - } - current = buffer[index++]; - } - - private void startCapture() { - if (captureBuffer == null) { - captureBuffer = new StringBuilder(); - } - captureStart = index - 1; - } - - private void pauseCapture() { - int end = current == -1 ? index : index - 1; - captureBuffer.append(buffer, captureStart, end - captureStart); - captureStart = -1; - } - - private String endCapture() { - int end = current == -1 ? index : index - 1; - String captured; - if (captureBuffer.length() > 0) { - captureBuffer.append(buffer, captureStart, end - captureStart); - captured = captureBuffer.toString(); - captureBuffer.setLength(0); - } else { - captured = new String(buffer, captureStart, end - captureStart); - } - captureStart = -1; - return captured; - } - - private ParseException expected(String expected) { - if (isEndOfText()) { - return error("Unexpected end of input"); - } - return error("Expected " + expected); - } - - private ParseException error(String message) { - int absIndex = bufferOffset + index; - int column = absIndex - lineOffset; - int offset = isEndOfText() ? absIndex : absIndex - 1; - return new ParseException(message, offset, line, column - 1); - } - - private boolean isWhiteSpace() { - return current == ' ' || current == '\t' || current == '\n' || current == '\r'; - } - - private boolean isDigit() { - return current >= '0' && current <= '9'; - } - - private boolean isHexDigit() { - return current >= '0' && current <= '9' - || current >= 'a' && current <= 'f' - || current >= 'A' && current <= 'F'; - } - - private boolean isEndOfText() { - return current == -1; - } - -} diff --git a/src/main/java/com/eclipsesource/json/JsonString.java b/src/main/java/com/eclipsesource/json/JsonString.java deleted file mode 100644 index bd76bfc7e..000000000 --- a/src/main/java/com/eclipsesource/json/JsonString.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; - - -@SuppressWarnings("serial") // use default serial UID -class JsonString extends JsonValue { - - private final String string; - - JsonString(String string) { - if (string == null) { - throw new NullPointerException("string is null"); - } - this.string = string; - } - - @Override - void write(JsonWriter writer) throws IOException { - writer.writeString(string); - } - - @Override - public boolean isString() { - return true; - } - - @Override - public String asString() { - return string; - } - - @Override - public int hashCode() { - return string.hashCode(); - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object == null) { - return false; - } - if (getClass() != object.getClass()) { - return false; - } - JsonString other = (JsonString)object; - return string.equals(other.string); - } - -} diff --git a/src/main/java/com/eclipsesource/json/JsonValue.java b/src/main/java/com/eclipsesource/json/JsonValue.java deleted file mode 100644 index df4243135..000000000 --- a/src/main/java/com/eclipsesource/json/JsonValue.java +++ /dev/null @@ -1,500 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; -import java.io.Reader; -import java.io.Serializable; -import java.io.StringWriter; -import java.io.Writer; - - -/** - * Represents a JSON value. This can be a JSON object, an array, - * a number, a string, or one of the literals - * true, false, and null. - *

- * The literals true, false, and null are - * represented by the constants {@link #TRUE}, {@link #FALSE}, and {@link #NULL}. - *

- *

- * JSON objects and arrays are represented by the subtypes - * {@link JsonObject} and {@link JsonArray}. Instances of these types can be created using the - * public constructors of these classes. - *

- *

- * Instances that represent JSON numbers, strings and - * boolean values can be created using the static factory methods - * {@link #valueOf(String)}, {@link #valueOf(long)}, {@link #valueOf(double)}, etc. - *

- *

- * In order to find out whether an instance of this class is of a certain type, the methods - * {@link #isObject()}, {@link #isArray()}, {@link #isString()}, {@link #isNumber()} etc. can be - * used. - *

- *

- * If the type of a JSON value is known, the methods {@link #asObject()}, {@link #asArray()}, - * {@link #asString()}, {@link #asInt()}, etc. can be used to get this value directly in the - * appropriate target type. - *

- *

- * This class is not supposed to be extended by clients. - *

- */ -@SuppressWarnings("serial") // use default serial UID -public abstract class JsonValue implements Serializable { - - /** - * Represents the JSON literal true. - * @deprecated Use Json.TRUE instead - */ - @Deprecated - public static final JsonValue TRUE = Json.TRUE; - - /** - * Represents the JSON literal false. - * @deprecated Use Json.FALSE instead - */ - @Deprecated - public static final JsonValue FALSE = Json.FALSE; - - /** - * Represents the JSON literal null. - * @deprecated Use Json.NULL instead - */ - @Deprecated - public static final JsonValue NULL = Json.NULL; - - JsonValue() { - // prevent subclasses outside of this package - } - - /** - * Reads a JSON value from the given reader. - *

- * Characters are read in chunks and buffered internally, therefore wrapping an existing reader in - * an additional BufferedReader does not improve reading - * performance. - *

- * - * @param reader - * the reader to read the JSON value from - * @return the JSON value that has been read - * @throws IOException - * if an I/O error occurs in the reader - * @throws ParseException - * if the input is not valid JSON - * @deprecated Use {@link Json#parse(Reader)} instead - */ - @Deprecated - public static JsonValue readFrom(Reader reader) throws IOException { - return new JsonParser(reader).parse(); - } - - /** - * Reads a JSON value from the given string. - * - * @param text - * the string that contains the JSON value - * @return the JSON value that has been read - * @throws ParseException - * if the input is not valid JSON - * @deprecated Use {@link Json#parse(String)} instead - */ - @Deprecated - public static JsonValue readFrom(String text) { - try { - return new JsonParser(text).parse(); - } catch (IOException exception) { - // JsonParser does not throw IOException for String - throw new RuntimeException(exception); - } - } - - /** - * Returns a JsonValue instance that represents the given int value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - * @deprecated Use Json.value() instead - */ - @Deprecated - public static JsonValue valueOf(int value) { - return Json.value(value); - } - - /** - * Returns a JsonValue instance that represents the given long value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - * @deprecated Use Json.value() instead - */ - @Deprecated - public static JsonValue valueOf(long value) { - return Json.value(value); - } - - /** - * Returns a JsonValue instance that represents the given float value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - * @deprecated Use Json.value() instead - */ - @Deprecated - public static JsonValue valueOf(float value) { - return Json.value(value); - } - - /** - * Returns a JsonValue instance that represents the given double value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - * @deprecated Use Json.value() instead - */ - @Deprecated - public static JsonValue valueOf(double value) { - return Json.value(value); - } - - /** - * Returns a JsonValue instance that represents the given string. - * - * @param string - * the string to get a JSON representation for - * @return a JSON value that represents the given string - * @deprecated Use Json.value() instead - */ - @Deprecated - public static JsonValue valueOf(String string) { - return Json.value(string); - } - - /** - * Returns a JsonValue instance that represents the given boolean value. - * - * @param value - * the value to get a JSON representation for - * @return a JSON value that represents the given value - * @deprecated Use Json.value() instead - */ - @Deprecated - public static JsonValue valueOf(boolean value) { - return Json.value(value); - } - - /** - * Detects whether this value represents a JSON object. If this is the case, this value is an - * instance of {@link JsonObject}. - * - * @return true if this value is an instance of JsonObject - */ - public boolean isObject() { - return false; - } - - /** - * Detects whether this value represents a JSON array. If this is the case, this value is an - * instance of {@link JsonArray}. - * - * @return true if this value is an instance of JsonArray - */ - public boolean isArray() { - return false; - } - - /** - * Detects whether this value represents a JSON number. - * - * @return true if this value represents a JSON number - */ - public boolean isNumber() { - return false; - } - - /** - * Detects whether this value represents a JSON string. - * - * @return true if this value represents a JSON string - */ - public boolean isString() { - return false; - } - - /** - * Detects whether this value represents a boolean value. - * - * @return true if this value represents either the JSON literal true or - * false - */ - public boolean isBoolean() { - return false; - } - - /** - * Detects whether this value represents the JSON literal true. - * - * @return true if this value represents the JSON literal true - */ - public boolean isTrue() { - return false; - } - - /** - * Detects whether this value represents the JSON literal false. - * - * @return true if this value represents the JSON literal false - */ - public boolean isFalse() { - return false; - } - - /** - * Detects whether this value represents the JSON literal null. - * - * @return true if this value represents the JSON literal null - */ - public boolean isNull() { - return false; - } - - /** - * Returns this JSON value as {@link JsonObject}, assuming that this value represents a JSON - * object. If this is not the case, an exception is thrown. - * - * @return a JSONObject for this value - * @throws UnsupportedOperationException - * if this value is not a JSON object - */ - public JsonObject asObject() { - throw new UnsupportedOperationException("Not an object: " + toString()); - } - - /** - * Returns this JSON value as {@link JsonArray}, assuming that this value represents a JSON array. - * If this is not the case, an exception is thrown. - * - * @return a JSONArray for this value - * @throws UnsupportedOperationException - * if this value is not a JSON array - */ - public JsonArray asArray() { - throw new UnsupportedOperationException("Not an array: " + toString()); - } - - /** - * Returns this JSON value as an int value, assuming that this value represents a - * JSON number that can be interpreted as Java int. If this is not the case, an - * exception is thrown. - *

- * To be interpreted as Java int, the JSON number must neither contain an exponent - * nor a fraction part. Moreover, the number must be in the Integer range. - *

- * - * @return this value as int - * @throws UnsupportedOperationException - * if this value is not a JSON number - * @throws NumberFormatException - * if this JSON number can not be interpreted as int value - */ - public int asInt() { - throw new UnsupportedOperationException("Not a number: " + toString()); - } - - /** - * Returns this JSON value as a long value, assuming that this value represents a - * JSON number that can be interpreted as Java long. If this is not the case, an - * exception is thrown. - *

- * To be interpreted as Java long, the JSON number must neither contain an exponent - * nor a fraction part. Moreover, the number must be in the Long range. - *

- * - * @return this value as long - * @throws UnsupportedOperationException - * if this value is not a JSON number - * @throws NumberFormatException - * if this JSON number can not be interpreted as long value - */ - public long asLong() { - throw new UnsupportedOperationException("Not a number: " + toString()); - } - - /** - * Returns this JSON value as a float value, assuming that this value represents a - * JSON number. If this is not the case, an exception is thrown. - *

- * If the JSON number is out of the Float range, {@link Float#POSITIVE_INFINITY} or - * {@link Float#NEGATIVE_INFINITY} is returned. - *

- * - * @return this value as float - * @throws UnsupportedOperationException - * if this value is not a JSON number - */ - public float asFloat() { - throw new UnsupportedOperationException("Not a number: " + toString()); - } - - /** - * Returns this JSON value as a double value, assuming that this value represents a - * JSON number. If this is not the case, an exception is thrown. - *

- * If the JSON number is out of the Double range, {@link Double#POSITIVE_INFINITY} or - * {@link Double#NEGATIVE_INFINITY} is returned. - *

- * - * @return this value as double - * @throws UnsupportedOperationException - * if this value is not a JSON number - */ - public double asDouble() { - throw new UnsupportedOperationException("Not a number: " + toString()); - } - - /** - * Returns this JSON value as String, assuming that this value represents a JSON string. If this - * is not the case, an exception is thrown. - * - * @return the string represented by this value - * @throws UnsupportedOperationException - * if this value is not a JSON string - */ - public String asString() { - throw new UnsupportedOperationException("Not a string: " + toString()); - } - - /** - * Returns this JSON value as a boolean value, assuming that this value is either - * true or false. If this is not the case, an exception is thrown. - * - * @return this value as boolean - * @throws UnsupportedOperationException - * if this value is neither true or false - */ - public boolean asBoolean() { - throw new UnsupportedOperationException("Not a boolean: " + toString()); - } - - /** - * Writes the JSON representation of this value to the given writer in its minimal form, without - * any additional whitespace. - *

- * Writing performance can be improved by using a {@link java.io.BufferedWriter BufferedWriter}. - *

- * - * @param writer - * the writer to write this value to - * @throws IOException - * if an I/O error occurs in the writer - */ - public void writeTo(Writer writer) throws IOException { - writeTo(writer, WriterConfig.MINIMAL); - } - - /** - * Writes the JSON representation of this value to the given writer using the given formatting. - *

- * Writing performance can be improved by using a {@link java.io.BufferedWriter BufferedWriter}. - *

- * - * @param writer - * the writer to write this value to - * @param config - * a configuration that controls the formatting or null for the minimal form - * @throws IOException - * if an I/O error occurs in the writer - */ - public void writeTo(Writer writer, WriterConfig config) throws IOException { - if (writer == null) { - throw new NullPointerException("writer is null"); - } - if (config == null) { - throw new NullPointerException("config is null"); - } - WritingBuffer buffer = new WritingBuffer(writer, 128); - write(config.createWriter(buffer)); - buffer.flush(); - } - - /** - * Returns the JSON string for this value in its minimal form, without any additional whitespace. - * The result is guaranteed to be a valid input for the method {@link #readFrom(String)} and to - * create a value that is equal to this object. - * - * @return a JSON string that represents this value - */ - @Override - public String toString() { - return toString(WriterConfig.MINIMAL); - } - - /** - * Returns the JSON string for this value using the given formatting. - * - * @param config - * a configuration that controls the formatting or null for the minimal form - * @return a JSON string that represents this value - */ - public String toString(WriterConfig config) { - StringWriter writer = new StringWriter(); - try { - writeTo(writer, config); - } catch (IOException exception) { - // StringWriter does not throw IOExceptions - throw new RuntimeException(exception); - } - return writer.toString(); - } - - /** - * Indicates whether some other object is "equal to" this one according to the contract specified - * in {@link Object#equals(Object)}. - *

- * Two JsonValues are considered equal if and only if they represent the same JSON text. As a - * consequence, two given JsonObjects may be different even though they contain the same set of - * names with the same values, but in a different order. - *

- * - * @param object - * the reference object with which to compare - * @return true if this object is the same as the object argument; false otherwise - */ - @Override - public boolean equals(Object object) { - return super.equals(object); - } - - @Override - public int hashCode() { - return super.hashCode(); - } - - abstract void write(JsonWriter writer) throws IOException; - -} diff --git a/src/main/java/com/eclipsesource/json/JsonWriter.java b/src/main/java/com/eclipsesource/json/JsonWriter.java deleted file mode 100644 index 6d06e1a3d..000000000 --- a/src/main/java/com/eclipsesource/json/JsonWriter.java +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; -import java.io.Writer; - - -class JsonWriter { - - private static final int CONTROL_CHARACTERS_END = 0x001f; - - private static final char[] QUOT_CHARS = {'\\', '"'}; - private static final char[] BS_CHARS = {'\\', '\\'}; - private static final char[] LF_CHARS = {'\\', 'n'}; - private static final char[] CR_CHARS = {'\\', 'r'}; - private static final char[] TAB_CHARS = {'\\', 't'}; - // In JavaScript, U+2028 and U+2029 characters count as line endings and must be encoded. - // http://stackoverflow.com/questions/2965293/javascript-parse-error-on-u2028-unicode-character - private static final char[] UNICODE_2028_CHARS = {'\\', 'u', '2', '0', '2', '8'}; - private static final char[] UNICODE_2029_CHARS = {'\\', 'u', '2', '0', '2', '9'}; - private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f'}; - - protected final Writer writer; - - JsonWriter(Writer writer) { - this.writer = writer; - } - - protected void writeLiteral(String value) throws IOException { - writer.write(value); - } - - protected void writeNumber(String string) throws IOException { - writer.write(string); - } - - protected void writeString(String string) throws IOException { - writer.write('"'); - writeJsonString(string); - writer.write('"'); - } - - protected void writeArrayOpen() throws IOException { - writer.write('['); - } - - protected void writeArrayClose() throws IOException { - writer.write(']'); - } - - protected void writeArraySeparator() throws IOException { - writer.write(','); - } - - protected void writeObjectOpen() throws IOException { - writer.write('{'); - } - - protected void writeObjectClose() throws IOException { - writer.write('}'); - } - - protected void writeMemberName(String name) throws IOException { - writer.write('"'); - writeJsonString(name); - writer.write('"'); - } - - protected void writeMemberSeparator() throws IOException { - writer.write(':'); - } - - protected void writeObjectSeparator() throws IOException { - writer.write(','); - } - - protected void writeJsonString(String string) throws IOException { - int length = string.length(); - int start = 0; - for (int index = 0; index < length; index++) { - char[] replacement = getReplacementChars(string.charAt(index)); - if (replacement != null) { - writer.write(string, start, index - start); - writer.write(replacement); - start = index + 1; - } - } - writer.write(string, start, length - start); - } - - private static char[] getReplacementChars(char ch) { - if (ch > '\\') { - if (ch < '\u2028' || ch > '\u2029') { - // The lower range contains 'a' .. 'z'. Only 2 checks required. - return null; - } - return ch == '\u2028' ? UNICODE_2028_CHARS : UNICODE_2029_CHARS; - } - if (ch == '\\') { - return BS_CHARS; - } - if (ch > '"') { - // This range contains '0' .. '9' and 'A' .. 'Z'. Need 3 checks to get here. - return null; - } - if (ch == '"') { - return QUOT_CHARS; - } - if (ch > CONTROL_CHARACTERS_END) { - return null; - } - if (ch == '\n') { - return LF_CHARS; - } - if (ch == '\r') { - return CR_CHARS; - } - if (ch == '\t') { - return TAB_CHARS; - } - return new char[] {'\\', 'u', '0', '0', HEX_DIGITS[ch >> 4 & 0x000f], HEX_DIGITS[ch & 0x000f]}; - } - -} diff --git a/src/main/java/com/eclipsesource/json/ParseException.java b/src/main/java/com/eclipsesource/json/ParseException.java deleted file mode 100644 index 40aae2f71..000000000 --- a/src/main/java/com/eclipsesource/json/ParseException.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -/** - * An unchecked exception to indicate that an input does not qualify as valid JSON. - */ -@SuppressWarnings("serial") // use default serial UID -public class ParseException extends RuntimeException { - - private final int offset; - private final int line; - private final int column; - - ParseException(String message, int offset, int line, int column) { - super(message + " at " + line + ":" + column); - this.offset = offset; - this.line = line; - this.column = column; - } - - /** - * Returns the absolute index of the character at which the error occurred. The index of the first - * character of a document is 0. - * - * @return the character offset at which the error occurred, will be >= 0 - */ - public int getOffset() { - return offset; - } - - /** - * Returns the number of the line in which the error occurred. The first line counts as 1. - * - * @return the line in which the error occurred, will be >= 1 - */ - public int getLine() { - return line; - } - - /** - * Returns the index of the character at which the error occurred, relative to the line. The index - * of the first character of a line is 0. - * - * @return the column in which the error occurred, will be >= 0 - */ - public int getColumn() { - return column; - } - -} diff --git a/src/main/java/com/eclipsesource/json/PrettyPrint.java b/src/main/java/com/eclipsesource/json/PrettyPrint.java deleted file mode 100644 index 9e60e890f..000000000 --- a/src/main/java/com/eclipsesource/json/PrettyPrint.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; -import java.io.Writer; -import java.util.Arrays; - - -/** - * Enables human readable JSON output by inserting whitespace between values.after commas and - * colons. Example: - * - *
- * jsonValue.writeTo(writer, PrettyPrint.singleLine());
- * 
- */ -public class PrettyPrint extends WriterConfig { - - private final char[] indentChars; - - protected PrettyPrint(char[] indentChars) { - this.indentChars = indentChars; - } - - /** - * Print every value on a separate line. Use tabs (\t) for indentation. - * - * @return A PrettyPrint instance for wrapped mode with tab indentation - */ - public static PrettyPrint singleLine() { - return new PrettyPrint(null); - } - - /** - * Print every value on a separate line. Use the given number of spaces for indentation. - * - * @param number - * the number of spaces to use - * @return A PrettyPrint instance for wrapped mode with spaces indentation - */ - public static PrettyPrint indentWithSpaces(int number) { - if (number < 0) { - throw new IllegalArgumentException("number is negative"); - } - char[] chars = new char[number]; - Arrays.fill(chars, ' '); - return new PrettyPrint(chars); - } - - /** - * Do not break lines, but still insert whitespace between values. - * - * @return A PrettyPrint instance for single-line mode - */ - public static PrettyPrint indentWithTabs() { - return new PrettyPrint(new char[] {'\t'}); - } - - @Override - protected JsonWriter createWriter(Writer writer) { - return new PrettyPrintWriter(writer, indentChars); - } - - private static class PrettyPrintWriter extends JsonWriter { - - private final char[] indentChars; - private int indent; - - private PrettyPrintWriter(Writer writer, char[] indentChars) { - super(writer); - this.indentChars = indentChars; - } - - @Override - protected void writeArrayOpen() throws IOException { - indent++; - writer.write('['); - writeNewLine(); - } - - @Override - protected void writeArrayClose() throws IOException { - indent--; - writeNewLine(); - writer.write(']'); - } - - @Override - protected void writeArraySeparator() throws IOException { - writer.write(','); - if (!writeNewLine()) { - writer.write(' '); - } - } - - @Override - protected void writeObjectOpen() throws IOException { - indent++; - writer.write('{'); - writeNewLine(); - } - - @Override - protected void writeObjectClose() throws IOException { - indent--; - writeNewLine(); - writer.write('}'); - } - - @Override - protected void writeMemberSeparator() throws IOException { - writer.write(':'); - writer.write(' '); - } - - @Override - protected void writeObjectSeparator() throws IOException { - writer.write(','); - if (!writeNewLine()) { - writer.write(' '); - } - } - - private boolean writeNewLine() throws IOException { - if (indentChars == null) { - return false; - } - writer.write('\n'); - for (int i = 0; i < indent; i++) { - writer.write(indentChars); - } - return true; - } - - } - -} diff --git a/src/main/java/com/eclipsesource/json/WriterConfig.java b/src/main/java/com/eclipsesource/json/WriterConfig.java deleted file mode 100644 index 14c762922..000000000 --- a/src/main/java/com/eclipsesource/json/WriterConfig.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.Writer; - - -/** - * Controls the formatting of the JSON output. Use one of the available constants. - */ -public abstract class WriterConfig { - - /** - * Write JSON in its minimal form, without any additional whitespace. This is the default. - */ - public static WriterConfig MINIMAL = new WriterConfig() { - @Override - JsonWriter createWriter(Writer writer) { - return new JsonWriter(writer); - } - }; - - /** - * Write JSON in pretty-print, with each value on a separate line and an indentation of two - * spaces. - */ - public static WriterConfig PRETTY_PRINT = PrettyPrint.indentWithSpaces(2); - - abstract JsonWriter createWriter(Writer writer); - -} diff --git a/src/main/java/com/eclipsesource/json/WritingBuffer.java b/src/main/java/com/eclipsesource/json/WritingBuffer.java deleted file mode 100644 index 0132c3afc..000000000 --- a/src/main/java/com/eclipsesource/json/WritingBuffer.java +++ /dev/null @@ -1,99 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 EclipseSource. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ******************************************************************************/ -package com.eclipsesource.json; - -import java.io.IOException; -import java.io.Writer; - - -/** - * A lightweight writing buffer to reduce the amount of write operations to be performed on the - * underlying writer. This implementation is not thread-safe. It deliberately deviates from the - * contract of Writer. In particular, it does not flush or close the wrapped writer nor does it - * ensure that the wrapped writer is open. - */ -class WritingBuffer extends Writer { - - private final Writer writer; - private final char[] buffer; - private int fill = 0; - - WritingBuffer(Writer writer) { - this(writer, 16); - } - - WritingBuffer(Writer writer, int bufferSize) { - this.writer = writer; - buffer = new char[bufferSize]; - } - - @Override - public void write(int c) throws IOException { - if (fill > buffer.length - 1) { - flush(); - } - buffer[fill++] = (char)c; - } - - @Override - public void write(char[] cbuf, int off, int len) throws IOException { - if (fill > buffer.length - len) { - flush(); - if (len > buffer.length) { - writer.write(cbuf, off, len); - return; - } - } - System.arraycopy(cbuf, off, buffer, fill, len); - fill += len; - } - - @Override - public void write(String str, int off, int len) throws IOException { - if (fill > buffer.length - len) { - flush(); - if (len > buffer.length) { - writer.write(str, off, len); - return; - } - } - str.getChars(off, off + len, buffer, fill); - fill += len; - } - - /** - * Flushes the internal buffer but does not flush the wrapped writer. - */ - @Override - public void flush() throws IOException { - writer.write(buffer, 0, fill); - fill = 0; - } - - /** - * Does not close or flush the wrapped writer. - */ - @Override - public void close() throws IOException { - } - -} diff --git a/src/main/java/com/jhe/hexed/JHexEditor.java b/src/main/java/com/jhe/hexed/JHexEditor.java deleted file mode 100644 index af2cc4bb7..000000000 --- a/src/main/java/com/jhe/hexed/JHexEditor.java +++ /dev/null @@ -1,257 +0,0 @@ -package com.jhe.hexed; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; - -/** - * Created by IntelliJ IDEA. User: laullon Date: 08-abr-2003 Time: 13:21:09 - */ -public class JHexEditor extends JPanel implements FocusListener, - AdjustmentListener, MouseWheelListener { - private static final long serialVersionUID = 2289328616534802372L; - byte[] buff; - public int cursor; - protected static Font font = new Font("Monospaced", 0, 12); - protected int border = 2; - public boolean DEBUG = false; - private JPanel panel; - private JScrollBar sb; - private int inicio = 0; - private int lineas = 10; - - public JHexEditor(byte[] buff) { - super(); - this.buff = buff; - - this.addMouseWheelListener(this); - - sb = new JScrollBar(JScrollBar.VERTICAL); - sb.addAdjustmentListener(this); - sb.setMinimum(0); - sb.setMaximum(buff.length / getLineas()); - - JPanel p1, p2, p3; - // centro - p1 = new JPanel(new BorderLayout(1, 1)); - p1.add(new JHexEditorHEX(this), BorderLayout.CENTER); - p1.add(new Columnas(), BorderLayout.NORTH); - - // izq. - p2 = new JPanel(new BorderLayout(1, 1)); - p2.add(new Filas(), BorderLayout.CENTER); - p2.add(new Caja(), BorderLayout.NORTH); - - // der - p3 = new JPanel(new BorderLayout(1, 1)); - p3.add(sb, BorderLayout.EAST); - p3.add(new JHexEditorASCII(this), BorderLayout.CENTER); - p3.add(new Caja(), BorderLayout.NORTH); - - panel = new JPanel(); - panel.setLayout(new BorderLayout(1, 1)); - panel.add(p1, BorderLayout.CENTER); - panel.add(p2, BorderLayout.WEST); - panel.add(p3, BorderLayout.EAST); - - this.setLayout(new BorderLayout(1, 1)); - this.add(panel, BorderLayout.CENTER); - } - - public void paint(Graphics g) { - FontMetrics fn = getFontMetrics(font); - Rectangle rec = this.getBounds(); - lineas = (rec.height / fn.getHeight()) - 1; - int n = (buff.length / 16) - 1; - if (lineas > n) { - lineas = n; - inicio = 0; - } - - sb.setValues(getInicio(), +getLineas(), 0, buff.length / 16); - sb.setValueIsAdjusting(true); - super.paint(g); - } - - protected void actualizaCursor() { - int n = (cursor / 16); - - System.out.print("- " + inicio + "<" + n + "<" + (lineas + inicio) - + "(" + lineas + ")"); - - if (n < inicio) - inicio = n; - else if (n >= inicio + lineas) - inicio = n - (lineas - 1); - - System.out.println(" - " + inicio + "<" + n + "<" + (lineas + inicio) - + "(" + lineas + ")"); - - repaint(); - } - - protected int getInicio() { - return inicio; - } - - protected int getLineas() { - return lineas; - } - - protected void fondo(Graphics g, int x, int y, int s) { - FontMetrics fn = getFontMetrics(font); - g.fillRect(((fn.stringWidth(" ") + 1) * x) + border, - (fn.getHeight() * y) + border, ((fn.stringWidth(" ") + 1) * s), - fn.getHeight() + 1); - } - - protected void cuadro(Graphics g, int x, int y, int s) { - FontMetrics fn = getFontMetrics(font); - g.drawRect(((fn.stringWidth(" ") + 1) * x) + border, - (fn.getHeight() * y) + border, ((fn.stringWidth(" ") + 1) * s), - fn.getHeight() + 1); - } - - protected void printString(Graphics g, String s, int x, int y) { - FontMetrics fn = getFontMetrics(font); - g.drawString(s, ((fn.stringWidth(" ") + 1) * x) + border, - ((fn.getHeight() * (y + 1)) - fn.getMaxDescent()) + border); - } - - public void focusGained(FocusEvent e) { - this.repaint(); - } - - public void focusLost(FocusEvent e) { - this.repaint(); - } - - public void adjustmentValueChanged(AdjustmentEvent e) { - inicio = e.getValue(); - if (inicio < 0) - inicio = 0; - repaint(); - } - - public void mouseWheelMoved(MouseWheelEvent e) { - inicio += (e.getUnitsToScroll()); - if ((inicio + lineas) >= buff.length / 16) - inicio = (buff.length / 16) - lineas; - if (inicio < 0) - inicio = 0; - repaint(); - } - - public void keyPressed(KeyEvent e) { - /* - * switch(e.getKeyCode()) { case 33: // rep if(cursor>=(16*lineas)) - * cursor-=(16*lineas); actualizaCursor(); break; case 34: // fin - * if(cursor<(buff.length-(16*lineas))) cursor+=(16*lineas); - * actualizaCursor(); break; case 35: // fin cursor=buff.length-1; - * actualizaCursor(); break; case 36: // ini cursor=0; - * actualizaCursor(); break; case 37: // <-- if(cursor!=0) cursor--; - * actualizaCursor(); break; case 38: // <-- if(cursor>15) cursor-=16; - * actualizaCursor(); break; case 39: // --> if(cursor!=(buff.length-1)) - * cursor++; actualizaCursor(); break; case 40: // --> - * if(cursor<(buff.length-16)) cursor+=16; actualizaCursor(); break; } - */ - } - - private class Columnas extends JPanel { - private static final long serialVersionUID = -1734199617526339842L; - - public Columnas() { - this.setLayout(new BorderLayout(1, 1)); - } - - public Dimension getPreferredSize() { - return getMinimumSize(); - } - - public Dimension getMinimumSize() { - Dimension d = new Dimension(); - FontMetrics fn = getFontMetrics(font); - int h = fn.getHeight(); - int nl = 1; - d.setSize(((fn.stringWidth(" ") + 1) * +((16 * 3) - 1)) - + (border * 2) + 1, h * nl + (border * 2) + 1); - return d; - } - - public void paint(Graphics g) { - Dimension d = getMinimumSize(); - g.setColor(Color.white); - g.fillRect(0, 0, d.width, d.height); - g.setColor(Color.black); - g.setFont(font); - - for (int n = 0; n < 16; n++) { - if (n == (cursor % 16)) - cuadro(g, n * 3, 0, 2); - String s = "00" + Integer.toHexString(n); - s = s.substring(s.length() - 2); - printString(g, s, n * 3, 0); - } - } - } - - private class Caja extends JPanel { - private static final long serialVersionUID = -6124062720565016834L; - - public Dimension getPreferredSize() { - return getMinimumSize(); - } - - public Dimension getMinimumSize() { - Dimension d = new Dimension(); - FontMetrics fn = getFontMetrics(font); - int h = fn.getHeight(); - d.setSize((fn.stringWidth(" ") + 1) + (border * 2) + 1, h - + (border * 2) + 1); - return d; - } - - } - - private class Filas extends JPanel { - private static final long serialVersionUID = 8797347523486018051L; - - public Filas() { - this.setLayout(new BorderLayout(1, 1)); - } - - public Dimension getPreferredSize() { - return getMinimumSize(); - } - - public Dimension getMinimumSize() { - Dimension d = new Dimension(); - FontMetrics fn = getFontMetrics(font); - int h = fn.getHeight(); - int nl = getLineas(); - d.setSize((fn.stringWidth(" ") + 1) * (8) + (border * 2) + 1, h - * nl + (border * 2) + 1); - return d; - } - - public void paint(Graphics g) { - Dimension d = getMinimumSize(); - g.setColor(Color.white); - g.fillRect(0, 0, d.width, d.height); - g.setColor(Color.black); - g.setFont(font); - - int ini = getInicio(); - int fin = ini + getLineas(); - int y = 0; - for (int n = ini; n < fin; n++) { - if (n == (cursor / 16)) - cuadro(g, 0, y, 8); - String s = "0000000000000" + Integer.toHexString(n); - s = s.substring(s.length() - 8); - printString(g, s, 0, y++); - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/com/jhe/hexed/JHexEditorASCII.java b/src/main/java/com/jhe/hexed/JHexEditorASCII.java deleted file mode 100644 index 0631f84db..000000000 --- a/src/main/java/com/jhe/hexed/JHexEditorASCII.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.jhe.hexed; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; - -/** - * Created by IntelliJ IDEA. User: laullon Date: 09-abr-2003 Time: 12:47:18 - */ -public class JHexEditorASCII extends JComponent implements MouseListener, - KeyListener { - private static final long serialVersionUID = 5505374841731053461L; - private JHexEditor he; - - public JHexEditorASCII(JHexEditor he) { - this.he = he; - addMouseListener(this); - addKeyListener(this); - addFocusListener(he); - } - - public Dimension getPreferredSize() { - debug("getPreferredSize()"); - return getMinimumSize(); - } - - public Dimension getMinimumSize() { - debug("getMinimumSize()"); - - Dimension d = new Dimension(); - FontMetrics fn = getFontMetrics(JHexEditor.font); - int h = fn.getHeight(); - int nl = he.getLineas(); - d.setSize((fn.stringWidth(" ") + 1) * (16) + (he.border * 2) + 1, h - * nl + (he.border * 2) + 1); - return d; - } - - public void paint(Graphics g) { - debug("paint(" + g + ")"); - debug("cursor=" + he.cursor + " buff.length=" + he.buff.length); - Dimension d = getMinimumSize(); - g.setColor(Color.white); - g.fillRect(0, 0, d.width, d.height); - g.setColor(Color.black); - - g.setFont(JHexEditor.font); - - // datos ascii - int ini = he.getInicio() * 16; - int fin = ini + (he.getLineas() * 16); - if (fin > he.buff.length) - fin = he.buff.length; - - int x = 0; - int y = 0; - for (int n = ini; n < fin; n++) { - if (n == he.cursor) { - g.setColor(Color.blue); - if (hasFocus()) - he.fondo(g, x, y, 1); - else - he.cuadro(g, x, y, 1); - if (hasFocus()) - g.setColor(Color.white); - else - g.setColor(Color.black); - } else { - g.setColor(Color.black); - } - - String s = String.valueOf(he.buff[n]); - if ((he.buff[n] < 20) || (he.buff[n] > 126)) - s = "" + (char) 16; - he.printString(g, s, (x++), y); - if (x == 16) { - x = 0; - y++; - } - } - - } - - private void debug(String s) { - if (he.DEBUG) - System.out.println("JHexEditorASCII ==> " + s); - } - - // calcular la posicion del raton - public int calcularPosicionRaton(int x, int y) { - FontMetrics fn = getFontMetrics(JHexEditor.font); - x = x / (fn.stringWidth(" ") + 1); - y = y / fn.getHeight(); - debug("x=" + x + " ,y=" + y); - return x + ((y + he.getInicio()) * 16); - } - - // mouselistener - public void mouseClicked(MouseEvent e) { - debug("mouseClicked(" + e + ")"); - he.cursor = calcularPosicionRaton(e.getX(), e.getY()); - this.requestFocus(); - he.repaint(); - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseReleased(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - // KeyListener - public void keyTyped(KeyEvent e) { - /* - * debug("keyTyped("+e+")"); - * - * he.buff[he.cursor]=(byte)e.getKeyChar(); - * - * if(he.cursor!=(he.buff.length-1)) he.cursor++; he.repaint(); - */ - } - - public void keyPressed(KeyEvent e) { - debug("keyPressed(" + e + ")"); - he.keyPressed(e); - } - - public void keyReleased(KeyEvent e) { - debug("keyReleased(" + e + ")"); - } - - public boolean isFocusTraversable() { - return true; - } -} \ No newline at end of file diff --git a/src/main/java/com/jhe/hexed/JHexEditorHEX.java b/src/main/java/com/jhe/hexed/JHexEditorHEX.java deleted file mode 100644 index 23666cda7..000000000 --- a/src/main/java/com/jhe/hexed/JHexEditorHEX.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.jhe.hexed; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; - -/** - * Created by IntelliJ IDEA. User: laullon Date: 09-abr-2003 Time: 12:47:32 - */ -public class JHexEditorHEX extends JComponent implements MouseListener, - KeyListener { - private static final long serialVersionUID = 1481995655372014571L; - private JHexEditor he; - private int cursor = 0; - - public JHexEditorHEX(JHexEditor he) { - this.he = he; - addMouseListener(this); - addKeyListener(this); - addFocusListener(he); - } - - /* - * public Dimension getPreferredSize() { debug("getPreferredSize()"); return - * getMinimumSize(); } - */ - - public Dimension getMaximumSize() { - debug("getMaximumSize()"); - return getMinimumSize(); - } - - /* - * public Dimension getMinimumSize() { debug("getMinimumSize()"); - * - * Dimension d=new Dimension(); FontMetrics fn=getFontMetrics(he.font); int - * h=fn.getHeight(); int nl=he.getLineas(); - * d.setSize(((fn.stringWidth(" ")+1 - * )*+((16*3)-1))+(he.border*2)+1,h*nl+(he.border*2)+1); return d; } - */ - - public void paint(Graphics g) { - debug("paint(" + g + ")"); - debug("cursor=" + he.cursor + " buff.length=" + he.buff.length); - Dimension d = getMinimumSize(); - g.setColor(Color.white); - g.fillRect(0, 0, d.width, d.height); - g.setColor(Color.black); - - g.setFont(JHexEditor.font); - - int ini = he.getInicio() * 16; - int fin = ini + (he.getLineas() * 16); - if (fin > he.buff.length) - fin = he.buff.length; - - // datos hex - int x = 0; - int y = 0; - for (int n = ini; n < fin; n++) { - if (n == he.cursor) { - if (hasFocus()) { - g.setColor(Color.black); - he.fondo(g, (x * 3), y, 2); - g.setColor(Color.blue); - he.fondo(g, (x * 3) + cursor, y, 1); - } else { - g.setColor(Color.blue); - he.cuadro(g, (x * 3), y, 2); - } - - if (hasFocus()) - g.setColor(Color.white); - else - g.setColor(Color.black); - } else { - g.setColor(Color.black); - } - - String s = ("0" + Integer.toHexString(he.buff[n])); - s = s.substring(s.length() - 2); - he.printString(g, s, ((x++) * 3), y); - if (x == 16) { - x = 0; - y++; - } - } - } - - private void debug(String s) { - if (he.DEBUG) - System.out.println("JHexEditorHEX ==> " + s); - } - - // calcular la posicion del raton - public int calcularPosicionRaton(int x, int y) { - FontMetrics fn = getFontMetrics(JHexEditor.font); - x = x / ((fn.stringWidth(" ") + 1) * 3); - y = y / fn.getHeight(); - debug("x=" + x + " ,y=" + y); - return x + ((y + he.getInicio()) * 16); - } - - // mouselistener - public void mouseClicked(MouseEvent e) { - debug("mouseClicked(" + e + ")"); - he.cursor = calcularPosicionRaton(e.getX(), e.getY()); - this.requestFocus(); - he.repaint(); - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseReleased(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - // KeyListener - public void keyTyped(KeyEvent e) { - debug("keyTyped(" + e + ")"); - - /* - * char c=e.getKeyChar(); - * if(((c>='0')&&(c<='9'))||((c>='A')&&(c<='F'))||((c>='a')&&(c<='f'))) - * { char[] str=new char[2]; String - * n="00"+Integer.toHexString((int)he.buff[he.cursor]); if(n.length()>2) - * n=n.substring(n.length()-2); str[1-cursor]=n.charAt(1-cursor); - * str[cursor]=e.getKeyChar(); - * he.buff[he.cursor]=(byte)Integer.parseInt(new String(str),16); - * - * if(cursor!=1) cursor=1; else if(he.cursor!=(he.buff.length-1)){ - * he.cursor++; cursor=0;} he.actualizaCursor(); } - */ - } - - public void keyPressed(KeyEvent e) { - debug("keyPressed(" + e + ")"); - he.keyPressed(e); - } - - public void keyReleased(KeyEvent e) { - debug("keyReleased(" + e + ")"); - } - - public boolean isFocusTraversable() { - return true; - } -} \ No newline at end of file diff --git a/src/main/java/jd/cli/Main.java b/src/main/java/jd/cli/Main.java deleted file mode 100644 index 11004a4fc..000000000 --- a/src/main/java/jd/cli/Main.java +++ /dev/null @@ -1,54 +0,0 @@ -package jd.cli; - -import java.io.File; -import java.io.PrintStream; - -import jd.cli.loader.DirectoryLoader; -import jd.cli.preferences.CommonPreferences; -import jd.cli.printer.text.PlainTextPrinter; -import jd.cli.util.ClassFileUtil; -import jd.core.Decompiler; -import jd.core.process.DecompilerImpl; - - -public class Main -{ - /** - * @param args Path to java class - */ - public static void main(String[] args) { - - if (args.length == 0) { - System.out.println("usage: ..."); - } else { - try { - String pathToClass = args[0].replace('/', File.separatorChar).replace('\\', File.separatorChar); - String directoryPath = ClassFileUtil.ExtractDirectoryPath(pathToClass); - - if (directoryPath == null) - return; - - String internalPath = ClassFileUtil.ExtractInternalPath(directoryPath, pathToClass); - - if (internalPath == null) - return; - - CommonPreferences preferences = new CommonPreferences(); - DirectoryLoader loader = new DirectoryLoader(new File(directoryPath)); - - //PrintStream ps = new PrintStream("test.html"); - //HtmlPrinter printer = new HtmlPrinter(ps); - PrintStream ps = new PrintStream("test.txt"); - PlainTextPrinter printer = new PlainTextPrinter(preferences, ps); - - Decompiler decompiler = new DecompilerImpl(); - decompiler.decompile(preferences, loader, printer, internalPath); - - System.out.println("done."); - - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/src/main/java/jd/cli/loader/BaseLoader.java b/src/main/java/jd/cli/loader/BaseLoader.java deleted file mode 100644 index 67f6979a3..000000000 --- a/src/main/java/jd/cli/loader/BaseLoader.java +++ /dev/null @@ -1,34 +0,0 @@ -package jd.cli.loader; - -import java.io.File; - -import jd.core.loader.Loader; - -public abstract class BaseLoader implements Loader -{ - protected String codebase; - protected long lastModified; - protected boolean isFile; - - public BaseLoader(File file) - { - this.codebase = file.getAbsolutePath(); - this.lastModified = file.lastModified(); - this.isFile = file.isFile(); - } - - public String getCodebase() - { - return codebase; - } - - public long getLastModified() - { - return lastModified; - } - - public boolean isFile() - { - return isFile; - } -} diff --git a/src/main/java/jd/cli/loader/DirectoryLoader.java b/src/main/java/jd/cli/loader/DirectoryLoader.java deleted file mode 100644 index 1a85fcafc..000000000 --- a/src/main/java/jd/cli/loader/DirectoryLoader.java +++ /dev/null @@ -1,44 +0,0 @@ -package jd.cli.loader; - -import java.io.BufferedInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; - -import jd.core.loader.LoaderException; - - -public class DirectoryLoader extends BaseLoader -{ - public DirectoryLoader(File file) throws LoaderException - { - super(file); - - if (! (file.exists() && file.isDirectory())) - throw new LoaderException("'" + codebase + "' is not a directory"); - } - - public DataInputStream load(String internalPath) - throws LoaderException - { - File file = new File(this.codebase, internalPath); - - try - { - return new DataInputStream( - new BufferedInputStream(new FileInputStream(file))); - } - catch (FileNotFoundException e) - { - throw new LoaderException( - "'" + file.getAbsolutePath() + "' not found."); - } - } - - public boolean canLoad(String internalPath) - { - File file = new File(this.codebase, internalPath); - return file.exists() && file.isFile(); - } -} diff --git a/src/main/java/jd/cli/loader/JarLoader.java b/src/main/java/jd/cli/loader/JarLoader.java deleted file mode 100644 index 695d47808..000000000 --- a/src/main/java/jd/cli/loader/JarLoader.java +++ /dev/null @@ -1,59 +0,0 @@ -package jd.cli.loader; - -import java.io.DataInputStream; -import java.io.File; -import java.io.IOException; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import jd.core.loader.LoaderException; - - -public class JarLoader extends BaseLoader -{ - private ZipFile zipFile; - - public JarLoader(File file) throws LoaderException - { - super(file); - - if (! (file.exists() && file.isFile())) - { - throw new LoaderException("'" + codebase + "' is not a directory"); - } - - try - { - this.zipFile = new ZipFile(codebase); - } - catch (IOException e) - { - throw new LoaderException("Error reading from '" + codebase + "'"); - } - } - - public DataInputStream load(String internalPath) - throws LoaderException - { - ZipEntry zipEntry = this.zipFile.getEntry(internalPath); - - if (zipEntry == null) - { - throw new LoaderException("Can not read '" + internalPath + "'"); - } - - try - { - return new DataInputStream(this.zipFile.getInputStream(zipEntry)); - } - catch (IOException e) - { - throw new LoaderException("Error reading '" + internalPath + "'"); - } - } - - public boolean canLoad(String internalPath) - { - return this.zipFile.getEntry(internalPath) != null; - } -} diff --git a/src/main/java/jd/cli/loader/LoaderManager.java b/src/main/java/jd/cli/loader/LoaderManager.java deleted file mode 100644 index 6a9e949de..000000000 --- a/src/main/java/jd/cli/loader/LoaderManager.java +++ /dev/null @@ -1,79 +0,0 @@ -package jd.cli.loader; - -import java.io.File; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import jd.core.loader.LoaderException; - -public class LoaderManager -{ - protected final static String JAR_SUFFIX = ".jar"; - protected final static String ZIP_SUFFIX = ".zip"; - - protected Map map; - - public LoaderManager() - { - this.map = new ConcurrentHashMap(); - } - - public BaseLoader getLoader(String codebase) throws LoaderException - { - File file = new File(codebase); - String key = file.getAbsolutePath(); - BaseLoader loader = map.get(key); - - if (loader == null) - { - if (file.exists()) - { - loader = newLoader(key, file); - } - } - else - { - if (file.exists()) - { - if ((file.lastModified() != loader.getLastModified()) || - (file.isFile() != loader.isFile())) - { - loader = newLoader(key, file); - } - } - else - { - map.remove(key); - } - } - - return loader; - } - - protected BaseLoader newLoader(String key, File file) throws LoaderException - { - BaseLoader loader = null; - - if (file.isFile()) - { - if (endsWithIgnoreCase(key, JAR_SUFFIX) || - endsWithIgnoreCase(key, ZIP_SUFFIX)) - { - this.map.put(key, loader = new JarLoader(file)); - } - } - else if (file.isDirectory()) - { - this.map.put(key, loader = new DirectoryLoader(file)); - } - - return loader; - } - - protected static boolean endsWithIgnoreCase(String s, String suffix) - { - int suffixLength = suffix.length(); - int index = s.length() - suffixLength; - return (s.regionMatches(true, index, suffix, 0, suffixLength)); - } -} diff --git a/src/main/java/jd/cli/preferences/CommonPreferences.java b/src/main/java/jd/cli/preferences/CommonPreferences.java deleted file mode 100644 index 37650a028..000000000 --- a/src/main/java/jd/cli/preferences/CommonPreferences.java +++ /dev/null @@ -1,36 +0,0 @@ -package jd.cli.preferences; - -import jd.core.preferences.Preferences; - -public class CommonPreferences extends Preferences -{ - protected boolean showPrefixThis; - protected boolean mergeEmptyLines; - protected boolean unicodeEscape; - protected boolean showLineNumbers; - - public CommonPreferences() - { - this.showPrefixThis = true; - this.mergeEmptyLines = false; - this.unicodeEscape = false; - this.showLineNumbers = true; - } - - public CommonPreferences( - boolean showDefaultConstructor, boolean realignmentLineNumber, - boolean showPrefixThis, boolean mergeEmptyLines, - boolean unicodeEscape, boolean showLineNumbers) - { - super(showDefaultConstructor, realignmentLineNumber); - this.showPrefixThis = showPrefixThis; - this.mergeEmptyLines = mergeEmptyLines; - this.unicodeEscape = unicodeEscape; - this.showLineNumbers = showLineNumbers; - } - - public boolean isShowPrefixThis() { return showPrefixThis; } - public boolean isMergeEmptyLines() { return mergeEmptyLines; } - public boolean isUnicodeEscape() { return unicodeEscape; } - public boolean isShowLineNumbers() { return showLineNumbers; } -} diff --git a/src/main/java/jd/cli/printer/html/HtmlPrinter.java b/src/main/java/jd/cli/printer/html/HtmlPrinter.java deleted file mode 100644 index 0a1b73931..000000000 --- a/src/main/java/jd/cli/printer/html/HtmlPrinter.java +++ /dev/null @@ -1,544 +0,0 @@ -package jd.cli.printer.html; - -import java.io.PrintStream; - -import jd.cli.util.VersionUtil; -import jd.core.CoreConstants; -import jd.core.printer.Printer; - -/* - * CSS - * .javacode{font-size:11px} - * .javacode .linenumber, .javacode .l, i{color:#3f7f5f} - * .javacode .keyword, .javacode .k, b{color:#7f0055;font-weight:bold} - * .javacode .comment, .javacode .t, cite{color:#3f7f5f} - * .javacode .javadoc, .javacode .d, dfn{color:#3f5fbf} - * .javacode .error, .javacode .e, span{color:#ff0000} - * .javacode .annotationname, .javacode .a, del{color:#646464} - * .javacode .constant, .javacode .c, u{color:#2a00ff} - * .javacode .field, .javacode .f, var{color:#0000c0} - * .javacode .staticfield, .javacode .g, em{color:#0000c0;font-style:italic} - * .javacode .staticmethod, .javacode .n, samp{font-style:italic} - * .javacode .debuglayoutblock{background-color:#ccffff;border:1px solid #99eeee} - * .javacode .debugseparatorlayoutblock{background-color:#ccffcc;border:1px solid #99ee99} - * .javacode .debugstatementblocklayoutblock{background-color:#ffcccc;border:1px solid #ee9999} - * .javacode .debugenumblocklayoutblock{background-color:#ffffcc;border:1px solid #eeee99} - * .javacode .debugcommentdeprecatedlayoutblock{background-color:#fefefe;border:1px solid #e9e9e9} - * .javacode .debugmarker{background-color:#ffd2ff;border:1px solid #cfb2cf} - * .javacode .extraline, .javacode .x, s - * .javacode .optionalthisprefix, .javacode .o, kbd - * .javacode .metadata, .javacode .m, ins - */ -public class HtmlPrinter implements Printer -{ - private final static boolean DEBUG = true; - - private PrintStream printStream; - private StringBuffer sbLineNumber; - private StringBuffer sbCode; - private int maxLineNumber; - private int majorVersion; - private int minorVersion; - private int realLineNumber; - private String realLineNumberFormatPrefix; - private String lineNumberFormatPrefix; - private String unknownLineNumberPrefix; - private int indentationCount; - private int commentJavadocErrorDepth; - - public HtmlPrinter(PrintStream printStream) - { - this.printStream = printStream; - this.sbLineNumber = new StringBuffer(10*1024); - this.sbCode = new StringBuffer(30*1024); - } - - public void print(byte b) { this.sbCode.append(String.valueOf(b)); } - public void print(char c) - { - switch (c) - { - case '<': - this.sbCode.append("<"); - break; - case '>': - this.sbCode.append(">"); - break; - default: - this.sbCode.append(String.valueOf(c)); - break; - } - } - public void print(int i) { this.sbCode.append(String.valueOf(i)); } - public void print(String s) { this.sbCode.append(s); } - - public void printNumeric(String s) - { - this.sbCode.append(""); - this.sbCode.append(s); - this.sbCode.append(""); - } - - public void printString(String s, String scopeInternalName) - { - this.sbCode.append(""); - - // Replace '<' by '<' - int length = s.length(); - - if (length > 0) - { - for (int i=0; i"); - } - - public void printKeyword(String s) - { - if (this.commentJavadocErrorDepth == 0) - { - this.sbCode.append(""); - this.sbCode.append(s); - this.sbCode.append(""); - } - else - { - this.sbCode.append(s); - } - } - - public void printJavaWord(String s) { printKeyword(s); } - - public void printType(String internalName, String name, String scopeInternalName) - { - this.sbCode.append(name); - } - public void printTypeDeclaration(String internalName, String name) - { - this.sbCode.append(name); - } - public void printTypeImport(String internalName, String name) - { - this.sbCode.append(name); - } - - public void printField( - String internalName, String name, - String descriptor, String scopeInternalName) - { - printFieldDeclaration(internalName, name, descriptor); - } - public void printFieldDeclaration( - String internalName, String name, String descriptor) - { - this.sbCode.append(""); - this.sbCode.append(name); - this.sbCode.append(""); - } - - public void printStaticField( - String internalName, String name, - String descriptor, String scopeInternalName) - { - printStaticFieldDeclaration(internalName, name, descriptor); - } - public void printStaticFieldDeclaration( - String internalName, String name, String descriptor) - { - this.sbCode.append(""); - this.sbCode.append(name); - this.sbCode.append(""); - } - - public void printConstructor( - String internalName, String name, - String descriptor, String scopeInternalName) - { - this.sbCode.append(name); - } - public void printConstructorDeclaration( - String internalName, String name, String descriptor) - { - this.sbCode.append(name); - } - - public void printStaticConstructorDeclaration( - String internalName, String name) - { - this.sbCode.append(""); - this.sbCode.append(name); - this.sbCode.append(""); - } - - public void printMethod( - String internalName, String name, - String descriptor, String scopeInternalName) - { - this.sbCode.append(name); - } - public void printMethodDeclaration( - String internalName, String name, String descriptor) - { - this.sbCode.append(name); - } - - public void printStaticMethod( - String internalName, String name, - String descriptor, String scopeInternalName) - { - printStaticMethodDeclaration(internalName, name, descriptor); - } - public void printStaticMethodDeclaration( - String internalName, String name, String descriptor) - { - this.sbCode.append(""); - this.sbCode.append(name); - this.sbCode.append(""); - } - - public void start(int maxLineNumber, int majorVersion, int minorVersion) - { - this.maxLineNumber = maxLineNumber; - this.majorVersion = majorVersion; - this.minorVersion = minorVersion; - this.realLineNumber = 0; - this.indentationCount = 0; - this.commentJavadocErrorDepth = 0; - - int digitCount = 1; - int maximum = 9; - - while (maximum < maxLineNumber) - { - digitCount++; - maximum = maximum*10 + 9; - } - - this.realLineNumberFormatPrefix = "%" + (digitCount+1) + "d:"; - this.lineNumberFormatPrefix = "%" + digitCount + "d
"; - - StringBuilder sb = new StringBuilder(digitCount + 7); - sb.append("%" + (digitCount+1) + "d:"); - for (int i=0; i"); - this.unknownLineNumberPrefix = sb.toString(); - - this.printStream.print( - "" + - "" + - "

Preview

" + - "
"); - } - - public void end() - { - if (this.maxLineNumber > 0) - { - this.printStream.print("
"); - this.printStream.print(this.sbLineNumber.toString()); - this.printStream.print("
"); - } - - this.printStream.print("
"); - this.printStream.print(this.sbCode.toString()); - this.printStream.print("
"); - - this.printStream.print("
"); - this.printStream.print("Java Class Version: " + VersionUtil.getJDKVersion(this.majorVersion, this.minorVersion) + "
"); - this.printStream.print("JD-CL Version: " + "0.1.0" + "
"); - this.printStream.print("JD-Core Version: " + CoreConstants.JD_CORE_VERSION); - this.printStream.print("
"); - - this.printStream.print("
"); - } - - public void indent() - { - this.indentationCount++; - } - public void desindent() - { - if (this.indentationCount > 0) - this.indentationCount--; - } - - public void startOfLine(int lineNumber) - { - this.realLineNumber++; - - if (this.maxLineNumber > 0) - { - if (lineNumber == UNKNOWN_LINE_NUMBER) - { - this.sbLineNumber.append(String.format( - this.unknownLineNumberPrefix, this.realLineNumber)); - } - else - { - this.sbLineNumber.append(String.format( - this.realLineNumberFormatPrefix, this.realLineNumber)); - - if (this.realLineNumber == lineNumber) - { - this.sbLineNumber.append(String.format( - this.lineNumberFormatPrefix, lineNumber)); - } - else - { - this.sbLineNumber.append(""); - this.sbLineNumber.append(String.format( - this.lineNumberFormatPrefix, lineNumber)); - this.sbLineNumber.append(""); - } - } - } - - for (int i=0; i"); - } - - public void extraLine(int count) - { - if (this.maxLineNumber > 0) - { - this.sbLineNumber.append(""); - } - this.sbCode.append(""); - - while (count-- > 0) - { - this.realLineNumber++; - - if (this.maxLineNumber > 0) - { - this.sbLineNumber.append(String.format( - this.unknownLineNumberPrefix, this.realLineNumber)); - } - - this.sbCode.append("
"); - } - - if (this.maxLineNumber > 0) - { - this.sbLineNumber.append("
"); - } - this.sbCode.append("
"); - } - - public void startOfComment() - { - this.sbCode.append(""); - this.commentJavadocErrorDepth++; - } - public void endOfComment() - { - this.sbCode.append(""); - this.commentJavadocErrorDepth--; - } - - public void startOfJavadoc() - { - this.sbCode.append(""); - this.commentJavadocErrorDepth++; - } - public void endOfJavadoc() - { - this.sbCode.append(""); - this.commentJavadocErrorDepth--; - } - - public void startOfXdoclet() { this.sbCode.append(""); } - public void endOfXdoclet() { this.sbCode.append(""); } - - public void startOfError() - { - this.sbCode.append(""); - this.commentJavadocErrorDepth++; - } - public void endOfError() - { - this.sbCode.append(""); - this.commentJavadocErrorDepth--; - } - - public void startOfImportStatements() {} - public void endOfImportStatements() {} - - public void startOfTypeDeclaration(String internalPath) {} - public void endOfTypeDeclaration() {} - - public void startOfAnnotationName() - { - this.sbCode.append(""); - } - public void endOfAnnotationName() - { - this.sbCode.append(""); - } - - public void startOfOptionalPrefix() - { - this.sbCode.append(""); - } - public void endOfOptionalPrefix() - { - this.sbCode.append(""); - } - - public void debugStartOfLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } - public void debugEndOfLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } - - public void debugStartOfSeparatorLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } - public void debugEndOfSeparatorLayoutBlock(int min, int value, int max) - { - if (DEBUG) - { - // DEBUG // this.sb.append(min); - // DEBUG // this.sb.append("<="); - // DEBUG // this.sb.append(value); - // DEBUG // this.sb.append("<="); - // DEBUG // this.sb.append(max); - this.sbCode.append(""); - } - } - - public void debugStartOfStatementsBlockLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } - public void debugEndOfStatementsBlockLayoutBlock(int min, int value, int max) - { - if (DEBUG) - { - // DEBUG // this.sb.append(min); - // DEBUG // this.sb.append("<="); - // DEBUG // this.sb.append(value); - // DEBUG // this.sb.append("<="); - // DEBUG // this.sb.append(max); - this.sbCode.append(""); - } - } - - public void debugStartOfInstructionBlockLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } - public void debugEndOfInstructionBlockLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } - - public void debugStartOfCommentDeprecatedLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } - public void debugEndOfCommentDeprecatedLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } - - public void debugMarker(String marker) - { - if (DEBUG) - { - // DEBUG // this.sb.append(""); - // DEBUG // this.sb.append(marker); - // DEBUG // this.sb.append(""); - } - } - - public void debugStartOfCaseBlockLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } - public void debugEndOfCaseBlockLayoutBlock() - { - if (DEBUG) - { - this.sbCode.append(""); - } - } -} diff --git a/src/main/java/jd/cli/printer/text/PlainTextPrinter.java b/src/main/java/jd/cli/printer/text/PlainTextPrinter.java deleted file mode 100644 index ae9f6da7f..000000000 --- a/src/main/java/jd/cli/printer/text/PlainTextPrinter.java +++ /dev/null @@ -1,378 +0,0 @@ -package jd.cli.printer.text; - -import java.io.PrintStream; - -import jd.cli.preferences.CommonPreferences; -import jd.core.model.instruction.bytecode.instruction.Instruction; -import jd.core.printer.Printer; - -public class PlainTextPrinter implements Printer -{ - protected static final String TAB = " "; - protected static final String NEWLINE = "\n"; - - protected CommonPreferences preferences; - protected PrintStream printStream; - protected int maxLineNumber; - protected int majorVersion; - protected int minorVersion; - protected int digitCount; - protected String lineNumberBeginPrefix; - protected String lineNumberEndPrefix; - protected String unknownLineNumberPrefix; - protected int indentationCount; - protected boolean display; - - public PlainTextPrinter( - CommonPreferences preferences, PrintStream printStream) - { - this.preferences = preferences; - this.printStream = printStream; - this.maxLineNumber = 0; - this.majorVersion = 0; - this.minorVersion = 0; - this.indentationCount = 0; - } - - public int getMajorVersion() { return majorVersion; } - public int getMinorVersion() { return minorVersion; } - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - public void print(byte b) { this.printStream.append(String.valueOf(b)); } - public void print(int i) { this.printStream.append(String.valueOf(i)); } - - public void print(char c) - { - if (this.display) - this.printStream.append(String.valueOf(c)); - } - - public void print(String s) - { - if (this.display) - printEscape(s); - } - - public void printNumeric(String s) { this.printStream.append(s); } - - public void printString(String s, String scopeInternalName) { this.printStream.append(s); } - - public void printKeyword(String s) - { - if (this.display) - this.printStream.append(s); - } - - public void printJavaWord(String s) { this.printStream.append(s); } - - public void printType(String internalName, String name, String scopeInternalName) - { - if (this.display) - printEscape(name); - } - - public void printTypeDeclaration(String internalName, String name) - { - printEscape(name); - } - - public void printTypeImport(String internalName, String name) - { - printEscape(name); - } - - public void printField( - String internalName, String name, - String descriptor, String scopeInternalName) - { - printEscape(name); - } - public void printFieldDeclaration( - String internalName, String name, String descriptor) - { - printEscape(name); - } - - public void printStaticField( - String internalName, String name, - String descriptor, String scopeInternalName) - { - printEscape(name); - } - public void printStaticFieldDeclaration( - String internalName, String name, String descriptor) - { - printEscape(name); - } - - public void printConstructor( - String internalName, String name, - String descriptor, String scopeInternalName) - { - printEscape(name); - } - public void printConstructorDeclaration( - String internalName, String name, String descriptor) - { - printEscape(name); - } - - public void printStaticConstructorDeclaration( - String internalName, String name) - { - this.printStream.append(name); - } - - public void printMethod( - String internalName, String name, - String descriptor, String scopeInternalName) - { - printEscape(name); - } - public void printMethodDeclaration( - String internalName, String name, String descriptor) - { - printEscape(name); - } - - public void printStaticMethod( - String internalName, String name, - String descriptor, String scopeInternalName) - { - printEscape(name); - } - public void printStaticMethodDeclaration( - String internalName, String name, String descriptor) - { - printEscape(name); - } - - public void start(int maxLineNumber, int majorVersion, int minorVersion) - { - this.majorVersion = majorVersion; - this.minorVersion = minorVersion; - this.indentationCount = 0; - this.display = true; - - if (this.preferences.isShowLineNumbers()) - { - this.maxLineNumber = maxLineNumber; - - if (maxLineNumber > 0) - { - this.digitCount = 1; - this.unknownLineNumberPrefix = " "; - int maximum = 9; - - while (maximum < maxLineNumber) - { - this.digitCount++; - this.unknownLineNumberPrefix += ' '; - maximum = maximum*10 + 9; - } - - this.lineNumberBeginPrefix = "/* "; - this.lineNumberEndPrefix = " */ "; - } - else - { - this.unknownLineNumberPrefix = ""; - this.lineNumberBeginPrefix = ""; - this.lineNumberEndPrefix = ""; - } - } - else - { - this.maxLineNumber = 0; - this.unknownLineNumberPrefix = ""; - this.lineNumberBeginPrefix = ""; - this.lineNumberEndPrefix = ""; - } - } - - public void end() {} - - public void indent() - { - this.indentationCount++; - } - public void desindent() - { - if (this.indentationCount > 0) - this.indentationCount--; - } - - public void startOfLine(int lineNumber) - { - if (this.maxLineNumber > 0) - { - this.printStream.append(this.lineNumberBeginPrefix); - - if (lineNumber == Instruction.UNKNOWN_LINE_NUMBER) - { - this.printStream.append(this.unknownLineNumberPrefix); - } - else - { - int left = 0; - - left = printDigit(5, lineNumber, 10000, left); - left = printDigit(4, lineNumber, 1000, left); - left = printDigit(3, lineNumber, 100, left); - left = printDigit(2, lineNumber, 10, left); - this.printStream.append((char)('0' + (lineNumber-left))); - } - - this.printStream.append(this.lineNumberEndPrefix); - } - - for (int i=0; i 0) - { - if (this.maxLineNumber > 0) - { - this.printStream.append(this.lineNumberBeginPrefix); - this.printStream.append(this.unknownLineNumberPrefix); - this.printStream.append(this.lineNumberEndPrefix); - } - - this.printStream.append(NEWLINE); - } - } - } - - public void startOfComment() {} - public void endOfComment() {} - - public void startOfJavadoc() {} - public void endOfJavadoc() {} - - public void startOfXdoclet() {} - public void endOfXdoclet() {} - - public void startOfError() {} - public void endOfError() {} - - public void startOfImportStatements() {} - public void endOfImportStatements() {} - - public void startOfTypeDeclaration(String internalPath) {} - public void endOfTypeDeclaration() {} - - public void startOfAnnotationName() {} - public void endOfAnnotationName() {} - - public void startOfOptionalPrefix() - { - if (this.preferences.isShowPrefixThis() == false) - this.display = false; - } - - public void endOfOptionalPrefix() - { - this.display = true; - } - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - public void debugStartOfLayoutBlock() {} - public void debugEndOfLayoutBlock() {} - - public void debugStartOfSeparatorLayoutBlock() {} - public void debugEndOfSeparatorLayoutBlock(int min, int value, int max) {} - - public void debugStartOfStatementsBlockLayoutBlock() {} - public void debugEndOfStatementsBlockLayoutBlock(int min, int value, int max) {} - - public void debugStartOfInstructionBlockLayoutBlock() {} - public void debugEndOfInstructionBlockLayoutBlock() {} - - public void debugStartOfCommentDeprecatedLayoutBlock() {} - public void debugEndOfCommentDeprecatedLayoutBlock() {} - - public void debugMarker(String marker) {} - - public void debugStartOfCaseBlockLayoutBlock() {} - public void debugEndOfCaseBlockLayoutBlock() {} - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - protected void printEscape(String s) - { - if (this.preferences.isUnicodeEscape()) - { - int length = s.length(); - - for (int i=0; i> 3))); - this.printStream.append((char)('0' + (c & 0x7))); - } - else if (c > 127) - { - // Write octal format - this.printStream.append("\\u"); - - int z = (c >> 12); - this.printStream.append((char)((z <= 9) ? ('0' + z) : (('A' - 10) + z))); - z = ((c >> 8) & 0xF); - this.printStream.append((char)((z <= 9) ? ('0' + z) : (('A' - 10) + z))); - z = ((c >> 4) & 0xF); - this.printStream.append((char)((z <= 9) ? ('0' + z) : (('A' - 10) + z))); - z = (c & 0xF); - this.printStream.append((char)((z <= 9) ? ('0' + z) : (('A' - 10) + z))); - } - else - { - this.printStream.append(c); - } - } - } - else - { - this.printStream.append(s); - } - } - - protected int printDigit(int dcv, int lineNumber, int divisor, int left) - { - if (this.digitCount >= dcv) - { - if (lineNumber < divisor) - { - this.printStream.append(' '); - } - else - { - int e = (lineNumber-left) / divisor; - this.printStream.append((char)('0' + e)); - left += e*divisor; - } - } - - return left; - } -} diff --git a/src/main/java/jd/cli/util/ClassFileUtil.java b/src/main/java/jd/cli/util/ClassFileUtil.java deleted file mode 100644 index 76e620445..000000000 --- a/src/main/java/jd/cli/util/ClassFileUtil.java +++ /dev/null @@ -1,132 +0,0 @@ -package jd.cli.util; - -import jd.core.CoreConstants; -import jd.core.model.classfile.constant.Constant; -import jd.core.model.classfile.constant.ConstantClass; -import jd.core.model.classfile.constant.ConstantConstant; -import jd.core.model.classfile.constant.ConstantUtf8; -import jd.core.process.deserializer.ClassFormatException; -import jd.core.util.StringConstants; - -import java.io.*; - - -public class ClassFileUtil { - /* - * Lecture rapide de la structure de la classe et extraction du nom du - * repoertoire de base. - */ - public static String ExtractDirectoryPath(String pathToClass) throws Exception { - DataInputStream dis = null; - String directoryPath = null; - - try { - dis = new DataInputStream( - new BufferedInputStream( - new FileInputStream(pathToClass))); - int magic = dis.readInt(); - if (magic != CoreConstants.JAVA_MAGIC_NUMBER) - throw new ClassFormatException("Invalid Java .class file"); - - /* int minor_version = */ - dis.readUnsignedShort(); - /* int major_version = */ - dis.readUnsignedShort(); - - Constant[] constants = DeserializeConstants(dis); - - /* int access_flags = */ - dis.readUnsignedShort(); - int this_class = dis.readUnsignedShort(); - - Constant c = constants[this_class]; - if ((c == null) || (c.tag != ConstantConstant.CONSTANT_Class)) - throw new ClassFormatException("Invalid contant pool"); - - c = constants[((ConstantClass) c).name_index]; - if ((c == null) || (c.tag != ConstantConstant.CONSTANT_Utf8)) - throw new ClassFormatException("Invalid contant pool"); - - String internalClassName = ((ConstantUtf8) c).bytes; - String pathSuffix = internalClassName.replace( - StringConstants.INTERNAL_PACKAGE_SEPARATOR, File.separatorChar) + - StringConstants.CLASS_FILE_SUFFIX; - - int index = pathToClass.indexOf(pathSuffix); - - if (index < 0) - throw new ClassFormatException("Invalid internal class name"); - - directoryPath = pathToClass.substring(0, index); - } finally { - if (dis != null) - try { - dis.close(); - } catch (IOException e) { - } - } - - return directoryPath; - } - - public static String ExtractInternalPath( - String directoryPath, String pathToClass) { - if ((directoryPath == null) || (pathToClass == null) || - !pathToClass.startsWith(directoryPath)) - return null; - - String s = pathToClass.substring(directoryPath.length()); - - return s.replace(File.separatorChar, StringConstants.INTERNAL_PACKAGE_SEPARATOR); - } - - private static Constant[] DeserializeConstants(DataInputStream dis) - throws IOException { - int count = dis.readUnsignedShort(); - if (count == 0) - return null; - - Constant[] constants = new Constant[count]; - - for (int i = 1; i < count; i++) { - byte tag = dis.readByte(); - - switch (tag) { - case ConstantConstant.CONSTANT_Class: - constants[i] = new ConstantClass(tag, dis.readUnsignedShort()); - break; - case ConstantConstant.CONSTANT_Utf8: - constants[i] = new ConstantUtf8(tag, dis.readUTF()); - break; - case ConstantConstant.CONSTANT_Long: - case ConstantConstant.CONSTANT_Double: - dis.readInt(); - dis.readInt(); - i++; - break; - case ConstantConstant.CONSTANT_Fieldref: - case ConstantConstant.CONSTANT_Methodref: - case ConstantConstant.CONSTANT_InterfaceMethodref: - case ConstantConstant.CONSTANT_NameAndType: - dis.readUnsignedShort(); - dis.readUnsignedShort(); - break; - case ConstantConstant.CONSTANT_Integer: - case ConstantConstant.CONSTANT_Float: - dis.readInt(); - break; - case ConstantConstant.CONSTANT_String: - dis.readUnsignedShort(); - break; - case 15: - case 16: - case 18: - throw new IllegalArgumentException("JD-GUI does not support Java 8 as of yet"); - default: - throw new ClassFormatException("Invalid constant pool entry"); - } - } - - return constants; - } -} diff --git a/src/main/java/jd/cli/util/CommonTypeNameUtil.java b/src/main/java/jd/cli/util/CommonTypeNameUtil.java deleted file mode 100644 index 9a20d83de..000000000 --- a/src/main/java/jd/cli/util/CommonTypeNameUtil.java +++ /dev/null @@ -1,12 +0,0 @@ -package jd.cli.util; - -import jd.core.util.TypeNameUtil; - -public class CommonTypeNameUtil -{ - public static String InternalPathToQualifiedTypeName(String internalPath) - { - String internalTypeName = internalPath.substring(0, internalPath.length()-6); - return TypeNameUtil.InternalTypeNameToQualifiedTypeName(internalTypeName); - } -} diff --git a/src/main/java/jd/cli/util/VersionUtil.java b/src/main/java/jd/cli/util/VersionUtil.java deleted file mode 100644 index 1fe47db32..000000000 --- a/src/main/java/jd/cli/util/VersionUtil.java +++ /dev/null @@ -1,31 +0,0 @@ -package jd.cli.util; - -public class VersionUtil -{ - public static String getJDKVersion(int majorVersion, int minorVersion) - { - StringBuffer sb = new StringBuffer(20); - - if (majorVersion >= 49) - { - sb.append(majorVersion - (49-5)); - sb.append(" ("); - sb.append(majorVersion); - sb.append('.'); - sb.append(minorVersion); - sb.append(')'); - } - else if (majorVersion >= 45) - { - sb.append("1."); - sb.append(majorVersion - (45-1)); - sb.append(" ("); - sb.append(majorVersion); - sb.append('.'); - sb.append(minorVersion); - sb.append(')'); - } - - return sb.toString(); - } -} diff --git a/src/main/java/me/konloch/kontainer/io/HTTPRequest.java b/src/main/java/me/konloch/kontainer/io/HTTPRequest.java deleted file mode 100644 index 2f85b2279..000000000 --- a/src/main/java/me/konloch/kontainer/io/HTTPRequest.java +++ /dev/null @@ -1,253 +0,0 @@ -package me.konloch.kontainer.io; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.Proxy; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -/** - * A wrapper for Java SE classes to write/read an HTTP Request - * - * @author Konloch - * - */ - -public class HTTPRequest { - - public URL url; - private int timeout = 30000; - private String cookie; - private String referer; - private String postData; - private String useragent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0"; - private Proxy proxy; - private boolean setFollowRedirects = true; - private BufferedReader reader; - private DataOutputStream writer; - private HttpURLConnection connection; - private Set>> lastConnectionHeaders; - - /** - * Creates a new HTTPRequest object - * @param url - */ - public HTTPRequest(URL url) { - this.url = url; - } - - /** - * Sets a referer to send to the web server - */ - public void setReferer(String referer) { - this.referer = referer; - } - - /** - * Set a cookie string to send to the web server - */ - public void setCookie(String cookie) { - this.cookie = cookie; - } - - /** - * Sets post data to send to the web server - */ - public void setPostData(String postData) { - this.postData = postData; - } - - /** - * Sets a custom useragent, default 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0' - */ - public void setUseragent(String useragent) { - this.useragent = useragent; - } - - /** - * Sets the seconds till timeout, default 30,000 milliseconds - */ - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - /** - * Sets a proxy to connect through - */ - public void setProxy(Proxy proxy) { - this.proxy = proxy; - } - - /** - * Used to get the headers the webserver sent on our last connection - */ - public Set>> getLastConnectionHeaders() { - return lastConnectionHeaders; - } - - /** - * By default follow redirects are enabled - */ - public void setFollowRedirects(boolean setFollowRedirects) { - this.setFollowRedirects = setFollowRedirects; - } - - /** - * Used to set up the connection to read the content. - */ - private void setup() throws Exception { - if(proxy != null) - connection = (HttpURLConnection) url.openConnection(proxy); - else - connection = (HttpURLConnection) url.openConnection(); - - if(cookie != null) - connection.setRequestProperty("Cookie", cookie); - if(referer != null) - connection.addRequestProperty("Referer", referer); - - connection.setRequestProperty("User-Agent", useragent); - connection.setReadTimeout(timeout); - connection.setConnectTimeout(timeout); - connection.setUseCaches(false); - HttpURLConnection.setFollowRedirects(setFollowRedirects); - - if(postData != null) { - connection.setRequestMethod("POST"); - connection.setDoOutput(true); - connection.setDoInput(true); - writer = new DataOutputStream(connection.getOutputStream()); - writer.writeBytes(postData); - writer.flush(); - } - - reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - } - - /** - * Reads the entire page and returns a string array - * @return - * @throws Exception - */ - public String[] read() throws Exception { - ArrayList st; - - try { - setup(); - - st = new ArrayList(); - String s; - while((s = reader.readLine()) != null) - st.add(s); - - lastConnectionHeaders = connection.getHeaderFields().entrySet(); - } catch(Exception e) { - cleanup(); - throw e; - } finally { - cleanup(); - } - - return st.toArray(new String[st.size()]); - } - - /** - * Reads as many lines as expected unless it reaches the end. - * @param linesToRead - * @return - * @throws Exception - */ - public String[] read(int linesToRead) throws Exception { - ArrayList st; - - try { - setup(); - - st = new ArrayList(); - for(int i = 0; i < linesToRead; i++) { - String s = reader.readLine(); - if(s != null) - st.add(s); - } - - lastConnectionHeaders = connection.getHeaderFields().entrySet(); - } catch(Exception e) { - cleanup(); - throw e; - } finally { - cleanup(); - } - - return st.toArray(new String[st.size()]); - } - - /** - * Only reads the first line - * @return - * @throws Exception - */ - public String readSingle() throws Exception { - String s; - - try { - setup(); - - s = reader.readLine(); - - lastConnectionHeaders = connection.getHeaderFields().entrySet(); - } catch(Exception e) { - cleanup(); - throw e; - } finally { - cleanup(); - } - - return s; - } - - /** - * Reads until it reaches the expected line then it returns it. - * @param linesToRead - * @return - * @throws Exception - */ - public String readSingle(int linesToRead) throws Exception { - String s; - - try { - setup(); - - for(int i = 0; i < linesToRead-1; i++) - reader.readLine(); - - s = reader.readLine(); - - lastConnectionHeaders = connection.getHeaderFields().entrySet(); - } catch(Exception e) { - cleanup(); - throw e; - } finally { - cleanup(); - } - - return s; - } - - /** - * Used to clean up the connection, closes the connections and nulls the objects - */ - private void cleanup() { - try { reader.close(); } catch(Exception e) {} - try { writer.close(); } catch(Exception e) {} - try { connection.disconnect(); } catch(Exception e) {} - reader = null; - writer = null; - connection = null; - } - -} \ No newline at end of file diff --git a/src/main/java/org/apache/commons/cli/AlreadySelectedException.java b/src/main/java/org/apache/commons/cli/AlreadySelectedException.java deleted file mode 100644 index 7078cd7aa..000000000 --- a/src/main/java/org/apache/commons/cli/AlreadySelectedException.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.cli; - -/** - * Thrown when more than one option in an option group - * has been provided. - * - * @version $Id: AlreadySelectedException.java 1443102 2013-02-06 18:12:16Z tn $ - */ -public class AlreadySelectedException extends ParseException -{ - /** - * This exception {@code serialVersionUID}. - */ - private static final long serialVersionUID = 3674381532418544760L; - - /** The option group selected. */ - private OptionGroup group; - - /** The option that triggered the exception. */ - private Option option; - - /** - * Construct a new AlreadySelectedException - * with the specified detail message. - * - * @param message the detail message - */ - public AlreadySelectedException(String message) - { - super(message); - } - - /** - * Construct a new AlreadySelectedException - * for the specified option group. - * - * @param group the option group already selected - * @param option the option that triggered the exception - * @since 1.2 - */ - public AlreadySelectedException(OptionGroup group, Option option) - { - this("The option '" + option.getKey() + "' was specified but an option from this group " - + "has already been selected: '" + group.getSelected() + "'"); - this.group = group; - this.option = option; - } - - /** - * Returns the option group where another option has been selected. - * - * @return the related option group - * @since 1.2 - */ - public OptionGroup getOptionGroup() - { - return group; - } - - /** - * Returns the option that was added to the group and triggered the exception. - * - * @return the related option - * @since 1.2 - */ - public Option getOption() - { - return option; - } -} diff --git a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java deleted file mode 100644 index 92d87f0d1..000000000 --- a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.cli; - -import java.util.Collection; -import java.util.Iterator; - -/** - * Exception thrown when an option can't be identified from a partial name. - * - * @version $Id: AmbiguousOptionException.java 1669814 2015-03-28 18:09:26Z britter $ - * @since 1.3 - */ -public class AmbiguousOptionException extends UnrecognizedOptionException -{ - /** - * This exception {@code serialVersionUID}. - */ - private static final long serialVersionUID = 5829816121277947229L; - - /** The list of options matching the partial name specified */ - private final Collection matchingOptions; - - /** - * Constructs a new AmbiguousOptionException. - * - * @param option the partial option name - * @param matchingOptions the options matching the name - */ - public AmbiguousOptionException(String option, Collection matchingOptions) - { - super(createMessage(option, matchingOptions), option); - this.matchingOptions = matchingOptions; - } - - /** - * Returns the options matching the partial name. - * @return a collection of options matching the name - */ - public Collection getMatchingOptions() - { - return matchingOptions; - } - - /** - * Build the exception message from the specified list of options. - * - * @param option - * @param matchingOptions - * @return - */ - private static String createMessage(String option, Collection matchingOptions) - { - StringBuilder buf = new StringBuilder("Ambiguous option: '"); - buf.append(option); - buf.append("' (could be: "); - - Iterator it = matchingOptions.iterator(); - while (it.hasNext()) - { - buf.append("'"); - buf.append(it.next()); - buf.append("'"); - if (it.hasNext()) - { - buf.append(", "); - } - } - buf.append(")"); - - return buf.toString(); - } -} diff --git a/src/main/java/org/apache/commons/cli/BasicParser.java b/src/main/java/org/apache/commons/cli/BasicParser.java deleted file mode 100644 index d1c1c0e27..000000000 --- a/src/main/java/org/apache/commons/cli/BasicParser.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.cli; - -/** - * The class BasicParser provides a very simple implementation of - * the {@link Parser#flatten(Options,String[],boolean) flatten} method. - * - * @version $Id: BasicParser.java 1443102 2013-02-06 18:12:16Z tn $ - * @deprecated since 1.3, use the {@link DefaultParser} instead - */ -@Deprecated -public class BasicParser extends Parser -{ - /** - *

A simple implementation of {@link Parser}'s abstract - * {@link Parser#flatten(Options, String[], boolean) flatten} method.

- * - *

Note: options and stopAtNonOption - * are not used in this flatten method.

- * - * @param options The command line {@link Options} - * @param arguments The command line arguments to be parsed - * @param stopAtNonOption Specifies whether to stop flattening - * when an non option is found. - * @return The arguments String array. - */ - @Override - protected String[] flatten(@SuppressWarnings("unused") Options options, - String[] arguments, - @SuppressWarnings("unused") boolean stopAtNonOption) - { - // just echo the arguments - return arguments; - } -} diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java deleted file mode 100644 index bac7bcd13..000000000 --- a/src/main/java/org/apache/commons/cli/CommandLine.java +++ /dev/null @@ -1,380 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.cli; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -/** - * Represents list of arguments parsed against a {@link Options} descriptor. - *

- * It allows querying of a boolean {@link #hasOption(String opt)}, - * in addition to retrieving the {@link #getOptionValue(String opt)} - * for options requiring arguments. - *

- * Additionally, any left-over or unrecognized arguments, - * are available for further processing. - * - * @version $Id: CommandLine.java 1444365 2013-02-09 14:21:27Z tn $ - */ -public class CommandLine implements Serializable -{ - /** The serial version UID. */ - private static final long serialVersionUID = 1L; - - /** the unrecognised options/arguments */ - private final List args = new LinkedList(); - - /** the processed options */ - private final List

Dump state, suitable for debugging.

- * - * @return Stringified form of this object - */ - - /* - public String toString() { - StringBuilder buf = new StringBuilder(); - - buf.append("[ CommandLine: [ options: "); - buf.append(options.toString()); - buf.append(" ] [ args: "); - buf.append(args.toString()); - buf.append(" ] ]"); - - return buf.toString(); - } - */ - - /** - * Add left-over unrecognized option/argument. - * - * @param arg the unrecognised option/argument. - */ - protected void addArg(String arg) - { - args.add(arg); - } - - /** - * Add an option to the command line. The values of the option are stored. - * - * @param opt the processed option - */ - protected void addOption(Option opt) - { - options.add(opt); - } - - /** - * Returns an iterator over the Option members of CommandLine. - * - * @return an Iterator over the processed {@link Option} - * members of this {@link CommandLine} - */ - public Iterator