>();
24 |
25 | public static void registerDefaultSubClasses() {
26 | registerSubclass(ParseUser.class);
27 | registerSubclass(ParseRole.class);
28 | }
29 |
30 | public static void unregisterSubclass(String className) {
31 | objectTypes.remove(className);
32 | }
33 |
34 | public static void registerSubclass(Class extends ParseObject> subclass) {
35 |
36 | String className = getClassName(subclass);
37 | if(LOGGER.isDebugEnabled()) {
38 | LOGGER.debug("Registering sub class {}", className);
39 | }
40 | if (className == null) {
41 | throw new IllegalArgumentException(
42 | "No ParseClassName annoation provided on " + subclass);
43 | }
44 |
45 | if (subclass.getDeclaredConstructors().length > 0) {
46 | try {
47 | if (!isAccessible(subclass.getDeclaredConstructor(new Class[0])))
48 | throw new IllegalArgumentException(
49 | "Default constructor for " + subclass
50 | + " is not accessible.");
51 | } catch (NoSuchMethodException e) {
52 | throw new IllegalArgumentException(
53 | "No default constructor provided for " + subclass);
54 | }
55 | }
56 |
57 | Class extends ParseObject> oldValue = (Class extends ParseObject>) objectTypes.get(className);
58 | if ((oldValue != null) && (subclass.isAssignableFrom(oldValue))) {
59 | return;
60 | }
61 |
62 | objectTypes.put(className, subclass);
63 |
64 | }
65 |
66 | private static boolean isAccessible(Member m) {
67 | return (Modifier.isPublic(m.getModifiers()))
68 | || ((m.getDeclaringClass().getPackage().getName()
69 | .equals("com.parse"))
70 | && (!Modifier.isPrivate(m.getModifiers())) && (!Modifier
71 | .isProtected(m.getModifiers())));
72 | }
73 |
74 | public static String getClassName(Class extends ParseObject> clazz) {
75 | String name = (String) classNames.get(clazz);
76 | if (name == null) {
77 | ParseClassName info = (ParseClassName) clazz.getAnnotation(ParseClassName.class);
78 | if (info == null) {
79 | return null;
80 | }
81 | name = info.value();
82 | classNames.put(clazz, name);
83 | }
84 | return name;
85 | }
86 |
87 | public static Class extends ParseObject> getParseClass(String className) {
88 | Class extends ParseObject> value = (Class extends ParseObject>) objectTypes.get(className);
89 | return value;
90 | }
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/src/main/java/org/parse4j/util/Preconditions.java:
--------------------------------------------------------------------------------
1 | package org.parse4j.util;
2 |
3 | import java.util.NoSuchElementException;
4 |
5 | /**
6 | * Simple static methods to be called at the start of your own methods to verify
7 | * correct arguments and state. This allows constructs such as
8 | *
9 | *
10 | * if (count <= 0) {
11 | * throw new IllegalArgumentException("must be positive: " + count);
12 | * }
13 | *
14 | *
15 | * to be replaced with the more compact
16 | *
17 | *
18 | * checkArgument(count > 0, "must be positive: %s", count);
19 | *
20 | *
21 | * Note that the sense of the expression is inverted; with {@code Preconditions}
22 | * you declare what you expect to be true, just as you do with an
24 | * {@code assert} or a JUnit {@code assertTrue} call.
25 | *
26 | *
27 | * Warning: only the {@code "%s"} specifier is recognized as a
28 | * placeholder in these messages, not the full range of
29 | * {@link String#format(String, Object[])} specifiers.
30 | *
31 | *
32 | * Take care not to confuse precondition checking with other similar types of
33 | * checks! Precondition exceptions -- including those provided here, but also
34 | * {@link IndexOutOfBoundsException}, {@link NoSuchElementException},
35 | * {@link UnsupportedOperationException} and others -- are used to signal that
36 | * the calling method has made an error. This tells the caller that it
37 | * should not have invoked the method when it did, with the arguments it did, or
38 | * perhaps ever. Postcondition or other invariant failures should not throw
39 | * these types of exceptions.
40 | *
41 | *
42 | * See the Guava User Guide on using
44 | * {@code Preconditions}.
45 | *
46 | * @author Kevin Bourrillion
47 | * @since 2.0 (imported from Google Collections Library)
48 | */
49 | public final class Preconditions {
50 | private Preconditions() {
51 | }
52 |
53 | /**
54 | * Ensures the truth of an expression involving one or more parameters to
55 | * the calling method.
56 | *
57 | * @param expression
58 | * a boolean expression
59 | * @throws IllegalArgumentException
60 | * if {@code expression} is false
61 | */
62 | public static void checkArgument(boolean expression) {
63 | if (!expression) {
64 | throw new IllegalArgumentException();
65 | }
66 | }
67 |
68 | /**
69 | * Ensures the truth of an expression involving one or more parameters to
70 | * the calling method.
71 | *
72 | * @param expression
73 | * a boolean expression
74 | * @param errorMessage
75 | * the exception message to use if the check fails; will be
76 | * converted to a string using {@link String#valueOf(Object)}
77 | * @throws IllegalArgumentException
78 | * if {@code expression} is false
79 | */
80 | public static void checkArgument(boolean expression, Object errorMessage) {
81 | if (!expression) {
82 | throw new IllegalArgumentException(String.valueOf(errorMessage));
83 | }
84 | }
85 |
86 | /**
87 | * Ensures the truth of an expression involving one or more parameters to
88 | * the calling method.
89 | *
90 | * @param expression
91 | * a boolean expression
92 | * @param errorMessageTemplate
93 | * a template for the exception message should the check fail.
94 | * The message is formed by replacing each {@code %s} placeholder
95 | * in the template with an argument. These are matched by
96 | * position - the first {@code %s} gets
97 | * {@code errorMessageArgs[0]}, etc. Unmatched arguments will be
98 | * appended to the formatted message in square braces. Unmatched
99 | * placeholders will be left as-is.
100 | * @param errorMessageArgs
101 | * the arguments to be substituted into the message template.
102 | * Arguments are converted to strings using
103 | * {@link String#valueOf(Object)}.
104 | * @throws IllegalArgumentException
105 | * if {@code expression} is false
106 | * @throws NullPointerException
107 | * if the check fails and either {@code errorMessageTemplate} or
108 | * {@code errorMessageArgs} is null (don't let this happen)
109 | */
110 | public static void checkArgument(boolean expression,
111 | String errorMessageTemplate, Object... errorMessageArgs) {
112 | if (!expression) {
113 | throw new IllegalArgumentException(format(errorMessageTemplate,
114 | errorMessageArgs));
115 | }
116 | }
117 |
118 | /**
119 | * Ensures the truth of an expression involving the state of the calling
120 | * instance, but not involving any parameters to the calling method.
121 | *
122 | * @param expression
123 | * a boolean expression
124 | * @throws IllegalStateException
125 | * if {@code expression} is false
126 | */
127 | public static void checkState(boolean expression) {
128 | if (!expression) {
129 | throw new IllegalStateException();
130 | }
131 | }
132 |
133 | /**
134 | * Ensures the truth of an expression involving the state of the calling
135 | * instance, but not involving any parameters to the calling method.
136 | *
137 | * @param expression
138 | * a boolean expression
139 | * @param errorMessage
140 | * the exception message to use if the check fails; will be
141 | * converted to a string using {@link String#valueOf(Object)}
142 | * @throws IllegalStateException
143 | * if {@code expression} is false
144 | */
145 | public static void checkState(boolean expression, Object errorMessage) {
146 | if (!expression) {
147 | throw new IllegalStateException(String.valueOf(errorMessage));
148 | }
149 | }
150 |
151 | /**
152 | * Ensures the truth of an expression involving the state of the calling
153 | * instance, but not involving any parameters to the calling method.
154 | *
155 | * @param expression
156 | * a boolean expression
157 | * @param errorMessageTemplate
158 | * a template for the exception message should the check fail.
159 | * The message is formed by replacing each {@code %s} placeholder
160 | * in the template with an argument. These are matched by
161 | * position - the first {@code %s} gets
162 | * {@code errorMessageArgs[0]}, etc. Unmatched arguments will be
163 | * appended to the formatted message in square braces. Unmatched
164 | * placeholders will be left as-is.
165 | * @param errorMessageArgs
166 | * the arguments to be substituted into the message template.
167 | * Arguments are converted to strings using
168 | * {@link String#valueOf(Object)}.
169 | * @throws IllegalStateException
170 | * if {@code expression} is false
171 | * @throws NullPointerException
172 | * if the check fails and either {@code errorMessageTemplate} or
173 | * {@code errorMessageArgs} is null (don't let this happen)
174 | */
175 | public static void checkState(boolean expression,
176 | String errorMessageTemplate, Object... errorMessageArgs) {
177 | if (!expression) {
178 | throw new IllegalStateException(format(errorMessageTemplate,
179 | errorMessageArgs));
180 | }
181 | }
182 |
183 | /**
184 | * Ensures that an object reference passed as a parameter to the calling
185 | * method is not null.
186 | *
187 | * @param reference
188 | * an object reference
189 | * @return the non-null reference that was validated
190 | * @throws NullPointerException
191 | * if {@code reference} is null
192 | */
193 | public static T checkNotNull(T reference) {
194 | if (reference == null) {
195 | throw new NullPointerException();
196 | }
197 | return reference;
198 | }
199 |
200 | /**
201 | * Ensures that an object reference passed as a parameter to the calling
202 | * method is not null.
203 | *
204 | * @param reference
205 | * an object reference
206 | * @param errorMessage
207 | * the exception message to use if the check fails; will be
208 | * converted to a string using {@link String#valueOf(Object)}
209 | * @return the non-null reference that was validated
210 | * @throws NullPointerException
211 | * if {@code reference} is null
212 | */
213 | public static T checkNotNull(T reference, Object errorMessage) {
214 | if (reference == null) {
215 | throw new NullPointerException(String.valueOf(errorMessage));
216 | }
217 | return reference;
218 | }
219 |
220 | /**
221 | * Ensures that an object reference passed as a parameter to the calling
222 | * method is not null.
223 | *
224 | * @param reference
225 | * an object reference
226 | * @param errorMessageTemplate
227 | * a template for the exception message should the check fail.
228 | * The message is formed by replacing each {@code %s} placeholder
229 | * in the template with an argument. These are matched by
230 | * position - the first {@code %s} gets
231 | * {@code errorMessageArgs[0]}, etc. Unmatched arguments will be
232 | * appended to the formatted message in square braces. Unmatched
233 | * placeholders will be left as-is.
234 | * @param errorMessageArgs
235 | * the arguments to be substituted into the message template.
236 | * Arguments are converted to strings using
237 | * {@link String#valueOf(Object)}.
238 | * @return the non-null reference that was validated
239 | * @throws NullPointerException
240 | * if {@code reference} is null
241 | */
242 | public static T checkNotNull(T reference, String errorMessageTemplate,
243 | Object... errorMessageArgs) {
244 | if (reference == null) {
245 | // If either of these parameters is null, the right thing happens
246 | // anyway
247 | throw new NullPointerException(format(errorMessageTemplate,
248 | errorMessageArgs));
249 | }
250 | return reference;
251 | }
252 |
253 | /*
254 | * All recent hotspots (as of 2009) *really* like to have the natural code
255 | *
256 | * if (guardExpression) { throw new BadException(messageExpression); }
257 | *
258 | * refactored so that messageExpression is moved to a separate
259 | * String-returning method.
260 | *
261 | * if (guardExpression) { throw new BadException(badMsg(...)); }
262 | *
263 | * The alternative natural refactorings into void or Exception-returning
264 | * methods are much slower. This is a big deal - we're talking factors of
265 | * 2-8 in microbenchmarks, not just 10-20%. (This is a hotspot optimizer
266 | * bug, which should be fixed, but that's a separate, big project).
267 | *
268 | * The coding pattern above is heavily used in java.util, e.g. in ArrayList.
269 | * There is a RangeCheckMicroBenchmark in the JDK that was used to test
270 | * this.
271 | *
272 | * But the methods in this class want to throw different exceptions,
273 | * depending on the args, so it appears that this pattern is not directly
274 | * applicable. But we can use the ridiculous, devious trick of throwing an
275 | * exception in the middle of the construction of another exception. Hotspot
276 | * is fine with that.
277 | */
278 |
279 | /**
280 | * Ensures that {@code index} specifies a valid element in an array,
281 | * list or string of size {@code size}. An element index may range from
282 | * zero, inclusive, to {@code size}, exclusive.
283 | *
284 | * @param index
285 | * a user-supplied index identifying an element of an array, list
286 | * or string
287 | * @param size
288 | * the size of that array, list or string
289 | * @return the value of {@code index}
290 | * @throws IndexOutOfBoundsException
291 | * if {@code index} is negative or is not less than {@code size}
292 | * @throws IllegalArgumentException
293 | * if {@code size} is negative
294 | */
295 | public static int checkElementIndex(int index, int size) {
296 | return checkElementIndex(index, size, "index");
297 | }
298 |
299 | /**
300 | * Ensures that {@code index} specifies a valid element in an array,
301 | * list or string of size {@code size}. An element index may range from
302 | * zero, inclusive, to {@code size}, exclusive.
303 | *
304 | * @param index
305 | * a user-supplied index identifying an element of an array, list
306 | * or string
307 | * @param size
308 | * the size of that array, list or string
309 | * @param desc
310 | * the text to use to describe this index in an error message
311 | * @return the value of {@code index}
312 | * @throws IndexOutOfBoundsException
313 | * if {@code index} is negative or is not less than {@code size}
314 | * @throws IllegalArgumentException
315 | * if {@code size} is negative
316 | */
317 | public static int checkElementIndex(int index, int size, String desc) {
318 | // Carefully optimized for execution by hotspot (explanatory comment
319 | // above)
320 | if (index < 0 || index >= size) {
321 | throw new IndexOutOfBoundsException(badElementIndex(index, size,
322 | desc));
323 | }
324 | return index;
325 | }
326 |
327 | private static String badElementIndex(int index, int size, String desc) {
328 | if (index < 0) {
329 | return format("%s (%s) must not be negative", desc, index);
330 | } else if (size < 0) {
331 | throw new IllegalArgumentException("negative size: " + size);
332 | } else { // index >= size
333 | return format("%s (%s) must be less than size (%s)", desc, index,
334 | size);
335 | }
336 | }
337 |
338 | /**
339 | * Ensures that {@code index} specifies a valid position in an array,
340 | * list or string of size {@code size}. A position index may range from zero
341 | * to {@code size}, inclusive.
342 | *
343 | * @param index
344 | * a user-supplied index identifying a position in an array, list
345 | * or string
346 | * @param size
347 | * the size of that array, list or string
348 | * @return the value of {@code index}
349 | * @throws IndexOutOfBoundsException
350 | * if {@code index} is negative or is greater than {@code size}
351 | * @throws IllegalArgumentException
352 | * if {@code size} is negative
353 | */
354 | public static int checkPositionIndex(int index, int size) {
355 | return checkPositionIndex(index, size, "index");
356 | }
357 |
358 | /**
359 | * Ensures that {@code index} specifies a valid position in an array,
360 | * list or string of size {@code size}. A position index may range from zero
361 | * to {@code size}, inclusive.
362 | *
363 | * @param index
364 | * a user-supplied index identifying a position in an array, list
365 | * or string
366 | * @param size
367 | * the size of that array, list or string
368 | * @param desc
369 | * the text to use to describe this index in an error message
370 | * @return the value of {@code index}
371 | * @throws IndexOutOfBoundsException
372 | * if {@code index} is negative or is greater than {@code size}
373 | * @throws IllegalArgumentException
374 | * if {@code size} is negative
375 | */
376 | public static int checkPositionIndex(int index, int size, String desc) {
377 | // Carefully optimized for execution by hotspot (explanatory comment
378 | // above)
379 | if (index < 0 || index > size) {
380 | throw new IndexOutOfBoundsException(badPositionIndex(index, size,
381 | desc));
382 | }
383 | return index;
384 | }
385 |
386 | private static String badPositionIndex(int index, int size, String desc) {
387 | if (index < 0) {
388 | return format("%s (%s) must not be negative", desc, index);
389 | } else if (size < 0) {
390 | throw new IllegalArgumentException("negative size: " + size);
391 | } else { // index > size
392 | return format("%s (%s) must not be greater than size (%s)", desc,
393 | index, size);
394 | }
395 | }
396 |
397 | /**
398 | * Ensures that {@code start} and {@code end} specify a valid
399 | * positions in an array, list or string of size {@code size}, and
400 | * are in order. A position index may range from zero to {@code size},
401 | * inclusive.
402 | *
403 | * @param start
404 | * a user-supplied index identifying a starting position in an
405 | * array, list or string
406 | * @param end
407 | * a user-supplied index identifying a ending position in an
408 | * array, list or string
409 | * @param size
410 | * the size of that array, list or string
411 | * @throws IndexOutOfBoundsException
412 | * if either index is negative or is greater than {@code size},
413 | * or if {@code end} is less than {@code start}
414 | * @throws IllegalArgumentException
415 | * if {@code size} is negative
416 | */
417 | public static void checkPositionIndexes(int start, int end, int size) {
418 | // Carefully optimized for execution by hotspot (explanatory comment
419 | // above)
420 | if (start < 0 || end < start || end > size) {
421 | throw new IndexOutOfBoundsException(badPositionIndexes(start, end,
422 | size));
423 | }
424 | }
425 |
426 | private static String badPositionIndexes(int start, int end, int size) {
427 | if (start < 0 || start > size) {
428 | return badPositionIndex(start, size, "start index");
429 | }
430 | if (end < 0 || end > size) {
431 | return badPositionIndex(end, size, "end index");
432 | }
433 | // end < start
434 | return format("end index (%s) must not be less than start index (%s)",
435 | end, start);
436 | }
437 |
438 | /**
439 | * Substitutes each {@code %s} in {@code template} with an argument. These
440 | * are matched by position - the first {@code %s} gets {@code args[0]}, etc.
441 | * If there are more arguments than placeholders, the unmatched arguments
442 | * will be appended to the end of the formatted message in square braces.
443 | *
444 | * @param template
445 | * a non-null string containing 0 or more {@code %s}
446 | * placeholders.
447 | * @param args
448 | * the arguments to be substituted into the message template.
449 | * Arguments are converted to strings using
450 | * {@link String#valueOf(Object)}. Arguments can be null.
451 | */
452 | static String format(String template, Object... args) {
453 | template = String.valueOf(template); // null -> "null"
454 |
455 | // start substituting the arguments into the '%s' placeholders
456 | StringBuilder builder = new StringBuilder(template.length() + 16
457 | * args.length);
458 | int templateStart = 0;
459 | int i = 0;
460 | while (i < args.length) {
461 | int placeholderStart = template.indexOf("%s", templateStart);
462 | if (placeholderStart == -1) {
463 | break;
464 | }
465 | builder.append(template.substring(templateStart, placeholderStart));
466 | builder.append(args[i++]);
467 | templateStart = placeholderStart + 2;
468 | }
469 | builder.append(template.substring(templateStart));
470 |
471 | // if we run out of placeholders, append the extra args in square braces
472 | if (i < args.length) {
473 | builder.append(" [");
474 | builder.append(args[i++]);
475 | while (i < args.length) {
476 | builder.append(", ");
477 | builder.append(args[i++]);
478 | }
479 | builder.append(']');
480 | }
481 |
482 | return builder.toString();
483 | }
484 | }
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/Parse4JTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import java.io.IOException;
4 | import java.io.RandomAccessFile;
5 | import java.util.ArrayList;
6 | import java.util.Date;
7 | import java.util.List;
8 |
9 | import org.junit.AfterClass;
10 | import org.junit.BeforeClass;
11 |
12 | public class Parse4JTestCase {
13 |
14 | public static String CLASS_NAME = "parse4j";
15 | private static String APP_ID = "RWjFpDDbwCIXF8Gy9dHEBpR7Fs2PZ0UzcNdxhAvf";
16 | private static String APP_REST_API_ID = "EWpTGoOFgGr9vXfPLBRYZjhDL0pg4MQ1F7i3wWAq";
17 |
18 | @BeforeClass
19 | public static void setupParse() {
20 | System.out.println("setupParse(): initializing...");
21 | Parse.initialize(APP_ID, APP_REST_API_ID);
22 | }
23 |
24 | @AfterClass
25 | public static void tearDown() {
26 | System.out.println("tearDown(): finalizing...");
27 | ParseExecutor.getExecutor().shutdown();
28 | //while(!ParseExecutor.getExecutor().isTerminated()) { }
29 | }
30 |
31 | protected ParseObject getEmptyParseObject(String className) {
32 | ParseObject parseObject = new ParseObject(className);
33 | return parseObject;
34 | }
35 |
36 | protected ParseObject getParseObject(String className) {
37 | ParseObject parseObject = new ParseObject(className);
38 | parseObject.put("name", "parse developer");
39 | parseObject.put("int", 10);
40 | parseObject.put("long", 10l);
41 | parseObject.put("boolean", true);
42 | parseObject.put("dob", new Date());
43 | parseObject.put("double", 10.5);
44 |
45 | List types = new ArrayList();
46 | types.add("type1");
47 | types.add("type2");
48 | types.add("type3");
49 | parseObject.put("types", types);
50 |
51 | ParseGeoPoint gp = new ParseGeoPoint(40.0, -30.0);
52 | parseObject.put("location", gp);
53 |
54 | return parseObject;
55 | }
56 |
57 | protected ParseUser getParseUser(String number) {
58 | ParseUser parseUser = new ParseUser();
59 | parseUser.setUsername("parse4j-user" + number);
60 | parseUser.setPassword("parse4j-password");
61 | parseUser.setEmail("parse4j-email"+number+"@gmail.com");
62 | parseUser.put("dob", new Date());
63 | parseUser.put("city", "westbury");
64 | parseUser.put("state", "ny");
65 | return parseUser;
66 | }
67 |
68 | protected void sleep(int millis) {
69 | try {
70 | Thread.sleep(millis);
71 | }
72 | catch(InterruptedException e) {
73 |
74 | }
75 | }
76 |
77 | public byte[] getBytes(String fileName) throws ParseException {
78 | try {
79 | RandomAccessFile f = new RandomAccessFile(getClass().getResource(fileName).getFile(), "r");
80 | byte[] b = new byte[(int)f.length()];
81 | f.read(b);
82 | f.close();
83 | return b;
84 | }
85 | catch(IOException e) {
86 | throw new ParseException(e);
87 | }
88 | }
89 |
90 | }
91 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseAnalyticsTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | import org.junit.Test;
7 |
8 | public class ParseAnalyticsTestCase extends Parse4JTestCase {
9 |
10 |
11 | @Test
12 | public void trackAppOpened() {
13 | System.out.println("trackAppOpened(): initializing...");
14 | ParseAnalytics.trackAppOpened();
15 | sleep(1000);
16 | }
17 |
18 | @Test
19 | public void trackJunitTest() {
20 | System.out.println("trackJunitTest(): initializing...");
21 | ParseAnalytics.trackEvent("JUnitTestStarted");
22 | sleep(1000);
23 | }
24 |
25 | @Test
26 | public void trackJunitTest2() {
27 | System.out.println("trackJunitTest2(): initializing...");
28 | Map dimensions = new HashMap();
29 | dimensions.put("attr1", "10");
30 | dimensions.put("attr2", "127.0.0.1");
31 | ParseAnalytics.trackEvent("JUnitTestStarted");
32 | sleep(1000);
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseBatchTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertNotNull;
5 | import static org.junit.Assert.assertTrue;
6 |
7 | import java.util.List;
8 |
9 | import org.json.JSONArray;
10 | import org.json.JSONObject;
11 | import org.junit.Test;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | public class ParseBatchTestCase extends Parse4JTestCase {
16 |
17 | private static Logger LOGGER = LoggerFactory.getLogger(ParseBatchTestCase.class);
18 |
19 | @Test
20 | public void testReadData() throws ParseException{
21 | ParseQuery query = ParseQuery.getQuery("Post");
22 | query.limit(20);
23 | List find = query.find();
24 |
25 | for (int i = 0; i < find.size(); i++) {
26 | ParseObject current = find.get(i);
27 | System.out.println(current.get("title"));
28 | System.out.println(current.getUpdatedAt());
29 | }
30 | }
31 | @Test
32 | public void testBatchInsert() throws ParseException{
33 | ParseBatch batcher = new ParseBatch();
34 | for (int i = 0; i < 20; i++) {
35 | ParseObject obj = new ParseObject("Post");
36 | obj.put("title", "input message " + i);
37 | batcher.createObject(obj);
38 |
39 | }
40 | JSONArray batch = batcher.batch();
41 | assertNotNull(batch);
42 | assertTrue(batch.length() == 20);
43 |
44 | }
45 | @Test
46 | public void testBatchUpdate() throws ParseException{
47 | ParseQuery query = ParseQuery.getQuery("Post");
48 | query.limit(20);
49 | query.addDescendingOrder("updateAt");
50 | List find = query.find();
51 | LOGGER.info("size is " + find.size());
52 |
53 | ParseBatch batcher = new ParseBatch();
54 | for (int i = 0; i < find.size(); i++) {
55 | ParseObject current = find.get(i);
56 | current.put("title", "input updated message " + i);
57 | batcher.updateObject(current);
58 | }
59 |
60 | //send batch update
61 | JSONArray batch = batcher.batch();
62 | assertNotNull(batch);
63 | assertTrue(batch.length() == 20);
64 |
65 | //refresh results
66 | find = query.find();
67 | for (int i = 0; i < find.size(); i++) {
68 | assertEquals("not equal", "input updated message " + i , find.get(i).getString("title"));
69 | }
70 | }
71 | @Test
72 | public void testBatchDelete() throws ParseException{
73 | final int size = 5;
74 | //first insert 5 objects that should be deleted !
75 | for(int i = 0;i query = ParseQuery.getQuery("Post");
82 | query.limit(size);
83 | query.addDescendingOrder("updatedAt");
84 | List find = query.find();
85 | ParseBatch batcher = new ParseBatch();
86 | for (int i = 0; i < find.size(); i++) {
87 | ParseObject current = find.get(i);
88 | LOGGER.info("object found " + current.get("title"));
89 | LOGGER.info("updated at " + current.getUpdatedAt());
90 | batcher.deleteObject(current);
91 | }
92 | JSONArray batch = batcher.batch();
93 | assertNotNull(batch);
94 | assertEquals(batch.length(), find.size());
95 | }
96 |
97 | @Test(expected = IllegalArgumentException.class)
98 | public void testFailureOnDelete() throws ParseException{
99 | ParseBatch batch = new ParseBatch();
100 | ParseObject obj = new ParseObject();
101 | batch.deleteObject(obj);
102 | batch.batch();
103 | }
104 | @Test(expected = IllegalArgumentException.class)
105 | public void testFailureOnUpdate() throws ParseException{
106 | ParseBatch batch = new ParseBatch();
107 | ParseObject obj = new ParseObject();
108 | batch.updateObject(obj);
109 | batch.batch();
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseCloudTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertNull;
5 |
6 | import java.util.HashMap;
7 |
8 | import org.junit.Test;
9 | import org.parse4j.callback.FunctionCallback;
10 |
11 | public class ParseCloudTestCase extends Parse4JTestCase {
12 |
13 | /*
14 | Parse.Cloud.define("helloWorld", function(request, response) {
15 | response.success("Hello, " + request.params.name + "!!!");
16 | });
17 |
18 | Parse.Cloud.define("Multiply", function(request, response) {
19 | response.success(request.params.A * request.params.B);
20 | });
21 |
22 | Parse.Cloud.define("ForcedError", function(request, response) {
23 | response.error("forced error");
24 | });
25 | */
26 |
27 | @Test
28 | public void testInvalidFunction() {
29 | System.out.println("InvalidFunction(): initializing...");
30 | try {
31 | HashMap params = new HashMap();
32 | params.put("name", "Parse");
33 | String result = ParseCloud.callFunction("InvalidFunction", params);
34 | assertEquals("Hello, Parse!!!", result);
35 | }
36 | catch(ParseException pe) {
37 | assertEquals(ParseException.CLOUD_ERROR, pe.getCode());
38 | }
39 | }
40 |
41 | @Test
42 | public void testForcedError() {
43 | System.out.println("testForcedError(): initializing...");
44 | try {
45 | HashMap params = new HashMap();
46 | params.put("name", "Parse");
47 | String result = ParseCloud.callFunction("ForcedError", params);
48 | assertEquals("Hello, Parse!!!", result);
49 | }
50 | catch(ParseException pe) {
51 | assertEquals(ParseException.CLOUD_ERROR, pe.getCode());
52 | }
53 | }
54 |
55 | @Test
56 | public void testHelloWorld() {
57 | System.out.println("testHelloWorld(): initializing...");
58 | try {
59 | HashMap params = new HashMap();
60 | params.put("name", "Parse");
61 | String result = ParseCloud.callFunction("helloWorld", params);
62 | assertEquals("Hello, Parse!!!", result);
63 | }
64 | catch(ParseException pe) {
65 | assertNull("testHelloWorld(): should not have thrown ParseException", pe);
66 | }
67 | }
68 |
69 | @Test
70 | public void testMultiply() {
71 | System.out.println("testMultiply(): initializing...");
72 | try {
73 | HashMap params = new HashMap();
74 | params.put("A", 12);
75 | params.put("B", 4);
76 | Integer result = ParseCloud.callFunction("Multiply", params);
77 | assertEquals("48", result.toString());
78 | }
79 | catch(ParseException pe) {
80 | assertNull("testMultiply(): should not have thrown ParseException", pe);
81 | }
82 |
83 | }
84 |
85 | @Test
86 | public void testCallInBackground() {
87 | System.out.println("testCallInBackground(): initializing...");
88 |
89 | HashMap params = new HashMap();
90 | params.put("A", 12);
91 | params.put("B", 4);
92 | ParseCloud.callFunctionInBackground("Multiply", params, new FunctionCallback() {
93 |
94 | @Override
95 | public void done(Integer result, ParseException parseException) {
96 | assertEquals("48", result.toString());
97 |
98 | }
99 |
100 | });
101 | sleep(2000);
102 | }
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseDecoderTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import java.lang.reflect.Field;
6 | import java.util.List;
7 | import java.util.Map;
8 |
9 | import org.json.JSONObject;
10 | import org.junit.Test;
11 | import org.parse4j.operation.ParseFieldOperation;
12 |
13 | public class ParseDecoderTestCase {
14 |
15 | @Test
16 | public void decode() throws ParseException {
17 | JSONObject jsonObject = new JSONObject(
18 | "{\"createdAt\":\"2015-12-28T06:18:45.493Z\",\"__type\":\"Object\",\"name\":\"test object\",\"nested_object\":{ \"createdAt\":\"2015-12-28T04:24:57.680Z\",\"__type\":\"Object\",\"name\":\"nested object\",\"className\":\"NestedTestClass\",\"objectId\":\"DdDjWiUT8y\",\"updatedAt\":\"2015-12-28T04:42:38.980Z\"},\"className\":\"TestClass\",\"objectId\":\"Ts7L6Bhv00\",\"updatedAt\":\"2015-12-30T11:31:51.512Z\"}");
19 | ParseObject decodedObject = (ParseObject) ParseDecoder.decode(jsonObject);
20 | assertFalse(decodedObject.isDirty);
21 | assertNotNull(decodedObject.getCreatedAt());
22 | assertNotNull(decodedObject.getUpdatedAt());
23 | assertEquals("TestClass", decodedObject.getClassName());
24 | assertEquals("test object", decodedObject.getString("name"));
25 | assertEquals("Object", decodedObject.getString("__type"));
26 | assertEquals("Ts7L6Bhv00", decodedObject.getObjectId());
27 | List> dirtyKeys = (List>) getPrivateField(decodedObject, "dirtyKeys");
28 | @SuppressWarnings("unchecked")
29 | Map operations = (Map) getPrivateField(decodedObject, "operations");
30 | assertTrue(dirtyKeys.size() == 0);
31 | assertTrue(operations.size() == 0);
32 | ParseObject nestedObject = decodedObject.getParseObject("nested_object");
33 | assertFalse(nestedObject.isDirty);
34 | assertNotNull(nestedObject.getCreatedAt());
35 | assertNotNull(nestedObject.getUpdatedAt());
36 | assertEquals("NestedTestClass", nestedObject.getClassName());
37 | assertEquals("nested object", nestedObject.getString("name"));
38 | assertEquals("Object", nestedObject.getString("__type"));
39 | assertEquals("DdDjWiUT8y", nestedObject.getObjectId());
40 | List> dirtyKeys2 = (List>) getPrivateField(nestedObject, "dirtyKeys");
41 | @SuppressWarnings("unchecked")
42 | Map operations2 = (Map) getPrivateField(nestedObject, "operations");
43 | assertTrue(dirtyKeys2.size() == 0);
44 | assertTrue(operations2.size() == 0);
45 | }
46 |
47 | private Object getPrivateField(Object obj, String fieldName) {
48 | try {
49 | Field field = obj.getClass().getDeclaredField(fieldName);
50 | field.setAccessible(true);
51 | Object value = field.get(obj);
52 | field.setAccessible(false);
53 | return value;
54 | } catch (Exception e) {
55 | return null;
56 | }
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseFileTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertNotNull;
5 | import static org.junit.Assert.assertNull;
6 | import junit.framework.Assert;
7 |
8 | import org.junit.Test;
9 | import org.parse4j.callback.ProgressCallback;
10 |
11 | public class ParseFileTestCase extends Parse4JTestCase {
12 |
13 | @Test
14 | public void uploadTxt() {
15 | System.out.println("uploadTxt(): initializing...");
16 | try {
17 | byte[] data = "Working at Parse is great!".getBytes();
18 | ParseFile file = new ParseFile("resume.txt", data);
19 | file.save();
20 | testParseFile(file);
21 | }
22 | catch(ParseException pe) {
23 | assertNull("uploadTxt(): should not have thrown ParseException", pe);
24 | }
25 | }
26 |
27 | @Test
28 | public void uploadPng() {
29 | System.out.println("uploadPng(): initializing...");
30 | assertNotNull("Test file missing", getClass().getResource("/parse.png"));
31 |
32 | try {
33 | byte[] data = getBytes("/parse.png");
34 | ParseFile file = new ParseFile("parse.png", data);
35 | file.save();
36 | testParseFile(file);
37 | }
38 | catch(ParseException pe) {
39 | assertNull("uploadTxt(): should not have thrown ParseException", pe);
40 | }
41 | }
42 |
43 | @Test
44 | public void uploadDoc() {
45 | System.out.println("uploadDoc(): initializing...");
46 | try {
47 | byte[] data = getBytes("/parse.docx");
48 | ParseFile file = new ParseFile("parse.docx", data);
49 | file.save();
50 | testParseFile(file);
51 | }
52 | catch(ParseException pe) {
53 | assertNull("uploadDoc(): should not have thrown ParseException", pe);
54 | }
55 | }
56 |
57 | @Test
58 | public void uploadExr() {
59 | System.out.println("uploadExr(): initializing...");
60 | try {
61 | byte[] data = getBytes("/parse.exr");
62 | ParseFile file = new ParseFile("parse.exr", data);
63 | file.save();
64 | testParseFile(file);
65 | }
66 | catch(ParseException pe) {
67 | assertNull("uploadExr(): should not have thrown ParseException", pe);
68 | }
69 | }
70 |
71 | @Test
72 | public void uploadPdf() {
73 | System.out.println("uploadPdf(): initializing...");
74 | try {
75 | byte[] data = getBytes("/parse.pdf");
76 | ParseFile file = new ParseFile("parse.pdf", data);
77 | file.save();
78 | testParseFile(file);
79 | }
80 | catch(ParseException pe) {
81 | assertNull("uploadPdf(): should not have thrown ParseException", pe);
82 | }
83 | }
84 |
85 | public void uploadPdfWithProgressCallback() {
86 | System.out.println("uploadPdf(): initializing...");
87 | try {
88 | byte[] data = getBytes("/ml-1m.zip");
89 | ParseFile file = new ParseFile("ml-1m.zip", data);
90 | file.save(new ProgressCallback() {
91 |
92 | @Override
93 | public void done(Integer percentDone) {
94 | System.out.println("uploadPdf(): progress " + percentDone + "%");
95 | }
96 | });
97 | sleep(2000);
98 | testParseFile(file);
99 | }
100 | catch(ParseException pe) {
101 | assertNull("uploadPdfWithProgressCallback(): should not have thrown ParseException", pe);
102 | }
103 | }
104 |
105 | @Test
106 | public void uploadDocAndGetData() {
107 | System.out.println("uploadDocAndGetData(): initializing...");
108 | try {
109 | byte[] data = getBytes("/parse.docx");
110 | ParseFile file = new ParseFile("parse.docx", data);
111 | file.save();
112 | testParseFile(file);
113 |
114 | ParseFile getFile = new ParseFile(file.getName(), file.getUrl());
115 | byte[] getData = getFile.getData();
116 | System.out.println("uploadDocAndGetData(): data.length: " + data.length);
117 | System.out.println("uploadDocAndGetData(): getData.length: " + getData.length);
118 | assertEquals(data.length, getData.length);
119 | }
120 | catch(ParseException pe) {
121 | assertNull("uploadDocAndGetData(): should not have thrown ParseException", pe);
122 | }
123 | }
124 |
125 | public void testParseFile(ParseFile file) {
126 | System.out.println("Name: " + file.getName());
127 | assertNotNull("name should not be null", file.getName());
128 | System.out.println("File: " + file.getUrl());
129 | assertNotNull("url should not be null", file.getUrl());
130 | }
131 |
132 |
133 |
134 |
135 | }
136 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseObjectCRUDTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import static org.junit.Assert.assertNotNull;
4 | import static org.junit.Assert.assertNull;
5 |
6 | import java.util.Date;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 | import org.junit.runners.JUnit4;
11 | import org.parse4j.callback.DeleteCallback;
12 | import org.parse4j.callback.SaveCallback;
13 |
14 | @RunWith(JUnit4.class)
15 | public class ParseObjectCRUDTestCase extends Parse4JTestCase {
16 |
17 | @Test
18 | public void save() {
19 | System.out.println("save(): initializing...");
20 | ParseObject parseObject = getParseObject(CLASS_NAME);
21 |
22 | try {
23 | parseObject.save();
24 | System.out.println("save(): objectId: " + parseObject.getObjectId());
25 | System.out.println("save(): createdAt: " + parseObject.getCreatedAt());
26 | System.out.println("save(): updatedAt: " + parseObject.getUpdatedAt());
27 | assertNotNull("objectId should not be null", parseObject.getObjectId());
28 | assertNotNull("createdAt should not be null", parseObject.getCreatedAt());
29 | assertNotNull("updatedAt should not be null", parseObject.getUpdatedAt());
30 | }
31 | catch(ParseException pe) {
32 | assertNull("save(): should not have thrown ParseException", pe);
33 | }
34 | }
35 |
36 | @Test
37 | public void saveWithFile() {
38 | System.out.println("saveWithFile(): initializing...");
39 | ParseObject parseObject = getParseObject(CLASS_NAME);
40 | byte[] data = null;
41 | ParseFile file = null;
42 |
43 | try {
44 |
45 | data = getBytes("/parse.png");
46 | file = new ParseFile("parse.png", data);
47 | file.save();
48 | parseObject.put("pngFile", file);
49 |
50 | data = getBytes("/parse.pdf");
51 | file = new ParseFile("parse.pdf", data);
52 | file.save();
53 | parseObject.put("pdfFile", file);
54 |
55 | data = getBytes("/parse.docx");
56 | file = new ParseFile("parse.docx", data);
57 | file.save();
58 | parseObject.put("docxFile", file);
59 |
60 | parseObject.save();
61 | System.out.println("saveWithFile(): objectId: " + parseObject.getObjectId());
62 | System.out.println("saveWithFile(): createdAt: " + parseObject.getCreatedAt());
63 | System.out.println("saveWithFile(): updatedAt: " + parseObject.getUpdatedAt());
64 | assertNotNull("objectId should not be null", parseObject.getObjectId());
65 | assertNotNull("createdAt should not be null", parseObject.getCreatedAt());
66 | assertNotNull("updatedAt should not be null", parseObject.getUpdatedAt());
67 | }
68 | catch(ParseException pe) {
69 | assertNull("saveWithFile(): should not have thrown ParseException", pe);
70 | }
71 | }
72 |
73 | @Test
74 | public void update() {
75 | System.out.println("update(): initializing...");
76 | ParseObject parseObject = getParseObject(CLASS_NAME);
77 |
78 | try {
79 | parseObject.save();
80 | System.out.println("update(): objectId: " + parseObject.getObjectId());
81 | System.out.println("update(): createdAt: " + parseObject.getCreatedAt());
82 | System.out.println("update(): updatedAt: " + parseObject.getUpdatedAt());
83 | System.out.println("update(): initial name: " + parseObject.getString("name"));
84 | System.out.println("update(): initial int: " + parseObject.getInt("int"));
85 | System.out.println("update(): initial double: " + parseObject.getDouble("double"));
86 | assertNotNull("objectId should not be null", parseObject.getObjectId());
87 | assertNotNull("createdAt should not be null", parseObject.getCreatedAt());
88 | assertNotNull("updatedAt should not be null", parseObject.getUpdatedAt());
89 |
90 | parseObject.put("name", "updated");
91 | parseObject.increment("int");
92 | parseObject.decrement("double");
93 | parseObject.save();
94 | System.out.println("update(): name: " + parseObject.getString("name"));
95 | System.out.println("update(): incrementedInt: " + parseObject.getInt("int"));
96 | System.out.println("update(): incrementedInt: " + parseObject.getDouble("double"));
97 | System.out.println("update(): createdAt: " + parseObject.getCreatedAt());
98 | System.out.println("update(): updatedAt: " + parseObject.getUpdatedAt());
99 |
100 | }
101 | catch(ParseException pe) {
102 | assertNull("update(): should not have thrown ParseException", pe);
103 | }
104 | }
105 |
106 | @Test
107 | public void delete() {
108 | System.out.println("delete(): initializing...");
109 | ParseObject parseObject = getParseObject(CLASS_NAME);
110 |
111 | try {
112 | System.out.println("delete(): saving parseObject first...");
113 | parseObject.save();
114 | System.out.println("delete(): objectId: " + parseObject.getObjectId());
115 | assertNotNull("delete(): objectId should not be null", parseObject.getObjectId());
116 | assertNotNull("delete(): createdAt should not be null", parseObject.getCreatedAt());
117 | assertNotNull("delete(): updatedAt should not be null", parseObject.getUpdatedAt());
118 | System.out.println("delete(): deleting parseObject with objectId " + parseObject.getObjectId());
119 | parseObject.delete();
120 | assertNull("delete(): parseObject deleted, objectId should be null", parseObject.getObjectId());
121 | assertNull("delete(): parseObject deleted, createdAt should not be null", parseObject.getCreatedAt());
122 | assertNull("delete(): parseObject deleted, updatedAt should not be null", parseObject.getUpdatedAt());
123 | }
124 | catch(ParseException pe) {
125 | assertNull("delete() should not have thrown ParseException", pe);
126 | }
127 | }
128 |
129 |
130 | public void saveInBackground() {
131 | System.out.println("saveInBackground(): initializing...");
132 | final ParseObject parseObject = getParseObject(CLASS_NAME);
133 |
134 | parseObject.saveInBackground(new SaveCallback() {
135 | @Override
136 | public void done(ParseException parseException) {
137 | assertNull("saveInBackground(): parseException should not be null", parseException);
138 | System.out.println("saveInBackground(): objectId: " + parseObject.getObjectId());
139 | System.out.println("saveInBackground(): createdAt: " + parseObject.getCreatedAt());
140 | System.out.println("saveInBackground(): updatedAt: " + parseObject.getUpdatedAt());
141 | assertNotNull("objectId should not be null", parseObject.getObjectId());
142 | assertNotNull("createdAt should not be null", parseObject.getCreatedAt());
143 | assertNotNull("updatedAt should not be null", parseObject.getUpdatedAt());
144 | }
145 | });
146 |
147 | }
148 |
149 | public void updateInBackground() {
150 | System.out.println("update(): initializing...");
151 | final ParseObject parseObject = getParseObject(CLASS_NAME);
152 |
153 | try {
154 | parseObject.save();
155 | System.out.println("updateInBackground(): objectId: " + parseObject.getObjectId());
156 | System.out.println("updateInBackground(): createdAt: " + parseObject.getCreatedAt());
157 | System.out.println("updateInBackground(): updatedAt: " + parseObject.getUpdatedAt());
158 | System.out.println("updateInBackground(): initial name: " + parseObject.getString("name"));
159 | System.out.println("updateInBackground(): initial int: " + parseObject.getInt("int"));
160 | System.out.println("updateInBackground(): initial double: " + parseObject.getDouble("double"));
161 | assertNotNull("objectId should not be null", parseObject.getObjectId());
162 | assertNotNull("createdAt should not be null", parseObject.getCreatedAt());
163 | assertNotNull("updatedAt should not be null", parseObject.getUpdatedAt());
164 |
165 | parseObject.put("name", "updated");
166 | parseObject.increment("int");
167 | parseObject.decrement("double");
168 | parseObject.saveInBackground(new SaveCallback() {
169 |
170 | @Override
171 | public void done(ParseException parseException) {
172 | assertNull("updateInBackground(): parseException should not be null", parseException);
173 | System.out.println("updateInBackground(): name: " + parseObject.getString("name"));
174 | System.out.println("updateInBackground(): incrementedInt: " + parseObject.getInt("int"));
175 | System.out.println("updateInBackground(): incrementedInt: " + parseObject.getDouble("double"));
176 | System.out.println("updateInBackground(): createdAt: " + parseObject.getCreatedAt());
177 | System.out.println("updateInBackground(): updatedAt: " + parseObject.getUpdatedAt());
178 |
179 | }
180 | });
181 |
182 | }
183 | catch(ParseException pe) {
184 | assertNull("update(): should not have thrown ParseException", pe);
185 | }
186 | }
187 |
188 | public void deleteInBackground() {
189 | System.out.println("deleteInBackground(): initializing...");
190 | final ParseObject parseObject = getParseObject(CLASS_NAME);
191 |
192 | try {
193 | System.out.println("deleteInBackground(): saving parseObject first...");
194 | parseObject.save();
195 | String objectId = parseObject.getObjectId();
196 | Date createdAt = parseObject.getCreatedAt();
197 | Date updatedAt = parseObject.getUpdatedAt();
198 | System.out.println("deleteInBackground(): objectId: " + objectId);
199 | System.out.println("deleteInBackground(): createdAt: " + createdAt);
200 | System.out.println("deleteInBackground(): updatedAt: " + updatedAt);
201 | assertNotNull("objectId should not be null", objectId);
202 | assertNotNull("createdAt should not be null", createdAt);
203 | assertNotNull("updatedAt should not be null", updatedAt);
204 | System.out.println("deleteInBackground(): deleting parseObject with objectId " + objectId);
205 | }
206 | catch(ParseException pe) {
207 | assertNull("deleteInBackground(): should not have thrown ParseException", pe);
208 | }
209 |
210 | parseObject.deleteInBackground(new DeleteCallback() {
211 |
212 | @Override
213 | public void done(ParseException parseException) {
214 | String objectId = parseObject.getObjectId();
215 | Date createdAt = parseObject.getCreatedAt();
216 | Date updatedAt = parseObject.getUpdatedAt();
217 | assertNull("deleteInBackground(): parseObject deleted, objectId should be null", objectId);
218 | assertNull("deleteInBackground(): parseObject deleted, createdAt should not be null", createdAt);
219 | assertNull("deleteInBackground(): parseObject deleted, updatedAt should not be null", updatedAt);
220 |
221 | }
222 | });
223 |
224 | }
225 |
226 | }
227 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseObjectCustomTest.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import static org.junit.Assert.assertFalse;
4 | import static org.junit.Assert.assertNotNull;
5 | import static org.junit.Assert.assertNull;
6 |
7 | import org.junit.Test;
8 | import org.parse4j.custom.Person;
9 | import org.parse4j.custom.Person2;
10 | import org.parse4j.util.ParseRegistry;
11 |
12 | public class ParseObjectCustomTest extends Parse4JTestCase {
13 |
14 | @Test(expected = IllegalArgumentException.class)
15 | public void parseSubclassNoAnnotation() {
16 | ParseRegistry.registerSubclass(Person2.class);
17 | }
18 |
19 | @Test
20 | public void parseSubclass() {
21 | ParseRegistry.registerSubclass(Person.class);
22 | }
23 |
24 | @Test
25 | public void save() {
26 | System.out.println("save(): initializing...");
27 | ParseRegistry.registerSubclass(Person.class);
28 | Person parseObject = new Person();
29 | parseObject.setAge(15);
30 | parseObject.setGender("male");
31 | parseObject.getString("age");
32 |
33 | try {
34 | parseObject.save();
35 | System.out.println("save(): objectId: " + parseObject.getObjectId());
36 | System.out.println("save(): createdAt: " + parseObject.getCreatedAt());
37 | System.out.println("save(): updatedAt: " + parseObject.getUpdatedAt());
38 | assertNotNull("objectId should not be null", parseObject.getObjectId());
39 | assertNotNull("createdAt should not be null", parseObject.getCreatedAt());
40 | assertNotNull("updatedAt should not be null", parseObject.getUpdatedAt());
41 | }
42 | catch(ParseException pe) {
43 | assertNull("save(): should not have thrown ParseException", pe);
44 | }
45 | }
46 |
47 | @Test
48 | public void get() {
49 | System.out.println("get(): initializing...");
50 | ParseRegistry.registerSubclass(Person.class);
51 | Person parseObject = new Person();
52 | parseObject.setAge(31);
53 | parseObject.setGender("female");
54 |
55 | try {
56 | parseObject.save();
57 |
58 | ParseQuery query = ParseQuery.getQuery(Person.class);
59 | Person person = query.get(parseObject.getObjectId());
60 | System.out.println("get(): objectId - " + person.getObjectId() + "-" + parseObject.getObjectId());
61 | System.out.println("get(): gender - " + person.getGender() + "-" + parseObject.getGender());
62 | System.out.println("get(): ages - " + person.getAge() + "-" + parseObject.getAge());
63 | assertFalse("get(): ObjectIds should be the same", !parseObject.getObjectId().equals(person.getObjectId()));
64 | assertFalse("get(): Ages should be the same", parseObject.getAge() != person.getAge());
65 | assertFalse("get(): Genders should be the same", !parseObject.getGender().equals(person.getGender()));
66 | }
67 | catch(ParseException pe) {
68 | assertNull("save(): should not have thrown ParseException", pe);
69 | }
70 | }
71 |
72 | @Test
73 | public void saveWithChar() {
74 | System.out.println("save(): initializing...");
75 | ParseRegistry.registerSubclass(Person.class);
76 | Person parseObject = new Person();
77 | parseObject.setAge(15);
78 | parseObject.setGender("Suíça");
79 | parseObject.getString("age");
80 |
81 | try {
82 | parseObject.save();
83 | System.out.println("save(): objectId: " + parseObject.getObjectId());
84 | System.out.println("save(): createdAt: " + parseObject.getCreatedAt());
85 | System.out.println("save(): updatedAt: " + parseObject.getUpdatedAt());
86 | assertNotNull("objectId should not be null", parseObject.getObjectId());
87 | assertNotNull("createdAt should not be null", parseObject.getCreatedAt());
88 | assertNotNull("updatedAt should not be null", parseObject.getUpdatedAt());
89 | }
90 | catch(ParseException pe) {
91 | assertNull("save(): should not have thrown ParseException", pe);
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseObjectOperationsTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertFalse;
5 |
6 | import org.junit.Test;
7 | import org.parse4j.util.MimeType;
8 |
9 | public class ParseObjectOperationsTestCase extends Parse4JTestCase {
10 |
11 | @Test(expected = IllegalArgumentException.class )
12 | public void putNullKey() {
13 | System.out.println("putNullKey(): initializing...");
14 | ParseObject parseObject = getEmptyParseObject(CLASS_NAME);
15 | parseObject.put(null, "parse developer");
16 | }
17 |
18 | @Test(expected = IllegalArgumentException.class )
19 | public void putNullValue() {
20 | System.out.println("putNullValue(): initializing...");
21 | ParseObject parseObject = getEmptyParseObject(CLASS_NAME);
22 | parseObject.put("name", null);
23 | }
24 |
25 | @Test(expected = IllegalArgumentException.class)
26 | public void incrementString() {
27 | System.out.println("incrementString(): initializing...");
28 | ParseObject parseObject = getEmptyParseObject(CLASS_NAME);
29 | parseObject.put("field", "value");
30 | parseObject.increment("field");
31 | }
32 |
33 | @Test(expected = IllegalArgumentException.class)
34 | public void decrementString() {
35 | System.out.println("decrementString(): initializing...");
36 | ParseObject parseObject = getEmptyParseObject(CLASS_NAME);
37 | parseObject.put("field", "value");
38 | parseObject.decrement("field");
39 | }
40 |
41 | @Test
42 | public void incrementNumbers() {
43 | System.out.println("incrementNumbers(): initializing...");
44 | ParseObject parseObject = getEmptyParseObject(CLASS_NAME);
45 | parseObject.put("field1", 1);
46 | parseObject.increment("field1");
47 | parseObject.put("field2", 2L);
48 | parseObject.increment("field2");
49 | parseObject.put("field3", 3.3);
50 | parseObject.increment("field3");
51 | }
52 |
53 | @Test(expected = IllegalArgumentException.class)
54 | public void invalidPutKey1() {
55 | System.out.println("invalidPutKey1(): initializing...");
56 | ParseObject parseObject = getEmptyParseObject(CLASS_NAME);
57 | parseObject.put("objectId", "value");
58 | }
59 |
60 | @Test(expected = IllegalArgumentException.class)
61 | public void invalidPutKey2() {
62 | System.out.println("invalidPutKey2(): initializing...");
63 | ParseObject parseObject = getEmptyParseObject(CLASS_NAME);
64 | parseObject.put("createdAt", "value");
65 | }
66 |
67 | @Test(expected = IllegalArgumentException.class)
68 | public void invalidPutKey3() {
69 | System.out.println("invalidPutKey3(): initializing...");
70 | ParseObject parseObject = getEmptyParseObject(CLASS_NAME);
71 | parseObject.put("updatedAt", "value");
72 | }
73 |
74 | @Test
75 | public void extension() {
76 | System.out.println("extension(): initializing...");
77 |
78 | for(String extension : MimeType.mimeTypes.keySet()) {
79 | String fileName = "test." + extension;
80 | //System.out.println("File name:" + fileName);
81 | assertEquals("Expected " + MimeType.getFileExtension(fileName), MimeType.getFileExtension(fileName), extension);
82 | }
83 |
84 | String fileName = "test";
85 | //System.out.println("File name:" + fileName);
86 | assertEquals("Expected " + MimeType.getFileExtension(fileName), MimeType.getFileExtension(fileName), "");
87 | }
88 |
89 | @Test
90 | public void extensionNotEqual() {
91 | System.out.println("extensionNotEqual(): initializing...");
92 |
93 | for(String extension : MimeType.mimeTypes.keySet()) {
94 | String fileName = "test." + extension;
95 | //System.out.println("File name:" + fileName + ", testing against: " + (extension+"x"));
96 | boolean result = (extension+"x").equals(MimeType.getFileExtension(fileName));
97 | assertFalse(result);
98 | }
99 | }
100 |
101 | @Test
102 | public void mimeType() {
103 | System.out.println("mimeType(): initializing...");
104 |
105 | for(String extension : MimeType.mimeTypes.keySet()) {
106 | String fileName = "test." + extension;
107 | //System.out.print("File name:" + fileName);
108 | String mime = MimeType.getMimeType(MimeType.getFileExtension(fileName));
109 | //System.out.println(", content-type: " + mime);
110 | assertEquals("Expected " + MimeType.getMimeType(extension), MimeType.getMimeType(extension), mime);
111 | }
112 |
113 | String fileName = "test";
114 | //System.out.print("File name:" + fileName);
115 | String mime = MimeType.getMimeType(MimeType.getFileExtension(fileName));
116 | String extension = MimeType.getFileExtension(fileName);
117 | //System.out.println(", content-type: " + mime);
118 | assertEquals("Expected " + MimeType.getMimeType(extension), MimeType.getMimeType(extension), mime);
119 |
120 | }
121 |
122 | @Test(expected = IllegalArgumentException.class)
123 | public void testFileNotSave() {
124 | System.out.println("testFileNotSave(): initializing...");
125 | try {
126 | byte[] data = getBytes("/parse.png");
127 | ParseFile file = new ParseFile("parse.png", data);
128 | ParseObject po = getParseObject(CLASS_NAME);
129 | po.put("logo", file);
130 | }
131 | catch(ParseException pe) {
132 |
133 | }
134 | }
135 |
136 | }
137 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseQueryTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import static org.junit.Assert.assertFalse;
4 | import static org.junit.Assert.assertNotNull;
5 | import static org.junit.Assert.assertNull;
6 |
7 | import java.util.Arrays;
8 | import java.util.List;
9 |
10 | import org.junit.Test;
11 | import org.parse4j.callback.CountCallback;
12 | import org.parse4j.callback.FindCallback;
13 | import org.parse4j.callback.GetCallback;
14 |
15 | public class ParseQueryTestCase extends Parse4JTestCase {
16 |
17 |
18 | @Test
19 | public void query1() {
20 | ParseQuery query = ParseQuery.getQuery("games");
21 | String[] names = {"Jonathan Walsh", "Dario Wunsch", "Shawn Simon"};
22 | query.addAscendingOrder("loosingScore")
23 | .addDescendingOrder("score2")
24 | .whereGreaterThan("score1", 6)
25 | .whereLessThanOrEqualTo("score2", 2)
26 | .whereContainedIn("playerName", Arrays.asList(names));;
27 | query.limit(10);
28 | query.skip(10);
29 | System.out.println(query.toREST());
30 | }
31 |
32 | @Test
33 | public void test1() {
34 | System.out.println("test1(): initializing...");
35 |
36 | try {
37 | ParseQuery query = ParseQuery.getQuery("games");
38 | ParseObject po = query.get("GLVPuc2X8H");
39 | assertNotNull("ObjectId should not be null", po.getObjectId());
40 | }
41 | catch(ParseException e) {
42 | assertNull("test1(): should not have thrown ParseException", e);
43 | }
44 |
45 | }
46 |
47 | @Test
48 | public void test12() {
49 | System.out.println("test12(): initializing...");
50 |
51 | ParseQuery query = ParseQuery.getQuery("games");
52 | query.getInBackground("GLVPuc2X8H", new GetCallback() {
53 |
54 | @Override
55 | public void done(ParseObject t, ParseException parseException) {
56 | assertNotNull("ObjectId should not be null", t);
57 | assertNull("test12(): should not have thrown ParseException", parseException);
58 | }
59 | });
60 | sleep(1000);
61 | }
62 |
63 | @Test
64 | public void test13() {
65 | System.out.println("test13(): initializing...");
66 |
67 | ParseQuery query = ParseQuery.getQuery("games");
68 | query.getInBackground("NOT_FOUND", new GetCallback() {
69 |
70 | @Override
71 | public void done(ParseObject t, ParseException parseException) {
72 | assertNull("ObjectId should be null", t);
73 | assertNull("test13(): should not have been trown", parseException);
74 | }
75 | });
76 | sleep(1000);
77 | }
78 |
79 | @Test
80 | public void test2() {
81 | System.out.println("test2(): initializing...");
82 |
83 | try {
84 | ParseQuery query = ParseQuery.getQuery("games");
85 | query.whereGreaterThan("losingScore", 140);
86 | List po = query.find();
87 | assertFalse("There should be 15 items on the list", po.size() != 15);
88 | }
89 | catch(ParseException e) {
90 | assertNull("test2(): should not have thrown ParseException", e);
91 | }
92 |
93 | }
94 |
95 | @Test
96 | public void test21() {
97 | System.out.println("test21(): initializing...");
98 |
99 | ParseQuery query = ParseQuery.getQuery("games");
100 | query.whereGreaterThan("losingScore", 140);
101 | query.findInBackground(new FindCallback() {
102 |
103 | @Override
104 | public void done(List list, ParseException parseException) {
105 | assertFalse("test21(): There should be 15 items on the list", list.size() != 15);
106 | assertNull("test21(): should not have thrown ParseException", parseException);
107 |
108 | }
109 | });
110 |
111 | sleep(1000);
112 | }
113 |
114 | @Test
115 | public void test22() {
116 | System.out.println("test21(): initializing...");
117 |
118 | ParseQuery query = ParseQuery.getQuery("games");
119 | query.whereGreaterThan("losingScore", 140);
120 | query.skip(4);
121 | query.findInBackground(new FindCallback() {
122 |
123 | @Override
124 | public void done(List list, ParseException parseException) {
125 | assertFalse("test21(): There should be 15 items on the list", list.size() != 11);
126 | assertNull("test21(): should not have thrown ParseException", parseException);
127 |
128 | }
129 | });
130 |
131 | sleep(1000);
132 | }
133 |
134 | @Test
135 | public void test23() {
136 | System.out.println("test21(): initializing...");
137 |
138 | ParseQuery query = ParseQuery.getQuery("games");
139 | query.whereGreaterThan("losingScore", 140);
140 | query.limit(7);
141 | query.findInBackground(new FindCallback() {
142 |
143 | @Override
144 | public void done(List list, ParseException parseException) {
145 | assertFalse("test21(): There should be 15 items on the list", list.size() != 7);
146 | assertNull("test21(): should not have thrown ParseException", parseException);
147 |
148 | }
149 | });
150 |
151 | sleep(1000);
152 | }
153 |
154 | @Test
155 | public void test3() {
156 | System.out.println("test3(): initializing...");
157 |
158 | try {
159 | ParseQuery query = ParseQuery.getQuery("games");
160 | query.whereGreaterThan("losingScore", 140)
161 | .whereLessThan("winningScore", 150)
162 | .whereStartsWith("losingTeam", "Denver");
163 | List po = query.find();
164 | assertFalse("There should be 3 items on the list", po.size() != 3);
165 | }
166 | catch(ParseException e) {
167 | assertNull("test3(): should not have thrown ParseException", e);
168 | }
169 |
170 | }
171 |
172 | @Test
173 | public void test31() {
174 | System.out.println("test31(): initializing...");
175 |
176 | ParseQuery query = ParseQuery.getQuery("games");
177 | query.whereGreaterThan("losingScore", 140)
178 | .whereLessThan("winningScore", 150)
179 | .whereStartsWith("losingTeam", "Denver");
180 | query.findInBackground(new FindCallback() {
181 |
182 | @Override
183 | public void done(List list, ParseException parseException) {
184 | assertFalse("test31(): There shoult be 3 items on the list", list.size() != 3);
185 | assertNull("test31(): should not have thrown ParseException", parseException);
186 |
187 | }
188 | });
189 |
190 | sleep(1000);
191 | }
192 |
193 | @Test
194 | public void test4() {
195 | System.out.println("test4(): initializing...");
196 |
197 | try {
198 | ParseQuery query = ParseQuery.getQuery("games");
199 | query.whereGreaterThan("losingScore", 140);
200 | int total = query.count();
201 | assertFalse("There should be 15 items on the list", total != 15);
202 | }
203 | catch(ParseException e) {
204 | assertNull("test4(): should not have thrown ParseException", e);
205 | }
206 |
207 | }
208 |
209 | @Test
210 | public void test41() {
211 | System.out.println("test41(): initializing...");
212 |
213 | ParseQuery query = ParseQuery.getQuery("games");
214 | query.whereGreaterThan("losingScore", 140);
215 | query.countInBackground(new CountCallback() {
216 |
217 | @Override
218 | public void done(Integer count, ParseException parseException) {
219 | assertFalse("test41(): There should be 15 items on the list", count != 15);
220 | assertNull("test41(): should not have thrown ParseException", parseException);
221 |
222 | }
223 | });
224 |
225 | sleep(1000);
226 | }
227 |
228 | @Test
229 | public void test5() {
230 | //selectKeys
231 | System.out.println("test5(): initializing...");
232 |
233 | try {
234 | ParseQuery query = ParseQuery.getQuery("games");
235 | query.selectKeys(Arrays.asList("losingTeam", "losingScore"));
236 | query.setTrace(true);
237 | ParseObject po = query.get("GLVPuc2X8H");
238 | assertNotNull("test5(): ObjectId should not be null", po.getObjectId());
239 | }
240 | catch(ParseException e) {
241 | assertNull("test5(): should not have thrown ParseException", e);
242 | }
243 | }
244 |
245 | @Test
246 | public void test6() {
247 | System.out.println("test6(): initializing...");
248 |
249 | try {
250 | ParseQuery query = ParseQuery.getQuery("games");
251 | ParseObject po = query.get("GLVPuc2X8H");
252 | //po.increment("losingScore", -3);
253 | //po.remove("data");
254 | //po.save();
255 | assertNotNull("test6(): ObjectId should not be null", po.getObjectId());
256 | }
257 | catch(ParseException e) {
258 | assertNull("test6(): should not have thrown ParseException", e);
259 | }
260 |
261 | }
262 |
263 | }
264 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseRelationTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import static org.junit.Assert.assertNotNull;
4 | import static org.junit.Assert.assertNull;
5 | import static org.junit.Assert.assertTrue;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Date;
9 | import java.util.List;
10 |
11 | import org.junit.Test;
12 | import org.parse4j.callback.GetCallback;
13 |
14 | public class ParseRelationTestCase extends Parse4JTestCase {
15 |
16 |
17 | @Test
18 | public void test1() throws ParseException {
19 |
20 | for(int i = 1; i < 21; i++) {
21 |
22 | // Create the post
23 | ParseObject myPost = new ParseObject("Post");
24 | myPost.put("title", "Post Number " + i);
25 | myPost.put("content", "Content for Post " + 1);
26 | myPost.save();
27 |
28 | // Create the comment
29 | ParseObject myComment = new ParseObject("Comment");
30 | myComment.put("content", "Content for Post" + i);
31 | myComment.put("parent", myPost);
32 | myComment.save();
33 |
34 | ParseQuery query = ParseQuery.getQuery("Comment");
35 | ParseObject fetchedComment = query.get(myComment.getObjectId());
36 |
37 | ParseObject postObj = fetchedComment.getParseObject("parent");
38 | postObj.fetchIfNeeded(new GetCallback() {
39 | public void done(ParseObject post, ParseException e) {
40 | String title = post.getString("title");
41 | assertNull("title should not be null", title);
42 | }
43 | });
44 |
45 | //myComment.remove("parent");
46 | //myComment.save();
47 | //postObj.delete();
48 | //myComment.delete();
49 | }
50 |
51 | }
52 |
53 | @Test
54 | public void list() throws ParseException {
55 | ParseQuery query = ParseQuery.getQuery("Comment");
56 | List list = query.find();
57 | for(ParseObject po : list) {
58 | System.out.println(po.getObjectId());
59 | po.remove("parent");
60 | po.save();
61 | }
62 | }
63 |
64 |
65 |
66 | @Test
67 | public void relation4() throws ParseException {
68 | ParseQuery query = ParseQuery.getQuery("Post");
69 | query.whereEqualTo("title", "Post Number 20");
70 |
71 | ParseQuery commentsQuery = ParseQuery.getQuery("Comment");
72 | commentsQuery.whereMatchesQuery("parent", query);
73 | List find = commentsQuery.find();
74 |
75 | assertNotNull(find);
76 | assertTrue(find.size()>1);
77 | }
78 | @Test
79 | public void relation() throws ParseException {
80 |
81 | ParseObject member = new ParseObject("Member");
82 | member.put("name", "member name");
83 | member.put("country", "brazil");
84 | member.save();
85 |
86 | ParseObject project1 = new ParseObject("Project");
87 | project1.put("name", "project name 1");
88 | project1.put("start", new Date());
89 | project1.save();
90 |
91 | ParseObject project2 = new ParseObject("Project");
92 | project2.put("name", "project name 2");
93 | project2.put("start", new Date());
94 | project2.save();
95 |
96 | ParseRelation relation = member.getRelation("projects");
97 | relation.add(project1);
98 | relation.add(project2);
99 | member.save();
100 |
101 | ParseQuery query = ParseQuery.getQuery("Member");
102 | ParseObject fetchedMember = query.get(member.getObjectId());
103 |
104 | ParseRelation fetchedRelations = member.getRelation("projects");
105 | ParseQuery fetchQuery = fetchedRelations.getQuery();
106 | List list = fetchQuery.find();
107 |
108 | }
109 |
110 | @Test
111 | public void relation3() throws ParseException {
112 |
113 | ParseQuery query = ParseQuery.getQuery("Member");
114 | ParseObject member = query.get("8EOuUQSV38");
115 |
116 | ParseRelation fetchedRelations = member.getRelation("projects");
117 | ParseQuery fetchQuery = fetchedRelations.getQuery();
118 | List list = fetchQuery.find();
119 | for(ParseObject po : list) {
120 | System.out.println(po.getDate("start"));
121 | }
122 | }
123 |
124 | @Test
125 | public void relation2() throws ParseException {
126 |
127 | ParseObject member = new ParseObject("GameScore");
128 | member.put("date", new Date());
129 | member.put("local", "usa");
130 | member.save();
131 |
132 | ParseObject project1 = new ParseObject("Team");
133 | project1.put("name", "Team C");
134 | project1.save();
135 |
136 | ParseObject project2 = new ParseObject("Team");
137 | project2.put("name", "Team D");
138 | project2.save();
139 |
140 | ParseRelation relation = member.getRelation("opponents");
141 | relation.add(project1);
142 | //relation.add(project2);
143 | member.save();
144 |
145 | ParseQuery query = ParseQuery.getQuery("GameScore");
146 | ParseObject fetchedMember = query.get(member.getObjectId());
147 |
148 | ParseRelation fetchedRelations = member.getRelation("opponents");
149 | }
150 |
151 |
152 | @Test
153 | public void arrayParseObject() {
154 |
155 | // let's say we have four weapons
156 | ParseObject scimitar = new ParseObject("weapon");
157 | scimitar.put("name", "scimitar");
158 | ParseObject plasmaRifle = new ParseObject("weapon");
159 | plasmaRifle.put("name", "plasmaRifle");
160 | ParseObject grenade = new ParseObject("weapon");
161 | grenade.put("name", "grenade");
162 | ParseObject bunnyRabbit = new ParseObject("weapon");
163 | bunnyRabbit.put("name", "bunnyRabbit");
164 |
165 | // stick the objects in an array
166 | ArrayList weapons = new ArrayList();
167 | weapons.add(scimitar);
168 | weapons.add(plasmaRifle);
169 | weapons.add(grenade);
170 | weapons.add(bunnyRabbit);
171 |
172 | ParseObject soldier = new ParseObject("soldier");
173 | soldier.put("name", "soldier");
174 |
175 |
176 | }
177 |
178 | @Test
179 | public void arrayStrings() throws ParseException {
180 |
181 | // stick the objects in an array
182 | ArrayList weapons = new ArrayList();
183 | weapons.add("scimitar");
184 | weapons.add("plasmaRifle");
185 | weapons.add("grenade");
186 | weapons.add("bunnyRabbit");
187 |
188 | ParseObject soldier = new ParseObject("soldier");
189 | soldier.put("name", "soldier");
190 | soldier.put("weapons", weapons);
191 | soldier.save();
192 |
193 | ParseQuery query = ParseQuery.getQuery("soldier");
194 | ParseObject fetchedSoldier = query.get(soldier.getObjectId());
195 | System.out.println(fetchedSoldier.getList("weapons"));
196 |
197 | }
198 |
199 | }
200 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/ParseUserTestCase.java:
--------------------------------------------------------------------------------
1 | package org.parse4j;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.UUID;
6 |
7 | import static org.hamcrest.CoreMatchers.is;
8 | import static org.hamcrest.CoreMatchers.notNullValue;
9 | import static org.junit.Assert.*;
10 |
11 | public class ParseUserTestCase extends Parse4JTestCase {
12 |
13 | @Test(expected = IllegalArgumentException.class)
14 | public void signupNoUsername() {
15 | System.out.println("signupNoUsername(): initializing...");
16 |
17 | ParseUser parseUser = new ParseUser();
18 | try {
19 | parseUser.signUp();
20 | } catch (ParseException e) {
21 | assertNull("ParseException should be null", e);
22 | }
23 |
24 | }
25 |
26 | @Test(expected = IllegalArgumentException.class)
27 | public void signupNoPassword() {
28 | System.out.println("signupNoPassword(): initializing...");
29 |
30 | ParseUser parseUser = new ParseUser();
31 | try {
32 | parseUser.setUsername("parse4j-user");
33 | parseUser.signUp();
34 | } catch (ParseException e) {
35 | assertNull("ParseException should be null", e);
36 | }
37 |
38 | }
39 |
40 | @Test(expected = IllegalArgumentException.class)
41 | public void signupWithObjectId() {
42 | System.out.println("signupWithObjectId(): initializing...");
43 |
44 | ParseUser parseUser = new ParseUser();
45 | try {
46 | parseUser.setUsername("parse4j-user");
47 | parseUser.setPassword("parse4j-password");
48 | parseUser.setObjectId("tempObjectId");
49 | parseUser.signUp();
50 | } catch (ParseException e) {
51 | assertNull("ParseException should be null", e);
52 | }
53 |
54 | }
55 |
56 | @Test public void
57 | sign_up_and_delete_an_user() throws ParseException {
58 | final String number = UUID.randomUUID().toString();
59 | ParseUser parseUser = getParseUser(number);
60 | parseUser.signUp();
61 | assertThat(parseUser.getObjectId(), is(notNullValue()));
62 | assertThat(parseUser.getSessionToken(), is(notNullValue()));
63 | assertThat(parseUser.getSessionToken(), is(notNullValue()));
64 |
65 | parseUser.delete();
66 | }
67 |
68 | @Test(expected = ParseException.class)
69 | public void signupExistingUsername() throws ParseException {
70 | System.out.println("signupExistingUsername(): initializing...");
71 |
72 | ParseUser parseUser = getParseUser("2");
73 | parseUser.signUp();
74 |
75 | parseUser = getParseUser("2");
76 | parseUser.signUp();
77 |
78 | assertNotNull("objectId should not be null", parseUser.getObjectId());
79 | assertNotNull("createdAt should not be null", parseUser.getCreatedAt());
80 | assertNotNull("sessionToken should not be null", parseUser.getSessionToken());
81 | }
82 |
83 | @Test public void
84 | login() throws ParseException {
85 | final String number = UUID.randomUUID().toString();
86 | ParseUser pu = getParseUser(number);
87 | pu.signUp();
88 |
89 | ParseUser parseUser = ParseUser.login(pu.getUsername(), "parse4j-password");
90 |
91 | assertThat(parseUser.getString("city"), is("westbury"));
92 | assertThat(parseUser.getString("state"), is("ny"));
93 |
94 | assertThat(parseUser.getObjectId(), is(notNullValue()));
95 | assertThat(parseUser.getSessionToken(), is(notNullValue()));
96 | assertThat(parseUser.getSessionToken(), is(notNullValue()));
97 |
98 | pu.delete();
99 | }
100 |
101 | @Test public void
102 | verify_email() throws ParseException {
103 | final String number = UUID.randomUUID().toString();
104 | ParseUser parseUser = getParseUser(number);
105 | parseUser.signUp();
106 |
107 | ParseUser.requestPasswordReset(parseUser.getEmail());
108 |
109 | parseUser.delete();
110 | }
111 |
112 | @Test(expected = ParseException.class)
113 | public void verifyInvalidEmail() throws ParseException {
114 | System.out.println("verifyEmail(): initializing...");
115 |
116 | try {
117 | ParseUser.requestPasswordReset("invalid@gamil.com");
118 | } catch (ParseException e) {
119 | throw e;
120 | }
121 |
122 | }
123 |
124 |
125 | }
126 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/bolts/TestBolts.java:
--------------------------------------------------------------------------------
1 | package org.parse4j.bolts;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertTrue;
5 |
6 | import java.util.List;
7 | import java.util.concurrent.Callable;
8 |
9 | import org.junit.Test;
10 | import org.parse4j.Parse4JTestCase;
11 | import org.parse4j.ParseObject;
12 | import org.parse4j.ParseQuery;
13 |
14 | public class TestBolts extends Parse4JTestCase {
15 |
16 | @Test
17 | public void testBackgroundCallWaiting() throws Exception {
18 |
19 | Task> task = Task.callInBackground(new Callable>() {
20 |
21 | @Override
22 | public List call() throws Exception {
23 | ParseQuery query = ParseQuery.getQuery("games");
24 | query.whereGreaterThan("losingScore", 140);
25 | query.skip(4);
26 | System.out.println("before running");
27 | return query.find();
28 | }
29 |
30 | });
31 |
32 | //task.waitForCompletion();
33 | assertTrue(task.isCompleted());
34 | assertEquals(11, task.getResult().size());
35 | System.out.println("finish");
36 | }
37 |
38 | @Test
39 | public void testForResult() throws Exception {
40 | ParseQuery query = ParseQuery.getQuery("games");
41 | query.whereGreaterThan("losingScore", 140);
42 | query.skip(4);
43 | Task> task = Task.forResult(query.find());
44 |
45 | //task.waitForCompletion();
46 | assertTrue(task.isCompleted());
47 | assertEquals(11, task.getResult().size());
48 | }
49 |
50 |
51 | @Test
52 | public void testContinuationWith() throws InterruptedException {
53 |
54 |
55 | Task> task = Task.callInBackground(new Callable>() {
56 |
57 | @Override
58 | public List call() throws Exception {
59 | ParseQuery query = ParseQuery.getQuery("games");
60 | query.whereGreaterThan("losingScore", 140);
61 | query.skip(4);
62 | return query.find();
63 | }
64 |
65 | }).continueWith(new Continuation, List>() {
66 |
67 | @Override
68 | public List then(Task> task) throws Exception {
69 | System.out.println("completed");
70 | return null;
71 | }
72 |
73 | }).onSuccess(new Continuation, List>() {
74 |
75 | @Override
76 | public List then(Task> task) throws Exception {
77 | System.out.println("onSucess 1");
78 | return null;
79 | }
80 |
81 | }).onSuccess(new Continuation, List>() {
82 |
83 | @Override
84 | public List then(Task> task) throws Exception {
85 | System.out.println("onSucess 2");
86 | return null;
87 | }
88 |
89 | }).onSuccess(new Continuation, List>() {
90 |
91 | @Override
92 | public List then(Task> task) throws Exception {
93 | System.out.println("onSucess 3");
94 | return null;
95 | }
96 |
97 | });
98 |
99 | task.waitForCompletion();
100 | }
101 |
102 | }
103 |
--------------------------------------------------------------------------------
/src/test/java/org/parse4j/bolts/TestTask.java:
--------------------------------------------------------------------------------
1 | package org.parse4j.bolts;
2 |
3 | import java.util.ArrayList;
4 | import java.util.concurrent.Callable;
5 | import java.util.concurrent.CancellationException;
6 | import java.util.concurrent.Executors;
7 | import java.util.concurrent.atomic.AtomicInteger;
8 |
9 | import junit.framework.TestCase;
10 |
11 | public class TestTask extends TestCase {
12 |
13 | private void runTaskTest(Callable> callable) {
14 | try {
15 | Task> task = callable.call();
16 | task.waitForCompletion();
17 | if (task.isFaulted()) {
18 | Exception error = task.getError();
19 | if (error instanceof RuntimeException) {
20 | throw (RuntimeException) error;
21 | }
22 | throw new RuntimeException(error);
23 | } else if (task.isCancelled()) {
24 | throw new RuntimeException(new CancellationException());
25 | }
26 | } catch (Exception e) {
27 | throw new RuntimeException(e);
28 | }
29 | }
30 |
31 | public void testPrimitives() {
32 | Task complete = Task.forResult(5);
33 | Task error = Task.forError(new RuntimeException());
34 | Task cancelled = Task.cancelled();
35 |
36 | assertTrue(complete.isCompleted());
37 | assertEquals(5, complete.getResult().intValue());
38 | assertFalse(complete.isFaulted());
39 | assertFalse(complete.isCancelled());
40 |
41 | assertTrue(error.isCompleted());
42 | assertTrue(error.getError() instanceof RuntimeException);
43 | assertTrue(error.isFaulted());
44 | assertFalse(error.isCancelled());
45 |
46 | assertTrue(cancelled.isCompleted());
47 | assertFalse(cancelled.isFaulted());
48 | assertTrue(cancelled.isCancelled());
49 | }
50 |
51 | public void testSynchronousContinuation() {
52 |
53 | final Task complete = Task.forResult(5);
54 | final Task error = Task.forError(new RuntimeException());
55 | final Task cancelled = Task.cancelled();
56 |
57 | complete.continueWith(new Continuation() {
58 | public Void then(Task task) {
59 | assertEquals(complete, task);
60 | assertTrue(task.isCompleted());
61 | assertEquals(5, task.getResult().intValue());
62 | assertFalse(task.isFaulted());
63 | assertFalse(task.isCancelled());
64 | return null;
65 | }
66 | });
67 |
68 | error.continueWith(new Continuation() {
69 | public Void then(Task task) {
70 | assertEquals(error, task);
71 | assertTrue(task.isCompleted());
72 | assertTrue(task.getError() instanceof RuntimeException);
73 | assertTrue(task.isFaulted());
74 | assertFalse(task.isCancelled());
75 | return null;
76 | }
77 | });
78 |
79 | cancelled.continueWith(new Continuation() {
80 | public Void then(Task task) {
81 | assertEquals(cancelled, task);
82 | assertTrue(cancelled.isCompleted());
83 | assertFalse(cancelled.isFaulted());
84 | assertTrue(cancelled.isCancelled());
85 | return null;
86 | }
87 | });
88 | }
89 |
90 | public void testSynchronousChaining() {
91 | Task first = Task.forResult(1);
92 | Task second = first
93 | .continueWith(new Continuation() {
94 | public Integer then(Task task) {
95 | return 2;
96 | }
97 | });
98 | Task third = second
99 | .continueWithTask(new Continuation>() {
100 | public Task then(Task task) {
101 | return Task.forResult(3);
102 | }
103 | });
104 | assertTrue(first.isCompleted());
105 | assertTrue(second.isCompleted());
106 | assertTrue(third.isCompleted());
107 | assertEquals(1, first.getResult().intValue());
108 | assertEquals(2, second.getResult().intValue());
109 | assertEquals(3, third.getResult().intValue());
110 | }
111 |
112 | public void testBackgroundCall() {
113 | runTaskTest(new Callable>() {
114 | public Task> call() throws Exception {
115 | return Task.callInBackground(new Callable() {
116 | public Integer call() throws Exception {
117 | Thread.sleep(100);
118 | return 5;
119 | }
120 | }).continueWith(new Continuation() {
121 | public Void then(Task task) {
122 | assertEquals(5, task.getResult().intValue());
123 | return null;
124 | }
125 | });
126 | }
127 | });
128 | }
129 |
130 | public void testBackgroundCallWaiting() throws Exception {
131 | Task task = Task.callInBackground(new Callable() {
132 | public Integer call() throws Exception {
133 | Thread.sleep(100);
134 | return 5;
135 | }
136 | });
137 | task.waitForCompletion();
138 | assertTrue(task.isCompleted());
139 | assertEquals(5, task.getResult().intValue());
140 | }
141 |
142 | public void testBackgroundCallWaitingOnError() throws Exception {
143 | Task task = Task.callInBackground(new Callable() {
144 | public Integer call() throws Exception {
145 | Thread.sleep(100);
146 | throw new RuntimeException();
147 | }
148 | });
149 | task.waitForCompletion();
150 | assertTrue(task.isCompleted());
151 | assertTrue(task.isFaulted());
152 | }
153 |
154 | public void testBackgroundCallWaitOnCancellation() throws Exception {
155 | Task task = Task.callInBackground(new Callable() {
156 | public Integer call() throws Exception {
157 | Thread.sleep(100);
158 | return 5;
159 | }
160 | }).continueWithTask(new Continuation>() {
161 |
162 | public Task then(Task task) {
163 | return Task.cancelled();
164 | }
165 | });
166 | task.waitForCompletion();
167 | assertTrue(task.isCompleted());
168 | assertTrue(task.isCancelled());
169 | }
170 |
171 | public void testBackgroundError() {
172 | runTaskTest(new Callable>() {
173 | public Task> call() throws Exception {
174 | return Task.callInBackground(new Callable() {
175 | public Integer call() throws Exception {
176 | throw new IllegalStateException();
177 | }
178 | }).continueWith(new Continuation() {
179 | public Void then(Task task) {
180 | assertTrue(task.isFaulted());
181 | assertTrue(task.getError() instanceof IllegalStateException);
182 | return null;
183 | }
184 | });
185 | }
186 | });
187 | }
188 |
189 | public void testWhenAllSuccess() {
190 | runTaskTest(new Callable>() {
191 | @Override
192 | public Task> call() throws Exception {
193 | final ArrayList> tasks = new ArrayList>();
194 | for (int i = 0; i < 20; i++) {
195 | Task task = Task
196 | .callInBackground(new Callable() {
197 | @Override
198 | public Void call() throws Exception {
199 | Thread.sleep((long) (Math.random() * 1000));
200 | return null;
201 | }
202 | });
203 | tasks.add(task);
204 | }
205 | return Task.whenAll(tasks).continueWith(
206 | new Continuation() {
207 | @Override
208 | public Void then(Task task) {
209 | assertTrue(task.isCompleted());
210 | assertFalse(task.isFaulted());
211 | assertFalse(task.isCancelled());
212 |
213 | for (Task t : tasks) {
214 | assertTrue(t.isCompleted());
215 | }
216 | return null;
217 | }
218 | });
219 | }
220 | });
221 | }
222 |
223 | public void testWhenAllOneError() {
224 | final Exception error = new RuntimeException("This task failed.");
225 |
226 | runTaskTest(new Callable>() {
227 | @Override
228 | public Task> call() throws Exception {
229 | final ArrayList> tasks = new ArrayList>();
230 | for (int i = 0; i < 20; i++) {
231 | final int number = i;
232 | Task task = Task
233 | .callInBackground(new Callable() {
234 | @Override
235 | public Void call() throws Exception {
236 | Thread.sleep((long) (Math.random() * 1000));
237 | if (number == 10) {
238 | throw error;
239 | }
240 | return null;
241 | }
242 | });
243 | tasks.add(task);
244 | }
245 | return Task.whenAll(tasks).continueWith(
246 | new Continuation() {
247 | @Override
248 | public Void then(Task