Build a new {@link HttpTracing} instance for interfacing with Zipkin

@param environment Environment
@return Brave instance
546018
@Override
  public Optional<HttpTracing> build(final Environment environment) {
    if (!isEnabled()) {
      LOGGER.warn("Zipkin tracing is disabled");
      return Optional.empty();
    }

    final ReporterMetrics metricsHandler = new DropwizardReporterMetrics(environment.metrics());

    final KafkaSender sender =
        KafkaSender.newBuilder()
            .bootstrapServers(bootstrapServers)
            .topic(topic)
            .overrides(overrides)
            .build();

    final AsyncReporter<Span> reporter =
        AsyncReporter.builder(sender).metrics(metricsHandler).build();

    environment.lifecycle().manage(new ReporterManager(reporter, sender));

    LOGGER.info("Sending spans to Kafka topic \"{}\" at: {}", topic, bootstrapServers);

    return buildTracing(environment, reporter);
  }
500280
public static function create(
        BunqEnumApiEnvironmentType $environmentType,
        string $apiKey,
        string $description,
        array $allPermittedIp = [],
        string $proxyUrl = null
    ): ApiContext {
        InstallationUtil::assertDeviceDescriptionIsValid($description);
        InstallationUtil::assertAllIpIsValid($allPermittedIp);

        $apiContext = new static();
        $apiContext->environmentType = $environmentType;
        $apiContext->apiKey = $apiKey;
        $apiContext->proxyUrl = $proxyUrl;
        $apiContext->initialize($description, $allPermittedIp);

        return $apiContext;
    }
797873
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException {
    Preconditions.checkArgument(uploader == null);
    Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET));
    String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod;
    final HttpRequest httpRequest = getAbstractGoogleClient()
        .getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent);
    new MethodOverride().intercept(httpRequest);
    httpRequest.setParser(getAbstractGoogleClient().getObjectParser());
    // custom methods may use POST with no content but require a Content-Length header
    if (httpContent == null && (requestMethod.equals(HttpMethods.POST)
        || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) {
      httpRequest.setContent(new EmptyContent());
    }
    httpRequest.getHeaders().putAll(requestHeaders);
    if (!disableGZipContent) {
      httpRequest.setEncoding(new GZipEncoding());
    }
    final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor();
    httpRequest.setResponseInterceptor(new HttpResponseInterceptor() {

      public void interceptResponse(HttpResponse response) throws IOException {
        if (responseInterceptor != null) {
          responseInterceptor.interceptResponse(response);
        }
        if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) {
          throw newExceptionOnError(response);
        }
      }
    });
    return httpRequest;
  }
