Exemplo n.º 1
0
  private <T> Response<T> sendRequest(
      RequestType type,
      SlaveContext slaveContext,
      Serializer serializer,
      Deserializer<T> deserializer) {
    // TODO Refactor, break into smaller methods
    Triplet<Channel, ChannelBuffer, ByteBuffer> channelContext = null;
    try {
      // Send 'em over the wire
      channelContext = getChannel();
      Channel channel = channelContext.first();
      ChannelBuffer buffer = channelContext.second();
      buffer.clear();
      buffer = new ChunkingChannelBuffer(buffer, channel, MAX_FRAME_LENGTH);
      buffer.writeByte(type.ordinal());
      if (type.includesSlaveContext()) {
        writeSlaveContext(buffer, slaveContext);
      }
      serializer.write(buffer, channelContext.third());
      if (buffer.writerIndex() > 0) {
        channel.write(buffer);
      }

      // Read the response
      @SuppressWarnings("unchecked")
      BlockingReadHandler<ChannelBuffer> reader =
          (BlockingReadHandler<ChannelBuffer>) channel.getPipeline().get("blockingHandler");
      final Triplet<Channel, ChannelBuffer, ByteBuffer> finalChannelContext = channelContext;
      DechunkingChannelBuffer dechunkingBuffer =
          new DechunkingChannelBuffer(reader) {
            @Override
            protected ChannelBuffer readNext() {
              ChannelBuffer result = super.readNext();
              if (result == null) {
                channelPool.dispose(finalChannelContext);
                throw new HaCommunicationException("Channel has been closed");
              }
              return result;
            }
          };
      T response = deserializer.read(dechunkingBuffer);
      TransactionStream txStreams =
          type.includesSlaveContext()
              ? readTransactionStreams(dechunkingBuffer)
              : TransactionStream.EMPTY;
      return new Response<T>(response, txStreams);
    } catch (ClosedChannelException e) {
      channelPool.dispose(channelContext);
      throw new HaCommunicationException(e);
    } catch (IOException e) {
      throw new HaCommunicationException(e);
    } catch (InterruptedException e) {
      throw new HaCommunicationException(e);
    } catch (Exception e) {
      throw new HaCommunicationException(e);
    }
  }
 private static <
         RequestType extends ConversationsSubmissionRequest,
         ResponseType extends ConversationsResponse>
     LoadCallSubmission<RequestType, ResponseType> createCall(
         Class<ResponseType> responseTypeClass, RequestType submission) {
   if (submission.getBuilder().getAction() == Action.Submit) {
     submission.setForcePreview(true);
   }
   return loadCallFromSubmission(responseTypeClass, submission);
 }
 private Pair<String, RequestType> parseRequestType(HttpServletRequest req) {
   String path = req.getPathInfo();
   path = path == null ? "" : path.substring(1); // Take off the leading '/'
   RequestType requestType = RequestType.HANDLE_STATIC;
   for (RequestType rt : RequestType.values()) {
     if (rt.matches(path)) {
       requestType = rt;
       break;
     }
   }
   return Pair.of(path, requestType);
 }
  static <
          RequestType extends ConversationsSubmissionRequest,
          ResponseType extends ConversationsResponse>
      LoadCall<RequestType, ResponseType> reCreateCallWithPhotos(
          Class<ResponseType> responseTypeClass, RequestType submission, List<Photo> photos) {
    submission.setPhotos(photos);
    submission.getBuilder().photoUploads.clear();
    submission.setForcePreview(false);

    LoadCall loadCall = loadCallFromSubmission(responseTypeClass, submission);
    return loadCall;
  }
