@Override
  protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    final int index = requestCode - RESULT_FIRST_USER;

    try {
      final ResponseHandler handler = mResponseHandlers.get(index);
      handler.onActivityResult(resultCode, data);
    } catch (final ArrayIndexOutOfBoundsException e) {
      super.onActivityResult(requestCode, resultCode, data);
    }
  }
Ejemplo n.º 2
0
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   Object attachment = ctx.getAttachment();
   if (e.getMessage() instanceof KafkaResponse && attachment instanceof ResponseHandler) {
     ((ResponseHandler) attachment).received((KafkaResponse) e.getMessage());
   } else {
     super.messageReceived(ctx, e);
   }
 }
 protected long run() throws RemoteException {
   int responseCode =
       mService
           .sendBillingRequest(makeRequestBundle("CHECK_BILLING_SUPPORTED"))
           .getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE);
   Log.i(
       TAG,
       new StringBuilder("CheckBillingSupported response code: ")
           .append(ResponseCode.valueOf(responseCode))
           .toString());
   ResponseHandler.checkBillingSupportedResponse(
       responseCode == ResponseCode.RESULT_OK.ordinal());
   return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
 }
 @Override
 protected void onPostExecute(String result) {
   if (result != null) {
     try {
       JSONObject response = new JSONObject(result);
       if (mResponseHandler != null) {
         mResponseHandler.onResponse(response);
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
   super.onPostExecute(result);
 }
Ejemplo n.º 5
0
 private Response executeSyncInner(ResponseHandler callback) throws Exception {
   HttpLite lite = request.lite;
   if (callback instanceof DownloadHandler) ((DownloadHandler) callback).doResumeWork();
   if (lite.getRequestFilter() != null)
     lite.getRequestFilter().onRequest(lite, request, callback.resultType());
   Executable executable = lite.getClient().executable(request);
   if (callback instanceof DownloadHandler)
     executable = ((DownloadHandler) callback).wrap(executable);
   setExecutable(executable);
   Response response = executable().execute();
   if (lite.getResponseFilter() != null)
     lite.getResponseFilter().onResponse(lite, request, response);
   response = request.handleResponse(response);
   return response;
 }
 private void purchaseStateChanged(int startId, String signedData, String signature) {
   ArrayList<VerifiedPurchase> purchases = Security.verifyPurchase(signedData, signature);
   if (purchases != null) {
     ArrayList<String> notifyList = new ArrayList();
     Iterator it = purchases.iterator();
     while (it.hasNext()) {
       VerifiedPurchase vp = (VerifiedPurchase) it.next();
       if (vp.notificationId != null) {
         notifyList.add(vp.notificationId);
       }
       ResponseHandler.purchaseResponse(
           this, vp.purchaseState, vp.productId, vp.orderId, vp.purchaseTime, vp.developerPayload);
     }
     if (!notifyList.isEmpty()) {
       confirmNotifications(startId, (String[]) notifyList.toArray(new String[notifyList.size()]));
     }
   }
 }
 protected long run() throws RemoteException {
   Bundle request = makeRequestBundle("REQUEST_PURCHASE");
   request.putString(Consts.BILLING_REQUEST_ITEM_ID, this.mProductId);
   if (this.mDeveloperPayload != null) {
     request.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, this.mDeveloperPayload);
   }
   Bundle response = mService.sendBillingRequest(request);
   PendingIntent pendingIntent =
       (PendingIntent) response.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT);
   if (pendingIntent == null) {
     Log.e(TAG, "Error with requestPurchase");
     return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
   } else {
     ResponseHandler.buyPageIntentResponse(pendingIntent, new Intent());
     return response.getLong(
         Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
   }
 }
Ejemplo n.º 8
0
 /*
  * 1. Take the responseTemplate of the event object and do the variable
  * substitution using freemarker and the params object for the values. 2.
  * See what is the type of the response and proceed accordingly. Create an
  * appropriate response handler and call its respond() method. 3. Create and
  * persist the EventResult
  */
 public void process(final Event e) {
   EventProcessorSpec eventSpec = null;
   try {
     RESULT = "success";
     eventSpec =
         eventProcessSpecService.getEventProcessingSpecByModAndCode(
             e.getModule(), e.getEventCode());
     if (eventSpec != null) e.setResponseTemplate(eventSpec.getResponseTemplate());
     String processedTemplate = null;
     processedTemplate = substituteParams(e);
     e.setResponseTemplate(processedTemplate);
     final Response response = response(processedTemplate);
     responseCallback(e, response);
     responseHandler.respond(response);
   } catch (final Exception ex) {
     RESULT = "failure:: " + ex.getMessage();
   }
   persistEventResult(e, eventSpec);
 }
  private <T> T executeRequest(final HttpUriRequest request, final ResponseHandler<T> handler)
      throws IOException {
    final CloseableHttpClient client = createClientInstance();
    try {
      final CloseableHttpResponse response = client.execute(request);
      //  Wrap the response in a buffer to facilitate error handlers re-playing the content if the
      // response
      //  size is smaller than the max allowable buffer
      if (response.getEntity().getContentLength() >= 0
          && response.getEntity().getContentLength() < config.getMaxBufferSize()) {
        EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity()));
      }

      //  Explicit check for the authorization status of the API key
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        throw new HyppoAuthException(config);
      }

      try {
        log.debug(
            "{} - {} : {}",
            request.getMethod(),
            request.getURI().getPath(),
            response.getStatusLine().getStatusCode());
        return handler.handleResponse(response);
      } finally {
        IOUtils.closeQuietly(response);
      }
    } catch (Exception e) {
      log.error(
          "{} - {} : FAILED - {}", request.getMethod(), request.getURI().getPath(), e.toString());
      throw e;
    } finally {
      IOUtils.closeQuietly(client);
    }
  }
