io.vertx.core.MultiMap Java Examples

The following examples show how to use io.vertx.core.MultiMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ActionsHandler.java    From hawkular-alerts with Apache License 2.0 6 votes vote down vote up
ActionsCriteria buildCriteria(MultiMap params) {
    ActionsCriteria criteria = new ActionsCriteria();
    if (params.get(PARAM_START_TIME) != null) {
        criteria.setStartTime(Long.valueOf(params.get(PARAM_START_TIME)));
    }
    if (params.get(PARAM_END_TIME) != null) {
        criteria.setEndTime(Long.valueOf(params.get(PARAM_END_TIME)));
    }
    if (params.get(PARAM_ACTION_PLUGINS) != null) {
        criteria.setActionPlugins(Arrays.asList(params.get(PARAM_ACTION_PLUGINS).split(COMMA)));
    }
    if (params.get(PARAM_ACTION_IDS) != null) {
        criteria.setActionIds(Arrays.asList(params.get(PARAM_ACTION_IDS).split(COMMA)));
    }
    if (params.get(PARAM_ALERTS_IDS) != null) {
        criteria.setEventIds(Arrays.asList(params.get(PARAM_ALERTS_IDS).split(COMMA)));
    }
    if (params.get(PARAM_EVENT_IDS) != null) {
        criteria.setEventIds(Arrays.asList(params.get(PARAM_EVENT_IDS).split(COMMA)));
    }
    if (params.get(PARAM_RESULTS) != null) {
        criteria.setResults(Arrays.asList(params.get(PARAM_RESULTS).split(COMMA)));
    }
    return criteria;
}
 
Example #2
Source File: CorsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the HTTP adapter returns matching CORS headers in response to a
 * CORS preflight request for posting a command response.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCorsPreflightRequestForPostingCommandResponse(final VertxTestContext ctx) {

    httpClient.options(
            String.format("/%s/res/%s", CommandConstants.COMMAND_ENDPOINT, "cmd-request-id"),
            MultiMap.caseInsensitiveMultiMap()
                .add(HttpHeaders.ORIGIN, CrudHttpClient.ORIGIN_URI)
                .add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name()),
            status -> status == HttpURLConnection.HTTP_OK)
    .onComplete(ctx.succeeding(headers -> {
        ctx.verify(() -> {
            assertAccessControlHeaders(headers, HttpMethod.POST);
            assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains(Constants.HEADER_COMMAND_RESPONSE_STATUS);
        });
        ctx.completeNow();
    }));
}
 
Example #3
Source File: DeviceRegistryHttpClient.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Adds a device with a given password to an existing tenant.
 * <p>
 * The password will be added as a hashed password using the device identifier as the authentication identifier.
 *
 * @param tenantId The identifier of the tenant to add the device to.
 * @param deviceId The identifier of the device to add.
 * @param data The data to register for the device.
 * @param password The password to use for the device's credentials.
 * @return A future indicating the outcome of the operation.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public Future<MultiMap> addDeviceToTenant(
        final String tenantId,
        final String deviceId,
        final Device data,
        final String password) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(data);
    Objects.requireNonNull(password);

    final PasswordCredential secret = IntegrationTestSupport.createPasswordCredential(deviceId, password);

    return registerDevice(tenantId, deviceId, data)
            .compose(ok -> addCredentials(tenantId, deviceId, Collections.singletonList(secret)));
}
 
Example #4
Source File: Container.java    From sfs with Apache License 2.0 6 votes vote down vote up
public T merge(SfsRequest httpServerRequest) {
    MultiMap headers = httpServerRequest.headers();

    if (headers.contains(X_SFS_OBJECT_REPLICAS)) {
        setObjectReplicas(parseInt(headers.get(X_SFS_OBJECT_REPLICAS)));
    } else {
        setObjectReplicas(NOT_SET);
    }

    if (headers.contains(X_SFS_OBJECT_WRITE_CONSISTENCY)) {
        String str = headers.get(X_SFS_OBJECT_WRITE_CONSISTENCY);
        if (StringUtils.isBlank(str)) {
            // if it's blank set consistency to use node settings
            setObjectWriteConsistency(null);
        } else {
            WriteConsistency writeConsistency = WriteConsistency.fromValueIfExists(headers.get(X_SFS_OBJECT_WRITE_CONSISTENCY));
            if (writeConsistency != null) {
                setObjectWriteConsistency(writeConsistency);
            }
        }
    }

    getMetadata().withHttpHeaders(headers);

    return (T) this;
}
 
