@Override
  protected void handleRequest(
      final RestRequest request, final RestChannel channel, final Client client) throws Exception {
    BytesRestResponse response = null;
    final XContentBuilder builder = channel.newBuilder();
    try {
      builder.startObject();
      final User user = ((User) request.getFromContext("_shield_user"));
      if (user != null) {
        builder.field("principal", user.principal());
        builder.field("roles", user.roles());
      } else {
        builder.nullField("principal");
      }

      builder.field("remote_address", request.getFromContext("_rest_remote_address"));
      builder.endObject();
      response = new BytesRestResponse(RestStatus.OK, builder);
    } catch (final Exception e1) {
      builder.startObject();
      builder.field("error", e1.toString());
      builder.endObject();
      response = new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, builder);
    }

    channel.sendResponse(response);
  }
Ejemplo n.º 2
0
 private static String renderValue(RestRequest request, Object value) {
   if (value == null) {
     return null;
   }
   if (value instanceof ByteSizeValue) {
     ByteSizeValue v = (ByteSizeValue) value;
     String resolution = request.param("bytes");
     if ("b".equals(resolution)) {
       return Long.toString(v.bytes());
     } else if ("k".equals(resolution)) {
       return Long.toString(v.kb());
     } else if ("m".equals(resolution)) {
       return Long.toString(v.mb());
     } else if ("g".equals(resolution)) {
       return Long.toString(v.gb());
     } else if ("t".equals(resolution)) {
       return Long.toString(v.tb());
     } else if ("p".equals(resolution)) {
       return Long.toString(v.pb());
     } else {
       return v.toString();
     }
   }
   if (value instanceof SizeValue) {
     SizeValue v = (SizeValue) value;
     String resolution = request.param("size");
     if ("b".equals(resolution)) {
       return Long.toString(v.singles());
     } else if ("k".equals(resolution)) {
       return Long.toString(v.kilo());
     } else if ("m".equals(resolution)) {
       return Long.toString(v.mega());
     } else if ("g".equals(resolution)) {
       return Long.toString(v.giga());
     } else if ("t".equals(resolution)) {
       return Long.toString(v.tera());
     } else if ("p".equals(resolution)) {
       return Long.toString(v.peta());
     } else {
       return v.toString();
     }
   }
   if (value instanceof TimeValue) {
     TimeValue v = (TimeValue) value;
     String resolution = request.param("time");
     if ("ms".equals(resolution)) {
       return Long.toString(v.millis());
     } else if ("s".equals(resolution)) {
       return Long.toString(v.seconds());
     } else if ("m".equals(resolution)) {
       return Long.toString(v.minutes());
     } else if ("h".equals(resolution)) {
       return Long.toString(v.hours());
     } else {
       return v.toString();
     }
   }
   // Add additional built in data points we can render based on request parameters?
   return value.toString();
 }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final NodeClient client) {
   GetIndexTemplatesRequest getIndexTemplatesRequest =
       new GetIndexTemplatesRequest(request.param("name"));
   getIndexTemplatesRequest.local(
       request.paramAsBoolean("local", getIndexTemplatesRequest.local()));
   getIndexTemplatesRequest.masterNodeTimeout(
       request.paramAsTime("master_timeout", getIndexTemplatesRequest.masterNodeTimeout()));
   client
       .admin()
       .indices()
       .getTemplates(
           getIndexTemplatesRequest,
           new RestResponseListener<GetIndexTemplatesResponse>(channel) {
             @Override
             public RestResponse buildResponse(
                 GetIndexTemplatesResponse getIndexTemplatesResponse) {
               boolean templateExists = getIndexTemplatesResponse.getIndexTemplates().size() > 0;
               if (templateExists) {
                 return new BytesRestResponse(
                     OK, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY);
               } else {
                 return new BytesRestResponse(
                     NOT_FOUND, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY);
               }
             }
           });
 }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final NodeClient client) {
   ForceMergeRequest mergeRequest =
       new ForceMergeRequest(Strings.splitStringByCommaToArray(request.param("index")));
   mergeRequest.indicesOptions(IndicesOptions.fromRequest(request, mergeRequest.indicesOptions()));
   mergeRequest.maxNumSegments(
       request.paramAsInt("max_num_segments", mergeRequest.maxNumSegments()));
   mergeRequest.onlyExpungeDeletes(
       request.paramAsBoolean("only_expunge_deletes", mergeRequest.onlyExpungeDeletes()));
   mergeRequest.flush(request.paramAsBoolean("flush", mergeRequest.flush()));
   client
       .admin()
       .indices()
       .forceMerge(
           mergeRequest,
           new RestBuilderListener<ForceMergeResponse>(channel) {
             @Override
             public RestResponse buildResponse(
                 ForceMergeResponse response, XContentBuilder builder) throws Exception {
               builder.startObject();
               buildBroadcastShardsHeader(builder, request, response);
               builder.endObject();
               return new BytesRestResponse(OK, builder);
             }
           });
 }
  @Override
  public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client)
      throws IOException {
    final String[] names = Strings.splitStringByCommaToArray(request.param("name"));

    GetIndexTemplatesRequest getIndexTemplatesRequest = new GetIndexTemplatesRequest(names);
    getIndexTemplatesRequest.local(
        request.paramAsBoolean("local", getIndexTemplatesRequest.local()));
    getIndexTemplatesRequest.masterNodeTimeout(
        request.paramAsTime("master_timeout", getIndexTemplatesRequest.masterNodeTimeout()));

    final boolean implicitAll = getIndexTemplatesRequest.names().length == 0;

    return channel ->
        client
            .admin()
            .indices()
            .getTemplates(
                getIndexTemplatesRequest,
                new RestToXContentListener<GetIndexTemplatesResponse>(channel) {
                  @Override
                  protected RestStatus getStatus(GetIndexTemplatesResponse response) {
                    boolean templateExists = false == response.getIndexTemplates().isEmpty();

                    return (templateExists || implicitAll) ? OK : NOT_FOUND;
                  }
                });
  }
 @Override
 public void handleRequest(final RestRequest request, final RestChannel channel, Client client) {
   DeleteIndexedScriptRequest deleteIndexedScriptRequest =
       new DeleteIndexedScriptRequest(getScriptLang(request), request.param("id"));
   deleteIndexedScriptRequest.version(
       request.paramAsLong("version", deleteIndexedScriptRequest.version()));
   deleteIndexedScriptRequest.versionType(
       VersionType.fromString(
           request.param("version_type"), deleteIndexedScriptRequest.versionType()));
   client.deleteIndexedScript(
       deleteIndexedScriptRequest,
       new RestBuilderListener<DeleteIndexedScriptResponse>(channel) {
         @Override
         public RestResponse buildResponse(
             DeleteIndexedScriptResponse result, XContentBuilder builder) throws Exception {
           builder
               .startObject()
               .field(Fields.FOUND, result.isFound())
               .field(Fields._INDEX, result.getIndex())
               .field(Fields._TYPE, result.getType())
               .field(Fields._ID, result.getId())
               .field(Fields._VERSION, result.getVersion())
               .endObject();
           RestStatus status = OK;
           if (!result.isFound()) {
             status = NOT_FOUND;
           }
           return new BytesRestResponse(status, builder);
         }
       });
 }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    DeleteMappingRequest deleteMappingRequest =
        deleteMappingRequest(splitIndices(request.param("index")));
    deleteMappingRequest.type(request.param("type"));
    client
        .admin()
        .indices()
        .deleteMapping(
            deleteMappingRequest,
            new ActionListener<DeleteMappingResponse>() {
              @Override
              public void onResponse(DeleteMappingResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder.startObject().field("ok", true);
                  builder.endObject();
                  channel.sendResponse(new XContentRestResponse(request, OK, builder));
                } catch (IOException e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new XContentThrowableRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
  @Override
  public void login(final RestRequest request, final ActionListener<String[]> listener) {
    String username = request.param(usernameKey);
    String password = request.param(passwordKey);
    final BytesReference content = request.content();
    final XContentType xContentType = XContentFactory.xContentType(content);
    XContentParser parser = null;
    try {
      parser = XContentFactory.xContent(xContentType).createParser(content);
      final XContentParser.Token t = parser.nextToken();
      if (t != null) {
        final Map<String, Object> contentMap = parser.map();
        username = MapUtil.getAsString(contentMap, usernameKey, username);
        password = MapUtil.getAsString(contentMap, passwordKey, password);
      }
    } catch (final Exception e) {
      listener.onFailure(e);
      return;
    } finally {
      if (parser != null) {
        parser.close();
      }
    }

    if (username == null) {
      listener.onResponse(new String[0]);
      return;
    }

    processLogin(username, password, listener);
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, NodeClient client) {
   PutStoredScriptRequest putRequest =
       new PutStoredScriptRequest(getScriptLang(request), request.param("id"));
   putRequest.script(request.content());
   client.admin().cluster().putStoredScript(putRequest, new AcknowledgedRestListener<>(channel));
 }
 protected AbstractRestChannel(RestRequest request, boolean detailedErrorsEnabled) {
   this.request = request;
   this.detailedErrorsEnabled = detailedErrorsEnabled;
   this.format = request.param("format", request.header("Accept"));
   this.filterPath = request.param("filter_path", null);
   this.pretty = request.paramAsBoolean("pretty", false);
   this.human = request.paramAsBoolean("human", false);
 }
Ejemplo n.º 11
0
  @Override
  public void doRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final ClusterStateRequest clusterStateRequest = new ClusterStateRequest();
    clusterStateRequest.clear().nodes(true);
    clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
    clusterStateRequest.masterNodeTimeout(
        request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));

    client
        .admin()
        .cluster()
        .state(
            clusterStateRequest,
            new RestActionListener<ClusterStateResponse>(channel) {
              @Override
              public void processResponse(final ClusterStateResponse clusterStateResponse) {
                NodesInfoRequest nodesInfoRequest = new NodesInfoRequest();
                nodesInfoRequest.clear().jvm(true).os(true).process(true);
                client
                    .admin()
                    .cluster()
                    .nodesInfo(
                        nodesInfoRequest,
                        new RestActionListener<NodesInfoResponse>(channel) {
                          @Override
                          public void processResponse(final NodesInfoResponse nodesInfoResponse) {
                            NodesStatsRequest nodesStatsRequest = new NodesStatsRequest();
                            nodesStatsRequest
                                .clear()
                                .jvm(true)
                                .os(true)
                                .fs(true)
                                .indices(true)
                                .process(true)
                                .script(true);
                            client
                                .admin()
                                .cluster()
                                .nodesStats(
                                    nodesStatsRequest,
                                    new RestResponseListener<NodesStatsResponse>(channel) {
                                      @Override
                                      public RestResponse buildResponse(
                                          NodesStatsResponse nodesStatsResponse) throws Exception {
                                        return RestTable.buildResponse(
                                            buildTable(
                                                request,
                                                clusterStateResponse,
                                                nodesInfoResponse,
                                                nodesStatsResponse),
                                            channel);
                                      }
                                    });
                          }
                        });
              }
            });
  }
Ejemplo n.º 12
0
 public static RestResponse buildResponse(Table table, RestChannel channel) throws Exception {
   RestRequest request = channel.request();
   XContentType xContentType =
       XContentType.fromMediaTypeOrFormat(request.param("format", request.header("Accept")));
   if (xContentType != null) {
     return buildXContentBuilder(table, channel);
   }
   return buildTextPlainResponse(table, channel);
 }
Ejemplo n.º 13
0
 public static RestResponse buildResponse(Table table, RestRequest request, RestChannel channel)
     throws Exception {
   XContentType xContentType =
       XContentType.fromRestContentType(request.param("format", request.header("Content-Type")));
   if (xContentType != null) {
     return buildXContentBuilder(table, request, channel);
   }
   return buildTextPlainResponse(table, request, channel);
 }
 private static String getXForwardedForHeader(RestRequest request) {
   if (!ConfigurationHelper.isNullOrEmpty(request.header("X-Forwarded-For"))) {
     String[] parts = request.header("X-Forwarded-For").split(",");
     if (!ConfigurationHelper.isNullOrEmpty(parts[0])) {
       return parts[0];
     }
   }
   return null;
 }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final Client client) {
   ClusterStatsRequest clusterStatsRequest =
       new ClusterStatsRequest().nodesIds(request.paramAsStringArray("nodeId", null));
   clusterStatsRequest.timeout(request.param("timeout"));
   client
       .admin()
       .cluster()
       .clusterStats(clusterStatsRequest, new RestToXContentListener<>(channel));
 }