Ejemplo n.º 10
0
 protected <T> T parseResult(Response response, ResponseHandler<T> callback) throws Exception {
   return callback.parseResponse(response);
 }
Ejemplo n.º 11
0
  /* Parse a request or response line
   */
  private boolean parseLine(ByteBuffer buffer) {
    boolean handle = false;

    // Process headers
    while (_state.ordinal() < State.HEADER.ordinal() && buffer.hasRemaining() && !handle) {
      // process each character
      byte ch = next(buffer);
      if (ch == 0) break;

      if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) {
        if (_state == State.URI) {
          LOG.warn("URI is too large >" + _maxHeaderBytes);
          throw new BadMessage(HttpStatus.REQUEST_URI_TOO_LONG_414);
        } else {
          if (_requestHandler != null) LOG.warn("request is too large >" + _maxHeaderBytes);
          else LOG.warn("response is too large >" + _maxHeaderBytes);
          throw new BadMessage(HttpStatus.REQUEST_ENTITY_TOO_LARGE_413);
        }
      }

      switch (_state) {
        case METHOD:
          if (ch == HttpTokens.SPACE) {
            _length = _string.length();
            _methodString = takeString();
            HttpMethod method = HttpMethod.CACHE.get(_methodString);
            if (method != null && !_strict) _methodString = method.asString();
            setState(State.SPACE1);
          } else if (ch < HttpTokens.SPACE)
            throw new BadMessage(ch < 0 ? "Illegal character" : "No URI");
          else _string.append((char) ch);
          break;

        case RESPONSE_VERSION:
          if (ch == HttpTokens.SPACE) {
            _length = _string.length();
            String version = takeString();
            _version = HttpVersion.CACHE.get(version);
            if (_version == null)
              throw new BadMessage(HttpStatus.BAD_REQUEST_400, "Unknown Version");
            setState(State.SPACE1);
          } else if (ch < HttpTokens.SPACE)
            throw new BadMessage(ch < 0 ? "Illegal character" : "No Status");
          else _string.append((char) ch);
          break;

        case SPACE1:
          if (ch > HttpTokens.SPACE || ch < 0) {
            if (_responseHandler != null) {
              setState(State.STATUS);
              setResponseStatus(ch - '0');
            } else {
              _uri.clear();
              setState(State.URI);
              // quick scan for space or EoBuffer
              if (buffer.hasArray()) {
                byte[] array = buffer.array();
                int p = buffer.arrayOffset() + buffer.position();
                int l = buffer.arrayOffset() + buffer.limit();
                int i = p;
                while (i < l && array[i] > HttpTokens.SPACE) i++;

                int len = i - p;
                _headerBytes += len;

                if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) {
                  LOG.warn("URI is too large >" + _maxHeaderBytes);
                  throw new BadMessage(HttpStatus.REQUEST_URI_TOO_LONG_414);
                }
                if (_uri.remaining() <= len) {
                  ByteBuffer uri = ByteBuffer.allocate(_uri.capacity() + 2 * len);
                  _uri.flip();
                  uri.put(_uri);
                  _uri = uri;
                }
                _uri.put(array, p - 1, len + 1);
                buffer.position(i - buffer.arrayOffset());
              } else _uri.put(ch);
            }
          } else if (ch < HttpTokens.SPACE) {
            throw new BadMessage(
                HttpStatus.BAD_REQUEST_400, _requestHandler != null ? "No URI" : "No Status");
          }
          break;

        case STATUS:
          if (ch == HttpTokens.SPACE) {
            setState(State.SPACE2);
          } else if (ch >= '0' && ch <= '9') {
            _responseStatus = _responseStatus * 10 + (ch - '0');
          } else if (ch < HttpTokens.SPACE && ch >= 0) {
            handle = _responseHandler.startResponse(_version, _responseStatus, null) || handle;
            setState(State.HEADER);
          } else {
            throw new BadMessage();
          }
          break;

        case URI:
          if (ch == HttpTokens.SPACE) {
            setState(State.SPACE2);
          } else if (ch < HttpTokens.SPACE && ch >= 0) {
            // HTTP/0.9
            _uri.flip();
            handle = _requestHandler.startRequest(_method, _methodString, _uri, null) || handle;
            setState(State.END);
            BufferUtil.clear(buffer);
            handle = _handler.headerComplete() || handle;
            handle = _handler.messageComplete() || handle;
          } else {
            if (!_uri.hasRemaining()) {
              ByteBuffer uri = ByteBuffer.allocate(_uri.capacity() * 2);
              _uri.flip();
              uri.put(_uri);
              _uri = uri;
            }
            _uri.put(ch);
          }
          break;

        case SPACE2:
          if (ch > HttpTokens.SPACE) {
            _string.setLength(0);
            _string.append((char) ch);
            if (_responseHandler != null) {
              _length = 1;
              setState(State.REASON);
            } else {
              setState(State.REQUEST_VERSION);

              // try quick look ahead for HTTP Version
              HttpVersion version;
              if (buffer.position() > 0 && buffer.hasArray())
                version =
                    HttpVersion.lookAheadGet(
                        buffer.array(),
                        buffer.arrayOffset() + buffer.position() - 1,
                        buffer.arrayOffset() + buffer.limit());
              else version = HttpVersion.CACHE.getBest(buffer, 0, buffer.remaining());
              if (version != null) {
                int pos = buffer.position() + version.asString().length() - 1;
                if (pos < buffer.limit()) {
                  byte n = buffer.get(pos);
                  if (n == HttpTokens.CARRIAGE_RETURN) {
                    _cr = true;
                    _version = version;
                    _string.setLength(0);
                    buffer.position(pos + 1);
                  } else if (n == HttpTokens.LINE_FEED) {
                    _version = version;
                    _string.setLength(0);
                    buffer.position(pos);
                  }
                }
              }
            }
          } else if (ch == HttpTokens.LINE_FEED) {
            if (_responseHandler != null) {
              handle = _responseHandler.startResponse(_version, _responseStatus, null) || handle;
              setState(State.HEADER);
            } else {
              // HTTP/0.9
              _uri.flip();
              handle = _requestHandler.startRequest(_method, _methodString, _uri, null) || handle;
              setState(State.END);
              BufferUtil.clear(buffer);
              handle = _handler.headerComplete() || handle;
              handle = _handler.messageComplete() || handle;
            }
          } else if (ch < 0) throw new BadMessage();
          break;

        case REQUEST_VERSION:
          if (ch == HttpTokens.LINE_FEED) {
            if (_version == null) {
              _length = _string.length();
              _version = HttpVersion.CACHE.get(takeString());
            }
            if (_version == null)
              throw new BadMessage(HttpStatus.BAD_REQUEST_400, "Unknown Version");

            // Should we try to cache header fields?
            if (_connectionFields == null
                && _version.getVersion() >= HttpVersion.HTTP_1_1.getVersion()) {
              int header_cache = _handler.getHeaderCacheSize();
              if (header_cache > 0) _connectionFields = new ArrayTernaryTrie<>(header_cache);
            }

            setState(State.HEADER);
            _uri.flip();
            handle = _requestHandler.startRequest(_method, _methodString, _uri, _version) || handle;
            continue;
          } else if (ch >= HttpTokens.SPACE) _string.append((char) ch);
          else throw new BadMessage();

          break;

        case REASON:
          if (ch == HttpTokens.LINE_FEED) {
            String reason = takeString();

            setState(State.HEADER);
            handle = _responseHandler.startResponse(_version, _responseStatus, reason) || handle;
            continue;
          } else if (ch >= HttpTokens.SPACE) {
            _string.append((char) ch);
            if (ch != ' ' && ch != '\t') _length = _string.length();
          } else throw new BadMessage();
          break;

        default:
          throw new IllegalStateException(_state.toString());
      }
    }

    return handle;
  }