Example #5
Source File: ParametersTestAPIClient.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Call cookie_form_noexplode_string with empty body.
 * @param color Parameter color inside cookie
 * @param handler The handler for the asynchronous request
 */
public void cookieFormNoexplodeString(
    String color,
    Handler<AsyncResult<HttpResponse>> handler) {
    // Check required params
    if (color == null) throw new RuntimeException("Missing parameter color");


    // Generate the uri
    String uri = "/cookie/form/noexplode/string";

    HttpRequest request = client.get(uri);

    MultiMap requestCookies = MultiMap.caseInsensitiveMultiMap();
    if (color != null) this.renderCookieParam("color", color, requestCookies);


    this.renderAndAttachCookieHeader(request, requestCookies);
    request.send(handler);
}
 
Example #6
Source File: ApiClient.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Call cookie_form_noexplode_object with empty body.
 * @param color Parameter color inside cookie
 * @param handler The handler for the asynchronous request
 */
public void cookieFormNoexplodeObject(
    Map<String, Object> color,
    Handler<AsyncResult<HttpResponse>> handler) {
    // Check required params
    if (color == null) throw new RuntimeException("Missing parameter color");


    // Generate the uri
    String uri = "/cookie/form/noexplode/object";

    HttpRequest request = client.get(uri);

    MultiMap requestCookies = MultiMap.caseInsensitiveMultiMap();
    if (color != null) this.renderCookieObjectForm("color", color, requestCookies);


    this.renderAndAttachCookieHeader(request, requestCookies);
    request.send(handler);
}
 
Example #7
Source File: ApiClient.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Call cookie_form_explode_object with empty body.
 * @param color Parameter color inside cookie
 * @param handler The handler for the asynchronous request
 */
public void cookieFormExplodeObject(
    Map<String, Object> color,
    Handler<AsyncResult<HttpResponse>> handler) {
    // Check required params
    if (color == null) throw new RuntimeException("Missing parameter color");


    // Generate the uri
    String uri = "/cookie/form/explode/object";

    HttpRequest request = client.get(uri);

    MultiMap requestCookies = MultiMap.caseInsensitiveMultiMap();
    if (color != null) this.renderCookieObjectFormExplode("color", color, requestCookies);


    this.renderAndAttachCookieHeader(request, requestCookies);
    request.send(handler);
}
 
Example #8
Source File: TestVertxClientRequestToHttpServletRequest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void getCharacterEncoding() {
  String contentType = "ct";
  String characterEncoding = "ce";

  MultiMap headers = MultiMap.caseInsensitiveMultiMap();
  new Expectations(HttpUtils.class) {
    {
      HttpUtils.getCharsetFromContentType(contentType);
      result = characterEncoding;
      clientRequest.headers();
      result = headers;
    }
  };

  request.addHeader(HttpHeaders.CONTENT_TYPE, contentType);

  Assert.assertEquals("ce", request.getCharacterEncoding());
}
 
Example #9
Source File: NotificationEventHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotPassEventToAnalyticsReporterWhenAnalyticsValueIsZero() {
    // given
    given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap()
            .add("t", "win")
            .add("b", "bidId")
            .add("a", "accountId")
            .add("x", "0"));

    // when
    notificationHandler.handle(routingContext);

    // then
    verifyZeroInteractions(applicationSettings);
    verifyZeroInteractions(analyticsReporter);
}
 
Example #10
Source File: ParametersTestAPIClient.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Call cookie_form_explode_object with empty body.
 * @param color Parameter color inside cookie
 * @param handler The handler for the asynchronous request
 */
public void cookieFormExplodeObject(
    Map<String, Object> color,
    Handler<AsyncResult<HttpResponse>> handler) {
    // Check required params
    if (color == null) throw new RuntimeException("Missing parameter color");


    // Generate the uri
    String uri = "/cookie/form/explode/object";

    HttpRequest request = client.get(uri);

    MultiMap requestCookies = MultiMap.caseInsensitiveMultiMap();
    if (color != null) this.renderCookieObjectFormExplode("color", color, requestCookies);


    this.renderAndAttachCookieHeader(request, requestCookies);
    request.send(handler);
}
 