1258243
private HttpHandler configureUndertow(Configuration configuration, Undertow.Builder builder, HttpHandler rootHandler, URL undertowResource) {
        try {
            if (jaxb == null) {
                // we don't want static references here
                jaxb = JAXBContext.newInstance("org.ops4j.pax.web.service.undertow.internal.configuration.model",
                        UndertowConfiguration.class.getClassLoader());
            }
            Unmarshaller unmarshaller = jaxb.createUnmarshaller();
            UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();

            Dictionary<String, Object> properties = new Hashtable<>();

            if (configuration instanceof ConfigurationSource) {
                Dictionary<String, Object> externalConfig = ((ConfigurationSource) configuration).getConfiguration();
                if (externalConfig != null) {
                    for (Enumeration<String> e = externalConfig.keys(); e.hasMoreElements(); ) {
                        String key = e.nextElement();
                        properties.put(key, externalConfig.get(key));
                    }
                }
            }
            if (properties.get(WebContainerConstants.PROPERTY_HTTP_PORT) == null && configuration.getHttpPort() != null) {
                properties.put(WebContainerConstants.PROPERTY_HTTP_PORT, Integer.toString(configuration.getHttpPort()));
            }
            if (properties.get(WebContainerConstants.PROPERTY_HTTP_SECURE_PORT) == null && configuration.getHttpSecurePort() != null) {
                properties.put(WebContainerConstants.PROPERTY_HTTP_SECURE_PORT, Integer.toString(configuration.getHttpSecurePort()));
            }

            // BundleContextPropertyResolver gives access to e.g., ${karaf.base}
            final PropertyResolver resolver = new DictionaryPropertyResolver(properties,
                    new BundleContextPropertyResolver(bundleContext));

            // indirect unmarslaling with property resolution *inside XML attribute values*
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setNamespaceAware(true);
            XMLReader xmlReader = spf.newSAXParser().getXMLReader();

            // tricky PropertyResolver -> Properties bridge
            xmlReader.setContentHandler(new ResolvingContentHandler(new Properties() {
                @Override
                public String getProperty(String key) {
                    return resolver.get(key);
                }

                @Override
                public String getProperty(String key, String defaultValue) {
                    String value = resolver.get(key);
                    return value == null ? defaultValue : value;
                }
            }, unmarshallerHandler));
            try (InputStream stream = undertowResource.openStream()) {
                xmlReader.parse(new InputSource(stream));
            }

            UndertowConfiguration cfg = (UndertowConfiguration) unmarshallerHandler.getResult();
            if (cfg == null
                    || cfg.getSocketBindings().size() == 0
                    || cfg.getInterfaces().size() == 0
                    || cfg.getSubsystem() == null
                    || cfg.getSubsystem().getServer() == null) {
                throw new IllegalArgumentException("Problem configuring Undertow server using \"" + undertowResource + "\": invalid XML");
            }
            cfg.init();

            if (LOG.isDebugEnabled()) {
                LOG.debug("Undertow XML configuration: {}", cfg);
            }

            // ok, we have everything unmarshalled from XML to config object
            // we can configure all/some aspects of Undertow now

            Server.HttpListener http = cfg.getSubsystem().getServer().getHttpListener();
            Server.HttpsListener https = cfg.getSubsystem().getServer().getHttpsListener();
            if (http == null && https == null) {
                throw new IllegalArgumentException("No listener configuration available in \"" + undertowResource + "\". Please configure http and/or https listeners.");
            }

            // http listener
            if (http != null) {
                UndertowConfiguration.BindingInfo binding = cfg.bindingInfo(http.getSocketBindingName());
                for (String address : binding.getAddresses()) {
                    LOG.info("Starting undertow http listener on " + address + ":" + binding.getPort());
                    builder.addHttpListener(binding.getPort(), address);
                }
            }

            // https listener
            if (https != null) {
                UndertowConfiguration.BindingInfo binding = cfg.bindingInfo(https.getSocketBindingName());
                SecurityRealm realm = cfg.securityRealm(https.getSecurityRealm());
                if (realm == null) {
                    throw new IllegalArgumentException("No security realm with name \"" + https.getSecurityRealm() + "\" available for \"" + https.getName() + "\" https listener.");
                }
                for (String address : binding.getAddresses()) {
                    LOG.info("Starting undertow https listener on " + address + ":" + binding.getPort());
                    // TODO: could this be shared across interface:port bindings?
                    SSLContext sslContext = buildSSLContext(realm);

                    builder.addHttpsListener(binding.getPort(), address, sslContext);

                    // options - see io.undertow.protocols.ssl.UndertowAcceptingSslChannel()
                    // one of NOT_REQUESTED, REQUESTED, REQUIRED
                    builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, SslClientAuthMode.valueOf(https.getVerifyClient()));

                    SecurityRealm.Engine engine = realm.getIdentities().getSsl().getEngine();
                    if (engine != null) {
                        // could be taken from these as well:
                        //  - https.getEnabledProtocols();
                        //  - https.getEnabledCipherSuites();
                        if (engine.getEnabledProtocols().size() > 0) {
                            builder.setSocketOption(Options.SSL_ENABLED_PROTOCOLS, Sequence.of(engine.getEnabledProtocols()));
                        }
                        if (engine.getEnabledCipherSuites().size() > 0) {
                            builder.setSocketOption(Options.SSL_ENABLED_CIPHER_SUITES, Sequence.of(engine.getEnabledCipherSuites()));
                        }
                    }
                }
            }

            // identity manager - looked up in "default" security realm
            SecurityRealm defaultRealm = cfg.securityRealm("default");
            if (defaultRealm != null) {
                SecurityRealm.JaasAuth jaasAuth = defaultRealm.getAuthentication().getJaas();
                SecurityRealm.PropertiesAuth propertiesAuth = defaultRealm.getAuthentication().getProperties();
                if (jaasAuth != null) {
                    String userPrincipalClassName = defaultRealm.getUserPrincipalClassName();
                    if (userPrincipalClassName == null || "".equals(userPrincipalClassName.trim())) {
                        userPrincipalClassName = "java.security.Principal";
                    }
                    Set<String> rolePrincipalClassNames = new LinkedHashSet<>(defaultRealm.getRolePrincipalClassNames());
                    identityManager = new JaasIdentityManager(jaasAuth.getName(),
                            userPrincipalClassName, rolePrincipalClassNames);
                } else if (propertiesAuth != null) {
                    File userBase = new File(propertiesAuth.getPath());
                    if (!userBase.isFile()) {
                        throw new IllegalArgumentException(userBase.getCanonicalPath() + " is not accessible. Can't load users/groups information.");
                    }
                    Properties userProperties = new Properties();
                    Map<String, String> map = new HashMap<>();
                    try (FileInputStream stream = new FileInputStream(userBase)) {
                        userProperties.load(stream);
                        for (String user : userProperties.stringPropertyNames()) {
                            map.put(user, userProperties.getProperty(user));
                        }
                    }
                    identityManager = new PropertiesIdentityManager(map);
                }
            }

            // /undertow/subsystem/server/host/location - file handlers for static context paths.
            if (cfg.getSubsystem().getServer().getHost() != null) {
                for (Server.Host.Location location : cfg.getSubsystem().getServer().getHost().getLocation()) {
                    String context = location.getName();
                    String handlerRef = location.getHandler();
                    UndertowSubsystem.FileHandler fileHandler = cfg.handler(handlerRef);
                    if (fileHandler == null) {
                        throw new IllegalArgumentException("No handler with name \"" + location.getHandler() + "\" available for " + location.getName() + " location.");
                    }
                    File base = new File(fileHandler.getPath());
                    if (!base.isDirectory()) {
                        throw new IllegalArgumentException(base.getCanonicalPath() + " is not accessible. Can't configure handler for " + location.getName() + " location.");
                    }
                    // fileHandler.path is simply filesystem directory
                    ResourceHandler rh = new ResourceHandler(new FileResourceManager(base, 4096));
                    if (cfg.getSubsystem().getServletContainer() != null) {
                        rh.setWelcomeFiles();
                        for (org.ops4j.pax.web.service.undertow.internal.configuration.model.ServletContainer.WelcomeFile wf : cfg.getSubsystem().getServletContainer().getWelcomeFiles()) {
                            rh.addWelcomeFiles(wf.getName());
                        }
                    }
                    if (rootHandler instanceof PathHandler) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Adding resource handler for location \"" + context + "\" and base path \"" + base.getCanonicalPath() + "\".");
                        }
                        ((PathHandler) rootHandler).addPrefixPath(context, rh);
                    }
                }
            }

            // global filters (subsystem/filters/response-header and subsystem/filters/filter)
            if (cfg.getSubsystem().getServer().getHost() != null) {
                for (Server.Host.FilterRef fr : cfg.getSubsystem().getServer().getHost().getFilterRef()) {
                    UndertowSubsystem.AbstractFilter filter = cfg.filter(fr.getName());
                    if (filter == null) {
                        throw new IllegalArgumentException("No filter with name \"" + fr.getName() + "\" available.");
                    }
                    rootHandler = filter.configure(rootHandler);
                }
            }

            // access log
            if (cfg.getSubsystem().getServer().getHost() != null
                    && cfg.getSubsystem().getServer().getHost().getAccessLog() != null) {
                Server.Host.AccessLog accessLog = cfg.getSubsystem().getServer().getHost().getAccessLog();

                Bundle bundle = FrameworkUtil.getBundle(ServerControllerImpl.class);
                ClassLoader loader = bundle.adapt(BundleWiring.class).getClassLoader();
                xnioWorker = UndertowUtil.createWorker(loader);

                AccessLogReceiver logReceiver = DefaultAccessLogReceiver.builder()
                        .setLogWriteExecutor(xnioWorker)
                        .setOutputDirectory(new File(accessLog.getDirectory()).toPath())
                        .setLogBaseName(accessLog.getPrefix())
                        .setLogNameSuffix(accessLog.getSuffix())
                        .setRotate(Boolean.parseBoolean(accessLog.getRotate()))
                        .build();

                rootHandler = new AccessLogHandler(rootHandler, logReceiver, accessLog.getPattern(),
                        AccessLogHandler.class.getClassLoader());
            }

            // session configuration and persistence
            this.defaultSessionTimeoutInMinutes = 30;
            try {
                if (cfg.getSubsystem().getServletContainer() != null) {
                    String defaultSessionTimeout = cfg.getSubsystem().getServletContainer().getDefaultSessionTimeout();
                    if (defaultSessionTimeout != null && !"".equals(defaultSessionTimeout)) {
                        this.defaultSessionTimeoutInMinutes = Integer.parseInt(defaultSessionTimeout);
                    }
                }
            } catch (NumberFormatException ignored) {
            }

            PersistentSessionsConfig persistentSessions = cfg.getSubsystem().getServletContainer() == null ? null
                    : cfg.getSubsystem().getServletContainer().getPersistentSessions();
            if (persistentSessions == null) {
                // no sessions, but let's use InMemorySessionPersistence
                LOG.info("Using in-memory session persistence");
                sessionPersistenceManager = new InMemorySessionPersistence();
            } else {
                if (persistentSessions.getPath() != null && !"".equals(persistentSessions.getPath().trim())) {
                    // file persistence manager
                    File sessionsDir = new File(persistentSessions.getPath());
                    sessionsDir.mkdirs();
                    LOG.info("Using file session persistence. Location: " + sessionsDir.getCanonicalPath());
                    sessionPersistenceManager = new FileSessionPersistence(sessionsDir);
                } else {
                    // in memory persistence manager
                    LOG.info("No path configured for persistent-sessions. Using in-memory session persistence.");
                    sessionPersistenceManager = new InMemorySessionPersistence();
                }
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("Problem configuring Undertow server using \"" + undertowResource + "\": " + e.getMessage(), e);
        }

        return rootHandler;
    }
