@Override public String toString() { String strVal = this.strVal; if (strVal == null) { this.strVal = strVal = toString( getClass(), defaultHostname(), hostnamePattern(), sslContext(), serviceConfigs()); } return strVal; }
VirtualHost decorate(@Nullable Function<Service<HttpRequest, HttpResponse>, Service<HttpRequest, HttpResponse>> decorator) { if (decorator == null) { return this; } final List<ServiceConfig> services = this.services.stream().map(cfg -> { final PathMapping pathMapping = cfg.pathMapping(); final Service<HttpRequest, HttpResponse> service = decorator.apply(cfg.service()); final String loggerName = cfg.loggerName().orElse(null); return new ServiceConfig(pathMapping, service, loggerName); }).collect(Collectors.toList()); return new VirtualHost(defaultHostname(), hostnamePattern(), sslContext(), services, producibleMediaTypes()); }
private VirtualHost normalizeDefaultVirtualHost(VirtualHost h, @Nullable SslContext defaultSslContext) { final SslContext sslCtx = h.sslContext() != null ? h.sslContext() : defaultSslContext; return new VirtualHost( h.defaultHostname(), "*", sslCtx, h.serviceConfigs().stream().map( e -> new ServiceConfig(e.pathMapping(), e.service(), e.loggerName().orElse(null))) .collect(Collectors.toList()), h.producibleMediaTypes(), rejectedPathMappingHandler, host -> h.accessLogger()); }
@Override public String toString() { if (virtualHost != null) { return virtualHost.hostnamePattern() + ": " + pathMapping + " -> " + service; } else { return pathMapping + " -> " + service; } } }
private String hostname(ChannelHandlerContext ctx, HttpHeaders headers) { final String hostname = headers.authority(); if (hostname == null) { // Fill the authority with the default host name and current port, just in case the client did not // send it. final String defaultHostname = config.defaultVirtualHost().defaultHostname(); final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort(); headers.authority(defaultHostname + ':' + port); return defaultHostname; } final int hostnameColonIdx = hostname.lastIndexOf(':'); if (hostnameColonIdx < 0) { return hostname; } return hostname.substring(0, hostnameColonIdx); }
final VirtualHost defaultVirtualHost; if (this.defaultVirtualHost != null) { defaultVirtualHost = this.defaultVirtualHost.decorate(decorator); } else { defaultVirtualHost = defaultVirtualHostBuilder.build().decorate(decorator); if (decorator != null) { virtualHosts = this.virtualHosts.stream() .map(h -> h.decorate(decorator)) .collect(Collectors.toList()); } else { if (vh.accessLoggerOrNull() == null) { final Logger logger = accessLoggerMapper.apply(vh); vh.hostnamePattern()); vh.accessLogger(logger); if (defaultVirtualHost.accessLoggerOrNull() == null) { final Logger logger = accessLoggerMapper.apply(defaultVirtualHost); checkState(logger != null, "accessLoggerMapper.apply() has returned null for the default virtual host."); defaultVirtualHost.accessLogger(logger); mappingBuilder = new DomainNameMappingBuilder<>(defaultSslContext); for (VirtualHost h : virtualHosts) { final SslContext sslCtx = h.sslContext(); if (sslCtx != null) { mappingBuilder.add(h.hostnamePattern(), sslCtx);
mappingBuilder.add(h.hostnamePattern(), h); virtualHostsCopy.forEach(h -> h.setServerConfig(this)); if (virtualHostsCopy.stream().allMatch(h -> h.serviceConfigs().isEmpty())) { throw new IllegalArgumentException("no services in the server"); .flatMap(h -> h.serviceConfigs().stream()) .collect(toImmutableList());
/** * Finds the {@link List} of {@link VirtualHost}s that contains the specified {@link Service}. If there's * no match, an empty {@link List} is returned. Note that this is potentially an expensive operation and * thus should not be used in a performance-sensitive path. */ public List<VirtualHost> findVirtualHosts(Service<?, ?> service) { requireNonNull(service, "service"); @SuppressWarnings("rawtypes") final Class<? extends Service> serviceType = service.getClass(); final List<VirtualHost> res = new ArrayList<>(); for (VirtualHost h : virtualHosts) { for (ServiceConfig c : h.serviceConfigs()) { // Consider the case where the specified service is decorated before being added. final Service<?, ?> s = c.service(); @SuppressWarnings("rawtypes") final Optional<? extends Service> sOpt = s.as(serviceType); if (!sOpt.isPresent()) { continue; } if (sOpt.get() == service) { res.add(c.virtualHost()); break; } } } return res; }
/** * Returns a newly-created {@link VirtualHost} based on the properties of this builder and the services * added to this builder. */ protected VirtualHost build() { final List<MediaType> producibleTypes = new ArrayList<>(); // Collect producible media types over this virtual host. services.forEach(s -> producibleTypes.addAll(s.pathMapping().produceTypes())); final VirtualHost virtualHost = new VirtualHost(defaultHostname, hostnamePattern, sslContext, services, new MediaTypeSet(producibleTypes), accessLoggerMapper); return decorator != null ? virtualHost.decorate(decorator) : virtualHost; }
/** * Writes an access log for the specified {@link RequestLog}. */ static void write(List<AccessLogComponent> format, RequestLog log) { final VirtualHost host = ((ServiceRequestContext) log.context()).virtualHost(); final Logger logger = host.accessLogger(); if (!format.isEmpty() && logger.isInfoEnabled()) { logger.info(format(format, log)); } }
@Override public ServiceSpecification generateSpecification(Set<ServiceConfig> serviceConfigs) { requireNonNull(serviceConfigs, "serviceConfigs"); final Map<Class<?>, Set<MethodInfo>> methodInfos = new HashMap<>(); final Map<Class<?>, String> serviceDescription = new HashMap<>(); serviceConfigs.forEach(sc -> { final Optional<AnnotatedHttpService> service = sc.service().as(AnnotatedHttpService.class); service.ifPresent( httpService -> { addMethodInfo(methodInfos, sc.virtualHost().hostnamePattern(), httpService); addServiceDescription(serviceDescription, httpService); }); }); return generate(serviceDescription, methodInfos); }
/** * Returns the hostname of the default {@link VirtualHost}, which is the hostname of the machine unless * configured explicitly via {@link ServerBuilder#defaultVirtualHost(VirtualHost)}. */ public String defaultHostname() { return config().defaultVirtualHost().defaultHostname(); }
private static ServiceConfig findServiceConfig(Server server, String path, Service<?, ?> service) { for (ServiceConfig cfg : server.config().defaultVirtualHost().serviceConfigs()) { final Optional<String> exactPath = cfg.pathMapping().exactPath(); if (!exactPath.isPresent()) { continue; } if (!path.equals(exactPath.get())) { continue; } if (cfg.service().as(service.getClass()).isPresent()) { return cfg; } } throw new Error(); // Never reaches here. } }
if (!virtualHosts.isEmpty()) { virtualHosts.forEach(c -> { buf.append(VirtualHost.toString(null, c.defaultHostname(), c.hostnamePattern(), c.sslContext(), c.serviceConfigs())); buf.append(", "); }); buf.append(VirtualHost.toString(null, defaultVirtualHost.defaultHostname(), "*", defaultVirtualHost.sslContext(), defaultVirtualHost.serviceConfigs())); } else { buf.setLength(buf.length() - 2); buf.append(VirtualHost.toString(null, defaultVirtualHost.defaultHostname(), "*", defaultVirtualHost.sslContext(), defaultVirtualHost.serviceConfigs()));
@Override public ServiceSpecification generateSpecification(Set<ServiceConfig> serviceConfigs) { final Map<Class<?>, EntryBuilder> map = new LinkedHashMap<>(); for (ServiceConfig c : serviceConfigs) { final THttpService service = c.service().as(THttpService.class).get(); service.entries().forEach((serviceName, entry) -> { for (Class<?> iface : entry.interfaces()) { final Class<?> serviceClass = iface.getEnclosingClass(); final EntryBuilder builder = map.computeIfAbsent(serviceClass, cls -> new EntryBuilder(serviceClass)); // Add all available endpoints. Accept only the services with exact and prefix path // mappings, whose endpoint path can be determined. final PathMapping pathMapping = c.pathMapping(); final String path = pathMapping.exactPath().orElse(pathMapping.prefix().orElse(null)); if (path != null) { builder.endpoint(new EndpointInfoBuilder(c.virtualHost().hostnamePattern(), path) .fragment(serviceName) .defaultFormat(service.defaultSerializationFormat()) .availableFormats(service.allowedSerializationFormats()) .build()); } } }); } final List<Entry> entries = map.values().stream() .map(EntryBuilder::build) .collect(Collectors.toList()); return generate(entries); }
.append(sessionProtocol().uriText()) .append("://") .append(virtualHost().defaultHostname());
private static Service<?, ?> service(ServerBuilder sb) { final Server server = sb.build(); return server.config().defaultVirtualHost().serviceConfigs().get(0).service(); }
final String serviceName = service.getServiceDescriptor().getName(); map.get(serviceName).endpoint( new EndpointInfoBuilder(serviceConfig.virtualHost().hostnamePattern(),
final ServiceRequestContext sCtx = (ServiceRequestContext) ctx; final int port = ((InetSocketAddress) sCtx.remoteAddress()).getPort(); final String hostname = sCtx.virtualHost().defaultHostname(); if (port == ctx.sessionProtocol().defaultPort()) { authority = hostname;
private List<Tag> buildTags(RequestLog log) { final RequestContext ctx = log.context(); final Object requestContent = log.requestContent(); String methodName = null; if (requestContent instanceof RpcRequest) { methodName = ((RpcRequest) requestContent).method(); } if (methodName == null) { final HttpHeaders requestHeaders = log.requestHeaders(); final HttpMethod httpMethod = requestHeaders.method(); if (httpMethod != null) { methodName = httpMethod.name(); } } if (methodName == null) { methodName = MoreObjects.firstNonNull(log.method().name(), "__UNKNOWN_METHOD__"); } final List<Tag> tags = new ArrayList<>(4); // method, hostNamePattern, pathMapping, status tags.add(Tag.of("method", methodName)); if (ctx instanceof ServiceRequestContext) { final ServiceRequestContext sCtx = (ServiceRequestContext) ctx; tags.add(Tag.of("hostnamePattern", sCtx.virtualHost().hostnamePattern())); tags.add(Tag.of("pathMapping", sCtx.pathMapping().meterTag())); } return tags; } };