Example #11
Source File: VideoHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    given(routingContext.request()).willReturn(httpRequest);
    given(routingContext.response()).willReturn(httpResponse);

    given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap());
    given(httpRequest.headers()).willReturn(new CaseInsensitiveHeaders());

    given(httpResponse.exceptionHandler(any())).willReturn(httpResponse);
    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);
    given(httpResponse.headers()).willReturn(new CaseInsensitiveHeaders());

    given(clock.millis()).willReturn(Instant.now().toEpochMilli());
    timeout = new TimeoutFactory(clock).create(2000L);

    given(exchangeService.holdAuction(any())).willReturn(Future.succeededFuture(BidResponse.builder().build()));

    videoHandler = new VideoHandler(videoRequestFactory, videoResponseFactory, exchangeService, analyticsReporter,
            metrics, clock, jacksonMapper);
}
 
Example #12
Source File: ApiClient.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Call query_form_explode_object with empty body.
 * @param color Parameter color inside query
 * @param handler The handler for the asynchronous request
 */
public void queryFormExplodeObject(
    Map<String, Object> color,
    Handler<AsyncResult<HttpResponse>> handler) {
    // Check required params
    if (color == null) throw new RuntimeException("Missing parameter color");


    // Generate the uri
    String uri = "/query/form/explode/object";

    HttpRequest request = client.get(uri);

    MultiMap requestCookies = MultiMap.caseInsensitiveMultiMap();
    if (color != null) this.addQueryObjectFormExplode("color", color, request);


    this.renderAndAttachCookieHeader(request, requestCookies);
    request.send(handler);
}
 
Example #13
Source File: BodyHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormURLEncoded() throws Exception {
  router.route().handler(rc -> {
    MultiMap attrs = rc.request().formAttributes();
    assertNotNull(attrs);
    assertEquals(3, attrs.size());
    assertEquals("junit-testUserAlias", attrs.get("origin"));
    assertEquals("[email protected]", attrs.get("login"));
    assertEquals("admin", attrs.get("pass word"));
    rc.response().end();
  });
  testRequest(HttpMethod.POST, "/", req -> {
    Buffer buffer = Buffer.buffer();
    buffer.appendString("origin=junit-testUserAlias&login=admin%40foo.bar&pass+word=admin");
    req.headers().set("content-length", String.valueOf(buffer.length()));
    req.headers().set("content-type", "application/x-www-form-urlencoded");
    req.write(buffer);
  }, 200, "OK", null);
}
 
Example #14
Source File: RouterTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testHeadersEndHandler() throws Exception {
  router.route().handler(rc -> {
    rc.addHeadersEndHandler(v -> rc.response().putHeader("header1", "foo"));
    rc.next();
  });
  router.route().handler(rc -> {
    rc.addHeadersEndHandler(v -> rc.response().putHeader("header2", "foo"));
    rc.next();
  });
  router.route().handler(rc -> {
    rc.addHeadersEndHandler(v -> rc.response().putHeader("header3", "foo"));
    rc.response().end();
  });
  testRequest(HttpMethod.GET, "/", null, resp -> {
    MultiMap headers = resp.headers();
    assertTrue(headers.contains("header1"));
    assertTrue(headers.contains("header2"));
    assertTrue(headers.contains("header3"));
  }, 200, "OK", null);
}
 
Example #15
Source File: CorsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the HTTP adapter returns matching CORS headers in response to a
 * CORS preflight request for putting an event.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCorsPreflightRequestForPuttingEvents(final VertxTestContext ctx) {

    httpClient.options(
            String.format("/%s/%s/%s", EventConstants.EVENT_ENDPOINT, "my-tenant", "my-device"),
            MultiMap.caseInsensitiveMultiMap()
                .add(HttpHeaders.ORIGIN, CrudHttpClient.ORIGIN_URI)
                .add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.PUT.name()),
            status -> status == HttpURLConnection.HTTP_OK)
    .onComplete(ctx.succeeding(headers -> {
        ctx.verify(() -> {
            assertAccessControlHeaders(headers, HttpMethod.PUT);
            assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS))
                    .contains(Constants.HEADER_TIME_TILL_DISCONNECT);
        });
        ctx.completeNow();
    }));
}
 
