@Override
  public void userStartedBroadcasting(User user, Stream stream) {

    List<User> friends = this.friendshipService.findAllFriendsOfUser(user.getId());
    for (User userToNotify : friends) {
      if (userToNotify == null
          || userToNotify.getAccount() == null
          || !StringUtils.hasText(userToNotify.getAccount().getPushNotificationID())) {
        continue;
      }

      if (ObjectUtils.nullSafeEquals(user, userToNotify)) {
        // do not notify current user
        continue;
      }

      final ParseRequest request = new ParseRequest();
      IOSNotification iosNotification = new IOSNotification(NotificationType.BROADCAST_STARTED);
      iosNotification.setUserId(user.getId());
      iosNotification.setUserName(user.getUserName());
      iosNotification.setAlert(stream.getText());
      iosNotification.setBadge("Increment");
      iosNotification.setCategory("pass_watch");

      final ParseQuery query = new ParseQuery(userToNotify.getAccount().getPushNotificationID());
      request.setWhere(query);
      request.setData(iosNotification);

      try {
        HttpEntity<ParseRequest> requestEntity = new HttpEntity<ParseRequest>(request);
        ParseResponse response =
            this.parseRestTemplate.postForObject(
                PARSE_POST_PUSH_URL, requestEntity, ParseResponse.class);
        if (response.getError() != null) {
          System.out.println("PARSE PUSH NOTIFICATIOn ERROR: " + response.getError());
        }
      } catch (Exception e) {
        log.error("Error while sending notification to Parse for iOS clients", e);
      }
    }
  }
Ejemplo n.º 2
0
  /**
   * Returns the unsigned {@code int} value represented by the given string.
   *
   * <p>Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
   *
   * <ul>
   *   <li>{@code 0x}<i>HexDigits</i>
   *   <li>{@code 0X}<i>HexDigits</i>
   *   <li>{@code #}<i>HexDigits</i>
   *   <li>{@code 0}<i>OctalDigits</i>
   * </ul>
   *
   * @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value
   * @since 13.0
   */
  public static int decode(String stringValue) {
    ParseRequest request = ParseRequest.fromString(stringValue);

    try {
      return parseUnsignedInt(request.rawValue, request.radix);
    } catch (NumberFormatException e) {
      NumberFormatException decodeException =
          new NumberFormatException("Error parsing value: " + stringValue);
      decodeException.initCause(e);
      throw decodeException;
    }
  }
  @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
  public void test4XXThrowsException() throws Exception {
    ParseRequest.setDefaultInitialRetryDelay(1L);
    InputStream mockInputStream =
        new ByteArrayInputStream("An Error occurred while saving".getBytes());
    ParseHttpResponse mockResponse = mock(ParseHttpResponse.class);
    when(mockResponse.getStatusCode()).thenReturn(400);
    when(mockResponse.getTotalSize()).thenReturn(0L);
    when(mockResponse.getReasonPhrase()).thenReturn("Bad Request");
    when(mockResponse.getContent()).thenReturn(mockInputStream);

    ParseHttpClient mockHttpClient = mock(ParseHttpClient.class);
    when(mockHttpClient.execute(any(ParseHttpRequest.class))).thenReturn(mockResponse);

    ParseAWSRequest request = new ParseAWSRequest(ParseHttpRequest.Method.GET, "http://parse.com");
    Task<byte[]> task = request.executeAsync(mockHttpClient);
    task.waitForCompletion();

    assertTrue(task.isFaulted());
    assertTrue(task.getError() instanceof ParseException);
    ParseException error = (ParseException) task.getError();
    assertEquals(error.getCode(), ParseException.CONNECTION_FAILED);
    assertTrue(error.getMessage().contains("Download from S3"));
  }
 @Override
 protected void tearDown() throws Exception {
   ParseRequest.setDefaultInitialRetryDelay(ParseRequest.DEFAULT_INITIAL_RETRY_DELAY);
   super.tearDown();
 }