Exemplo n.º 5
0
  @SuppressWarnings("unchecked")
  private static void addRRset(
      Name name, final Message response, Record[] records, final int section) {
    Multimap<RequestType, Record> rrsets = ArrayListMultimap.create();
    for (Record r : records) {
      RequestType type = RequestType.typeOf(r.getType());
      rrsets.get(type).addAll(Collections2.filter(Arrays.asList(records), type));
    }
    Predicate<Record> checkNewRecord =
        new Predicate<Record>() {

          @Override
          public boolean apply(Record input) {
            for (int s = 1; s <= section; s++) {
              if (response.findRecord(input, s)) {
                return false;
              }
            }
            return true;
          }
        };
    if (rrsets.containsKey(RequestType.CNAME)) {
      for (Record cnames : Iterables.filter(rrsets.removeAll(RequestType.CNAME), checkNewRecord)) {
        response.addRecord(cnames, section);
      }
    }
    for (Record sectionRecord : Iterables.filter(rrsets.values(), checkNewRecord)) {
      response.addRecord(sectionRecord, section);
    }
  }
Exemplo n.º 6
0
 public NanoHTTPD.Response serve(NanoHTTPD server, Properties args, RequestType type) {
   // Needs to be done also for help to initialize or argument records
   String query = checkArguments(args, type);
   switch (type) {
     case help:
       return wrap(server, build(Response.done(serveHelp())));
     case json:
     case www:
       if (log()) {
         String log = getClass().getSimpleName();
         for (Object arg : args.keySet()) {
           String value = args.getProperty((String) arg);
           if (value != null && value.length() != 0) log += " " + arg + "=" + value;
         }
         Log.debug(Sys.HTTPD, log);
       }
       if (query != null) return wrap(server, query, type);
       long time = System.currentTimeMillis();
       Response response = serve();
       response.setTimeStart(time);
       if (type == RequestType.json) return wrap(server, response.toJson());
       return wrap(server, build(response));
     case debug:
       response = serve_debug();
       return wrap(server, build(response));
     case query:
       return wrap(server, query);
     default:
       throw new RuntimeException("Invalid request type " + type.toString());
   }
 }
Exemplo n.º 7
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String startDate = req.getParameter(Param.START_DATE);
    String endDate = req.getParameter(Param.END_DATE);
    String leaderboardStartDate = req.getParameter(Param.LEADERBOARD_START_DATE);
    String minRequiredGames = req.getParameter(Param.MIN_REQ_GAMES);

    Cors.addHeaders(req, resp);

    try {
      switch (RequestType.from(req)) {
        case GAME:
          printGameStats(resp);
          break;

        case MATCHMAKER:
          printJson(resp, db.makeMatch(startDate, endDate, getPlayers(req)));
          break;

        case PLAYER:
          printJson(
              resp,
              db.recalculate(startDate, endDate, minRequiredGames, leaderboardStartDate).toJson());
          break;
      }
    } catch (Exception e) {
      e.printStackTrace();
      resp.sendError(500, e.toString());
    }
  }
 static <
         RequestType extends ConversationsSubmissionRequest,
         ResponseType extends ConversationsResponse>
     LoadCall<RequestType, ResponseType> reCreateCallNoPreview(
         Class<ResponseType> responseTypeClass, RequestType submission) {
   submission.setForcePreview(false);
   return loadCallFromSubmission(responseTypeClass, submission);
 }
 private <
         RequestType extends ConversationsDisplayRequest,
         ResponseType extends ConversationsDisplayResponse>
     LoadCallDisplay<RequestType, ResponseType> createCall(
         Class<ResponseType> responseTypeClass, RequestType request) {
   String fullUrl =
       String.format(
           "%s%s?%s", conversationsBaseUrl, request.getEndPoint(), request.getUrlQueryString());
   Logger.d("url", fullUrl);
   Request okRequest =
       new Request.Builder()
           .addHeader("User-Agent", BVSDK.getInstance().getBvsdkUserAgent())
           .url(fullUrl)
           .build();
   return new LoadCallDisplay<RequestType, ResponseType>(
       request, responseTypeClass, okHttpClient.newCall(okRequest));
 }
  static <
          RequestType extends ConversationsSubmissionRequest,
          ResponseType extends ConversationsResponse>
      LoadCallSubmission<RequestType, ResponseType> loadCallFromSubmission(
          Class<ResponseType> responseTypeClass, RequestType submission) {
    String fullUrl = String.format("%s%s", conversationsBaseUrl, submission.getEndPoint());
    Log.d("url", fullUrl);

    String json = submission.getUrlQueryString();
    RequestBody body = RequestBody.create(URL_ENCODED, json);
    Request okRequest =
        new Request.Builder()
            .post(body)
            .addHeader("Content-type", "application/x-www-form-urlencoded")
            .addHeader("User-Agent", BVSDK.getInstance().getBvsdkUserAgent())
            .url(fullUrl)
            .build();
    return new LoadCallSubmission<RequestType, ResponseType>(
        submission, responseTypeClass, okHttpClient.newCall(okRequest));
  }