487708
public static Map<String, String> createEnvironment(Map<String, String> environment)
    {
        Map<String, String> result = null;
        
        try
        {
            result = EnvironmentUtils.getProcEnvironment();
        }
        catch (IOException ex)
        {
            throw new ElasticsearchSetupException(
                    "Cannot get the current process environment", ex);
        }
        
        // Clean up the base environment:

        // The elasticsearch start and plugin scripts print warnings if these environment variables
        // are set, so lets unset them.
        result.remove("JAVA_TOOL_OPTIONS");
        result.remove("JAVA_OPTS");

        // The following environment variables may interfere with the elasticsearch instance.
        result.remove("ES_HOME");
        result.remove("ES_JAVA_OPTS");
        result.remove("ES_PATH_CONF");
        result.remove("ES_TMPDIR");

        // Now that we have a clean environment, set the provided variables on it.
        if (environment != null)
        {
            result.putAll(environment);
        }

        return result;
    }
1261670
private ResourceHandler createZipResourceHandler(final URL zipFile) throws IOException {

        final FileSystem fileSystem = newFileSystem(URI.create("jar:" + zipFile), Collections.<String, Object>emptyMap());
        final ResourceManager resMgr = new FileSystemResourceManager(fileSystem);
        return new ResourceHandler(resMgr);
    }
