private void cancelRequest(@NotNull Runnable request, @NotNull List<Request> list) {
   for (int i = list.size() - 1; i >= 0; i--) {
     Request r = list.get(i);
     if (r.getTask() == request) {
       r.cancel();
       list.remove(i);
     }
   }
 }
 private int cancelAllRequests(@NotNull List<Request> list) {
   int count = 0;
   for (Request request : list) {
     count++;
     request.cancel();
   }
   list.clear();
   return count;
 }
Exemple #3
0
  private void processRequest(DataInputStream in) throws IOException {

    long serverId = in.readLong();

    ServerObject server = servingById.get(serverId);

    long requestId = in.readLong();
    Request r = new Request(this, server.getObject());
    r.deserialize(in);
    r.invoke();
    if (requestId != -1) {
      sendResponse(requestId, r.getResult(), r.getResultDeclaredType());
    }
  }
Exemple #4
0
  private void processResponse(DataInputStream in) throws IOException {
    long requestId = in.readLong();
    Request r = requests.remove(requestId);

    if (r == null) {
      throw new IllegalStateException(
          "Request " + requestId + " is unknown (last request generated was " + nextRequest.get());
    }

    Object o = null;
    if (in.readBoolean()) {
      o = serializerFor(classForName(in.readUTF()), r.getResultDeclaredType()).deserialize(in);
    }
    r.set(o);
  }
 private void _add(@NotNull Request requestToSchedule) {
   final ScheduledFuture<?> future =
       JobScheduler.getScheduler()
           .schedule(requestToSchedule, requestToSchedule.myDelay, TimeUnit.MILLISECONDS);
   requestToSchedule.setFuture(future);
   myRequests.add(requestToSchedule);
 }