Example #16
Source File: ParametersTestAPIClient.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Call query_form_explode_empty with empty body.
 * @param color Parameter color inside query
 * @param handler The handler for the asynchronous request
 */
public void queryFormExplodeEmpty(
    String color,
    Handler<AsyncResult<HttpResponse>> handler) {
    // Check required params
    if (color == null) throw new RuntimeException("Missing parameter color");


    // Generate the uri
    String uri = "/query/form/explode/empty";

    HttpRequest request = client.get(uri);

    MultiMap requestCookies = MultiMap.caseInsensitiveMultiMap();
    if (color != null) this.addQueryParam("color", color, request);


    this.renderAndAttachCookieHeader(request, requestCookies);
    request.send(handler);
}
 
Example #17
Source File: ProxyService.java    From okapi with Apache License 2.0 5 votes vote down vote up
/**
 * Actually make a request to a system interface, like _tenant. Assumes we are
 * operating as the correct tenant.
 */
private void doCallSystemInterface(
    MultiMap headersIn,
    String tenantId, String authToken, ModuleInstance inst, String modPerms,
    String request, Handler<AsyncResult<OkapiClient>> fut) {
  discoveryManager.getNonEmpty(inst.getModuleDescriptor().getId(), gres -> {
    DeploymentDescriptor instance = null;
    if (gres.succeeded()) {
      instance = pickInstance(gres.result());
    }
    if (instance == null) {
      fut.handle(Future.failedFuture(messages.getMessage("11100",
          inst.getModuleDescriptor().getId(), inst.getPath())));
      return;
    }
    String baseurl = instance.getUrl();
    Map<String, String> headers = sysReqHeaders(headersIn, tenantId, authToken, inst, modPerms);
    headers.put(XOkapiHeaders.URL_TO, baseurl);
    logger.info("syscall begin {} {}{}", inst.getMethod(), baseurl, inst.getPath());
    OkapiClient cli = new OkapiClient(this.httpClient, baseurl, vertx, headers);
    String reqId = inst.getPath().replaceFirst("^[/_]*([^/]+).*", "$1");
    cli.newReqId(reqId); // "tenant" or "tenantpermissions"
    cli.enableInfoLog();
    if (inst.isWithRetry()) {
      cli.setClosedRetry(40000);
    }
    cli.request(inst.getMethod(), inst.getPath(), request, cres -> {
      logger.info("syscall return {} {}{}", inst.getMethod(), baseurl, inst.getPath());
      if (cres.failed()) {
        String msg = messages.getMessage("11101", inst.getMethod(),
            inst.getModuleDescriptor().getId(), inst.getPath(), cres.cause().getMessage());
        logger.warn(msg);
        fut.handle(Future.failedFuture(msg));
        return;
      }
      // Pass response headers - needed for unit test, if nothing else
      fut.handle(Future.succeededFuture(cli));
    });
  });
}
 
Example #18
Source File: HeadersParamInjector.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolve(RoutingContext context, Headers annotation, String paramName, Class<?> resultClass) {
  if (!MultiMap.class.isAssignableFrom(resultClass)) {
    context.fail(new Exception("Could not inject @Headers to the method. Headers parameter should be a MultiMap."));
  }
  return context.request().headers();
}
 
Example #19
Source File: LockerdomeBidder.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Override
public Result<List<HttpRequest<BidRequest>>> makeHttpRequests(BidRequest bidRequest) {
    final List<BidderError> errors = new ArrayList<>();

    final List<Imp> requestImps = bidRequest.getImp();
    final List<Imp> validImps = new ArrayList<>();
    for (Imp imp : requestImps) {
        try {
            validImps.add(validateImp(imp));
        } catch (PreBidException e) {
            errors.add(BidderError.badInput(e.getMessage()));
        }
    }

    if (validImps.isEmpty()) {
        errors.add(BidderError.badInput("No valid or supported impressions in the bid request."));
        return Result.of(Collections.emptyList(), errors);
    }

    final MultiMap headers = HttpUtil.headers()
            .add("x-openrtb-version", "2.5");

    final BidRequest outgoingRequest = validImps.size() != requestImps.size()
            ? bidRequest.toBuilder().imp(validImps).build()
            : bidRequest;

    final String body = mapper.encode(outgoingRequest);

    return Result.of(Collections.singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(endpointUrl)
                    .headers(headers)
                    .body(body)
                    .payload(outgoingRequest)
                    .build()),
            errors);
}
 
