├── .DS_Store ├── .gitignore ├── BreakWords.jar ├── LICENSE ├── README.md ├── img └── img.jpg ├── resources └── META-INF │ └── plugin.xml └── src └── com └── elyria └── breakwords ├── BreakWords.kt └── YouDaoApi.java /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jungletian/BreakWords/2b1e1d497d33419d98d9d4a4f459517b455fe843/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /out 3 | *.iml 4 | -------------------------------------------------------------------------------- /BreakWords.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jungletian/BreakWords/2b1e1d497d33419d98d9d4a4f459517b455fe843/BreakWords.jar -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BreakWords 2 | An idea plugin to help you break down the barrier of language that written in Kotlin 3 | 4 | ### Aim 5 | 6 | Sometimes we deep into the wtf source code, new words are the barrier to continue reading. 7 | So this born to help you remember and break the words. 8 | 9 | ### Install 10 | 11 | Download the [BreakWords.jar](/BreakWords.jar) -> open your IDE (Idea, Android Studio, WebStorm...) -> press `cmd + ,` -> Plugins -> Install plugin from disk -> choose BreakWords.jar -> restart. 12 | 13 | ### Usage 14 | 15 | Select the word and press `alt + q` the prompt pop like following: 16 | 17 | 18 | 19 | ### Feature 20 | 21 | * auto recognize the language of the word in your env. (英 -> 汉 & 汉 -> 英) 22 | * only one `BreakWords.kt` file, simplify code, clean code. 23 | * hope your feedback and communicate with each other. 24 | * welcome scan the QR code or contact [jungletian](tjsummery@gmail.com) for feedback. 25 | 26 | 27 | 28 | ### Thanks 29 | 30 | [有道翻译API](http://ai.youdao.com/docs/api.s) 31 | 32 | [码个蛋](https://github.com/BolexLiu/ReciteWords) 33 | -------------------------------------------------------------------------------- /img/img.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jungletian/BreakWords/2b1e1d497d33419d98d9d4a4f459517b455fe843/img/img.jpg -------------------------------------------------------------------------------- /resources/META-INF/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | com.elyria.plugin.breakwords 3 | BreakWords 4 | 1.0 5 | BreakWords 6 | 7 | This is a idea plugin for helping you break down the barrier of language.
9 | openSource 10 | select your word and press alt + Q 11 | 12 | ]]>
13 | 14 | 17 | 18 | 19 | 20 | 21 | 22 | 24 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 36 | 37 | 38 | 39 | 40 | 41 |
-------------------------------------------------------------------------------- /src/com/elyria/breakwords/BreakWords.kt: -------------------------------------------------------------------------------- 1 | package com.elyria.breakwords 2 | 3 | import com.elyria.breakwords.YouDaoApi.ERROR_CODE_SUCCESS 4 | import com.google.gson.Gson 5 | import com.google.gson.annotations.SerializedName 6 | import com.intellij.openapi.actionSystem.AnAction 7 | import com.intellij.openapi.actionSystem.AnActionEvent 8 | import com.intellij.openapi.actionSystem.PlatformDataKeys 9 | import com.intellij.openapi.application.ApplicationManager 10 | import com.intellij.openapi.editor.Editor 11 | import com.intellij.openapi.ui.popup.Balloon 12 | import com.intellij.openapi.ui.popup.JBPopupFactory 13 | import com.intellij.openapi.util.TextRange 14 | import com.intellij.ui.JBColor 15 | import org.apache.http.NameValuePair 16 | import org.apache.http.client.entity.UrlEncodedFormEntity 17 | import org.apache.http.client.methods.HttpPost 18 | import org.apache.http.impl.client.HttpClients 19 | import org.apache.http.message.BasicNameValuePair 20 | import org.apache.http.util.EntityUtils 21 | import org.apache.http.util.TextUtils 22 | import java.awt.Color 23 | import java.util.* 24 | 25 | class BreakWords : AnAction() { 26 | 27 | private val URL = "https://openapi.youdao.com/api" 28 | // 应用信息 http://ai.youdao.com/docs/api.s 29 | private val APP_KEY = "2a9903a060d0511a" 30 | private val APP_SECRET = "hHcIipkvVFSeUBr1KnyeGFbHPbAknQQn" 31 | // 参数名 32 | private val PARAMS_QUERY = "q" 33 | private val PARAMS_APPKEY = "appKey" 34 | private val PARAMS_FROM = "from" 35 | private val PARAMS_TO = "to" 36 | private val PARAMS_SALT = "salt" 37 | private val PARAMS_SIGN = "sign" 38 | 39 | private val DEFAULT_VALUE_FROM = "auto" 40 | private val DEFAULT_VALUE_TO = "auto" 41 | 42 | private var latestClickTime: Long = 0 43 | private var mEditor: Editor? = null 44 | 45 | override fun actionPerformed(event: AnActionEvent?) { 46 | if (!isFastClick(1000)) { 47 | event?.let { 48 | var query: String? = null 49 | mEditor = it.getData(PlatformDataKeys.EDITOR) 50 | mEditor?.let { 51 | if (TextUtils.isBlank(it.selectionModel.selectedText)) { 52 | query = getCurrentWords(mEditor!!) 53 | } else { 54 | query = it.selectionModel.selectedText 55 | } 56 | } 57 | requestTranslate(strip(addBlanks(query!!))) 58 | } 59 | } 60 | } 61 | 62 | fun requestTranslate(query: String) { 63 | Thread(Runnable { 64 | kotlin.run { 65 | val httpPost = HttpPost(URL) 66 | httpPost.entity = UrlEncodedFormEntity(createTranslateParams(query), "UTF-8") 67 | val client = HttpClients.createDefault() 68 | val response = client.execute(httpPost) 69 | val status = response.statusLine.statusCode 70 | if (status in 200..299) { 71 | val entity = response.entity 72 | val json = EntityUtils.toString(entity, "UTF-8") 73 | val translation = Gson().fromJson(json, Translation::class.java) 74 | translation.errorMessage = when (translation.errorCode) { 75 | YouDaoApi.ERROR_CODE_PARAMS -> "缺少必填的参数,出现这个情况还可能是et的值和实际加密方式不对应" 76 | YouDaoApi.ERROR_CODE_UNSUPPORT_LANGUAGE -> "不支持的语言类型" 77 | YouDaoApi.ERROR_CODE_TOLONG -> "翻译文本过长" 78 | YouDaoApi.ERROR_CODE_UNSUPPORT_API -> "不支持的API类型" 79 | YouDaoApi.ERROR_CODE_UNSUPPORT_SIGN -> "不支持的签名类型" 80 | YouDaoApi.ERROR_CODE_UNSUPPORT_RESPONSE -> "不支持的响应类型" 81 | YouDaoApi.ERROR_CODE_UNSUPPORT_ENCRYPT -> "不支持的传输加密类型" 82 | YouDaoApi.ERROR_CODE_APPKEY_INVALID -> "appKey无效,注册账号" 83 | YouDaoApi.ERROR_CODE_BATCHLOG_ERROR -> "batchLog格式不正确" 84 | YouDaoApi.ERROR_CODE_NO_SERVICE -> "无相关服务的有效实例" 85 | YouDaoApi.ERROR_CODE_ACCOUNT_INVALID -> "开发者账号无效,可能是账号为欠费状态" 86 | YouDaoApi.ERROR_CODE_DEENCRYPT_ERROR -> "解密失败,可能为DES,BASE64,URLDecode的错误" 87 | YouDaoApi.ERROR_CODE_SIGN_FAILURE -> "签名检验失败" 88 | YouDaoApi.ERROR_CODE_UNSUPPORT_IP -> "访问IP地址不在可访问IP列表" 89 | YouDaoApi.ERROR_CODE_QUERY_ERROR -> "辞典查询失败" 90 | YouDaoApi.ERROR_CODE_TRANSLATE_ERROR -> "翻译查询失败" 91 | YouDaoApi.ERROR_CODE_SERVER_ERROR -> "服务端的其它异常" 92 | YouDaoApi.ERROR_CODE_ACCOUNT_ERROR -> "账户已经欠费停" 93 | ERROR_CODE_SUCCESS -> "成功" 94 | else -> "出现未知错误" 95 | } 96 | showPopupBalloon(translation.toString()) 97 | } else { 98 | showPopupBalloon(response.statusLine.reasonPhrase) 99 | } 100 | } 101 | }).start() 102 | } 103 | 104 | private fun getCurrentWords(editor: Editor): String? { 105 | val document = editor.document 106 | val caretModel = editor.caretModel 107 | val caretOffset = caretModel.offset 108 | val lineNum = document.getLineNumber(caretOffset) 109 | val lineStartOffset = document.getLineStartOffset(lineNum) 110 | val lineEndOffset = document.getLineEndOffset(lineNum) 111 | val lineContent = document.getText(TextRange(lineStartOffset, lineEndOffset)) 112 | val chars = lineContent.toCharArray() 113 | var end = 0 114 | val cursor = caretOffset - lineStartOffset 115 | 116 | if (!Character.isLetter(chars[cursor])) { 117 | return null 118 | } 119 | 120 | val start = (cursor downTo 0) 121 | .firstOrNull { !Character.isLetter(chars[it]) } 122 | ?.let { it + 1 } 123 | ?: 0 124 | 125 | var lastLetter = 0 126 | for (ptr in cursor until lineEndOffset - lineStartOffset) { 127 | lastLetter = ptr 128 | if (!Character.isLetter(chars[ptr])) { 129 | end = ptr 130 | break 131 | } 132 | } 133 | if (end == 0) { 134 | end = lastLetter + 1 135 | } 136 | 137 | return String(chars, start, end - start) 138 | } 139 | 140 | private fun addBlanks(str: String): String { 141 | val temp = str.replace("_".toRegex(), " ") 142 | if (temp == temp.toUpperCase()) { 143 | return temp 144 | } 145 | return temp.replace("([A-Z]+)".toRegex(), " $0") 146 | } 147 | 148 | private fun strip(str: String): String { 149 | return str.replace("/\\*+".toRegex(), "") 150 | .replace("\\*+/".toRegex(), "") 151 | .replace("\\*".toRegex(), "") 152 | .replace("//+".toRegex(), "") 153 | .replace("\r\n".toRegex(), " ") 154 | .replace("\\s+".toRegex(), " ") 155 | } 156 | 157 | private fun isFastClick(timeMillis: Long): Boolean { 158 | val time = System.currentTimeMillis() 159 | val timeD = time - latestClickTime 160 | if (timeD in 1..(timeMillis - 1)) { 161 | return true 162 | } 163 | latestClickTime = time 164 | return false 165 | } 166 | 167 | private fun showPopupBalloon(result: String) { 168 | ApplicationManager.getApplication().invokeLater { 169 | val factory = JBPopupFactory.getInstance() 170 | factory.createHtmlTextBalloonBuilder(result, null, JBColor(Color(186, 238, 186), Color(73, 117, 73)), null) 171 | .setFadeoutTime(5000) 172 | .createBalloon() 173 | .show(factory.guessBestPopupLocation(mEditor!!), Balloon.Position.below) 174 | } 175 | } 176 | 177 | private fun createTranslateParams(query: String): List { 178 | val salt = System.currentTimeMillis().toString() 179 | val params = ArrayList() 180 | params.add(BasicNameValuePair(PARAMS_QUERY, query)) 181 | params.add(BasicNameValuePair(PARAMS_FROM, DEFAULT_VALUE_FROM)) 182 | params.add(BasicNameValuePair(PARAMS_TO, DEFAULT_VALUE_TO)) 183 | params.add(BasicNameValuePair(PARAMS_SIGN, YouDaoApi.md5(APP_KEY + query + salt + APP_SECRET))) 184 | params.add(BasicNameValuePair(PARAMS_SALT, salt)) 185 | params.add(BasicNameValuePair(PARAMS_APPKEY, APP_KEY)) 186 | return params 187 | } 188 | } 189 | 190 | data class TranslationBasic( 191 | @SerializedName("us-phonetic") val phonetic_us: String?, 192 | @SerializedName("uk-phonetic") val phonetic_uk: String?, 193 | @SerializedName("phonetic") val phonetic: String?, 194 | @SerializedName("explains") val explains: Array? 195 | ) { 196 | override fun equals(other: Any?): Boolean { 197 | if (this === other) return true 198 | if (javaClass != other?.javaClass) return false 199 | 200 | other as TranslationBasic 201 | 202 | if (phonetic_us != other.phonetic_us) return false 203 | if (phonetic_uk != other.phonetic_uk) return false 204 | if (phonetic != other.phonetic) return false 205 | if (!Arrays.equals(explains, other.explains)) return false 206 | 207 | return true 208 | } 209 | 210 | override fun hashCode(): Int { 211 | var result = phonetic_us?.hashCode() ?: 0 212 | result = 31 * result + (phonetic_uk?.hashCode() ?: 0) 213 | result = 31 * result + (phonetic?.hashCode() ?: 0) 214 | result = 31 * result + (explains?.let { Arrays.hashCode(it) } ?: 0) 215 | return result 216 | } 217 | } 218 | 219 | data class WebTranslation( 220 | @SerializedName("key") private val key: String?, 221 | @SerializedName("value") private val values: Array? 222 | ) { 223 | override fun toString(): String { 224 | return key + ": " + values?.joinToString(" , ") 225 | } 226 | 227 | override fun equals(other: Any?): Boolean { 228 | if (this === other) return true 229 | if (javaClass != other?.javaClass) return false 230 | 231 | other as WebTranslation 232 | 233 | if (key != other.key) return false 234 | if (!Arrays.equals(values, other.values)) return false 235 | 236 | return true 237 | } 238 | 239 | override fun hashCode(): Int { 240 | var result = key?.hashCode() ?: 0 241 | result = 31 * result + (values?.let { Arrays.hashCode(it) } ?: 0) 242 | return result 243 | } 244 | } 245 | 246 | data class Translation( 247 | @SerializedName("translation") private val translations: Array?, 248 | @SerializedName("errorCode") val errorCode: Int, 249 | @SerializedName("query") private val query: String? = "翻译", 250 | @SerializedName("basic") private val basic: TranslationBasic?, 251 | @SerializedName("web") private val webTranslations: Array?, 252 | var errorMessage: String? 253 | ) { 254 | override fun toString(): String { 255 | if (errorCode != ERROR_CODE_SUCCESS) { 256 | return "错误代码: $errorCode \n $errorMessage" 257 | } else { 258 | val translationTop = "

${query ?: "翻译"}: ${translations?.joinToString(", ")}

" 259 | var phoneticUs: String? = "" 260 | var phoneticUk: String? = "" 261 | var phonetic: String? = "" 262 | basic?.phonetic_us?.let { 263 | phoneticUs = """美式: [$it]""" 264 | } 265 | basic?.phonetic_uk?.let { 266 | phoneticUk = """英式: [$it]""" 267 | } 268 | if (TextUtils.isBlank(phoneticUs) && TextUtils.isBlank(phoneticUk)) { 269 | basic?.phonetic?.let { 270 | phonetic = """发音: [$it]""" + "${System.lineSeparator()}
" 271 | } 272 | } else { 273 | phonetic = "$phoneticUs ; $phoneticUk ${System.lineSeparator()}
" 274 | } 275 | var translationBody: String? = "" 276 | basic?.explains?.let { 277 | translationBody = it.joinToString(separator = System.lineSeparator(), prefix = "", postfix = "") + "${System.lineSeparator()}
" 278 | } 279 | var translationWeb: String? = "" 280 | webTranslations?.let { 281 | translationWeb = "网络释义:
${it.joinToString(System.lineSeparator())}
" 282 | } 283 | return "$translationTop $phonetic $translationBody $translationWeb" 284 | } 285 | } 286 | 287 | override fun equals(other: Any?): Boolean { 288 | if (this === other) return true 289 | if (javaClass != other?.javaClass) return false 290 | 291 | other as Translation 292 | 293 | if (!Arrays.equals(translations, other.translations)) return false 294 | if (errorCode != other.errorCode) return false 295 | if (query != other.query) return false 296 | if (basic != other.basic) return false 297 | if (!Arrays.equals(webTranslations, other.webTranslations)) return false 298 | if (errorMessage != other.errorMessage) return false 299 | 300 | return true 301 | } 302 | 303 | override fun hashCode(): Int { 304 | var result = translations?.let { Arrays.hashCode(it) } ?: 0 305 | result = 31 * result + errorCode 306 | result = 31 * result + (query?.hashCode() ?: 0) 307 | result = 31 * result + (basic?.hashCode() ?: 0) 308 | result = 31 * result + (webTranslations?.let { Arrays.hashCode(it) } ?: 0) 309 | result = 31 * result + (errorMessage?.hashCode() ?: 0) 310 | return result 311 | } 312 | } 313 | -------------------------------------------------------------------------------- /src/com/elyria/breakwords/YouDaoApi.java: -------------------------------------------------------------------------------- 1 | package com.elyria.breakwords; 2 | 3 | import java.io.IOException; 4 | import java.io.UnsupportedEncodingException; 5 | import java.net.URLEncoder; 6 | import java.security.MessageDigest; 7 | import java.security.NoSuchAlgorithmException; 8 | import java.util.ArrayList; 9 | import java.util.Iterator; 10 | import java.util.List; 11 | import java.util.Map; 12 | import org.apache.http.HttpEntity; 13 | import org.apache.http.NameValuePair; 14 | import org.apache.http.client.entity.UrlEncodedFormEntity; 15 | import org.apache.http.client.methods.CloseableHttpResponse; 16 | import org.apache.http.client.methods.HttpPost; 17 | import org.apache.http.impl.client.CloseableHttpClient; 18 | import org.apache.http.impl.client.HttpClients; 19 | import org.apache.http.message.BasicNameValuePair; 20 | import org.apache.http.util.EntityUtils; 21 | 22 | public class YouDaoApi { 23 | 24 | public final static int ERROR_CODE_SUCCESS = 0; 25 | public final static int ERROR_CODE_PARAMS = 101; // 缺少必填的参数,出现这个情况还可能是et的值和实际加密方式不对应 26 | public final static int ERROR_CODE_UNSUPPORT_LANGUAGE = 102; // 不支持的语言类型 27 | public final static int ERROR_CODE_TOLONG = 103; // 翻译文本过长 28 | public final static int ERROR_CODE_UNSUPPORT_API = 104; // 不支持的API类型 29 | public final static int ERROR_CODE_UNSUPPORT_SIGN = 105; // 不支持的签名类型 30 | public final static int ERROR_CODE_UNSUPPORT_RESPONSE = 106; // 不支持的响应类型 31 | public final static int ERROR_CODE_UNSUPPORT_ENCRYPT = 107; // 不支持的传输加密类型 32 | public final static int ERROR_CODE_APPKEY_INVALID = 108; // appKey无效,注册账号,登录后台创建应用和实例并完成绑定, 可获得应用ID和密钥等信息,其中应用ID就是appKey( 注意不是应用密钥) 33 | public final static int ERROR_CODE_BATCHLOG_ERROR = 109; // batchLog格式不正确 34 | public final static int ERROR_CODE_NO_SERVICE = 110; // 无相关服务的有效实例 35 | public final static int ERROR_CODE_ACCOUNT_INVALID = 111; // 开发者账号无效,可能是账号为欠费状态 36 | public final static int ERROR_CODE_DEENCRYPT_ERROR = 201; // 解密失败,可能为DES,BASE64,URLDecode的错误 37 | public final static int ERROR_CODE_SIGN_FAILURE = 202; // 签名检验失败 38 | public final static int ERROR_CODE_UNSUPPORT_IP = 203; // 访问IP地址不在可访问IP列表 39 | public final static int ERROR_CODE_QUERY_ERROR = 301; // 辞典查询失败 40 | public final static int ERROR_CODE_TRANSLATE_ERROR = 302; // 翻译查询失败 41 | public final static int ERROR_CODE_SERVER_ERROR = 303; // 服务端的其它异常 42 | public final static int ERROR_CODE_ACCOUNT_ERROR = 401; // 账户已经欠费停 43 | 44 | public static void main(String[] args) throws Exception { 45 | BreakWords breakWords = new BreakWords(); 46 | breakWords.requestTranslate("context"); 47 | } 48 | 49 | public static String requestForHttp(String url, Map requestParams) 50 | throws Exception { 51 | String result = null; 52 | CloseableHttpClient httpClient = HttpClients.createDefault(); 53 | /**HttpPost*/ 54 | HttpPost httpPost = new HttpPost(url); 55 | List params = new ArrayList(); 56 | Iterator> it = requestParams.entrySet().iterator(); 57 | while (it.hasNext()) { 58 | Map.Entry en = it.next(); 59 | String key = en.getKey(); 60 | String value = en.getValue(); 61 | if (value != null) { 62 | params.add(new BasicNameValuePair(key, value)); 63 | } 64 | } 65 | httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); 66 | /**HttpResponse*/ 67 | System.out.println(params); 68 | CloseableHttpResponse httpResponse = httpClient.execute(httpPost); 69 | try { 70 | HttpEntity httpEntity = httpResponse.getEntity(); 71 | result = EntityUtils.toString(httpEntity, "utf-8"); 72 | EntityUtils.consume(httpEntity); 73 | } finally { 74 | try { 75 | if (httpResponse != null) { 76 | httpResponse.close(); 77 | } 78 | } catch (IOException e) { 79 | e.printStackTrace(); 80 | } 81 | } 82 | return result; 83 | } 84 | 85 | /** 86 | * 生成32位MD5摘要 87 | */ 88 | public static String md5(String string) { 89 | if (string == null) { 90 | return null; 91 | } 92 | char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 93 | 'A', 'B', 'C', 'D', 'E', 'F'}; 94 | try { 95 | byte[] btInput = string.getBytes("utf-8"); 96 | /** 获得MD5摘要算法的 MessageDigest 对象 */ 97 | MessageDigest mdInst = MessageDigest.getInstance("MD5"); 98 | /** 使用指定的字节更新摘要 */ 99 | mdInst.update(btInput); 100 | /** 获得密文 */ 101 | byte[] md = mdInst.digest(); 102 | /** 把密文转换成十六进制的字符串形式 */ 103 | int j = md.length; 104 | char str[] = new char[j * 2]; 105 | int k = 0; 106 | for (byte byte0 : md) { 107 | str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 108 | str[k++] = hexDigits[byte0 & 0xf]; 109 | } 110 | return new String(str); 111 | } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { 112 | return null; 113 | } 114 | } 115 | 116 | /** 117 | * 根据api地址和参数生成请求URL 118 | */ 119 | public static String getUrlWithQueryString(String url, Map params) { 120 | if (params == null) { 121 | return url; 122 | } 123 | StringBuilder builder = new StringBuilder(url); 124 | if (url.contains("?")) { 125 | builder.append("&"); 126 | } else { 127 | builder.append("?"); 128 | } 129 | 130 | int i = 0; 131 | for (String key : params.keySet()) { 132 | String value = params.get(key); 133 | if (value == null) { // 过滤空的key 134 | continue; 135 | } 136 | if (i != 0) { 137 | builder.append('&'); 138 | } 139 | builder.append(key); 140 | builder.append('='); 141 | builder.append(encode(value)); 142 | 143 | i++; 144 | } 145 | return builder.toString(); 146 | } 147 | 148 | /** 149 | * 进行URL编码 150 | */ 151 | public static String encode(String input) { 152 | if (input == null) { 153 | return ""; 154 | } 155 | try { 156 | return URLEncoder.encode(input, "utf-8"); 157 | } catch (UnsupportedEncodingException e) { 158 | e.printStackTrace(); 159 | } 160 | return input; 161 | } 162 | } 163 | --------------------------------------------------------------------------------