Ejemplo n.º 12
0
  @SuppressWarnings("deprecation")
  protected void doProcess(Exchange exchange) throws Exception {
    if (session == null && !lazySessionCreation) {
      throw new IllegalStateException("Not started yet!");
    }
    if (session == null || !session.isConnected()) {
      openConnection();
    }

    // set the exchange encoding property
    if (getEndpoint().getConfiguration().getCharsetName() != null) {
      exchange.setProperty(
          Exchange.CHARSET_NAME,
          IOConverter.normalizeCharset(getEndpoint().getConfiguration().getCharsetName()));
    }

    Object body = Mina2PayloadHelper.getIn(getEndpoint(), exchange);
    if (body == null) {
      noReplyLogger.log("No payload to send for exchange: " + exchange);
      return; // exit early since nothing to write
    }

    // if textline enabled then covert to a String which must be used for textline
    if (getEndpoint().getConfiguration().isTextline()) {
      body =
          getEndpoint()
              .getCamelContext()
              .getTypeConverter()
              .mandatoryConvertTo(String.class, exchange, body);
    }

    // if sync is true then we should also wait for a response (synchronous mode)
    if (sync) {
      // only initialize latch if we should get a response
      latch = new CountDownLatch(1);
      // reset handler if we expect a response
      ResponseHandler handler = (ResponseHandler) session.getHandler();
      handler.reset();
    }

    // log what we are writing
    if (LOG.isDebugEnabled()) {
      Object out = body;
      if (body instanceof byte[]) {
        // byte arrays is not readable so convert to string
        out = exchange.getContext().getTypeConverter().convertTo(String.class, body);
      }
      LOG.debug("Writing body: {}", out);
    }
    // write the body
    Mina2Helper.writeBody(session, body, exchange);

    if (sync) {
      // wait for response, consider timeout
      LOG.debug("Waiting for response using timeout {} millis.", timeout);
      boolean done = latch.await(timeout, TimeUnit.MILLISECONDS);
      if (!done) {
        throw new ExchangeTimedOutException(exchange, timeout);
      }

      // did we get a response
      ResponseHandler handler = (ResponseHandler) session.getHandler();
      if (handler.getCause() != null) {
        throw new CamelExchangeException(
            "Error occurred in ResponseHandler", exchange, handler.getCause());
      } else if (!handler.isMessageReceived()) {
        // no message received
        throw new ExchangeTimedOutException(exchange, timeout);
      } else {
        // set the result on either IN or OUT on the original exchange depending on its pattern
        if (ExchangeHelper.isOutCapable(exchange)) {
          Mina2PayloadHelper.setOut(exchange, handler.getMessage());
        } else {
          Mina2PayloadHelper.setIn(exchange, handler.getMessage());
        }
      }
    }
  }