429146
public static StatsTraceContext newServerContext(
      List<? extends ServerStreamTracer.Factory> factories,
      String fullMethodName,
      Metadata headers) {
    if (factories.isEmpty()) {
      return NOOP;
    }
    StreamTracer[] tracers = new StreamTracer[factories.size()];
    for (int i = 0; i < tracers.length; i++) {
      tracers[i] = factories.get(i).newServerStreamTracer(fullMethodName, headers);
    }
    return new StatsTraceContext(tracers);
  }
742745
@Override
  public Optional<HttpTracing> build(@NotNull final Environment environment) {
    if (!isEnabled()) {
      LOGGER.warn("Zipkin tracing is disabled");
      return Optional.empty();
    }

    final ReporterMetrics metricsHandler = new DropwizardReporterMetrics(environment.metrics());

    final RabbitMQSender sender =
        RabbitMQSender.newBuilder()
            .addresses(addresses)
            .queue(queue)
            .connectionTimeout((int) connectionTimeout.toMilliseconds())
            .username(username)
            .password(password)
            .virtualHost(virtualHost)
            .build();

    final AsyncReporter<Span> reporter =
        AsyncReporter.builder(sender).metrics(metricsHandler).build();

    environment.lifecycle().manage(new ReporterManager(reporter, sender));

    LOGGER.info("Sending spans to RabbitMQ queue \"{}\" at: {}", queue, addresses);

    return buildTracing(environment, reporter);
  }
1089780
public ServiceCall<Environment> getEnvironment(GetEnvironmentOptions getEnvironmentOptions) {
    Validator.notNull(getEnvironmentOptions, "getEnvironmentOptions cannot be null");
    String[] pathSegments = { "v1/environments" };
    String[] pathParameters = { getEnvironmentOptions.environmentId() };
    RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
        pathParameters));
    builder.query("version", versionDate);
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("discovery", "v1", "getEnvironment");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
      builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Environment.class));
  }
