├── .gitignore ├── LICENSE ├── README.md ├── TranslationAS.jar ├── build.xml ├── build └── built-jar.properties ├── libs ├── commons-codec-1.9.jar ├── commons-httpclient-3.1.jar ├── commons-io-2.4.jar ├── commons-logging-1.2.jar ├── httpasyncclient-4.1.jar ├── httpasyncclient-cache-4.1.jar ├── httpclient-4.4.1.jar ├── httpclient-cache-4.4.1.jar ├── httpcore-4.4.1.jar ├── httpcore-nio-4.4.1.jar ├── httpmime-4.1.2.jar ├── json_simple-1.1.jar ├── jsoup-1.8.3.jar ├── log4j-1.2.17.jar ├── microsoft-translator-java-api-0.6.2.jar └── mysql-connector-java-5.1.22-bin.jar ├── manifest.mf ├── nbproject ├── build-impl.xml ├── build-native.xml ├── genfiles.properties ├── private │ ├── config.properties │ ├── private.properties │ └── private.xml ├── project.properties └── project.xml └── src ├── test ├── AsyncClientCustomContext.java ├── DBManager.java ├── Escape.java ├── Google.java ├── HttpClientUtil.java ├── TranslateUtil.java └── examples │ └── org │ └── apache │ └── http │ └── examples │ └── nio │ └── client │ ├── AsyncClientAuthentication.java │ ├── AsyncClientConfiguration.java │ ├── AsyncClientCustomContext.java │ ├── AsyncClientCustomSSL.java │ ├── AsyncClientEvictExpiredConnections.java │ ├── AsyncClientExecuteProxy.java │ ├── AsyncClientHttpExchange.java │ ├── AsyncClientHttpExchangeFutureCallback.java │ ├── AsyncClientHttpExchangeStreaming.java │ ├── AsyncClientPipelined.java │ ├── AsyncClientPipelinedStreaming.java │ ├── AsyncClientProxyAuthentication.java │ ├── QuickStart.java │ └── ZeroCopyHttpExchange.java └── translation ├── HttpDownloader.java ├── MSDN_Translate(1).java ├── MSDN_Translate.java ├── MultiLineRowRenderer.java ├── Post(1).java ├── Post.java ├── PropertiesControl(1).java ├── PropertiesControl.java ├── PropertiesControl2.java ├── WordsTransfer.java ├── baidu ├── BaiDuTranslate.java ├── BaiDuTranslateApi.java └── BaiDuTranslateApiConfig.java ├── utils ├── HttpGet.java └── MD5.java └── view ├── JTA.java ├── TAS.form ├── TAS.java ├── TAS1.form └── TAS1.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | dist/ 4 | *~ 5 | /src/translation/baidu/BaiDuTranslateApiConfig.java -------------------------------------------------------------------------------- /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, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "{}" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright 2015 wellchang 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 1. 工具使用命令:java -jar TranslationAS.jar(新建lib文件夹,并复制相关的库到lib) 2 | 2. 工具说明:该工具直接选择resources_en.jar,点击获取jar包目录,勾选翻译,双击列表会自动翻译成中文,翻译完一个属性文件后点击保存属性值文件,翻译完后,请从新生成的jar包中将相应的属性文件在该库中进行修改。 3 | 3. 工具会自动进行编码转换 4 | 4. 使用netbeans开发 5 | 5. jdk版本: 1.7 6 | 7 | %注意% 8 | 点击比较新旧按钮,选择新旧(任意已汉化的)resources_en.jar文件,点击比较会将新的进行翻译并生成一个新的文件 9 | 10 | 由于百度翻译API限制ip,请自行申请,并在[BaiDuTranslateApiConfig.java](https://github.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/blob/master/src/translation/baidu/BaiDuTranslateApiConfig.java "BaiDuTranslateApiConfig.java")进行配置. 11 | 12 | 13 | # windows安装文件链接(win10 x64测试,由于上传大小限制,只能放在百度网盘): https://pan.baidu.com/s/1EaRbIbRw2Dh36eS58MxpUA 提取码: cjhf 14 | 15 | # 对新的语言包进行汉化看这里https://github.com/AndroidStudioTranslate/Android-Studio-Translate-Tool-Replace 16 | 17 | # Python版看这里https://github.com/AndroidStudioTranslate/Android-Studio-Translate-Tool-Python 18 | -------------------------------------------------------------------------------- /TranslationAS.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/TranslationAS.jar -------------------------------------------------------------------------------- /build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Builds, tests, and runs the project TranslationAS. 12 | 13 | 73 | 74 | -------------------------------------------------------------------------------- /build/built-jar.properties: -------------------------------------------------------------------------------- 1 | #Wed, 25 Nov 2015 10:28:23 +0800 2 | 3 | 4 | /home/swtf/learnning/TranslationAS= 5 | -------------------------------------------------------------------------------- /libs/commons-codec-1.9.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/commons-codec-1.9.jar -------------------------------------------------------------------------------- /libs/commons-httpclient-3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/commons-httpclient-3.1.jar -------------------------------------------------------------------------------- /libs/commons-io-2.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/commons-io-2.4.jar -------------------------------------------------------------------------------- /libs/commons-logging-1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/commons-logging-1.2.jar -------------------------------------------------------------------------------- /libs/httpasyncclient-4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/httpasyncclient-4.1.jar -------------------------------------------------------------------------------- /libs/httpasyncclient-cache-4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/httpasyncclient-cache-4.1.jar -------------------------------------------------------------------------------- /libs/httpclient-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/httpclient-4.4.1.jar -------------------------------------------------------------------------------- /libs/httpclient-cache-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/httpclient-cache-4.4.1.jar -------------------------------------------------------------------------------- /libs/httpcore-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/httpcore-4.4.1.jar -------------------------------------------------------------------------------- /libs/httpcore-nio-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/httpcore-nio-4.4.1.jar -------------------------------------------------------------------------------- /libs/httpmime-4.1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/httpmime-4.1.2.jar -------------------------------------------------------------------------------- /libs/json_simple-1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/json_simple-1.1.jar -------------------------------------------------------------------------------- /libs/jsoup-1.8.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/jsoup-1.8.3.jar -------------------------------------------------------------------------------- /libs/log4j-1.2.17.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/log4j-1.2.17.jar -------------------------------------------------------------------------------- /libs/microsoft-translator-java-api-0.6.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/microsoft-translator-java-api-0.6.2.jar -------------------------------------------------------------------------------- /libs/mysql-connector-java-5.1.22-bin.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/libs/mysql-connector-java-5.1.22-bin.jar -------------------------------------------------------------------------------- /manifest.mf: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | X-COMMENT: Main-Class will be added automatically by build 3 | 4 | -------------------------------------------------------------------------------- /nbproject/genfiles.properties: -------------------------------------------------------------------------------- 1 | build.xml.data.CRC32=8272b576 2 | build.xml.script.CRC32=4f05a8cb 3 | build.xml.stylesheet.CRC32=8064a381@1.75.2.48 4 | # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. 5 | # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. 6 | nbproject/build-impl.xml.data.CRC32=8272b576 7 | nbproject/build-impl.xml.script.CRC32=bbbfecff 8 | nbproject/build-impl.xml.stylesheet.CRC32=05530350@1.79.1.48 9 | -------------------------------------------------------------------------------- /nbproject/private/config.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidStudioTranslate/Android-Studio-Translate-Tool/e96eaaa807af78fb6631facc55c1e41ac629e300/nbproject/private/config.properties -------------------------------------------------------------------------------- /nbproject/private/private.properties: -------------------------------------------------------------------------------- 1 | compile.on.save=true 2 | do.depend=false 3 | do.jar=false 4 | javac.debug=true 5 | javadoc.preview=true 6 | user.properties.file=C:\\Users\\swtf\\AppData\\Roaming\\NetBeans\\8.1\\build.properties 7 | -------------------------------------------------------------------------------- /nbproject/private/private.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /nbproject/project.properties: -------------------------------------------------------------------------------- 1 | annotation.processing.enabled=true 2 | annotation.processing.enabled.in.editor=false 3 | annotation.processing.processors.list= 4 | annotation.processing.run.all.processors=true 5 | annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output 6 | application.title=TranslationAS 7 | application.vendor=swtf 8 | auxiliary.org-netbeans-spi-editor-hints-projects.perProjectHintSettingsFile=nbproject/cfg_hints.xml 9 | build.classes.dir=${build.dir}/classes 10 | build.classes.excludes=**/*.java,**/*.form 11 | # This directory is removed when the project is cleaned: 12 | build.dir=build 13 | build.generated.dir=${build.dir}/generated 14 | build.generated.sources.dir=${build.dir}/generated-sources 15 | # Only compile against the classpath explicitly listed here: 16 | build.sysclasspath=ignore 17 | build.test.classes.dir=${build.dir}/test/classes 18 | build.test.results.dir=${build.dir}/test/results 19 | # Uncomment to specify the preferred debugger connection transport: 20 | #debug.transport=dt_socket 21 | debug.classpath=\ 22 | ${run.classpath} 23 | debug.test.classpath=\ 24 | ${run.test.classpath} 25 | # This directory is removed when the project is cleaned: 26 | dist.dir=dist 27 | dist.jar=${dist.dir}/TranslationAS.jar 28 | dist.javadoc.dir=${dist.dir}/javadoc 29 | endorsed.classpath= 30 | excludes= 31 | file.reference.commons-codec-1.9.jar=libs/commons-codec-1.9.jar 32 | file.reference.commons-httpclient-3.1.jar=libs/commons-httpclient-3.1.jar 33 | file.reference.commons-io-2.4.jar=libs/commons-io-2.4.jar 34 | file.reference.commons-logging-1.2.jar=libs/commons-logging-1.2.jar 35 | file.reference.httpasyncclient-4.1.jar=libs/httpasyncclient-4.1.jar 36 | file.reference.httpasyncclient-cache-4.1.jar=libs/httpasyncclient-cache-4.1.jar 37 | file.reference.httpclient-4.4.1.jar=libs/httpclient-4.4.1.jar 38 | file.reference.httpclient-cache-4.4.1.jar=libs/httpclient-cache-4.4.1.jar 39 | file.reference.httpcore-4.4.1.jar=libs/httpcore-4.4.1.jar 40 | file.reference.httpcore-nio-4.4.1.jar=libs/httpcore-nio-4.4.1.jar 41 | file.reference.httpmime-4.1.2.jar=libs/httpmime-4.1.2.jar 42 | file.reference.json_simple-1.1.jar=libs/json_simple-1.1.jar 43 | file.reference.jsoup-1.8.3.jar=libs/jsoup-1.8.3.jar 44 | file.reference.log4j-1.2.17.jar=libs/log4j-1.2.17.jar 45 | file.reference.microsoft-translator-java-api-0.6.2.jar=libs/microsoft-translator-java-api-0.6.2.jar 46 | file.reference.mysql-connector-java-5.1.22-bin.jar=libs/mysql-connector-java-5.1.22-bin.jar 47 | includes=** 48 | jar.archive.disabled=${jnlp.enabled} 49 | jar.compress=true 50 | jar.index=${jnlp.enabled} 51 | javac.classpath=\ 52 | ${file.reference.commons-codec-1.9.jar}:\ 53 | ${file.reference.commons-httpclient-3.1.jar}:\ 54 | ${file.reference.commons-io-2.4.jar}:\ 55 | ${file.reference.commons-logging-1.2.jar}:\ 56 | ${file.reference.httpasyncclient-4.1.jar}:\ 57 | ${file.reference.httpasyncclient-cache-4.1.jar}:\ 58 | ${file.reference.httpclient-4.4.1.jar}:\ 59 | ${file.reference.httpclient-cache-4.4.1.jar}:\ 60 | ${file.reference.httpcore-4.4.1.jar}:\ 61 | ${file.reference.httpcore-nio-4.4.1.jar}:\ 62 | ${file.reference.httpmime-4.1.2.jar}:\ 63 | ${file.reference.json_simple-1.1.jar}:\ 64 | ${file.reference.jsoup-1.8.3.jar}:\ 65 | ${file.reference.microsoft-translator-java-api-0.6.2.jar}:\ 66 | ${file.reference.mysql-connector-java-5.1.22-bin.jar}:\ 67 | ${file.reference.log4j-1.2.17.jar} 68 | # Space-separated list of extra javac options 69 | javac.compilerargs= 70 | javac.deprecation=false 71 | javac.processorpath=\ 72 | ${javac.classpath} 73 | javac.source=1.7 74 | javac.target=1.7 75 | javac.test.classpath=\ 76 | ${javac.classpath}:\ 77 | ${build.classes.dir} 78 | javac.test.processorpath=\ 79 | ${javac.test.classpath} 80 | javadoc.additionalparam= 81 | javadoc.author=true 82 | javadoc.encoding=${source.encoding} 83 | javadoc.noindex=false 84 | javadoc.nonavbar=false 85 | javadoc.notree=false 86 | javadoc.private=false 87 | javadoc.splitindex=true 88 | javadoc.use=true 89 | javadoc.version=true 90 | javadoc.windowtitle= 91 | jnlp.codebase.type=no.codebase 92 | jnlp.descriptor=application 93 | jnlp.enabled=false 94 | jnlp.mixed.code=default 95 | jnlp.offline-allowed=false 96 | jnlp.signed=false 97 | jnlp.signing= 98 | jnlp.signing.alias= 99 | jnlp.signing.keystore= 100 | main.class=translation.view.TAS 101 | # \u53ef\u4ee5\u9009\u62e9\u8986\u76d6\u9ed8\u8ba4\u7684\u4ee3\u7801\u5e93\u6e05\u5355\u5c5e\u6027, \u7528\u4e8e\u9632\u6b62 RIA \u88ab\u7528\u4f5c\u5176\u4ed6\u7528\u9014 102 | manifest.custom.codebase= 103 | # \u53ef\u4ee5\u9009\u62e9\u8986\u76d6\u9ed8\u8ba4\u7684\u6743\u9650\u6e05\u5355\u5c5e\u6027 (\u652f\u6301\u7684\u503c: sandbox, all-permissions) 104 | manifest.custom.permissions= 105 | manifest.file=manifest.mf 106 | meta.inf.dir=${src.dir}/META-INF 107 | mkdist.disabled=true 108 | native.bundling.enabled=true 109 | platform.active=JDK_1.7 110 | run.classpath=\ 111 | ${javac.classpath}:\ 112 | ${build.classes.dir} 113 | # Space-separated list of JVM arguments used when running the project 114 | # (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value 115 | # or test-sys-prop.name=value to set system properties for unit tests): 116 | run.jvmargs= 117 | run.test.classpath=\ 118 | ${javac.test.classpath}:\ 119 | ${build.test.classes.dir} 120 | source.encoding=UTF-8 121 | src.dir=src 122 | test.src.dir=test 123 | -------------------------------------------------------------------------------- /nbproject/project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | org.netbeans.modules.java.j2seproject 4 | 5 | 6 | 7 | 8 | 9 | TranslationAS 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/test/AsyncClientCustomContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package test; 7 | 8 | /* 9 | * ==================================================================== 10 | * Licensed to the Apache Software Foundation (ASF) under one 11 | * or more contributor license agreements. See the NOTICE file 12 | * distributed with this work for additional information 13 | * regarding copyright ownership. The ASF licenses this file 14 | * to you under the Apache License, Version 2.0 (the 15 | * "License"); you may not use this file except in compliance 16 | * with the License. You may obtain a copy of the License at 17 | * 18 | * http://www.apache.org/licenses/LICENSE-2.0 19 | * 20 | * Unless required by applicable law or agreed to in writing, 21 | * software distributed under the License is distributed on an 22 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 23 | * KIND, either express or implied. See the License for the 24 | * specific language governing permissions and limitations 25 | * under the License. 26 | * ==================================================================== 27 | * 28 | * This software consists of voluntary contributions made by many 29 | * individuals on behalf of the Apache Software Foundation. For more 30 | * information on the Apache Software Foundation, please see 31 | * . 32 | * 33 | */ 34 | import org.apache.http.HttpResponse; 35 | import org.apache.http.client.CookieStore; 36 | import org.apache.http.client.methods.HttpGet; 37 | import org.apache.http.client.protocol.HttpClientContext; 38 | import org.apache.http.cookie.Cookie; 39 | import org.apache.http.impl.client.BasicCookieStore; 40 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 41 | import org.apache.http.impl.nio.client.HttpAsyncClients; 42 | 43 | import java.util.List; 44 | import java.util.concurrent.Future; 45 | import org.apache.http.HttpEntity; 46 | import org.apache.http.util.EntityUtils; 47 | 48 | /** 49 | * This example demonstrates the use of a local HTTP context populated with 50 | * custom attributes. 51 | */ 52 | public class AsyncClientCustomContext { 53 | 54 | public final static void main(String[] args) throws Exception { 55 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); 56 | HttpEntity entity = null; 57 | String jsonContent = ""; 58 | try { 59 | // Create a local instance of cookie store 60 | CookieStore cookieStore = new BasicCookieStore(); 61 | 62 | // Create local HTTP context 63 | HttpClientContext localContext = HttpClientContext.create(); 64 | // Bind custom cookie store to the local context 65 | localContext.setCookieStore(cookieStore); 66 | 67 | HttpGet httpget = new HttpGet("http://viphp.sinaapp.com/baidu/translate/translate.php?origin=中文"); 68 | System.out.println("Executing request " + httpget.getRequestLine()); 69 | 70 | httpclient.start(); 71 | 72 | // Pass local context as a parameter 73 | Future future = httpclient.execute(httpget, localContext, null); 74 | 75 | // Please note that it may be unsafe to access HttpContext instance 76 | // while the request is still being executed 77 | HttpResponse response = future.get(); 78 | System.out.println("Response: " + response.getStatusLine()); 79 | entity = response.getEntity(); 80 | jsonContent = EntityUtils.toString(entity, "UTF-8"); 81 | System.out.println("jsonContent:" + jsonContent); 82 | List cookies = cookieStore.getCookies(); 83 | for (int i = 0; i < cookies.size(); i++) { 84 | System.out.println("Local cookie: " + cookies.get(i)); 85 | } 86 | System.out.println("Shutting down"); 87 | } finally { 88 | httpclient.close(); 89 | } 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /src/test/DBManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package test; 7 | 8 | import java.sql.Connection; 9 | import java.sql.DriverManager; 10 | import java.sql.ResultSet; 11 | import java.sql.SQLException; 12 | import java.sql.Statement; 13 | import java.util.logging.Level; 14 | import org.apache.log4j.Logger; 15 | 16 | /** 17 | * 18 | * @author swtf 19 | */ 20 | public class DBManager { 21 | 22 | String URL = "jdbc:mysql://localhost:3306/test"; 23 | String Username = "root"; 24 | String Password = "1234"; 25 | String Driver = "com.mysql.jdbc.Driver"; 26 | 27 | public DBManager() { 28 | try { 29 | Class.forName(Driver).newInstance(); 30 | } catch (Exception e) { 31 | e.printStackTrace(); 32 | } 33 | } 34 | 35 | public Connection getConnection() { 36 | Connection connection = null; 37 | try { 38 | connection = DriverManager.getConnection(URL, Username, Password); 39 | } catch (Exception e) { 40 | e.printStackTrace(); 41 | } 42 | return connection; 43 | } 44 | 45 | public Statement getStatement() { 46 | Connection connection = null; 47 | Statement stmt = null; 48 | try { 49 | connection = getConnection(); 50 | stmt = connection.createStatement(); 51 | return stmt; 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | return null; 55 | } 56 | } 57 | 58 | public ResultSet getResultSet(String sql, boolean isQuery) { 59 | ResultSet rs = null; 60 | Statement stmt = null; 61 | stmt = getStatement(); 62 | try { 63 | if (isQuery) { 64 | rs = stmt.executeQuery(sql); 65 | } else { 66 | stmt.executeUpdate(sql); 67 | } 68 | } catch (SQLException ex) { 69 | System.err.println(ex.getMessage()); 70 | } 71 | return rs; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/test/Escape.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package test; 7 | 8 | /** 9 | *   * JavaScript escape/unescape 编码的 Java 实现 10 | *

11 | *   * author jackyz 12 | *

13 | *   * keep this copyright info while using this method by free 14 | *

15 | */ 16 | 17 | public class Escape { 18 | 19 | private final static String[] hex = { 20 | 21 | "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", 22 | 23 | "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", 24 | 25 | "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", 26 | 27 | "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", 28 | 29 | "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", 30 | 31 | "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", 32 | 33 | "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", 34 | 35 | "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", 36 | 37 | "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", 38 | 39 | "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", 40 | 41 | "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", 42 | "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", 43 | "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", 44 | "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", 45 | "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", 46 | "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" 47 | }; 48 | 49 | private final static byte[] val = {0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 50 | 51 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 52 | 53 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 54 | 55 | 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 56 | 57 | 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 58 | 59 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 60 | 61 | 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 62 | 63 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 64 | 65 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 66 | 67 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 68 | 69 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 70 | 71 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 72 | 73 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 74 | 75 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 76 | 77 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 78 | 79 | 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F 80 | 81 | }; 82 | 83 | public static String escape(String s) { 84 | 85 | StringBuffer sbuf = new StringBuffer(); 86 | 87 | int len = s.length(); 88 | 89 | for (int i = 0; i < len; i++) { 90 | 91 | int ch = s.charAt(i); 92 | 93 | if (ch == ' ') { // space : map to '+' 94 | 95 | sbuf.append('+'); 96 | 97 | } else if ('A' <= ch && ch <= 'Z') { // 'A'..'Z' : as it was 98 | 99 | sbuf.append((char) ch); 100 | 101 | } else if ('a' <= ch && ch <= 'z') { // 'a'..'z' : as it was 102 | 103 | sbuf.append((char) ch); 104 | 105 | } else if ('0' <= ch && ch <= '9') { // '0'..'9' : as it was 106 | 107 | sbuf.append((char) ch); 108 | 109 | } else if (ch == '-' || ch == '_' // unreserved : as it was 110 | 111 | || ch == '.' || ch == '!' 112 | 113 | || ch == '~' || ch == '*' 114 | 115 | || ch == '/' || ch == '(' 116 | 117 | || ch == ')') { 118 | 119 | sbuf.append((char) ch); 120 | 121 | } else if (ch <= 0x007F) { // other ASCII : map to %XX 122 | 123 | sbuf.append('%'); 124 | 125 | sbuf.append(hex[ch]); 126 | 127 | } else { // unicode : map to %uXXXX 128 | 129 | sbuf.append('%'); 130 | 131 | sbuf.append('u'); 132 | 133 | sbuf.append(hex[(ch >>> 8)]); 134 | 135 | sbuf.append(hex[(0x00FF & ch)]); 136 | 137 | } 138 | 139 | } 140 | 141 | return sbuf.toString(); 142 | 143 | } 144 | 145 | public static String unescape(String s) { 146 | 147 | StringBuffer sbuf = new StringBuffer(); 148 | 149 | int i = 0; 150 | 151 | int len = s.length(); 152 | 153 | while (i < len) { 154 | 155 | int ch = s.charAt(i); 156 | 157 | if (ch == '+') { // + : map to ' ' 158 | 159 | sbuf.append(' '); 160 | 161 | } else if ('A' <= ch && ch <= 'Z') { // 'A'..'Z' : as it was 162 | 163 | sbuf.append((char) ch); 164 | 165 | } else if ('a' <= ch && ch <= 'z') { // 'a'..'z' : as it was 166 | 167 | sbuf.append((char) ch); 168 | 169 | } else if ('0' <= ch && ch <= '9') { // '0'..'9' : as it was 170 | 171 | sbuf.append((char) ch); 172 | 173 | } else if (ch == '-' || ch == '_' // unreserved : as it was 174 | 175 | || ch == '.' || ch == '!' 176 | 177 | || ch == '~' || ch == '*' 178 | 179 | || ch == '/' || ch == '(' 180 | 181 | || ch == ')') { 182 | 183 | sbuf.append((char) ch); 184 | 185 | } else if (ch == '%') { 186 | 187 | int cint = 0; 188 | 189 | if ('u' != s.charAt(i + 1)) { // %XX : map to ascii(XX) 190 | 191 | cint = (cint << 4) | val[s.charAt(i + 1)]; 192 | 193 | cint = (cint << 4) | val[s.charAt(i + 2)]; 194 | 195 | i += 2; 196 | 197 | } else { // %uXXXX : map to unicode(XXXX) 198 | 199 | cint = (cint << 4) | val[s.charAt(i + 2)]; 200 | 201 | cint = (cint << 4) | val[s.charAt(i + 3)]; 202 | 203 | cint = (cint << 4) | val[s.charAt(i + 4)]; 204 | 205 | cint = (cint << 4) | val[s.charAt(i + 5)]; 206 | 207 | i += 5; 208 | 209 | } 210 | 211 | sbuf.append((char) cint); 212 | 213 | } 214 | 215 | i++; 216 | 217 | } 218 | 219 | return sbuf.toString(); 220 | 221 | } 222 | 223 | // public static void main(String[] args) { 224 | // 225 | // String stest = "黄修群1234 abcd[]()<+>,.~//"; 226 | // 227 | // System.out.println(stest); 228 | // 229 | // System.out.println(escape(stest)); 230 | // 231 | // System.out.println(unescape(escape(stest))); 232 | // 233 | // } 234 | 235 | } 236 | -------------------------------------------------------------------------------- /src/test/Google.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package test; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | import java.util.logging.Level; 10 | import java.util.logging.Logger; 11 | import translation.Post; 12 | 13 | /** 14 | * 15 | * @author vi 16 | */ 17 | public class Google { 18 | 19 | public static void main(String[] args) { 20 | String words = "this is a test!\nthis is a test!\nthis is a test!"; 21 | try { 22 | Map map = new HashMap(); 23 | map.put("client", "t"); 24 | map.put("text", words); 25 | map.put("sl", "en"); 26 | map.put("tl", "zh_CN"); 27 | String dst=Post.http("http://translate.google.com/translate_a/t", map); 28 | System.out.println(dst); 29 | //System.out.println(TranslateUtil.en2cn(words)); 30 | } catch (Exception ex) { 31 | Logger.getLogger(Google.class.getName()).log(Level.SEVERE, null, ex); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/HttpClientUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package test; 6 | 7 | /** 8 | * 9 | * @author vi 10 | */ 11 | import java.io.BufferedInputStream; 12 | import java.io.File; 13 | import java.io.FileOutputStream; 14 | import java.io.InputStream; 15 | import java.util.Map; 16 | 17 | import org.apache.commons.io.IOUtils; 18 | import org.apache.commons.logging.Log; 19 | import org.apache.commons.logging.LogFactory; 20 | import org.apache.http.HttpEntity; 21 | import org.apache.http.HttpResponse; 22 | import org.apache.http.client.HttpClient; 23 | import org.apache.http.client.methods.HttpGet; 24 | import org.apache.http.client.methods.HttpPost; 25 | import org.apache.http.client.methods.HttpRequestBase; 26 | import org.apache.http.conn.scheme.PlainSocketFactory; 27 | import org.apache.http.conn.scheme.Scheme; 28 | import org.apache.http.conn.scheme.SchemeRegistry; 29 | import org.apache.http.conn.ssl.SSLSocketFactory; 30 | import org.apache.http.entity.BufferedHttpEntity; 31 | import org.apache.http.impl.client.DefaultHttpClient; 32 | import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; 33 | import org.apache.http.params.BasicHttpParams; 34 | 35 | /** 36 | * PostUtil.java 37 | * 38 | * @author catty 39 | * @version 1.0, Created on 2008/2/20 40 | */ 41 | public class HttpClientUtil { 42 | 43 | protected static Log log = LogFactory.getLog(HttpClientUtil.class); 44 | protected static HttpClient httpclient = null; 45 | protected static int maxTotal = 200; 46 | protected static int maxPerRoute = 20; 47 | protected static String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7"; 48 | 49 | static { 50 | if (httpclient == null) { 51 | // ~~~~~~~~~~~~~~~~~~~~ 52 | // create httpclient 53 | // ~~~~~~~~~~~~~~~~~~~~ 54 | SchemeRegistry reg = new SchemeRegistry(); 55 | reg.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); 56 | reg.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); 57 | ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(reg); 58 | cm.setMaxTotal(maxTotal); 59 | cm.setDefaultMaxPerRoute(maxPerRoute); 60 | httpclient = new DefaultHttpClient(cm); 61 | } 62 | } 63 | 64 | /** 65 | *

下載後回傳Inputstream
66 | * 67 | * @param url 68 | * @return 69 | * @throws Exception 70 | */ 71 | public static InputStream downloadAsStream(String url) throws Exception { 72 | InputStream is = (InputStream) download(url, null, null, false); 73 | return is; 74 | } 75 | 76 | /** 77 | *
下載後儲存到File
78 | * 79 | * @param url 80 | * @param saveFile 81 | * @throws Exception 82 | */ 83 | public static void download(String url, File saveFile) throws Exception { 84 | download(url, saveFile, null, false); 85 | } 86 | 87 | /** 88 | *
下載
89 | * 90 | * @param url 91 | * @param saveFile 92 | * @param params 93 | * @param isPost 94 | * @return 如果saveFile==null則回傳inputstream, 否則回傳saveFile 95 | * @throws Exception 96 | */ 97 | public static Object download(final String url, final File saveFile, final Map params, 98 | final boolean isPost) throws Exception { 99 | 100 | boolean saveToFile = saveFile != null; 101 | 102 | // check dir exist ?? 103 | if (saveToFile && saveFile.getParentFile().exists() == false) { 104 | saveFile.getParentFile().mkdirs(); 105 | } 106 | 107 | Exception err = null; 108 | HttpRequestBase request = null; 109 | HttpResponse response = null; 110 | HttpEntity entity = null; 111 | FileOutputStream fos = null; 112 | Object result = null; 113 | 114 | try { 115 | // create request 116 | if (isPost) { 117 | request = new HttpPost(url); 118 | } else { 119 | request = new HttpGet(url); 120 | } 121 | 122 | // add header & params 123 | addHeaderAndParams(request, params); 124 | 125 | // connect 126 | response = httpclient.execute(request); 127 | entity = response.getEntity(); 128 | entity = new BufferedHttpEntity(entity); 129 | 130 | // get result 131 | if (saveToFile) {// save to disk 132 | fos = new FileOutputStream(saveFile); 133 | IOUtils.copy(entity.getContent(), fos); 134 | result = saveFile; 135 | } else { // warp to inpustream 136 | result = new BufferedInputStream(entity.getContent()); 137 | } 138 | 139 | } catch (Exception e) { 140 | err = e; 141 | } finally { 142 | 143 | // close 144 | IOUtils.closeQuietly(fos); 145 | 146 | // clear 147 | request = null; 148 | response = null; 149 | entity = null; 150 | 151 | if (err != null) { 152 | throw err; 153 | } 154 | 155 | return result; 156 | } 157 | 158 | } 159 | 160 | protected static void addHeaderAndParams(final HttpRequestBase request, final Map params) { 161 | // add default header 162 | request.addHeader("User-Agent", userAgent); 163 | 164 | // add params 165 | if (params != null) { 166 | 167 | // map --> HttpParams 168 | BasicHttpParams myParams = new BasicHttpParams(); 169 | for (String key : params.keySet()) { 170 | myParams.setParameter(key, params.get(key)); 171 | } 172 | 173 | request.setParams(myParams); 174 | } 175 | } 176 | 177 | public static HttpClient getHttpclient() { 178 | return httpclient; 179 | } 180 | 181 | public static void setHttpclient(HttpClient httpclient) { 182 | HttpClientUtil.httpclient = httpclient; 183 | } 184 | 185 | public static int getMaxTotal() { 186 | return maxTotal; 187 | } 188 | 189 | public static void setMaxTotal(int maxTotal) { 190 | HttpClientUtil.maxTotal = maxTotal; 191 | } 192 | 193 | public static int getMaxPerRoute() { 194 | return maxPerRoute; 195 | } 196 | 197 | public static void setMaxPerRoute(int maxPerRoute) { 198 | HttpClientUtil.maxPerRoute = maxPerRoute; 199 | } 200 | 201 | public static String getUserAgent() { 202 | return userAgent; 203 | } 204 | 205 | public static void setUserAgent(String userAgent) { 206 | HttpClientUtil.userAgent = userAgent; 207 | } 208 | 209 | } 210 | -------------------------------------------------------------------------------- /src/test/TranslateUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package test; 6 | 7 | /** 8 | * 9 | * @author vi 10 | */ 11 | /** 12 | * Copyright (c) blackbear, Inc All Rights Reserved. 13 | */ 14 | 15 | import java.io.InputStream; 16 | import java.net.URLEncoder; 17 | import java.text.MessageFormat; 18 | 19 | import org.apache.commons.io.IOUtils; 20 | 21 | import org.jsoup.Jsoup; 22 | import org.jsoup.nodes.Document; 23 | import org.jsoup.nodes.Element; 24 | 25 | /** 26 | * TranslateUtil 27 | * 28 | *
翻譯工具
 29 |  * PS: 透過google translate
 30 |  * 
31 | * 32 | * @author catty 33 | * @version 1.0, Created on 2011/9/2 34 | */ 35 | public class TranslateUtil { 36 | 37 | protected static final String URL_TEMPLATE = "http://translate.google.com/?langpair={0}&text={1}"; 38 | protected static final String ID_RESULTBOX = "result_box"; 39 | protected static final String ENCODING = "UTF-8"; 40 | 41 | protected static final String AUTO = "auto"; // google自動判斷來源語系 42 | protected static final String TAIWAN = "zh-TW"; // 繁中 43 | protected static final String CHINA = "zh-CN"; // 簡中 44 | protected static final String ENGLISH = "en"; // 英 45 | protected static final String JAPAN = "ja"; // 日 46 | 47 | /** 48 | *
Google翻譯
 49 | 	 * PS: 交由google自動判斷來源語系
 50 | 	 * 
51 | * 52 | * @param text 53 | * @param target_lang 目標語系 54 | * @return 55 | * @throws Exception 56 | */ 57 | public static String translate(final String text, final String target_lang) throws Exception { 58 | return translate(text, AUTO, target_lang); 59 | } 60 | 61 | /** 62 | *
Google翻譯
63 | * 64 | * @param text 65 | * @param src_lang 來源語系 66 | * @param target_lang 目標語系 67 | * @return 68 | * @throws Exception 69 | */ 70 | public static String translate(final String text, final String src_lang, final String target_lang) 71 | throws Exception { 72 | InputStream is = null; 73 | Document doc = null; 74 | Element ele = null; 75 | try { 76 | // create URL string 77 | String url = MessageFormat.format(URL_TEMPLATE, 78 | URLEncoder.encode(src_lang + "|" + target_lang, ENCODING), 79 | URLEncoder.encode(text, ENCODING)); 80 | 81 | // connect & download html 82 | is = HttpClientUtil.downloadAsStream(url); 83 | 84 | // parse html by Jsoup 85 | doc = Jsoup.parse(is, ENCODING, ""); 86 | ele = doc.getElementById(ID_RESULTBOX); 87 | String result = ele.text(); 88 | return result; 89 | 90 | } finally { 91 | IOUtils.closeQuietly(is); 92 | is = null; 93 | doc = null; 94 | ele = null; 95 | } 96 | } 97 | 98 | /** 99 | *
Google翻譯: 簡中-->繁中
100 | * 101 | * @param text 102 | * @return 103 | * @throws Exception 104 | */ 105 | public static String cn2tw(final String text) throws Exception { 106 | return translate(text, CHINA, TAIWAN); 107 | } 108 | 109 | /** 110 | *
Google翻譯: 繁中-->簡中
111 | * 112 | * @param text 113 | * @return 114 | * @throws Exception 115 | */ 116 | public static String tw2cn(final String text) throws Exception { 117 | return translate(text, TAIWAN, CHINA); 118 | } 119 | 120 | /** 121 | *
Google翻譯: 英文-->繁中
122 | * 123 | * @param text 124 | * @return 125 | * @throws Exception 126 | */ 127 | public static String en2tw(final String text) throws Exception { 128 | return translate(text, ENGLISH, TAIWAN); 129 | }/** 130 | *
Google翻譯: 英文-->繁中
131 | * 132 | * @param text 133 | * @return 134 | * @throws Exception 135 | */ 136 | public static String en2cn(final String text) throws Exception { 137 | return translate(text, ENGLISH, CHINA); 138 | } 139 | 140 | /** 141 | *
Google翻譯: 繁中-->英文
142 | * 143 | * @param text 144 | * @return 145 | * @throws Exception 146 | */ 147 | public static String tw2en(final String text) throws Exception { 148 | return translate(text, TAIWAN, ENGLISH); 149 | } 150 | 151 | /** 152 | *
Google翻譯: 日文-->繁中
153 | * 154 | * @param text 155 | * @return 156 | * @throws Exception 157 | */ 158 | public static String jp2tw(final String text) throws Exception { 159 | return translate(text, JAPAN, TAIWAN); 160 | } 161 | 162 | /** 163 | *
Google翻譯: 繁中-->日
164 | * 165 | * @param text 166 | * @return 167 | * @throws Exception 168 | */ 169 | public static String tw2jp(final String text) throws Exception { 170 | return translate(text, TAIWAN, JAPAN); 171 | } 172 | 173 | } 174 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientAuthentication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import org.apache.http.HttpResponse; 30 | import org.apache.http.auth.AuthScope; 31 | import org.apache.http.auth.UsernamePasswordCredentials; 32 | import org.apache.http.client.CredentialsProvider; 33 | import org.apache.http.client.methods.HttpGet; 34 | import org.apache.http.impl.client.BasicCredentialsProvider; 35 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 36 | import org.apache.http.impl.nio.client.HttpAsyncClients; 37 | 38 | import java.util.concurrent.Future; 39 | 40 | /** 41 | * A simple example that uses HttpClient to execute an HTTP request against 42 | * a target site that requires user authentication. 43 | */ 44 | public class AsyncClientAuthentication { 45 | 46 | public static void main(String[] args) throws Exception { 47 | CredentialsProvider credsProvider = new BasicCredentialsProvider(); 48 | credsProvider.setCredentials( 49 | new AuthScope("localhost", 443), 50 | new UsernamePasswordCredentials("username", "password")); 51 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() 52 | .setDefaultCredentialsProvider(credsProvider) 53 | .build(); 54 | try { 55 | HttpGet httpget = new HttpGet("http://localhost/"); 56 | 57 | System.out.println("Executing request " + httpget.getRequestLine()); 58 | Future future = httpclient.execute(httpget, null); 59 | HttpResponse response = future.get(); 60 | System.out.println("Response: " + response.getStatusLine()); 61 | System.out.println("Shutting down"); 62 | } finally { 63 | httpclient.close(); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | 28 | package test.examples.org.apache.http.examples.nio.client; 29 | 30 | import java.net.InetAddress; 31 | import java.net.UnknownHostException; 32 | import java.nio.charset.CodingErrorAction; 33 | import java.util.Arrays; 34 | import java.util.concurrent.Future; 35 | 36 | import javax.net.ssl.HostnameVerifier; 37 | import javax.net.ssl.SSLContext; 38 | 39 | import org.apache.http.Consts; 40 | import org.apache.http.Header; 41 | import org.apache.http.HttpHost; 42 | import org.apache.http.HttpRequest; 43 | import org.apache.http.HttpResponse; 44 | import org.apache.http.ParseException; 45 | import org.apache.http.client.CookieStore; 46 | import org.apache.http.client.CredentialsProvider; 47 | import org.apache.http.client.config.AuthSchemes; 48 | import org.apache.http.client.config.CookieSpecs; 49 | import org.apache.http.client.config.RequestConfig; 50 | import org.apache.http.client.methods.HttpGet; 51 | import org.apache.http.client.protocol.HttpClientContext; 52 | import org.apache.http.config.ConnectionConfig; 53 | import org.apache.http.config.MessageConstraints; 54 | import org.apache.http.config.Registry; 55 | import org.apache.http.config.RegistryBuilder; 56 | import org.apache.http.conn.DnsResolver; 57 | import org.apache.http.conn.routing.HttpRoute; 58 | import org.apache.http.conn.ssl.DefaultHostnameVerifier; 59 | import org.apache.http.conn.ssl.SSLContexts; 60 | import org.apache.http.impl.DefaultHttpResponseFactory; 61 | import org.apache.http.impl.client.BasicCookieStore; 62 | import org.apache.http.impl.client.BasicCredentialsProvider; 63 | import org.apache.http.impl.conn.SystemDefaultDnsResolver; 64 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 65 | import org.apache.http.impl.nio.client.HttpAsyncClients; 66 | import org.apache.http.impl.nio.codecs.DefaultHttpRequestWriterFactory; 67 | import org.apache.http.impl.nio.codecs.DefaultHttpResponseParser; 68 | import org.apache.http.impl.nio.codecs.DefaultHttpResponseParserFactory; 69 | import org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionFactory; 70 | import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; 71 | import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; 72 | import org.apache.http.impl.nio.reactor.IOReactorConfig; 73 | import org.apache.http.message.BasicHeader; 74 | import org.apache.http.message.BasicLineParser; 75 | import org.apache.http.message.LineParser; 76 | import org.apache.http.nio.NHttpMessageParser; 77 | import org.apache.http.nio.NHttpMessageParserFactory; 78 | import org.apache.http.nio.NHttpMessageWriterFactory; 79 | import org.apache.http.nio.conn.ManagedNHttpClientConnection; 80 | import org.apache.http.nio.conn.NHttpConnectionFactory; 81 | import org.apache.http.nio.conn.NoopIOSessionStrategy; 82 | import org.apache.http.nio.conn.SchemeIOSessionStrategy; 83 | import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; 84 | import org.apache.http.nio.reactor.ConnectingIOReactor; 85 | import org.apache.http.nio.reactor.SessionInputBuffer; 86 | import org.apache.http.nio.util.HeapByteBufferAllocator; 87 | import org.apache.http.util.CharArrayBuffer; 88 | 89 | /** 90 | * This example demonstrates how to customize and configure the most common aspects 91 | * of HTTP request execution and connection management. 92 | */ 93 | public class AsyncClientConfiguration { 94 | 95 | public final static void main(String[] args) throws Exception { 96 | 97 | // Use custom message parser / writer to customize the way HTTP 98 | // messages are parsed from and written out to the data stream. 99 | NHttpMessageParserFactory responseParserFactory = new DefaultHttpResponseParserFactory() { 100 | 101 | @Override 102 | public NHttpMessageParser create( 103 | final SessionInputBuffer buffer, 104 | final MessageConstraints constraints) { 105 | LineParser lineParser = new BasicLineParser() { 106 | 107 | @Override 108 | public Header parseHeader(final CharArrayBuffer buffer) { 109 | try { 110 | return super.parseHeader(buffer); 111 | } catch (ParseException ex) { 112 | return new BasicHeader(buffer.toString(), null); 113 | } 114 | } 115 | 116 | }; 117 | return new DefaultHttpResponseParser( 118 | buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints); 119 | } 120 | 121 | }; 122 | NHttpMessageWriterFactory requestWriterFactory = new DefaultHttpRequestWriterFactory(); 123 | 124 | // Use a custom connection factory to customize the process of 125 | // initialization of outgoing HTTP connections. Beside standard connection 126 | // configuration parameters HTTP connection factory can define message 127 | // parser / writer routines to be employed by individual connections. 128 | NHttpConnectionFactory connFactory = new ManagedNHttpClientConnectionFactory( 129 | requestWriterFactory, responseParserFactory, HeapByteBufferAllocator.INSTANCE); 130 | 131 | // Client HTTP connection objects when fully initialized can be bound to 132 | // an arbitrary network socket. The process of network socket initialization, 133 | // its connection to a remote address and binding to a local one is controlled 134 | // by a connection socket factory. 135 | 136 | // SSL context for secure connections can be created either based on 137 | // system or application specific properties. 138 | SSLContext sslcontext = SSLContexts.createSystemDefault(); 139 | // Use custom hostname verifier to customize SSL hostname verification. 140 | HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(); 141 | 142 | // Create a registry of custom connection session strategies for supported 143 | // protocol schemes. 144 | Registry sessionStrategyRegistry = RegistryBuilder.create() 145 | .register("http", NoopIOSessionStrategy.INSTANCE) 146 | .register("https", new SSLIOSessionStrategy(sslcontext, hostnameVerifier)) 147 | .build(); 148 | 149 | // Use custom DNS resolver to override the system DNS resolution. 150 | DnsResolver dnsResolver = new SystemDefaultDnsResolver() { 151 | 152 | @Override 153 | public InetAddress[] resolve(final String host) throws UnknownHostException { 154 | if (host.equalsIgnoreCase("myhost")) { 155 | return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) }; 156 | } else { 157 | return super.resolve(host); 158 | } 159 | } 160 | 161 | }; 162 | 163 | // Create I/O reactor configuration 164 | IOReactorConfig ioReactorConfig = IOReactorConfig.custom() 165 | .setIoThreadCount(Runtime.getRuntime().availableProcessors()) 166 | .setConnectTimeout(30000) 167 | .setSoTimeout(30000) 168 | .build(); 169 | 170 | // Create a custom I/O reactort 171 | ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig); 172 | 173 | // Create a connection manager with custom configuration. 174 | PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager( 175 | ioReactor, connFactory, sessionStrategyRegistry, dnsResolver); 176 | 177 | // Create message constraints 178 | MessageConstraints messageConstraints = MessageConstraints.custom() 179 | .setMaxHeaderCount(200) 180 | .setMaxLineLength(2000) 181 | .build(); 182 | // Create connection configuration 183 | ConnectionConfig connectionConfig = ConnectionConfig.custom() 184 | .setMalformedInputAction(CodingErrorAction.IGNORE) 185 | .setUnmappableInputAction(CodingErrorAction.IGNORE) 186 | .setCharset(Consts.UTF_8) 187 | .setMessageConstraints(messageConstraints) 188 | .build(); 189 | // Configure the connection manager to use connection configuration either 190 | // by default or for a specific host. 191 | connManager.setDefaultConnectionConfig(connectionConfig); 192 | connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); 193 | 194 | // Configure total max or per route limits for persistent connections 195 | // that can be kept in the pool or leased by the connection manager. 196 | connManager.setMaxTotal(100); 197 | connManager.setDefaultMaxPerRoute(10); 198 | connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); 199 | 200 | // Use custom cookie store if necessary. 201 | CookieStore cookieStore = new BasicCookieStore(); 202 | // Use custom credentials provider if necessary. 203 | CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); 204 | // Create global request configuration 205 | RequestConfig defaultRequestConfig = RequestConfig.custom() 206 | .setCookieSpec(CookieSpecs.DEFAULT) 207 | .setExpectContinueEnabled(true) 208 | .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) 209 | .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) 210 | .build(); 211 | 212 | // Create an HttpClient with the given custom dependencies and configuration. 213 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() 214 | .setConnectionManager(connManager) 215 | .setDefaultCookieStore(cookieStore) 216 | .setDefaultCredentialsProvider(credentialsProvider) 217 | .setProxy(new HttpHost("myproxy", 8080)) 218 | .setDefaultRequestConfig(defaultRequestConfig) 219 | .build(); 220 | 221 | try { 222 | HttpGet httpget = new HttpGet("http://localhost/"); 223 | // Request configuration can be overridden at the request level. 224 | // They will take precedence over the one set at the client level. 225 | RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig) 226 | .setSocketTimeout(5000) 227 | .setConnectTimeout(5000) 228 | .setConnectionRequestTimeout(5000) 229 | .setProxy(new HttpHost("myotherproxy", 8080)) 230 | .build(); 231 | httpget.setConfig(requestConfig); 232 | 233 | // Execution context can be customized locally. 234 | HttpClientContext localContext = HttpClientContext.create(); 235 | // Contextual attributes set the local context level will take 236 | // precedence over those set at the client level. 237 | localContext.setCookieStore(cookieStore); 238 | localContext.setCredentialsProvider(credentialsProvider); 239 | 240 | System.out.println("Executing request " + httpget.getRequestLine()); 241 | 242 | httpclient.start(); 243 | 244 | // Pass local context as a parameter 245 | Future future = httpclient.execute(httpget, localContext, null); 246 | 247 | // Please note that it may be unsafe to access HttpContext instance 248 | // while the request is still being executed 249 | 250 | HttpResponse response = future.get(); 251 | System.out.println("Response: " + response.getStatusLine()); 252 | 253 | // Once the request has been executed the local context can 254 | // be used to examine updated state and various objects affected 255 | // by the request execution. 256 | 257 | // Last executed request 258 | localContext.getRequest(); 259 | // Execution route 260 | localContext.getHttpRoute(); 261 | // Target auth state 262 | localContext.getTargetAuthState(); 263 | // Proxy auth state 264 | localContext.getTargetAuthState(); 265 | // Cookie origin 266 | localContext.getCookieOrigin(); 267 | // Cookie spec used 268 | localContext.getCookieSpec(); 269 | // User security token 270 | localContext.getUserToken(); 271 | } finally { 272 | httpclient.close(); 273 | } 274 | } 275 | 276 | } 277 | 278 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientCustomContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | 28 | package test.examples.org.apache.http.examples.nio.client; 29 | 30 | import org.apache.http.HttpResponse; 31 | import org.apache.http.client.CookieStore; 32 | import org.apache.http.client.methods.HttpGet; 33 | import org.apache.http.client.protocol.HttpClientContext; 34 | import org.apache.http.cookie.Cookie; 35 | import org.apache.http.impl.client.BasicCookieStore; 36 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 37 | import org.apache.http.impl.nio.client.HttpAsyncClients; 38 | 39 | import java.util.List; 40 | import java.util.concurrent.Future; 41 | 42 | /** 43 | * This example demonstrates the use of a local HTTP context populated with 44 | * custom attributes. 45 | */ 46 | public class AsyncClientCustomContext { 47 | 48 | public final static void main(String[] args) throws Exception { 49 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); 50 | try { 51 | // Create a local instance of cookie store 52 | CookieStore cookieStore = new BasicCookieStore(); 53 | 54 | // Create local HTTP context 55 | HttpClientContext localContext = HttpClientContext.create(); 56 | // Bind custom cookie store to the local context 57 | localContext.setCookieStore(cookieStore); 58 | 59 | HttpGet httpget = new HttpGet("http://localhost/"); 60 | System.out.println("Executing request " + httpget.getRequestLine()); 61 | 62 | httpclient.start(); 63 | 64 | // Pass local context as a parameter 65 | Future future = httpclient.execute(httpget, localContext, null); 66 | 67 | // Please note that it may be unsafe to access HttpContext instance 68 | // while the request is still being executed 69 | 70 | HttpResponse response = future.get(); 71 | System.out.println("Response: " + response.getStatusLine()); 72 | List cookies = cookieStore.getCookies(); 73 | for (int i = 0; i < cookies.size(); i++) { 74 | System.out.println("Local cookie: " + cookies.get(i)); 75 | } 76 | System.out.println("Shutting down"); 77 | } finally { 78 | httpclient.close(); 79 | } 80 | } 81 | 82 | } 83 | 84 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientCustomSSL.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import java.io.File; 30 | import java.io.FileInputStream; 31 | import java.security.KeyStore; 32 | import java.util.concurrent.Future; 33 | 34 | import javax.net.ssl.SSLContext; 35 | 36 | import org.apache.http.HttpResponse; 37 | import org.apache.http.client.methods.HttpGet; 38 | import org.apache.http.conn.ssl.TrustSelfSignedStrategy; 39 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 40 | import org.apache.http.impl.nio.client.HttpAsyncClients; 41 | import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; 42 | import org.apache.http.ssl.SSLContexts; 43 | 44 | /** 45 | * This example demonstrates how to create secure connections with a custom SSL 46 | * context. 47 | */ 48 | public class AsyncClientCustomSSL { 49 | 50 | public final static void main(String[] args) throws Exception { 51 | KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 52 | FileInputStream instream = new FileInputStream(new File("my.keystore")); 53 | try { 54 | trustStore.load(instream, "nopassword".toCharArray()); 55 | } finally { 56 | instream.close(); 57 | } 58 | // Trust own CA and all self-signed certs 59 | SSLContext sslcontext = SSLContexts.custom() 60 | .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) 61 | .build(); 62 | // Allow TLSv1 protocol only 63 | SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy( 64 | sslcontext, 65 | new String[] { "TLSv1" }, 66 | null, 67 | SSLIOSessionStrategy.getDefaultHostnameVerifier()); 68 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() 69 | .setSSLStrategy(sslSessionStrategy) 70 | .build(); 71 | try { 72 | httpclient.start(); 73 | HttpGet request = new HttpGet("https://issues.apache.org/"); 74 | Future future = httpclient.execute(request, null); 75 | HttpResponse response = future.get(); 76 | System.out.println("Response: " + response.getStatusLine()); 77 | System.out.println("Shutting down"); 78 | } finally { 79 | httpclient.close(); 80 | } 81 | System.out.println("Done"); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientEvictExpiredConnections.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import org.apache.http.HttpResponse; 30 | import org.apache.http.client.methods.HttpGet; 31 | import org.apache.http.concurrent.FutureCallback; 32 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 33 | import org.apache.http.impl.nio.client.HttpAsyncClients; 34 | import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; 35 | import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; 36 | import org.apache.http.nio.conn.NHttpClientConnectionManager; 37 | import org.apache.http.nio.reactor.ConnectingIOReactor; 38 | 39 | import java.util.concurrent.CountDownLatch; 40 | import java.util.concurrent.TimeUnit; 41 | 42 | /** 43 | * Example demonstrating how to evict expired and idle connections 44 | * from the connection pool. 45 | */ 46 | public class AsyncClientEvictExpiredConnections { 47 | 48 | public static void main(String[] args) throws Exception { 49 | ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); 50 | PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor); 51 | cm.setMaxTotal(100); 52 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() 53 | .setConnectionManager(cm) 54 | .build(); 55 | try { 56 | httpclient.start(); 57 | 58 | // create an array of URIs to perform GETs on 59 | String[] urisToGet = { 60 | "http://hc.apache.org/", 61 | "http://hc.apache.org/httpcomponents-core-ga/", 62 | "http://hc.apache.org/httpcomponents-client-ga/", 63 | }; 64 | 65 | IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm); 66 | connEvictor.start(); 67 | 68 | final CountDownLatch latch = new CountDownLatch(urisToGet.length); 69 | for (final String uri: urisToGet) { 70 | final HttpGet httpget = new HttpGet(uri); 71 | httpclient.execute(httpget, new FutureCallback() { 72 | 73 | @Override 74 | public void completed(final HttpResponse response) { 75 | latch.countDown(); 76 | System.out.println(httpget.getRequestLine() + "->" + response.getStatusLine()); 77 | } 78 | 79 | @Override 80 | public void failed(final Exception ex) { 81 | latch.countDown(); 82 | System.out.println(httpget.getRequestLine() + "->" + ex); 83 | } 84 | 85 | @Override 86 | public void cancelled() { 87 | latch.countDown(); 88 | System.out.println(httpget.getRequestLine() + " cancelled"); 89 | } 90 | 91 | }); 92 | } 93 | latch.await(); 94 | 95 | // Sleep 10 sec and let the connection evictor do its job 96 | Thread.sleep(20000); 97 | 98 | // Shut down the evictor thread 99 | connEvictor.shutdown(); 100 | connEvictor.join(); 101 | 102 | } finally { 103 | httpclient.close(); 104 | } 105 | } 106 | 107 | public static class IdleConnectionEvictor extends Thread { 108 | 109 | private final NHttpClientConnectionManager connMgr; 110 | 111 | private volatile boolean shutdown; 112 | 113 | public IdleConnectionEvictor(NHttpClientConnectionManager connMgr) { 114 | super(); 115 | this.connMgr = connMgr; 116 | } 117 | 118 | @Override 119 | public void run() { 120 | try { 121 | while (!shutdown) { 122 | synchronized (this) { 123 | wait(5000); 124 | // Close expired connections 125 | connMgr.closeExpiredConnections(); 126 | // Optionally, close connections 127 | // that have been idle longer than 5 sec 128 | connMgr.closeIdleConnections(5, TimeUnit.SECONDS); 129 | } 130 | } 131 | } catch (InterruptedException ex) { 132 | // terminate 133 | } 134 | } 135 | 136 | public void shutdown() { 137 | shutdown = true; 138 | synchronized (this) { 139 | notifyAll(); 140 | } 141 | } 142 | 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientExecuteProxy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | 28 | package test.examples.org.apache.http.examples.nio.client; 29 | 30 | import java.util.concurrent.Future; 31 | 32 | import org.apache.http.HttpHost; 33 | import org.apache.http.HttpResponse; 34 | import org.apache.http.client.config.RequestConfig; 35 | import org.apache.http.client.methods.HttpGet; 36 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 37 | import org.apache.http.impl.nio.client.HttpAsyncClients; 38 | 39 | /** 40 | * This example demonstrates a basic asynchronous HTTP request / response exchange 41 | * via an HTTP proxy. 42 | */ 43 | public class AsyncClientExecuteProxy { 44 | 45 | public static void main(String[] args)throws Exception { 46 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); 47 | try { 48 | httpclient.start(); 49 | HttpHost proxy = new HttpHost("someproxy", 8080); 50 | RequestConfig config = RequestConfig.custom() 51 | .setProxy(proxy) 52 | .build(); 53 | HttpGet request = new HttpGet("https://issues.apache.org/"); 54 | request.setConfig(config); 55 | Future future = httpclient.execute(request, null); 56 | HttpResponse response = future.get(); 57 | System.out.println("Response: " + response.getStatusLine()); 58 | System.out.println("Shutting down"); 59 | } finally { 60 | httpclient.close(); 61 | } 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientHttpExchange.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import java.util.concurrent.Future; 30 | 31 | import org.apache.http.HttpResponse; 32 | import org.apache.http.client.methods.HttpGet; 33 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 34 | import org.apache.http.impl.nio.client.HttpAsyncClients; 35 | 36 | /** 37 | * This example demonstrates a basic asynchronous HTTP request / response exchange. 38 | * Response content is buffered in memory for simplicity. 39 | */ 40 | public class AsyncClientHttpExchange { 41 | 42 | public static void main(final String[] args) throws Exception { 43 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); 44 | try { 45 | httpclient.start(); 46 | HttpGet request = new HttpGet("http://www.apache.org/"); 47 | Future future = httpclient.execute(request, null); 48 | HttpResponse response = future.get(); 49 | System.out.println("Response: " + response.getStatusLine()); 50 | System.out.println("Shutting down"); 51 | } finally { 52 | httpclient.close(); 53 | } 54 | System.out.println("Done"); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientHttpExchangeFutureCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import java.util.concurrent.CountDownLatch; 30 | 31 | import org.apache.http.HttpResponse; 32 | import org.apache.http.client.config.RequestConfig; 33 | import org.apache.http.client.methods.HttpGet; 34 | import org.apache.http.concurrent.FutureCallback; 35 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 36 | import org.apache.http.impl.nio.client.HttpAsyncClients; 37 | 38 | /** 39 | * This example demonstrates a fully asynchronous execution of multiple HTTP exchanges 40 | * where the result of an individual operation is reported using a callback interface. 41 | */ 42 | public class AsyncClientHttpExchangeFutureCallback { 43 | 44 | public static void main(final String[] args) throws Exception { 45 | RequestConfig requestConfig = RequestConfig.custom() 46 | .setSocketTimeout(3000) 47 | .setConnectTimeout(3000).build(); 48 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() 49 | .setDefaultRequestConfig(requestConfig) 50 | .build(); 51 | try { 52 | httpclient.start(); 53 | final HttpGet[] requests = new HttpGet[] { 54 | new HttpGet("http://www.apache.org/"), 55 | new HttpGet("https://www.verisign.com/"), 56 | new HttpGet("http://www.google.com/") 57 | }; 58 | final CountDownLatch latch = new CountDownLatch(requests.length); 59 | for (final HttpGet request: requests) { 60 | httpclient.execute(request, new FutureCallback() { 61 | 62 | @Override 63 | public void completed(final HttpResponse response) { 64 | latch.countDown(); 65 | System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); 66 | } 67 | 68 | @Override 69 | public void failed(final Exception ex) { 70 | latch.countDown(); 71 | System.out.println(request.getRequestLine() + "->" + ex); 72 | } 73 | 74 | @Override 75 | public void cancelled() { 76 | latch.countDown(); 77 | System.out.println(request.getRequestLine() + " cancelled"); 78 | } 79 | 80 | }); 81 | } 82 | latch.await(); 83 | System.out.println("Shutting down"); 84 | } finally { 85 | httpclient.close(); 86 | } 87 | System.out.println("Done"); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientHttpExchangeStreaming.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import java.io.IOException; 30 | import java.nio.CharBuffer; 31 | import java.util.concurrent.Future; 32 | 33 | import org.apache.http.HttpResponse; 34 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 35 | import org.apache.http.impl.nio.client.HttpAsyncClients; 36 | import org.apache.http.nio.IOControl; 37 | import org.apache.http.nio.client.methods.AsyncCharConsumer; 38 | import org.apache.http.nio.client.methods.HttpAsyncMethods; 39 | import org.apache.http.protocol.HttpContext; 40 | 41 | /** 42 | * This example demonstrates an asynchronous HTTP request / response exchange with 43 | * a full content streaming. 44 | */ 45 | public class AsyncClientHttpExchangeStreaming { 46 | 47 | public static void main(final String[] args) throws Exception { 48 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); 49 | try { 50 | httpclient.start(); 51 | Future future = httpclient.execute( 52 | HttpAsyncMethods.createGet("http://localhost:8080/"), 53 | new MyResponseConsumer(), null); 54 | Boolean result = future.get(); 55 | if (result != null && result.booleanValue()) { 56 | System.out.println("Request successfully executed"); 57 | } else { 58 | System.out.println("Request failed"); 59 | } 60 | System.out.println("Shutting down"); 61 | } finally { 62 | httpclient.close(); 63 | } 64 | System.out.println("Done"); 65 | } 66 | 67 | static class MyResponseConsumer extends AsyncCharConsumer { 68 | 69 | @Override 70 | protected void onResponseReceived(final HttpResponse response) { 71 | } 72 | 73 | @Override 74 | protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException { 75 | while (buf.hasRemaining()) { 76 | System.out.print(buf.get()); 77 | } 78 | } 79 | 80 | @Override 81 | protected void releaseResources() { 82 | } 83 | 84 | @Override 85 | protected Boolean buildResult(final HttpContext context) { 86 | return Boolean.TRUE; 87 | } 88 | 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientPipelined.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import java.util.Arrays; 30 | import java.util.List; 31 | import java.util.concurrent.Future; 32 | 33 | import org.apache.http.HttpHost; 34 | import org.apache.http.HttpRequest; 35 | import org.apache.http.HttpResponse; 36 | import org.apache.http.client.methods.HttpGet; 37 | import org.apache.http.impl.nio.client.CloseableHttpPipeliningClient; 38 | import org.apache.http.impl.nio.client.HttpAsyncClients; 39 | 40 | /** 41 | * This example demonstrates a pipelinfed execution of multiple HTTP request / response exchanges 42 | * Response content is buffered in memory for simplicity. 43 | */ 44 | public class AsyncClientPipelined { 45 | 46 | public static void main(final String[] args) throws Exception { 47 | CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining(); 48 | try { 49 | httpclient.start(); 50 | 51 | HttpHost targetHost = new HttpHost("localhost", 8080); 52 | HttpGet[] resquests = { 53 | new HttpGet("/docs/index.html"), 54 | new HttpGet("/docs/introduction.html"), 55 | new HttpGet("/docs/setup.html"), 56 | new HttpGet("/docs/config/index.html") 57 | }; 58 | 59 | Future> future = httpclient.execute(targetHost, 60 | Arrays.asList(resquests), null); 61 | List responses = future.get(); 62 | System.out.println(responses); 63 | 64 | System.out.println("Shutting down"); 65 | } finally { 66 | httpclient.close(); 67 | } 68 | System.out.println("Done"); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientPipelinedStreaming.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import java.io.IOException; 30 | import java.nio.CharBuffer; 31 | import java.util.ArrayList; 32 | import java.util.List; 33 | import java.util.concurrent.Future; 34 | 35 | import org.apache.http.HttpHost; 36 | import org.apache.http.HttpRequest; 37 | import org.apache.http.HttpResponse; 38 | import org.apache.http.client.methods.HttpGet; 39 | import org.apache.http.impl.nio.client.CloseableHttpPipeliningClient; 40 | import org.apache.http.impl.nio.client.HttpAsyncClients; 41 | import org.apache.http.nio.IOControl; 42 | import org.apache.http.nio.client.methods.AsyncCharConsumer; 43 | import org.apache.http.nio.protocol.BasicAsyncRequestProducer; 44 | import org.apache.http.protocol.HttpContext; 45 | 46 | /** 47 | * This example demonstrates a pipelinfed execution of multiple HTTP request / response exchanges 48 | * with a full content streaming. 49 | */ 50 | public class AsyncClientPipelinedStreaming { 51 | 52 | public static void main(final String[] args) throws Exception { 53 | CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining(); 54 | try { 55 | httpclient.start(); 56 | 57 | HttpHost targetHost = new HttpHost("localhost", 8080); 58 | HttpGet[] resquests = { 59 | new HttpGet("/docs/index.html"), 60 | new HttpGet("/docs/introduction.html"), 61 | new HttpGet("/docs/setup.html"), 62 | new HttpGet("/docs/config/index.html") 63 | }; 64 | 65 | List requestProducers = new ArrayList(); 66 | List responseConsumers = new ArrayList(); 67 | for (HttpGet request: resquests) { 68 | requestProducers.add(new MyRequestProducer(targetHost, request)); 69 | responseConsumers.add(new MyResponseConsumer(request)); 70 | } 71 | 72 | Future> future = httpclient.execute( 73 | targetHost, requestProducers, responseConsumers, null); 74 | future.get(); 75 | System.out.println("Shutting down"); 76 | } finally { 77 | httpclient.close(); 78 | } 79 | System.out.println("Done"); 80 | } 81 | 82 | static class MyRequestProducer extends BasicAsyncRequestProducer { 83 | 84 | private final HttpRequest request; 85 | 86 | MyRequestProducer(final HttpHost target, final HttpRequest request) { 87 | super(target, request); 88 | this.request = request; 89 | } 90 | 91 | @Override 92 | public void requestCompleted(final HttpContext context) { 93 | super.requestCompleted(context); 94 | System.out.println(); 95 | System.out.println("Request sent: " + this.request.getRequestLine()); 96 | System.out.println("================================================="); 97 | } 98 | } 99 | 100 | static class MyResponseConsumer extends AsyncCharConsumer { 101 | 102 | private final HttpRequest request; 103 | 104 | MyResponseConsumer(final HttpRequest request) { 105 | this.request = request; 106 | } 107 | 108 | @Override 109 | protected void onResponseReceived(final HttpResponse response) { 110 | System.out.println(); 111 | System.out.println("Response received: " + response.getStatusLine() + " -> " + this.request.getRequestLine()); 112 | System.out.println("================================================="); 113 | } 114 | 115 | @Override 116 | protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException { 117 | while (buf.hasRemaining()) { 118 | System.out.print(buf.get()); 119 | } 120 | } 121 | 122 | @Override 123 | protected void releaseResources() { 124 | } 125 | 126 | @Override 127 | protected Boolean buildResult(final HttpContext context) { 128 | System.out.println(); 129 | System.out.println("================================================="); 130 | System.out.println(); 131 | return Boolean.TRUE; 132 | } 133 | 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/AsyncClientProxyAuthentication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | 28 | package test.examples.org.apache.http.examples.nio.client; 29 | 30 | import org.apache.http.HttpHost; 31 | import org.apache.http.HttpResponse; 32 | import org.apache.http.auth.AuthScope; 33 | import org.apache.http.auth.UsernamePasswordCredentials; 34 | import org.apache.http.client.CredentialsProvider; 35 | import org.apache.http.client.config.RequestConfig; 36 | import org.apache.http.client.methods.HttpGet; 37 | import org.apache.http.impl.client.BasicCredentialsProvider; 38 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 39 | import org.apache.http.impl.nio.client.HttpAsyncClients; 40 | 41 | import java.util.concurrent.Future; 42 | 43 | /** 44 | * This example demonstrates a basic asynchronous HTTP request / response exchange 45 | * over a secure connection tunneled through an authenticating proxy. 46 | */ 47 | public class AsyncClientProxyAuthentication { 48 | 49 | public static void main(String[] args)throws Exception { 50 | CredentialsProvider credsProvider = new BasicCredentialsProvider(); 51 | credsProvider.setCredentials( 52 | new AuthScope("someproxy", 8080), 53 | new UsernamePasswordCredentials("username", "password")); 54 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() 55 | .setDefaultCredentialsProvider(credsProvider) 56 | .build(); 57 | try { 58 | httpclient.start(); 59 | HttpHost proxy = new HttpHost("someproxy", 8080); 60 | RequestConfig config = RequestConfig.custom() 61 | .setProxy(proxy) 62 | .build(); 63 | HttpGet httpget = new HttpGet("https://issues.apache.org/"); 64 | httpget.setConfig(config); 65 | Future future = httpclient.execute(httpget, null); 66 | HttpResponse response = future.get(); 67 | System.out.println("Response: " + response.getStatusLine()); 68 | System.out.println("Shutting down"); 69 | } finally { 70 | httpclient.close(); 71 | } 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/QuickStart.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import org.apache.http.HttpResponse; 30 | import org.apache.http.client.methods.HttpGet; 31 | import org.apache.http.concurrent.FutureCallback; 32 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 33 | import org.apache.http.impl.nio.client.HttpAsyncClients; 34 | import org.apache.http.nio.IOControl; 35 | import org.apache.http.nio.client.methods.AsyncCharConsumer; 36 | import org.apache.http.nio.client.methods.HttpAsyncMethods; 37 | import org.apache.http.nio.protocol.HttpAsyncRequestProducer; 38 | import org.apache.http.protocol.HttpContext; 39 | 40 | import java.io.IOException; 41 | import java.nio.CharBuffer; 42 | import java.util.concurrent.CountDownLatch; 43 | import java.util.concurrent.Future; 44 | import java.util.logging.Level; 45 | import java.util.logging.Logger; 46 | import org.apache.http.HttpEntity; 47 | import org.apache.http.ParseException; 48 | import org.apache.http.util.EntityUtils; 49 | 50 | public class QuickStart { 51 | 52 | public static void main(String[] args) throws Exception { 53 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); 54 | HttpEntity entity = null; 55 | String jsonContent = ""; 56 | try { 57 | // Start the client 58 | httpclient.start(); 59 | 60 | // Execute request 61 | final HttpGet request1 = new HttpGet("http://viphp.sinaapp.com/baidu/translate/translate.php?origin=中文"); 62 | Future future = httpclient.execute(request1, null); 63 | // and wait until response is received 64 | final HttpResponse response1 = future.get(); 65 | System.out.println(request1.getRequestLine() + "->" + response1.getStatusLine()); 66 | 67 | entity = response1.getEntity(); 68 | jsonContent = EntityUtils.toString(entity, "UTF-8"); 69 | System.out.println("jsonContent:" + jsonContent); 70 | // One most likely would want to use a callback for operation result 71 | final CountDownLatch latch1 = new CountDownLatch(1); 72 | final HttpGet request2 = new HttpGet("http://viphp.sinaapp.com/baidu/translate/translate.php?origin=中文"); 73 | httpclient.execute(request2, new FutureCallback() { 74 | 75 | @Override 76 | public void completed(final HttpResponse response2) { 77 | try { 78 | latch1.countDown(); 79 | System.out.println(request2.getRequestLine() + "->" + response2.getStatusLine()); 80 | HttpEntity entity = response2.getEntity(); 81 | String jsonContent = EntityUtils.toString(entity, "UTF-8"); 82 | System.out.println("jsonContent2:" + jsonContent); 83 | } catch (IOException ex) { 84 | Logger.getLogger(QuickStart.class.getName()).log(Level.SEVERE, null, ex); 85 | } catch (ParseException ex) { 86 | Logger.getLogger(QuickStart.class.getName()).log(Level.SEVERE, null, ex); 87 | } 88 | } 89 | 90 | @Override 91 | public void failed(final Exception ex) { 92 | latch1.countDown(); 93 | System.out.println(request2.getRequestLine() + "->" + ex); 94 | } 95 | 96 | @Override 97 | public void cancelled() { 98 | latch1.countDown(); 99 | System.out.println(request2.getRequestLine() + " cancelled"); 100 | } 101 | 102 | }); 103 | latch1.await(); 104 | 105 | // In real world one most likely would want also want to stream 106 | // request and response body content 107 | final CountDownLatch latch2 = new CountDownLatch(1); 108 | final HttpGet request3 = new HttpGet("http://viphp.sinaapp.com/baidu/translate/translate.php?origin=中文"); 109 | HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(request3); 110 | AsyncCharConsumer consumer3 = new AsyncCharConsumer() { 111 | 112 | HttpResponse response; 113 | 114 | @Override 115 | protected void onResponseReceived(final HttpResponse response) { 116 | this.response = response; 117 | } 118 | 119 | @Override 120 | protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException { 121 | // Do something useful 122 | System.out.println(buf.toString()); 123 | } 124 | 125 | @Override 126 | protected void releaseResources() { 127 | } 128 | 129 | @Override 130 | protected HttpResponse buildResult(final HttpContext context) { 131 | return this.response; 132 | } 133 | 134 | }; 135 | httpclient.execute(producer3, consumer3, new FutureCallback() { 136 | 137 | @Override 138 | public void completed(final HttpResponse response3) { 139 | try { 140 | latch2.countDown(); 141 | System.out.println(request2.getRequestLine() + "-3>" + response3.getStatusLine()); 142 | HttpEntity entity = response3.getEntity(); 143 | String jsonContent = EntityUtils.toString(entity, "UTF-8"); 144 | System.out.println("jsonContent3:" + jsonContent); 145 | } catch (IOException ex) { 146 | Logger.getLogger(QuickStart.class.getName()).log(Level.SEVERE, null, ex); 147 | } catch (ParseException ex) { 148 | Logger.getLogger(QuickStart.class.getName()).log(Level.SEVERE, null, ex); 149 | } 150 | } 151 | 152 | @Override 153 | public void failed(final Exception ex) { 154 | latch2.countDown(); 155 | System.out.println(request2.getRequestLine() + "->" + ex); 156 | } 157 | 158 | @Override 159 | public void cancelled() { 160 | latch2.countDown(); 161 | System.out.println(request2.getRequestLine() + " cancelled"); 162 | } 163 | 164 | }); 165 | latch2.await(); 166 | 167 | } finally { 168 | httpclient.close(); 169 | } 170 | } 171 | 172 | } 173 | -------------------------------------------------------------------------------- /src/test/examples/org/apache/http/examples/nio/client/ZeroCopyHttpExchange.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ==================================================================== 3 | * Licensed to the Apache Software Foundation (ASF) under one 4 | * or more contributor license agreements. See the NOTICE file 5 | * distributed with this work for additional information 6 | * regarding copyright ownership. The ASF licenses this file 7 | * to you under the Apache License, Version 2.0 (the 8 | * "License"); you may not use this file except in compliance 9 | * with the License. You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, 14 | * software distributed under the License is distributed on an 15 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | * KIND, either express or implied. See the License for the 17 | * specific language governing permissions and limitations 18 | * under the License. 19 | * ==================================================================== 20 | * 21 | * This software consists of voluntary contributions made by many 22 | * individuals on behalf of the Apache Software Foundation. For more 23 | * information on the Apache Software Foundation, please see 24 | * . 25 | * 26 | */ 27 | package test.examples.org.apache.http.examples.nio.client; 28 | 29 | import java.io.File; 30 | import java.util.concurrent.Future; 31 | 32 | import org.apache.http.HttpResponse; 33 | import org.apache.http.HttpStatus; 34 | import org.apache.http.client.ClientProtocolException; 35 | import org.apache.http.entity.ContentType; 36 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; 37 | import org.apache.http.impl.nio.client.HttpAsyncClients; 38 | import org.apache.http.nio.client.methods.ZeroCopyConsumer; 39 | import org.apache.http.nio.client.methods.ZeroCopyPost; 40 | 41 | /** 42 | * This example demonstrates how HttpAsyncClient can be used to upload or download files 43 | * without creating an intermediate content buffer in memory (zero copy file transfer). 44 | */ 45 | public class ZeroCopyHttpExchange { 46 | 47 | public static void main(final String[] args) throws Exception { 48 | CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); 49 | try { 50 | httpclient.start(); 51 | File upload = new File(args[0]); 52 | File download = new File(args[1]); 53 | ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload, 54 | ContentType.create("text/plain")); 55 | ZeroCopyConsumer consumer = new ZeroCopyConsumer(download) { 56 | 57 | @Override 58 | protected File process( 59 | final HttpResponse response, 60 | final File file, 61 | final ContentType contentType) throws Exception { 62 | if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { 63 | throw new ClientProtocolException("Upload failed: " + response.getStatusLine()); 64 | } 65 | return file; 66 | } 67 | 68 | }; 69 | Future future = httpclient.execute(httpost, consumer, null); 70 | File result = future.get(); 71 | System.out.println("Response file length: " + result.length()); 72 | System.out.println("Shutting down"); 73 | } finally { 74 | httpclient.close(); 75 | } 76 | System.out.println("Done"); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/translation/HttpDownloader.java: -------------------------------------------------------------------------------- 1 | package translation; 2 | 3 | import java.io.*; 4 | import java.net.HttpURLConnection; 5 | import java.net.URL; 6 | 7 | public class HttpDownloader { 8 | 9 | private static URL url = null; 10 | private static String tagstr = null; 11 | private static String tagstrtemp = null; 12 | private static String tagstrtemp2 = null; 13 | //private static String nl=System.lineSeparator(); 14 | private static String newline = System.getProperty("line.separator"); 15 | private static int counter = 0; 16 | 17 | public static String download(String urlPath) { 18 | StringBuffer sb = new StringBuffer(); 19 | String line = null; 20 | BufferedReader br = null; 21 | 22 | try { 23 | //create a URL object 24 | url = new URL(urlPath); 25 | //create http connection 26 | HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 27 | //use i/o stream to read data 28 | br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8")); 29 | while ((line = br.readLine()) != null) { 30 | sb.append(line + newline); 31 | } 32 | br.close(); 33 | } catch (Exception e) { 34 | e.printStackTrace(); 35 | } 36 | tagstr = sb.toString(); 37 | return tagstr; 38 | } 39 | 40 | public static String getHtml(String urlPath, String c) { 41 | StringBuffer sb = new StringBuffer(); 42 | String line = null; 43 | BufferedReader br = null; 44 | 45 | try { 46 | //create a URL object 47 | url = new URL(urlPath); 48 | //create http connection 49 | HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 50 | //use i/o stream to read data 51 | br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), c)); 52 | while ((line = br.readLine()) != null) { 53 | sb.append(line + newline); 54 | } 55 | br.close(); 56 | } catch (Exception e) { 57 | e.printStackTrace(); 58 | } 59 | tagstr = sb.toString(); 60 | return tagstr; 61 | } 62 | 63 | public static int stringNumbers(String str, String find) { 64 | if (str.indexOf("<" + find) == -1) { 65 | return 0; 66 | } else if (str.indexOf("<" + find) != -1) { 67 | counter++; 68 | tagstrtemp = tagstrtemp.replaceFirst("<" + find, "<" + counter + find); 69 | tagstrtemp = tagstrtemp.replaceFirst(">> "+tags[i]); } int 82 | * c=stringNumbers(tagstr,"div");System.out.println(c); 83 | * //tagstr.replaceFirst("<"+tag, "<"+i+tag); String [] 84 | * tagstemp=tagstrtemp.split(nl); 85 | * System.out.println("----------------------------"); for(int 86 | * i=0;i>> 87 | * "+tagstemp[i]); } 88 | */ 89 | try { 90 | File f = new File("D:\\12.txt"); 91 | System.out.println(f.getAbsoluteFile()); 92 | if (!f.exists()) { 93 | f.createNewFile(); 94 | System.out.println(f.exists()); 95 | } 96 | // FileOutputStream out = new FileOutputStream(f, true);//第二参数为true时,从文件结尾添加 97 | // out.write((newline + "123").getBytes()); 98 | // //out.flush(); 99 | // out.close(); 100 | FileWriter fw = new FileWriter(f,true); 101 | PrintWriter pw=new PrintWriter(fw); 102 | pw.println("append content"); 103 | pw.close () ; 104 | fw.close () ; 105 | System.out.println("123"); 106 | } catch (Exception e) { 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/translation/MSDN_Translate(1).java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package translation; 6 | // 7 | //import com.memetix.mst.language.Language; 8 | //import com.memetix.mst.translate.Translate; 9 | // 10 | ///** 11 | // * 12 | // * @author v 13 | // */ 14 | //public class MSDN_Translate { 15 | // 16 | // public static String t(String args) throws Exception { 17 | // // Set your Windows Azure Marketplace client info - See http://msdn.microsoft.com/en-us/library/hh454950.aspx 18 | // Translate.setClientId("9cf63463-28b0-49d9-9649-a71bd3a983c3"); 19 | // Translate.setClientSecret("sZE0BqM84VSU4QLpmGSTuEe2RMw4Sr9n1rnOwojEcJo"); 20 | // 21 | // String translatedText = Translate.execute(args, Language.ENGLISH, Language.CHINESE_SIMPLIFIED); 22 | // return translatedText; 23 | // } 24 | //} 25 | -------------------------------------------------------------------------------- /src/translation/MSDN_Translate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package translation; 6 | 7 | import com.memetix.mst.language.Language; 8 | import com.memetix.mst.translate.Translate; 9 | 10 | /** 11 | * 12 | * @author v 13 | */ 14 | public class MSDN_Translate { 15 | 16 | public static String t(String args) throws Exception { 17 | // Set your Windows Azure Marketplace client info - See http://msdn.microsoft.com/en-us/library/hh454950.aspx 18 | Translate.setClientId("9cf63463-28b0-49d9-9649-a71bd3a983c3"); 19 | Translate.setClientSecret("sZE0BqM84VSU4QLpmGSTuEe2RMw4Sr9n1rnOwojEcJo"); 20 | 21 | String translatedText = Translate.execute(args, Language.ENGLISH, Language.CHINESE_SIMPLIFIED); 22 | return translatedText; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/translation/MultiLineRowRenderer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package translation; 7 | 8 | import javax.swing.JTextArea; 9 | import javax.swing.table.TableCellRenderer; 10 | import javax.swing.table.DefaultTableCellRenderer; 11 | import java.util.*; 12 | import javax.swing.JTable; 13 | import java.awt.Component; 14 | import javax.swing.table.TableColumn; 15 | import javax.swing.table.TableColumnModel; 16 | 17 | /** 18 | *

19 | * Title:

20 | *

21 | * Description:

22 | *

23 | * Copyright: Copyright (c) 2008

24 | *

25 | * Company:

26 | * 27 | * @Author SamZheng 2008-03-31 28 | * @version 1.0 29 | */ 30 | public class MultiLineRowRenderer 31 | extends JTextArea 32 | implements TableCellRenderer { 33 | 34 | private final DefaultTableCellRenderer adaptee = new DefaultTableCellRenderer(); 35 | 36 | /** 37 | * map from table to map of rows to map of column heights 38 | */ 39 | private final Map cellSizes = new HashMap(); 40 | 41 | public MultiLineRowRenderer() { 42 | setLineWrap(true); 43 | setWrapStyleWord(true); 44 | } 45 | 46 | public Component getTableCellRendererComponent( // 47 | JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, 48 | int column) { 49 | // set the colours, etc. using the standard for that platform 50 | adaptee.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, 51 | column); 52 | setForeground(adaptee.getForeground()); 53 | setBackground(adaptee.getBackground()); 54 | setBorder(adaptee.getBorder()); 55 | setFont(adaptee.getFont()); 56 | setText(adaptee.getText()); 57 | 58 | // This line was very important to get it working with JDK1.4 59 | TableColumnModel columnModel = table.getColumnModel(); 60 | setSize(columnModel.getColumn(column).getWidth(), 100000); 61 | int height_wanted = (int) getPreferredSize().getHeight(); 62 | addSize(table, row, column, height_wanted); 63 | height_wanted = findTotalMaximumRowSize(table, row); 64 | if (height_wanted != table.getRowHeight(row)) { 65 | table.setRowHeight(row, height_wanted); 66 | } 67 | return this; 68 | } 69 | 70 | private void addSize(JTable table, int row, int column, int height) { 71 | Map rows = (Map) cellSizes.get(table); 72 | if (rows == null) { 73 | cellSizes.put(table, rows = new HashMap()); 74 | } 75 | Map rowheights = (Map) rows.get(new Integer(row)); 76 | if (rowheights == null) { 77 | rows.put(new Integer(row), rowheights = new HashMap()); 78 | } 79 | rowheights.put(new Integer(column), new Integer(height)); 80 | } 81 | 82 | /** 83 | * Look through all columns and get the renderer. If it is also a 84 | * MultiLineRowRenderer, we look at the maximum height in its hash table for 85 | * this row. 86 | */ 87 | private int findTotalMaximumRowSize(JTable table, int row) { 88 | int maximum_height = 0; 89 | Enumeration columns = table.getColumnModel().getColumns(); 90 | while (columns.hasMoreElements()) { 91 | TableColumn tc = (TableColumn) columns.nextElement(); 92 | TableCellRenderer cellRenderer = tc.getCellRenderer(); 93 | if (cellRenderer instanceof MultiLineRowRenderer) { 94 | MultiLineRowRenderer tar = (MultiLineRowRenderer) cellRenderer; 95 | maximum_height = Math.max(maximum_height, 96 | tar.findMaximumRowSize(table, row)); 97 | } 98 | } 99 | return maximum_height; 100 | } 101 | 102 | private int findMaximumRowSize(JTable table, int row) { 103 | Map rows = (Map) cellSizes.get(table); 104 | if (rows == null) { 105 | return 0; 106 | } 107 | Map rowheights = (Map) rows.get(new Integer(row)); 108 | if (rowheights == null) { 109 | return 0; 110 | } 111 | int maximum_height = 0; 112 | for (Iterator it = rowheights.entrySet().iterator(); it.hasNext();) { 113 | Map.Entry entry = (Map.Entry) it.next(); 114 | int cellHeight = ((Integer) entry.getValue()).intValue(); 115 | maximum_height = Math.max(maximum_height, cellHeight); 116 | } 117 | return maximum_height; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/translation/Post(1).java: -------------------------------------------------------------------------------- 1 | ///* 2 | // * To change this template, choose Tools | Templates 3 | // * and open the template in the editor. 4 | // */ 5 | //package translation; 6 | // 7 | //import java.io.BufferedReader; 8 | //import java.io.InputStreamReader; 9 | //import java.io.OutputStreamWriter; 10 | //import java.net.HttpURLConnection; 11 | //import java.net.URL; 12 | //import java.util.*; 13 | //import java.util.Map.Entry; 14 | //import net.sf.json.JSONArray; 15 | // 16 | //import net.sf.json.JSONObject; 17 | // 18 | ///** 19 | // * @author yoUng @description 发送http请求 @filename HttpUtil.java @time 2011-6-15 20 | // * 下午05:26:36 21 | // * @version 1.0 22 | // */ 23 | //public class Post { 24 | // 25 | // public static String http(String url, Map params) { 26 | // URL u = null; 27 | // HttpURLConnection con = null; 28 | // StringBuffer buffer = new StringBuffer(); 29 | // //构建请求参数 30 | // StringBuffer sb = new StringBuffer(); 31 | // if (params != null) { 32 | // for (Entry e : params.entrySet()) { 33 | // sb.append(e.getKey()); 34 | // sb.append("="); 35 | // sb.append(e.getValue()); 36 | // sb.append("&");//多个参数时需要加上 37 | // } 38 | // sb.substring(0, sb.length() - 1); 39 | // } 40 | // // System.out.println("send_url:" + url); 41 | // // System.out.println("send_data:" + sb.toString()); 42 | // //尝试发送请求 43 | // try { 44 | // u = new URL(url); 45 | // con = (HttpURLConnection) u.openConnection(); 46 | // con.setRequestMethod("POST"); 47 | // con.setDoOutput(true); 48 | // con.setDoInput(true); 49 | // con.setUseCaches(false); 50 | // con.setReadTimeout(3000); 51 | // con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 52 | // OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); 53 | // osw.write(sb.toString()); 54 | // osw.flush(); 55 | // osw.close(); 56 | // } catch (Exception e) { 57 | // e.printStackTrace(); 58 | // } finally { 59 | // if (con != null) { 60 | // con.disconnect(); 61 | // } 62 | // } 63 | // 64 | // //读取返回内容 65 | // 66 | // try { 67 | // if (con.getResponseCode() == 200) { 68 | // BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); 69 | // String temp; 70 | // while ((temp = br.readLine()) != null) { 71 | // buffer.append(temp); 72 | // buffer.append("\n"); 73 | // } 74 | // } else { 75 | // buffer.append(con.getResponseCode()); 76 | // } 77 | // //System.out.println(con.getResponseCode() + ""); 78 | // } catch (Exception e) { 79 | // e.printStackTrace(); 80 | // } 81 | // return buffer.toString(); 82 | // } 83 | // 84 | // /** 85 | // * 获取翻译结果 86 | // * 87 | // * @param tvalue 需要翻译的中文字符串 88 | // * @return 89 | // */ 90 | // public static String tg(String tvalue) { 91 | // Map map = new HashMap(); 92 | // map.put("client_id", client_id); 93 | // map.put("from", "en"); 94 | // map.put("to", "zh"); 95 | // map.put("q", tvalue); 96 | // String tempt=WordsTransfer.unicodeToUtf8(http("http://openapi.baidu.com/public/2.0/bmt/translate", map).trim().replace("\\", "\\\\")); 97 | // JSONObject json=JSONObject.fromObject(tempt); 98 | // //json=JSONObject.fromObject(json.get("trans_result").toString().replace("[", "").replace("]", "")); 99 | // JSONArray ja=JSONArray.fromObject(json.get("trans_result")); 100 | // json=JSONObject.fromObject(ja.getString(0)); 101 | // //return (String)json.get("dst"); 102 | // return (String)json.getString("dst"); 103 | // } 104 | // /** 105 | // * 获取翻译结果(比用JSON速度更快) 106 | // * 107 | // * @param tvalue 需要翻译的中文字符串 108 | // * @return 109 | // */ 110 | // public static String tg1(String tvalue) { 111 | // Map map = new HashMap(); 112 | // map.put("client_id", client_id); 113 | // map.put("from", "en"); 114 | // map.put("to", "zh"); 115 | // map.put("q", tvalue); 116 | // String tempt=WordsTransfer.unicodeToUtf8(http("http://openapi.baidu.com/public/2.0/bmt/translate", map).trim()); 117 | // tempt=tempt.substring(tempt.lastIndexOf(":")+1,tempt.length()-3).replaceAll("\"",""); 118 | // return tempt; 119 | // } 120 | // /**public static void main(String[] args) { 121 | // long l=System.currentTimeMillis(); 122 | // //System.out.println(tg1("what's your name? How Are You?铅笔")); 123 | // String[] a={"1","2","3","12","32","233","3222","2222","3333333","2234","3443","432","324","2345","314","221","213"}; 124 | // List list=Arrays.asList(a); 125 | // if(list.contains("2234")){ 126 | // System.out.println("contains 1"); 127 | // }else{ 128 | // System.out.println("not contains 1"); 129 | // } 130 | // long l1=System.currentTimeMillis(); 131 | // System.out.println("time1: "+(l1-l)); 132 | // long l2=System.currentTimeMillis(); 133 | // //System.out.println(tg("what's your name? How Are You?铅笔")); 134 | // String[] a1={"1","2","3","12","32","233","3222","2222","3333333","2234","3443","432","324","2345","314","221","213"}; 135 | // for(int i=0;i params) { 26 | URL u = null; 27 | HttpURLConnection con = null; 28 | StringBuffer buffer = new StringBuffer(); 29 | //构建请求参数 30 | StringBuffer sb = new StringBuffer(); 31 | if (params != null) { 32 | for (Entry e : params.entrySet()) { 33 | sb.append(e.getKey()); 34 | sb.append("="); 35 | sb.append(e.getValue()); 36 | //sb.append("&");//多个参数时需要加上 37 | } 38 | sb.substring(0, sb.length() - 1); 39 | } 40 | // System.out.println("send_url:" + url); 41 | // System.out.println("send_data:" + sb.toString()); 42 | //尝试发送请求 43 | try { 44 | u = new URL(url); 45 | con = (HttpURLConnection) u.openConnection(); 46 | con.setRequestMethod("POST"); 47 | con.setDoOutput(true); 48 | con.setDoInput(true); 49 | con.setUseCaches(false); 50 | con.setReadTimeout(3000); 51 | con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 52 | OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); 53 | osw.write(sb.toString()); 54 | osw.flush(); 55 | osw.close(); 56 | } catch (Exception e) { 57 | e.printStackTrace(); 58 | } finally { 59 | if (con != null) { 60 | con.disconnect(); 61 | } 62 | } 63 | 64 | //读取返回内容 65 | try { 66 | if (con.getResponseCode() == 200) { 67 | BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); 68 | String temp; 69 | while ((temp = br.readLine()) != null) { 70 | buffer.append(temp); 71 | buffer.append("\n"); 72 | } 73 | } else { 74 | buffer.append(con.getResponseCode()); 75 | } 76 | //System.out.println(con.getResponseCode() + ""); 77 | } catch (Exception e) { 78 | e.printStackTrace(); 79 | } 80 | return buffer.toString(); 81 | } 82 | 83 | /** 84 | * 获取翻译结果 85 | * 86 | * @param tvalue 需要翻译的中文字符串 87 | * @return 88 | */ 89 | public static String tg(String translate_site, String tvalue) { 90 | Map map = new HashMap();; 91 | map.put("origin", tvalue); 92 | return http(translate_site, map).trim(); 93 | } 94 | 95 | /** 96 | * 获取翻译结果(比用JSON速度更快) 97 | * 98 | * @param tvalue 需要翻译的中文字符串 99 | * @return 100 | */ 101 | public String tg1(String translate_site, String tvalue) { 102 | Map map = new HashMap(); 103 | map.put("origin", tvalue); 104 | String tempt = WordsTransfer.unicodeToUtf8(http(translate_site, map).trim()); 105 | tempt = tempt.substring(tempt.lastIndexOf(":") + 1, tempt.length() - 3).replaceAll("\"", ""); 106 | return tempt; 107 | } 108 | // public static void main(String[] args) { 109 | // Map map = new HashMap();; 110 | // map.put("q", "中国"); 111 | // System.out.println(http("http://zhangwei911.duapp.com/TranslateGet.jsp", map).trim()); 112 | // } 113 | } 114 | -------------------------------------------------------------------------------- /src/translation/PropertiesControl(1).java: -------------------------------------------------------------------------------- 1 | ///* 2 | // * To change this template, choose Tools | Templates 3 | // * and open the template in the editor. 4 | // */ 5 | // 6 | //import java.io.*; 7 | //import java.util.Enumeration; 8 | //import java.util.LinkedList; 9 | //import java.util.List; 10 | //import java.util.jar.JarEntry; 11 | //import java.util.jar.JarFile; 12 | //import java.util.jar.JarOutputStream; 13 | // 14 | ///** 15 | // * @author v 16 | // */ 17 | //public class PropertiesControl { 18 | // 19 | // private static String newline = System.getProperty("line.separator"); 20 | // private static String[] kav; 21 | // 22 | // public PropertiesControl(String filepath) { 23 | // kav = getKeysAndValues(filepath); 24 | // } 25 | // 26 | // public static void put(String newfilepath, String[] content, 27 | // String[] content1) { 28 | // try { 29 | // PrintWriter pw = new PrintWriter(new File(newfilepath)); 30 | // StringBuffer sb = new StringBuffer(); 31 | // for (int i = 0; i < content.length; i++) { 32 | // if (content[i].equals("")) { 33 | // sb.append(newline); 34 | // } else { 35 | // if (i == content.length - 1) { 36 | // sb.append(content[i] + "=" + content1[i]); 37 | // } else { 38 | // sb.append(content[i] + "=" + content1[i] + newline); 39 | // } 40 | // } 41 | // } 42 | // pw.write(sb.toString()); 43 | // pw.close(); 44 | // } catch (Exception e) { 45 | // e.printStackTrace(); 46 | // } 47 | // } 48 | // 49 | // public static String[] getValues(String filepath) { 50 | // String[] values = new String[kav.length]; 51 | // for (int i = 0; i < kav.length; i++) { 52 | // if (!kav[i].contains("=")) { 53 | // values[i] = ""; 54 | // } else { 55 | // values[i] = kav[i].substring(kav[i].indexOf("=") + 1); 56 | // } 57 | // } 58 | // return values; 59 | // } 60 | // 61 | // public static String[] getKeys(String filepath) { 62 | // String[] keys = new String[kav.length]; 63 | // for (int i = 0; i < kav.length; i++) { 64 | // if (!kav[i].contains("=")) { 65 | // keys[i] = ""; 66 | // } else { 67 | // keys[i] = kav[i].substring(0, kav[i].indexOf("=")); 68 | // } 69 | // } 70 | // return keys; 71 | // } 72 | // 73 | // public static String[] getKeysAndValues(String filepath) { 74 | // String[] keysAndValues = null; 75 | // try { 76 | // int count = getFileLineNumber(filepath); 77 | // 78 | // BufferedReader br = getBR(filepath); 79 | // 80 | // String line1 = br.readLine(); 81 | // keysAndValues = new String[count]; 82 | // int count1 = 0; 83 | // while (null != line1) { 84 | // keysAndValues[count1] = line1; 85 | // line1 = br.readLine(); 86 | // count1++; 87 | // } 88 | // br.close(); 89 | // } catch (Exception e) { 90 | // e.printStackTrace(); 91 | // } 92 | // return keysAndValues; 93 | // } 94 | // 95 | // public static int getFileLineNumber(String filepath) { 96 | // int count = 0; 97 | // try { 98 | // BufferedReader br = new BufferedReader(new InputStreamReader( 99 | // new FileInputStream(new File(filepath)))); 100 | // String line = br.readLine(); 101 | // while (null != line) { 102 | // count++; 103 | // line = br.readLine(); 104 | // } 105 | // br.close(); 106 | // } catch (IOException e) { 107 | // e.printStackTrace(); 108 | // } 109 | // 110 | // return count; 111 | // } 112 | // 113 | // public static BufferedReader getBR(String filepath) { 114 | // BufferedReader br = null; 115 | // try { 116 | // br = new BufferedReader(new InputStreamReader(new FileInputStream( 117 | // new File(filepath)))); 118 | // } catch (FileNotFoundException e) { 119 | // e.printStackTrace(); 120 | // } 121 | // return br; 122 | // } 123 | // 124 | // /** 125 | // * 写入jar文件的话会将 jar文件原来的内容统统抹掉!!切记!!~ 126 | // * 127 | // * @param original 源jar包路径 128 | // * @param configPath jar包内属性文件路径 129 | // * @param values 属性文件内容 130 | // * @param ctrl 0为另存为以"'原文件名'+'_temp.jar'"命名的文件,1为删除源文件,2为覆盖源文件。 131 | // */ 132 | // public static void write2JarFile(File original, String configPath, byte[] values) { 133 | // String originalPath = original.getAbsolutePath(); 134 | // /** 135 | // * 创建一个临时文件来做暂存,待一切操作完毕之后会将该文件重命名为原文件的名称(原文件会被删除掉)~ 136 | // */ 137 | // String tempPath = originalPath.substring(0, originalPath.length() - 4) + "_temp.jar"; 138 | //// System.out.println(tempPath); 139 | // 140 | // JarFile originalJar = null; 141 | // try { 142 | // originalJar = new JarFile(originalPath); 143 | // } catch (IOException e1) { 144 | // e1.printStackTrace(); 145 | // } 146 | // List lists = new LinkedList(); 147 | // for (Enumeration entrys = originalJar.entries(); entrys.hasMoreElements(); ) { 148 | // JarEntry jarEntry = entrys.nextElement(); 149 | //// System.out.println(jarEntry.getName()); 150 | // lists.add(jarEntry); 151 | // } 152 | // 153 | // // 定义一个 jaroutputstream 流 154 | // File handled = new File(tempPath); 155 | // JarOutputStream jos = null; 156 | // try { 157 | // FileOutputStream fos = new FileOutputStream(handled); 158 | // jos = new JarOutputStream(fos); 159 | // 160 | // /** 161 | // * 将源文件中的内容复制过来~ 可以利用循环将一个文件夹中的文件都写入jar包中 其实很简单 162 | // */ 163 | // for (JarEntry je : lists) { 164 | // // jar 中的每一个文件夹 每一个文件 都是一个 jarEntry 165 | // JarEntry newEntry = new JarEntry(je.getName()); 166 | // 167 | //// newEntry.setComment(je.getComment()); 168 | //// newEntry.setCompressedSize(je.getCompressedSize()); 169 | //// newEntry.setCrc(je.getCrc()); 170 | //// newEntry.setExtra(je.getExtra()); 171 | //// newEntry.setMethod(je.getMethod()); 172 | //// newEntry.setTime(je.getTime()); 173 | //// System.out.println(je.getAttributes()); 174 | // /** 175 | // * 这句代码有问题,会导致将jar包重命名为zip包之后无法解压缩~ 176 | // */ 177 | //// newEntry.setSize(je.getSize()); 178 | // // 表示将该entry写入jar文件中 也就是创建该文件夹和文件 179 | // jos.putNextEntry(newEntry); 180 | // //System.out.println(je.getName()); 181 | // /** 182 | // * 如果当前已经处理到属性文件了,那么将在 JTextArea 中编辑过的文本写入到该属性文件~ 183 | // */ 184 | // if (je.getName().equals(configPath)) { 185 | // jos.write(values); 186 | // continue; 187 | // } 188 | // 189 | // InputStream is = originalJar.getInputStream(je); 190 | // byte[] bytes = inputStream2byteArray(is); 191 | // is.close(); 192 | // 193 | // // 然后就是往entry中的jj.txt文件中写入内容 194 | // jos.write(bytes); 195 | // } 196 | // // 最后不能忘记关闭流 197 | // jos.close(); 198 | // fos.close(); 199 | // 200 | // /** 201 | // * 删除原始文件,将新生成的文件重命名为原始文件的名称~ 202 | // */ 203 | // handled.renameTo(new File(originalPath)); 204 | // } catch (Exception e) { 205 | // e.printStackTrace(); 206 | // } 207 | // } 208 | // 209 | // public static String[] getJarFileContent(File original) { 210 | // JarFile originalJar = null; 211 | // String[] jarFileContent = null; 212 | // try { 213 | // originalJar = new JarFile(original.getAbsoluteFile()); 214 | // } catch (IOException e1) { 215 | // e1.printStackTrace(); 216 | // } 217 | // List lists = new LinkedList(); 218 | // for (Enumeration entrys = originalJar.entries(); entrys.hasMoreElements(); ) { 219 | // JarEntry jarEntry = entrys.nextElement(); 220 | //// System.out.println(jarEntry.getName()); 221 | // lists.add(jarEntry); 222 | // } 223 | // 224 | // try { 225 | // String[] temppath = new String[lists.size()]; 226 | // int i = 0; 227 | // /** 228 | // * 将源文件中的内容复制过来~ 可以利用循环将一个文件夹中的文件都写入jar包中 其实很简单 229 | // */ 230 | // for (JarEntry je : lists) { 231 | // if (je.getName().toString().endsWith(".properties")) { 232 | // temppath[i] = je.getName(); 233 | // i++; 234 | // } 235 | // } 236 | // jarFileContent = new String[i]; 237 | // for (int tempi = 0; tempi < i; tempi++) { 238 | // jarFileContent[tempi] = temppath[tempi]; 239 | // } 240 | // } catch (Exception e) { 241 | // e.printStackTrace(); 242 | // } 243 | // return jarFileContent; 244 | // } 245 | // 246 | // /** 247 | // * InputStream 转 byte[]~ 248 | // * 249 | // * @param is 250 | // * @return 251 | // */ 252 | // public static byte[] inputStream2byteArray(InputStream is) { 253 | // ByteArrayOutputStream baos = new ByteArrayOutputStream(); 254 | // int i; 255 | // try { 256 | // while ((i = is.read()) != -1) { 257 | // baos.write(i); 258 | // } 259 | // baos.close(); 260 | // } catch (IOException e) { 261 | // e.printStackTrace(); 262 | // } 263 | // byte[] bytes = baos.toByteArray(); 264 | // return bytes; 265 | // } 266 | // 267 | // public static String[] getBytesValue(byte[] bytes) { 268 | // return new String(bytes).split("\n"); 269 | // } 270 | //} 271 | -------------------------------------------------------------------------------- /src/translation/PropertiesControl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package translation; 6 | 7 | import java.io.*; 8 | import java.util.Enumeration; 9 | import java.util.LinkedList; 10 | import java.util.List; 11 | import java.util.jar.JarEntry; 12 | import java.util.jar.JarFile; 13 | import java.util.jar.JarOutputStream; 14 | 15 | /** 16 | * 17 | * @author v 18 | */ 19 | public class PropertiesControl { 20 | 21 | private static String newline = System.getProperty("line.separator"); 22 | 23 | public static void put(String newfilepath, String[] content, 24 | String[] content1) { 25 | try { 26 | PrintWriter pw = new PrintWriter(new File(newfilepath)); 27 | StringBuffer sb = new StringBuffer(); 28 | for (int i = 0; i < content.length; i++) { 29 | if (content[i].equals("")) { 30 | sb.append(newline); 31 | } else { 32 | if (i == content.length - 1) { 33 | sb.append(content[i] + "=" + content1[i]); 34 | } else { 35 | sb.append(content[i] + "=" + content1[i] + newline); 36 | } 37 | } 38 | } 39 | pw.write(sb.toString()); 40 | pw.close(); 41 | } catch (Exception e) { 42 | e.printStackTrace(); 43 | } 44 | } 45 | 46 | public static String[] getValues(String filepath) { 47 | String[] kav = getKeysAndValues(filepath); 48 | String[] values = new String[kav.length]; 49 | for (int i = 0; i < kav.length; i++) { 50 | values[i] = kav[i].substring(kav[i].indexOf("=") + 1); 51 | } 52 | return values; 53 | } 54 | 55 | public static String[] getKeys(String filepath) { 56 | String[] kav = getKeysAndValues(filepath); 57 | String[] keys = new String[kav.length]; 58 | for (int i = 0; i < kav.length; i++) { 59 | if (kav[i].indexOf("=") == -1) { 60 | keys[i] = ""; 61 | } else { 62 | keys[i] = kav[i].substring(0, kav[i].indexOf("=")); 63 | } 64 | } 65 | return keys; 66 | } 67 | 68 | public static String[] getKeysAndValues(String filepath) { 69 | String[] keysAndValues = null; 70 | try { 71 | int count = getFileLineNumber(filepath); 72 | 73 | BufferedReader br = getBR(filepath); 74 | 75 | String line1 = br.readLine(); 76 | keysAndValues = new String[count]; 77 | int count1 = 0; 78 | while (null != line1) { 79 | keysAndValues[count1] = line1; 80 | line1 = br.readLine(); 81 | count1++; 82 | } 83 | br.close(); 84 | } catch (Exception e) { 85 | e.printStackTrace(); 86 | } 87 | return keysAndValues; 88 | } 89 | 90 | public static int getFileLineNumber(String filepath) { 91 | int count = 0; 92 | try { 93 | BufferedReader br = new BufferedReader(new InputStreamReader( 94 | new FileInputStream(new File(filepath)))); 95 | String line = br.readLine(); 96 | while (null != line) { 97 | count++; 98 | line = br.readLine(); 99 | } 100 | br.close(); 101 | } catch (IOException e) { 102 | e.printStackTrace(); 103 | } 104 | 105 | return count; 106 | } 107 | 108 | public static BufferedReader getBR(String filepath) { 109 | BufferedReader br = null; 110 | try { 111 | br = new BufferedReader(new InputStreamReader(new FileInputStream( 112 | new File(filepath)))); 113 | } catch (FileNotFoundException e) { 114 | e.printStackTrace(); 115 | } 116 | return br; 117 | } 118 | 119 | /** 120 | * 写入jar文件的话会将 jar文件原来的内容统统抹掉!!切记!!~ 121 | * 122 | * @param original 源jar包路径 123 | * @param configPath jar包内属性文件路径 124 | * @param values 属性文件内容 125 | * @param ctrl 0为另存为以"'原文件名'+'_temp.jar'"命名的文件,1为删除源文件,2为覆盖源文件。 126 | */ 127 | public static void write2JarFile(File original, String configPath, byte[] values) { 128 | String originalPath = original.getAbsolutePath(); 129 | /** 130 | * 创建一个临时文件来做暂存,待一切操作完毕之后会将该文件重命名为原文件的名称(原文件会被删除掉)~ 131 | */ 132 | String tempPath = originalPath.substring(0, originalPath.length() - 4) + "_temp.jar"; 133 | // System.out.println(tempPath); 134 | 135 | JarFile originalJar = null; 136 | try { 137 | originalJar = new JarFile(originalPath); 138 | } catch (IOException e1) { 139 | e1.printStackTrace(); 140 | } 141 | List lists = new LinkedList(); 142 | for (Enumeration entrys = originalJar.entries(); entrys.hasMoreElements();) { 143 | JarEntry jarEntry = entrys.nextElement(); 144 | // System.out.println(jarEntry.getName()); 145 | lists.add(jarEntry); 146 | } 147 | 148 | // 定义一个 jaroutputstream 流 149 | File handled = new File(tempPath); 150 | JarOutputStream jos = null; 151 | try { 152 | FileOutputStream fos = new FileOutputStream(handled); 153 | jos = new JarOutputStream(fos); 154 | 155 | /** 156 | * 将源文件中的内容复制过来~ 可以利用循环将一个文件夹中的文件都写入jar包中 其实很简单 157 | */ 158 | for (JarEntry je : lists) { 159 | // jar 中的每一个文件夹 每一个文件 都是一个 jarEntry 160 | JarEntry newEntry = new JarEntry(je.getName()); 161 | 162 | // newEntry.setComment(je.getComment()); 163 | // newEntry.setCompressedSize(je.getCompressedSize()); 164 | // newEntry.setCrc(je.getCrc()); 165 | // newEntry.setExtra(je.getExtra()); 166 | // newEntry.setMethod(je.getMethod()); 167 | // newEntry.setTime(je.getTime()); 168 | // System.out.println(je.getAttributes()); 169 | /** 170 | * 这句代码有问题,会导致将jar包重命名为zip包之后无法解压缩~ 171 | */ 172 | // newEntry.setSize(je.getSize()); 173 | // 表示将该entry写入jar文件中 也就是创建该文件夹和文件 174 | jos.putNextEntry(newEntry); 175 | //System.out.println(je.getName()); 176 | /** 177 | * 如果当前已经处理到属性文件了,那么将在 JTextArea 中编辑过的文本写入到该属性文件~ 178 | */ 179 | if (je.getName().equals(configPath)) { 180 | jos.write(values); 181 | continue; 182 | } 183 | 184 | InputStream is = originalJar.getInputStream(je); 185 | byte[] bytes = inputStream2byteArray(is); 186 | is.close(); 187 | 188 | // 然后就是往entry中的jj.txt文件中写入内容 189 | jos.write(bytes); 190 | } 191 | // 最后不能忘记关闭流 192 | jos.close(); 193 | fos.close(); 194 | 195 | /** 196 | * 删除原始文件,将新生成的文件重命名为原始文件的名称~ 197 | */ 198 | handled.renameTo(new File(originalPath)); 199 | } catch (Exception e) { 200 | e.printStackTrace(); 201 | } 202 | } 203 | 204 | public static String[] getJarFileContent(File original) { 205 | JarFile originalJar = null; 206 | String[] jarFileContent = null; 207 | try { 208 | originalJar = new JarFile(original.getAbsoluteFile()); 209 | } catch (IOException e1) { 210 | e1.printStackTrace(); 211 | } 212 | List lists = new LinkedList(); 213 | for (Enumeration entrys = originalJar.entries(); entrys.hasMoreElements();) { 214 | JarEntry jarEntry = entrys.nextElement(); 215 | // System.out.println(jarEntry.getName()); 216 | lists.add(jarEntry); 217 | } 218 | 219 | try { 220 | String[] temppath = new String[lists.size()]; 221 | int i = 0; 222 | /** 223 | * 将源文件中的内容复制过来~ 可以利用循环将一个文件夹中的文件都写入jar包中 其实很简单 224 | */ 225 | for (JarEntry je : lists) { 226 | if (je.getName().toString().endsWith(".properties")) { 227 | temppath[i] = je.getName(); 228 | i++; 229 | } 230 | } 231 | jarFileContent = new String[i]; 232 | for (int tempi = 0; tempi < i; tempi++) { 233 | jarFileContent[tempi] = temppath[tempi]; 234 | } 235 | } catch (Exception e) { 236 | e.printStackTrace(); 237 | } 238 | return jarFileContent; 239 | } 240 | 241 | /** 242 | * InputStream 转 byte[]~ 243 | * 244 | * @param is 245 | * @return 246 | */ 247 | public static byte[] inputStream2byteArray(InputStream is) { 248 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 249 | int i; 250 | try { 251 | while ((i = is.read()) != -1) { 252 | baos.write(i); 253 | } 254 | baos.close(); 255 | } catch (IOException e) { 256 | e.printStackTrace(); 257 | } 258 | byte[] bytes = baos.toByteArray(); 259 | return bytes; 260 | } 261 | 262 | public static String[] getBytesValue(byte[] bytes) { 263 | return new String(bytes).split("\n"); 264 | } 265 | } 266 | -------------------------------------------------------------------------------- /src/translation/PropertiesControl2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package translation; 7 | 8 | import java.io.ByteArrayOutputStream; 9 | import java.io.File; 10 | import java.io.FileInputStream; 11 | import java.io.FileNotFoundException; 12 | import java.io.FileOutputStream; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | import java.util.ArrayList; 16 | import java.util.Enumeration; 17 | import java.util.HashMap; 18 | import java.util.Iterator; 19 | import java.util.LinkedList; 20 | import java.util.List; 21 | import java.util.Map; 22 | import java.util.Map.Entry; 23 | import java.util.Properties; 24 | import java.util.jar.JarEntry; 25 | import java.util.jar.JarFile; 26 | import java.util.jar.JarOutputStream; 27 | 28 | /** 29 | * 30 | * @author swtf 31 | */ 32 | public class PropertiesControl2 { 33 | 34 | private Properties props = new Properties(); 35 | private boolean isNull = false; 36 | 37 | private List keyList = new ArrayList(); 38 | private List valueList = new ArrayList(); 39 | 40 | private Map kvMap = new HashMap(); 41 | 42 | public PropertiesControl2(String filepath) { 43 | try { 44 | InputStream is = new FileInputStream(new File(filepath)); 45 | if (null != is) { 46 | props.load(is); 47 | is.close(); 48 | setKeysAndValues(); 49 | } 50 | } catch (FileNotFoundException e) { 51 | System.err.println("文件" + filepath + "不存在"); 52 | isNull = true; 53 | } catch (IOException e) { 54 | e.printStackTrace(); 55 | } 56 | } 57 | 58 | public PropertiesControl2(InputStream is) { 59 | try { 60 | if (null != is) { 61 | props.load(is); 62 | is.close(); 63 | setKeysAndValues(); 64 | } 65 | } catch (FileNotFoundException e) { 66 | isNull = true; 67 | } catch (IOException e) { 68 | e.printStackTrace(); 69 | } 70 | } 71 | 72 | public String getStringValue(String key) { 73 | if (!isNull) { 74 | return props.getProperty(key); 75 | } else { 76 | return null; 77 | } 78 | } 79 | 80 | public boolean getBooleanValue(String key) { 81 | if (!isNull) { 82 | String value = props.getProperty(key); 83 | if (value.equals("true")) { 84 | return true; 85 | } else { 86 | return false; 87 | } 88 | } else { 89 | return false; 90 | } 91 | } 92 | 93 | public int getCount() { 94 | return props.size(); 95 | } 96 | 97 | /** 98 | * @param properties 99 | */ 100 | private void setKeysAndValues() { 101 | Iterator> it = props.entrySet().iterator(); 102 | while (it.hasNext()) { 103 | Entry entry = it.next(); 104 | String key = (String) entry.getKey(); 105 | String value = (String) entry.getValue(); 106 | keyList.add(key); 107 | valueList.add(value); 108 | kvMap.put(key, value); 109 | } 110 | } 111 | 112 | public List getKeyList() { 113 | return keyList; 114 | } 115 | 116 | public List getValueList() { 117 | return valueList; 118 | } 119 | 120 | public Map getKeysAndValuesMap() { 121 | return kvMap; 122 | } 123 | 124 | public Iterator> getIterator() { 125 | return props.entrySet().iterator(); 126 | } 127 | 128 | public void save(List kList, List vList) { 129 | int count = getCount(); 130 | for (int i = 0; i < count; i++) { 131 | props.setProperty(kList.get(i), vList.get(i)); 132 | } 133 | } 134 | 135 | /** 136 | * 写入jar文件的话会将 jar文件原来的内容统统抹掉!!切记!!~ 137 | * 138 | * @param original 源jar包路径 139 | * @param configPath jar包内属性文件路径 140 | * @param values 属性文件内容 141 | */ 142 | public void write2JarFile(File original, String configPath, byte[] values) { 143 | write2JarFile(original, null, configPath, values, 0); 144 | } 145 | 146 | /** 147 | * 写入jar文件的话会将 jar文件原来的内容统统抹掉!!切记!!~ 148 | * 149 | * @param original 源jar包路径 150 | * @param tempFileName jar包名称 151 | * @param configPath jar包内属性文件路径 152 | * @param values 属性文件内容 153 | */ 154 | public void write2JarFile(File original, String tempFileName, String configPath, byte[] values) { 155 | write2JarFile(original, tempFileName, configPath, values, 0); 156 | } 157 | 158 | /** 159 | * 写入jar文件的话会将 jar文件原来的内容统统抹掉!!切记!!~ 160 | * 161 | * @param original 源jar包路径 162 | * @param tempFileName jar包名称 163 | * @param configPath jar包内属性文件路径 164 | * @param values 属性文件内容 165 | * @param ctrl 0为另存为以"'原文件名'+'_temp.jar'"命名的文件,1为删除源文件,2为覆盖源文件。 166 | */ 167 | public void write2JarFile(File original, String tempFileName, String configPath, byte[] values, int ctrl) { 168 | String originalPath = original.getAbsolutePath(); 169 | /** 170 | * 创建一个临时文件来做暂存,待一切操作完毕之后会将该文件重命名为原文件的名称(原文件会被删除掉)~ 171 | */ 172 | String tempPath = null; 173 | if (tempFileName == null) { 174 | tempPath = originalPath.substring(0, originalPath.lastIndexOf(".")) + "_temp" + originalPath.substring(originalPath.lastIndexOf(".")); 175 | } else { 176 | tempPath = original.getParent() + File.separator + tempFileName; 177 | } 178 | 179 | System.out.println(tempPath); 180 | JarFile originalJar = null; 181 | try { 182 | originalJar = new JarFile(originalPath); 183 | } catch (IOException e1) { 184 | e1.printStackTrace(); 185 | } 186 | List lists = new LinkedList(); 187 | for (Enumeration entrys = originalJar.entries(); entrys.hasMoreElements();) { 188 | JarEntry jarEntry = entrys.nextElement(); 189 | // System.out.println(jarEntry.getName()); 190 | lists.add(jarEntry); 191 | } 192 | 193 | // 定义一个 jaroutputstream 流 194 | File handled = new File(tempPath); 195 | JarOutputStream jos = null; 196 | try { 197 | FileOutputStream fos = new FileOutputStream(handled); 198 | jos = new JarOutputStream(fos); 199 | 200 | /** 201 | * 将源文件中的内容复制过来~ 可以利用循环将一个文件夹中的文件都写入jar包中 其实很简单 202 | */ 203 | for (JarEntry je : lists) { 204 | // jar 中的每一个文件夹 每一个文件 都是一个 jarEntry 205 | JarEntry newEntry = new JarEntry(je.getName()); 206 | 207 | // newEntry.setComment(je.getComment()); 208 | // newEntry.setCompressedSize(je.getCompressedSize()); 209 | // newEntry.setCrc(je.getCrc()); 210 | // newEntry.setExtra(je.getExtra()); 211 | // newEntry.setMethod(je.getMethod()); 212 | // newEntry.setTime(je.getTime()); 213 | // System.out.println(je.getAttributes()); 214 | /** 215 | * 这句代码有问题,会导致将jar包重命名为zip包之后无法解压缩~ 216 | */ 217 | // newEntry.setSize(je.getSize()); 218 | // 表示将该entry写入jar文件中 也就是创建该文件夹和文件 219 | jos.putNextEntry(newEntry); 220 | //System.out.println(je.getName()); 221 | /** 222 | * 如果当前已经处理到属性文件了,那么将在 JTextArea 中编辑过的文本写入到该属性文件~ 223 | */ 224 | if (je.getName().equals(configPath)) { 225 | jos.write(values); 226 | continue; 227 | } 228 | 229 | InputStream is = originalJar.getInputStream(je); 230 | byte[] bytes = inputStream2byteArray(is); 231 | is.close(); 232 | 233 | // 然后就是往entry中的jj.txt文件中写入内容 234 | jos.write(bytes); 235 | } 236 | // 最后不能忘记关闭流 237 | jos.close(); 238 | fos.close(); 239 | 240 | switch (ctrl) { 241 | case 0: 242 | 243 | break; 244 | case 1: 245 | new File(originalPath).delete(); 246 | break; 247 | case 2: 248 | /** 249 | * 删除原始文件,将新生成的文件重命名为原始文件的名称~ 250 | */ 251 | System.out.println(originalPath); 252 | // handled.renameTo(new File(originalPath)); 253 | copyFile(tempPath,originalPath); 254 | handled.delete(); 255 | break; 256 | default: 257 | 258 | break; 259 | } 260 | 261 | } catch (Exception e) { 262 | e.printStackTrace(); 263 | } 264 | } 265 | 266 | /** 267 | * InputStream 转 byte[]~ 268 | * 269 | * @param is 270 | * @return 271 | */ 272 | public byte[] inputStream2byteArray(InputStream is) { 273 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 274 | int i; 275 | try { 276 | while ((i = is.read()) != -1) { 277 | baos.write(i); 278 | } 279 | baos.close(); 280 | } catch (IOException e) { 281 | e.printStackTrace(); 282 | } 283 | byte[] bytes = baos.toByteArray(); 284 | return bytes; 285 | } 286 | 287 | private static void copyFile(String oldPath, 288 | String newPath) 289 | throws Exception { 290 | 291 | int bytesum = 0; 292 | int byteread = 0; 293 | FileInputStream inPutStream = null; 294 | FileOutputStream outPutStream = null; 295 | 296 | try { 297 | 298 | // oldPath的文件copy到新的路径下,如果在新路径下有同名文件,则覆盖源文件 299 | inPutStream = new FileInputStream(oldPath); 300 | 301 | outPutStream = new FileOutputStream(newPath); 302 | byte[] buffer = new byte[4096]; 303 | 304 | while ((byteread = inPutStream.read(buffer)) != -1) { 305 | 306 | // byte ファイル 307 | bytesum += byteread; 308 | outPutStream.write(buffer, 0, byteread); 309 | } 310 | } finally { 311 | 312 | // inPutStreamを关闭 313 | if (inPutStream != null) { 314 | inPutStream.close(); 315 | inPutStream = null; 316 | } 317 | 318 | // inPutStream关闭 319 | if (outPutStream != null) { 320 | outPutStream.close(); 321 | outPutStream = null; 322 | } 323 | 324 | } 325 | 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /src/translation/WordsTransfer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | package translation; 6 | 7 | import java.lang.Character.UnicodeBlock; 8 | public class WordsTransfer{ 9 | 10 | public String gbkToUtf8(String gbk) { 11 | String l_temp = GBKToUnicode(gbk); 12 | l_temp = unicodeToUtf8(l_temp); 13 | 14 | return l_temp; 15 | } 16 | 17 | public String utf8ToGBk(String utf) { 18 | String l_temp = utf8ToUnicode(utf); 19 | l_temp = UnicodeToGBK(l_temp); 20 | 21 | return l_temp; 22 | } 23 | 24 | /** 25 | * 26 | * @param str 27 | * @return String 28 | */ 29 | 30 | public static String GBKToUnicode(String str) { 31 | StringBuffer result = new StringBuffer(); 32 | for (int i = 0; i < str.length(); i++) { 33 | char chr1 = (char) str.charAt(i); 34 | 35 | if (!isNeedConvert(chr1)) { 36 | result.append(chr1); 37 | continue; 38 | } 39 | 40 | result.append("\\u" + Integer.toHexString((int) chr1)); 41 | } 42 | 43 | return result.toString(); 44 | } 45 | 46 | /** 47 | * 48 | * @param dataStr 49 | * @return String 50 | */ 51 | 52 | public static String UnicodeToGBK(String dataStr) { 53 | int index = 0; 54 | StringBuffer buffer = new StringBuffer(); 55 | 56 | int li_len = dataStr.length(); 57 | while (index < li_len) { 58 | if (index >= li_len - 1 59 | || !"\\u".equals(dataStr.substring(index, index + 2))) { 60 | buffer.append(dataStr.charAt(index)); 61 | 62 | index++; 63 | continue; 64 | } 65 | 66 | String charStr = ""; 67 | charStr = dataStr.substring(index + 2, index + 6); 68 | 69 | char letter = (char) Integer.parseInt(charStr, 16); 70 | 71 | buffer.append(letter); 72 | index += 6; 73 | } 74 | 75 | return buffer.toString(); 76 | } 77 | 78 | public static boolean isNeedConvert(char para) { 79 | return ((para & (0x00FF)) != para); 80 | } 81 | 82 | /** 83 | * utf-8 转unicode 84 | * 85 | * @param inStr 86 | * @return String 87 | */ 88 | public static String utf8ToUnicode(String inStr) { 89 | char[] myBuffer = inStr.toCharArray(); 90 | 91 | StringBuffer sb = new StringBuffer(); 92 | for (int i = 0; i < inStr.length(); i++) { 93 | UnicodeBlock ub = UnicodeBlock.of(myBuffer[i]); 94 | if (ub == UnicodeBlock.BASIC_LATIN) { 95 | sb.append(myBuffer[i]); 96 | } else if (ub == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { 97 | int j = (int) myBuffer[i] - 65248; 98 | sb.append((char) j); 99 | } else { 100 | short s = (short) myBuffer[i]; 101 | String hexS = Integer.toHexString(s); 102 | String unicode = "\\u" + hexS; 103 | sb.append(unicode.toLowerCase()); 104 | } 105 | } 106 | return sb.toString().replaceAll("ffff", ""); 107 | } 108 | 109 | /** 110 | * 111 | * @param theString 112 | * @return String 113 | */ 114 | public static String unicodeToUtf8(String theString) { 115 | char aChar; 116 | int len = theString.length(); 117 | StringBuffer outBuffer = new StringBuffer(len); 118 | for (int x = 0; x < len;) { 119 | aChar = theString.charAt(x++); 120 | if (aChar == '\\') { 121 | aChar = theString.charAt(x++); 122 | if (aChar == 'u') { 123 | // Read the xxxx 124 | int value = 0; 125 | for (int i = 0; i < 4; i++) { 126 | aChar = theString.charAt(x++); 127 | switch (aChar) { 128 | case '0': 129 | case '1': 130 | case '2': 131 | case '3': 132 | case '4': 133 | case '5': 134 | case '6': 135 | case '7': 136 | case '8': 137 | case '9': 138 | value = (value << 4) + aChar - '0'; 139 | break; 140 | case 'a': 141 | case 'b': 142 | case 'c': 143 | case 'd': 144 | case 'e': 145 | case 'f': 146 | value = (value << 4) + 10 + aChar - 'a'; 147 | break; 148 | case 'A': 149 | case 'B': 150 | case 'C': 151 | case 'D': 152 | case 'E': 153 | case 'F': 154 | value = (value << 4) + 10 + aChar - 'A'; 155 | break; 156 | default: 157 | throw new IllegalArgumentException( 158 | "Malformed \\uxxxx encoding."); 159 | } 160 | } 161 | outBuffer.append((char) value); 162 | } else { 163 | if (aChar == 't') 164 | aChar = '\t'; 165 | else if (aChar == 'r') 166 | aChar = '\r'; 167 | else if (aChar == 'n') 168 | aChar = '\n'; 169 | else if (aChar == 'f') 170 | aChar = '\f'; 171 | outBuffer.append(aChar); 172 | } 173 | } else 174 | outBuffer.append(aChar); 175 | } 176 | return outBuffer.toString(); 177 | } 178 | 179 | 180 | } 181 | -------------------------------------------------------------------------------- /src/translation/baidu/BaiDuTranslate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package translation.baidu; 7 | 8 | import static translation.baidu.BaiDuTranslateApiConfig.APP_ID; 9 | import static translation.baidu.BaiDuTranslateApiConfig.SECURITY_KEY; 10 | 11 | /** 12 | * 13 | * @author swtf 14 | */ 15 | public class BaiDuTranslate { 16 | public static String translate(String query,String to){ 17 | BaiDuTranslateApi api = new BaiDuTranslateApi(APP_ID, SECURITY_KEY); 18 | return api.getTransResult(query, "auto", to); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/translation/baidu/BaiDuTranslateApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package translation.baidu; 7 | 8 | /** 9 | * 10 | * @author swtf 11 | */ 12 | import translation.utils.HttpGet; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | import translation.utils.MD5; 16 | 17 | public class BaiDuTranslateApi { 18 | private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate"; 19 | 20 | private String appid; 21 | private String securityKey; 22 | 23 | public BaiDuTranslateApi(String appid, String securityKey) { 24 | this.appid = appid; 25 | this.securityKey = securityKey; 26 | } 27 | 28 | public String getTransResult(String query, String from, String to) { 29 | Map params = buildParams(query, from, to); 30 | return HttpGet.get(TRANS_API_HOST, params); 31 | } 32 | 33 | private Map buildParams(String query, String from, String to) { 34 | Map params = new HashMap(); 35 | params.put("q", query); 36 | params.put("from", from); 37 | params.put("to", to); 38 | 39 | params.put("appid", appid); 40 | 41 | // 随机数 42 | String salt = String.valueOf(System.currentTimeMillis()); 43 | params.put("salt", salt); 44 | 45 | // 签名 46 | String src = appid + query + salt + securityKey; // 加密前的原文 47 | params.put("sign", MD5.md5(src)); 48 | 49 | return params; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/translation/baidu/BaiDuTranslateApiConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package translation.baidu; 7 | 8 | /** 9 | * 10 | * @author swtf 11 | */ 12 | public class BaiDuTranslateApiConfig { 13 | public static final String APP_ID = ""; 14 | public static final String SECURITY_KEY = ""; 15 | } 16 | -------------------------------------------------------------------------------- /src/translation/utils/HttpGet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package translation.utils; 7 | 8 | /** 9 | * 10 | * @author swtf 11 | */ 12 | import java.io.BufferedReader; 13 | import java.io.Closeable; 14 | import java.io.IOException; 15 | import java.io.InputStream; 16 | import java.io.InputStreamReader; 17 | import java.io.UnsupportedEncodingException; 18 | import java.net.HttpURLConnection; 19 | import java.net.MalformedURLException; 20 | import java.net.URL; 21 | import java.net.URLEncoder; 22 | import java.security.KeyManagementException; 23 | import java.security.NoSuchAlgorithmException; 24 | import java.security.cert.CertificateException; 25 | import java.security.cert.X509Certificate; 26 | import java.util.Map; 27 | 28 | import javax.net.ssl.HttpsURLConnection; 29 | import javax.net.ssl.SSLContext; 30 | import javax.net.ssl.TrustManager; 31 | import javax.net.ssl.X509TrustManager; 32 | 33 | public class HttpGet { 34 | protected static final int SOCKET_TIMEOUT = 10000; // 10S 35 | protected static final String GET = "GET"; 36 | 37 | public static String get(String host, Map params) { 38 | try { 39 | // 设置SSLContext 40 | SSLContext sslcontext = SSLContext.getInstance("TLS"); 41 | sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null); 42 | 43 | String sendUrl = getUrlWithQueryString(host, params); 44 | 45 | // System.out.println("URL:" + sendUrl); 46 | 47 | URL uri = new URL(sendUrl); // 创建URL对象 48 | HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); 49 | if (conn instanceof HttpsURLConnection) { 50 | ((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory()); 51 | } 52 | 53 | conn.setConnectTimeout(SOCKET_TIMEOUT); // 设置相应超时 54 | conn.setRequestMethod(GET); 55 | int statusCode = conn.getResponseCode(); 56 | if (statusCode != HttpURLConnection.HTTP_OK) { 57 | System.out.println("Http错误码:" + statusCode); 58 | } 59 | 60 | // 读取服务器的数据 61 | InputStream is = conn.getInputStream(); 62 | BufferedReader br = new BufferedReader(new InputStreamReader(is)); 63 | StringBuilder builder = new StringBuilder(); 64 | String line = null; 65 | while ((line = br.readLine()) != null) { 66 | builder.append(line); 67 | } 68 | 69 | String text = builder.toString(); 70 | 71 | close(br); // 关闭数据流 72 | close(is); // 关闭数据流 73 | conn.disconnect(); // 断开连接 74 | 75 | return text; 76 | } catch (MalformedURLException e) { 77 | e.printStackTrace(); 78 | } catch (IOException e) { 79 | e.printStackTrace(); 80 | } catch (KeyManagementException e) { 81 | e.printStackTrace(); 82 | } catch (NoSuchAlgorithmException e) { 83 | e.printStackTrace(); 84 | } 85 | 86 | return null; 87 | } 88 | 89 | public static String getUrlWithQueryString(String url, Map params) { 90 | if (params == null) { 91 | return url; 92 | } 93 | 94 | StringBuilder builder = new StringBuilder(url); 95 | if (url.contains("?")) { 96 | builder.append("&"); 97 | } else { 98 | builder.append("?"); 99 | } 100 | 101 | int i = 0; 102 | for (String key : params.keySet()) { 103 | String value = params.get(key); 104 | if (value == null) { // 过滤空的key 105 | continue; 106 | } 107 | 108 | if (i != 0) { 109 | builder.append('&'); 110 | } 111 | 112 | builder.append(key); 113 | builder.append('='); 114 | builder.append(encode(value)); 115 | 116 | i++; 117 | } 118 | 119 | return builder.toString(); 120 | } 121 | 122 | protected static void close(Closeable closeable) { 123 | if (closeable != null) { 124 | try { 125 | closeable.close(); 126 | } catch (IOException e) { 127 | e.printStackTrace(); 128 | } 129 | } 130 | } 131 | 132 | /** 133 | * 对输入的字符串进行URL编码, 即转换为%20这种形式 134 | * 135 | * @param input 原文 136 | * @return URL编码. 如果编码失败, 则返回原文 137 | */ 138 | public static String encode(String input) { 139 | if (input == null) { 140 | return ""; 141 | } 142 | 143 | try { 144 | return URLEncoder.encode(input, "utf-8"); 145 | } catch (UnsupportedEncodingException e) { 146 | e.printStackTrace(); 147 | } 148 | 149 | return input; 150 | } 151 | 152 | private static TrustManager myX509TrustManager = new X509TrustManager() { 153 | 154 | @Override 155 | public X509Certificate[] getAcceptedIssuers() { 156 | return null; 157 | } 158 | 159 | @Override 160 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 161 | } 162 | 163 | @Override 164 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 165 | } 166 | }; 167 | 168 | } 169 | 170 | -------------------------------------------------------------------------------- /src/translation/utils/MD5.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package translation.utils; 7 | 8 | import java.io.File; 9 | import java.io.FileInputStream; 10 | import java.io.FileNotFoundException; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | import java.io.UnsupportedEncodingException; 14 | import java.security.MessageDigest; 15 | import java.security.NoSuchAlgorithmException; 16 | import java.util.logging.Level; 17 | import java.util.logging.Logger; 18 | 19 | /** 20 | * MD5编码相关的类 21 | * 22 | * @author wangjingtao 23 | * 24 | */ 25 | public class MD5 { 26 | // 首先初始化一个字符数组,用来存放每个16进制字符 27 | private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 28 | 'e', 'f' }; 29 | 30 | /** 31 | * 获得一个字符串的MD5值 32 | * 33 | * @param input 输入的字符串 34 | * @return 输入字符串的MD5值 35 | * 36 | */ 37 | public static String md5(String input) { 38 | if (input == null) 39 | return null; 40 | 41 | try { 42 | // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”) 43 | MessageDigest messageDigest = MessageDigest.getInstance("MD5"); 44 | // 输入的字符串转换成字节数组 45 | byte[] inputByteArray = input.getBytes("utf-8"); 46 | // inputByteArray是输入字符串转换得到的字节数组 47 | messageDigest.update(inputByteArray); 48 | // 转换并返回结果,也是字节数组,包含16个元素 49 | byte[] resultByteArray = messageDigest.digest(); 50 | // 字符数组转换成字符串返回 51 | return byteArrayToHex(resultByteArray); 52 | } catch (NoSuchAlgorithmException e) { 53 | Logger.getLogger(MD5.class.getName()).log(Level.SEVERE, null, e); 54 | return null; 55 | } catch (UnsupportedEncodingException ex) { 56 | Logger.getLogger(MD5.class.getName()).log(Level.SEVERE, null, ex); 57 | return null; 58 | } 59 | } 60 | 61 | /** 62 | * 获取文件的MD5值 63 | * 64 | * @param file 65 | * @return 66 | */ 67 | public static String md5(File file) { 68 | try { 69 | if (!file.isFile()) { 70 | System.err.println("文件" + file.getAbsolutePath() + "不存在或者不是文件"); 71 | return null; 72 | } 73 | 74 | FileInputStream in = new FileInputStream(file); 75 | 76 | String result = md5(in); 77 | 78 | in.close(); 79 | 80 | return result; 81 | 82 | } catch (FileNotFoundException e) { 83 | e.printStackTrace(); 84 | } catch (IOException e) { 85 | e.printStackTrace(); 86 | } 87 | 88 | return null; 89 | } 90 | 91 | public static String md5(InputStream in) { 92 | 93 | try { 94 | MessageDigest messagedigest = MessageDigest.getInstance("MD5"); 95 | 96 | byte[] buffer = new byte[1024]; 97 | int read = 0; 98 | while ((read = in.read(buffer)) != -1) { 99 | messagedigest.update(buffer, 0, read); 100 | } 101 | 102 | in.close(); 103 | 104 | String result = byteArrayToHex(messagedigest.digest()); 105 | 106 | return result; 107 | } catch (NoSuchAlgorithmException e) { 108 | e.printStackTrace(); 109 | } catch (FileNotFoundException e) { 110 | e.printStackTrace(); 111 | } catch (IOException e) { 112 | e.printStackTrace(); 113 | } 114 | 115 | return null; 116 | } 117 | 118 | private static String byteArrayToHex(byte[] byteArray) { 119 | // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方)) 120 | char[] resultCharArray = new char[byteArray.length * 2]; 121 | // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去 122 | int index = 0; 123 | for (byte b : byteArray) { 124 | resultCharArray[index++] = hexDigits[b >>> 4 & 0xf]; 125 | resultCharArray[index++] = hexDigits[b & 0xf]; 126 | } 127 | 128 | // 字符数组组合成字符串返回 129 | return new String(resultCharArray); 130 | 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /src/translation/view/JTA.java: -------------------------------------------------------------------------------- 1 | package translation.view; 2 | 3 | import java.awt.AWTException; 4 | import java.awt.Robot; 5 | import java.awt.datatransfer.Clipboard; 6 | import java.awt.datatransfer.DataFlavor; 7 | import java.awt.datatransfer.Transferable; 8 | import java.awt.event.*; 9 | import java.util.logging.Level; 10 | import java.util.logging.Logger; 11 | 12 | import javax.swing.JFrame; 13 | import javax.swing.JMenuItem; 14 | import javax.swing.JPopupMenu; 15 | import javax.swing.JScrollPane; 16 | import javax.swing.JTextArea; 17 | import javax.swing.KeyStroke; 18 | import javax.swing.UIManager; 19 | 20 | /** 21 | * Java右键菜单实现文本组件内容的的复制、粘贴、剪切功能 22 | * 23 | * @author 五斗米 <如转载请保留作者和出处> @blog http://blog.csdn.net/mq612 24 | */ 25 | public class JTA extends JTextArea implements MouseListener { 26 | 27 | private static final long serialVersionUID = -2308615404205560110L; 28 | private JPopupMenu pop = null; // 弹出菜单 29 | private JMenuItem copy = null, paste = null, cut = null, delete = null; // 四个功能菜单 30 | 31 | public JTA() { 32 | super(); 33 | init(); 34 | } 35 | 36 | private void init() { 37 | this.addMouseListener(this); 38 | pop = new JPopupMenu(); 39 | pop.add(copy = new JMenuItem("复制")); 40 | pop.add(paste = new JMenuItem("粘贴")); 41 | pop.add(cut = new JMenuItem("剪切")); 42 | pop.add(delete = new JMenuItem("删除")); 43 | copy.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK)); 44 | paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK)); 45 | cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK)); 46 | delete.setAccelerator(KeyStroke.getKeyStroke("DELETE")); 47 | copy.addActionListener(new ActionListener() { 48 | 49 | public void actionPerformed(ActionEvent e) { 50 | action(e); 51 | } 52 | }); 53 | paste.addActionListener(new ActionListener() { 54 | 55 | public void actionPerformed(ActionEvent e) { 56 | action(e); 57 | } 58 | }); 59 | cut.addActionListener(new ActionListener() { 60 | 61 | public void actionPerformed(ActionEvent e) { 62 | action(e); 63 | } 64 | }); 65 | delete.addActionListener(new ActionListener() { 66 | 67 | public void actionPerformed(ActionEvent e) { 68 | try { 69 | Robot robot = new Robot(); 70 | robot.keyPress(KeyEvent.VK_DELETE); 71 | robot.keyRelease(KeyEvent.VK_DELETE); 72 | } catch (AWTException ex) { 73 | Logger.getLogger(JTA.class.getName()).log(Level.SEVERE, null, ex); 74 | } 75 | } 76 | }); 77 | this.add(pop); 78 | } 79 | 80 | /** 81 | * 菜单动作 82 | * 83 | * @param e 84 | */ 85 | public void action(ActionEvent e) { 86 | String str = e.getActionCommand(); 87 | if (str.equals(copy.getText())) { // 复制 88 | this.copy(); 89 | } else if (str.equals(paste.getText())) { // 粘贴 90 | this.paste(); 91 | } else if (str.equals(cut.getText())) { // 剪切 92 | this.cut(); 93 | } 94 | } 95 | 96 | public JPopupMenu getPop() { 97 | return pop; 98 | } 99 | 100 | public void setPop(JPopupMenu pop) { 101 | this.pop = pop; 102 | } 103 | 104 | /** 105 | * 剪切板中是否有文本数据可供粘贴 106 | * 107 | * @return true为有文本数据 108 | */ 109 | public boolean isClipboardString() { 110 | boolean b = false; 111 | Clipboard clipboard = this.getToolkit().getSystemClipboard(); 112 | Transferable content = clipboard.getContents(this); 113 | try { 114 | if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) { 115 | b = true; 116 | } 117 | } catch (Exception e) { 118 | } 119 | return b; 120 | } 121 | 122 | /** 123 | * 文本组件中是否具备复制的条件 124 | * 125 | * @return true为具备 126 | */ 127 | public boolean isCanCopy() { 128 | boolean b = false; 129 | int start = this.getSelectionStart(); 130 | int end = this.getSelectionEnd(); 131 | if (start != end) { 132 | b = true; 133 | } 134 | return b; 135 | } 136 | 137 | public void mouseClicked(MouseEvent e) { 138 | } 139 | 140 | public void mouseEntered(MouseEvent e) { 141 | } 142 | 143 | public void mouseExited(MouseEvent e) { 144 | } 145 | 146 | public void mousePressed(MouseEvent e) { 147 | if (e.getButton() == MouseEvent.BUTTON3) { 148 | copy.setEnabled(isCanCopy()); 149 | paste.setEnabled(isClipboardString()); 150 | cut.setEnabled(isCanCopy()); 151 | pop.show(this, e.getX(), e.getY()); 152 | } 153 | } 154 | 155 | public void mouseReleased(MouseEvent e) { 156 | } 157 | } 158 | --------------------------------------------------------------------------------