Ejemplo n.º 13
0
  /**
   * Retrieve the data for a resource using the given http client and endpoint definition. The
   * service is supposed to manage the connection handling itself. See {@link AbstractHttpProvider}
   * for a generic implementation of this method.
   *
   * @param resource the resource to be retrieved
   * @param endpoint the endpoint definition
   * @return a completely specified client response, including expiry information and the set of
   *     triples
   */
  @Override
  public ClientResponse retrieveResource(String resource, LDClientService client, Endpoint endpoint)
      throws DataRetrievalException {

    try {

      String contentType;
      if (endpoint != null && endpoint.getContentTypes().size() > 0) {
        contentType =
            CollectionUtils.fold(
                endpoint.getContentTypes(),
                new CollectionUtils.StringSerializer<ContentType>() {
                  @Override
                  public String serialize(ContentType contentType) {
                    return contentType.toString("q");
                  }
                },
                ",");
      } else {
        contentType = CollectionUtils.fold(Arrays.asList(listMimeTypes()), ",");
      }

      long defaultExpires = client.getClientConfiguration().getDefaultExpiry();
      if (endpoint != null && endpoint.getDefaultExpiry() != null) {
        defaultExpires = endpoint.getDefaultExpiry();
      }

      final ResponseHandler handler = new ResponseHandler(resource, endpoint);

      // a queue for queuing the request URLs needed to build the query response
      Queue<String> requestUrls = new LinkedList<String>();
      requestUrls.addAll(buildRequestUrl(resource, endpoint));

      Set<String> visited = new HashSet<String>();

      String requestUrl = requestUrls.poll();
      while (requestUrl != null) {

        if (!visited.contains(requestUrl)) {
          HttpGet get = new HttpGet(requestUrl);
          try {
            get.setHeader("Accept", contentType);
            get.setHeader("Accept-Language", "*"); // PoolParty compatibility

            log.info(
                "retrieving resource data for {} from '{}' endpoint, request URI is <{}>",
                new Object[] {resource, getName(), get.getURI().toASCIIString()});

            handler.requestUrl = requestUrl;
            List<String> additionalRequestUrls = client.getClient().execute(get, handler);
            requestUrls.addAll(additionalRequestUrls);

            visited.add(requestUrl);
          } finally {
            get.releaseConnection();
          }
        }

        requestUrl = requestUrls.poll();
      }

      Date expiresDate = handler.expiresDate;
      if (expiresDate == null) {
        expiresDate = new Date(System.currentTimeMillis() + defaultExpires * 1000);
      }

      long min_expires =
          System.currentTimeMillis() + client.getClientConfiguration().getMinimumExpiry() * 1000;
      if (expiresDate.getTime() < min_expires) {
        log.info(
            "expiry time returned by request lower than minimum expiration time; using minimum time instead");
        expiresDate = new Date(min_expires);
      }

      if (log.isInfoEnabled()) {
        RepositoryConnection con = handler.triples.getConnection();
        log.info(
            "retrieved {} triples for resource {}; expiry date: {}",
            new Object[] {con.size(), resource, expiresDate});
        con.close();
      }

      ClientResponse result = new ClientResponse(handler.httpStatus, handler.triples);
      result.setExpires(expiresDate);
      return result;
    } catch (RepositoryException e) {
      log.error("error while initialising Sesame repository; classpath problem?", e);
      throw new DataRetrievalException(
          "error while initialising Sesame repository; classpath problem?", e);
    } catch (ClientProtocolException e) {
      log.error(
          "HTTP client error while trying to retrieve resource {}: {}", resource, e.getMessage());
      throw new DataRetrievalException(
          "I/O error while trying to retrieve resource " + resource, e);
    } catch (IOException e) {
      log.error("I/O error while trying to retrieve resource {}: {}", resource, e.getMessage());
      throw new DataRetrievalException(
          "I/O error while trying to retrieve resource " + resource, e);
    } catch (RuntimeException ex) {
      log.error(
          "Unknown error while trying to retrieve resource {}: {}", resource, ex.getMessage());
      throw new DataRetrievalException(
          "Unknown error while trying to retrieve resource " + resource, ex);
    }
  }