Ejemplo n.º 16
0
  static List<DisplayHeader> buildDisplayHeaders(Table table, RestRequest request) {
    List<DisplayHeader> display = new ArrayList<>();
    if (request.hasParam("h")) {
      Set<String> headers = expandHeadersFromRequest(table, request);

      for (String possibility : headers) {
        DisplayHeader dispHeader = null;

        if (table.getAsMap().containsKey(possibility)) {
          dispHeader = new DisplayHeader(possibility, possibility);
        } else {
          for (Table.Cell headerCell : table.getHeaders()) {
            String aliases = headerCell.attr.get("alias");
            if (aliases != null) {
              for (String alias : Strings.splitStringByCommaToArray(aliases)) {
                if (possibility.equals(alias)) {
                  dispHeader = new DisplayHeader(headerCell.value.toString(), alias);
                  break;
                }
              }
            }
          }
        }

        if (dispHeader != null && checkOutputTimestamp(dispHeader, request)) {
          // We know we need the header asked for:
          display.add(dispHeader);

          // Look for accompanying sibling column
          Table.Cell hcell = table.getHeaderMap().get(dispHeader.name);
          String siblingFlag = hcell.attr.get("sibling");
          if (siblingFlag != null) {
            // ...link the sibling and check that its flag is set
            String sibling = siblingFlag + "." + dispHeader.name;
            Table.Cell c = table.getHeaderMap().get(sibling);
            if (c != null && request.paramAsBoolean(siblingFlag, false)) {
              display.add(
                  new DisplayHeader(c.value.toString(), siblingFlag + "." + dispHeader.display));
            }
          }
        }
      }
    } else {
      for (Table.Cell cell : table.getHeaders()) {
        String d = cell.attr.get("default");
        if (Booleans.parseBoolean(d, true)
            && checkOutputTimestamp(cell.value.toString(), request)) {
          display.add(new DisplayHeader(cell.value.toString(), cell.value.toString()));
        }
      }
    }
    return display;
  }
