├── .DS_Store ├── .gitignore ├── LICENSE ├── README.md ├── README_CN.md ├── Screenshot ├── 复杂.gif ├── 快捷键.png └── 简单的.gif ├── ThirdParty ├── json │ └── java │ │ └── src │ │ └── org │ │ └── json │ │ ├── JSONArray.java │ │ ├── JSONException.java │ │ ├── JSONObject.java │ │ ├── JSONString.java │ │ └── JSONTokener.java └── treetable │ └── java │ └── src │ ├── cn │ └── vearn │ │ └── checktreetable │ │ └── FiledTreeTableModel.java │ └── org │ └── jdesktop │ └── swingx │ └── ux │ ├── CellProvider.java │ ├── CheckTreeCellProvider.java │ ├── CheckTreeSelectionModel.java │ ├── CheckTreeTableManager.java │ ├── Selector.java │ └── TristateCheckBox.java ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle ├── src └── main │ ├── java │ └── org │ │ └── gsonformat │ │ └── intellij │ │ ├── ConvertBridge.java │ │ ├── MainAction.java │ │ ├── action │ │ └── DataWriter.java │ │ ├── common │ │ ├── CheckUtil.java │ │ ├── FieldHelper.java │ │ ├── PsiClassUtil.java │ │ ├── StringUtils.java │ │ ├── Try.java │ │ └── Utils.java │ │ ├── config │ │ ├── Config.java │ │ └── Constant.java │ │ ├── entity │ │ ├── ClassEntity.java │ │ ├── ConvertLibrary.java │ │ ├── DataType.java │ │ ├── FieldEntity.java │ │ └── IterableFieldEntity.java │ │ ├── process │ │ ├── AutoValueProcessor.java │ │ ├── ClassProcessor.java │ │ ├── FastJsonProcessor.java │ │ ├── GsonProcessor.java │ │ ├── IProcessor.java │ │ ├── JackProcessor.java │ │ ├── LoganSquareProcessor.java │ │ ├── LombokProcessor.java │ │ ├── OtherProcessor.java │ │ └── Processor.java │ │ └── ui │ │ ├── EditDialog.form │ │ ├── EditDialog.java │ │ ├── ErrorDialog.form │ │ ├── ErrorDialog.java │ │ ├── FieldsDialog.form │ │ ├── FieldsDialog.java │ │ ├── JsonDialog.form │ │ ├── JsonDialog.java │ │ ├── NotificationCenter.java │ │ ├── SettingDialog.form │ │ ├── SettingDialog.java │ │ └── Toast.java │ └── resources │ └── META-INF │ └── plugin.xml └── 测试用例. txt /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DimRed/GsonFormat/e3cf3c3d968b785d47fb1d0ed5e3002541ab4897/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | .gradle 3 | build/ 4 | .gradletasknamecache 5 | .idea 6 | *.iws 7 | /out/ 8 | *.iml 9 | .idea_modules/ 10 | atlassian-ide-plugin.xml 11 | com_crashlytics_export_strings.xml 12 | crashlytics.properties 13 | crashlytics-build.properties 14 | fabric.properties 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | GsonFormat 2 | ------ 3 | [jetbrains](https://plugins.jetbrains.com/plugin/7654?pr=androidstudio) 4 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-GsonFormat-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/1896) 5 | [swift](https://github.com/EnjoySR/ESJsonFormat-Xcode) 6 | [Json Annotation](https://github.com/tianzhijiexian/JsonAnnotation) 7 | [中文Readme](README_CN.md) 8 | 9 | 因为一些因素导致 zzz40500 的账号不可用了. 现在将所有的代码从 [zzz40500](https://github.com/zzz40500/GsonFormat) 迁出至 [DimRed](https://github.com/DimRed/GsonFormat). 所有的维护以及更新也会在新的项目目录下进行.     10 | 11 | This is a plugin you can generate Json model from Json String. 12 | Please do aware **This Plugin is only for Android Studio and IntelliJ IDEA**. 13 | 14 | ## Install 15 | - Using IDE built-in plugin system on Windows: 16 | - File > Settings > Plugins > Browse repositories... > Search for "GsonFormat" > Install Plugin 17 | - Using IDE built-in plugin system on MacOs: 18 | - Preferences > Settings > Plugins > Browse repositories... > Search for "GsonFormat" > Install Plugin 19 | - Manually: 20 | - Download the [latest release](https://github.com/zzz40500/GsonFormat/releases/latest) and install it manually using Preferences > Plugins > Install plugin from disk... 21 | - From official jetbrains store from [download](https://plugins.jetbrains.com/plugin/7654?pr=androidstudio) 22 | 23 | Restart IDE. 24 | 25 | ## Usage 26 | ### Use IDE menu 27 | 28 | ![Generate.png](http://upload-images.jianshu.io/upload_images/166866-2c5168c72b7155ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 29 | 30 | ### Use hotkey 31 | 32 | Default **Option + s**(Mac), **Alt + s** (win) 33 | 34 | You can change the hotkey via: 35 | ![修改快捷键.png](http://upload-images.jianshu.io/upload_images/166866-f9e20ca0ad7b9ae4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 36 | 37 | 38 | ## Demo picture 39 | ![gsonFormat.gif](http://upload-images.jianshu.io/upload_images/166866-ff9dc336af72d7d7.gif?imageMogr2/auto-orient/strip) 40 | 41 | ## Version Info 42 | 43 | v1.2.2 44 | > 45 | * Supports field type changes. 46 | * Supports shortcut to open GsonFormat, default option + s (mac), alt + s (win) 47 | * Support for field name changes. 48 | * Support to add the prefix field. 49 | * Support for multiple conversion libraries (Gson, Jackjson, FastJson, LoganSquare). 50 | * Support for private and public modes. 51 | * Supports filtering of superclass into existing fields. 52 | 53 | ## License 54 | 55 | Copyright 2014 The GsonFormat Authors 56 | 57 | Licensed under the Apache License, Version 2.0 (the "License"); 58 | you may not use this file except in compliance with the License. 59 | You may obtain a copy of the License at 60 | 61 | http://www.apache.org/licenses/LICENSE-2.0 62 | 63 | Unless required by applicable law or agreed to in writing, software 64 | distributed under the License is distributed on an "AS IS" BASIS, 65 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 66 | See the License for the specific language governing permissions and 67 | limitations under the License. 68 | -------------------------------------------------------------------------------- /README_CN.md: -------------------------------------------------------------------------------- 1 | **写在前头:本插件只适用 android studio和 Intellij IDEA 工具,eclipse 的少年无视我吧!!!** 2 | 3 | 这是一个根据JSONObject格式的字符串,自动生成实体类参数. 4 | 5 | [github](https://github.com/zzz40500/GsonFormat) 6 | 7 | [jetbrains](https://plugins.jetbrains.com/plugin/7654?pr=androidstudio) 8 | 9 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-GsonFormat-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/1896) 10 | 11 | [swift 版](https://github.com/EnjoySR/ESJsonFormat-Xcode); 12 | 13 | [Json 新视觉](https://github.com/tianzhijiexian/JsonAnnotation) 14 | 15 | ###**写在前头:本插件只适用 android studio和 Intellij IDEA 工具!!!** 16 | 17 | 18 | ##版本说明 19 | 20 | 版本1.2.2 21 | > 22 | * 支持 field 类型的修改. 23 | * 支持快捷键打开 GsonFormat ,默认为 option+s(mac), alt+s(win) 24 | * 支持 field 名称的修改. 25 | * 支持添加 field 前缀. 26 | * 支持多种转换库 (Gson,Jackjson,FastJson,LoganSquare). 27 | * 支持 private 和 public 两种模式. 28 | * 支持过滤父类已有属性. 29 | 30 | 31 | 32 | ##安装方法 33 | 方法1: 34 | ~~~ 35 | 1.Android studio 36 | File->Settings..->Plugins-->Browse repositores..搜索GsonFormat 37 | 2.安装插件,重启android studio 38 | ~~~ 39 | 40 | 方法2: [下载地址](https://plugins.jetbrains.com/plugin/7654?pr=androidstudio) 41 | ~~~ 42 | 1.下载 GsonFormat.jar , 43 | 2.Android studio File->Settings..->Plugins --> 44 | install plugin from disk..导入下载的 GsonFormat.jar , 45 | 3重启 android studio . 46 | ~~~ 47 | 48 | ##打开方法 49 | 1. 使用Generate的快捷键. 50 | 快捷键:图中选中的部分 51 | ![Generate快捷键.png](http://upload-images.jianshu.io/upload_images/166866-2c5168c72b7155ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 52 | 53 | * 使用 GsonFommat 的快捷键. 54 | 默认 option + s (mac), alt + s (win) 55 | 通过以下方式修改快捷键: 56 | ![修改快捷键.png](http://upload-images.jianshu.io/upload_images/166866-f9e20ca0ad7b9ae4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 57 | 58 | 59 | #使用截图 # 60 | 61 | 62 | ![gsonFormat.gif](http://upload-images.jianshu.io/upload_images/166866-ff9dc336af72d7d7.gif?imageMogr2/auto-orient/strip) 63 | -------------------------------------------------------------------------------- /Screenshot/复杂.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DimRed/GsonFormat/e3cf3c3d968b785d47fb1d0ed5e3002541ab4897/Screenshot/复杂.gif -------------------------------------------------------------------------------- /Screenshot/快捷键.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DimRed/GsonFormat/e3cf3c3d968b785d47fb1d0ed5e3002541ab4897/Screenshot/快捷键.png -------------------------------------------------------------------------------- /Screenshot/简单的.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DimRed/GsonFormat/e3cf3c3d968b785d47fb1d0ed5e3002541ab4897/Screenshot/简单的.gif -------------------------------------------------------------------------------- /ThirdParty/json/java/src/org/json/JSONException.java: -------------------------------------------------------------------------------- 1 | package org.json; 2 | 3 | /** 4 | * The JSONException is thrown by the JSON.org classes when things are amiss. 5 | * 6 | * @author JSON.org 7 | * @version 2014-05-03 8 | */ 9 | public class JSONException extends RuntimeException { 10 | private static final long serialVersionUID = 0; 11 | private Throwable cause; 12 | 13 | /** 14 | * Constructs a JSONException with an explanatory message. 15 | * 16 | * @param message 17 | * Detail about the reason for the exception. 18 | */ 19 | public JSONException(String message) { 20 | super(message); 21 | } 22 | 23 | /** 24 | * Constructs a new JSONException with the specified cause. 25 | * @param cause The cause. 26 | */ 27 | public JSONException(Throwable cause) { 28 | super(cause.getMessage()); 29 | this.cause = cause; 30 | } 31 | 32 | /** 33 | * Returns the cause of this exception or null if the cause is nonexistent 34 | * or unknown. 35 | * 36 | * @return the cause of this exception or null if the cause is nonexistent 37 | * or unknown. 38 | */ 39 | @Override 40 | public Throwable getCause() { 41 | return this.cause; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ThirdParty/json/java/src/org/json/JSONString.java: -------------------------------------------------------------------------------- 1 | package org.json; 2 | /** 3 | * The JSONString interface allows a toJSONString() 4 | * method so that a class can change the behavior of 5 | * JSONObject.toString(), JSONArray.toString(), 6 | * and JSONWriter.value(Object). The 7 | * toJSONString method will be used instead of the default behavior 8 | * of using the Object's toString() method and quoting the result. 9 | */ 10 | public interface JSONString { 11 | /** 12 | * The toJSONString method allows a class to produce its own JSON 13 | * serialization. 14 | * 15 | * @return A strictly syntactically correct JSON text. 16 | */ 17 | public String toJSONString(); 18 | } 19 | -------------------------------------------------------------------------------- /ThirdParty/json/java/src/org/json/JSONTokener.java: -------------------------------------------------------------------------------- 1 | package org.json; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | import java.io.Reader; 8 | import java.io.StringReader; 9 | 10 | /* 11 | Copyright (c) 2002 JSON.org 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy 14 | of this software and associated documentation files (the "Software"), to deal 15 | in the Software without restriction, including without limitation the rights 16 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 17 | copies of the Software, and to permit persons to whom the Software is 18 | furnished to do so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | The Software shall be used for Good, not Evil. 24 | 25 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 27 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 28 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 29 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 30 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 31 | SOFTWARE. 32 | */ 33 | 34 | /** 35 | * A JSONTokener takes a source string and extracts characters and tokens from 36 | * it. It is used by the JSONObject and JSONArray constructors to parse 37 | * JSON source strings. 38 | * @author JSON.org 39 | * @version 2014-05-03 40 | */ 41 | public class JSONTokener { 42 | 43 | private long character; 44 | private boolean eof; 45 | private long index; 46 | private long line; 47 | private char previous; 48 | private Reader reader; 49 | private boolean usePrevious; 50 | 51 | 52 | /** 53 | * Construct a JSONTokener from a Reader. 54 | * 55 | * @param reader A reader. 56 | */ 57 | public JSONTokener(Reader reader) { 58 | this.reader = reader.markSupported() 59 | ? reader 60 | : new BufferedReader(reader); 61 | this.eof = false; 62 | this.usePrevious = false; 63 | this.previous = 0; 64 | this.index = 0; 65 | this.character = 1; 66 | this.line = 1; 67 | } 68 | 69 | 70 | /** 71 | * Construct a JSONTokener from an InputStream. 72 | * @param inputStream The source. 73 | */ 74 | public JSONTokener(InputStream inputStream) throws JSONException { 75 | this(new InputStreamReader(inputStream)); 76 | } 77 | 78 | 79 | /** 80 | * Construct a JSONTokener from a string. 81 | * 82 | * @param s A source string. 83 | */ 84 | public JSONTokener(String s) { 85 | this(new StringReader(s)); 86 | } 87 | 88 | 89 | /** 90 | * Back up one character. This provides a sort of lookahead capability, 91 | * so that you can test for a digit or letter before attempting to parse 92 | * the next number or identifier. 93 | */ 94 | public void back() throws JSONException { 95 | if (this.usePrevious || this.index <= 0) { 96 | throw new JSONException("Stepping back two steps is not supported"); 97 | } 98 | this.index -= 1; 99 | this.character -= 1; 100 | this.usePrevious = true; 101 | this.eof = false; 102 | } 103 | 104 | 105 | /** 106 | * Get the hex value of a character (base16). 107 | * @param c A character between '0' and '9' or between 'A' and 'F' or 108 | * between 'a' and 'f'. 109 | * @return An int between 0 and 15, or -1 if c was not a hex digit. 110 | */ 111 | public static int dehexchar(char c) { 112 | if (c >= '0' && c <= '9') { 113 | return c - '0'; 114 | } 115 | if (c >= 'A' && c <= 'F') { 116 | return c - ('A' - 10); 117 | } 118 | if (c >= 'a' && c <= 'f') { 119 | return c - ('a' - 10); 120 | } 121 | return -1; 122 | } 123 | 124 | public boolean end() { 125 | return this.eof && !this.usePrevious; 126 | } 127 | 128 | 129 | /** 130 | * Determine if the source string still contains characters that next() 131 | * can consume. 132 | * @return true if not yet at the end of the source. 133 | */ 134 | public boolean more() throws JSONException { 135 | this.next(); 136 | if (this.end()) { 137 | return false; 138 | } 139 | this.back(); 140 | return true; 141 | } 142 | 143 | 144 | /** 145 | * Get the next character in the source string. 146 | * 147 | * @return The next character, or 0 if past the end of the source string. 148 | */ 149 | public char next() throws JSONException { 150 | int c; 151 | if (this.usePrevious) { 152 | this.usePrevious = false; 153 | c = this.previous; 154 | } else { 155 | try { 156 | c = this.reader.read(); 157 | } catch (IOException exception) { 158 | throw new JSONException(exception); 159 | } 160 | 161 | if (c <= 0) { // End of stream 162 | this.eof = true; 163 | c = 0; 164 | } 165 | } 166 | this.index += 1; 167 | if (this.previous == '\r') { 168 | this.line += 1; 169 | this.character = c == '\n' ? 0 : 1; 170 | } else if (c == '\n') { 171 | this.line += 1; 172 | this.character = 0; 173 | } else { 174 | this.character += 1; 175 | } 176 | this.previous = (char) c; 177 | return this.previous; 178 | } 179 | 180 | 181 | /** 182 | * Consume the next character, and check that it matches a specified 183 | * character. 184 | * @param c The character to match. 185 | * @return The character. 186 | * @throws JSONException if the character does not match. 187 | */ 188 | public char next(char c) throws JSONException { 189 | char n = this.next(); 190 | if (n != c) { 191 | throw this.syntaxError("Expected '" + c + "' and instead saw '" + 192 | n + "'"); 193 | } 194 | return n; 195 | } 196 | 197 | 198 | /** 199 | * Get the next n characters. 200 | * 201 | * @param n The number of characters to take. 202 | * @return A string of n characters. 203 | * @throws JSONException 204 | * Substring bounds error if there are not 205 | * n characters remaining in the source string. 206 | */ 207 | public String next(int n) throws JSONException { 208 | if (n == 0) { 209 | return ""; 210 | } 211 | 212 | char[] chars = new char[n]; 213 | int pos = 0; 214 | 215 | while (pos < n) { 216 | chars[pos] = this.next(); 217 | if (this.end()) { 218 | throw this.syntaxError("Substring bounds error"); 219 | } 220 | pos += 1; 221 | } 222 | return new String(chars); 223 | } 224 | 225 | 226 | /** 227 | * Get the next char in the string, skipping whitespace. 228 | * @throws JSONException 229 | * @return A character, or 0 if there are no more characters. 230 | */ 231 | public char nextClean() throws JSONException { 232 | for (;;) { 233 | char c = this.next(); 234 | if (c == 0 || c > ' ') { 235 | return c; 236 | } 237 | } 238 | } 239 | 240 | 241 | /** 242 | * Return the characters up to the next close quote character. 243 | * Backslash processing is done. The formal JSON format does not 244 | * allow strings in single quotes, but an implementation is allowed to 245 | * accept them. 246 | * @param quote The quoting character, either 247 | * " (double quote) or 248 | * ' (single quote). 249 | * @return A String. 250 | * @throws JSONException Unterminated string. 251 | */ 252 | public String nextString(char quote) throws JSONException { 253 | char c; 254 | StringBuilder sb = new StringBuilder(); 255 | for (;;) { 256 | c = this.next(); 257 | switch (c) { 258 | case 0: 259 | case '\n': 260 | case '\r': 261 | throw this.syntaxError("Unterminated string"); 262 | case '\\': 263 | c = this.next(); 264 | switch (c) { 265 | case 'b': 266 | sb.append('\b'); 267 | break; 268 | case 't': 269 | sb.append('\t'); 270 | break; 271 | case 'n': 272 | sb.append('\n'); 273 | break; 274 | case 'f': 275 | sb.append('\f'); 276 | break; 277 | case 'r': 278 | sb.append('\r'); 279 | break; 280 | case 'u': 281 | sb.append((char)Integer.parseInt(this.next(4), 16)); 282 | break; 283 | case '"': 284 | case '\'': 285 | case '\\': 286 | case '/': 287 | sb.append(c); 288 | break; 289 | default: 290 | throw this.syntaxError("Illegal escape."); 291 | } 292 | break; 293 | default: 294 | if (c == quote) { 295 | return sb.toString(); 296 | } 297 | sb.append(c); 298 | } 299 | } 300 | } 301 | 302 | 303 | /** 304 | * Get the text up but not including the specified character or the 305 | * end of line, whichever comes first. 306 | * @param delimiter A delimiter character. 307 | * @return A string. 308 | */ 309 | public String nextTo(char delimiter) throws JSONException { 310 | StringBuilder sb = new StringBuilder(); 311 | for (;;) { 312 | char c = this.next(); 313 | if (c == delimiter || c == 0 || c == '\n' || c == '\r') { 314 | if (c != 0) { 315 | this.back(); 316 | } 317 | return sb.toString().trim(); 318 | } 319 | sb.append(c); 320 | } 321 | } 322 | 323 | 324 | /** 325 | * Get the text up but not including one of the specified delimiter 326 | * characters or the end of line, whichever comes first. 327 | * @param delimiters A set of delimiter characters. 328 | * @return A string, trimmed. 329 | */ 330 | public String nextTo(String delimiters) throws JSONException { 331 | char c; 332 | StringBuilder sb = new StringBuilder(); 333 | for (;;) { 334 | c = this.next(); 335 | if (delimiters.indexOf(c) >= 0 || c == 0 || 336 | c == '\n' || c == '\r') { 337 | if (c != 0) { 338 | this.back(); 339 | } 340 | return sb.toString().trim(); 341 | } 342 | sb.append(c); 343 | } 344 | } 345 | 346 | 347 | /** 348 | * Get the next value. The value can be a Boolean, Double, Integer, 349 | * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. 350 | * @throws JSONException If syntax error. 351 | * 352 | * @return An object. 353 | */ 354 | public Object nextValue() throws JSONException { 355 | char c = this.nextClean(); 356 | String string; 357 | 358 | switch (c) { 359 | case '"': 360 | case '\'': 361 | return this.nextString(c); 362 | case '{': 363 | this.back(); 364 | return new JSONObject(this); 365 | case '[': 366 | this.back(); 367 | return new JSONArray(this); 368 | } 369 | 370 | /* 371 | * Handle unquoted text. This could be the values true, false, or 372 | * null, or it can be a number. An implementation (such as this one) 373 | * is allowed to also accept non-standard forms. 374 | * 375 | * Accumulate characters until we reach the end of the text or a 376 | * formatting character. 377 | */ 378 | 379 | StringBuilder sb = new StringBuilder(); 380 | while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { 381 | sb.append(c); 382 | c = this.next(); 383 | } 384 | this.back(); 385 | 386 | string = sb.toString().trim(); 387 | if ("".equals(string)) { 388 | throw this.syntaxError("Missing value"); 389 | } 390 | return JSONObject.stringToValue(string); 391 | } 392 | 393 | 394 | /** 395 | * Skip characters until the next character is the requested character. 396 | * If the requested character is not found, no characters are skipped. 397 | * @param to A character to skip to. 398 | * @return The requested character, or zero if the requested character 399 | * is not found. 400 | */ 401 | public char skipTo(char to) throws JSONException { 402 | char c; 403 | try { 404 | long startIndex = this.index; 405 | long startCharacter = this.character; 406 | long startLine = this.line; 407 | this.reader.mark(1000000); 408 | do { 409 | c = this.next(); 410 | if (c == 0) { 411 | this.reader.reset(); 412 | this.index = startIndex; 413 | this.character = startCharacter; 414 | this.line = startLine; 415 | return c; 416 | } 417 | } while (c != to); 418 | } catch (IOException exception) { 419 | throw new JSONException(exception); 420 | } 421 | this.back(); 422 | return c; 423 | } 424 | 425 | 426 | /** 427 | * Make a JSONException to signal a syntax error. 428 | * 429 | * @param message The error message. 430 | * @return A JSONException object, suitable for throwing 431 | */ 432 | public JSONException syntaxError(String message) { 433 | return new JSONException(message + this.toString()); 434 | } 435 | 436 | 437 | /** 438 | * Make a printable string of this JSONTokener. 439 | * 440 | * @return " at {index} [character {character} line {line}]" 441 | */ 442 | public String toString() { 443 | return " at " + this.index + " [character " + this.character + " line " + 444 | this.line + "]"; 445 | } 446 | } 447 | -------------------------------------------------------------------------------- /ThirdParty/treetable/java/src/cn/vearn/checktreetable/FiledTreeTableModel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package cn.vearn.checktreetable; 6 | 7 | import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; 8 | import org.jdesktop.swingx.treetable.DefaultTreeTableModel; 9 | import org.jdesktop.swingx.treetable.TreeTableNode; 10 | import org.jdesktop.swingx.ux.CellProvider; 11 | 12 | /** 13 | * @author vearn 14 | */ 15 | public class FiledTreeTableModel extends DefaultTreeTableModel { 16 | 17 | private String[] _names = {" Key ", "Value", "Data Type", " Field name "}; 18 | private Class[] _types = {Object.class, Object.class, Object.class, Object.class}; 19 | 20 | 21 | public FiledTreeTableModel(TreeTableNode node) { 22 | super(node); 23 | } 24 | 25 | /** 26 | * 列的类型 27 | */ 28 | @Override 29 | public Class getColumnClass(int col) { 30 | return _types[col]; 31 | } 32 | 33 | /** 34 | * 列的数量 35 | */ 36 | @Override 37 | public int getColumnCount() { 38 | return _names.length; 39 | } 40 | 41 | /** 42 | * 表头显示的内容 43 | */ 44 | @Override 45 | public String getColumnName(int column) { 46 | return _names[column]; 47 | } 48 | 49 | /** 50 | * 返回在单元格中显示的Object 51 | */ 52 | @Override 53 | public Object getValueAt(Object node, int column) { 54 | Object value = ""; 55 | if (node instanceof DefaultMutableTreeTableNode) { 56 | DefaultMutableTreeTableNode mutableNode = (DefaultMutableTreeTableNode) node; 57 | Object o = mutableNode.getUserObject(); 58 | if (o != null && o instanceof CellProvider) { 59 | CellProvider cellProvider = (CellProvider) o; 60 | value = cellProvider.getCellTitle(column); 61 | 62 | } 63 | } 64 | return value; 65 | } 66 | 67 | @Override 68 | public void setValueAt(Object value, Object node, int column) { 69 | super.setValueAt(value, node, column); 70 | if (node instanceof DefaultMutableTreeTableNode) { 71 | DefaultMutableTreeTableNode mutableNode = (DefaultMutableTreeTableNode) node; 72 | Object o = mutableNode.getUserObject(); 73 | if (o != null && o instanceof CellProvider) { 74 | CellProvider cellProvider = (CellProvider) o; 75 | 76 | cellProvider.setValueAt(column,value.toString()); 77 | } 78 | } 79 | } 80 | 81 | 82 | @Override 83 | public boolean isCellEditable(Object node, int column) { 84 | if (column == 2) { 85 | return true; 86 | } 87 | if (column == 3) { 88 | return true; 89 | } 90 | return false; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /ThirdParty/treetable/java/src/org/jdesktop/swingx/ux/CellProvider.java: -------------------------------------------------------------------------------- 1 | package org.jdesktop.swingx.ux; 2 | 3 | /** 4 | * Created by dim on 16/11/7. 5 | */ 6 | public interface CellProvider { 7 | 8 | String getCellTitle(int index); 9 | 10 | void setValueAt(int column, String text); 11 | } 12 | -------------------------------------------------------------------------------- /ThirdParty/treetable/java/src/org/jdesktop/swingx/ux/CheckTreeCellProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package org.jdesktop.swingx.ux; 6 | 7 | import java.awt.BorderLayout; 8 | import javax.swing.JLabel; 9 | import javax.swing.JPanel; 10 | import javax.swing.JTree; 11 | import javax.swing.tree.TreePath; 12 | 13 | import org.gsonformat.intellij.entity.FieldEntity; 14 | import org.gsonformat.intellij.entity.ClassEntity; 15 | import org.jdesktop.swingx.renderer.CellContext; 16 | import org.jdesktop.swingx.renderer.ComponentProvider; 17 | import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; 18 | 19 | /** 20 | * 21 | * @author vearn 22 | */ 23 | public class CheckTreeCellProvider extends ComponentProvider { 24 | 25 | private CheckTreeSelectionModel selectionModel; 26 | private TristateCheckBox _checkBox = null; 27 | private JLabel _label = null; 28 | 29 | public CheckTreeCellProvider(CheckTreeSelectionModel selectionModel) { 30 | this.selectionModel = selectionModel; 31 | _checkBox = new TristateCheckBox(); // 创建一个TristateCheckBox实例 32 | _checkBox.setOpaque(false); // 设置TristateCheckBox不绘制背景 33 | _label = new JLabel(); // 创建一个JLabel实例 34 | } 35 | 36 | @Override 37 | protected void format(CellContext arg0) { 38 | // 从CellContext获取tree中的文字和图标 39 | JTree tree = (JTree) arg0.getComponent(); 40 | DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) arg0.getValue(); 41 | Object obj = node.getUserObject(); 42 | if(obj instanceof FieldEntity){ 43 | _label.setText(((FieldEntity) obj).getKey()); 44 | _checkBox.setSelector((FieldEntity) obj); 45 | }else if(obj instanceof ClassEntity){ 46 | _label.setText(((ClassEntity) obj).getClassName()); 47 | _checkBox.setSelector((ClassEntity) obj); 48 | } 49 | 50 | // _label.setIcon(arg0.getIcon()); 51 | 52 | // 根据selectionModel中的状态来绘制TristateCheckBox的外观 53 | TreePath path = tree.getPathForRow(arg0.getRow()); 54 | if (path != null) { 55 | if (selectionModel.isPathSelected(path, true)) { 56 | _checkBox.setState(Boolean.TRUE); 57 | } else if (selectionModel.isPartiallySelected(path)) { 58 | _checkBox.setState(null); // 注意“部分选中”状态的API 59 | } else { 60 | _checkBox.setState(Boolean.FALSE); 61 | } 62 | } 63 | 64 | // 使用BorderLayout布局,依次放置TristateCheckBox和JLabel 65 | rendererComponent.setLayout(new BorderLayout()); 66 | rendererComponent.add(_checkBox); 67 | rendererComponent.add(_label, BorderLayout.LINE_END); 68 | } 69 | 70 | @Override 71 | protected void configureState(CellContext arg0) { 72 | } 73 | 74 | /** 75 | * 初始化一个JPanel来放置TristateCheckBox和JLabel 76 | */ 77 | @Override 78 | protected JPanel createRendererComponent() { 79 | JPanel panel = new JPanel(); 80 | return panel; 81 | } 82 | } -------------------------------------------------------------------------------- /ThirdParty/treetable/java/src/org/jdesktop/swingx/ux/CheckTreeSelectionModel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package org.jdesktop.swingx.ux; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | import java.util.Stack; 10 | import javax.swing.tree.DefaultTreeSelectionModel; 11 | import javax.swing.tree.TreeModel; 12 | import javax.swing.tree.TreeNode; 13 | import javax.swing.tree.TreePath; 14 | import javax.swing.tree.TreeSelectionModel; 15 | import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; 16 | 17 | /** 18 | * 19 | * @author Santhosh Kumar T - santhosh@in.fiorano.com 20 | */ 21 | public class CheckTreeSelectionModel extends DefaultTreeSelectionModel { 22 | 23 | private TreeModel model; 24 | 25 | public CheckTreeSelectionModel(TreeModel model) { 26 | this.model = model; 27 | setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); 28 | } 29 | 30 | // tests whether there is any unselected node in the subtree of given path 31 | public boolean isPartiallySelected(TreePath path) { 32 | if (isPathSelected(path, true)) { 33 | return false; 34 | } 35 | TreePath[] selectionPaths = getSelectionPaths(); 36 | if (selectionPaths == null) { 37 | return false; 38 | } 39 | for (int j = 0; j < selectionPaths.length; j++) { 40 | if (isDescendant(selectionPaths[j], path)) { 41 | return true; 42 | } 43 | } 44 | return false; 45 | } 46 | 47 | // tells whether given path is selected. 48 | // if dig is true, then a path is assumed to be selected, if 49 | // one of its ancestor is selected. 50 | public boolean isPathSelected(TreePath path, boolean dig) { 51 | if (!dig) { 52 | return super.isPathSelected(path); 53 | } 54 | while (path != null && !super.isPathSelected(path)) { 55 | path = path.getParentPath(); 56 | } 57 | return path != null; 58 | } 59 | 60 | // is path1 descendant of path2 61 | private boolean isDescendant(TreePath path1, TreePath path2) { 62 | Object obj1[] = path1.getPath(); 63 | Object obj2[] = path2.getPath(); 64 | for (int i = 0; i < obj2.length; i++) { 65 | if (obj1[i] != obj2[i]) { 66 | return false; 67 | } 68 | } 69 | return true; 70 | } 71 | 72 | public void addPathsByNodes(List selectedNodes) { 73 | int num = selectedNodes.size(); 74 | TreePath[] tps = new TreePath[num]; 75 | for (int i = 0; i < num; i++) { 76 | DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) selectedNodes.get(i); 77 | tps[i] = new TreePath(getPathToRoot(node)); 78 | } 79 | this.addSelectionPaths(tps); 80 | } 81 | 82 | @Override 83 | public void addSelectionPaths(TreePath[] paths) { 84 | // unselect all descendants of paths[] 85 | for (int i = 0; i < paths.length; i++) { 86 | TreePath path = paths[i]; 87 | TreePath[] selectionPaths = getSelectionPaths(); 88 | if (selectionPaths == null) { 89 | break; 90 | } 91 | ArrayList toBeRemoved = new ArrayList(); 92 | for (int j = 0; j < selectionPaths.length; j++) { 93 | if (isDescendant(selectionPaths[j], path)) { 94 | toBeRemoved.add(selectionPaths[j]); 95 | } 96 | } 97 | super.removeSelectionPaths((TreePath[]) toBeRemoved.toArray(new TreePath[0])); 98 | } 99 | 100 | // if all siblings are selected then unselect them and select parent recursively 101 | // otherwize just select that path. 102 | for (int i = 0; i < paths.length; i++) { 103 | TreePath path = paths[i]; 104 | TreePath temp = null; 105 | while (areSiblingsSelected(path)) { 106 | temp = path; 107 | if (path.getParentPath() == null) { 108 | break; 109 | } 110 | path = path.getParentPath(); 111 | } 112 | if (temp != null) { 113 | if (temp.getParentPath() != null) { 114 | addSelectionPath(temp.getParentPath()); 115 | } else { 116 | if (!isSelectionEmpty()) { 117 | removeSelectionPaths(getSelectionPaths()); 118 | } 119 | super.addSelectionPaths(new TreePath[]{temp}); 120 | } 121 | } else { 122 | super.addSelectionPaths(new TreePath[]{path}); 123 | } 124 | } 125 | } 126 | 127 | // tells whether all siblings of given path are selected. 128 | private boolean areSiblingsSelected(TreePath path) { 129 | TreePath parent = path.getParentPath(); 130 | if (parent == null) { 131 | return true; 132 | } 133 | Object node = path.getLastPathComponent(); 134 | Object parentNode = parent.getLastPathComponent(); 135 | 136 | int childCount = model.getChildCount(parentNode); 137 | for (int i = 0; i < childCount; i++) { 138 | Object childNode = model.getChild(parentNode, i); 139 | if (childNode == node) { 140 | continue; 141 | } 142 | if (!isPathSelected(parent.pathByAddingChild(childNode))) { 143 | return false; 144 | } 145 | } 146 | return true; 147 | } 148 | 149 | @Override 150 | public void removeSelectionPaths(TreePath[] paths) { 151 | for (int i = 0; i < paths.length; i++) { 152 | TreePath path = paths[i]; 153 | if (path.getPathCount() == 1) { 154 | super.removeSelectionPaths(new TreePath[]{path}); 155 | } else { 156 | toggleRemoveSelection(path); 157 | } 158 | } 159 | } 160 | 161 | // if any ancestor node of given path is selected then unselect it 162 | // and selection all its descendants except given path and descendants. 163 | // otherwise just unselect the given path 164 | private void toggleRemoveSelection(TreePath path) { 165 | Stack stack = new Stack(); 166 | TreePath parent = path.getParentPath(); 167 | while (parent != null && !isPathSelected(parent)) { 168 | stack.push(parent); 169 | parent = parent.getParentPath(); 170 | } 171 | if (parent != null) { 172 | stack.push(parent); 173 | } else { 174 | super.removeSelectionPaths(new TreePath[]{path}); 175 | return; 176 | } 177 | 178 | while (!stack.isEmpty()) { 179 | TreePath temp = (TreePath) stack.pop(); 180 | TreePath peekPath = stack.isEmpty() ? path : (TreePath) stack.peek(); 181 | Object node = temp.getLastPathComponent(); 182 | Object peekNode = peekPath.getLastPathComponent(); 183 | int childCount = model.getChildCount(node); 184 | for (int i = 0; i < childCount; i++) { 185 | Object childNode = model.getChild(node, i); 186 | if (childNode != peekNode) { 187 | super.addSelectionPaths(new TreePath[]{temp.pathByAddingChild(childNode)}); 188 | } 189 | } 190 | } 191 | super.removeSelectionPaths(new TreePath[]{parent}); 192 | } 193 | 194 | private TreeNode[] getPathToRoot(TreeNode aNode) { 195 | TreeNode[] retNodes; 196 | ArrayList temp = new ArrayList(); 197 | 198 | /* Check for null, in case someone passed in a null node, or 199 | they passed in an element that isn't rooted at root. */ 200 | while (aNode != null) { 201 | temp.add(aNode); 202 | aNode = aNode.getParent(); 203 | } 204 | 205 | int num = temp.size(); 206 | retNodes = new TreeNode[num]; 207 | for (int i = num - 1; i >= 0; i--) { 208 | retNodes[num - 1 - i] = temp.get(i); 209 | } 210 | 211 | return retNodes; 212 | } 213 | } -------------------------------------------------------------------------------- /ThirdParty/treetable/java/src/org/jdesktop/swingx/ux/CheckTreeTableManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package org.jdesktop.swingx.ux; 6 | 7 | import java.awt.event.MouseAdapter; 8 | import java.awt.event.MouseEvent; 9 | import javax.swing.JCheckBox; 10 | import javax.swing.JTree; 11 | import javax.swing.event.TreeSelectionEvent; 12 | import javax.swing.event.TreeSelectionListener; 13 | import javax.swing.tree.TreePath; 14 | import org.jdesktop.swingx.JXTreeTable; 15 | import org.jdesktop.swingx.renderer.DefaultTreeRenderer; 16 | 17 | /** 18 | * 19 | * @author Santhosh Kumr T - santhosh@in.fiorano.com 20 | */ 21 | public class CheckTreeTableManager extends MouseAdapter implements TreeSelectionListener { 22 | 23 | private CheckTreeSelectionModel selectionModel; 24 | private JXTreeTable treetable; 25 | private JTree tree; 26 | int hotspot = new JCheckBox().getPreferredSize().width; 27 | 28 | public CheckTreeTableManager(JXTreeTable treeTable) { 29 | this.treetable = treeTable; 30 | this.tree = (JTree) treeTable.getCellRenderer(0, 0); 31 | selectionModel = new CheckTreeSelectionModel(tree.getModel()); 32 | tree.setCellRenderer(new DefaultTreeRenderer(new CheckTreeCellProvider(selectionModel))); 33 | treeTable.addMouseListener(this); 34 | 35 | selectionModel.addTreeSelectionListener(this); 36 | } 37 | 38 | @Override 39 | public void mouseClicked(MouseEvent me) { 40 | TreePath path = tree.getPathForLocation(me.getX(), me.getY()); 41 | if (path == null) { 42 | return; 43 | } 44 | if (me.getX() > tree.getPathBounds(path).x + hotspot) { 45 | return; 46 | } 47 | 48 | boolean selected = selectionModel.isPathSelected(path, true); 49 | selectionModel.removeTreeSelectionListener(this); 50 | 51 | try { 52 | if (selected) { 53 | selectionModel.removeSelectionPath(path); 54 | } else { 55 | selectionModel.addSelectionPath(path); 56 | } 57 | } finally { 58 | selectionModel.addTreeSelectionListener(this); 59 | treetable.repaint(); 60 | } 61 | } 62 | 63 | public CheckTreeSelectionModel getSelectionModel() { 64 | return selectionModel; 65 | } 66 | 67 | public void valueChanged(TreeSelectionEvent e) { 68 | } 69 | } -------------------------------------------------------------------------------- /ThirdParty/treetable/java/src/org/jdesktop/swingx/ux/Selector.java: -------------------------------------------------------------------------------- 1 | package org.jdesktop.swingx.ux; 2 | 3 | /** 4 | * Created by dim on 16/11/7. 5 | */ 6 | public interface Selector { 7 | 8 | void setSelect(boolean select); 9 | 10 | } 11 | -------------------------------------------------------------------------------- /ThirdParty/treetable/java/src/org/jdesktop/swingx/ux/TristateCheckBox.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package org.jdesktop.swingx.ux; 6 | 7 | 8 | import javax.swing.*; 9 | import javax.swing.event.ChangeListener; 10 | import javax.swing.plaf.ActionMapUIResource; 11 | import java.awt.event.*; 12 | 13 | /** 14 | * Maintenance tip - There were some tricks to getting this code 15 | * working: 16 | * 17 | * 1. You have to overwite addMouseListener() to do nothing 18 | * 2. You have to add a mouse event on mousePressed by calling 19 | * super.addMouseListener() 20 | * 3. You have to replace the UIActionMap for the keyboard event 21 | * "pressed" with your own one. 22 | * 4. You have to remove the UIActionMap for the keyboard event 23 | * "released". 24 | * 5. You have to grab focus when the next state is entered, 25 | * otherwise clicking on the component won't get the focus. 26 | * 6. You have to make a TristateDecorator as a button model that 27 | * wraps the original button model and does state management. 28 | */ 29 | public class TristateCheckBox extends JCheckBox { 30 | 31 | private final TristateDecorator decorator; 32 | 33 | private Selector selector; 34 | 35 | 36 | 37 | public void setSelector(Selector selector) { 38 | this.selector = selector; 39 | } 40 | 41 | public TristateCheckBox(String text, Icon icon, Boolean initial) { 42 | super(text, icon); 43 | // Add a listener for when the mouse is pressed 44 | super.addMouseListener(new MouseAdapter() { 45 | 46 | @Override 47 | public void mousePressed(MouseEvent e) { 48 | grabFocus(); 49 | decorator.nextState(); 50 | } 51 | }); 52 | // Reset the keyboard action map 53 | ActionMap map = new ActionMapUIResource(); 54 | map.put("pressed", new AbstractAction() { //NOI18N 55 | 56 | public void actionPerformed(ActionEvent e) { 57 | grabFocus(); 58 | decorator.nextState(); 59 | } 60 | }); 61 | map.put("released", null); //NOI18N 62 | SwingUtilities.replaceUIActionMap(this, map); 63 | // set the model to the adapted model 64 | decorator = new TristateDecorator(getModel()); 65 | setModel(decorator); 66 | setState(initial); 67 | } 68 | 69 | public TristateCheckBox(String text, Boolean initial) { 70 | this(text, null, initial); 71 | } 72 | 73 | public TristateCheckBox(String text) { 74 | this(text, true); 75 | } 76 | 77 | public TristateCheckBox() { 78 | this(null); 79 | } 80 | 81 | /** No one may add mouse listeners, not even Swing! */ 82 | @Override 83 | public void addMouseListener(MouseListener l) { 84 | } 85 | 86 | /** 87 | * Set the new state to either SELECTED, NOT_SELECTED or 88 | * DONT_CARE. If state == null, it is treated as DONT_CARE. 89 | */ 90 | public void setState(Boolean state) { 91 | decorator.setState(state); 92 | } 93 | 94 | /** Return the current state, which is determined by the 95 | * selection status of the model. */ 96 | public Boolean getState() { 97 | return decorator.getState(); 98 | } 99 | 100 | /** 101 | * Exactly which Design Pattern is this? Is it an Adapter, 102 | * a Proxy or a Decorator? In this case, my vote lies with the 103 | * Decorator, because we are extending functionality and 104 | * "decorating" the original model with a more powerful model. 105 | */ 106 | private class TristateDecorator implements ButtonModel { 107 | 108 | private final ButtonModel other; 109 | 110 | private TristateDecorator(ButtonModel other) { 111 | this.other = other; 112 | } 113 | 114 | private void setState(Boolean state) { 115 | if (state == Boolean.FALSE) { 116 | other.setArmed(false); 117 | if(selector != null){ 118 | selector.setSelect(false); 119 | } 120 | setPressed(false); 121 | setSelected(false); 122 | } else if (state == Boolean.TRUE) { 123 | other.setArmed(false); 124 | setPressed(false); 125 | setSelected(true); 126 | if(selector != null){ 127 | selector.setSelect(true); 128 | } 129 | } else { 130 | other.setArmed(true); 131 | setPressed(true); 132 | setSelected(true); 133 | if(selector != null){ 134 | selector.setSelect(true); 135 | } 136 | 137 | } 138 | } 139 | 140 | /** 141 | * The current state is embedded in the selection / armed 142 | * state of the model. 143 | * 144 | * We return the SELECTED state when the checkbox is selected 145 | * but not armed, DONT_CARE state when the checkbox is 146 | * selected and armed (grey) and NOT_SELECTED when the 147 | * checkbox is deselected. 148 | */ 149 | private Boolean getState() { 150 | if (isSelected() && !isArmed()) { 151 | // normal black tick 152 | return Boolean.TRUE; 153 | } else if (isSelected() && isArmed()) { 154 | // don't care grey tick 155 | return null; 156 | } else { 157 | // normal deselected 158 | return Boolean.FALSE; 159 | } 160 | } 161 | 162 | /** We rotate between NOT_SELECTED, SELECTED and DONT_CARE.*/ 163 | private void nextState() { 164 | Boolean current = getState(); 165 | if (current == Boolean.FALSE) { 166 | setState(Boolean.TRUE); 167 | } else if (current == Boolean.TRUE) { 168 | setState(null); 169 | } else if (current == null) { 170 | setState(Boolean.FALSE); 171 | } 172 | } 173 | 174 | /** Filter: No one may change the armed status except us. */ 175 | public void setArmed(boolean b) { 176 | } 177 | 178 | public boolean isFocusTraversable() { 179 | return isEnabled(); 180 | } 181 | 182 | /** We disable focusing on the component when it is not 183 | * enabled. */ 184 | public void setEnabled(boolean b) { 185 | // setFocusable(b); 186 | other.setEnabled(b); 187 | } 188 | 189 | /** All these methods simply delegate to the "other" model 190 | * that is being decorated. */ 191 | public boolean isArmed() { 192 | return other.isArmed(); 193 | } 194 | 195 | public boolean isSelected() { 196 | return other.isSelected(); 197 | } 198 | 199 | public boolean isEnabled() { 200 | return other.isEnabled(); 201 | } 202 | 203 | public boolean isPressed() { 204 | return other.isPressed(); 205 | } 206 | 207 | public boolean isRollover() { 208 | return other.isRollover(); 209 | } 210 | 211 | public void setSelected(boolean b) { 212 | other.setSelected(b); 213 | } 214 | 215 | public void setPressed(boolean b) { 216 | other.setPressed(b); 217 | } 218 | 219 | public void setRollover(boolean b) { 220 | other.setRollover(b); 221 | } 222 | 223 | public void setMnemonic(int key) { 224 | other.setMnemonic(key); 225 | } 226 | 227 | public int getMnemonic() { 228 | return other.getMnemonic(); 229 | } 230 | 231 | public void setActionCommand(String s) { 232 | other.setActionCommand(s); 233 | } 234 | 235 | public String getActionCommand() { 236 | return other.getActionCommand(); 237 | } 238 | 239 | public void setGroup(ButtonGroup group) { 240 | other.setGroup(group); 241 | } 242 | 243 | public void addActionListener(ActionListener l) { 244 | other.addActionListener(l); 245 | } 246 | 247 | public void removeActionListener(ActionListener l) { 248 | other.removeActionListener(l); 249 | } 250 | 251 | public void addItemListener(ItemListener l) { 252 | other.addItemListener(l); 253 | } 254 | 255 | public void removeItemListener(ItemListener l) { 256 | other.removeItemListener(l); 257 | } 258 | 259 | public void addChangeListener(ChangeListener l) { 260 | other.addChangeListener(l); 261 | } 262 | 263 | public void removeChangeListener(ChangeListener l) { 264 | other.removeChangeListener(l); 265 | } 266 | 267 | public Object[] getSelectedObjects() { 268 | return other.getSelectedObjects(); 269 | } 270 | } 271 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | maven { url 'http://dl.bintray.com/jetbrains/intellij-plugin-service' } 4 | } 5 | } 6 | plugins { 7 | id "org.jetbrains.intellij" version "0.1.10" 8 | } 9 | 10 | apply plugin: 'org.jetbrains.intellij' 11 | apply plugin: 'java' 12 | // dependencies { 13 | // compile project(':ThirdPart:checktreetable') 14 | // compile project(':ThirdPart:json') 15 | // } 16 | sourceSets { 17 | main { 18 | java { 19 | srcDir "${project.rootDir.absolutePath}/ThirdParty/json/java/src" 20 | srcDir "${project.rootDir.absolutePath}/ThirdParty/treetable/java/src" 21 | } 22 | 23 | } 24 | } 25 | intellij { 26 | version 'IC-2016.2.5' 27 | pluginName 'GsonFormat' 28 | updateSinceUntilBuild false 29 | 30 | // publish { 31 | // pluginId '7910' 32 | // username publishUsername 33 | // password publishPassword 34 | // } 35 | 36 | // Uncomment to test against Android Studio 37 | // intellij.alternativeIdePath = '/Applications/Android Studio.app' 38 | } 39 | 40 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DimRed/GsonFormat/e3cf3c3d968b785d47fb1d0ed5e3002541ab4897/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Oct 24 12:20:13 CST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 165 | if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then 166 | cd "$(dirname "$0")" 167 | fi 168 | 169 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 170 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This settings file was auto generated by the Gradle buildInit task 3 | * by 'gengjiawen' at '10/24/16 12:20 PM' with Gradle 3.1 4 | * 5 | * The settings file is used to specify which projects to include in your build. 6 | * In a single project build this file can be empty or even removed. 7 | * 8 | * Detailed information about configuring a multi-project build in Gradle can be found 9 | * in the user guide at https://docs.gradle.org/3.1/userguide/multi_project_builds.html 10 | */ 11 | 12 | /* 13 | // To declare projects as part of a multi-project build use the 'include' method 14 | include 'shared' 15 | include 'api' 16 | include 'services:webservice' 17 | */ 18 | rootProject.name = 'GsonFormat' 19 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/MainAction.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij; 2 | 3 | import com.intellij.codeInsight.CodeInsightActionHandler; 4 | import com.intellij.codeInsight.generation.actions.BaseGenerateAction; 5 | import com.intellij.openapi.actionSystem.AnActionEvent; 6 | import com.intellij.openapi.actionSystem.PlatformDataKeys; 7 | import com.intellij.openapi.editor.Editor; 8 | import com.intellij.openapi.project.Project; 9 | import com.intellij.psi.PsiClass; 10 | import com.intellij.psi.PsiFile; 11 | import com.intellij.psi.util.PsiUtilBase; 12 | import org.gsonformat.intellij.ui.JsonDialog; 13 | 14 | /** 15 | * User: dim 16 | * Date: 14-7-4 17 | * Time: 下午1:44 18 | */ 19 | public class MainAction extends BaseGenerateAction { 20 | 21 | @SuppressWarnings("unused") 22 | public MainAction() { 23 | super(null); 24 | } 25 | 26 | @SuppressWarnings("unused") 27 | public MainAction(CodeInsightActionHandler handler) { 28 | super(handler); 29 | } 30 | 31 | @Override 32 | protected boolean isValidForClass(final PsiClass targetClass) { 33 | return super.isValidForClass(targetClass); 34 | } 35 | 36 | @Override 37 | public boolean isValidForFile(Project project, Editor editor, PsiFile file) { 38 | return super.isValidForFile(project, editor, file); 39 | } 40 | 41 | public void actionPerformed(AnActionEvent event) { 42 | Project project = event.getData(PlatformDataKeys.PROJECT); 43 | Editor editor = event.getData(PlatformDataKeys.EDITOR); 44 | PsiFile mFile = PsiUtilBase.getPsiFileInEditor(editor, project); 45 | PsiClass psiClass = getTargetClass(editor, mFile); 46 | JsonDialog jsonD = new JsonDialog(psiClass, mFile, project); 47 | jsonD.setClass(psiClass); 48 | jsonD.setFile(mFile); 49 | jsonD.setProject(project); 50 | jsonD.setSize(600, 400); 51 | jsonD.setLocationRelativeTo(null); 52 | jsonD.setVisible(true); 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/action/DataWriter.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.action; 2 | 3 | import com.intellij.openapi.application.RunResult; 4 | import com.intellij.openapi.command.WriteCommandAction; 5 | import com.intellij.openapi.progress.ProgressIndicator; 6 | import com.intellij.openapi.progress.ProgressManager; 7 | import com.intellij.openapi.progress.Task; 8 | import com.intellij.openapi.project.Project; 9 | import com.intellij.openapi.ui.MessageType; 10 | import com.intellij.psi.JavaPsiFacade; 11 | import com.intellij.psi.PsiClass; 12 | import com.intellij.psi.PsiElementFactory; 13 | import com.intellij.psi.PsiFile; 14 | import org.gsonformat.intellij.entity.ClassEntity; 15 | import org.gsonformat.intellij.process.ClassProcessor; 16 | import org.gsonformat.intellij.process.IProcessor; 17 | import org.gsonformat.intellij.ui.Toast; 18 | import org.jetbrains.annotations.NotNull; 19 | 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | 23 | /** 24 | * Created with IntelliJ IDEA. 25 | * User: dim 26 | * Date: 14-7-4 27 | * Time: 下午3:58 28 | */ 29 | public class DataWriter extends WriteCommandAction.Simple { 30 | 31 | private PsiClass cls; 32 | private PsiElementFactory factory; 33 | private Project project; 34 | private PsiFile file; 35 | private ClassEntity targetClass; 36 | private List generateClassList = new ArrayList<>(); 37 | 38 | public DataWriter(PsiFile file, Project project, PsiClass cls) { 39 | super(project, file); 40 | factory = JavaPsiFacade.getElementFactory(project); 41 | this.file = file; 42 | this.project = project; 43 | this.cls = cls; 44 | } 45 | 46 | public void execute(ClassEntity targetClass) { 47 | this.targetClass = targetClass; 48 | ProgressManager.getInstance().run(new Task.Backgroundable(project, "GsonFormat") { 49 | 50 | @Override 51 | public void run(@NotNull ProgressIndicator progressIndicator) { 52 | progressIndicator.setIndeterminate(true); 53 | long currentTimeMillis = System.currentTimeMillis(); 54 | execute(); 55 | progressIndicator.setIndeterminate(false); 56 | progressIndicator.setFraction(1.0); 57 | StringBuffer sb = new StringBuffer(); 58 | sb.append("GsonFormat [" + (System.currentTimeMillis() - currentTimeMillis) + " ms]\n"); 59 | // sb.append("generate class : ( "+generateClassList.size()+" )\n"); 60 | // for (String item: generateClassList) { 61 | // sb.append(" at "+item+"\n"); 62 | // } 63 | // sb.append(" \n"); 64 | // NotificationCenter.info(sb.toString()); 65 | Toast.make(project, MessageType.INFO, sb.toString()); 66 | } 67 | }); 68 | } 69 | 70 | @NotNull 71 | @Override 72 | @Deprecated() 73 | public RunResult execute() { 74 | return super.execute(); 75 | } 76 | 77 | @Override 78 | protected void run() { 79 | if (targetClass == null) { 80 | return; 81 | } 82 | generateClassList.clear(); 83 | new ClassProcessor(factory, cls).generate(targetClass, new IProcessor() { 84 | @Override 85 | public void onStarProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls) { 86 | generateClassList.add(cls.getQualifiedName()); 87 | } 88 | 89 | @Override 90 | public void onEndProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls) { 91 | 92 | } 93 | 94 | @Override 95 | public void onStartGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass) { 96 | 97 | } 98 | 99 | @Override 100 | public void onEndGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, PsiClass generateClass) { 101 | generateClassList.add(generateClass.getQualifiedName()); 102 | 103 | } 104 | }); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/common/CheckUtil.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.common; 2 | 3 | import org.gsonformat.intellij.config.Constant; 4 | 5 | import java.util.ArrayList; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Set; 9 | import java.util.regex.Matcher; 10 | import java.util.regex.Pattern; 11 | 12 | /** 13 | * Created by dim on 2015/8/21. 14 | */ 15 | public class CheckUtil { 16 | 17 | private static CheckUtil sCheckUtil; 18 | private List keyWordList = new ArrayList(); 19 | private List simpleTypeList = new ArrayList(); 20 | private Set declareClassNameList = new HashSet(); 21 | private Set declareFieldNameList = new HashSet(); 22 | private static Pattern sPattern = Pattern.compile("^\\d+"); 23 | 24 | private CheckUtil() { 25 | keyWordList.add("abstract"); 26 | keyWordList.add("assert"); 27 | keyWordList.add("boolean"); 28 | keyWordList.add("break"); 29 | keyWordList.add("byte"); 30 | keyWordList.add("case"); 31 | keyWordList.add("catch"); 32 | keyWordList.add("char"); 33 | keyWordList.add("class"); 34 | keyWordList.add("const"); 35 | keyWordList.add("continue"); 36 | keyWordList.add("default"); 37 | keyWordList.add("do"); 38 | keyWordList.add("double"); 39 | keyWordList.add("else"); 40 | keyWordList.add("enum"); 41 | keyWordList.add("extends"); 42 | keyWordList.add("final"); 43 | keyWordList.add("finally"); 44 | keyWordList.add("float"); 45 | keyWordList.add("for"); 46 | keyWordList.add("goto"); 47 | keyWordList.add("if"); 48 | keyWordList.add("implements"); 49 | keyWordList.add("import"); 50 | keyWordList.add("instanceof"); 51 | keyWordList.add("int"); 52 | keyWordList.add("interface"); 53 | keyWordList.add("long"); 54 | keyWordList.add("native"); 55 | keyWordList.add("new"); 56 | keyWordList.add("package"); 57 | keyWordList.add("private"); 58 | keyWordList.add("protected"); 59 | keyWordList.add("public"); 60 | keyWordList.add("return"); 61 | keyWordList.add("strictfp"); 62 | keyWordList.add("short"); 63 | keyWordList.add("static"); 64 | keyWordList.add("super"); 65 | keyWordList.add("switch"); 66 | keyWordList.add("synchronized"); 67 | keyWordList.add("this"); 68 | keyWordList.add("throw"); 69 | keyWordList.add("throws"); 70 | keyWordList.add("transient"); 71 | keyWordList.add("try"); 72 | keyWordList.add("abstract"); 73 | keyWordList.add("void"); 74 | keyWordList.add("volatile"); 75 | keyWordList.add("while"); 76 | 77 | simpleTypeList.add("String"); 78 | simpleTypeList.add("boolean"); 79 | simpleTypeList.add("Boolean"); 80 | simpleTypeList.add("int"); 81 | simpleTypeList.add("Integer"); 82 | simpleTypeList.add("Float"); 83 | simpleTypeList.add("float"); 84 | simpleTypeList.add("Double"); 85 | simpleTypeList.add("double"); 86 | simpleTypeList.add("Long"); 87 | simpleTypeList.add("long"); 88 | } 89 | 90 | public static CheckUtil getInstant() { 91 | if (sCheckUtil == null) { 92 | sCheckUtil = new CheckUtil(); 93 | } 94 | return sCheckUtil; 95 | } 96 | 97 | public void cleanDeclareData() { 98 | declareClassNameList.clear(); 99 | declareFieldNameList.clear(); 100 | } 101 | 102 | 103 | public boolean containsDeclareClassName(String name) { 104 | return declareClassNameList.contains(name); 105 | } 106 | 107 | public void addDeclareClassName(String name) { 108 | declareClassNameList.add(name.replace(".java", "")); 109 | } 110 | 111 | public void removeDeclareClassName(String name) { 112 | declareClassNameList.remove(name); 113 | } 114 | 115 | public boolean containsDeclareFieldName(String name) { 116 | return declareFieldNameList.contains(name); 117 | } 118 | 119 | public void addDeclareFieldName(String name) { 120 | declareFieldNameList.add(name); 121 | } 122 | 123 | public void removeDeclareFieldName(String name) { 124 | declareFieldNameList.remove(name); 125 | } 126 | 127 | public boolean checkSimpleType(String s) { 128 | 129 | return simpleTypeList.contains(s); 130 | } 131 | 132 | public boolean checkKeyWord(String key) { 133 | return keyWordList.contains(key); 134 | } 135 | 136 | public String handleArg(String arg) { 137 | 138 | arg = arg.replaceAll("-", ""); 139 | Matcher matcher = sPattern.matcher(arg); 140 | if (matcher.find()) { 141 | return Constant.DEFAULT_PREFIX + arg; 142 | } else { 143 | if (CheckUtil.getInstant().checkKeyWord(arg)) { 144 | return arg + "X"; 145 | } 146 | return arg; 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/common/FieldHelper.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.common; 2 | 3 | 4 | import org.gsonformat.intellij.config.Constant; 5 | 6 | import java.util.Random; 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | 10 | /** 11 | * Created by dim on 17/1/21. 12 | */ 13 | public class FieldHelper { 14 | 15 | 16 | public static String generateLuckyFieldName(String name) { 17 | 18 | if (name == null) { 19 | return Constant.DEFAULT_PREFIX + new Random().nextInt(333); 20 | } 21 | Matcher matcher = Pattern.compile("(\\w+)").matcher(name); 22 | StringBuilder sb = new StringBuilder("_$"); 23 | while (matcher.find()) { 24 | sb.append(StringUtils.captureName(matcher.group(1))); 25 | } 26 | return sb.append(new Random().nextInt(333)).toString(); 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/common/PsiClassUtil.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.common; 2 | 3 | import com.intellij.ide.util.DirectoryUtil; 4 | import com.intellij.openapi.fileEditor.FileEditorManager; 5 | import com.intellij.openapi.project.Project; 6 | import com.intellij.psi.*; 7 | import com.intellij.psi.impl.source.PsiJavaFileImpl; 8 | import com.intellij.psi.search.EverythingGlobalScope; 9 | import com.intellij.psi.search.GlobalSearchScope; 10 | import org.apache.http.util.TextUtils; 11 | 12 | import java.io.File; 13 | 14 | /** 15 | * Created by dim on 15/8/22. 16 | */ 17 | public class PsiClassUtil { 18 | 19 | 20 | public static PsiClass exist(PsiFile psiFile, String generateClass) { 21 | PsiClass psiClass = null; 22 | PsiDirectory psiDirectory = getJavaSrc(psiFile); 23 | if (psiDirectory == null || psiDirectory.getVirtualFile().getCanonicalPath() == null) { 24 | return null; 25 | } 26 | 27 | File file = new File(psiDirectory.getVirtualFile().getCanonicalPath().concat("/") 28 | .concat(generateClass.trim().replace(".", "/")).concat(".java")); 29 | 30 | String[] strArray = generateClass.replace(" ", "").split("\\."); 31 | if (TextUtils.isEmpty(generateClass)) { 32 | return null; 33 | } 34 | String className = strArray[strArray.length - 1]; 35 | String packName = generateClass.substring(generateClass.length() - className.length(), generateClass.length()); 36 | if (file.exists()) { 37 | for (int i = 0; i < strArray.length - 1; i++) { 38 | psiDirectory = psiDirectory.findSubdirectory(strArray[i]); 39 | if (psiDirectory == null) { 40 | return null; 41 | } 42 | } 43 | PsiFile psiFile1 = psiDirectory.findFile(className + ".java"); 44 | if ((psiFile1 instanceof PsiJavaFile) && ((PsiJavaFile) psiFile1).getClasses().length > 0) { 45 | psiClass = ((PsiJavaFile) psiFile1).getClasses()[0]; 46 | } 47 | } 48 | return psiClass; 49 | } 50 | 51 | public static PsiDirectory getJavaSrc(PsiFile psiFile) { 52 | PsiDirectory psiDirectory = null; 53 | if (psiFile instanceof PsiJavaFileImpl) { 54 | String packageName = ((PsiJavaFileImpl) psiFile).getPackageName(); 55 | String[] arg = packageName.split("\\."); 56 | psiDirectory = psiFile.getContainingDirectory(); 57 | 58 | for (int i = 0; i < arg.length; i++) { 59 | psiDirectory = psiDirectory.getParent(); 60 | if (psiDirectory == null) { 61 | break; 62 | } 63 | } 64 | } 65 | return psiDirectory; 66 | } 67 | 68 | public static File getPackageFile(PsiFile psiFile, String packageName) { 69 | PsiDirectory psiDirectory = getJavaSrc(psiFile); 70 | if (psiDirectory == null || psiDirectory.getVirtualFile().getCanonicalPath() == null) { 71 | return null; 72 | } 73 | 74 | if (packageName == null) { 75 | return new File(psiDirectory.getVirtualFile().getCanonicalPath()); 76 | } 77 | File file = new File(psiDirectory.getVirtualFile().getCanonicalPath().concat("/") 78 | .concat(packageName.trim().replace(".", "/"))); 79 | if (file.exists()) { 80 | return file; 81 | } 82 | return null; 83 | } 84 | 85 | 86 | public static PsiClass getPsiClass(PsiFile psiFile, Project project, String generateClass) throws Throwable { 87 | 88 | PsiClass psiClass = null; 89 | PsiDirectory psiDirectory = getJavaSrc(psiFile); 90 | 91 | if (psiDirectory == null || psiDirectory.getVirtualFile().getCanonicalPath() == null) { 92 | return null; 93 | } 94 | 95 | File file = new File(psiDirectory.getVirtualFile().getCanonicalPath().concat("/") 96 | .concat(generateClass.trim().replace(".", "/")).concat(".java")); 97 | 98 | String[] strArray = generateClass.replace(" ", "").split("\\."); 99 | if (TextUtils.isEmpty(generateClass)) { 100 | return null; 101 | } 102 | String className = strArray[strArray.length - 1]; 103 | String packName = generateClass.substring(0, generateClass.length() - className.length()); 104 | if (file.exists()) { 105 | for (int i = 0; i < strArray.length - 1; i++) { 106 | psiDirectory = psiDirectory.findSubdirectory(strArray[i]); 107 | if (psiDirectory == null) { 108 | return null; 109 | } 110 | } 111 | PsiFile psiFile1 = psiDirectory.findFile(className + ".java"); 112 | if ((psiFile1 instanceof PsiJavaFile) && ((PsiJavaFile) psiFile1).getClasses().length > 0) { 113 | psiClass = ((PsiJavaFile) psiFile1).getClasses()[0]; 114 | } 115 | if (psiClass != null) { 116 | FileEditorManager manager = FileEditorManager.getInstance(project); 117 | manager.openFile(psiClass.getContainingFile().getVirtualFile(), true, true); 118 | } 119 | 120 | } else { 121 | if (!file.getParentFile().exists() && !TextUtils.isEmpty(packName)) { 122 | psiDirectory = createPackageInSourceRoot(packName, psiDirectory); 123 | 124 | } else { 125 | for (int i = 0; i < strArray.length - 1; i++) { 126 | psiDirectory = psiDirectory.findSubdirectory(strArray[i]); 127 | if (psiDirectory == null) { 128 | return null; 129 | } 130 | } 131 | } 132 | 133 | psiClass = JavaDirectoryService.getInstance().createClass(psiDirectory, className); 134 | FileEditorManager manager = FileEditorManager.getInstance(project); 135 | manager.openFile(psiClass.getContainingFile().getVirtualFile(), true, true); 136 | } 137 | 138 | return psiClass; 139 | } 140 | 141 | public static PsiDirectory createPackageInSourceRoot(String packageName, PsiDirectory sourcePackageRoot) { 142 | return DirectoryUtil.createSubdirectories(packageName, sourcePackageRoot, "."); 143 | } 144 | 145 | private PsiClass getPsiClassByName(Project project, String cls) { 146 | GlobalSearchScope searchScope = GlobalSearchScope.allScope(project); 147 | JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project); 148 | return javaPsiFacade.findClass(cls, searchScope); 149 | } 150 | 151 | 152 | public static String getPackage(PsiClass cls) { 153 | if (cls.getQualifiedName() == null) { 154 | return null; 155 | } 156 | int i = cls.getQualifiedName().lastIndexOf("."); 157 | if (i > -1) { 158 | return cls.getQualifiedName().substring(0, i); 159 | } else { 160 | return ""; 161 | } 162 | } 163 | 164 | public static boolean isClassAvailableForProject(Project project, String className) { 165 | PsiClass classInModule = JavaPsiFacade.getInstance(project).findClass(className, 166 | new EverythingGlobalScope(project)); 167 | return classInModule != null; 168 | } 169 | 170 | 171 | // public static a(PsiElementFactory factory){ 172 | // PsiElement psiElement = cls.addAfter(factory.createCommentFromText("// todo dim " + fieldEntity.getFieldName(), cls), add); 173 | //// CharTable charTableByTree = SharedImplUtil.findCharTableByTree( 174 | //// (ASTNode) psiElement); 175 | //// PsiWhiteSpace psiWhiteSpace = (PsiWhiteSpace) Factory.createSingleLeafElement(TokenType.WHITE_SPACE, "\n\n", 176 | //// charTableByTree, PsiManager.getInstance(cls.getProject())); 177 | //// cls.addAfter(psiWhiteSpace, psiElement); 178 | // } 179 | 180 | } 181 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/common/StringUtils.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.common; 2 | 3 | import org.apache.http.util.TextUtils; 4 | 5 | /** 6 | * Created by dim on 16/11/5. 7 | */ 8 | public class StringUtils { 9 | 10 | /** 11 | * 转成驼峰 12 | * 13 | * @param text 14 | * @return 15 | */ 16 | public static String captureStringLeaveUnderscore(String text) { 17 | if (TextUtils.isEmpty(text)) { 18 | return text; 19 | } 20 | String temp = text.replaceAll("^_+", ""); 21 | 22 | if (!TextUtils.isEmpty(temp)) { 23 | text = temp; 24 | } 25 | String[] strings = text.split("_"); 26 | StringBuilder stringBuilder = new StringBuilder(); 27 | stringBuilder.append(strings[0]); 28 | for (int i = 1; i < strings.length; i++) { 29 | stringBuilder.append(captureName(strings[i])); 30 | } 31 | return stringBuilder.toString(); 32 | } 33 | 34 | public static String captureName(String text) { 35 | 36 | if (text.length() > 0) { 37 | text = text.substring(0, 1).toUpperCase() + text.substring(1); 38 | } 39 | return text; 40 | } 41 | 42 | public static String getPackage(String generateClassName) { 43 | int index = generateClassName.lastIndexOf("."); 44 | if (index > 0) { 45 | return generateClassName.substring(0, index); 46 | } 47 | return null; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/common/Try.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.common; 2 | 3 | /** 4 | * Created by dim on 17/1/21. 5 | */ 6 | public class Try { 7 | 8 | public static void run(TryListener tryListener) { 9 | try { 10 | tryListener.run(); 11 | } catch (Exception e) { 12 | e.printStackTrace(); 13 | try { 14 | tryListener.runAgain(); 15 | } catch (Exception e1) { 16 | e1.printStackTrace(); 17 | try { 18 | tryListener.error(); 19 | }catch (Exception e3){ 20 | e3.printStackTrace(); 21 | } 22 | } 23 | } 24 | } 25 | 26 | public interface TryListener { 27 | void run(); 28 | void runAgain(); 29 | void error(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/common/Utils.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.common; 2 | 3 | import org.json.JSONObject; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Created by dim on 16/11/7. 9 | */ 10 | public class Utils { 11 | 12 | public static String createCommentString(JSONObject json, List filedList) { 13 | StringBuilder sb = new StringBuilder(); 14 | sb.append("/** \n"); 15 | for (int i = 0; i < filedList.size(); i++) { 16 | String key = filedList.get(i); 17 | sb.append("* ").append(key).append(" : "); 18 | sb.append(json.get(key).toString().replaceAll("\r", "") 19 | .replaceAll("\t ", "").replaceAll("\f", "")); 20 | sb.append("\n"); 21 | } 22 | sb.append("*/ \n"); 23 | return sb.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/config/Config.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.config; 2 | 3 | import com.intellij.ide.util.PropertiesComponent; 4 | 5 | /** 6 | * Created by dim on 15/5/31. 7 | */ 8 | public class Config { 9 | 10 | private static Config config; 11 | 12 | private boolean fieldPrivateMode = true; 13 | private boolean generateComments = true; 14 | private boolean useSerializedName = false; 15 | private boolean objectFromData = false; 16 | private boolean objectFromData1 = false; 17 | private boolean arrayFromData = false; 18 | private boolean arrayFromData1 = false; 19 | private boolean reuseEntity = false; 20 | private boolean virgoMode = true; //处女座模式 21 | private boolean useFieldNamePrefix = false; 22 | private boolean splitGenerate = false; 23 | 24 | 25 | private String objectFromDataStr; 26 | private String objectFromDataStr1; 27 | private String arrayFromDataStr; 28 | private String arrayFromData1Str; 29 | private String annotationStr; //注解语句 30 | private String filedNamePreFixStr; //字段前缀 31 | private String entityPackName;//创建实体类的包名. 32 | private String suffixStr; 33 | 34 | /** 35 | * 错误次数,前两次提醒哪里查看错误日志. 36 | */ 37 | private int errorCount; 38 | 39 | /** 40 | * 是否使用包装类来替代基本类型 41 | */ 42 | private boolean useWrapperClass; 43 | 44 | 45 | private Config() { 46 | 47 | } 48 | 49 | public void save() { 50 | 51 | PropertiesComponent.getInstance().setValue("fieldPrivateMode", "" + isFieldPrivateMode()); 52 | PropertiesComponent.getInstance().setValue("useSerializedName", isUseSerializedName() + ""); 53 | PropertiesComponent.getInstance().setValue("objectFromData", objectFromData + ""); 54 | PropertiesComponent.getInstance().setValue("objectFromData1", objectFromData1 + ""); 55 | PropertiesComponent.getInstance().setValue("arrayFromData", arrayFromData + ""); 56 | PropertiesComponent.getInstance().setValue("arrayFromData1", arrayFromData1 + ""); 57 | PropertiesComponent.getInstance().setValue("objectFromDataStr", objectFromDataStr + ""); 58 | PropertiesComponent.getInstance().setValue("objectFromDataStr1", objectFromDataStr1 + ""); 59 | PropertiesComponent.getInstance().setValue("arrayFromData1Str", arrayFromData1Str + ""); 60 | PropertiesComponent.getInstance().setValue("suffixStr", suffixStr + ""); 61 | PropertiesComponent.getInstance().setValue("reuseEntity", reuseEntity + ""); 62 | PropertiesComponent.getInstance().setValue("virgoMode", virgoMode + ""); 63 | PropertiesComponent.getInstance().setValue("filedNamePreFixStr", filedNamePreFixStr + ""); 64 | PropertiesComponent.getInstance().setValue("annotationStr", annotationStr + ""); 65 | PropertiesComponent.getInstance().setValue("errorCount", errorCount + ""); 66 | PropertiesComponent.getInstance().setValue("entityPackName", entityPackName + ""); 67 | PropertiesComponent.getInstance().setValue("useFieldNamePrefix", useFieldNamePrefix + ""); 68 | PropertiesComponent.getInstance().setValue("generateComments", generateComments + ""); 69 | PropertiesComponent.getInstance().setValue("splitGenerate", splitGenerate + ""); 70 | PropertiesComponent.getInstance().setValue("useWrapperClass", useWrapperClass + ""); 71 | 72 | } 73 | 74 | public static Config getInstant() { 75 | 76 | if (config == null) { 77 | config = new Config(); 78 | config.setFieldPrivateMode(PropertiesComponent.getInstance().getBoolean("fieldPrivateMode", true)); 79 | config.setUseSerializedName(PropertiesComponent.getInstance().getBoolean("useSerializedName", false)); 80 | config.setObjectFromData(PropertiesComponent.getInstance().getBoolean("objectFromData", false)); 81 | config.setObjectFromData1(PropertiesComponent.getInstance().getBoolean("objectFromData1", false)); 82 | config.setArrayFromData(PropertiesComponent.getInstance().getBoolean("arrayFromData", false)); 83 | config.setArrayFromData1(PropertiesComponent.getInstance().getBoolean("arrayFromData1", false)); 84 | config.setSuffixStr(PropertiesComponent.getInstance().getValue("suffixStr", "Bean")); 85 | config.setReuseEntity(PropertiesComponent.getInstance().getBoolean("reuseEntity", false)); 86 | config.setObjectFromDataStr(PropertiesComponent.getInstance().getValue("objectFromDataStr", Constant.objectFromObject)); 87 | config.setObjectFromDataStr1(PropertiesComponent.getInstance().getValue("objectFromDataStr1", Constant.objectFromObject1)); 88 | config.setArrayFromDataStr(PropertiesComponent.getInstance().getValue("arrayFromDataStr", Constant.arrayFromData)); 89 | config.setArrayFromData1Str(PropertiesComponent.getInstance().getValue("arrayFromData1Str", Constant.arrayFromData1)); 90 | config.setAnnotationStr(PropertiesComponent.getInstance().getValue("annotationStr", Constant.gsonAnnotation)); 91 | config.setEntityPackName(PropertiesComponent.getInstance().getValue("entityPackName")); 92 | config.setFiledNamePreFixStr(PropertiesComponent.getInstance().getValue("filedNamePreFixStr")); 93 | config.setErrorCount(PropertiesComponent.getInstance().getOrInitInt("errorCount", 0)); 94 | config.setVirgoMode(PropertiesComponent.getInstance().getBoolean("virgoMode", true)); 95 | config.setUseFieldNamePrefix(PropertiesComponent.getInstance().getBoolean("useFieldNamePrefix", false)); 96 | config.setGenerateComments(PropertiesComponent.getInstance().getBoolean("generateComments", true)); 97 | config.setSplitGenerate(PropertiesComponent.getInstance().getBoolean("splitGenerate", false)); 98 | config.setUseWrapperClass(PropertiesComponent.getInstance().getBoolean("useWrapperClass", false)); 99 | 100 | } 101 | return config; 102 | } 103 | 104 | public boolean isUseFieldNamePrefix() { 105 | return useFieldNamePrefix; 106 | } 107 | 108 | public void setUseFieldNamePrefix(boolean useFieldNamePrefix) { 109 | this.useFieldNamePrefix = useFieldNamePrefix; 110 | } 111 | 112 | public boolean isObjectFromData() { 113 | return objectFromData; 114 | } 115 | 116 | public int getErrorCount() { 117 | return errorCount; 118 | } 119 | 120 | public void setErrorCount(int errorCount) { 121 | this.errorCount = errorCount; 122 | } 123 | 124 | public String getEntityPackName() { 125 | return entityPackName; 126 | } 127 | 128 | public String geFullNameAnnotation() { 129 | 130 | if (annotationStr.equals(Constant.gsonAnnotation)) { 131 | return Constant.gsonFullNameAnnotation; 132 | } 133 | if (annotationStr.equals(Constant.jackAnnotation)) { 134 | return Constant.jackFullNameAnnotation; 135 | } 136 | if (annotationStr.equals(Constant.fastAnnotation)) { 137 | return Constant.fastFullNameAnnotation; 138 | } 139 | if (annotationStr.equals(Constant.loganSquareAnnotation)) { 140 | return Constant.loganSquareFullNameAnnotation; 141 | } 142 | return annotationStr.replaceAll("\\(", "(").replaceAll("\\)", ")").replaceAll("\\s\\*", ""); 143 | } 144 | 145 | 146 | public boolean isGenerateComments() { 147 | return generateComments; 148 | } 149 | 150 | public void setGenerateComments(boolean generateComments) { 151 | this.generateComments = generateComments; 152 | } 153 | 154 | public void setEntityPackName(String entityPackName) { 155 | this.entityPackName = entityPackName; 156 | } 157 | 158 | public boolean isVirgoMode() { 159 | return virgoMode; 160 | } 161 | 162 | public void setVirgoMode(boolean virgoMode) { 163 | this.virgoMode = virgoMode; 164 | } 165 | 166 | public String getFiledNamePreFixStr() { 167 | return filedNamePreFixStr; 168 | } 169 | 170 | public void setFiledNamePreFixStr(String filedNamePreFixStr) { 171 | this.filedNamePreFixStr = filedNamePreFixStr; 172 | } 173 | 174 | public String getAnnotationStr() { 175 | return annotationStr; 176 | } 177 | 178 | public void setAnnotationStr(String annotationStr) { 179 | this.annotationStr = annotationStr; 180 | } 181 | 182 | public void setObjectFromData(boolean objectFromData) { 183 | this.objectFromData = objectFromData; 184 | } 185 | 186 | public boolean isObjectFromData1() { 187 | return objectFromData1; 188 | } 189 | 190 | public void setObjectFromData1(boolean objectFromData2) { 191 | this.objectFromData1 = objectFromData2; 192 | } 193 | 194 | public boolean isArrayFromData() { 195 | return arrayFromData; 196 | } 197 | 198 | public void setArrayFromData(boolean arrayFromData) { 199 | this.arrayFromData = arrayFromData; 200 | } 201 | 202 | public boolean isArrayFromData1() { 203 | return arrayFromData1; 204 | } 205 | 206 | public void setArrayFromData1(boolean arrayFromData1) { 207 | this.arrayFromData1 = arrayFromData1; 208 | } 209 | 210 | 211 | public void setObjectFromDataStr(String objectFromDataStr) { 212 | this.objectFromDataStr = objectFromDataStr; 213 | } 214 | 215 | public void setObjectFromDataStr1(String objectFromDataStr1) { 216 | this.objectFromDataStr1 = objectFromDataStr1; 217 | } 218 | 219 | public void setArrayFromDataStr(String arrayFromDataStr) { 220 | this.arrayFromDataStr = arrayFromDataStr; 221 | } 222 | 223 | public void setArrayFromData1Str(String arrayFromData1Str) { 224 | this.arrayFromData1Str = arrayFromData1Str; 225 | } 226 | 227 | public String getObjectFromDataStr() { 228 | return objectFromDataStr; 229 | } 230 | 231 | public String getObjectFromDataStr1() { 232 | return objectFromDataStr1; 233 | } 234 | 235 | public String getArrayFromDataStr() { 236 | return arrayFromDataStr; 237 | } 238 | 239 | public String getArrayFromData1Str() { 240 | return arrayFromData1Str; 241 | } 242 | 243 | public String getSuffixStr() { 244 | return suffixStr; 245 | } 246 | 247 | public void setSuffixStr(String suffixStr) { 248 | this.suffixStr = suffixStr; 249 | } 250 | 251 | public boolean isReuseEntity() { 252 | return reuseEntity; 253 | } 254 | 255 | public void setReuseEntity(boolean reuseEntity) { 256 | this.reuseEntity = reuseEntity; 257 | } 258 | 259 | public boolean isUseSerializedName() { 260 | return useSerializedName; 261 | } 262 | 263 | public void setUseSerializedName(boolean useSerializedName) { 264 | this.useSerializedName = useSerializedName; 265 | } 266 | 267 | public boolean isFieldPrivateMode() { 268 | return fieldPrivateMode; 269 | } 270 | 271 | public void setFieldPrivateMode(boolean fieldPrivateMode) { 272 | this.fieldPrivateMode = fieldPrivateMode; 273 | } 274 | 275 | 276 | public void saveObjectFromDataStr(String objectFromDataStr) { 277 | this.objectFromDataStr = objectFromDataStr; 278 | PropertiesComponent.getInstance().setValue("objectFromDataStr", objectFromDataStr + ""); 279 | } 280 | 281 | public void saveObjectFromDataStr1(String objectFromDataStr1) { 282 | this.objectFromDataStr1 = objectFromDataStr1; 283 | PropertiesComponent.getInstance().setValue("objectFromDataStr1", objectFromDataStr1 + ""); 284 | } 285 | 286 | public void saveArrayFromDataStr(String arrayFromDataStr) { 287 | this.arrayFromDataStr = arrayFromDataStr; 288 | PropertiesComponent.getInstance().setValue("arrayFromDataStr", arrayFromDataStr + ""); 289 | } 290 | 291 | public void saveArrayFromData1Str(String arrayFromData1Str) { 292 | this.arrayFromData1Str = arrayFromData1Str; 293 | PropertiesComponent.getInstance().setValue("arrayFromData1Str", arrayFromData1Str + ""); 294 | } 295 | 296 | public boolean isToastError() { 297 | if (Config.getInstant().getErrorCount() < 3) { 298 | Config.getInstant().setErrorCount(Config.getInstant().getErrorCount() + 1); 299 | Config.getInstant().save(); 300 | return true; 301 | } 302 | return false; 303 | } 304 | 305 | public boolean isSplitGenerate() { 306 | return splitGenerate; 307 | } 308 | 309 | public void setSplitGenerate(boolean splitGenerate) { 310 | this.splitGenerate = splitGenerate; 311 | } 312 | 313 | 314 | public void saveCurrentPackPath(String entityPackName) { 315 | if (entityPackName == null) { 316 | return; 317 | } 318 | setEntityPackName(entityPackName+"."); 319 | save(); 320 | } 321 | 322 | public boolean isUseWrapperClass() { 323 | return useWrapperClass; 324 | } 325 | 326 | public void setUseWrapperClass(boolean useWrapperClass) { 327 | this.useWrapperClass = useWrapperClass; 328 | } 329 | } 330 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/config/Constant.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.config; 2 | 3 | /** 4 | * Created by dim on 15/5/31. 5 | */ 6 | public class Constant { 7 | 8 | 9 | public static final String DEFAULT_PREFIX = "_$"; 10 | public static String FIXME="// FIXME check this code"; 11 | 12 | 13 | public static final String privateStr = " private String name;\n" + 14 | "\n" + 15 | " public void setName(String name){\n" + 16 | " this.name=name;\n" + 17 | " }\n" + 18 | "\n" + 19 | " public String getName(){\n" + 20 | " return name;\n" + 21 | " }"; 22 | public static final String publicStr = " public String name;"; 23 | 24 | public static final String privateUseSerializedNameStr = " @SerializedName(\"name\")\n" + 25 | " private String name;\n" + 26 | "\n" + 27 | " public void setName(String name){\n" + 28 | " this.name=name;\n" + 29 | " }\n" + 30 | "\n" + 31 | " public String getName(){\n" + 32 | " return name;\n" + 33 | " }"; 34 | 35 | public static final String publicUseSerializedNameStr = " @SerializedName(\"name\")\n" + 36 | " public String name;"; 37 | 38 | public static final String objectFromObject = " public static $ClassName$ objectFromData(String str){\n" + 39 | "\n" + 40 | " return new com.google.gson.Gson().fromJson(str,$ClassName$.class);\n" + 41 | " }"; 42 | 43 | public static final String objectFromObject1 = " public static $ClassName$ objectFromData(String str, String key){\n" + 44 | "\n" + 45 | " try {\n" + 46 | " org.json.JSONObject jsonObject=new org.json.JSONObject(str);\n" + 47 | "\n" + 48 | " return new com.google.gson.Gson().fromJson(jsonObject.getString(str),$ClassName$.class);\n" + 49 | " } catch (org.json.JSONException e) {\n" + 50 | " e.printStackTrace();\n" + 51 | " }\n" + 52 | "\n" + 53 | " return null;\n" + 54 | " }"; 55 | 56 | public static final String arrayFromData = " public static java.util.List<$ClassName$> array$ClassName$FromData(String str){\n" + 57 | "\n" + 58 | " java.lang.reflect.Type listType=new com.google.gson.reflect.TypeToken>(){}.getType();\n" + 59 | "\n" + 60 | " return new com.google.gson.Gson().fromJson(str,listType);\n" + 61 | " }"; 62 | 63 | public static final String arrayFromData1 = " public static java.util.List<$ClassName$> array$ClassName$FromData(String str,String key){\n" + 64 | "\n" + 65 | " try {\n" + 66 | " org.json.JSONObject jsonObject=new org.json.JSONObject(str);\n" + 67 | " java.lang.reflect.Type listType=new com.google.gson.reflect.TypeToken>(){}.getType();\n" + 68 | "\n" + 69 | " return new com.google.gson.Gson().fromJson(jsonObject.getString(str),listType);\n" + 70 | "\n" + 71 | " } catch (org.json.JSONException e) {\n" + 72 | " e.printStackTrace();\n" + 73 | " }\n" + 74 | "\n" + 75 | " return new java.util.ArrayList();\n" + 76 | "\n" + 77 | "\n" + 78 | " }"; 79 | 80 | public static final String autoValueMethodTemplate = "public static com.google.gson.TypeAdapter<$className$> typeAdapter(com.google.gson.Gson gson)" + 81 | " {\n" + 82 | " return new AutoValue_$AdapterClassName$.GsonTypeAdapter(gson);\n" + 83 | "}"; 84 | 85 | public static final String gsonAnnotation = "@com.google.gson.annotations.SerializedName\\s*\\(\\s*\"{filed}\"\\s*\\)"; 86 | 87 | public static final String gsonFullNameAnnotation = "@com.google.gson.annotations.SerializedName(\"{filed}\")"; 88 | 89 | public static final String fastFullNameAnnotation = "@com.alibaba.fastjson.annotation.JSONField(name=\"{filed}\")"; 90 | 91 | public static final String fastAnnotation = "@com.alibaba.fastjson.annotation.JSONField\\s*\\(\\s*name\\s*=\\s*\"{filed}\"\\s*\\)"; 92 | 93 | public static final String jackAnnotation = "@com.fasterxml.jackson.annotation.JsonProperty\\s*\\(\\s*\"{filed}\"\\s*\\)"; 94 | 95 | public static final String loganSquareAnnotation = "@com.bluelinelabs.logansquare.annotation.JsonField\\s*\\(\\s*name\\s*=\\s*\"{filed}\"\\s*\\)"; 96 | 97 | public static final String jackFullNameAnnotation = "@com.fasterxml.jackson.annotation.JsonProperty(\"{filed}\")"; 98 | 99 | public static final String autoValueAnnotation = "autoValue"; 100 | public static final String lombokAnnotation = "lombok"; 101 | 102 | public static final String loganSquareFullNameAnnotation = "@com.bluelinelabs.logansquare.annotation.JsonField(name=\"{filed}\")"; 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/entity/ClassEntity.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.entity; 2 | 3 | import com.intellij.psi.PsiClass; 4 | import org.apache.http.util.TextUtils; 5 | import org.gsonformat.intellij.common.CheckUtil; 6 | import org.jdesktop.swingx.ux.CellProvider; 7 | import org.jdesktop.swingx.ux.Selector; 8 | import org.json.JSONObject; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * Created by dim on 2015/7/15. 15 | */ 16 | public class ClassEntity implements Selector, CellProvider { 17 | 18 | private PsiClass psiClass; 19 | private String fieldTypeSuffix; 20 | private String className; 21 | private List fields = new ArrayList<>(); 22 | private List innerClasss = new ArrayList<>(); 23 | private String packName; 24 | /** 25 | * 存储 comment 26 | */ 27 | private String extra; 28 | private boolean generate = true; 29 | private boolean lock = false; 30 | 31 | public boolean isLock() { 32 | return lock; 33 | } 34 | 35 | public void setLock(boolean lock) { 36 | this.lock = lock; 37 | } 38 | 39 | public boolean isGenerate() { 40 | return generate; 41 | } 42 | 43 | public void setGenerate(boolean generate) { 44 | this.generate = generate; 45 | } 46 | 47 | public String getExtra() { 48 | return extra; 49 | } 50 | 51 | public void setExtra(String extra) { 52 | this.extra = extra; 53 | } 54 | 55 | public void addAllFields(List fields) { 56 | this.fields.addAll(fields); 57 | } 58 | 59 | public void addField(FieldEntity fieldEntity) { 60 | this.fields.add(fieldEntity); 61 | } 62 | 63 | public void addInnerClass(ClassEntity classEntity) { 64 | this.innerClasss.add(classEntity); 65 | } 66 | 67 | public List getInnerClasss() { 68 | return innerClasss; 69 | } 70 | 71 | public String getPackName() { 72 | return packName; 73 | } 74 | 75 | public void setPackName(String packName) { 76 | this.packName = packName; 77 | } 78 | 79 | 80 | public String getFieldTypeSuffix() { 81 | return fieldTypeSuffix; 82 | } 83 | 84 | public void setFieldTypeSuffix(String fieldTypeSuffix) { 85 | this.fieldTypeSuffix = fieldTypeSuffix; 86 | } 87 | 88 | public String getClassName() { 89 | return className; 90 | } 91 | 92 | public void setClassName(String className) { 93 | this.className = CheckUtil.getInstant().handleArg(className); 94 | } 95 | 96 | public List getFields() { 97 | return fields; 98 | } 99 | 100 | public PsiClass getPsiClass() { 101 | return psiClass; 102 | } 103 | 104 | public void setPsiClass(PsiClass psiClass) { 105 | this.psiClass = psiClass; 106 | } 107 | 108 | public String getQualifiedName() { 109 | String fullClassName; 110 | if (!TextUtils.isEmpty(packName)) { 111 | fullClassName = packName + "." + className; 112 | } else { 113 | fullClassName = className; 114 | } 115 | 116 | return fullClassName; 117 | } 118 | 119 | @Override 120 | public void setSelect(boolean select) { 121 | setGenerate(select); 122 | } 123 | 124 | public boolean isSame(JSONObject o) { 125 | if (o == null) { 126 | return false; 127 | } 128 | boolean same = true; 129 | for (String key : o.keySet()) { 130 | same = false; 131 | for (FieldEntity field : fields) { 132 | if (field.getKey().equals(key)) { 133 | if (field.isSameType(o.get(key))) { 134 | same = true; 135 | } 136 | break; 137 | } 138 | } 139 | if (!same) { 140 | break; 141 | } 142 | } 143 | return same; 144 | } 145 | 146 | 147 | @Override 148 | public String getCellTitle(int index) { 149 | String result = ""; 150 | switch (index) { 151 | case 0: 152 | result = getClassName(); 153 | break; 154 | 155 | case 3: 156 | result = getClassName(); 157 | break; 158 | } 159 | return result; 160 | } 161 | 162 | @Override 163 | public void setValueAt(int column, String text) { 164 | switch (column) { 165 | case 2: 166 | break; 167 | case 3: 168 | String result; 169 | if (!TextUtils.isEmpty(fieldTypeSuffix)) { 170 | result = fieldTypeSuffix + "." + text; 171 | } else { 172 | result = text; 173 | } 174 | if (CheckUtil.getInstant().containsDeclareClassName(result)) { 175 | return; 176 | } 177 | CheckUtil.getInstant().removeDeclareClassName(getQualifiedName()); 178 | setClassName(text); 179 | break; 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/entity/ConvertLibrary.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.entity; 2 | 3 | import org.gsonformat.intellij.config.Config; 4 | import org.gsonformat.intellij.config.Constant; 5 | 6 | /** 7 | * Created by didm on 16/11/7. 8 | */ 9 | public enum ConvertLibrary { 10 | 11 | Gson, Jack, FastJson, LoganSquare, AutoValue, Other, Lombok; 12 | 13 | public static ConvertLibrary from() { 14 | return from(Config.getInstant().getAnnotationStr()); 15 | } 16 | 17 | private static ConvertLibrary from(String annotation) { 18 | if (Config.getInstant().getAnnotationStr().equals(Constant.gsonAnnotation)) { 19 | return Gson; 20 | } 21 | if (Config.getInstant().getAnnotationStr().equals(Constant.fastAnnotation)) { 22 | return FastJson; 23 | } 24 | if (Config.getInstant().getAnnotationStr().equals(Constant.loganSquareAnnotation)) { 25 | return LoganSquare; 26 | } 27 | if (Config.getInstant().getAnnotationStr().equals(Constant.autoValueAnnotation)) { 28 | return AutoValue; 29 | } 30 | if (Config.getInstant().getAnnotationStr().equals(Constant.jackAnnotation)) { 31 | return Jack; 32 | } 33 | if (Config.getInstant().getAnnotationStr().equals(Constant.lombokAnnotation)) { 34 | return Lombok; 35 | } 36 | return Other; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/entity/DataType.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.entity; 2 | 3 | import org.json.JSONArray; 4 | import org.json.JSONObject; 5 | 6 | /** 7 | * Created by dim on 16/11/7. 8 | */ 9 | public enum DataType { 10 | 11 | Data_Type_Boolean("boolean"), Data_Type_Int("int"), Data_Type_Double("double"), 12 | Data_Type_long("long"), Data_Type_String("String"), Data_type_Object("Object"), Data_Type_Array("array"); 13 | private String value; 14 | 15 | DataType(String value) { 16 | this.value = value; 17 | } 18 | 19 | public String getValue() { 20 | return value; 21 | } 22 | 23 | public static DataType typeOfObject(Object value) { 24 | if (value == null) { 25 | return Data_type_Object; 26 | } 27 | DataType type = null; 28 | if (value instanceof Boolean) { 29 | type = Data_Type_Boolean; 30 | } else if (value instanceof Integer) { 31 | type = Data_Type_Int; 32 | } else if (value instanceof Double) { 33 | type = Data_Type_Double; 34 | } else if (value instanceof Long) { 35 | type = Data_Type_long; 36 | } else if (value instanceof String) { 37 | type = Data_Type_String; 38 | } else if (value instanceof JSONObject) { 39 | type = Data_type_Object; 40 | } else if (value instanceof JSONArray) { 41 | type = Data_Type_Array; 42 | } else { 43 | type = Data_type_Object; 44 | } 45 | return type; 46 | } 47 | 48 | public static DataType typeOfString(String type) { 49 | if ("boolean".equals(type) || "Boolean".equals(type)) { 50 | return Data_Type_Boolean; 51 | } 52 | if ("Integer".equals(type) || "int".equals(type)) { 53 | return Data_Type_Int; 54 | } 55 | if ("long".equals(type) || "Long".equals(type)) { 56 | return Data_Type_long; 57 | } 58 | if ("String".equals(type) || "String".equals(type)) { 59 | return Data_Type_String; 60 | } 61 | if ("object".equals(type)) { 62 | return Data_type_Object; 63 | } 64 | if ("array".equals(type)) { 65 | return Data_Type_Array; 66 | } 67 | 68 | return null; 69 | } 70 | 71 | public static boolean isSameDataType(String text, String text2) { 72 | return isSameDataType(typeOfString(text), typeOfString(text2)); 73 | } 74 | 75 | public static boolean isSameDataType(DataType dataType, DataType dataType1) { 76 | if (dataType == null || dataType1 == null) { 77 | return false; 78 | } 79 | return dataType == dataType1; 80 | } 81 | 82 | public static String getWrapperTypeSimpleName(DataType type) { 83 | switch (type) { 84 | case Data_Type_Boolean: 85 | return "Boolean"; 86 | case Data_Type_Int: 87 | return "Integer"; 88 | case Data_Type_Double: 89 | return "Double"; 90 | case Data_Type_long: 91 | return "Long"; 92 | default: 93 | return type.getValue(); 94 | } 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/entity/FieldEntity.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.entity; 2 | 3 | import org.apache.http.util.TextUtils; 4 | import org.gsonformat.intellij.common.CheckUtil; 5 | import org.jdesktop.swingx.ux.CellProvider; 6 | import org.jdesktop.swingx.ux.Selector; 7 | import org.json.JSONObject; 8 | 9 | /** 10 | * Created by dim on 2015/7/15. 11 | */ 12 | public class FieldEntity implements Selector, CellProvider { 13 | 14 | protected String key; 15 | protected String type; //类型 16 | protected String fieldName; // 生成的名字 17 | protected String value; // 值 18 | protected ClassEntity targetClass; //依赖的实体类 19 | protected boolean generate = true; 20 | 21 | public ClassEntity getTargetClass() { 22 | return targetClass; 23 | } 24 | 25 | public void setTargetClass(ClassEntity targetClass) { 26 | this.targetClass = targetClass; 27 | } 28 | 29 | public boolean isGenerate() { 30 | return generate; 31 | } 32 | 33 | public void setGenerate(boolean generate) { 34 | this.generate = generate; 35 | } 36 | 37 | public String getFieldName() { 38 | return fieldName; 39 | } 40 | 41 | public String getGenerateFieldName() { 42 | return CheckUtil.getInstant().handleArg(fieldName); 43 | } 44 | 45 | public void setFieldName(String fieldName) { 46 | if (TextUtils.isEmpty(fieldName)) { 47 | return; 48 | } 49 | this.fieldName = fieldName; 50 | } 51 | 52 | public void setValue(String value) { 53 | this.value = value; 54 | } 55 | 56 | public void setKey(String key) { 57 | this.key = key; 58 | } 59 | 60 | public String getType() { 61 | return type; 62 | } 63 | 64 | public String getRealType() { 65 | if (targetClass != null) { 66 | return targetClass.getClassName(); 67 | } 68 | return type; 69 | } 70 | 71 | public String getBriefType() { 72 | if (targetClass != null) { 73 | return targetClass.getClassName(); 74 | } 75 | int i = type.indexOf("."); 76 | if (i > 0) { 77 | return type.substring(i); 78 | } 79 | return type; 80 | } 81 | 82 | public String getFullNameType() { 83 | if (targetClass != null) { 84 | return targetClass.getQualifiedName(); 85 | } 86 | return type; 87 | } 88 | 89 | public void setType(String type) { 90 | this.type = type; 91 | } 92 | 93 | public void checkAndSetType(String text) { 94 | if (type != null && CheckUtil.getInstant().checkSimpleType(type.trim())) { 95 | //基本类型 96 | if (CheckUtil.getInstant().checkSimpleType(text.trim())) { 97 | this.type = text.trim(); 98 | } 99 | } else { 100 | //实体类: 101 | if (targetClass != null && !targetClass.isLock()) { 102 | if (!TextUtils.isEmpty(text)) { 103 | targetClass.setClassName(text); 104 | } 105 | } 106 | } 107 | } 108 | 109 | public String getKey() { 110 | return key; 111 | } 112 | 113 | public String getValue() { 114 | return value; 115 | } 116 | 117 | @Override 118 | public void setSelect(boolean select) { 119 | setGenerate(select); 120 | } 121 | 122 | public boolean isSameType(Object o) { 123 | if (o instanceof JSONObject) { 124 | if (targetClass != null) { 125 | return targetClass.isSame((JSONObject) o); 126 | } 127 | } else { 128 | return DataType.isSameDataType(DataType.typeOfString(type), DataType.typeOfObject(o)); 129 | } 130 | return false; 131 | } 132 | 133 | @Override 134 | public String getCellTitle(int index) { 135 | String result = ""; 136 | switch (index) { 137 | case 0: 138 | result = getKey(); 139 | break; 140 | case 1: 141 | result = getValue(); 142 | break; 143 | case 2: 144 | result = getBriefType(); 145 | break; 146 | case 3: 147 | result = getFieldName(); 148 | break; 149 | } 150 | return result; 151 | } 152 | 153 | @Override 154 | public void setValueAt(int column, String text) { 155 | switch (column) { 156 | case 2: 157 | checkAndSetType(text); 158 | break; 159 | case 3: 160 | if(CheckUtil.getInstant().containsDeclareFieldName(text)){ 161 | return; 162 | } 163 | CheckUtil.getInstant().removeDeclareFieldName(getFieldName()); 164 | setFieldName(text); 165 | break; 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/entity/IterableFieldEntity.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.entity; 2 | 3 | import org.apache.http.util.TextUtils; 4 | import org.json.JSONArray; 5 | import org.json.JSONObject; 6 | 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | 10 | /** 11 | * Created by dim on 16/11/6. 12 | */ 13 | public class IterableFieldEntity extends FieldEntity { 14 | 15 | private static final String listTemplate = "java.util.List<%s>"; 16 | private static final String briefListTemplate = "List<%s>"; 17 | 18 | private int deep; 19 | 20 | public int getDeep() { 21 | return deep; 22 | } 23 | 24 | public void setDeep(int deep) { 25 | this.deep = deep; 26 | } 27 | 28 | public String getRealType() { 29 | String typeName = getClassTypeName(); 30 | return String.format(getBriefTypeReg(), typeName); 31 | } 32 | 33 | public String getBriefType() { 34 | return String.format(getBriefTypeReg(), getBriefClassTypeName()); 35 | } 36 | 37 | private String getClassTypeName() { 38 | String typeName = ""; 39 | if (targetClass != null) { 40 | if (TextUtils.isEmpty(targetClass.getPackName())) { 41 | typeName = targetClass.getClassName(); 42 | } else { 43 | typeName = targetClass.getPackName() + "." + targetClass.getClassName(); 44 | } 45 | } else if (getType() != null && getType().length() > 0) { 46 | typeName = getType(); 47 | } 48 | return typeName; 49 | } 50 | 51 | private String getBriefClassTypeName() { 52 | String typeName = ""; 53 | if (targetClass != null) { 54 | typeName = targetClass.getClassName(); 55 | } else if (getType() != null && getType().length() > 0) { 56 | typeName = getType(); 57 | } 58 | return typeName; 59 | } 60 | 61 | 62 | public String getFullNameType() { 63 | String typeName = getClassTypeName(); 64 | return String.format(getTypeReg(), typeName); 65 | } 66 | 67 | private String getTypeReg() { 68 | return getRegForDeep(listTemplate); 69 | } 70 | 71 | private String getBriefTypeReg() { 72 | return getRegForDeep(briefListTemplate); 73 | } 74 | 75 | private String getRegForDeep(String template) { 76 | if (deep > 0) { 77 | String format = template; 78 | for (int i = 1; i < deep; i++) { 79 | format = String.format(format, template); 80 | } 81 | return format; 82 | } 83 | return "%s"; 84 | } 85 | 86 | @Override 87 | public void checkAndSetType(String text) { 88 | if (targetClass.isLock()) { 89 | return; 90 | } 91 | String regex = getBriefTypeReg().replaceAll("%s", "(\\\\w+)"); 92 | Pattern pattern = Pattern.compile(regex); 93 | Matcher matcher = pattern.matcher(text); 94 | if (matcher.find() && matcher.groupCount() > 0) { 95 | String temp = matcher.group(1); 96 | if (!TextUtils.isEmpty(temp)) { 97 | targetClass.setClassName(temp); 98 | } 99 | } 100 | } 101 | 102 | @Override 103 | public boolean isSameType(Object o) { 104 | 105 | if (o instanceof JSONArray) { 106 | 107 | Object o1 = deepObjectFromJson(deep, 0, (JSONArray) o); 108 | if (o1 instanceof JSONObject && getTargetClass() != null) { 109 | return getTargetClass().isSame((JSONObject) o1); 110 | } else if (getTargetClass() == null && getType() != null) { 111 | 112 | return DataType.isSameDataType(DataType.typeOfString(getType()), DataType.typeOfObject(o1)); 113 | 114 | } 115 | 116 | 117 | } else { 118 | return false; 119 | } 120 | 121 | return super.isSameType(o); 122 | } 123 | 124 | 125 | private Object deepObjectFromJson(int deep, int current, JSONArray array) { 126 | if (deep <= current) { 127 | return null; 128 | } 129 | if (array.length() > 0) { 130 | if (deep == current + 1 && !(array.get(0) instanceof JSONArray)) { 131 | return array.get(0); 132 | } 133 | if (array.get(0) instanceof JSONArray) { 134 | return deepObjectFromJson(deep, ++current, array.getJSONArray(0)); 135 | } 136 | } 137 | return null; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/AutoValueProcessor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | import com.intellij.psi.*; 4 | import org.apache.http.util.TextUtils; 5 | import org.gsonformat.intellij.common.FieldHelper; 6 | import org.gsonformat.intellij.common.Try; 7 | import org.gsonformat.intellij.config.Config; 8 | import org.gsonformat.intellij.config.Constant; 9 | import org.gsonformat.intellij.entity.ClassEntity; 10 | import org.gsonformat.intellij.entity.FieldEntity; 11 | 12 | import java.util.regex.Pattern; 13 | 14 | /** 15 | * Created by dim on 16/11/7. 16 | */ 17 | class AutoValueProcessor extends Processor { 18 | 19 | @Override 20 | public void onStarProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls, IProcessor visitor) { 21 | super.onStarProcess(classEntity, factory, cls, visitor); 22 | injectAutoAnnotation(factory, cls); 23 | } 24 | 25 | @Override 26 | public void generateField(PsiElementFactory factory, FieldEntity fieldEntity, PsiClass cls, ClassEntity classEntity) { 27 | 28 | if (fieldEntity.isGenerate()) { 29 | 30 | Try.run(new Try.TryListener() { 31 | @Override 32 | public void run() { 33 | cls.add(factory.createMethodFromText(generateFieldText(classEntity, fieldEntity, null), cls)); 34 | } 35 | 36 | @Override 37 | public void runAgain() { 38 | fieldEntity.setFieldName(FieldHelper.generateLuckyFieldName(fieldEntity.getFieldName())); 39 | cls.add(factory.createMethodFromText(generateFieldText(classEntity, fieldEntity, Constant.FIXME), cls)); 40 | } 41 | 42 | @Override 43 | public void error() { 44 | cls.addBefore(factory.createCommentFromText("// FIXME generate failure field " + fieldEntity.getFieldName(), cls), cls.getChildren()[0]); 45 | } 46 | }); 47 | 48 | } 49 | } 50 | 51 | @Override 52 | public void generateGetterAndSetter(PsiElementFactory factory, PsiClass cls, ClassEntity classEntity) { 53 | } 54 | 55 | @Override 56 | public void generateConvertMethod(PsiElementFactory factory, PsiClass cls, ClassEntity classEntity) { 57 | super.generateConvertMethod(factory, cls, classEntity); 58 | // if (PsiClassUtil.isClassAvailableForProject(cls.getProject(), "com.ryanharter.auto.value.gson.AutoValueGsonAdapterFactoryProcessor")) { 59 | // String qualifiedName = cls.getQualifiedName(); 60 | // String autoAdapter = qualifiedName.substring(mainPackage.length()+1, qualifiedName.length()); 61 | // createMethod(factory, Constant.autoValueMethodTemplate.replace("$className$", classEntity.getClassName()).replace("$AdapterClassName$", getAutoAdpaterClass(autoAdapter)).trim(), cls); 62 | // } 63 | } 64 | 65 | public static String getAutoAdpaterClass(String className) { 66 | return String.join("_", className.split("\\.")); 67 | } 68 | 69 | @Override 70 | protected void onEndGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, PsiClass generateClass, IProcessor visitor) { 71 | super.onEndGenerateClass(factory, classEntity, parentClass, generateClass, visitor); 72 | injectAutoAnnotation(factory, generateClass); 73 | } 74 | 75 | private void injectAutoAnnotation(PsiElementFactory factory, PsiClass cls) { 76 | PsiModifierList modifierList = cls.getModifierList(); 77 | if (modifierList != null) { 78 | PsiElement firstChild = modifierList.getFirstChild(); 79 | Pattern pattern = Pattern.compile("@.*?AutoValue"); 80 | if (firstChild != null && !pattern.matcher(firstChild.getText()).find()) { 81 | PsiAnnotation annotationFromText = factory.createAnnotationFromText("@com.google.auto.value.AutoValue", cls); 82 | modifierList.addBefore(annotationFromText, firstChild); 83 | } 84 | if (!modifierList.hasModifierProperty(PsiModifier.ABSTRACT)) { 85 | modifierList.setModifierProperty(PsiModifier.ABSTRACT, true); 86 | } 87 | } 88 | } 89 | 90 | private String generateFieldText(ClassEntity classEntity, FieldEntity fieldEntity, String fixme) { 91 | fixme = fixme == null ? "" : fixme; 92 | StringBuilder fieldSb = new StringBuilder(); 93 | String fieldName = fieldEntity.getGenerateFieldName(); 94 | if (!TextUtils.isEmpty(classEntity.getExtra())) { 95 | fieldSb.append(classEntity.getExtra()).append("\n"); 96 | classEntity.setExtra(null); 97 | } 98 | if (!fieldName.equals(fieldEntity.getKey()) || Config.getInstant().isUseSerializedName()) { 99 | fieldSb.append(Constant.gsonFullNameAnnotation.replaceAll("\\{filed\\}", fieldEntity.getKey())); 100 | } 101 | if (fieldEntity.getTargetClass() != null) { 102 | fieldEntity.getTargetClass().setGenerate(true); 103 | } 104 | return fieldSb.append(String.format("public abstract %s %s(); " + fixme, fieldEntity.getFullNameType(), fieldName)).toString(); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/ClassProcessor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | import com.intellij.psi.PsiClass; 4 | import com.intellij.psi.PsiElementFactory; 5 | import org.gsonformat.intellij.entity.ClassEntity; 6 | import org.gsonformat.intellij.entity.ConvertLibrary; 7 | 8 | 9 | /** 10 | * Created by dim on 16/11/7. 11 | */ 12 | public class ClassProcessor { 13 | 14 | private PsiElementFactory factory; 15 | private PsiClass cls; 16 | private Processor processor; 17 | 18 | public ClassProcessor(PsiElementFactory factory, PsiClass cls) { 19 | this.factory = factory; 20 | this.cls = cls; 21 | processor = Processor.getProcessor(ConvertLibrary.from()); 22 | } 23 | 24 | public void generate(ClassEntity classEntity, IProcessor visitor) { 25 | if (processor != null) processor.process(classEntity, factory, cls, visitor); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/FastJsonProcessor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | import com.intellij.psi.PsiClass; 4 | import com.intellij.psi.PsiElementFactory; 5 | import org.gsonformat.intellij.entity.ClassEntity; 6 | 7 | /** 8 | * Created by dim on 16/11/7. 9 | */ 10 | class FastJsonProcessor extends Processor { 11 | 12 | @Override 13 | public void onStarProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls,IProcessor visitor) { 14 | super.onEndProcess(classEntity, factory, cls, visitor); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/GsonProcessor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | 4 | /** 5 | * Created by dim on 16/11/7. 6 | */ 7 | class GsonProcessor extends Processor { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/IProcessor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | import com.intellij.psi.PsiClass; 4 | import com.intellij.psi.PsiElementFactory; 5 | import org.gsonformat.intellij.entity.ClassEntity; 6 | 7 | /** 8 | * Created by dim on 16/11/8. 9 | */ 10 | public interface IProcessor { 11 | 12 | void onStarProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls); 13 | 14 | void onEndProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls); 15 | 16 | void onStartGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass); 17 | 18 | void onEndGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, PsiClass generateClass); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/JackProcessor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | import com.intellij.psi.*; 4 | import org.gsonformat.intellij.entity.ClassEntity; 5 | 6 | import java.util.regex.Pattern; 7 | 8 | /** 9 | * Created by dim on 16/11/7. 10 | */ 11 | class JackProcessor extends Processor { 12 | 13 | @Override 14 | protected void onStartGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, IProcessor visitor) { 15 | super.onStartGenerateClass(factory, classEntity, parentClass, visitor); 16 | } 17 | 18 | @Override 19 | public void onStarProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls, IProcessor visitor) { 20 | super.onStarProcess(classEntity, factory, cls, visitor); 21 | injectAnnotation(factory, cls); 22 | } 23 | 24 | @Override 25 | protected void onEndGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, PsiClass generateClass, IProcessor visitor) { 26 | super.onEndGenerateClass(factory, classEntity, parentClass, generateClass, visitor); 27 | injectAnnotation(factory, generateClass); 28 | } 29 | 30 | private void injectAnnotation(PsiElementFactory factory, PsiClass generateClass) { 31 | if (factory == null || generateClass == null) { 32 | return; 33 | } 34 | PsiModifierList modifierList = generateClass.getModifierList(); 35 | PsiElement firstChild = modifierList.getFirstChild(); 36 | Pattern pattern = Pattern.compile("@.*?JsonIgnoreProperties"); 37 | if (firstChild != null && !pattern.matcher(firstChild.getText()).find()) { 38 | PsiAnnotation annotationFromText = 39 | factory.createAnnotationFromText("@com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true)", generateClass); 40 | modifierList.addBefore(annotationFromText, firstChild); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/LoganSquareProcessor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | import com.intellij.psi.*; 4 | import org.gsonformat.intellij.entity.ClassEntity; 5 | 6 | import java.util.regex.Pattern; 7 | 8 | /** 9 | * Created by dim on 16/11/7. 10 | */ 11 | public class LoganSquareProcessor extends Processor { 12 | @Override 13 | protected void onStarProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls, IProcessor visitor) { 14 | super.onStarProcess(classEntity, factory, cls, visitor); 15 | injectAnnotation(factory, cls); 16 | } 17 | 18 | @Override 19 | protected void onEndGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, PsiClass generateClass, IProcessor visitor) { 20 | super.onEndGenerateClass(factory, classEntity, parentClass, generateClass, visitor); 21 | injectAnnotation(factory, generateClass); 22 | } 23 | 24 | private void injectAnnotation(PsiElementFactory factory, PsiClass generateClass) { 25 | if (factory == null || generateClass == null) { 26 | return; 27 | } 28 | PsiModifierList modifierList = generateClass.getModifierList(); 29 | if (modifierList != null) { 30 | PsiElement firstChild = modifierList.getFirstChild(); 31 | Pattern pattern = Pattern.compile("@.*?JsonObject"); 32 | if (firstChild != null && !pattern.matcher(firstChild.getText()).find()) { 33 | PsiAnnotation annotationFromText = factory.createAnnotationFromText("@com.bluelinelabs.logansquare.annotation.JsonObject", generateClass); 34 | modifierList.addBefore(annotationFromText, firstChild); 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/LombokProcessor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | import com.intellij.psi.*; 4 | import org.apache.http.util.TextUtils; 5 | import org.gsonformat.intellij.common.FieldHelper; 6 | import org.gsonformat.intellij.common.Try; 7 | import org.gsonformat.intellij.config.Config; 8 | import org.gsonformat.intellij.config.Constant; 9 | import org.gsonformat.intellij.entity.ClassEntity; 10 | import org.gsonformat.intellij.entity.FieldEntity; 11 | 12 | import java.util.regex.Pattern; 13 | 14 | /** 15 | * Created by dim on 16/11/7. 16 | */ 17 | public class LombokProcessor extends Processor { 18 | 19 | @Override 20 | protected void onStarProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls, IProcessor visitor) { 21 | super.onStarProcess(classEntity, factory, cls, visitor); 22 | injectAnnotation(factory, cls); 23 | } 24 | 25 | private void injectAnnotation(PsiElementFactory factory, PsiClass generateClass) { 26 | if (factory == null || generateClass == null) { 27 | return; 28 | } 29 | PsiModifierList modifierList = generateClass.getModifierList(); 30 | if (modifierList != null) { 31 | PsiElement firstChild = modifierList.getFirstChild(); 32 | Pattern pattern = Pattern.compile("@.*?NoArgsConstructor"); 33 | if (firstChild != null && !pattern.matcher(firstChild.getText()).find()) { 34 | PsiAnnotation annotationFromText = factory.createAnnotationFromText("@lombok.NoArgsConstructor", generateClass); 35 | modifierList.addBefore(annotationFromText, firstChild); 36 | } 37 | Pattern pattern2 = Pattern.compile("@.*?Data"); 38 | if (firstChild != null && !pattern2.matcher(firstChild.getText()).find()) { 39 | PsiAnnotation annotationFromText = factory.createAnnotationFromText("@lombok.Data", generateClass); 40 | modifierList.addBefore(annotationFromText, firstChild); 41 | } 42 | } 43 | } 44 | 45 | @Override 46 | protected void generateField(PsiElementFactory factory, FieldEntity fieldEntity, PsiClass cls, ClassEntity classEntity) { 47 | if (fieldEntity.isGenerate()) { 48 | Try.run(new Try.TryListener() { 49 | @Override 50 | public void run() { 51 | cls.add(factory.createFieldFromText(generateLombokFieldText(classEntity, fieldEntity,null), cls)); 52 | } 53 | 54 | @Override 55 | public void runAgain() { 56 | fieldEntity.setFieldName(FieldHelper.generateLuckyFieldName(fieldEntity.getFieldName())); 57 | cls.add(factory.createFieldFromText(generateLombokFieldText(classEntity, fieldEntity, Constant.FIXME), cls)); 58 | } 59 | 60 | @Override 61 | public void error() { 62 | cls.addBefore(factory.createCommentFromText("// FIXME generate failure field " + fieldEntity.getFieldName(), cls), cls.getChildren()[0]); 63 | } 64 | }); 65 | } 66 | } 67 | 68 | @Override 69 | protected void createGetAndSetMethod(PsiElementFactory factory, PsiClass cls, FieldEntity field) { 70 | } 71 | 72 | @Override 73 | protected void onEndGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, PsiClass generateClass, IProcessor visitor) { 74 | super.onEndGenerateClass(factory, classEntity, parentClass, generateClass, visitor); 75 | injectAnnotation(factory, generateClass); 76 | } 77 | 78 | private String generateLombokFieldText(ClassEntity classEntity, FieldEntity fieldEntity, String fixme) { 79 | fixme = fixme == null ? "" : fixme; 80 | 81 | StringBuilder fieldSb = new StringBuilder(); 82 | String filedName = fieldEntity.getGenerateFieldName(); 83 | if (!TextUtils.isEmpty(classEntity.getExtra())) { 84 | fieldSb.append(classEntity.getExtra()).append("\n"); 85 | classEntity.setExtra(null); 86 | } 87 | if (fieldEntity.getTargetClass() != null) { 88 | fieldEntity.getTargetClass().setGenerate(true); 89 | } 90 | 91 | if (Config.getInstant().isFieldPrivateMode()) { 92 | fieldSb.append("private ").append(fieldEntity.getFullNameType()).append(" ").append(filedName).append(" ; "); 93 | } else { 94 | fieldSb.append("public ").append(fieldEntity.getFullNameType()).append(" ").append(filedName).append(" ; "); 95 | } 96 | return fieldSb.append(fixme).toString(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/OtherProcessor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | /** 4 | * Created by dim on 16/11/7. 5 | */ 6 | public class OtherProcessor extends Processor { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/process/Processor.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.process; 2 | 3 | import com.intellij.psi.PsiClass; 4 | import com.intellij.psi.PsiElementFactory; 5 | import com.intellij.psi.codeStyle.JavaCodeStyleManager; 6 | import org.apache.http.util.TextUtils; 7 | import org.gsonformat.intellij.common.FieldHelper; 8 | import org.gsonformat.intellij.common.PsiClassUtil; 9 | import org.gsonformat.intellij.common.Try; 10 | import org.gsonformat.intellij.config.Config; 11 | import org.gsonformat.intellij.config.Constant; 12 | import org.gsonformat.intellij.entity.ClassEntity; 13 | import org.gsonformat.intellij.entity.ConvertLibrary; 14 | import org.gsonformat.intellij.entity.FieldEntity; 15 | 16 | import java.util.HashMap; 17 | 18 | import static org.gsonformat.intellij.common.StringUtils.captureName; 19 | 20 | /** 21 | * Created by dim on 16/11/7. 22 | */ 23 | public abstract class Processor { 24 | 25 | private static HashMap sProcessorMap = new HashMap<>(); 26 | 27 | static { 28 | sProcessorMap.put(ConvertLibrary.Gson, new GsonProcessor()); 29 | sProcessorMap.put(ConvertLibrary.Jack, new JackProcessor()); 30 | sProcessorMap.put(ConvertLibrary.FastJson, new FastJsonProcessor()); 31 | sProcessorMap.put(ConvertLibrary.AutoValue, new AutoValueProcessor()); 32 | sProcessorMap.put(ConvertLibrary.LoganSquare, new LoganSquareProcessor()); 33 | sProcessorMap.put(ConvertLibrary.Other, new OtherProcessor()); 34 | sProcessorMap.put(ConvertLibrary.Lombok, new LombokProcessor()); 35 | } 36 | 37 | 38 | static Processor getProcessor(ConvertLibrary convertLibrary) { 39 | return sProcessorMap.get(convertLibrary); 40 | } 41 | 42 | protected String mainPackage; 43 | 44 | public void process(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls, IProcessor visitor) { 45 | mainPackage = PsiClassUtil.getPackage(cls); 46 | onStarProcess(classEntity, factory, cls, visitor); 47 | 48 | for (FieldEntity fieldEntity : classEntity.getFields()) { 49 | generateField(factory, fieldEntity, cls, classEntity); 50 | } 51 | for (ClassEntity innerClass : classEntity.getInnerClasss()) { 52 | generateClass(factory, innerClass, cls, visitor); 53 | } 54 | generateGetterAndSetter(factory, cls, classEntity); 55 | generateConvertMethod(factory, cls, classEntity); 56 | onEndProcess(classEntity, factory, cls, visitor); 57 | } 58 | 59 | protected void onEndProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls, IProcessor visitor) { 60 | if (visitor != null) { 61 | visitor.onEndProcess(classEntity, factory, cls); 62 | } 63 | formatJavCode(cls); 64 | } 65 | 66 | protected void formatJavCode(PsiClass cls) { 67 | if (cls == null) { 68 | return; 69 | } 70 | JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(cls.getProject()); 71 | styleManager.optimizeImports(cls.getContainingFile()); 72 | styleManager.shortenClassReferences(cls); 73 | } 74 | 75 | protected void onStarProcess(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls, IProcessor visitor) { 76 | if (visitor != null) { 77 | visitor.onStarProcess(classEntity, factory, cls); 78 | } 79 | } 80 | 81 | protected void generateConvertMethod(PsiElementFactory factory, PsiClass cls, ClassEntity classEntity) { 82 | if (cls == null || cls.getName() == null) { 83 | return; 84 | } 85 | if (Config.getInstant().isObjectFromData()) { 86 | createMethod(factory, Config.getInstant().getObjectFromDataStr().replace("$ClassName$", cls.getName()).trim(), cls); 87 | } 88 | if (Config.getInstant().isObjectFromData1()) { 89 | createMethod(factory, Config.getInstant().getObjectFromDataStr1().replace("$ClassName$", cls.getName()).trim(), cls); 90 | } 91 | if (Config.getInstant().isArrayFromData()) { 92 | createMethod(factory, Config.getInstant().getArrayFromDataStr().replace("$ClassName$", cls.getName()).trim(), cls); 93 | } 94 | if (Config.getInstant().isArrayFromData1()) { 95 | createMethod(factory, Config.getInstant().getArrayFromData1Str().replace("$ClassName$", cls.getName()).trim(), cls); 96 | } 97 | } 98 | 99 | protected void generateGetterAndSetter(PsiElementFactory factory, PsiClass cls, ClassEntity classEntity) { 100 | 101 | if (Config.getInstant().isFieldPrivateMode()) { 102 | for (FieldEntity field : classEntity.getFields()) { 103 | createGetAndSetMethod(factory, cls, field); 104 | } 105 | } 106 | } 107 | 108 | protected void createMethod(PsiElementFactory factory, String method, PsiClass cls) { 109 | Try.run(new Try.TryListener() { 110 | @Override 111 | public void run() { 112 | cls.add(factory.createMethodFromText(method, cls)); 113 | } 114 | 115 | @Override 116 | public void runAgain() { 117 | 118 | } 119 | 120 | @Override 121 | public void error() { 122 | 123 | } 124 | }); 125 | } 126 | 127 | protected void createGetAndSetMethod(PsiElementFactory factory, PsiClass cls, FieldEntity field) { 128 | if (field.isGenerate()) { 129 | String fieldName = field.getGenerateFieldName(); 130 | String typeStr = field.getRealType(); 131 | if (Config.getInstant().isUseFieldNamePrefix()) { 132 | String temp = fieldName.replaceAll("^" + Config.getInstant().getFiledNamePreFixStr(), ""); 133 | if (!TextUtils.isEmpty(temp)) { 134 | fieldName = temp; 135 | } 136 | } 137 | if (typeStr.equals("boolean") || typeStr.equals("Boolean")) { 138 | String method = "public ".concat(typeStr).concat(" is").concat( 139 | captureName(fieldName)).concat("() { return ").concat( 140 | field.getGenerateFieldName()).concat(" ;} "); 141 | cls.add(factory.createMethodFromText(method, cls)); 142 | } else { 143 | String method = "public ".concat(typeStr).concat(" get").concat( 144 | captureName(fieldName)).concat( 145 | "() { return ").concat( 146 | field.getGenerateFieldName()).concat(" ;} "); 147 | cls.add(factory.createMethodFromText(method, cls)); 148 | } 149 | 150 | String arg = fieldName; 151 | if (Config.getInstant().isUseFieldNamePrefix()) { 152 | String temp = fieldName.replaceAll("^" + Config.getInstant().getFiledNamePreFixStr(), ""); 153 | if (!TextUtils.isEmpty(temp)) { 154 | fieldName = temp; 155 | arg = fieldName; 156 | if (arg.length() > 0) { 157 | 158 | if (arg.length() > 1) { 159 | arg = (arg.charAt(0) + "").toLowerCase() + arg.substring(1); 160 | } else { 161 | arg = arg.toLowerCase(); 162 | } 163 | } 164 | } 165 | } 166 | 167 | String method = "public void set".concat(captureName(fieldName)).concat("( ").concat(typeStr).concat(" ").concat(arg).concat(") { "); 168 | if (field.getGenerateFieldName().equals(arg)) { 169 | method = method.concat("this.").concat(field.getGenerateFieldName()).concat(" = ").concat(arg).concat(";} "); 170 | } else { 171 | method = method.concat(field.getGenerateFieldName()).concat(" = ").concat(arg).concat(";} "); 172 | } 173 | 174 | String finalMethod = method; 175 | String finalFieldName = fieldName; 176 | Try.run(new Try.TryListener() { 177 | @Override 178 | public void run() { 179 | cls.add(factory.createMethodFromText(finalMethod, cls)); 180 | } 181 | 182 | @Override 183 | public void runAgain() { 184 | cls.addBefore(factory.createCommentFromText("// FIXME generate failure method set and get " + captureName(finalFieldName), cls), cls.getChildren()[0]); 185 | 186 | } 187 | 188 | @Override 189 | public void error() { 190 | 191 | } 192 | }); 193 | } 194 | } 195 | 196 | protected void generateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, IProcessor visitor) { 197 | 198 | onStartGenerateClass(factory, classEntity, parentClass, visitor); 199 | PsiClass generateClass = null; 200 | if (classEntity.isGenerate()) { 201 | //// TODO: 16/11/9 待重构 202 | if (Config.getInstant().isSplitGenerate()) { 203 | try { 204 | generateClass = PsiClassUtil.getPsiClass( 205 | parentClass.getContainingFile(), parentClass.getProject(), classEntity.getQualifiedName()); 206 | } catch (Throwable throwable) { 207 | throwable.printStackTrace(); 208 | } 209 | } else { 210 | String classContent = 211 | "public static class " + classEntity.getClassName() + "{}"; 212 | generateClass = factory.createClassFromText(classContent, null).getInnerClasses()[0]; 213 | } 214 | 215 | if (generateClass != null) { 216 | 217 | for (ClassEntity innerClass : classEntity.getInnerClasss()) { 218 | generateClass(factory, innerClass, generateClass, visitor); 219 | } 220 | if (!Config.getInstant().isSplitGenerate()) { 221 | generateClass = (PsiClass) parentClass.add(generateClass); 222 | } 223 | for (FieldEntity fieldEntity : classEntity.getFields()) { 224 | generateField(factory, fieldEntity, generateClass, classEntity); 225 | } 226 | generateGetterAndSetter(factory, generateClass, classEntity); 227 | generateConvertMethod(factory, generateClass, classEntity); 228 | } 229 | } 230 | onEndGenerateClass(factory, classEntity, parentClass, generateClass, visitor); 231 | if (Config.getInstant().isSplitGenerate()) { 232 | formatJavCode(generateClass); 233 | } 234 | } 235 | 236 | protected void onStartGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, IProcessor visitor) { 237 | if (visitor != null) { 238 | visitor.onStartGenerateClass(factory, classEntity, parentClass); 239 | } 240 | } 241 | 242 | protected void onEndGenerateClass(PsiElementFactory factory, ClassEntity classEntity, PsiClass parentClass, PsiClass generateClass, IProcessor visitor) { 243 | if (visitor != null) { 244 | visitor.onEndGenerateClass(factory, classEntity, parentClass, generateClass); 245 | } 246 | } 247 | 248 | protected void generateField(PsiElementFactory factory, FieldEntity fieldEntity, PsiClass cls, ClassEntity classEntity) { 249 | 250 | if (fieldEntity.isGenerate()) { 251 | Try.run(new Try.TryListener() { 252 | @Override 253 | public void run() { 254 | cls.add(factory.createFieldFromText(generateFieldText(classEntity, fieldEntity, null), cls)); 255 | 256 | } 257 | 258 | @Override 259 | public void runAgain() { 260 | fieldEntity.setFieldName(FieldHelper.generateLuckyFieldName(fieldEntity.getFieldName())); 261 | cls.add(factory.createFieldFromText(generateFieldText(classEntity, fieldEntity, Constant.FIXME), cls)); 262 | } 263 | 264 | @Override 265 | public void error() { 266 | cls.addBefore(factory.createCommentFromText("// FIXME generate failure field " + fieldEntity.getFieldName(), cls), cls.getChildren()[0]); 267 | } 268 | }); 269 | 270 | } 271 | 272 | } 273 | 274 | private String generateFieldText(ClassEntity classEntity, FieldEntity fieldEntity, String fixme) { 275 | fixme = fixme == null ? "" : fixme; 276 | StringBuilder fieldSb = new StringBuilder(); 277 | String filedName = fieldEntity.getGenerateFieldName(); 278 | if (!TextUtils.isEmpty(classEntity.getExtra())) { 279 | fieldSb.append(classEntity.getExtra()).append("\n"); 280 | classEntity.setExtra(null); 281 | } 282 | if (fieldEntity.getTargetClass() != null) { 283 | fieldEntity.getTargetClass().setGenerate(true); 284 | } 285 | if (!filedName.equals(fieldEntity.getKey()) || Config.getInstant().isUseSerializedName()) { 286 | fieldSb.append(Config.getInstant().geFullNameAnnotation().replaceAll("\\{filed\\}", fieldEntity.getKey())); 287 | } 288 | 289 | if (Config.getInstant().isFieldPrivateMode()) { 290 | fieldSb.append("private ").append(fieldEntity.getFullNameType()).append(" ").append(filedName).append(" ; "); 291 | } else { 292 | fieldSb.append("public ").append(fieldEntity.getFullNameType()).append(" ").append(filedName).append(" ; "); 293 | } 294 | return fieldSb.append(fixme).toString(); 295 | } 296 | } 297 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/EditDialog.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 |
99 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/EditDialog.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.ui; 2 | 3 | import org.gsonformat.intellij.config.Config; 4 | import org.gsonformat.intellij.config.Constant; 5 | 6 | import javax.swing.*; 7 | import java.awt.event.*; 8 | 9 | public class EditDialog extends JFrame { 10 | 11 | private JPanel contentPane; 12 | private JButton okButton; 13 | private JButton cancelButton; 14 | private JTextPane editTP; 15 | private JButton resetButton; 16 | private JLabel titleLB; 17 | private String titleName; 18 | private String editStr; 19 | private Type type; 20 | 21 | public EditDialog(Type type) { 22 | this.type = type; 23 | setContentPane(contentPane); 24 | // setModal(true); 25 | this.setAlwaysOnTop(true); 26 | getRootPane().setDefaultButton(okButton); 27 | okButton.addActionListener(new ActionListener() { 28 | public void actionPerformed(ActionEvent e) { 29 | onOK(); 30 | } 31 | }); 32 | cancelButton.addActionListener(new ActionListener() { 33 | public void actionPerformed(ActionEvent e) { 34 | onCancel(); 35 | } 36 | }); 37 | setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); 38 | addWindowListener(new WindowAdapter() { 39 | public void windowClosing(WindowEvent e) { 40 | onCancel(); 41 | } 42 | }); 43 | contentPane.registerKeyboardAction(new ActionListener() { 44 | public void actionPerformed(ActionEvent e) { 45 | onCancel(); 46 | } 47 | }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 48 | setTitle("Convert method"); 49 | 50 | switch (type) { 51 | case OBJECT_FROM_DATA: 52 | titleName = "objectFromData(Object data)"; 53 | editStr = Config.getInstant().getObjectFromDataStr(); 54 | break; 55 | case OBJECT_FROM_DATA1: 56 | titleName = "objectFromData(Object data,String key)"; 57 | editStr = Config.getInstant().getObjectFromDataStr1(); 58 | break; 59 | case ARRAY_FROM_DATA: 60 | titleName = "arrayFromData(Object data)"; 61 | editStr = Config.getInstant().getArrayFromDataStr(); 62 | break; 63 | case ARRAY_FROM_DATA1: 64 | titleName = "arrayFromData(Object data,String key)"; 65 | editStr = Config.getInstant().getArrayFromData1Str(); 66 | break; 67 | } 68 | titleLB.setText(titleName); 69 | editTP.setText(editStr); 70 | resetButton.addActionListener(new ActionListener() { 71 | @Override 72 | public void actionPerformed(ActionEvent actionEvent) { 73 | resetAction(); 74 | } 75 | }); 76 | 77 | 78 | } 79 | 80 | private void resetAction() { 81 | 82 | switch (type) { 83 | case OBJECT_FROM_DATA: 84 | editTP.setText(Constant.objectFromObject); 85 | break; 86 | case OBJECT_FROM_DATA1: 87 | System.out.println(Constant.objectFromObject1); 88 | editTP.setText(Constant.objectFromObject1); 89 | break; 90 | case ARRAY_FROM_DATA: 91 | editTP.setText(Constant.arrayFromData); 92 | break; 93 | case ARRAY_FROM_DATA1: 94 | editTP.setText(Constant.arrayFromData1); 95 | break; 96 | } 97 | } 98 | 99 | private void onOK() { 100 | 101 | switch (type) { 102 | case OBJECT_FROM_DATA: 103 | Config.getInstant().saveObjectFromDataStr(editTP.getText()); 104 | break; 105 | case OBJECT_FROM_DATA1: 106 | Config.getInstant().saveObjectFromDataStr1(editTP.getText()); 107 | break; 108 | case ARRAY_FROM_DATA: 109 | Config.getInstant().saveArrayFromDataStr(editTP.getText()); 110 | break; 111 | case ARRAY_FROM_DATA1: 112 | Config.getInstant().saveArrayFromData1Str(editTP.getText()); 113 | break; 114 | } 115 | 116 | dispose(); 117 | } 118 | 119 | private void onCancel() { 120 | 121 | dispose(); 122 | } 123 | 124 | public enum Type { 125 | OBJECT_FROM_DATA, OBJECT_FROM_DATA1, ARRAY_FROM_DATA, ARRAY_FROM_DATA1; 126 | } 127 | 128 | } 129 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/ErrorDialog.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 |
70 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/ErrorDialog.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.ui; 2 | 3 | import javax.swing.*; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | 7 | public class ErrorDialog extends JFrame { 8 | 9 | private JPanel contentPane; 10 | private JTextPane editTP; 11 | private JButton okButton; 12 | private JScrollPane scrollPane; 13 | 14 | public ErrorDialog(String errorInfo) { 15 | setContentPane(contentPane); 16 | setTitle("Error Info"); 17 | getRootPane().setDefaultButton(okButton); 18 | this.setAlwaysOnTop(true); 19 | editTP.setText(errorInfo); 20 | okButton.addActionListener(new ActionListener() { 21 | public void actionPerformed(ActionEvent e) { 22 | dispose(); 23 | } 24 | }); 25 | editTP.setCaretPosition(0); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/FieldsDialog.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 |
93 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/FieldsDialog.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.ui; 2 | 3 | import cn.vearn.checktreetable.FiledTreeTableModel; 4 | import com.intellij.openapi.command.WriteCommandAction; 5 | import com.intellij.openapi.project.Project; 6 | import com.intellij.psi.PsiClass; 7 | import com.intellij.psi.PsiElementFactory; 8 | import com.intellij.psi.PsiFile; 9 | import org.gsonformat.intellij.ConvertBridge; 10 | import org.gsonformat.intellij.action.DataWriter; 11 | import org.gsonformat.intellij.common.PsiClassUtil; 12 | import org.gsonformat.intellij.common.StringUtils; 13 | import org.gsonformat.intellij.config.Config; 14 | import org.gsonformat.intellij.entity.ClassEntity; 15 | import org.gsonformat.intellij.entity.FieldEntity; 16 | import org.jdesktop.swingx.JXTreeTable; 17 | import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; 18 | import org.jdesktop.swingx.ux.CheckTreeTableManager; 19 | 20 | import javax.swing.*; 21 | import javax.swing.event.ListSelectionEvent; 22 | import javax.swing.event.ListSelectionListener; 23 | import java.awt.event.*; 24 | import java.io.PrintWriter; 25 | import java.io.StringWriter; 26 | import java.io.Writer; 27 | import java.util.ArrayList; 28 | 29 | import static javax.swing.ListSelectionModel.SINGLE_SELECTION; 30 | 31 | public class FieldsDialog extends JFrame { 32 | 33 | private JPanel contentPane; 34 | private JButton buttonOK; 35 | private JButton buttonCancel; 36 | private JPanel filedPanel; 37 | private JScrollPane sp; 38 | private PsiClass psiClass; 39 | private ClassEntity classEntity; 40 | private ConvertBridge.Operator operator; 41 | private PsiElementFactory factory; 42 | private PsiClass aClass; 43 | private PsiFile file; 44 | private Project project; 45 | private JLabel generateClass; 46 | private String generateClassStr; 47 | private ArrayList defaultMutableTreeTableNodeList; 48 | 49 | 50 | public FieldsDialog(ConvertBridge.Operator operator, ClassEntity classEntity, 51 | PsiElementFactory factory, PsiClass psiClass, PsiClass aClass, PsiFile file, Project project 52 | , String generateClassStr) { 53 | this.operator = operator; 54 | this.factory = factory; 55 | this.aClass = aClass; 56 | this.file = file; 57 | this.project = project; 58 | this.psiClass = psiClass; 59 | this.generateClassStr = generateClassStr; 60 | setContentPane(contentPane); 61 | setTitle("Virgo Model"); 62 | getRootPane().setDefaultButton(buttonOK); 63 | this.setAlwaysOnTop(true); 64 | initListener(classEntity, generateClassStr); 65 | } 66 | 67 | private void initListener(ClassEntity classEntity, String generateClassStr) { 68 | this.classEntity = classEntity; 69 | defaultMutableTreeTableNodeList = new ArrayList(); 70 | JXTreeTable treetable = new JXTreeTable(new FiledTreeTableModel(createData(classEntity))); 71 | CheckTreeTableManager manager = new CheckTreeTableManager(treetable); 72 | manager.getSelectionModel().addPathsByNodes(defaultMutableTreeTableNodeList); 73 | treetable.getColumnModel().getColumn(0).setPreferredWidth(150); 74 | // treetable.setSelectionBackground(treetable.getBackground()); 75 | treetable.expandAll(); 76 | treetable.setCellSelectionEnabled(false); 77 | final DefaultListSelectionModel defaultListSelectionModel = new DefaultListSelectionModel(); 78 | treetable.setSelectionModel(defaultListSelectionModel); 79 | 80 | defaultListSelectionModel.setSelectionMode(SINGLE_SELECTION); 81 | defaultListSelectionModel.addListSelectionListener(new ListSelectionListener() { 82 | @Override 83 | public void valueChanged(ListSelectionEvent e) { 84 | defaultListSelectionModel.clearSelection(); 85 | } 86 | }); 87 | defaultMutableTreeTableNodeList = null; 88 | treetable.setRowHeight(30); 89 | sp.setViewportView(treetable); 90 | generateClass.setText(generateClassStr); 91 | buttonOK.addActionListener(new ActionListener() { 92 | public void actionPerformed(ActionEvent e) { 93 | onOK(); 94 | } 95 | }); 96 | buttonCancel.addActionListener(new ActionListener() { 97 | public void actionPerformed(ActionEvent e) { 98 | onCancel(); 99 | } 100 | }); 101 | setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); 102 | addWindowListener(new WindowAdapter() { 103 | public void windowClosing(WindowEvent e) { 104 | onCancel(); 105 | } 106 | }); 107 | contentPane.registerKeyboardAction(new ActionListener() { 108 | public void actionPerformed(ActionEvent e) { 109 | onCancel(); 110 | } 111 | }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 112 | 113 | contentPane.registerKeyboardAction(new ActionListener() { 114 | public void actionPerformed(ActionEvent e) { 115 | onOK(); 116 | } 117 | }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 118 | } 119 | 120 | private void onOK() { 121 | this.setAlwaysOnTop(false); 122 | WriteCommandAction.runWriteCommandAction(project, new Runnable() { 123 | 124 | @Override 125 | public void run() { 126 | if (psiClass == null) { 127 | try { 128 | psiClass = PsiClassUtil.getPsiClass(file, project, generateClassStr); 129 | } catch (Throwable throwable) { 130 | throwable.printStackTrace(); 131 | operator.showError(ConvertBridge.Error.DATA_ERROR); 132 | Writer writer = new StringWriter(); 133 | PrintWriter printWriter = new PrintWriter(writer); 134 | throwable.printStackTrace(printWriter); 135 | printWriter.close(); 136 | operator.setErrorInfo(writer.toString()); 137 | operator.setVisible(true); 138 | operator.showError(ConvertBridge.Error.PATH_ERROR); 139 | } 140 | } 141 | 142 | if (psiClass != null) { 143 | String[] arg = generateClassStr.split("\\."); 144 | if (arg.length > 1) { 145 | Config.getInstant().setEntityPackName(generateClassStr.substring(0, generateClassStr.length() - arg[arg.length - 1].length())); 146 | Config.getInstant().save(); 147 | } 148 | try { 149 | setVisible(false); 150 | DataWriter dataWriter = new DataWriter(file, project, psiClass); 151 | dataWriter.execute(classEntity); 152 | Config.getInstant().saveCurrentPackPath(StringUtils.getPackage(generateClassStr)); 153 | operator.dispose(); 154 | dispose(); 155 | } catch (Exception e) { 156 | e.printStackTrace(); 157 | operator.showError(ConvertBridge.Error.PARSE_ERROR); 158 | Writer writer = new StringWriter(); 159 | PrintWriter printWriter = new PrintWriter(writer); 160 | e.printStackTrace(printWriter); 161 | printWriter.close(); 162 | operator.setErrorInfo(writer.toString()); 163 | operator.setVisible(true); 164 | dispose(); 165 | } 166 | } 167 | } 168 | }); 169 | } 170 | 171 | private void onCancel() { 172 | operator.setVisible(true); 173 | dispose(); 174 | } 175 | 176 | private DefaultMutableTreeTableNode createData(ClassEntity classEntity) { 177 | DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode(classEntity); 178 | createDataNode(root, classEntity); 179 | return root; 180 | } 181 | 182 | private void createDataNode(DefaultMutableTreeTableNode root, ClassEntity innerClassEntity) { 183 | for (FieldEntity field : innerClassEntity.getFields()) { 184 | DefaultMutableTreeTableNode node = new DefaultMutableTreeTableNode(field); 185 | root.add(node); 186 | defaultMutableTreeTableNodeList.add(node); 187 | } 188 | for (ClassEntity classEntity : innerClassEntity.getInnerClasss()) { 189 | DefaultMutableTreeTableNode node = new DefaultMutableTreeTableNode(classEntity); 190 | root.add(node); 191 | createDataNode(node, classEntity); 192 | } 193 | 194 | } 195 | 196 | } 197 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/JsonDialog.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 |
190 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/JsonDialog.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.ui; 2 | 3 | import com.intellij.openapi.project.Project; 4 | import com.intellij.openapi.ui.MessageType; 5 | import com.intellij.psi.PsiClass; 6 | import com.intellij.psi.PsiFile; 7 | import com.intellij.psi.impl.source.PsiJavaFileImpl; 8 | import org.apache.http.util.TextUtils; 9 | import org.gsonformat.intellij.ConvertBridge; 10 | import org.gsonformat.intellij.common.PsiClassUtil; 11 | import org.gsonformat.intellij.config.Config; 12 | import org.json.JSONArray; 13 | import org.json.JSONObject; 14 | 15 | import javax.swing.*; 16 | import java.awt.*; 17 | import java.awt.event.*; 18 | 19 | public class JsonDialog extends JFrame implements ConvertBridge.Operator { 20 | 21 | private CardLayout cardLayout; 22 | private JPanel contentPane2; 23 | private JButton okButton; 24 | private JButton cancelButton; 25 | private JLabel errorLB; 26 | private JTextPane editTP; 27 | private JButton settingButton; 28 | private JLabel generateClassLB; 29 | private JTextField generateClassTF; 30 | private JPanel generateClassP; 31 | private JButton formatBtn; 32 | private PsiClass cls; 33 | private PsiFile file; 34 | private Project project; 35 | private String errorInfo = null; 36 | private String currentClass = null; 37 | 38 | public JsonDialog(PsiClass cls, PsiFile file, Project project) throws HeadlessException { 39 | this.cls = cls; 40 | this.file = file; 41 | this.project = project; 42 | setContentPane(contentPane2); 43 | setTitle("GsonFormat"); 44 | getRootPane().setDefaultButton(okButton); 45 | this.setAlwaysOnTop(true); 46 | initGeneratePanel(file); 47 | initListener(); 48 | } 49 | 50 | private void initListener() { 51 | 52 | okButton.addActionListener(new ActionListener() { 53 | public void actionPerformed(ActionEvent e) { 54 | if (generateClassTF.isFocusOwner()) { 55 | editTP.requestFocus(true); 56 | } else { 57 | onOK(); 58 | } 59 | } 60 | }); 61 | formatBtn.addActionListener(new ActionListener() { 62 | public void actionPerformed(ActionEvent e) { 63 | String json = editTP.getText(); 64 | json = json.trim(); 65 | if (json.startsWith("{")) { 66 | JSONObject jsonObject = new JSONObject(json); 67 | String formatJson = jsonObject.toString(4); 68 | editTP.setText(formatJson); 69 | } else if (json.startsWith("[")) { 70 | JSONArray jsonArray = new JSONArray(json); 71 | String formatJson = jsonArray.toString(4); 72 | editTP.setText(formatJson); 73 | } 74 | 75 | } 76 | }); 77 | editTP.addKeyListener(new KeyAdapter() { 78 | @Override 79 | public void keyReleased(KeyEvent keyEvent) { 80 | super.keyReleased(keyEvent); 81 | if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) { 82 | onOK(); 83 | } 84 | } 85 | }); 86 | generateClassP.addKeyListener(new KeyAdapter() { 87 | @Override 88 | public void keyReleased(KeyEvent keyEvent) { 89 | super.keyReleased(keyEvent); 90 | if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) { 91 | editTP.requestFocus(true); 92 | } 93 | } 94 | }); 95 | errorLB.addMouseListener(new MouseAdapter() { 96 | 97 | @Override 98 | public void mouseClicked(MouseEvent mouseEvent) { 99 | super.mouseClicked(mouseEvent); 100 | if (errorInfo != null) { 101 | ErrorDialog errorDialog = new ErrorDialog(errorInfo); 102 | errorDialog.setSize(800, 600); 103 | errorDialog.setLocationRelativeTo(null); 104 | errorDialog.setVisible(true); 105 | } 106 | } 107 | }); 108 | cancelButton.addActionListener(new ActionListener() { 109 | public void actionPerformed(ActionEvent e) { 110 | onCancel(); 111 | } 112 | }); 113 | settingButton.addActionListener(new ActionListener() { 114 | public void actionPerformed(ActionEvent e) { 115 | openSettingDialog(); 116 | } 117 | }); 118 | setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); 119 | addWindowListener(new WindowAdapter() { 120 | public void windowClosing(WindowEvent e) { 121 | onCancel(); 122 | } 123 | }); 124 | contentPane2.registerKeyboardAction(new ActionListener() { 125 | public void actionPerformed(ActionEvent e) { 126 | onCancel(); 127 | } 128 | }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 129 | } 130 | 131 | private void initGeneratePanel(PsiFile file) { 132 | 133 | cardLayout = (CardLayout) generateClassP.getLayout(); 134 | generateClassTF.setBackground(errorLB.getBackground()); 135 | currentClass = ((PsiJavaFileImpl) file).getPackageName() + "." + file.getName().split("\\.")[0]; 136 | generateClassLB.setText(currentClass); 137 | generateClassTF.setText(currentClass); 138 | generateClassTF.addFocusListener(new FocusListener() { 139 | @Override 140 | public void focusGained(FocusEvent focusEvent) { 141 | } 142 | 143 | @Override 144 | public void focusLost(FocusEvent focusEvent) { 145 | cardLayout.next(generateClassP); 146 | if (TextUtils.isEmpty(generateClassTF.getText())) { 147 | generateClassLB.setText(currentClass); 148 | generateClassTF.setText(currentClass); 149 | } else { 150 | generateClassLB.setText(generateClassTF.getText()); 151 | } 152 | } 153 | }); 154 | 155 | generateClassLB.addMouseListener(new MouseAdapter() { 156 | @Override 157 | public void mouseClicked(MouseEvent mouseEvent) { 158 | super.mouseClicked(mouseEvent); 159 | cardLayout.next(generateClassP); 160 | if (generateClassLB.getText().equals(currentClass) && !TextUtils.isEmpty(Config.getInstant().getEntityPackName()) && !Config.getInstant().getEntityPackName().equals("null")) { 161 | generateClassLB.setText(Config.getInstant().getEntityPackName()); 162 | generateClassTF.setText(Config.getInstant().getEntityPackName()); 163 | } 164 | generateClassTF.requestFocus(true); 165 | } 166 | 167 | }); 168 | } 169 | 170 | private void onOK() { 171 | 172 | this.setAlwaysOnTop(false); 173 | String jsonSTR = editTP.getText().trim(); 174 | if (TextUtils.isEmpty(jsonSTR)) { 175 | return; 176 | } 177 | String generateClassName = generateClassTF.getText().replaceAll(" ", "").replaceAll(".java$", ""); 178 | if (TextUtils.isEmpty(generateClassName) || generateClassName.endsWith(".")) { 179 | Toast.make(project, generateClassP, MessageType.ERROR, "the path is not allowed"); 180 | return; 181 | } 182 | PsiClass generateClass = null; 183 | if (!currentClass.equals(generateClassName)) { 184 | generateClass = PsiClassUtil.exist(file, generateClassTF.getText()); 185 | } else { 186 | generateClass = cls; 187 | } 188 | 189 | new ConvertBridge(this, jsonSTR, file, project, generateClass, 190 | cls, generateClassName).run(); 191 | } 192 | private void onCancel() { 193 | dispose(); 194 | } 195 | 196 | 197 | public PsiClass getClss() { 198 | return cls; 199 | } 200 | 201 | public void setClass(PsiClass mClass) { 202 | this.cls = mClass; 203 | } 204 | 205 | public void setProject(Project mProject) { 206 | this.project = mProject; 207 | } 208 | 209 | public void setFile(PsiFile mFile) { 210 | this.file = mFile; 211 | } 212 | 213 | private void createUIComponents() { 214 | 215 | } 216 | 217 | public void openSettingDialog() { 218 | 219 | SettingDialog settingDialog = new SettingDialog(project); 220 | settingDialog.setSize(800, 720); 221 | settingDialog.setLocationRelativeTo(null); 222 | // settingDialog.setResizable(false); 223 | settingDialog.setVisible(true); 224 | } 225 | 226 | 227 | public void cleanErrorInfo() { 228 | errorInfo = null; 229 | } 230 | 231 | public void setErrorInfo(String error) { 232 | errorInfo = error; 233 | } 234 | 235 | @Override 236 | public void showError(ConvertBridge.Error err) { 237 | switch (err) { 238 | case DATA_ERROR: 239 | errorLB.setText("data err !!"); 240 | if (Config.getInstant().isToastError()) { 241 | Toast.make(project, errorLB, MessageType.ERROR, "click to see details"); 242 | } 243 | break; 244 | case PARSE_ERROR: 245 | errorLB.setText("parse err !!"); 246 | if (Config.getInstant().isToastError()) { 247 | Toast.make(project, errorLB, MessageType.ERROR, "click to see details"); 248 | } 249 | break; 250 | case PATH_ERROR: 251 | Toast.make(project, generateClassP, MessageType.ERROR, "the path is not allowed"); 252 | break; 253 | } 254 | } 255 | 256 | } 257 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/NotificationCenter.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.ui; 2 | 3 | import com.intellij.notification.Notification; 4 | import com.intellij.notification.NotificationType; 5 | import com.intellij.notification.Notifications; 6 | 7 | public class NotificationCenter { 8 | public static void info(String message) { 9 | sendNotification(message, NotificationType.INFORMATION); 10 | } 11 | 12 | public static void error(String message) { 13 | sendNotification(message, NotificationType.ERROR); 14 | } 15 | 16 | public static void sendNotification(String message, NotificationType notificationType) { 17 | if(message == null || message.trim().length()==0){ 18 | return; 19 | } 20 | Notification notification = new Notification("com.dim.plugin.Gsonformat", "Gsonformat ", espaceString(message), notificationType); 21 | Notifications.Bus.notify(notification); 22 | } 23 | 24 | 25 | private static String espaceString(String string) { 26 | // replace with both so that it returns are preserved in the notification ballon and in the event log 27 | return string.replaceAll("\n", "\n
"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/gsonformat/intellij/ui/Toast.java: -------------------------------------------------------------------------------- 1 | package org.gsonformat.intellij.ui; 2 | 3 | import com.intellij.openapi.project.Project; 4 | import com.intellij.openapi.ui.MessageType; 5 | import com.intellij.openapi.ui.popup.Balloon; 6 | import com.intellij.openapi.ui.popup.JBPopupFactory; 7 | import com.intellij.openapi.wm.StatusBar; 8 | import com.intellij.openapi.wm.WindowManager; 9 | import com.intellij.ui.awt.RelativePoint; 10 | 11 | import javax.swing.*; 12 | 13 | /** 14 | * Created by dim on 15/8/24. 15 | */ 16 | public class Toast { 17 | 18 | /** 19 | * Display simple notification of given type 20 | * 21 | * @param project 22 | * @param type 23 | * @param text 24 | */ 25 | public static void make(Project project, JComponent jComponent, MessageType type, String text) { 26 | 27 | StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); 28 | 29 | JBPopupFactory.getInstance() 30 | .createHtmlTextBalloonBuilder(text, type, null) 31 | .setFadeoutTime(7500) 32 | .createBalloon() 33 | .show(RelativePoint.getCenterOf(jComponent), Balloon.Position.above); 34 | } 35 | 36 | /** 37 | * Display simple notification of given type 38 | * 39 | * @param project 40 | * @param type 41 | * @param text 42 | */ 43 | public static void make(Project project, MessageType type, String text) { 44 | 45 | StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); 46 | 47 | JBPopupFactory.getInstance() 48 | .createHtmlTextBalloonBuilder(text, type, null) 49 | .setFadeoutTime(7500) 50 | .createBalloon() 51 | .show(RelativePoint.getCenterOf(statusBar.getComponent()), Balloon.Position.atRight); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | GsonFormat 3 | quickly to convert a JSON string to an InnerClassEntity class ..
5 | openSource 6 | 7 | ]]> 8 |
9 | 1.5.0 10 | zzz40500 11 | 12 | 14 | 1.4.0 15 |
    16 |
  • New: Support for autovalue
  • 17 |
  • New: Support for lombok
  • 18 |
  • New: Support for split generate class
  • 19 |
20 | 1.5.0 21 |
    22 |
  • fix several bug
  • 23 |
  • fix unlock setting window size
  • 24 |

    25 | ]]> 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /测试用例. txt: -------------------------------------------------------------------------------- 1 | 测试1: 简单模型测试 2 | 3 | { 4 | "name": "王五", 5 | "gender": "man", 6 | "age": 15, 7 | "height": "140cm" 8 | } 9 | 测试2: 多种模型测试 10 | 11 | { 12 | "name": "王五", 13 | "gender": "man", 14 | "age": 15, 15 | "height": "140cm", 16 | "addr": { 17 | "province": "fujian", 18 | "city": "quanzhou", 19 | "code": "300000" 20 | }, 21 | "hobby": [ 22 | { 23 | "name": "billiards", 24 | "code": "1" 25 | }, 26 | { 27 | "name": "computerGame", 28 | "code": "2" 29 | } 30 | ] 31 | } 32 | 33 | 34 | 测试3: 测试List泛型 35 | 36 | { "list": [1,2,3,4] } 37 | 38 | 测试4: 测试多重嵌套 39 | { 40 | "kind": "youtube#searchListResponse", 41 | "etag": "\"k1sYjErg4tK7WaQQxvJkW5fVrfg/usRLzp_l5ss-L8Yb9ScY-VDAEOo\"", 42 | "nextPageToken": "CAIQAA", 43 | "pageInfo": { 44 | "totalResults": 1000000, 45 | "resultsPerPage": 2 46 | }, 47 | "items": [ 48 | { 49 | "kind": "youtube#searchResult", 50 | "etag": "\"k1sYjErg4tK7WaQQxvJkW5fVrfg/D0nlqgSgFFEQnTduJtwcQZ3Hc78\"", 51 | "id": { 52 | "kind": "youtube#video", 53 | "videoId": "5ixFWqZGZr8" 54 | }, 55 | "snippet": { 56 | "publishedAt": "2014-10-16T19:43:41.000Z", 57 | "channelId": "UC9-3c4LzdzT_HvW3Xuti9wg", 58 | "title": "Q&A WITH HARRY | PRANK CALLS!", 59 | "description": "Can we smash 4000 likes for this Q&A!? My Flatmate Harold - http://www.youtube.com/W2S Buy Cheap and Instant Coins here: http://goo.gl/IZyNg2 Use code ...", 60 | "thumbnails": { 61 | "default": { 62 | "url": "https://i.ytimg.com/vi/5ixFWqZGZr8/default.jpg" 63 | }, 64 | "medium": { 65 | "url": "https://i.ytimg.com/vi/5ixFWqZGZr8/mqdefault.jpg" 66 | }, 67 | "high": { 68 | "url": "https://i.ytimg.com/vi/5ixFWqZGZr8/hqdefault.jpg" 69 | } 70 | }, 71 | "channelTitle": "Calfreezy", 72 | "liveBroadcastContent": "none" 73 | } 74 | }, 75 | { 76 | "kind": "youtube#searchResult", 77 | "etag": "\"k1sYjErg4tK7WaQQxvJkW5fVrfg/R5nmI-OBXmHyiXsGtMC3J6IUlBs\"", 78 | "id": { 79 | "kind": "youtube#video", 80 | "videoId": "8KgzATFR0As" 81 | }, 82 | "snippet": { 83 | "publishedAt": "2014-09-03T12:49:15.000Z", 84 | "channelId": "UC8_yRRDIGFaJEC7NOc1qTMw", 85 | "title": "Harry at 30 Documentary", 86 | "description": "In celebration of Prince Harry's 30th birthday, ITV have released a new documentary celebrating the past three decades of his life. Featuring archive footage...", 87 | "thumbnails": { 88 | "default": { 89 | "url": "https://i.ytimg.com/vi/8KgzATFR0As/default.jpg" 90 | }, 91 | "medium": { 92 | "url": "https://i.ytimg.com/vi/8KgzATFR0As/mqdefault.jpg" 93 | }, 94 | "high": { 95 | "url": "https://i.ytimg.com/vi/8KgzATFR0As/hqdefault.jpg" 96 | } 97 | }, 98 | "channelTitle": "", 99 | "liveBroadcastContent": "none" 100 | } 101 | } 102 | ] 103 | } 104 | 105 | 测试 5 106 | 107 | { 108 | "_r":0, 109 | "err":"None", 110 | "photo":"http://xxxx.com/photo.jpg" 111 | } 112 | 113 | 测试 6 114 | 115 | 116 | { 117 | "mesg": "获取商品列表(某类型)", 118 | "data": { 119 | "list": [ 120 | { 121 | "y_price": "4", 122 | "selled": "100", 123 | "score": "5", 124 | "package": "200g", 125 | "isSpecial": "0", 126 | "n_price": "4", 127 | "nation": "中国", 128 | "version": "1", 129 | "productId": "1", 130 | "content": "180g", 131 | "imgUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 132 | "productDesc": "方便面,好吃不贵", 133 | "bestBeforeDate": "24个月", 134 | "isDiscount": "0", 135 | "moreInfoUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 136 | "isPromotion": "0", 137 | "productName": "大食桶红烧牛肉面-1", 138 | "productionPlace": "0" 139 | }, 140 | { 141 | "y_price": "4", 142 | "selled": "0", 143 | "score": "5", 144 | "package": "200g", 145 | "isSpecial": "0", 146 | "n_price": "4", 147 | "nation": "中国", 148 | "version": "1", 149 | "productId": "9", 150 | "content": "180g", 151 | "imgUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 152 | "productDesc": "方便面,好吃不贵", 153 | "bestBeforeDate": "24个月", 154 | "isDiscount": "0", 155 | "moreInfoUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 156 | "isPromotion": "0", 157 | "productName": "大食桶红烧牛肉面-2", 158 | "productionPlace": "0" 159 | }, 160 | { 161 | "y_price": "4", 162 | "selled": "0", 163 | "score": "5", 164 | "package": "200g", 165 | "isSpecial": "0", 166 | "n_price": "4", 167 | "nation": "中国", 168 | "version": "1", 169 | "productId": "17", 170 | "content": "180g", 171 | "imgUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 172 | "productDesc": "方便面,好吃不贵", 173 | "bestBeforeDate": "24个月", 174 | "isDiscount": "0", 175 | "moreInfoUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 176 | "isPromotion": "0", 177 | "productName": "大食桶红烧牛肉面-3", 178 | "productionPlace": "0" 179 | }, 180 | { 181 | "y_price": "4", 182 | "selled": "0", 183 | "score": "5", 184 | "package": "200g", 185 | "isSpecial": "0", 186 | "n_price": "4", 187 | "nation": "中国", 188 | "version": "1", 189 | "productId": "25", 190 | "content": "180g", 191 | "imgUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 192 | "productDesc": "方便面,好吃不贵", 193 | "bestBeforeDate": "24个月", 194 | "isDiscount": "0", 195 | "moreInfoUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 196 | "isPromotion": "0", 197 | "productName": "大食桶红烧牛肉面-4", 198 | "productionPlace": "0" 199 | }, 200 | { 201 | "y_price": "4", 202 | "selled": "0", 203 | "score": "5", 204 | "package": "200g", 205 | "isSpecial": "0", 206 | "n_price": "4", 207 | "nation": "中国", 208 | "version": "1", 209 | "productId": "25", 210 | "content": "180g", 211 | "imgUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 212 | "productDesc": "方便面,好吃不贵", 213 | "bestBeforeDate": "24个月", 214 | "isDiscount": "0", 215 | "moreInfoUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 216 | "isPromotion": "0", 217 | "productName": "大食桶红烧牛肉面-5", 218 | "productionPlace": "0" 219 | }, 220 | { 221 | "y_price": "4", 222 | "selled": "0", 223 | "score": "5", 224 | "package": "200g", 225 | "isSpecial": "0", 226 | "n_price": "4", 227 | "nation": "中国", 228 | "version": "1", 229 | "productId": "41", 230 | "content": "180g", 231 | "imgUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 232 | "productDesc": "方便面,好吃不贵", 233 | "bestBeforeDate": "24个月", 234 | "isDiscount": "0", 235 | "moreInfoUrl": "/SKU_PIC/jiee/KSFTM1.jpg", 236 | "isPromotion": "0", 237 | "productName": "大食桶红烧牛肉面-6", 238 | "productionPlace": "0" 239 | } 240 | ] 241 | }, 242 | "isSuccess": 0 243 | } --------------------------------------------------------------------------------