Java Code Examples for io.vertx.core.MultiMap#set()

The following examples show how to use io.vertx.core.MultiMap#set() . 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: AbstractHttpMessageConverter.java    From vertx-rest-client with Apache License 2.0 6 votes vote down vote up
@Override
public void write(T object, MediaType contentType, HttpOutputMessage httpOutputMessage) throws HttpMessageConverterException {
    try {
        final MultiMap headers = httpOutputMessage.getHeaders();
        if (headers.get(HttpHeaders.CONTENT_TYPE) == null) {
            MediaType contentTypeToUse = contentType;
            if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
                contentTypeToUse = getDefaultContentType(object);
            }
            if (contentTypeToUse != null) {
                headers.set(HttpHeaders.CONTENT_TYPE, contentTypeToUse.toString());
            }
        }

        writeInternal(object, httpOutputMessage);
    } catch (HttpMessageConverterException e) {
        throw e;
    } catch (Throwable t) {
        throw new HttpMessageConverterException("Error writing object", t);
    }
}
 
Example 2
Source File: ConsumableBidder.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
private static MultiMap resolveHeaders(BidRequest request) {
    final MultiMap headers = HttpUtil.headers();
    final Device device = request.getDevice();
    if (device != null) {
        HttpUtil.addHeaderIfValueIsNotEmpty(headers, "User-Agent", device.getUa());
        final String ip = device.getIp();
        if (StringUtils.isNotBlank(ip)) {
            headers.add("Forwarded", "for=" + ip);
            headers.add("X-Forwarded-For", ip);
        }
    }

    final User user = request.getUser();
    if (user != null && StringUtils.isNotBlank(user.getBuyeruid())) {
        headers.add("Cookie", String.format("azk=%s", user.getBuyeruid().trim()));
    }

    final Site site = request.getSite();
    if (site != null && StringUtils.isNotBlank(site.getPage())) {
        headers.set("Referer", site.getPage());
        try {
            headers.set("Origin", HttpUtil.validateUrl(site.getPage()));
        } catch (IllegalArgumentException e) {
            // do nothing, just skip adding this header
        }
    }

    return headers;
}
 
Example 3
Source File: ProxyService.java    From okapi with Apache License 2.0 5 votes vote down vote up
void callSystemInterface(MultiMap headersIn,
                         Tenant tenant, ModuleInstance inst,
                         String request, Handler<AsyncResult<OkapiClient>> fut) {

  if (!headersIn.contains(XOkapiHeaders.URL)) {
    headersIn.set(XOkapiHeaders.URL, okapiUrl);
  }
  String tenantId = tenant.getId(); // the tenant we are about to enable
  // Check if the actual tenant has auth enabled. If yes, get a token for it.
  // If we have auth for current (super)tenant is irrelevant here!
  logger.debug("callSystemInterface: Checking if {} has auth", tenantId);

  moduleManager.getEnabledModules(tenant, mres -> {
    if (mres.failed()) { // Should not happen
      fut.handle(new Failure<>(mres.getType(), mres.cause()));
      return;
    }
    List<ModuleDescriptor> enabledModules = mres.result();
    for (ModuleDescriptor md : enabledModules) {
      RoutingEntry[] filters = md.getFilters();
      if (filters != null) {
        for (RoutingEntry filt : filters) {
          if (XOkapiHeaders.FILTER_AUTH.equals(filt.getPhase())) {
            logger.debug("callSystemInterface: Found auth filter in {}", md.getId());
            authForSystemInterface(md, filt, tenantId, inst, request, headersIn, fut);
            return;
          }
        }
      }
    }
    logger.debug("callSystemInterface: No auth for {} calling with "
        + "tenant header only", tenantId);
    doCallSystemInterface(headersIn, tenantId, null, inst, null, request, fut);
  });
}
 
Example 4
Source File: MultipartHttpMessageConverter.java    From vertx-rest-client with Apache License 2.0 5 votes vote down vote up
private void setContentDispositionFormData(String name, String filename, MultiMap multiMap) {
    checkNotNull(name, "name must not be null");
    checkArgument(!name.isEmpty(), "name must not be empty");

    final StringBuilder builder = new StringBuilder("form-data; name=\"");
    builder.append(name).append('\"');
    if (filename != null) {
        builder.append("; filename=\"");
        builder.append(filename).append('\"');
    }
    multiMap.set(CONTENT_DISPOSITION, builder.toString());
}
 
Example 5
Source File: MailEncoder.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
/**
 * create the headers of the MIME message by combining the headers the user has supplied with the ones necessary for
 * the message
 *
 * @return MultiMap of final headers
 */
private MultiMap createHeaders(MultiMap additionalHeaders) {
  MultiMap headers = MultiMap.caseInsensitiveMultiMap();;

  if (!message.isFixedHeaders()) {
    headers.set("MIME-Version", "1.0");
    headers.set("Message-ID", Utils.generateMessageID(hostname, userAgent));
    headers.set("Date", Utils.generateDate());

    if (message.getSubject() != null) {
      headers.set("Subject", Utils.encodeHeader(message.getSubject(), 9));
    }

    if (message.getFrom() != null) {
      headers.set("From", Utils.encodeHeaderEmail(message.getFrom(), 6));
    }
    if (message.getTo() != null) {
      headers.set("To", Utils.encodeEmailList(message.getTo(), 4));
    }
    if (message.getCc() != null) {
      headers.set("Cc", Utils.encodeEmailList(message.getCc(), 4));
    }

    headers.addAll(additionalHeaders);
  }

  // add the user-supplied headers as last step, this way it is possible
  // to supply a custom Message-ID for example.
  MultiMap headersToSet = message.getHeaders();
  if (headersToSet != null) {
    for (String key : headersToSet.names()) {
      headers.remove(key);
    }
    headers.addAll(headersToSet);
  }

  messageID = headers.get("Message-ID");
  
  return headers;
}
 