Exemplo n.º 11
0
  /**
   * Constructor used for {@link HttpMethod#POST} requests, which receive a JSON payload.
   *
   * @param pMap map containing requests parameters
   * @param pInitParams optional processing parameters (obtained as query parameters or from within
   *     the JSON request)
   */
  public JmxRequest(Map<String, ?> pMap, ProcessingParameters pInitParams) {
    this(
        RequestType.getTypeByName((String) pMap.get("type")),
        HttpMethod.POST,
        EscapeUtil.parsePath((String) pMap.get("path")),
        pInitParams);

    Map target = (Map) pMap.get("target");
    if (target != null) {
      targetConfig = new ProxyTargetConfig(target);
    }
  }
Exemplo n.º 12
0
  /**
   * Convert this request to a JSON object, which can be used as a part of a return value.
   *
   * @return JSON object representing this base request object
   */
  public JSONObject toJSON() {
    JSONObject ret = new JSONObject();
    ret.put("type", type.getName());

    if (targetConfig != null) {
      ret.put("target", targetConfig.toJSON());
    }
    if (pathParts != null) {
      try {
        ret.put("path", getPath());
      } catch (UnsupportedOperationException exp) {
        // Happens when request doesnt support paths
      }
    }
    return ret;
  }
Exemplo n.º 13
0
  /**
   * Create PVItem from XML document
   *
   * @param model Model to which this item will belong (but doesn't, yet)
   * @param node XML node with item configuration
   * @return PVItem
   * @throws Exception on error
   */
  public static PVItem fromDocument(final Model model, final Element node) throws Exception {
    final String name = DOMHelper.getSubelementString(node, Model.TAG_NAME);
    final double period = DOMHelper.getSubelementDouble(node, Model.TAG_SCAN_PERIOD, 0.0);

    final PVItem item = new PVItem(name, period);
    final int buffer_size =
        DOMHelper.getSubelementInt(
            node, Model.TAG_LIVE_SAMPLE_BUFFER_SIZE, Preferences.getLiveSampleBufferSize());
    item.setLiveCapacity(buffer_size);

    final String req_txt =
        DOMHelper.getSubelementString(node, Model.TAG_REQUEST, RequestType.OPTIMIZED.name());
    try {
      final RequestType request = RequestType.valueOf(req_txt);
      item.setRequestType(request);
    } catch (Throwable ex) {
      // Ignore
    }

    item.configureFromDocument(model, node);

    // Load archives from saved configuration
    boolean have_imported_data = false;
    Element archive = DOMHelper.findFirstElementNode(node.getFirstChild(), Model.TAG_ARCHIVE);
    while (archive != null) {
      final String url = DOMHelper.getSubelementString(archive, Model.TAG_URL);
      final int key = DOMHelper.getSubelementInt(archive, Model.TAG_KEY);
      final String arch = DOMHelper.getSubelementString(archive, Model.TAG_NAME);

      if (url.startsWith(ImportArchiveReaderFactory.PREFIX)) have_imported_data = true;

      item.addArchiveDataSource(new ArchiveDataSource(url, key, arch));
      archive = DOMHelper.findNextElementNode(archive, Model.TAG_ARCHIVE);
    }

    // When requested, use default archive sources for 'real' archives (RDB, ...)
    // Do not clobber an imported archive data source, a specific file which was
    // probably not meant to be replaced by a default.
    if (Preferences.useDefaultArchives() && !have_imported_data)
      item.useDefaultArchiveDataSources();

    return item;
  }
