├── .gitignore ├── LICENSE ├── Log └── UpdateLog ├── bin └── .gitignore └── src └── com └── ericsoft ├── bmob ├── bson │ ├── BSON.java │ ├── BSONException.java │ ├── BSONObject.java │ └── BSONString.java └── restapi │ ├── Bmob.java │ └── BmobE.java └── demo └── TestDemo.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | .classpath 14 | .project 15 | 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /Log/UpdateLog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bmob/bmob-java-sdk/ffbfa9e5af5897aa68453af32dfbdf40fa9b385c/Log/UpdateLog -------------------------------------------------------------------------------- /bin/.gitignore: -------------------------------------------------------------------------------- 1 | /com 2 | -------------------------------------------------------------------------------- /src/com/ericsoft/bmob/bson/BSON.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Bmob移动后端云服务BmobJSON工具类 4 | * 5 | * 提供简单的BSON对象生成和解析成对象。 6 | * 使用方法:参考TestDemo 7 | * 8 | * @author 金鹰 9 | * @version V1.2.1 10 | * @since 2015-07-07 11 | * 12 | */ 13 | package com.ericsoft.bmob.bson; 14 | 15 | import java.text.ParseException; 16 | import java.text.SimpleDateFormat; 17 | import java.util.Date; 18 | 19 | public class BSON { 20 | public static final String TAG_MSG = "__MSG_"; 21 | public static final String TAG_KEY = "__KEY_"; 22 | public static final String TAG_VALUE = "__VALUE_"; 23 | public static final String TAG_TYPE = "__TYPE_"; 24 | public static final String TAG_BMOB_TYPE = "__type"; 25 | 26 | public static final String MSG_BSON = "String is BSONString."; 27 | public static final String MSG_BSON_EMPTY = "String is empty BSON."; 28 | public static final String MSG_BSON_ARRAY = "String is BSONArrayString."; 29 | public static final String MSG_ERROR_EMPTY = "String is empty."; 30 | public static final String MSG_ERROR_NOTBSON = "String is not BSONString."; 31 | public static final String MSG_ERROR_UNKNOW = "Unknow Error."; 32 | public static final String MSG_ERROR_NULL_KEY = "Null key."; 33 | 34 | public static final String CHAR_POINT = "."; 35 | public static final String CHAR_COMMA = ","; 36 | public static final String CHAR_QUOTES = "\""; 37 | public static final String CHAR_RISK = ":"; 38 | public static final String CHAR_LEFT_BIG = "{"; 39 | public static final String CHAR_RIGHT_BIG = "}"; 40 | public static final String CHAR_LEFT_MID = "["; 41 | public static final String CHAR_RIGHT_MID = "]"; 42 | public static final String CHAR_NULL = ""; 43 | 44 | public static final int TYPE_UNKNOW = -1; 45 | public static final int TYPE_INTEGER = 0; 46 | public static final int TYPE_LONG = 1; 47 | public static final int TYPE_FLOAT = 2; 48 | public static final int TYPE_DOUBLE = 3; 49 | public static final int TYPE_BOOLEAN = 4; 50 | public static final int TYPE_STRING = 5; 51 | public static final int TYPE_ARRAY = 6; 52 | public static final int TYPE_OBJECT = 7; 53 | public static final int TYPE_BSON = 8; 54 | public static final int TYPE_DATE = 9; 55 | public static final int TYPE_BSON_ARRAY = 10; 56 | 57 | public static void Log(Object obj){ 58 | if(obj == null){ 59 | Log("Object is null."); 60 | }else{ 61 | Log(obj.toString()); 62 | } 63 | } 64 | public static void Log(String str){ 65 | System.out.println(CHAR_LEFT_MID + Long2Time(0) + CHAR_RIGHT_MID + "-Log: "+ str); 66 | } 67 | public static void Warn(Object obj){ 68 | if(obj == null){ 69 | Warn("Object is null."); 70 | }else{ 71 | Warn(obj.toString()); 72 | } 73 | } 74 | public static void Warn(String str){ 75 | System.err.println(CHAR_LEFT_MID + Long2Time(0) + CHAR_RIGHT_MID + "-Warn: "+ str); 76 | } 77 | 78 | public static String Long2Time(long time) { 79 | if(time == 0){ 80 | time = new Date().getTime(); 81 | } 82 | SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 83 | String nowTime = formatter.format(time); 84 | return nowTime; 85 | } 86 | public static String Long2DateTime(long time) { 87 | SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 88 | String nowTime = formatter.format(time); 89 | return nowTime; 90 | } 91 | public static long DateTime2Long(String date) { 92 | long time = 0; 93 | SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat( 94 | "yyyy-MM-dd HH:mm:ss"); 95 | try { 96 | time = mSimpleDateFormat.parse(date).getTime(); 97 | } catch (ParseException e) { 98 | e.printStackTrace(); 99 | } 100 | return time; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/com/ericsoft/bmob/bson/BSONException.java: -------------------------------------------------------------------------------- 1 | package com.ericsoft.bmob.bson; 2 | 3 | public class BSONException extends RuntimeException { 4 | private static final long serialVersionUID = -19276996871164684L; 5 | 6 | public BSONException() { 7 | } 8 | 9 | public BSONException(String msg) { 10 | super(msg, null); 11 | } 12 | 13 | public BSONException(String msg, Throwable cause) { 14 | super(msg, cause); 15 | } 16 | 17 | public BSONException(Throwable cause) { 18 | super(cause == null ? null : cause.toString(), cause); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/com/ericsoft/bmob/bson/BSONObject.java: -------------------------------------------------------------------------------- 1 | package com.ericsoft.bmob.bson; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.HashMap; 6 | import java.util.Iterator; 7 | import java.util.LinkedHashMap; 8 | import java.util.Map; 9 | import java.util.Map.Entry; 10 | 11 | public class BSONObject { 12 | 13 | protected Map bson ; 14 | 15 | public BSONObject(){ 16 | this.bson = new LinkedHashMap(); 17 | } 18 | 19 | public BSONObject(String BSONString) throws BSONException{ 20 | this.bson = new LinkedHashMap(); 21 | BSONString bs = new BSONString(); 22 | LinkedHashMap map = bs.getBSON(BSONString); 23 | String msg = (String)map.get(BSON.TAG_MSG); 24 | if(msg.equals(BSON.MSG_BSON)){ 25 | String tag = (String) map.get(BSON.TAG_KEY); 26 | String value = (String) map.get(BSON.TAG_VALUE); 27 | LinkedHashMap hm = bs.getValue(value); 28 | bson.put(tag, hm.get(BSON.TAG_VALUE)); 29 | }else if(msg.equals(BSON.MSG_BSON_ARRAY)){ 30 | map.remove(BSON.TAG_MSG); 31 | Iterator> iter = map.entrySet().iterator(); 32 | while (iter.hasNext()) { 33 | Entry entry = (Entry) iter.next(); 34 | bson.put(entry.getKey(), entry.getValue()); 35 | } 36 | }else if(msg.equals(BSON.MSG_BSON_EMPTY)){ 37 | BSON.Warn(BSON.MSG_BSON_EMPTY); 38 | }else if(msg.equals(BSON.MSG_ERROR_NOTBSON)){ 39 | throw new BSONException(msg); 40 | }else if(msg.equals(BSON.MSG_ERROR_EMPTY)){ 41 | throw new BSONException(msg); 42 | }else{ 43 | throw new BSONException(BSON.MSG_ERROR_UNKNOW); 44 | } 45 | } 46 | 47 | public BSONObject(LinkedHashMap map){ 48 | this.bson = new LinkedHashMap(); 49 | bson.putAll(map); 50 | } 51 | 52 | public BSONObject(HashMap map){ 53 | this.bson = new LinkedHashMap(); 54 | bson.putAll(map); 55 | } 56 | 57 | public BSONObject(BSONObject bsonObj){ 58 | this.bson = new LinkedHashMap(); 59 | bson.putAll(bsonObj.getMap()); 60 | } 61 | 62 | public BSONObject(Date date){ 63 | this.bson = new LinkedHashMap(); 64 | bson.put("__type","Date"); 65 | bson.put("iso",BSON.Long2DateTime(date.getTime())); 66 | } 67 | 68 | public BSONObject copy(BSONObject bsonObj){ 69 | this.bson.clear(); 70 | bson.putAll(bsonObj.getMap()); 71 | return this; 72 | } 73 | 74 | public BSONObject add(BSONObject bsonObj){ 75 | bson.putAll(bsonObj.getMap()); 76 | return this; 77 | } 78 | 79 | public BSONObject put(String key, boolean value){ 80 | if(key == null){ 81 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 82 | } 83 | bson.put(key, value); 84 | return this; 85 | } 86 | public BSONObject put(String key, String value){ 87 | if(key == null){ 88 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 89 | } 90 | bson.put(key, value); 91 | return this; 92 | } 93 | public BSONObject put(String key, double value){ 94 | if(key == null){ 95 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 96 | } 97 | bson.put(key, value); 98 | return this; 99 | } 100 | public BSONObject put(String key, float value){ 101 | if(key == null){ 102 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 103 | } 104 | bson.put(key, value); 105 | return this; 106 | } 107 | public BSONObject put(String key, long value){ 108 | if(key == null){ 109 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 110 | } 111 | bson.put(key, value); 112 | return this; 113 | } 114 | public BSONObject put(String key, int value){ 115 | if(key == null){ 116 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 117 | } 118 | bson.put(key, value); 119 | return this; 120 | } 121 | public BSONObject put(String key, Date value){ 122 | if(key == null){ 123 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 124 | } 125 | if(value == null){ 126 | bson.remove(key); 127 | } 128 | bson.put(key, value); 129 | return this; 130 | } 131 | public BSONObject put(String key, BSONObject value){ 132 | if(key == null){ 133 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 134 | } 135 | if(value == null){ 136 | bson.remove(key); 137 | } 138 | bson.put(key, value); 139 | return this; 140 | } 141 | public BSONObject put(String key, Object value){ 142 | if(key == null){ 143 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 144 | } 145 | if(value == null){ 146 | bson.remove(key); 147 | } 148 | bson.put(key, value); 149 | return this; 150 | } 151 | public BSONObject putDate(String key, Date value){ 152 | if(key == null){ 153 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 154 | } 155 | if(value == null){ 156 | bson.remove(key); 157 | } 158 | bson.put(key, value); 159 | return this; 160 | } 161 | public BSONObject putDate(String key, long value){ 162 | if(key == null){ 163 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 164 | } 165 | bson.put(key, new Date(value)); 166 | return this; 167 | } 168 | 169 | public BSONObject remove(String key){ 170 | if(key == null){ 171 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 172 | } 173 | bson.remove(key); 174 | return this; 175 | } 176 | 177 | public Object get(String key){ 178 | Object obj = bson.get(key); 179 | if(obj == null){ 180 | throw new BSONException(BSON.MSG_ERROR_NULL_KEY); 181 | } 182 | return obj; 183 | } 184 | 185 | public Boolean getBoolean(String key){ 186 | Object obj = get(key); 187 | if(obj instanceof Boolean){ 188 | return (Boolean)obj; 189 | }else{ 190 | throw new BSONException("Not Boolean Type."); 191 | } 192 | } 193 | public String getString(String key){ 194 | Object obj = get(key); 195 | if(obj instanceof String){ 196 | return (String)obj; 197 | }else{ 198 | throw new BSONException("Not String Type."); 199 | } 200 | } 201 | public Long getLong(String key){ 202 | Object obj = get(key); 203 | if(obj instanceof Long || obj instanceof Integer){ 204 | if(obj instanceof Integer){ 205 | return new Long((Integer) obj); 206 | } 207 | return (Long)obj; 208 | }else{ 209 | throw new BSONException("Not Long Type."); 210 | } 211 | } 212 | public Double getDouble(String key){ 213 | Object obj = get(key); 214 | if(obj instanceof Double || obj instanceof Float){ 215 | return (Double)obj; 216 | }else{ 217 | throw new BSONException("Not Double Type."); 218 | } 219 | } 220 | public Float getFloat(String key){ 221 | Object obj = get(key); 222 | if(obj instanceof Float){ 223 | return (Float)obj; 224 | }else{ 225 | throw new BSONException("Not Float Type."); 226 | } 227 | } 228 | public int getInt(String key){ 229 | Object obj = get(key); 230 | if(obj instanceof Integer){ 231 | return (Integer)obj; 232 | }else{ 233 | throw new BSONException("Not int Type."); 234 | } 235 | } 236 | public Date getDate(String key){ 237 | Object obj = get(key); 238 | if(obj instanceof Date){ 239 | return (Date)obj; 240 | }else if(obj instanceof BSONObject){ 241 | BSONObject bsonObj = (BSONObject)obj; 242 | if(bsonObj.getString(BSON.TAG_BMOB_TYPE).equals("Date")){ 243 | String date = bsonObj.getString("iso"); 244 | return new Date(BSON.DateTime2Long(date)); 245 | }else{ 246 | throw new BSONException("Not Bmob Date Type."); 247 | } 248 | }else{ 249 | throw new BSONException("Not Bmob Date Type."); 250 | } 251 | } 252 | public BSONObject getBSONObject(String key){ 253 | Object obj = get(key); 254 | if(obj instanceof BSONObject){ 255 | return (BSONObject)obj; 256 | }else{ 257 | throw new BSONException("Not BSONObject Type."); 258 | } 259 | } 260 | public BSONObject[] getBSONArray(String key){ 261 | Object obj = get(key); 262 | if(obj instanceof Object[]){ 263 | try{ 264 | Object[] objArray = (Object[])obj; 265 | 266 | BSONObject[] bsonArray = new BSONObject[objArray.length]; 267 | int id = 0; 268 | for(Object o : objArray){ 269 | if(o instanceof String && o.equals(BSON.CHAR_NULL)){ 270 | bsonArray[id++] = new BSONObject(); 271 | }else{ 272 | bsonArray[id++] = (BSONObject)o; 273 | } 274 | } 275 | return bsonArray; 276 | }catch(BSONException be){ 277 | throw new BSONException("Not BSONArray Type."); 278 | } 279 | }else{ 280 | throw new BSONException("Not BSONArray Type."); 281 | } 282 | } 283 | 284 | public int length(){ 285 | return bson.size(); 286 | } 287 | 288 | public boolean isEmpty(){ 289 | return length() == 0; 290 | } 291 | 292 | public String toString(){ 293 | if(isEmpty()){ 294 | return BSON.CHAR_LEFT_BIG + BSON.CHAR_RIGHT_BIG; 295 | }else{ 296 | StringBuffer result = new StringBuffer(); 297 | Iterator> iter = bson.entrySet().iterator(); 298 | while (iter.hasNext()) { 299 | Entry entry = (Entry) iter.next(); 300 | result.insert(0,entryToString(entry)); 301 | if(iter.hasNext()){ 302 | result.insert(0,BSON.CHAR_COMMA); 303 | } 304 | } 305 | return result.append(BSON.CHAR_RIGHT_BIG).insert(0, BSON.CHAR_LEFT_BIG).toString(); 306 | } 307 | } 308 | 309 | public Map getMap(){ 310 | return this.bson; 311 | } 312 | 313 | public boolean containsKey(String key){ 314 | return this.bson.containsKey(key); 315 | } 316 | 317 | protected String entryToString(Entry entry){ 318 | StringBuffer result = new StringBuffer(); 319 | result.insert(0, BSON.CHAR_QUOTES + entry.getKey() + BSON.CHAR_QUOTES + BSON.CHAR_RISK); 320 | result.append(objectToString(entry.getValue())); 321 | return result.toString(); 322 | } 323 | 324 | protected String objectToString(Object val){ 325 | StringBuffer result = new StringBuffer(); 326 | if(val instanceof Integer 327 | || val instanceof Long 328 | || val instanceof Float 329 | || val instanceof Double 330 | || val instanceof Boolean) { 331 | result.append(val); 332 | }else if(val instanceof String) { 333 | if(!val.equals(BSON.CHAR_NULL)){ 334 | result.append(BSON.CHAR_QUOTES + val + BSON.CHAR_QUOTES); 335 | }else{ 336 | result.append(val); 337 | } 338 | }else if(val instanceof Byte) { 339 | result.append(val); 340 | }else if(val instanceof Date) { 341 | //BmobDate 格式 342 | result.append("{\"__type\":\"Date\",\"iso\":\""+BSON.Long2DateTime(((Date) val).getTime())+"\"}"); 343 | }else if(val instanceof BSONObject){ 344 | result.append(val.toString()); 345 | }else if(val instanceof Object[]){ 346 | Object[] value = (Object[])val; 347 | result.append(BSON.CHAR_LEFT_MID); 348 | int size = value.length; 349 | for(int i=0; i){ 393 | ArrayList value = (ArrayList)val; 394 | result.append(BSON.CHAR_LEFT_MID); 395 | int size = value.size(); 396 | for(int i=0; i getBSON(String str){ 13 | LinkedHashMap map = new LinkedHashMap(); 14 | map.put(BSON.TAG_MSG, BSON.MSG_ERROR_EMPTY); 15 | if(str.isEmpty() || str == null) return map; 16 | map.put(BSON.TAG_MSG, BSON.MSG_ERROR_NOTBSON); 17 | if(str.length()<2) return map; 18 | str = str.trim(); 19 | if(!(str.startsWith(BSON.CHAR_LEFT_BIG) && str.endsWith(BSON.CHAR_RIGHT_BIG))) return map; 20 | if(str.equals(BSON.CHAR_LEFT_BIG+BSON.CHAR_RIGHT_BIG)){ 21 | map.put(BSON.TAG_MSG, BSON.MSG_BSON_EMPTY); 22 | return map; 23 | } 24 | str = str.substring(1, str.length()-1); 25 | List bsons = checkArraySize(str); 26 | if(bsons.size()==1){ 27 | String[] strs = formatOneBSON(bsons.get(0)); 28 | if(strs == null) return map; 29 | map.put(BSON.TAG_MSG, BSON.MSG_BSON); 30 | map.put(BSON.TAG_KEY, strs[0]); 31 | map.put(BSON.TAG_VALUE, strs[1]); 32 | return map; 33 | }else{ 34 | for(int i=0; i checkArraySize(String str){ 47 | List array = new ArrayList(); 48 | String subStr; 49 | int flag = 0; 50 | int start = 0; 51 | boolean add = true; 52 | for(int i=0; i getValue(String str){ 101 | LinkedHashMap map = new LinkedHashMap(); 102 | int type; 103 | str = str.trim(); 104 | if(str.startsWith(BSON.CHAR_LEFT_MID) && str.endsWith(BSON.CHAR_RIGHT_MID)){ 105 | //Object[] 106 | type = BSON.TYPE_ARRAY; 107 | List array = checkArraySize(str.substring(1,str.length()-1)); 108 | Object[] objArray = new Object[array.size()]; 109 | for(int i=0; i tMap = getValue(array.get(i)); 111 | objArray[i] = tMap.get(BSON.TAG_VALUE); 112 | } 113 | map.put(BSON.TAG_VALUE, objArray); 114 | }else if(str.startsWith(BSON.CHAR_QUOTES) && str.endsWith(BSON.CHAR_QUOTES)){ 115 | type = BSON.TYPE_STRING; 116 | map.put(BSON.TAG_VALUE, str.substring(1, str.length()-1)); 117 | }else if(str.startsWith(BSON.CHAR_LEFT_BIG) && str.endsWith(BSON.CHAR_RIGHT_BIG)){ 118 | //BSON or JSON or Date or Object 119 | map = analyseObject(str, map); 120 | type = (Integer) map.get(BSON.TAG_TYPE); 121 | map.put(BSON.TAG_VALUE, map.get(BSON.TAG_VALUE)); 122 | }else if(str.toLowerCase(Locale.getDefault()).equals("true") || str.toLowerCase(Locale.getDefault()).equals("false") ){ 123 | type = BSON.TYPE_BOOLEAN; 124 | map.put(BSON.TAG_VALUE, Boolean.valueOf(str)); 125 | }else if(str.contains(BSON.CHAR_POINT) || str.contains("e") || str.contains("E")){ 126 | try{ 127 | if(Float.valueOf(str).isInfinite()){ 128 | type = BSON.TYPE_DOUBLE; 129 | map.put(BSON.TAG_VALUE, Double.valueOf(str)); 130 | }else{ 131 | type = BSON.TYPE_FLOAT; 132 | map.put(BSON.TAG_VALUE, Float.valueOf(str)); 133 | } 134 | }catch(Exception e){ 135 | type = BSON.TYPE_UNKNOW; 136 | map.put(BSON.TAG_VALUE, str); 137 | } 138 | 139 | }else if(true){ 140 | try{ 141 | Integer.valueOf(str); 142 | type = BSON.TYPE_INTEGER; 143 | map.put(BSON.TAG_VALUE, Integer.valueOf(str)); 144 | }catch(Exception e){ 145 | try{ 146 | type = BSON.TYPE_LONG; 147 | map.put(BSON.TAG_VALUE, Long.valueOf(str)); 148 | }catch(Exception ee){ 149 | type = BSON.TYPE_UNKNOW; 150 | map.put(BSON.TAG_VALUE, str); 151 | } 152 | } 153 | } 154 | 155 | map.put(BSON.TAG_TYPE, type); 156 | return map; 157 | } 158 | 159 | private LinkedHashMap analyseObject(String str, LinkedHashMap map){ 160 | LinkedHashMap oMap = getBSON(str); 161 | String msg = (String) oMap.get(BSON.TAG_MSG); 162 | if(msg.equals(BSON.MSG_BSON_ARRAY)){ 163 | map.put(BSON.TAG_TYPE, BSON.TYPE_BSON_ARRAY); 164 | BSONObject bson = new BSONObject(); 165 | oMap.remove(BSON.TAG_MSG); 166 | Iterator> iter = oMap.entrySet().iterator(); 167 | while (iter.hasNext()) { 168 | Entry entry = (Entry) iter.next(); 169 | bson.put(entry.getKey(), entry.getValue()); 170 | } 171 | map.put(BSON.TAG_VALUE, bson); 172 | map.put(BSON.TAG_TYPE, BSON.TYPE_BSON_ARRAY); 173 | 174 | return map; 175 | }else if(msg.equals(BSON.MSG_BSON_EMPTY)){ 176 | map.put(BSON.TAG_TYPE, BSON.TYPE_BSON); 177 | map.put(BSON.TAG_VALUE, new BSONObject()); 178 | return map; 179 | } 180 | String tag = (String) oMap.get(BSON.TAG_KEY); 181 | if(!tag.equals(BSON.MSG_ERROR_EMPTY) && !tag.equals(BSON.MSG_ERROR_NOTBSON)){ 182 | map.put(BSON.TAG_TYPE, BSON.TYPE_BSON); 183 | BSONObject bson = new BSONObject(); 184 | bson.put(tag, getValue((String)oMap.get(BSON.TAG_VALUE)).get(BSON.TAG_VALUE)); 185 | map.put(BSON.TAG_VALUE, bson); 186 | }else{ 187 | map.put(BSON.TAG_TYPE, BSON.TYPE_OBJECT); 188 | map.put(BSON.TAG_VALUE, str); 189 | } 190 | return map; 191 | } 192 | 193 | } 194 | -------------------------------------------------------------------------------- /src/com/ericsoft/bmob/restapi/Bmob.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Bmob移动后端云服务RestAPI工具类 4 | * 5 | * 提供简单的RestAPI增删改查工具,可直接对表、云函数、支付订单、消息推送进行操作。 6 | * 使用方法:先初始化initBmob,后调用其他方法即可。 7 | * 具体使用方法及传参格式详见Bmob官网RestAPI开发文档。 8 | * http://docs.bmob.cn/restful/developdoc/index.html?menukey=develop_doc&key=develop_restful 9 | * 10 | * @author 金鹰 11 | * @version V1.3.1 12 | * @since 2015-07-07 13 | * 14 | */ 15 | package com.ericsoft.bmob.restapi; 16 | 17 | import java.io.BufferedReader; 18 | import java.io.ByteArrayOutputStream; 19 | import java.io.File; 20 | import java.io.FileInputStream; 21 | import java.io.FileNotFoundException; 22 | import java.io.FileReader; 23 | import java.io.IOException; 24 | import java.io.InputStreamReader; 25 | import java.io.OutputStream; 26 | import java.io.OutputStreamWriter; 27 | import java.io.PrintWriter; 28 | import java.io.UnsupportedEncodingException; 29 | import java.net.HttpURLConnection; 30 | import java.net.URL; 31 | import java.net.URLEncoder; 32 | import java.security.SecureRandom; 33 | import java.security.cert.CertificateException; 34 | import java.security.cert.X509Certificate; 35 | import java.util.concurrent.TimeoutException; 36 | 37 | import javax.net.ssl.HttpsURLConnection; 38 | import javax.net.ssl.SSLContext; 39 | import javax.net.ssl.TrustManager; 40 | import javax.net.ssl.X509TrustManager; 41 | 42 | import com.ericsoft.bmob.bson.BSONObject; 43 | 44 | public class Bmob { 45 | 46 | private static boolean IS_INIT = false; 47 | private static int TIME_OUT = 10000; 48 | 49 | private static String STRING_EMPTY = ""; 50 | private static String APP_ID = STRING_EMPTY; 51 | private static String REST_API_KEY = STRING_EMPTY; 52 | private static String MASTER_KEY = STRING_EMPTY; 53 | 54 | private static final String BMOB_APP_ID_TAG = "X-Bmob-Application-Id"; 55 | private static final String BMOB_REST_KEY_TAG = "X-Bmob-REST-API-Key"; 56 | private static final String BMOB_MASTER_KEY_TAG = "X-Bmob-Master-Key"; 57 | private static final String CONTENT_TYPE_TAG = "Content-Type"; 58 | private static final String CONTENT_TYPE_JSON = "application/json"; 59 | 60 | private static final String METHOD_GET = "GET"; 61 | private static final String METHOD_POST = "POST"; 62 | private static final String METHOD_PUT = "PUT"; 63 | private static final String METHOD_DELETE = "DELETE"; 64 | 65 | private static final String UTF8 = "UTF-8"; 66 | private static final String CHAR_RISK = ":"; 67 | 68 | public static final String MSG_NOT_FOUND = "Not Found"; 69 | public static final String MSG_FILE_NOT_FOUND = "file Not Found"; 70 | public static final String MSG_ERROR = "Error"; 71 | public static final String MSG_UNREGISTERED = "Unregistered"; 72 | /** 73 | * 是否初始化Bmob 74 | * @return 初始化结果 75 | */ 76 | public static boolean isInit(){ 77 | return IS_INIT; 78 | } 79 | 80 | /** 81 | * 初始化Bmob 82 | * @param appId 填写 Application ID 83 | * @param apiKey 填写 REST API Key 84 | * @return 注册结果 85 | */ 86 | public static boolean initBmob(String appId, String apiKey){ 87 | return initBmob(appId, apiKey, 10000); 88 | } 89 | 90 | /** 91 | * 初始化Bmob 92 | * @param appId 填写 Application ID 93 | * @param apiKey 填写 REST API Key 94 | * @param timeout 设置超时(1000~20000ms) 95 | * @return 注册结果 96 | */ 97 | public static boolean initBmob(String appId, String apiKey, int timeout){ 98 | APP_ID = appId; 99 | REST_API_KEY = apiKey; 100 | if(!APP_ID.equals(STRING_EMPTY) && !REST_API_KEY.equals(STRING_EMPTY)){ 101 | IS_INIT = true; 102 | } 103 | if(timeout > 1000 && timeout < 20000){ 104 | TIME_OUT = timeout; 105 | } 106 | try{ 107 | SSLContext sc = SSLContext.getInstance("SSL"); 108 | sc.init(null, trustAllCerts, new SecureRandom()); 109 | HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 110 | }catch(Exception e){ 111 | IS_INIT = false; 112 | } 113 | return isInit(); 114 | } 115 | 116 | /** 117 | * 初始化Bmob Master权限 118 | * @param masterKey 填写 Master Key 119 | */ 120 | public static void initMaster(String masterKey){ 121 | MASTER_KEY = masterKey; 122 | } 123 | 124 | /** 125 | * 查询表全部记录(最多仅查询1000条记录) 126 | * @param tableName 表名 127 | * @return JSON格式结果 128 | */ 129 | public static String findAll(String tableName){ 130 | return find(tableName,STRING_EMPTY); 131 | } 132 | 133 | /** 134 | * 条件查询表全部记录(最多仅查询1000条记录) 135 | * @param tableName 表名 136 | * @param where 条件JOSN格式 137 | * @return JSON格式结果 138 | */ 139 | public static String findAll(String tableName, String where){ 140 | return find(tableName, where, STRING_EMPTY); 141 | } 142 | 143 | /** 144 | * 查询表单条记录 145 | * @param tableName 表名 146 | * @param objectId objectId 147 | * @return JSON格式结果 148 | */ 149 | public static String findOne(String tableName, String objectId){ 150 | String result = STRING_EMPTY; 151 | if(isInit()){ 152 | HttpURLConnection conn = null; 153 | String mURL = "https://api2.bmob.cn/1/classes/"+tableName+"/"+objectId; 154 | try { 155 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_GET); 156 | conn.connect(); 157 | result = getResultFromConnection(conn); 158 | conn.disconnect(); 159 | } catch (FileNotFoundException e){ 160 | result = MSG_NOT_FOUND + CHAR_RISK + "(findOne)" + e.getMessage(); 161 | } catch (Exception e) { 162 | result = MSG_ERROR + CHAR_RISK + "(findOne)" + e.getMessage(); 163 | } 164 | }else{ 165 | result = MSG_UNREGISTERED; 166 | } 167 | return result; 168 | } 169 | 170 | 171 | /** 172 | * 查询表限定数量记录 173 | * @param tableName 表名 174 | * @param limit 查询记录数(1~1000) 175 | * @return JSON格式结果 176 | */ 177 | public static String find(String tableName, int limit){ 178 | return find(tableName, "{}", 0,limit, STRING_EMPTY); 179 | } 180 | 181 | /** 182 | * 条件查询表限定数量记录 183 | * @param tableName 表名 184 | * @param where 条件JOSN格式 185 | * @param limit 查询记录数(1~1000) 186 | * @return JSON格式结果 187 | */ 188 | public static String find(String tableName, String where, int limit){ 189 | return find(tableName, where, 0,limit, STRING_EMPTY); 190 | } 191 | 192 | /** 193 | * 条件查询表限定数量记录,返回指定列 194 | * @param tableName 表名 195 | * @param keys 返回列 (例:score,name) 196 | * @param where 条件JOSN格式 197 | * @param limit 查询记录数(1~1000) 198 | * @return JSON格式结果 199 | */ 200 | public static String findColumns(String tableName, String keys, String where, int limit){ 201 | return findColumns(tableName, keys, where, 0,limit, STRING_EMPTY); 202 | } 203 | 204 | /** 205 | * 查询表区间记录 206 | * @param tableName 表名 207 | * @param skip 跳过记录数 208 | * @param limit 查询记录数(1~1000) 209 | * @return JSON格式结果 210 | */ 211 | public static String find(String tableName, int skip, int limit){ 212 | return find(tableName, "{}", skip, limit, STRING_EMPTY); 213 | } 214 | 215 | /** 216 | * 条件查询表区间记录 217 | * @param tableName 表名 218 | * @param where 条件JOSN格式 219 | * @param skip 跳过记录数 220 | * @param limit 查询记录数(1~1000) 221 | * @return JSON格式结果 222 | */ 223 | public static String find(String tableName, String where, int skip, int limit){ 224 | return find(tableName, where, skip, limit, STRING_EMPTY); 225 | } 226 | 227 | 228 | /** 229 | * 条件查询表区间记录,返回指定列 230 | * @param tableName 表名 231 | * @param keys 返回列 (例:score,name) 232 | * @param where 条件JOSN格式 233 | * @param skip 跳过记录数 234 | * @param limit 查询记录数(1~1000) 235 | * @return JSON格式结果 236 | */ 237 | public static String findColumns(String tableName, String keys, String where, int skip, int limit){ 238 | return findColumns(tableName, keys, where, skip, limit, STRING_EMPTY); 239 | } 240 | 241 | /** 242 | * 排序查询表记录 243 | * @param tableName 表名 244 | * @param order 排序字段(例:score,-name) 245 | * @return JSON格式结果 246 | */ 247 | public static String find(String tableName, String order){ 248 | return find(tableName, "{}", 0, 1000, order); 249 | } 250 | 251 | /** 252 | * 条件排序查询表记录 253 | * @param tableName 表名 254 | * @param where 条件JOSN格式 255 | * @param order 排序字段(例:score,-name) 256 | * @return JSON格式结果 257 | */ 258 | public static String find(String tableName, String where, String order){ 259 | return find(tableName, where, 0, 1000, order); 260 | } 261 | 262 | /** 263 | * 条件排序查询表记录,返回指定列 264 | * @param tableName 表名 265 | * @param keys 返回列 (例:score,name) 266 | * @param where 条件JOSN格式 267 | * @param order 排序字段(例:score,-name) 268 | * @return JSON格式结果 269 | */ 270 | public static String findColumns(String tableName, String keys, String where, String order){ 271 | return findColumns(tableName, keys, where, 0, 1000, order); 272 | } 273 | 274 | /** 275 | * 排序查询表限定数量记录 276 | * @param tableName 表名 277 | * @param limit 查询记录数(1~1000) 278 | * @param order 排序字段(例:score,-name) 279 | * @return JSON格式结果 280 | */ 281 | public static String find(String tableName, int limit, String order){ 282 | return find(tableName, "{}", 0, limit, order); 283 | } 284 | 285 | /** 286 | * 条件排序查询表限定数量记录 287 | * @param tableName 表名 288 | * @param where 条件JOSN格式 289 | * @param limit 查询记录数(1~1000) 290 | * @param order 排序字段(例:score,-name) 291 | * @return JSON格式结果 292 | */ 293 | public static String find(String tableName, String where, int limit, String order){ 294 | return find(tableName, where, 0, limit, order); 295 | } 296 | 297 | /** 298 | * 条件排序查询表限定数量记录,返回指定列 299 | * @param tableName 表名 300 | * @param keys 返回列 (例:score,name) 301 | * @param where 条件JOSN格式 302 | * @param limit 查询记录数(1~1000) 303 | * @param order 排序字段(例:score,-name) 304 | * @return JSON格式结果 305 | */ 306 | public static String findColumns(String tableName, String keys, String where, int limit, String order){ 307 | return findColumns(tableName, keys, where, 0, limit, order); 308 | } 309 | 310 | /** 311 | * 条件排序查询表区间记录 312 | * @param tableName 表名 313 | * @param where 条件JOSN格式 314 | * @param skip 跳过记录数 315 | * @param limit 查询记录数(1~1000) 316 | * @param order 排序字段(例:score,-name) 317 | * @return JSON格式结果 318 | */ 319 | public static String find(String tableName, String where, int skip, int limit, String order){ 320 | return findColumns(tableName, STRING_EMPTY, where, skip, limit, order); 321 | } 322 | 323 | 324 | /** 325 | * 条件排序查询表区间记录,返回指定列 326 | * @param tableName 表名 327 | * @param keys 返回列 (例:score,name) 328 | * @param where 条件JOSN格式 329 | * @param skip 跳过记录数 330 | * @param limit 查询记录数(1~1000) 331 | * @param order 排序字段(例:score,-name) 332 | * @return JSON格式结果 333 | */ 334 | public static String findColumns(String tableName, String keys, String where, int skip, int limit, String order){ 335 | String result = STRING_EMPTY; 336 | if(isInit()){ 337 | HttpURLConnection conn = null; 338 | skip = skip < 0 ? 0 : skip; 339 | limit = limit < 0 ? 0 : limit; 340 | limit = limit > 1000 ? 1000 : limit; 341 | where = where.equals(STRING_EMPTY) ? "{}" : where; 342 | String mURL = "https://api2.bmob.cn/1/classes/"+tableName+"?where="+urlEncoder(where)+"&limit="+limit + "&skip="+skip + "&order=" + order + "&keys=" + keys; 343 | 344 | try { 345 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_GET); 346 | conn.connect(); 347 | result = getResultFromConnection(conn); 348 | conn.disconnect(); 349 | } catch (FileNotFoundException e){ 350 | result = MSG_NOT_FOUND + CHAR_RISK + "(findColumns)" + e.getMessage(); 351 | } catch (Exception e) { 352 | result = MSG_ERROR + CHAR_RISK + "(findColumns)" + e.getMessage(); 353 | } 354 | }else{ 355 | result = MSG_UNREGISTERED; 356 | } 357 | return result; 358 | } 359 | 360 | /** 361 | * BQL查询表记录 362 | * @param BQL SQL语句。例如:select * from Student where name=\"张三\" limit 0,10 order by name 363 | * @return JSON格式结果 364 | */ 365 | public static String findBQL(String BQL){ 366 | return findBQL(BQL, STRING_EMPTY); 367 | } 368 | 369 | /** 370 | * BQL查询表记录 371 | * @param BQL SQL语句。例如:select * from Student where name=? limit ?,? order by name 372 | * @param value 参数对应SQL中?以,为分隔符。例如"\"张三\",0,10" 373 | * @return JSON格式结果 374 | */ 375 | public static String findBQL(String BQL, String value){ 376 | String result = STRING_EMPTY; 377 | if(isInit()){ 378 | HttpURLConnection conn = null; 379 | BQL = urlEncoder(BQL) + "&values=[" + urlEncoder(value)+"]"; 380 | String mURL = "https://api2.bmob.cn/1/cloudQuery?bql="+BQL ; 381 | 382 | try { 383 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_GET); 384 | conn.connect(); 385 | result = getResultFromConnection(conn); 386 | conn.disconnect(); 387 | } catch (FileNotFoundException e){ 388 | result = MSG_NOT_FOUND + CHAR_RISK + "(findBQL)" + e.getMessage(); 389 | } catch (Exception e) { 390 | result = MSG_ERROR + CHAR_RISK + "(findBQL)" + e.getMessage(); 391 | } 392 | }else{ 393 | result = MSG_UNREGISTERED; 394 | } 395 | return result; 396 | } 397 | 398 | 399 | /** 400 | * 获取服务器时间 401 | * @return 402 | */ 403 | public static String getServerTime(){ 404 | String result = STRING_EMPTY; 405 | if(isInit()){ 406 | HttpURLConnection conn = null; 407 | String mURL = "https://api2.bmob.cn/1/timestamp/"; 408 | try { 409 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_GET); 410 | conn.connect(); 411 | result = getResultFromConnection(conn); 412 | conn.disconnect(); 413 | } catch (FileNotFoundException e){ 414 | result = MSG_NOT_FOUND + CHAR_RISK + "(getServerTime)" + e.getMessage(); 415 | }catch (Exception e) { 416 | result = MSG_ERROR + CHAR_RISK + "(getServerTime)" + e.getMessage(); 417 | } 418 | }else{ 419 | result = MSG_UNREGISTERED; 420 | } 421 | return result; 422 | } 423 | 424 | /** 425 | * 查询表记录数 426 | * @param tableName 表名 427 | * @return 统计值 428 | */ 429 | public static int count(String tableName){ 430 | return count(tableName, "{}"); 431 | } 432 | 433 | /** 434 | * 条件查询记录数 435 | * @param tableName 表名 436 | * @param where 查询条件(JSON格式) 437 | * @return 统计值 438 | */ 439 | public static int count(String tableName, String where){ 440 | String result = STRING_EMPTY; 441 | if(isInit()){ 442 | HttpURLConnection conn = null; 443 | String mURL = "https://api2.bmob.cn/1/classes/"+tableName+"?where="+urlEncoder(where)+"&count=1&limit=0"; 444 | try { 445 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_GET); 446 | conn.connect(); 447 | result = getResultFromConnection(conn); 448 | conn.disconnect(); 449 | } catch (FileNotFoundException e){ 450 | result = MSG_NOT_FOUND + CHAR_RISK + "(count)" + e.getMessage(); 451 | System.err.println("Warn: "+ result); 452 | } catch (Exception e) { 453 | result = MSG_ERROR + CHAR_RISK + "(count)" + e.getMessage(); 454 | System.err.println("Warn: "+ result); 455 | } 456 | }else{ 457 | result = MSG_UNREGISTERED; 458 | System.err.println("Warn: "+ result); 459 | } 460 | int count = 0; 461 | if(result.contains(MSG_NOT_FOUND) || result.contains(MSG_ERROR) || result.equals(MSG_UNREGISTERED)){ 462 | return count; 463 | }else{ 464 | if(result.contains("count")){ 465 | count = Integer.valueOf(result.replaceAll("[^0-9]",STRING_EMPTY)); 466 | } 467 | } 468 | return count; 469 | } 470 | 471 | /** 472 | * 修改记录 473 | * @param tableName 表名 474 | * @param objectId objectId 475 | * @param paramContent JSON格式参数 476 | * @return JSON格式结果 477 | */ 478 | public static String update(String tableName, String objectId, String paramContent){ 479 | String result = STRING_EMPTY; 480 | if(isInit()){ 481 | HttpURLConnection conn = null; 482 | String mURL = "https://api2.bmob.cn/1/classes/"+tableName+"/"+objectId; 483 | try { 484 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_PUT); 485 | conn.setDoOutput(true); 486 | conn.connect(); 487 | printWriter(conn, paramContent); 488 | result = getResultFromConnection(conn); 489 | conn.disconnect(); 490 | } catch (FileNotFoundException e){ 491 | result = MSG_NOT_FOUND + CHAR_RISK + "(update)" + e.getMessage(); 492 | } catch (Exception e) { 493 | result = MSG_ERROR + CHAR_RISK + "(update)" + e.getMessage(); 494 | } 495 | }else{ 496 | result = MSG_UNREGISTERED; 497 | } 498 | return result; 499 | } 500 | 501 | /** 502 | * 插入记录 503 | * @param tableName 表名 504 | * @param paramContent JSON格式参数 505 | * @return JSON格式结果 506 | */ 507 | public static String insert(String tableName, String paramContent){ 508 | String result = STRING_EMPTY; 509 | if(isInit()){ 510 | HttpURLConnection conn = null; 511 | String mURL = "https://api2.bmob.cn/1/classes/"+tableName; 512 | try { 513 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_POST); 514 | conn.setDoOutput(true); 515 | conn.connect(); 516 | printWriter(conn, paramContent); 517 | result = getResultFromConnection(conn); 518 | conn.disconnect(); 519 | } catch (FileNotFoundException e){ 520 | result = MSG_NOT_FOUND + CHAR_RISK + "(insert)" + e.getMessage(); 521 | } catch (Exception e) { 522 | result = MSG_ERROR + CHAR_RISK + "(insert)" + e.getMessage(); 523 | } 524 | }else{ 525 | result = MSG_UNREGISTERED; 526 | } 527 | return result; 528 | } 529 | 530 | 531 | /** 532 | * 删除记录 533 | * @param tableName 表名 534 | * @param objectId objectId 535 | * @return JSON格式结果 536 | */ 537 | public static String delete(String tableName, String objectId){ 538 | String result = STRING_EMPTY; 539 | if(isInit()){ 540 | HttpURLConnection conn = null; 541 | String mURL = "https://api2.bmob.cn/1/classes/"+tableName+"/"+objectId; 542 | try { 543 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_DELETE); 544 | conn.connect(); 545 | result = getResultFromConnection(conn); 546 | conn.disconnect(); 547 | } catch (FileNotFoundException e){ 548 | result = MSG_NOT_FOUND + CHAR_RISK + "(delete)" + e.getMessage(); 549 | } catch (Exception e) { 550 | result = MSG_ERROR + CHAR_RISK + "(delete)" + e.getMessage(); 551 | } 552 | }else{ 553 | result = MSG_UNREGISTERED; 554 | } 555 | return result; 556 | } 557 | 558 | /** 559 | * 查询支付订单 560 | * @param payId 交易编号 561 | * @return JSON格式结果 562 | */ 563 | public static String findPayOrder(String payId){ 564 | String result = STRING_EMPTY; 565 | if(isInit()){ 566 | HttpURLConnection conn = null; 567 | String mURL = "https://api2.bmob.cn/1/pay/"+payId; 568 | try { 569 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_GET); 570 | conn.connect(); 571 | result = getResultFromConnection(conn); 572 | conn.disconnect(); 573 | } catch (FileNotFoundException e){ 574 | result = MSG_NOT_FOUND + CHAR_RISK + "(findPayOrder)" + e.getMessage(); 575 | } catch (Exception e) { 576 | result = MSG_ERROR + CHAR_RISK + "(findPayOrder)" + e.getMessage(); 577 | } 578 | }else{ 579 | result = MSG_UNREGISTERED; 580 | } 581 | return result; 582 | } 583 | 584 | 585 | 586 | /** 587 | * 推送消息 588 | * @param JSON格式 data 589 | * 详细使用方法参照 http://docs.bmob.cn/restful/developdoc/index.html?menukey=develop_doc&key=develop_restful#index_消息推送简介 590 | * @return JSON格式结果 591 | */ 592 | public static String pushMsg(String data){ 593 | String result = STRING_EMPTY; 594 | if(isInit()){ 595 | HttpURLConnection conn = null; 596 | String mURL = "https://api2.bmob.cn/1/push"; 597 | try { 598 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_POST); 599 | conn.setDoOutput(true); 600 | conn.connect(); 601 | printWriter(conn, data); 602 | result = getResultFromConnection(conn); 603 | conn.disconnect(); 604 | } catch (FileNotFoundException e){ 605 | result = MSG_NOT_FOUND + CHAR_RISK + "(pushMsg)" + e.getMessage(); 606 | } catch (Exception e) { 607 | result = MSG_ERROR + CHAR_RISK + "(pushMsg)" + e.getMessage(); 608 | } 609 | }else{ 610 | result = MSG_UNREGISTERED; 611 | } 612 | return result; 613 | } 614 | 615 | 616 | /** 617 | * 调用云端代码 618 | * @param funcName 云函数名 619 | * @param paramContent JSON格式参数 620 | * @return JSON格式结果 621 | */ 622 | public static String callFunction(String funcName, String paramContent){ 623 | String result = STRING_EMPTY; 624 | if(isInit()){ 625 | HttpURLConnection conn = null; 626 | String mURL = "https://api2.bmob.cn/1/functions/"+funcName; 627 | try { 628 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_POST); 629 | conn.setDoOutput(true); 630 | conn.connect(); 631 | printWriter(conn, paramContent); 632 | result = getResultFromConnection(conn); 633 | conn.disconnect(); 634 | } catch (FileNotFoundException e){ 635 | result = MSG_NOT_FOUND + CHAR_RISK + "(callFunction)" + e.getMessage(); 636 | } catch (Exception e) { 637 | result = MSG_ERROR + CHAR_RISK + "(callFunction)" + e.getMessage(); 638 | } 639 | }else{ 640 | result = MSG_UNREGISTERED; 641 | } 642 | return result; 643 | } 644 | 645 | /** 646 | * 发送短信 647 | * @param mobileNum 电话号码 648 | * @param content 短信内容 649 | * @return JSON格式结果 650 | */ 651 | public static String requestSms(String mobileNum, String content){ 652 | String result = STRING_EMPTY; 653 | if(isInit()){ 654 | HttpURLConnection conn = null; 655 | String mURL = "https://api2.bmob.cn/1/requestSms"; 656 | try { 657 | BSONObject bson = new BSONObject(); 658 | bson.put("mobilePhoneNumber", mobileNum); 659 | bson.put("content", mobileNum); 660 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_POST); 661 | conn.setDoOutput(true); 662 | conn.connect(); 663 | printWriter(conn, bson.toString()); 664 | result = getResultFromConnection(conn); 665 | conn.disconnect(); 666 | } catch (FileNotFoundException e){ 667 | result = MSG_NOT_FOUND + CHAR_RISK + "(callFunction)" + e.getMessage(); 668 | } catch (Exception e) { 669 | result = MSG_ERROR + CHAR_RISK + "(callFunction)" + e.getMessage(); 670 | } 671 | }else{ 672 | result = MSG_UNREGISTERED; 673 | } 674 | return result; 675 | } 676 | 677 | 678 | public static String uploadFile2(String file){ 679 | String result = STRING_EMPTY; 680 | if(isInit()){ 681 | HttpURLConnection conn = null; 682 | //获取文件名 683 | String fileName = file.trim(); 684 | fileName = fileName.substring(fileName.lastIndexOf("/")+1); 685 | 686 | String mURL = "https://api2.bmob.cn/2/files/"+fileName; 687 | try { 688 | 689 | FileInputStream fis = new FileInputStream(file); 690 | 691 | conn = connectionCommonSetting(conn, new URL(mURL), METHOD_POST); 692 | conn.setDoOutput(true); 693 | conn.connect(); 694 | 695 | //一次读多个字节 696 | byte[] tempbytes = new byte[1]; 697 | int byteread = 0; 698 | int i=0; 699 | ByteArrayOutputStream byteArr = new ByteArrayOutputStream(); 700 | OutputStream os = conn.getOutputStream(); 701 | while((byteread=fis.read(tempbytes))!=-1) 702 | { 703 | os.write(tempbytes); 704 | } 705 | 706 | os.flush(); 707 | os.close(); 708 | fis.close(); 709 | 710 | result = getResultFromConnection(conn); 711 | conn.disconnect(); 712 | } catch (FileNotFoundException e){ 713 | result = MSG_FILE_NOT_FOUND + CHAR_RISK + e.getMessage(); 714 | } catch (Exception e) { 715 | result = MSG_ERROR + CHAR_RISK + e.getMessage(); 716 | } 717 | }else{ 718 | result = MSG_UNREGISTERED; 719 | } 720 | return result; 721 | } 722 | 723 | /** 724 | * 复合查询-或 725 | * @param where1 JSON格式条件一 726 | * @param where2 JSON格式条件二 727 | * @return 复合或字符串 728 | */ 729 | public static String whereOr(String where1, String where2){ 730 | return "{\"$or\":["+where1+","+where2+"]}"; 731 | } 732 | 733 | /** 734 | * 复合查询-与 735 | * @param where1 JSON格式条件一 736 | * @param where2 JSON格式条件二 737 | * @return 复合与字符串 738 | */ 739 | public static String whereAnd(String where1, String where2){ 740 | return "{\"$and\":["+where1+","+where2+"]}"; 741 | } 742 | 743 | 744 | 745 | /** 746 | * 操作符-小于 747 | * @param value 目标值 748 | * @return 复合小于字符串 749 | */ 750 | public static String whereLess(int value){ 751 | return "{\"$lt\":"+value+"}"; 752 | } 753 | /** 754 | * 操作符-小于 755 | * @param value 目标值 756 | * @return 复合小于字符串 757 | */ 758 | public static String whereLess(String value){ 759 | return "{\"$lt\":"+value+"}"; 760 | } 761 | 762 | /** 763 | * 操作符-小于等于 764 | * @param value 目标值 765 | * @return 复合小于等于字符串 766 | */ 767 | public static String whereLessEqual(int value){ 768 | return "{\"$lte\":"+value+"}"; 769 | } 770 | /** 771 | * 操作符-小于等于 772 | * @param value 目标值 773 | * @return 复合小于等于字符串 774 | */ 775 | public static String whereLessEqual(String value){ 776 | return "{\"$lte\":"+value+"}"; 777 | } 778 | 779 | /** 780 | * 操作符-大于 781 | * @param value 目标值 782 | * @return 复合大于字符串 783 | */ 784 | public static String whereGreate(int value){ 785 | return "{\"$gt\":"+value+"}"; 786 | } 787 | /** 788 | * 操作符-大于 789 | * @param value 目标值 790 | * @return 复合大于字符串 791 | */ 792 | public static String whereGreate(String value){ 793 | return "{\"$gt\":"+value+"}"; 794 | } 795 | 796 | /** 797 | * 操作符-大于等于 798 | * @param value 目标值 799 | * @return 复合大于等于字符串 800 | */ 801 | public static String whereGreateEqual(int value){ 802 | return "{\"$gte\":"+value+"}"; 803 | } 804 | /** 805 | * 操作符-大于等于 806 | * @param value 目标值 807 | * @return 复合大于等于字符串 808 | */ 809 | public static String whereGreateEqual(String value){ 810 | return "{\"$gte\":"+value+"}"; 811 | } 812 | 813 | /** 814 | * 操作符-不等于 815 | * @param value 目标值 816 | * @return 复合不等于字符串 817 | */ 818 | public static String whereNotEqual(int value){ 819 | return "{\"$ne\":"+value+"}"; 820 | } 821 | /** 822 | * 操作符-不等于 823 | * @param value 目标值 824 | * @return 复合不等于字符串 825 | */ 826 | public static String whereNotEqual(String value){ 827 | return "{\"$ne\":"+value+"}"; 828 | } 829 | 830 | /** 831 | * 操作符-包含 832 | * @param value 目标数组值(例:new int[]{1,3,5,7}) 833 | * @return 复合包含字符串 834 | */ 835 | public static String whereIn(int[] value){ 836 | String result = STRING_EMPTY; 837 | for(int i=0; i