Example 6
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 7
Source File: MailEncoderTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeadersExist() {
  MailMessage message = new MailMessage();
  MultiMap headers = MultiMap.caseInsensitiveMultiMap();
  headers.set("mime-version", "2.1");
  message.setHeaders(headers);
  String mime = new MailEncoder(message, HOSTNAME).encode().toLowerCase(Locale.ENGLISH);
  assertThat(mime, containsString("mime-version: 2.1"));
  assertThat(mime, not(containsString("mime-version: 1.0")));
}
 
Example 8
Source File: MailEncoderTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testFixedHeaders() {
  MailMessage message = new MailMessage();
  MultiMap headers = MultiMap.caseInsensitiveMultiMap();
  headers.set("X-Header", "value");
  message.setHeaders(headers);
  message.setFixedHeaders(true);
  String mime = new MailEncoder(message, HOSTNAME).encode();
  assertThat(mime, containsString("X-Header: value"));
  assertThat(mime, not(containsString("MIME-Version: 1.0")));
}
 
Example 9
Source File: MailEncoderTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testFixedHeadersExist() {
  MailMessage message = new MailMessage();
  MultiMap headers = MultiMap.caseInsensitiveMultiMap();
  headers.set("Content-Type", "type");
  message.setHeaders(headers);
  message.setFixedHeaders(true);
  String mime = new MailEncoder(message, HOSTNAME).encode();
  assertThat(mime, containsString("Content-Type: type"));
  assertThat(mime, not(containsString("Content-Type: text/plain")));
}
 
Example 10
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 11
Source File: WebClientExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void sendMultipart(WebClient client) {
  MultiMap form = MultiMap.caseInsensitiveMultiMap();
  form.set("firstName", "Dale");
  form.set("lastName", "Cooper");

  // Submit the form as a multipart form body
  client
    .post(8080, "myserver.mycompany.com", "/some-uri")
    .putHeader("content-type", "multipart/form-data")
    .sendForm(form)
    .onSuccess(res -> {
      // OK
    });
}
 
Example 12
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 13
Source File: ProxyService.java    From okapi with Apache License 2.0 4 votes vote down vote up
private void passFilterHeaders(RoutingContext ctx, ProxyContext pc, ModuleInstance mi) {
  // Pass the X-Okapi-Filter header for filters (only)
  // And all kind of things for the auth filter
  MultiMap headers = ctx.request().headers();
  headers.remove(XOkapiHeaders.FILTER);

  final String phase = mi.getRoutingEntry().getPhase();
  if (phase != null) {
    String pth = mi.getRoutingEntry().getPathPattern();
    if (pth == null) {
      pth = mi.getRoutingEntry().getPath();
    }
    String filt = mi.getRoutingEntry().getPhase() + " " + pth;
    pc.debug("Adding " + XOkapiHeaders.FILTER + ": " + filt);
    // The auth filter needs all kinds of special headers
    headers.add(XOkapiHeaders.FILTER, filt);

    boolean badAuth = pc.getAuthRes() != 0 && (pc.getAuthRes() < 200 || pc.getAuthRes() >= 300);
    switch (phase) {
      case XOkapiHeaders.FILTER_AUTH:
        authHeaders(pc.getModList(), headers, pc);
        break;
      case XOkapiHeaders.FILTER_PRE:
        // pass request headers and failed auth result
        if (badAuth) {
          headers.add(XOkapiHeaders.AUTH_RESULT, "" + pc.getAuthRes());
        }
        break;
      case XOkapiHeaders.FILTER_POST:
        // pass request headers and failed handler/auth result
        if (pc.getHandlerRes() > 0) {
          String hresult = String.valueOf(pc.getHandlerRes());
          headers.set(XOkapiHeaders.HANDLER_RESULT, hresult);
          headers.set(XOkapiHeaders.HANDLER_HEADERS, Json.encode(pc.getHandlerHeaders()));
        } else if (badAuth) {
          headers.set(XOkapiHeaders.AUTH_RESULT, "" + pc.getAuthRes());
          headers.set(XOkapiHeaders.AUTH_HEADERS, Json.encode(pc.getAuthHeaders()));
        } else {
          logger.warn("proxyR: postHeader: Oops, no result to pass to post handler");
        }
        break;
      default:
        logger.error("Not supported phase: {}", phase);
        break;
    }
  }
}
 
Example 14
Source File: Utils.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public static void addToMapIfAbsent(MultiMap map, CharSequence key, String value) {
  if (!map.contains(key)) {
    map.set(key, value);
  }
}
 
Example 15
Source File: BasicAuth.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Override
public Authenticator authenticate(Vertx vertx, Map<String, String> config, MultiMap headerMap, Handler<AsyncResult<Void>> resultHandler) {
    headerMap.set("Authorization", Basic.encode(config.get("username"), config.get("password")));
    resultHandler.handle(Future.succeededFuture());
    return this;
}