Example #20
Source File: WebClientExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void sendHeaders1(WebClient client) {
  HttpRequest<Buffer> request = client
    .get(8080, "myserver.mycompany.com", "/some-uri");

  MultiMap headers = request.headers();
  headers.set("content-type", "application/json");
  headers.set("other-header", "foo");
}
 
Example #21
Source File: ApiWebTestBase.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void testRequestWithForm(HttpMethod method, String path, FormType formType, MultiMap formMap, int statusCode, String statusMessage) throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  HttpRequest<Buffer> request = webClient
    .request(method, 8080, "localhost", path);
  request
    .putHeader("Content-Type", formType.headerValue)
    .sendForm(formMap, (ar) -> {
      assertEquals(statusCode, ar.result().statusCode());
      assertEquals(statusMessage, ar.result().statusMessage());
      latch.countDown();
    });
  awaitLatch(latch);
}
 
Example #22
Source File: MailEncoderTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaders() {
  MailMessage message = new MailMessage();
  MultiMap headers = MultiMap.caseInsensitiveMultiMap();
  headers.set("X-Header", "value");
  message.setHeaders(headers);
  String mime = new MailEncoder(message, HOSTNAME).encode();
  assertThat(mime, containsString("X-Header: value"));
}
 
Example #23
Source File: BasicHttpClient.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Override
public Future<HttpClientResponse> request(HttpMethod method, String url, MultiMap headers, String body,
                                          long timeoutMs) {
    final Promise<HttpClientResponse> promise = Promise.promise();

    if (timeoutMs <= 0) {
        failResponse(new TimeoutException("Timeout has been exceeded"), promise);
    } else {
        final HttpClientRequest httpClientRequest = httpClient.requestAbs(method, url);

        // Vert.x HttpClientRequest timeout doesn't aware of case when a part of the response body is received,
        // but remaining part is delayed. So, overall request/response timeout is involved to fix it.
        final long timerId = vertx.setTimer(timeoutMs, id -> handleTimeout(promise, timeoutMs, httpClientRequest));

        httpClientRequest
                .setFollowRedirects(true)
                .handler(response -> handleResponse(response, promise, timerId))
                .exceptionHandler(exception -> failResponse(exception, promise, timerId));

        if (headers != null) {
            httpClientRequest.headers().addAll(headers);
        }

        if (body != null) {
            httpClientRequest.end(body);
        } else {
            httpClientRequest.end();
        }
    }

    return promise.future();
}
 
Example #24
Source File: WebClientExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void sendForm(WebClient client) {
  MultiMap form = MultiMap.caseInsensitiveMultiMap();
  form.set("firstName", "Dale");
  form.set("lastName", "Cooper");

  // Submit the form as a form URL encoded body
  client
    .post(8080, "myserver.mycompany.com", "/some-uri")
    .sendForm(form)
    .onSuccess(res -> {
      // OK
    });
}
 
Example #25
Source File: PredicateInterceptor.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private <B> HttpResponseImpl<B> responseCopy(HttpClientResponse resp, HttpContext<?> httpContext, B value) {
  return new HttpResponseImpl<>(
    resp.version(),
    resp.statusCode(),
    resp.statusMessage(),
    MultiMap.caseInsensitiveMultiMap().addAll(resp.headers()),
    null,
    new ArrayList<>(resp.cookies()),
    value,
    httpContext.getRedirectedLocations()
  );
}
 
Example #26
Source File: ApiControllerTest.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
@Test
void multiMapTest() {
  MultiMap m = multiMap("k1", "v1",
      "k2", "v2",
      "k3", "v3");

  assertThat(m.get("k1")).isEqualTo("v1");
  assertThat(m.get("k2")).isEqualTo("v2");
  assertThat(m.get("k3")).isEqualTo("v3");
}
 
Example #27
Source File: UserApiImpl.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Create user
 * This can only be done by the logged in user.
 * @param body Created user object (required)
 * @param resultHandler Asynchronous result handler
 */