Exemple #6
0
 private void sendRequest(long objectId, long requestId, Request r) throws IOException {
   DataOutputStream out = newFlusher();
   out.writeByte(REQUEST);
   out.writeLong(objectId);
   out.writeLong(requestId);
   r.serialize(out);
   out.writeBoolean(false);
   out.flush();
 }
  @Override
  public <T> ListenableFuture<T> execute(Request request, AsyncHandler<T> handler)
      throws IOException {
    final Expectation expectation = expectations.get(new URL(request.getUrl()));
    if (expectation == null) {
      throw new RuntimeException("Unknown URL requested, failing test: " + request.getUrl());
    }
    fulfilledExpectations.add(expectation);
    T t = null;
    try {
      final URI uri = expectation.getUrl().toURI();
      handler.onStatusReceived(
          new HttpResponseStatus(uri, this) {
            @Override
            public int getStatusCode() {
              return expectation.getStatusCode();
            }

            @Override
            public String getStatusText() {
              return ""; // TODO
            }

            @Override
            public String getProtocolName() {
              return expectation.getUrl().getProtocol();
            }

            @Override
            public int getProtocolMajorVersion() {
              return 1;
            }

            @Override
            public int getProtocolMinorVersion() {
              return 1;
            }

            @Override
            public String getProtocolText() {
              return ""; // TODO
            }
          });
      handler.onHeadersReceived(
          new HttpResponseHeaders(uri, this) {
            @Override
            public FluentCaseInsensitiveStringsMap getHeaders() {
              return new FluentCaseInsensitiveStringsMap();
            }
          });
      handler.onBodyPartReceived(
          new HttpResponseBodyPart(uri, this) {
            @Override
            public byte[] getBodyPartBytes() {
              return expectation.getPayload().getBytes(Charset.forName("UTF-8"));
            }

            @Override
            public int writeTo(OutputStream outputStream) throws IOException {
              final byte[] bodyPartBytes = getBodyPartBytes();
              outputStream.write(bodyPartBytes);
              return bodyPartBytes.length;
            }

            @Override
            public ByteBuffer getBodyByteBuffer() {
              return ByteBuffer.wrap(getBodyPartBytes());
            }

            @Override
            public boolean isLast() {
              return true;
            }

            @Override
            public void markUnderlyingConnectionAsClosed() {}

            @Override
            public boolean closeUnderlyingConnection() {
              return true;
            }
          });
      t = handler.onCompleted();
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
    final T finalT = t;
    final Future<T> futureT =
        Executors.newSingleThreadExecutor()
            .submit(
                new Callable<T>() {
                  @Override
                  public T call() throws Exception {
                    return finalT;
                  }
                });
    return new ImmediateFuture<>(futureT);
  }
Exemple #8
0
 @Override
 public void writeTo(DataOutput out) throws Exception {
   super.writeTo(out);
   out.writeLong(threadId);
 }
Exemple #9
0
 @Override
 public void readFrom(DataInput in) throws Exception {
   super.readFrom(in);
   threadId = in.readLong();
 }
Exemple #10
0
  static Response publishInstallAndWaitForResponse(
      final Context context, final String applicationId, final boolean isAutoPublish) {
    try {
      if (context == null || applicationId == null) {
        throw new IllegalArgumentException("Both context and applicationId must be non-null");
      }
      AttributionIdentifiers identifiers =
          AttributionIdentifiers.getAttributionIdentifiers(context);
      SharedPreferences preferences =
          context.getSharedPreferences(ATTRIBUTION_PREFERENCES, Context.MODE_PRIVATE);
      String pingKey = applicationId + "ping";
      String jsonKey = applicationId + "json";
      long lastPing = preferences.getLong(pingKey, 0);
      String lastResponseJSON = preferences.getString(jsonKey, null);

      // prevent auto publish from occurring if we have an explicit call.
      if (!isAutoPublish) {
        setShouldAutoPublishInstall(false);
      }

      GraphObject publishParams = GraphObject.Factory.create();
      publishParams.setProperty(ANALYTICS_EVENT, MOBILE_INSTALL_EVENT);

      Utility.setAppEventAttributionParameters(
          publishParams,
          identifiers,
          Utility.getHashedDeviceAndAppID(context, applicationId),
          getLimitEventAndDataUsage(context));
      publishParams.setProperty(AUTO_PUBLISH, isAutoPublish);
      publishParams.setProperty("application_package_name", context.getPackageName());

      String publishUrl = String.format(PUBLISH_ACTIVITY_PATH, applicationId);
      Request publishRequest = Request.newPostRequest(null, publishUrl, publishParams, null);

      if (lastPing != 0) {
        GraphObject graphObject = null;
        try {
          if (lastResponseJSON != null) {
            graphObject = GraphObject.Factory.create(new JSONObject(lastResponseJSON));
          }
        } catch (JSONException je) {
          // return the default graph object if there is any problem reading the data.
        }
        if (graphObject == null) {
          return Response.createResponsesFromString(
                  "true", null, new RequestBatch(publishRequest), true)
              .get(0);
        } else {
          return new Response(null, null, null, graphObject, true);
        }
      } else if (identifiers == null
          || (identifiers.getAndroidAdvertiserId() == null
              && identifiers.getAttributionId() == null)) {
        throw new FacebookException("No attribution id available to send to server.");
      } else {
        if (!Utility.queryAppSettings(applicationId, false).supportsAttribution()) {
          throw new FacebookException("Install attribution has been disabled on the server.");
        }

        Response publishResponse = publishRequest.executeAndWait();

        // denote success since no error threw from the post.
        SharedPreferences.Editor editor = preferences.edit();
        lastPing = System.currentTimeMillis();
        editor.putLong(pingKey, lastPing);

        // if we got an object response back, cache the string of the JSON.
        if (publishResponse.getGraphObject() != null
            && publishResponse.getGraphObject().getInnerJSONObject() != null) {
          editor.putString(
              jsonKey, publishResponse.getGraphObject().getInnerJSONObject().toString());
        }
        editor.apply();

        return publishResponse;
      }
    } catch (Exception e) {
      // if there was an error, fall through to the failure case.
      Utility.logd("Facebook-publish", e);
      return new Response(null, null, new FacebookRequestError(null, e));
    }
  }
Exemple #11
0
    /** {@inheritDoc} */
    @Override
    public String toString() {

      return request.toString();
    }
Exemple #12
0
    /** {@inheritDoc} */
    @Override
    public int hashCode() {

      return request.hashCode();
    }
Exemple #13
0
    /** {@inheritDoc} */
    @Override
    public boolean equals(Object obj) {

      if (obj == this) return true;
      return obj instanceof UpdateRequest && request.equals(((UpdateRequest) obj).request);
    }