Ejemplo n.º 14
0
    public void run() {
      Contact destination = request.getDestination();
      logger.info(
          "Sending message of type "
              + request.getClass().getSimpleName()
              + " to "
              + destination.getIp()
              + ":"
              + destination.getPort());

      ObjectInputStream inStream = null;
      ObjectOutputStream outStream = null;
      Socket socket = new Socket();

      try {
        socket.connect(new InetSocketAddress(destination.getIp(), destination.getPort()));

        try {
          outStream = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException e) {
          logger.error("IOException occured while trying to open the socket outputStream");
          throw e;
        }

        logger.debug("Writing object " + request + " to socket output stream");
        outStream.writeObject(request);

        try {
          inStream = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
          logger.error("IOException occured while trying to open the socket inputStream");
          throw e;
        }

        Object readObj = null;

        try {
          logger.debug("Reading object from the socket input stream");
          readObj = inStream.readObject();
        } catch (IOException e) {
          logger.error("IOException occured while trying to read the object from the socket");
          throw e;
        } catch (ClassNotFoundException e) {
          logger.error(
              "ClassNotFoundException occured while trying to read object from the socket");
          throw e;
        }

        if (readObj instanceof Response) {
          Response response = (Response) readObj;
          logger.debug("Received response: " + response);
          handler.handleResponse(response);
        } else {
          logger.warn(
              "Object read from the socket is of an unsupported type (not instance of "
                  + Response.class
                  + "): "
                  + readObj.getClass());
        }

      } catch (Exception e) {
        logger.error(null, e);
      } finally {
        closeResources(socket, inStream, outStream);
      }
    }
 protected void responseCodeReceived(ResponseCode responseCode) {
   ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode);
 }