public void createUser(User body, Handler<AsyncResult<Void>> resultHandler) {
    Object localVarBody = body;
    
    // verify the required parameter 'body' is set
    if (body == null) {
        resultHandler.handle(ApiException.fail(400, "Missing the required parameter 'body' when calling createUser"));
        return;
    }
    
    // create path and map variables
    String localVarPath = "/user";

    // query params
    List<Pair> localVarQueryParams = new ArrayList<>();

    // header params
    MultiMap localVarHeaderParams = MultiMap.caseInsensitiveMultiMap();
    
    // cookie params
    MultiMap localVarCookieParams = MultiMap.caseInsensitiveMultiMap();
    
    // form params
    // TODO: sending files within multipart/form-data is not supported yet (because of vertx web-client)
    Map<String, Object> localVarFormParams = new HashMap<>();
    
    String[] localVarAccepts = {  };
    String[] localVarContentTypes = {  };
    String[] localVarAuthNames = new String[] {  };

    apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccepts, localVarContentTypes, localVarAuthNames, null, resultHandler);
}
 
Example #28
Source File: MainVerticle.java    From okapi with Apache License 2.0 5 votes vote down vote up
private void recurseHandle(RoutingContext ctx) {
  String d = ctx.request().getParam("depth");
  if (d == null || d.isEmpty()) {
    d = "1";
  }
  String depthstr = d; // must be final
  int depth = Integer.parseInt(depthstr);
  if (depth < 0) {
    HttpResponse.responseError(ctx, 400, "Bad recursion, can not be negative " + depthstr);
  } else if (depth == 0) {
    HttpResponse.responseText(ctx, 200);
    ctx.response().end("Recursion done");
  } else {
    OkapiClient ok = new OkapiClient(ctx);
    depth--;
    ok.get("/recurse?depth=" + depth, res -> {
      ok.close();
      if (res.succeeded()) {
        MultiMap respH = ok.getRespHeaders();
        for (Map.Entry<String, String> e : respH.entries()) {
          if (e.getKey().startsWith("X-") || e.getKey().startsWith("x-")) {
            ctx.response().headers().add(e.getKey(), e.getValue());
          }
        }
        HttpResponse.responseText(ctx, 200);
        ctx.response().end(depthstr + " " + res.result());
      } else {
        String message = res.cause().getMessage();
        HttpResponse.responseError(ctx, 500, "Recurse " + depthstr + " failed with " + message);
      }
    });
  }
}
 
Example #29
Source File: MailMessageTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeadersEmpty() {
  MailMessage mailMessage = new MailMessage();
  MultiMap headers = MultiMap.caseInsensitiveMultiMap();
  mailMessage.setHeaders(headers);
  assertEquals(0, mailMessage.getHeaders().size());
  assertEquals("{\"headers\":{}}", mailMessage.toJson().encode());
}
 
Example #30
Source File: PetApiImpl.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes a pet
 * 
 * @param petId Pet id to delete (required)
 * @param apiKey  (optional)
 * @param resultHandler Asynchronous result handler
 */
public void deletePet(Long petId, String apiKey, Handler<AsyncResult<Void>> resultHandler) {
    Object localVarBody = null;
    
    // verify the required parameter 'petId' is set
    if (petId == null) {
        resultHandler.handle(ApiException.fail(400, "Missing the required parameter 'petId' when calling deletePet"));
        return;
    }
    
    // create path and map variables
    String localVarPath = "/pet/{petId}".replaceAll("\\{" + "petId" + "\\}", petId.toString());

    // query params
    List<Pair> localVarQueryParams = new ArrayList<>();

    // header params
    MultiMap localVarHeaderParams = MultiMap.caseInsensitiveMultiMap();
    if (apiKey != null)
    localVarHeaderParams.add("api_key", apiClient.parameterToString(apiKey));

    // cookie params
    MultiMap localVarCookieParams = MultiMap.caseInsensitiveMultiMap();
    
    // form params
    // TODO: sending files within multipart/form-data is not supported yet (because of vertx web-client)
    Map<String, Object> localVarFormParams = new HashMap<>();
    
    String[] localVarAccepts = {  };
    String[] localVarContentTypes = {  };
    String[] localVarAuthNames = new String[] { "petstore_auth" };

    apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccepts, localVarContentTypes, localVarAuthNames, null, resultHandler);
}