Ejemplo n.º 17
0
  private RestChannelConsumer parseDocPercolate(
      PercolateRequest percolateRequest, RestRequest restRequest, NodeClient client) {
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    percolateRequest.documentType(restRequest.param("type"));
    percolateRequest.routing(restRequest.param("routing"));
    percolateRequest.preference(restRequest.param("preference"));
    percolateRequest.source(restRequest.contentOrSourceParam());

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    return channel -> executePercolate(client, percolateRequest, channel);
  }
  public JsonContent(
      final Client client,
      final RestRequest request,
      final RestChannel channel,
      final SearchType searchType) {
    super(client, request, searchType);

    nettyChannel = NettyUtils.getChannel(channel);

    bulkIndex = request.param("bulk.index");
    bulkType = request.param("bulk.type");
  }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(aliases);
    getAliasesRequest.indices(indices);
    getAliasesRequest.indicesOptions(
        IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
    getAliasesRequest.local(request.paramAsBoolean("local", getAliasesRequest.local()));

    client
        .admin()
        .indices()
        .getAliases(
            getAliasesRequest,
            new RestBuilderListener<GetAliasesResponse>(channel) {
              @Override
              public RestResponse buildResponse(
                  GetAliasesResponse response, XContentBuilder builder) throws Exception {
                // empty body, if indices were specified but no aliases were
                if (indices.length > 0 && response.getAliases().isEmpty()) {
                  return new BytesRestResponse(OK, builder.startObject().endObject());
                } else if (response.getAliases().isEmpty()) {
                  String message =
                      String.format(
                          Locale.ROOT,
                          "alias [%s] missing",
                          toNamesString(getAliasesRequest.aliases()));
                  builder
                      .startObject()
                      .field("error", message)
                      .field("status", RestStatus.NOT_FOUND.getStatus())
                      .endObject();
                  return new BytesRestResponse(RestStatus.NOT_FOUND, builder);
                }

                builder.startObject();
                for (ObjectObjectCursor<String, List<AliasMetaData>> entry :
                    response.getAliases()) {
                  builder.startObject(entry.key, XContentBuilder.FieldCaseConversion.NONE);
                  builder.startObject(Fields.ALIASES);
                  for (AliasMetaData alias : entry.value) {
                    AliasMetaData.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
                  }
                  builder.endObject();
                  builder.endObject();
                }
                builder.endObject();
                return new BytesRestResponse(OK, builder);
              }
            });
  }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    final ClusterUpdateSettingsRequest clusterUpdateSettingsRequest =
        Requests.clusterUpdateSettingsRequest();
    clusterUpdateSettingsRequest.listenerThreaded(false);
    try {
      Map<String, Object> source =
          XContentFactory.xContent(request.content()).createParser(request.content()).mapAndClose();
      if (source.containsKey("transient")) {
        clusterUpdateSettingsRequest.transientSettings((Map) source.get("transient"));
      }
      if (source.containsKey("persistent")) {
        clusterUpdateSettingsRequest.persistentSettings((Map) source.get("persistent"));
      }
    } catch (Exception e) {
      try {
        channel.sendResponse(new XContentThrowableRestResponse(request, e));
      } catch (IOException e1) {
        logger.warn("Failed to send response", e1);
      }
      return;
    }

    client
        .admin()
        .cluster()
        .updateSettings(
            clusterUpdateSettingsRequest,
            new ActionListener<ClusterUpdateSettingsResponse>() {
              @Override
              public void onResponse(ClusterUpdateSettingsResponse response) {
                try {
                  channel.sendResponse(new StringRestResponse(RestStatus.OK));
                } catch (Throwable e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                if (logger.isDebugEnabled()) {
                  logger.debug("failed to handle cluster state", e);
                }
                try {
                  channel.sendResponse(new XContentThrowableRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
Ejemplo n.º 21
0
  @Override
  public void handleRequest(
      final RestRequest request, final RestChannel channel, final Client client) {
    final GetRequest getRequest =
        new GetRequest(request.param("index"), request.param("type"), request.param("id"));
    getRequest.operationThreaded(true);
    getRequest.refresh(request.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.routing(
        request.param(
            "routing")); // order is important, set it after routing, so it will set the routing
    getRequest.parent(request.param("parent"));
    getRequest.preference(request.param("preference"));
    getRequest.realtime(request.paramAsBoolean("realtime", getRequest.realtime()));
    // don't get any fields back...
    getRequest.fields(Strings.EMPTY_ARRAY);
    // TODO we can also just return the document size as Content-Length

    client.get(
        getRequest,
        new RestResponseListener<GetResponse>(channel) {
          @Override
          public RestResponse buildResponse(GetResponse response) {
            if (!response.isExists()) {
              return new BytesRestResponse(NOT_FOUND);
            } else {
              return new BytesRestResponse(OK);
            }
          }
        });
  }
Ejemplo n.º 22
0
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final Client client)
     throws IOException {
   final SearchRequest searchRequest =
       new SearchRequest(
           Strings.splitStringByCommaToArray(request.param("index")), new SearchSourceBuilder());
   searchRequest.indicesOptions(
       IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));
   if (RestActions.hasBodyContent(request)) {
     final BytesReference sourceBytes = RestActions.getRestContent(request);
     try (XContentParser parser =
         XContentFactory.xContent(sourceBytes).createParser(sourceBytes)) {
       final QueryParseContext context =
           new QueryParseContext(queryRegistry, parser, parseFieldMatcher);
       searchRequest.source().suggest(SuggestBuilder.fromXContent(context, suggesters));
     }
   } else {
     throw new IllegalArgumentException("no content or source provided to execute suggestion");
   }
   searchRequest.routing(request.param("routing"));
   searchRequest.preference(request.param("preference"));
   client.search(
       searchRequest,
       new RestBuilderListener<SearchResponse>(channel) {
         @Override
         public RestResponse buildResponse(SearchResponse response, XContentBuilder builder)
             throws Exception {
           RestStatus restStatus =
               RestStatus.status(
                   response.getSuccessfulShards(),
                   response.getTotalShards(),
                   response.getShardFailures());
           builder.startObject();
           buildBroadcastShardsHeader(
               builder,
               request,
               response.getTotalShards(),
               response.getSuccessfulShards(),
               response.getFailedShards(),
               response.getShardFailures());
           Suggest suggest = response.getSuggest();
           if (suggest != null) {
             suggest.toInnerXContent(builder, request);
           }
           builder.endObject();
           return new BytesRestResponse(restStatus, builder);
         }
       });
 }
  @SuppressWarnings({"unchecked"})
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    PutIndexTemplateRequest putRequest = new PutIndexTemplateRequest(request.param("name"));

    try {
      putRequest.create(request.paramAsBoolean("create", false));
      putRequest.cause(request.param("cause", ""));
      putRequest.timeout(request.paramAsTime("timeout", timeValueSeconds(10)));
      putRequest.source(
          request.contentByteArray(), request.contentByteArrayOffset(), request.contentLength());
    } catch (Exception e) {
      try {
        channel.sendResponse(new XContentThrowableRestResponse(request, e));
      } catch (IOException e1) {
        logger.warn("Failed to send response", e1);
      }
      return;
    }

    putRequest.template(request.param("template", putRequest.template()));
    putRequest.order(request.paramAsInt("order", putRequest.order()));

    client
        .admin()
        .indices()
        .putTemplate(
            putRequest,
            new ActionListener<PutIndexTemplateResponse>() {
              @Override
              public void onResponse(PutIndexTemplateResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder
                      .startObject()
                      .field(Fields.OK, true)
                      .field(Fields.ACKNOWLEDGED, response.acknowledged())
                      .endObject();
                  channel.sendResponse(new XContentRestResponse(request, OK, builder));
                } catch (IOException e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new XContentThrowableRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
Ejemplo n.º 24
0
  public static RestResponse buildTextPlainResponse(
      Table table, RestRequest request, RestChannel channel) {
    boolean verbose = request.paramAsBoolean("v", false);
    boolean help = request.paramAsBoolean("h", false);
    if (help) {
      int[] width = buildHelpWidths(table, request, verbose);
      StringBuilder out = new StringBuilder();
      for (Table.Cell cell : table.getHeaders()) {
        // need to do left-align always, so create new cells
        pad(new Table.Cell(cell.value), width[0], request, out);
        out.append(" ");
        pad(
            new Table.Cell(cell.attr.containsKey("desc") ? cell.attr.get("desc") : "not available"),
            width[1],
            request,
            out);
        out.append("\n");
      }
      return new StringRestResponse(RestStatus.OK, out.toString());
    }

    int[] width = buildWidths(table, request, verbose);
    Set<String> displayHeaders = buildDisplayHeaders(table, request);

    StringBuilder out = new StringBuilder();
    if (verbose) {
      // print the headers
      for (int i = 0; i < width.length; i++) {
        String headerName = table.getHeaders().get(i).value.toString();
        if (displayHeaders.contains(headerName)) {
          pad(table.getHeaders().get(i), width[i], request, out);
          out.append(" ");
        }
      }
      out.append("\n");
    }
    for (List<Table.Cell> row : table.getRows()) {
      for (int i = 0; i < width.length; i++) {
        String headerName = table.getHeaders().get(i).value.toString();
        if (displayHeaders.contains(headerName)) {
          pad(row.get(i), width[i], request, out);
          out.append(" ");
        }
      }
      out.append("\n");
    }

    return new StringRestResponse(RestStatus.OK, out.toString());
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final Client client) {
   PutRepositoryRequest putRepositoryRequest = putRepositoryRequest(request.param("repository"));
   putRepositoryRequest.source(request.content().toUtf8());
   putRepositoryRequest.verify(request.paramAsBoolean("verify", true));
   putRepositoryRequest.masterNodeTimeout(
       request.paramAsTime("master_timeout", putRepositoryRequest.masterNodeTimeout()));
   putRepositoryRequest.timeout(request.paramAsTime("timeout", putRepositoryRequest.timeout()));
   client
       .admin()
       .cluster()
       .putRepository(
           putRepositoryRequest, new AcknowledgedRestListener<PutRepositoryResponse>(channel));
 }
Ejemplo n.º 26
0
  void parseDocPercolate(
      PercolateRequest percolateRequest,
      RestRequest restRequest,
      RestChannel restChannel,
      final Client client) {
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    percolateRequest.documentType(restRequest.param("type"));
    percolateRequest.routing(restRequest.param("routing"));
    percolateRequest.preference(restRequest.param("preference"));
    percolateRequest.source(RestActions.getRestContent(restRequest));

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    executePercolate(percolateRequest, restChannel, client);
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final NodeClient client) {
   RestoreSnapshotRequest restoreSnapshotRequest =
       restoreSnapshotRequest(request.param("repository"), request.param("snapshot"));
   restoreSnapshotRequest.masterNodeTimeout(
       request.paramAsTime("master_timeout", restoreSnapshotRequest.masterNodeTimeout()));
   restoreSnapshotRequest.waitForCompletion(request.paramAsBoolean("wait_for_completion", false));
   restoreSnapshotRequest.source(request.content().utf8ToString());
   client
       .admin()
       .cluster()
       .restoreSnapshot(
           restoreSnapshotRequest, new RestToXContentListener<RestoreSnapshotResponse>(channel));
 }
Ejemplo n.º 28
0
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final NodeClient client)
     throws Exception {
   boolean helpWanted = request.paramAsBoolean("help", false);
   if (helpWanted) {
     Table table = getTableWithHeader(request);
     int[] width = buildHelpWidths(table, request);
     BytesStreamOutput bytesOutput = channel.bytesOutput();
     UTF8StreamWriter out = new UTF8StreamWriter().setOutput(bytesOutput);
     for (Table.Cell cell : table.getHeaders()) {
       // need to do left-align always, so create new cells
       pad(new Table.Cell(cell.value), width[0], request, out);
       out.append(" | ");
       pad(
           new Table.Cell(cell.attr.containsKey("alias") ? cell.attr.get("alias") : ""),
           width[1],
           request,
           out);
       out.append(" | ");
       pad(
           new Table.Cell(cell.attr.containsKey("desc") ? cell.attr.get("desc") : "not available"),
           width[2],
           request,
           out);
       out.append("\n");
     }
     out.close();
     channel.sendResponse(
         new BytesRestResponse(
             RestStatus.OK, BytesRestResponse.TEXT_CONTENT_TYPE, bytesOutput.bytes()));
   } else {
     doRequest(request, channel, client);
   }
 }
Ejemplo n.º 29
0
  public static RestResponse buildTextPlainResponse(
      Table table, RestRequest request, RestChannel channel) {
    boolean verbose = request.paramAsBoolean("v", false);

    List<DisplayHeader> headers = buildDisplayHeaders(table, request);
    int[] width = buildWidths(table, request, verbose, headers);

    StringBuilder out = new StringBuilder();
    if (verbose) {
      for (int col = 0; col < headers.size(); col++) {
        DisplayHeader header = headers.get(col);
        pad(
            new Table.Cell(header.display, table.findHeaderByName(header.name)),
            width[col],
            request,
            out);
        out.append(" ");
      }
      out.append("\n");
    }

    for (int row = 0; row < table.getRows().size(); row++) {
      for (int col = 0; col < headers.size(); col++) {
        DisplayHeader header = headers.get(col);
        pad(table.getAsMap().get(header.name).get(row), width[col], request, out);
        out.append(" ");
      }
      out.append("\n");
    }

    return new StringRestResponse(RestStatus.OK, out.toString());
  }
Ejemplo n.º 30
0
  public static RestResponse buildTextPlainResponse(
      Table table, RestRequest request, RestChannel channel) {
    boolean verbose = request.paramAsBoolean("v", true);
    int[] width = buildWidths(table, request, verbose);
    Set<String> displayHeaders = buildDisplayHeaders(table, request);

    StringBuilder out = new StringBuilder();
    if (verbose) {
      // print the headers
      for (int i = 0; i < width.length; i++) {
        String headerName = table.getHeaders().get(i).value.toString();
        if (displayHeaders.contains(headerName)) {
          pad(table.getHeaders().get(i), width[i], request, out);
          out.append(" ");
        }
      }
      out.append("\n");
    }
    for (List<Table.Cell> row : table.getRows()) {
      for (int i = 0; i < width.length; i++) {
        String headerName = table.getHeaders().get(i).value.toString();
        if (displayHeaders.contains(headerName)) {
          pad(row.get(i), width[i], request, out);
          out.append(" ");
        }
      }
      out.append("\n");
    }

    return new StringRestResponse(RestStatus.OK, out.toString());
  }