Exemplo n.º 14
0
 private static SetResponse lookupRecords(
     final Message response, final Record query, final InetAddress source) {
   final Name name = query.getName();
   final int type = query.getType();
   response.getHeader().setFlag(Flags.RA); // always mark the response w/ the recursion available
   // bit
   LOG.debug("DnsResolver: " + RequestType.typeOf(type) + " " + name);
   for (final DnsResolver r : DnsResolvers.resolversFor(query, source)) {
     try {
       final DnsResponse reply = r.lookupRecords(query);
       if (reply == null) {
         LOG.debug("DnsResolver: returned null " + name + " using " + r);
         continue;
       }
       if (reply.isAuthoritative()) { // mark
         response.getHeader().setFlag(Flags.AA);
       }
       if (reply.isNxdomain()) {
         addRRset(name, response, new Record[] {DomainNameRecords.sourceOfAuthority(name)}, type);
         response.getHeader().setRcode(Rcode.NXDOMAIN);
         return SetResponse.ofType(SetResponse.NXDOMAIN);
       } else if (reply.hasAnswer()) {
         for (ResponseSection s : ResponseSection.values()) {
           Record[] records = reply.section(s);
           if (records != null) {
             addRRset(name, response, records, s.section());
           }
         }
         return SetResponse.ofType(SetResponse.SUCCESSFUL);
       }
     } catch (final Exception ex) {
       LOG.debug(
           "DnsResolver: failed for " + name + " using " + r + " because of: " + ex.getMessage(),
           ex);
     }
   }
   return SetResponse.ofType(SetResponse.UNKNOWN); // no dice, return unknown
 }
Exemplo n.º 15
0
 public RequestType getRequestType() {
   return RequestType.valueOf(driver.getTitle());
 }
 @Nonnull
 protected final Cache.Key newKey() {
   return new Cache.Key(counter.getAndIncrement() % RequestType.values().length, "test");
 }
Exemplo n.º 17
0
 public RequestType findValueByNumber(int number) {
   return RequestType.valueOf(number);
 }
Exemplo n.º 18
0
 /**
  * Builds the actual string that is POSTed to the KeyServer
  *
  * @param localhostname Local Hostname
  * @param request KeyServer request
  * @param key Key to allocate/deallocate
  * @return String to POST
  */
 protected static String buildRequestString(
     String localhostname, RequestType request, String key) {
   return buildRequestString(localhostname, request.getNativeRequest(), key);
 }
Exemplo n.º 19
0
 @Factory("requestTypes")
 public RequestType[] getRequestTypes() {
   return RequestType.values();
 }
Exemplo n.º 20
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse resp)
      throws ServletException, IOException {
    // super.doGet(req, resp);

    HttpSession session = null;
    Request wiraRequest = new Request();

    try {
      session = request.getSession(true);
      SessionHelper.setHttpRequest(request);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Response response = new Response();

    try {
      DB.beginTransaction();
      wiraRequest.setCommandName(IncomingRequestImpl.NEWAPPROVALREQUESTCOMMAND);

      String parameter = request.getParameter("docType");
      RequestType requestType = RequestType.getRequestType(parameter);

      // Create Context and set it
      wiraRequest.setContext(createContext(request, requestType, wiraRequest));

      HTUser user = new HTUser();
      user.setUserId(wiraRequest.getContext("ownerId").toString());
      if (session != null) session.setAttribute(ServerConstants.USER, user);

      // Submit
      IncomingRequestImpl handler = new IncomingRequestImpl();
      handler.executeClientRequest(wiraRequest, response);

      // Response
      PrintWriter out = resp.getWriter();
      BusinessKey key = response.getBusinessKey();
      assert key != null;

      resp.setContentType("text/json");
      out.println(
          "Response:"
              + key.getDocumentId()
              + " : "
              + key.getProcessInstanceId()
              + ":"
              + key.getSessionId()
              + "</b>");
      out.close();

      DB.commitTransaction();
    } catch (Exception e) {
      DB.rollback();
      e.printStackTrace();
      throw new RuntimeException(e);
    } finally {
      if (session != null) {
        session.invalidate();
      }

      DB.closeSession();
      SessionHelper.setHttpRequest(null);
      JBPMHelper.clearRequestData();
    }
  }