Ejemplo n.º 5
0
  /**
   * Authenticates this client as belonging to your application.
   *
   * <p>This method is only required if you intend to use a different {@code applicationId} or
   * {@code clientKey} than is defined by {@code com.parse.APPLICATION_ID} or {@code
   * com.parse.CLIENT_KEY} in your {@code AndroidManifest.xml}.
   *
   * <p>This must be called before your application can use the Parse library. The recommended way
   * is to put a call to {@code Parse.initialize} in your {@code Application}'s {@code onCreate}
   * method:
   *
   * <p>
   *
   * <pre>
   * public class MyApplication extends Application {
   *   public void onCreate() {
   *     Parse.initialize(this, &quot;your application id&quot;, &quot;your client key&quot;);
   *   }
   * }
   * </pre>
   *
   * @param context The active {@link Context} for your application.
   * @param applicationId The application id provided in the Parse dashboard.
   * @param clientKey The client key provided in the Parse dashboard.
   */
  public static void initialize(Context context, String applicationId, String clientKey) {
    ParsePlugins.Android.initialize(context, applicationId, clientKey);
    Context applicationContext = context.getApplicationContext();

    ParseHttpClient.setKeepAlive(true);
    ParseHttpClient.setMaxConnections(20);
    ParseRequest.setDefaultClient(ParsePlugins.get().restClient());
    // If we have interceptors in list, we have to initialize all http clients and add interceptors
    if (interceptors != null) {
      initializeParseHttpClientsWithParseNetworkInterceptors();
    }

    ParseObject.registerParseSubclasses();

    if (isLocalDatastoreEnabled()) {
      offlineStore = new OfflineStore(context);
    } else {
      ParseKeyValueCache.initialize(context);
    }

    // Make sure the data on disk for Parse is for the current
    // application.
    checkCacheApplicationId();
    new Thread("Parse.initialize Disk Check & Starting Command Cache") {
      @Override
      public void run() {
        // Trigger the command cache to flush its contents.
        getEventuallyQueue();
      }
    }.start();

    ParseFieldOperations.registerDefaultDecoders();

    if (!allParsePushIntentReceiversInternal()) {
      throw new SecurityException(
          "To prevent external tampering to your app's notifications, "
              + "all receivers registered to handle the following actions must have "
              + "their exported attributes set to false: com.parse.push.intent.RECEIVE, "
              + "com.parse.push.intent.OPEN, com.parse.push.intent.DELETE");
    }

    // May need to update GCM registration ID if app version has changed.
    // This also primes current installation.
    GcmRegistrar.getInstance()
        .registerAsync()
        .continueWithTask(
            new Continuation<Void, Task<Void>>() {
              @Override
              public Task<Void> then(Task<Void> task) throws Exception {
                // Prime current user in the background
                return ParseUser.getCurrentUserAsync().makeVoid();
              }
            })
        .continueWith(
            new Continuation<Void, Void>() {
              @Override
              public Void then(Task<Void> task) throws Exception {
                // Prime config in the background
                ParseConfig.getCurrentConfig();
                return null;
              }
            },
            Task.BACKGROUND_EXECUTOR);

    if (ManifestInfo.getPushType() == PushType.PPNS) {
      PushService.startServiceIfRequired(applicationContext);
    }

    dispatchOnParseInitialized();

    // FYI we probably don't want to do this if we ever add other callbacks.
    synchronized (MUTEX_CALLBACKS) {
      Parse.callbacks = null;
    }
  }
  public List<TaggedPositionRegion<TokenTag<Token>>> getHighlights(int startOffset, int endOffset) {
    List<TaggedPositionRegion<TokenTag<Token>>> tags = new ArrayList<>();
    boolean updateOffsets = true;

    if (endOffset == Integer.MAX_VALUE) {
      endOffset = snapshot.length();
    }

    OffsetRegion span = OffsetRegion.fromBounds(startOffset, endOffset);

    if (failedTimeout) {
      return tags;
    }

    boolean spanExtended = false;

    int extendMultiLineSpanToLine = 0;
    OffsetRegion extendedSpan = span;

    synchronized (lock) {
      OffsetRegion requestedSpan = span;

      ParseRequest<TState> request = adjustParseSpan(span);
      TState startState = request.getState();
      span = request.getRegion();

      CharStream input;
      try {
        input = createInputStream(span);
      } catch (BadLocationException ex) {
        LOGGER.log(Level.WARNING, ex.getMessage(), ex);
        return tags;
      }

      TokenSourceWithStateV4<TState> lexer = createLexer(input, startState);
      lexer.setTokenFactory(new DocumentSnapshotTokenFactory(getEffectiveTokenSource(lexer)));

      Token previousToken = null;
      boolean previousTokenEndsLine = false;

      /* this is held outside the loop because only tokens which end at the end of a line
       * impact its value.
       */
      boolean lineStateChanged = false;

      while (true) {
        // TODO: perform this under a read lock
        Token token = lexer.nextToken();

        // The latter is true for EOF token with span.getEnd() at the end of the document
        boolean inBounds =
            token.getStartIndex() < span.getEnd() || token.getStopIndex() < span.getEnd();

        if (updateOffsets) {
          int startLineCurrent;
          if (token.getType() == Token.EOF) startLineCurrent = snapshot.getLineCount();
          else startLineCurrent = snapshot.findLineNumber(token.getStartIndex());

          // endLinePrevious is the line number the previous token ended on
          int endLinePrevious;
          if (previousToken != null)
            endLinePrevious = snapshot.findLineNumber(previousToken.getStopIndex() + 1);
          else endLinePrevious = snapshot.findLineNumber(span.getStart()) - 1;

          if (startLineCurrent > endLinePrevious + 1
              || (startLineCurrent == endLinePrevious + 1 && !previousTokenEndsLine)) {
            int firstMultilineLine = endLinePrevious;
            if (previousToken == null || previousTokenEndsLine) firstMultilineLine++;

            for (int i = firstMultilineLine; i < startLineCurrent; i++) {
              if (!lineStates.get(i).getIsMultiLineToken() || lineStateChanged)
                extendMultiLineSpanToLine = i + 1;

              if (inBounds) setLineState(i, lineStates.get(i).createMultiLineState());
            }
          }
        }

        if (token.getType() == Token.EOF) break;

        if (updateOffsets && isMultiLineToken(lexer, token)) {
          int startLine = snapshot.findLineNumber(token.getStartIndex());
          int stopLine = snapshot.findLineNumber(token.getStopIndex() + 1);
          for (int i = startLine; i < stopLine; i++) {
            if (!lineStates.get(i).getIsMultiLineToken()) extendMultiLineSpanToLine = i + 1;

            if (inBounds) setLineState(i, lineStates.get(i).createMultiLineState());
          }
        }

        boolean tokenEndsLine = tokenEndsAtEndOfLine(lexer, token);
        if (updateOffsets && tokenEndsLine) {
          TState stateAtEndOfLine = lexer.getCurrentState();
          int line = snapshot.findLineNumber(token.getStopIndex() + 1);
          lineStateChanged =
              lineStates.get(line).getIsMultiLineToken()
                  || !lineStates.get(line).equals(stateAtEndOfLine);

          // even if the state didn't change, we call SetLineState to make sure the
          // _first/_lastChangedLine values get updated.
          // have to check bounds for this one or the editor might not get an update (if the token
          // ends a line)
          if (updateOffsets && inBounds) setLineState(line, stateAtEndOfLine);

          if (lineStateChanged) {
            if (line < snapshot.getLineCount() - 1) {
              /* update the span's end position or the line state change won't be reflected
               * in the editor
               */
              int endPosition =
                  line < snapshot.getLineCount() - 2
                      ? snapshot.findLineFromLineNumber(line + 2).getStart().getOffset()
                      : snapshot.length();
              if (endPosition > extendedSpan.getEnd()) {
                spanExtended = true;
                extendedSpan = OffsetRegion.fromBounds(extendedSpan.getStart(), endPosition);
              }
            }
          }
        }

        if (token.getStartIndex() >= span.getEnd()) {
          break;
        }

        previousToken = token;
        previousTokenEndsLine = tokenEndsLine;

        if (token.getStopIndex() < requestedSpan.getStart()) {
          continue;
        }

        Collection<TaggedPositionRegion<TokenTag<Token>>> tokenClassificationSpans =
            getTagsForToken(token);
        if (tokenClassificationSpans != null) {
          tags.addAll(tokenClassificationSpans);
        }

        if (!inBounds) {
          break;
        }
      }
    }

    if (updateOffsets && extendMultiLineSpanToLine > 0) {
      int endPosition =
          extendMultiLineSpanToLine < snapshot.getLineCount() - 1
              ? snapshot
                  .findLineFromLineNumber(extendMultiLineSpanToLine + 1)
                  .getStart()
                  .getOffset()
              : snapshot.length();
      if (endPosition > extendedSpan.getEnd()) {
        spanExtended = true;
        extendedSpan = OffsetRegion.fromBounds(extendedSpan.getStart(), endPosition);
      }
    }

    if (updateOffsets && spanExtended) {
      /* Subtract 1 from each of these because the spans include the line break on their last
       * line, forcing it to appear as the first position on the following line.
       */
      assert extendedSpan.getEnd() > span.getEnd();
      int firstLine = snapshot.findLineNumber(span.getEnd());
      int lastLine = snapshot.findLineNumber(extendedSpan.getEnd()) - 1;
      // when considering the last line of a document, span and extendedSpan may end on the same
      // line
      forceRehighlightLines(firstLine, Math.max(firstLine, lastLine));
    }

    return tags;
  }