581260
def create_environ(self, req, payload):
        """"""
        ws_req = req.copy()

        del ws_req.controller_info

        ws_req.environ.pop("wsgi.input", None)
        ws_req.body_kwargs = payload.body

        ws_req.environ["REQUEST_METHOD"] = payload.method
        ws_req.method = payload.method

        ws_req.environ["PATH_INFO"] = payload.path
        ws_req.path = payload.path

        ws_req.environ["WS_PAYLOAD"] = payload
        ws_req.environ["WS_ORIGINAL"] = req

        ws_req.payload = payload
        ws_req.parent = req
        return {"WS_REQUEST": ws_req}
1038051
public static <R, W> HttpServerInterceptorChain<R, W, R, W> start() {
        return new HttpServerInterceptorChain<>(new TransformingInterceptor<R, W, R, W>() {
            @Override
            public RequestHandler<R, W> intercept(RequestHandler<R, W> handler) {
                return handler;
            }
        });
    }
242625
@Override
    public ZipImporter importFrom(InputStream stream, Filter<ArchivePath> filter) throws ArchiveImportException {
        Validate.notNull(stream, "Stream must be specified");
        Validate.notNull(filter, "Filter must be specified");

        try {
            // Wrap in ZipInputStream if we haven't been given one
            final ZipInputStream zipStream = new ZipInputStream(stream);

            ZipEntry entry;
            while ((entry = zipStream.getNextEntry()) != null) {
                // Get the name
                final String entryName = entry.getName();

                if(!filter.include(ArchivePaths.create(entryName))) {
                    zipStream.closeEntry();
                    continue;
                }

                // Get the archive
                final Archive<?> archive = this.getArchive();

                // Handle directories separately
                if (entry.isDirectory()) {
                    archive.addAsDirectory(entryName);
                    continue;
                }

                final ByteArrayOutputStream output = new ByteArrayOutputStream(8192);
                IOUtil.copy(zipStream, output);
                archive.add(new ByteArrayAsset(output.toByteArray()), entryName);
                zipStream.closeEntry();
            }
        } catch (IOException e) {
            throw new ArchiveImportException("Could not import stream", e);
        }
        return this;
    }
1000044
@Singleton
    HttpServerHandler<HttpRequest<?>, HttpResponse<?>> httpServerHandler(HttpTracing httpTracing) {
        return HttpServerHandler.create(httpTracing, new HttpServerAdapter<HttpRequest<?>, HttpResponse<?>>() {
            @Override
            public String method(HttpRequest<?> request) {
                return request.getMethod().name();
            }

            @Override
            public String url(HttpRequest<?> request) {
                return request.getUri().toString();
            }

            @Override
            public String requestHeader(HttpRequest<?> request, String name) {
                return request.getHeaders().get(name);
            }

            @Override
            public Integer statusCode(HttpResponse<?> response) {
                return response.getStatus().getCode();
            }

            @Override
            public String route(HttpResponse<?> response) {
                Optional<String> value = response.getAttribute(HttpAttributes.URI_TEMPLATE, String.class);
                return value.orElseGet(() -> super.route(response));
            }

            @Override
            public String methodFromResponse(HttpResponse<?> httpResponse) {
                return httpResponse.getAttribute(HttpAttributes.METHOD_NAME, String.class).orElse(null);
            }

            @Override
            public boolean parseClientAddress(HttpRequest<?> httpRequest, Endpoint.Builder builder) {
                InetSocketAddress remoteAddress = httpRequest.getRemoteAddress();
                return builder.parseIp(remoteAddress.getAddress());
            }
        });
    }
869217
function httpClient(baseUrl, globalTrackingId) {
  var self = object.create(httpClient.prototype);

  self.baseUrl = baseUrl;
  self.globalTrackingId = globalTrackingId;

  return self;
}
14743
def app(environ, start_response):
    """"""
    r = HttpRequestHandler(environ, start_response, Router).dispatch()
    return r
519528
public Client build(final ZipkinClientConfiguration configuration) {
    final Client client =
        new JerseyClientBuilder(environment)
            .using(configuration)
            .build(configuration.getServiceName());
    return build(client);
  }
163211
public static CloudTraceContext toCloudTraceContext(SpanContext spanContext) {
    checkNotNull(spanContext, "spanContext");

    ByteBuffer traceIdBuf = ByteBuffer.wrap(spanContext.getTraceId().getBytes());
    TraceIdProto traceIdProto =
        TraceIdProto.newBuilder().setHi(traceIdBuf.getLong()).setLo(traceIdBuf.getLong()).build();
    ByteBuffer spanIdBuf = ByteBuffer.wrap(spanContext.getSpanId().getBytes());

    return new CloudTraceContext(
        traceIdProto.toByteArray(),
        spanIdBuf.getLong(),
        spanContext.getTraceOptions().isSampled() ? 1L : 0L);
  }