text:
package io.fabric8.elasticsearch.plugin;

import static io.fabric8.elasticsearch.plugin.acl.SearchGuardSyncStrategyFactory.PROJECT;
import static io.fabric8.elasticsearch.plugin.acl.SearchGuardSyncStrategyFactory.USER;

import org.apache.commons.lang.ArrayUtils;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;

public class PluginSettings implements ConfigurationSettings {

    private static final ESLogger LOGGER = Loggers.getLogger(PluginSettings.class);

    private String kibanaIndexMode;
    private String roleStrategy;
    private final String cdmProjectPrefix;
    private final String defaultKibanaIndex;
    private final String searchGuardIndex;
    private final String kibanaVersion;
    private final String kbnVersionHeader;
    private final Boolean enabled;

    @Inject
    public PluginSettings(final Settings settings) {
        this.kibanaIndexMode = settings.get(OPENSHIFT_KIBANA_INDEX_MODE, KibanaIndexMode.DEFAULT_MODE);
        if(!ArrayUtils.contains(new String [] {UNIQUE, SHARED_OPS, SHARED_NON_OPS}, kibanaIndexMode.toLowerCase())) {
            this.kibanaIndexMode = UNIQUE;
        }

        this.roleStrategy = settings.get(OPENSHIFT_ACL_ROLE_STRATEGY, DEFAULT_ACL_ROLE_STRATEGY);
        if(!ArrayUtils.contains(new String [] {PROJECT, USER}, roleStrategy.toLowerCase())) {
            this.kibanaIndexMode = USER;
        }

        this.cdmProjectPrefix = settings.get(OPENSHIFT_CONFIG_PROJECT_INDEX_PREFIX,
                OPENSHIFT_DEFAULT_PROJECT_INDEX_PREFIX);
        this.defaultKibanaIndex = settings.get(KIBANA_CONFIG_INDEX_NAME, DEFAULT_USER_PROFILE_PREFIX);
        this.searchGuardIndex = settings.get(SEARCHGUARD_CONFIG_INDEX_NAME, DEFAULT_SECURITY_CONFIG_INDEX);
        this.kibanaVersion = settings.get(KIBANA_CONFIG_VERSION, DEFAULT_KIBANA_VERSION);
        this.kbnVersionHeader = settings.get(KIBANA_VERSION_HEADER, DEFAULT_KIBANA_VERSION_HEADER);
        this.enabled = settings.getAsBoolean(OPENSHIFT_DYNAMIC_ENABLED_FLAG, OPENSHIFT_DYNAMIC_ENABLED_DEFAULT);

        LOGGER.info("Using kibanaIndexMode: '{}'", this.kibanaIndexMode);
        LOGGER.debug("searchGuardIndex: {}", this.searchGuardIndex);
        LOGGER.debug("roleStrategy: {}", this.roleStrategy);

    }

    public String getRoleStrategy() {
        return this.roleStrategy;
    }

    public String getKibanaIndexMode() {
        return kibanaIndexMode;
    }

    public String getCdmProjectPrefix() {
        return cdmProjectPrefix;
    }

    public String getDefaultKibanaIndex() {
        return defaultKibanaIndex;
    }

    public String getSearchGuardIndex() {
        return searchGuardIndex;
    }

    public String getKibanaVersion() {
        return kibanaVersion;
    }

    public String getKbnVersionHeader() {
        return kbnVersionHeader;
    }

    public Boolean isEnabled() {
        return enabled;
    }

    public void setKibanaIndexMode(String kibanaIndexMode) {
        this.kibanaIndexMode = kibanaIndexMode;
    }
}


text:
namespace IECore
{

IE_CORE_FORWARDDECLARE( Object );

/// Utility function that applies linear interpolation on objects. Returns a "null" pointer if the Object cannot be interpolated.
IECORE_API ObjectPtr linearObjectInterpolation( const Object *y0, const Object *y1, double x );

typedef ObjectPtr (*ObjectInterpolator)( const IECore::Object *y0, const IECore::Object *y1, double x );
/// Registers a custom interpolator for a specific object type.
IECORE_API void registerInterpolator( IECore::TypeId objectType, ObjectInterpolator interpolator );

/// Class which registers an interpolator for type T automatically when instantiated.
template<typename T>
class InterpolatorDescription
{

	public :

		/// Type-specific interpolation function
		typedef typename T::Ptr (*Interpolator)( const T *y0, const T *y1, double x );

		InterpolatorDescription( Interpolator interpolator )
		{
			registerInterpolator(
				T::staticTypeId(),
				reinterpret_cast<ObjectInterpolator>( interpolator )
			);
		}

};

} // namespace IECore

#endif // IE_CORE_OBJECTINTERPOLATOR_H

redpajama_set_name: RedPajamaGithub


text:
namespace switches {

#if defined(OS_LINUX)
extern const char kAlsaDevice[];
#endif

extern const char kVideoH264Annexb[];

}  // namespace switches

#endif  // MEDIA_BASE_SWITCHES_H_


text:
#if defined(USE_TI_XML) || defined(USE_TI_NETWORK)

#import "TiDOMNamedNodeMapProxy.h"
#import "TiDOMNodeProxy.h"
#import "TiUtils.h"

@implementation TiDOMNamedNodeMapProxy
@synthesize document;

-(void)dealloc
{
	RELEASE_TO_NIL(element);
	RELEASE_TO_NIL(document);
	[super dealloc];
}

-(void)setElement:(GDataXMLElement*)element_
{
	RELEASE_TO_NIL(element);
	element = [element_ retain];
}

-(id)getNamedItem:(id)name
{
	ENSURE_SINGLE_ARG(name,NSString);
	GDataXMLNode *node = [element attributeForName:name];
	TiDOMNodeProxy *proxy = [[[TiDOMNodeProxy alloc] _initWithPageContext:[self pageContext]] autorelease];
	[proxy setNode:node];
	[proxy setDocument:[self document]];
	return proxy;
}

-(void)setNamedItem:(id)args
{
	//TODO:
}

-(void)removeNamedItem:(id)args
{
	//TODO:
}

-(id)item:(id)args
{
	ENSURE_SINGLE_ARG(args,NSObject);
	int index = [TiUtils intValue:args];
	GDataXMLNode *node = [[element attributes] objectAtIndex:index];
	TiDOMNodeProxy *proxy = [[[TiDOMNodeProxy alloc] _initWithPageContext:[self pageContext]] autorelease];
	[proxy setNode:node];
	[proxy setDocument:[self document]];
	return proxy;
}

-(NSNumber*)length
{
	return NUMINT([[element attributes] count]);
}

@end

#endif


text: void gtk_builder_add_from_file_verbose(GtkBuilder*, const char*);


text:
package com.google.enterprise.cloudsearch.sdk.identity;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.api.services.cloudidentity.v1.model.EntityKey;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.enterprise.cloudsearch.sdk.CheckpointCloseableIterable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;

public class TestIdentityRepository implements Repository {
  private final Map<String, List<String>> userPages;
  private final Map<String, String> usersNextCheckpoint;
  private final Map<String, Boolean> usersHasMore;

  private final Map<String, List<String>> groupsPages;
  private final Map<String, String> groupsNextCheckpoint;
  private final Map<String, Boolean> groupsHasMore;
  private final String customerDomain;
  private RepositoryContext context;

  public TestIdentityRepository(Builder builder) {
    this.customerDomain = builder.customerDomain;
    this.userPages = builder.userPages;
    this.usersNextCheckpoint = builder.usersNextCheckpoint;
    this.usersHasMore = builder.usersHasMore;
    this.groupsPages = builder.groupsPages;
    this.groupsNextCheckpoint = builder.groupsNextCheckpoint;
    this.groupsHasMore = builder.groupsHasMore;
  }

  @Override
  public void init(RepositoryContext context) throws IOException {
    this.context = checkNotNull(context);
  }

  @Override
  public CheckpointCloseableIterable<IdentityUser> listUsers(byte[] checkpoint) throws IOException {
    String checkpointValue = (checkpoint == null) ? "" : new String(checkpoint, UTF_8);
    if (!userPages.containsKey(checkpointValue)) {
      throw new UnsupportedOperationException("unexpected checkpoint value " + checkpointValue);
    }
    List<IdentityUser> usersToReturn =
        userPages
            .get(checkpointValue)
            .stream()
            .map(s -> buildIdentityUser(s, context))
            .collect(ImmutableList.toImmutableList());
    return new CheckpointCloseableIterableImpl<>(
        usersToReturn, usersNextCheckpoint.get(checkpointValue), usersHasMore.get(checkpointValue));
  }

  @Override
  public CheckpointCloseableIterable<IdentityGroup> listGroups(byte[] checkpoint)
      throws IOException {
    String checkpointValue = checkpoint == null ? "" : new String(checkpoint, UTF_8);
    if (!groupsPages.containsKey(checkpointValue)) {
      throw new UnsupportedOperationException("unexpected checkpoint value " + checkpointValue);
    }
    List<IdentityGroup> groupsToReturn =
        groupsPages
            .get(checkpointValue)
            .stream()
            .map(s -> buildIdentityGroup(s, context))
            .collect(ImmutableList.toImmutableList());
    return new CheckpointCloseableIterableImpl<>(
        groupsToReturn,
        groupsNextCheckpoint.get(checkpointValue),
        groupsHasMore.get(checkpointValue));
  }

  @Override
  public void close() {
  }

  private IdentityUser buildIdentityUser(String userKey, RepositoryContext context) {
    return context.buildIdentityUser(
        String.format("%s@%s", userKey, customerDomain),
        String.format("%s\\%s", customerDomain, userKey));
  }

  private IdentityGroup buildIdentityGroup(String groupKey, RepositoryContext context) {
    String groupIdentifier = String.format("%s\\%s", customerDomain, groupKey);
    EntityKey key = context.buildEntityKeyForGroup(groupIdentifier);
    return new IdentityGroup.Builder()
        .setGroupIdentity(groupIdentifier)
        .setGroupKey(key)
        .setMembers(ImmutableSet.of())
        .build();
  }

  public ImmutableList<IdentityUser> getAllUsersList() {
    ImmutableList.Builder<IdentityUser> builder = ImmutableList.<IdentityUser>builder();
    for (Entry<String, List<String>> entry : userPages.entrySet()) {
      builder.addAll(
          entry
              .getValue()
              .stream()
              .map(s -> buildIdentityUser(s, context))
              .collect(ImmutableList.toImmutableList()));
    }
    return builder.build();
  }

  public ImmutableList<IdentityGroup> getAllGroupsList() {
    ImmutableList.Builder<IdentityGroup> builder = ImmutableList.<IdentityGroup>builder();
    for (Entry<String, List<String>> entry : groupsPages.entrySet()) {
      builder.addAll(
          entry
              .getValue()
              .stream()
              .map(s -> buildIdentityGroup(s, context))
              .collect(ImmutableList.toImmutableList()));
    }
    return builder.build();
  }

  public boolean allUserPagesClosed() {
    return true;
  }

  public boolean allGroupPagesClosed() {
    return true;
  }

  public static class Builder {
    private final String customerDomain;
    private final Map<String, List<String>> userPages = new HashMap<>();
    private final Map<String, String> usersNextCheckpoint = new HashMap<>();
    private final Map<String, Boolean> usersHasMore = new HashMap<>();

    private final Map<String, List<String>> groupsPages = new HashMap<>();
    private final Map<String, String> groupsNextCheckpoint = new HashMap<>();
    private final Map<String, Boolean> groupsHasMore = new HashMap<>();

    public Builder(String customerDomain) {
      this.customerDomain = customerDomain;
    }

    public Builder addUserPage(
        String forCheckpoint, String nextCheckpoint, boolean hasMore, List<String> usersInPage) {
      userPages.put(forCheckpoint, usersInPage);
      usersNextCheckpoint.put(forCheckpoint, nextCheckpoint);
      usersHasMore.put(forCheckpoint, hasMore);
      return this;
    }

    public Builder addGroupPage(
        String forCheckpoint, String nextCheckpoint, boolean hasMore, List<String> groupsInPage) {
      groupsPages.put(forCheckpoint, groupsInPage);
      groupsNextCheckpoint.put(forCheckpoint, nextCheckpoint);
      groupsHasMore.put(forCheckpoint, hasMore);
      return this;
    }

    public TestIdentityRepository build() {
      return new TestIdentityRepository(this);
    }
  }

  private static class CheckpointCloseableIterableImpl<T>
      implements CheckpointCloseableIterable<T> {
    private final Iterator<T> identities;
    private final byte[] nextCheckpoint;
    private final boolean hasMore;
    private final AtomicBoolean closed = new AtomicBoolean();

    private CheckpointCloseableIterableImpl(
        Collection<T> identities, String nextCheckpoint, boolean hasMore) {
      this.identities = identities.iterator();
      this.nextCheckpoint = nextCheckpoint == null ? null : nextCheckpoint.getBytes(UTF_8);
      this.hasMore = hasMore;
    }

    @Override
    public Iterator<T> iterator() {
      return identities;
    }

    @Override
    public byte[] getCheckpoint() {
      return nextCheckpoint;
    }

    @Override
    public boolean hasMore() {
      return hasMore;
    }

    @Override
    public void close() {
      closed.set(true);
    }}

  public static void main(String[] args) throws InterruptedException {
    // TODO(tvartak) : Make number of groups and domain name as command line inputs or
    // configuration values
    List<String> groups = new ArrayList<String>();
    for (int i = 0; i < 10; i++) {
      groups.add("testGroup-" + i);
    }
    IdentityApplication application =
        new IdentityApplication.Builder(
                new FullSyncIdentityConnector(
                    new TestIdentityRepository.Builder("mydomain.com")
                        .addUserPage("", "1", false, Arrays.asList("user1", "user2", "user3"))
                        .addGroupPage("", "1", false, groups)
                        .build()),
                args)
            .build();
    application.start();
  }
}


text:
package org.elasticsearch.xpack.security.authc.oidc;

import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.rest.ESRestTestCase;
import org.elasticsearch.xpack.core.common.socket.SocketAccess;
import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.BeforeClass;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.common.xcontent.XContentHelper.convertToMap;
import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;

public class OpenIdConnectAuthIT extends ESRestTestCase {

    private static final String REALM_NAME = "c2id";
    private static final String REALM_NAME_IMPLICIT = "c2id-implicit";
    private static final String REALM_NAME_PROXY = "c2id-proxy";
    private static final String REALM_NAME_CLIENT_POST_AUTH = "c2id-post";
    private static final String REALM_NAME_CLIENT_JWT_AUTH = "c2id-jwt";
    private static final String FACILITATOR_PASSWORD = "f@cilit@t0r";
    private static final String REGISTRATION_URL = "http://127.0.0.1:" + getEphemeralTcpPortFromProperty("oidc-provider", "8080")
        + "/c2id/clients";
    private static final String LOGIN_API = "http://127.0.0.1:" + getEphemeralTcpPortFromProperty("oidc-provider", "8080")
        + "/c2id-login/api/";
    private static final String CLIENT_SECRET = "b07efb7a1cf6ec9462afe7b6d3ab55c6c7880262aa61ac28dded292aca47c9a2";
    // SHA256 of this is defined in  x-pack/test/idp-fixture/oidc/override.properties
    private static final String OP_API_BEARER_TOKEN = "811fa888f3e0fdc9e01d4201bfeee46a";
    private static final String ES_PORT = getEphemeralTcpPortFromProperty("elasticsearch-node", "9200");
    private static Path HTTP_TRUSTSTORE;

    @Before
    public void setupUserAndRoles() throws Exception {
        setFacilitatorUser();
        setRoleMappings();
    }

    @BeforeClass
    public static void readTrustStore() throws Exception {
        final URL resource = OpenIdConnectAuthIT.class.getResource("/tls/testnode.jks");
        if (resource == null) {
            throw new FileNotFoundException("Cannot find classpath resource /tls/testnode.jks");
        }
        HTTP_TRUSTSTORE = PathUtils.get(resource.toURI());
    }

    /**
     * C2id server only supports dynamic registration, so we can't pre-seed it's config with our client data. Execute only once
     */
    @BeforeClass
    public static void registerClients() throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String codeClient = "{" +
                "\"grant_types\": [\"authorization_code\"]," +
                "\"response_types\": [\"code\"]," +
                "\"preferred_client_id\":\"https://my.elasticsearch.org/rp\"," +
                "\"preferred_client_secret\":\"" + CLIENT_SECRET + "\"," +
                "\"redirect_uris\": [\"https://my.fantastic.rp/cb\"]," +
                "\"token_endpoint_auth_method\":\"client_secret_basic\"" +
                "}";
            String implicitClient = "{" +
                "\"grant_types\": [\"implicit\"]," +
                "\"response_types\": [\"token id_token\"]," +
                "\"preferred_client_id\":\"elasticsearch-rp\"," +
                "\"preferred_client_secret\":\"" + CLIENT_SECRET + "\"," +
                "\"redirect_uris\": [\"https://my.fantastic.rp/cb\"]" +
                "}";
            String postClient = "{" +
                "\"grant_types\": [\"authorization_code\"]," +
                "\"response_types\": [\"code\"]," +
                "\"preferred_client_id\":\"elasticsearch-post\"," +
                "\"preferred_client_secret\":\"" + CLIENT_SECRET + "\"," +
                "\"redirect_uris\": [\"https://my.fantastic.rp/cb\"]," +
                "\"token_endpoint_auth_method\":\"client_secret_post\"" +
                "}";
            String jwtClient = "{" +
                "\"grant_types\": [\"authorization_code\"]," +
                "\"response_types\": [\"code\"]," +
                "\"preferred_client_id\":\"elasticsearch-post-jwt\"," +
                "\"preferred_client_secret\":\"" + CLIENT_SECRET + "\"," +
                "\"redirect_uris\": [\"https://my.fantastic.rp/cb\"]," +
                "\"token_endpoint_auth_method\":\"client_secret_jwt\"" +
                "}";
            HttpPost httpPost = new HttpPost(REGISTRATION_URL);
            final BasicHttpContext context = new BasicHttpContext();
            httpPost.setEntity(new StringEntity(codeClient, ContentType.APPLICATION_JSON));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + OP_API_BEARER_TOKEN);

            HttpPost httpPost2 = new HttpPost(REGISTRATION_URL);
            httpPost2.setEntity(new StringEntity(implicitClient, ContentType.APPLICATION_JSON));
            httpPost2.setHeader("Accept", "application/json");
            httpPost2.setHeader("Content-type", "application/json");
            httpPost2.setHeader("Authorization", "Bearer " + OP_API_BEARER_TOKEN);

            HttpPost httpPost3 = new HttpPost(REGISTRATION_URL);
            httpPost3.setEntity(new StringEntity(postClient, ContentType.APPLICATION_JSON));
            httpPost3.setHeader("Accept", "application/json");
            httpPost3.setHeader("Content-type", "application/json");
            httpPost3.setHeader("Authorization", "Bearer " + OP_API_BEARER_TOKEN);

            HttpPost httpPost4 = new HttpPost(REGISTRATION_URL);
            httpPost4.setEntity(new StringEntity(jwtClient, ContentType.APPLICATION_JSON));
            httpPost4.setHeader("Accept", "application/json");
            httpPost4.setHeader("Content-type", "application/json");
            httpPost4.setHeader("Authorization", "Bearer " + OP_API_BEARER_TOKEN);

            SocketAccess.doPrivileged(() -> {
                try (CloseableHttpResponse response = httpClient.execute(httpPost, context)) {
                    assertThat(response.getStatusLine().getStatusCode(), equalTo(201));
                }
                try (CloseableHttpResponse response2 = httpClient.execute(httpPost2, context)) {
                    assertThat(response2.getStatusLine().getStatusCode(), equalTo(201));
                }
                try (CloseableHttpResponse response3 = httpClient.execute(httpPost3, context)) {
                    assertThat(response3.getStatusLine().getStatusCode(), equalTo(201));
                }
                try (CloseableHttpResponse response4 = httpClient.execute(httpPost4, context)) {
                    assertThat(response4.getStatusLine().getStatusCode(), equalTo(201));
                }
            });
        }
    }

    @Override
    protected Settings restAdminSettings() {
        String token = basicAuthHeaderValue("x_pack_rest_user", new SecureString("x-pack-test-password".toCharArray()));
        return Settings.builder()
            .put(ThreadContext.PREFIX + ".Authorization", token)
            .put(TRUSTSTORE_PATH, HTTP_TRUSTSTORE)
            .put(TRUSTSTORE_PASSWORD, "testnode")
            .build();
    }

    private String authenticateAtOP(URI opAuthUri) throws Exception {
        // C2ID doesn't have a non JS login page :/, so use their API directly
        // see https://connect2id.com/products/server/docs/guides/login-page
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            final BasicHttpContext context = new BasicHttpContext();
            // Initiate the authentication process
            HttpPost httpPost = new HttpPost(LOGIN_API + "initAuthRequest");
            String initJson = "{" +
                "  \"qs\":\"" + opAuthUri.getRawQuery() + "\"" +
                "}";
            configureJsonRequest(httpPost, initJson);
            JSONObject initResponse = execute(httpClient, httpPost, context, response -> {
                assertHttpOk(response.getStatusLine());
                return parseJsonResponse(response);
            });
            assertThat(initResponse.getAsString("type"), equalTo("auth"));
            final String sid = initResponse.getAsString("sid");
            // Actually authenticate the user with ldapAuth
            HttpPost loginHttpPost = new HttpPost(LOGIN_API + "authenticateSubject?cacheBuster=" + randomAlphaOfLength(8));
            String loginJson = "{" +
                "\"username\":\"alice\"," +
                "\"password\":\"secret\"" +
                "}";
            configureJsonRequest(loginHttpPost, loginJson);
            JSONObject loginJsonResponse = execute(httpClient, loginHttpPost, context, response -> {
                assertHttpOk(response.getStatusLine());
                return parseJsonResponse(response);
            });
            // Get the consent screen
            HttpPut consentFetchHttpPut =
                new HttpPut(LOGIN_API + "updateAuthRequest" + "/" + sid + "?cacheBuster=" + randomAlphaOfLength(8));
            String consentFetchJson = "{" +
                "\"sub\": \"" + loginJsonResponse.getAsString("id") + "\"," +
                "\"acr\": \"http://loa.c2id.com/basic\"," +
                "\"amr\": [\"pwd\"]," +
                "\"data\": {" +
                "\"email\": \"" + loginJsonResponse.getAsString("email") + "\"," +
                "\"name\": \"" + loginJsonResponse.getAsString("name") + "\"" +
                "}" +
                "}";
            configureJsonRequest(consentFetchHttpPut, consentFetchJson);
            JSONObject consentFetchResponse = execute(httpClient, consentFetchHttpPut, context, response -> {
                assertHttpOk(response.getStatusLine());
                return parseJsonResponse(response);
            });
            if (consentFetchResponse.getAsString("type").equals("consent")) {
                // If needed, submit the consent
                HttpPut consentHttpPut =
                    new HttpPut(LOGIN_API + "updateAuthRequest" + "/" + sid + "?cacheBuster=" + randomAlphaOfLength(8));
                String consentJson = "{" +
                    "\"claims\":[\"name\", \"email\"]," +
                    "\"scope\":[\"openid\"]" +
                    "}";
                configureJsonRequest(consentHttpPut, consentJson);
                JSONObject jsonConsentResponse = execute(httpClient, consentHttpPut, context, response -> {
                    assertHttpOk(response.getStatusLine());
                    return parseJsonResponse(response);
                });
                assertThat(jsonConsentResponse.getAsString("type"), equalTo("response"));
                JSONObject parameters = (JSONObject) jsonConsentResponse.get("parameters");
                return parameters.getAsString("uri");
            } else if (consentFetchResponse.getAsString("type").equals("response")) {
                JSONObject parameters = (JSONObject) consentFetchResponse.get("parameters");
                return parameters.getAsString("uri");
            } else {
                fail("Received an invalid response from the OP");
                return null;
            }
        }
    }

    private static String getEphemeralTcpPortFromProperty(String service, String port) {
        String key = "test.fixtures." + service + ".tcp." + port;
        final String value = System.getProperty(key);
        assertNotNull("Expected the actual value for port " + port + " to be in system property " + key, value);
        return value;
    }

    private Map<String, Object> callAuthenticateApiUsingAccessToken(String accessToken) throws Exception {
        Request request = new Request("GET", "/_security/_authenticate");
        RequestOptions.Builder options = request.getOptions().toBuilder();
        options.addHeader("Authorization", "Bearer " + accessToken);
        request.setOptions(options);
        try (RestClient restClient = getClient()) {
            return entityAsMap(restClient.performRequest(request));
        }
    }

    private <T> T execute(CloseableHttpClient client, HttpEntityEnclosingRequestBase request,
                          HttpContext context, CheckedFunction<HttpResponse, T, Exception> body)
        throws Exception {
        final int timeout = (int) TimeValue.timeValueSeconds(90).millis();
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout)
            .setSocketTimeout(timeout)
            .build();
        request.setConfig(requestConfig);
        logger.info("Execute HTTP " + request.getMethod() + " " + request.getURI() +
            " with payload " + EntityUtils.toString(request.getEntity()));
        try (CloseableHttpResponse response = SocketAccess.doPrivileged(() -> client.execute(request, context))) {
            return body.apply(response);
        } catch (Exception e) {
            logger.warn(new ParameterizedMessage("HTTP Request [{}] failed", request.getURI()), e);
            throw e;
        }
    }

    private JSONObject parseJsonResponse(HttpResponse response) throws Exception {
        JSONParser parser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE);
        String entity = EntityUtils.toString(response.getEntity());
        logger.info("Response entity as string: " + entity);
        return (JSONObject) parser.parse(entity);
    }

    private void configureJsonRequest(HttpEntityEnclosingRequestBase request, String jsonBody) {
        StringEntity entity = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
        request.setEntity(entity);
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");
    }

    public void testAuthenticateWithCodeFlow() throws Exception {
        final PrepareAuthResponse prepareAuthResponse = getRedirectedFromFacilitator(REALM_NAME);
        final String redirectUri = authenticateAtOP(prepareAuthResponse.getAuthUri());
        Tuple<String, String> tokens = completeAuthentication(redirectUri, prepareAuthResponse.getState(),
            prepareAuthResponse.getNonce(), REALM_NAME);
        verifyElasticsearchAccessTokenForCodeFlow(tokens.v1());
    }

    public void testAuthenticateWithCodeFlowAndClientPost() throws Exception {
        final PrepareAuthResponse prepareAuthResponse = getRedirectedFromFacilitator(REALM_NAME_CLIENT_POST_AUTH);
        final String redirectUri = authenticateAtOP(prepareAuthResponse.getAuthUri());
        Tuple<String, String> tokens = completeAuthentication(redirectUri, prepareAuthResponse.getState(),
            prepareAuthResponse.getNonce(), REALM_NAME_CLIENT_POST_AUTH);
        verifyElasticsearchAccessTokenForCodeFlow(tokens.v1());
    }

    public void testAuthenticateWithCodeFlowAndClientJwtPost() throws Exception {
        final PrepareAuthResponse prepareAuthResponse = getRedirectedFromFacilitator(REALM_NAME_CLIENT_JWT_AUTH);
        final String redirectUri = authenticateAtOP(prepareAuthResponse.getAuthUri());
        Tuple<String, String> tokens = completeAuthentication(redirectUri, prepareAuthResponse.getState(),
            prepareAuthResponse.getNonce(), REALM_NAME_CLIENT_JWT_AUTH);
        verifyElasticsearchAccessTokenForCodeFlow(tokens.v1());
    }

    public void testAuthenticateWithImplicitFlow() throws Exception {
        final PrepareAuthResponse prepareAuthResponse = getRedirectedFromFacilitator(REALM_NAME_IMPLICIT);
        final String redirectUri = authenticateAtOP(prepareAuthResponse.getAuthUri());
        Tuple<String, String> tokens = completeAuthentication(redirectUri, prepareAuthResponse.getState(),
            prepareAuthResponse.getNonce(), REALM_NAME_IMPLICIT);
        verifyElasticsearchAccessTokenForImplicitFlow(tokens.v1());
    }

    public void testAuthenticateWithCodeFlowUsingHttpProxy() throws Exception {
        final PrepareAuthResponse prepareAuthResponse = getRedirectedFromFacilitator(REALM_NAME_PROXY);
        final String redirectUri = authenticateAtOP(prepareAuthResponse.getAuthUri());

        Tuple<String, String> tokens = completeAuthentication(redirectUri, prepareAuthResponse.getState(),
            prepareAuthResponse.getNonce(), REALM_NAME_PROXY);
        verifyElasticsearchAccessTokenForCodeFlow(tokens.v1());
    }

    public void testAuthenticateWithCodeFlowFailsForWrongRealm() throws Exception {
        final PrepareAuthResponse prepareAuthResponse = getRedirectedFromFacilitator(REALM_NAME);
        final String redirectUri = authenticateAtOP(prepareAuthResponse.getAuthUri());
        // Use existing realm that can't authenticate the response, or a non-existent realm
        ResponseException e = expectThrows(ResponseException.class, () -> {
            completeAuthentication(redirectUri,
                prepareAuthResponse.getState(),
                prepareAuthResponse.getNonce(), randomFrom(REALM_NAME_IMPLICIT, REALM_NAME + randomAlphaOfLength(8)));
        });
        assertThat(401, equalTo(e.getResponse().getStatusLine().getStatusCode()));
    }

    private void verifyElasticsearchAccessTokenForCodeFlow(String accessToken) throws Exception {
        final Map<String, Object> map = callAuthenticateApiUsingAccessToken(accessToken);
        logger.info("Authentication with token Response: " + map);
        assertThat(map.get("username"), equalTo("alice"));
        assertThat((List<?>) map.get("roles"), containsInAnyOrder("kibana_admin", "auditor"));

        assertThat(map.get("metadata"), instanceOf(Map.class));
        final Map<?, ?> metadata = (Map<?, ?>) map.get("metadata");
        assertThat(metadata.get("oidc(sub)"), equalTo("alice"));
        assertThat(metadata.get("oidc(iss)"), equalTo("http://oidc-provider:8080/c2id"));
    }

    private void verifyElasticsearchAccessTokenForImplicitFlow(String accessToken) throws Exception {
        final Map<String, Object> map = callAuthenticateApiUsingAccessToken(accessToken);
        logger.info("Authentication with token Response: " + map);
        assertThat(map.get("username"), equalTo("alice"));
        assertThat((List<?>) map.get("roles"), containsInAnyOrder("limited_user", "auditor"));

        assertThat(map.get("metadata"), instanceOf(Map.class));
        final Map<?, ?> metadata = (Map<?, ?>) map.get("metadata");
        assertThat(metadata.get("oidc(sub)"), equalTo("alice"));
        assertThat(metadata.get("oidc(iss)"), equalTo("http://oidc-provider:8080/c2id"));
    }

    private PrepareAuthResponse getRedirectedFromFacilitator(String realmName) throws Exception {
        final Map<String, String> body = Collections.singletonMap("realm", realmName);
        Request request = buildRequest("POST", "/_security/oidc/prepare?error_trace=true", body, facilitatorAuth());
        try (RestClient restClient = getClient()) {
            final Response prepare = restClient.performRequest(request);
            assertOK(prepare);
            final Map<String, Object> responseBody = parseResponseAsMap(prepare.getEntity());
            logger.info("Created OpenIDConnect authentication request {}", responseBody);
            final String state = (String) responseBody.get("state");
            final String nonce = (String) responseBody.get("nonce");
            final String authUri = (String) responseBody.get("redirect");
            final String realm = (String) responseBody.get("realm");
            return new PrepareAuthResponse(new URI(authUri), state, nonce, realm);
        }
    }

    private Tuple<String, String> completeAuthentication(String redirectUri, String state, String nonce, @Nullable String realm)
        throws Exception {
        final Map<String, String> body = new HashMap<>();
        body.put("redirect_uri", redirectUri);
        body.put("state", state);
        body.put("nonce", nonce);
        if (realm != null) {
            body.put("realm", realm);
        }
        Request request = buildRequest("POST", "/_security/oidc/authenticate", body, facilitatorAuth());
        try (RestClient restClient = getClient()) {
            final Response authenticate = restClient.performRequest(request);
            assertOK(authenticate);
            final Map<String, Object> responseBody = parseResponseAsMap(authenticate.getEntity());
            logger.info(" OpenIDConnect authentication response {}", responseBody);
            assertNotNull(responseBody.get("access_token"));
            assertNotNull(responseBody.get("refresh_token"));
            return Tuple.tuple(responseBody.get("access_token").toString(), responseBody.get("refresh_token").toString());
        }
    }

    private Request buildRequest(String method, String endpoint, Map<String, ?> body, Header... headers) throws IOException {
        Request request = new Request(method, endpoint);
        XContentBuilder builder = XContentFactory.jsonBuilder().map(body);
        if (body != null) {
            request.setJsonEntity(BytesReference.bytes(builder).utf8ToString());
        }
        final RequestOptions.Builder options = request.getOptions().toBuilder();
        for (Header header : headers) {
            options.addHeader(header.getName(), header.getValue());
        }
        request.setOptions(options);
        return request;
    }

    private static BasicHeader facilitatorAuth() {
        final String auth =
            UsernamePasswordToken.basicAuthHeaderValue("facilitator", new SecureString(FACILITATOR_PASSWORD.toCharArray()));
        return new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, auth);
    }

    private Map<String, Object> parseResponseAsMap(HttpEntity entity) throws IOException {
        return convertToMap(XContentType.JSON.xContent(), entity.getContent(), false);
    }

    private void assertHttpOk(StatusLine status) {
        assertThat("Unexpected HTTP Response status: " + status, status.getStatusCode(), Matchers.equalTo(200));
    }

    /**
     * We create a user named `facilitator` with the appropriate privileges ( `manage_oidc` ). A facilitator web app
     * would need to create one also, in order to access the OIDC related APIs on behalf of the user.
     */
    private void setFacilitatorUser() throws Exception {
        try (RestClient restClient = getClient()) {
            Request createRoleRequest = new Request("PUT", "/_security/role/facilitator");
            createRoleRequest.setJsonEntity("{ \"cluster\" : [\"manage_oidc\", \"manage_token\"] }");
            restClient.performRequest(createRoleRequest);
            Request createUserRequest = new Request("PUT", "/_security/user/facilitator");
            createUserRequest.setJsonEntity("{ \"password\" : \"" + FACILITATOR_PASSWORD + "\", \"roles\" : [\"facilitator\"] }");
            restClient.performRequest(createUserRequest);
        }
    }

    private void setRoleMappings() throws Exception {
        try (RestClient restClient = getClient()) {
            Request createRoleMappingRequest = new Request("PUT", "/_security/role_mapping/oidc_kibana");
            createRoleMappingRequest.setJsonEntity("{ \"roles\" : [\"kibana_admin\"]," +
                "\"enabled\": true," +
                "\"rules\": {" +
                "  \"any\" : [" +
                "    {\"field\": { \"realm.name\": \"" + REALM_NAME + "\"} }," +
                "    {\"field\": { \"realm.name\": \"" + REALM_NAME_PROXY + "\"} }," +
                "    {\"field\": { \"realm.name\": \"" + REALM_NAME_CLIENT_POST_AUTH + "\"} }," +
                "    {\"field\": { \"realm.name\": \"" + REALM_NAME_CLIENT_JWT_AUTH + "\"} }" +
                "  ]" +
                "}" +
                "}");
            restClient.performRequest(createRoleMappingRequest);

            createRoleMappingRequest = new Request("PUT", "/_security/role_mapping/oidc_limited");
            createRoleMappingRequest.setJsonEntity("{ \"roles\" : [\"limited_user\"]," +
                "\"enabled\": true," +
                "\"rules\": {" +
                "\"field\": { \"realm.name\": \"" + REALM_NAME_IMPLICIT + "\"}" +
                "}" +
                "}");
            restClient.performRequest(createRoleMappingRequest);

            createRoleMappingRequest = new Request("PUT", "/_security/role_mapping/oidc_auditor");
            createRoleMappingRequest.setJsonEntity("{ \"roles\" : [\"auditor\"]," +
                "\"enabled\": true," +
                "\"rules\": {" +
                "\"field\": { \"groups\": \"audit\"}" +
                "}" +
                "}");
            restClient.performRequest(createRoleMappingRequest);
        }
    }

    private RestClient getClient() throws Exception {
        return buildClient(restAdminSettings(), new HttpHost[]{new HttpHost("localhost", Integer.parseInt(ES_PORT), "https")});
    }

    /**
     * Simple POJO encapsulating a response to calling /_security/oidc/prepare
     */
    class PrepareAuthResponse {
        private URI authUri;
        private String state;
        private String nonce;

        PrepareAuthResponse(URI authUri, String state, String nonce, @Nullable String realm) {
            this.authUri = authUri;
            this.state = state;
            this.nonce = nonce;
        }

        URI getAuthUri() {
            return authUri;
        }

        String getState() {
            return state;
        }

        String getNonce() {
            return nonce;
        }

    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TEST HTML FILE</title>
</head>
<body>
    TEST HTML FILE
</body>
</html>


text:
<?php

// # Create Webhook Sample
//
// This sample code demonstrate how you can create a webhook, as documented here at:
// https://developer.paypal.com/webapps/developer/docs/api/#create-a-webhook
// API used: POST /v1/notifications/webhooks

require __DIR__ . '/../bootstrap.php';

// Create a new instance of Webhook object
$webhook = new \PayPal\Api\Webhook();

// # Basic Information
//     {
//         "url":"https://requestb.in/10ujt3c1",
//         "event_types":[
//            {
//                "name":"PAYMENT.AUTHORIZATION.CREATED"
//            },
//            {
//                "name":"PAYMENT.AUTHORIZATION.VOIDED"
//            }
//         ]
//      }
// Fill up the basic information that is required for the webhook
// The URL should be actually accessible over the internet. Having a localhost here would not work.
// #### There is an open source tool http://requestb.in/ that allows you to receive any web requests to a url given there.
// #### NOTE: Please note that you need an https url for paypal webhooks. You can however override the url with https, and accept
// any warnings your browser might show you. Also, please note that this is entirely for demo purposes, and you should not
// be using this in production
$webhook->setUrl("https://requestb.in/10ujt3c1?uniqid=" . uniqid());

// # Event Types
// Event types correspond to what kind of notifications you want to receive on the given URL.
$webhookEventTypes = array();
$webhookEventTypes[] = new \PayPal\Api\WebhookEventType(
    '{
        "name":"PAYMENT.AUTHORIZATION.CREATED"
    }'
);
$webhookEventTypes[] = new \PayPal\Api\WebhookEventType(
    '{
        "name":"PAYMENT.AUTHORIZATION.VOIDED"
    }'
);
$webhook->setEventTypes($webhookEventTypes);

// For Sample Purposes Only.
$request = clone $webhook;

// ### Create Webhook
try {
    $output = $webhook->create($apiContext);
} catch (Exception $ex) {
    // ^ Ignore workflow code segment
    if ($ex instanceof \PayPal\Exception\PayPalConnectionException) {
        $data = $ex->getData();
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printError("Created Webhook Failed. Checking if it is Webhook Number Limit Exceeded. Trying to delete all existing webhooks", "Webhook", "Please Use Delete All Webhooks Sample to delete all existing webhooks in sample", $request, $ex);
        if (strpos($data, 'WEBHOOK_NUMBER_LIMIT_EXCEEDED') !== false) {
            require 'DeleteAllWebhooks.php';
            try {
                $output = $webhook->create($apiContext);
            } catch (Exception $ex) {
                // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
                ResultPrinter::printError("Created Webhook", "Webhook", null, $request, $ex);
                exit(1);
            }
        } else {
            // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
            ResultPrinter::printError("Created Webhook", "Webhook", null, $request, $ex);
            exit(1);
        }
    } else {
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printError("Created Webhook", "Webhook", null, $request, $ex);
        exit(1);
    }
    // Print Success Result
}

// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
 ResultPrinter::printResult("Created Webhook", "Webhook", $output->getId(), $request, $output);

return $output;


text:
using System.IO;

namespace Yalla
{
    /// <summary>
    /// Encapsulates compiler-populated caller information.
    /// </summary>
    public sealed class CallerInfo
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CallerInfo"/> class.
        /// </summary>
        /// <param name="filePath">File path.</param>
        /// <param name="memberName">Member name.</param>
        /// <param name="lineNumber">Line number.</param>
        public CallerInfo(string filePath, string memberName, int lineNumber)
        {
            FilePath = filePath;
            MemberName = memberName;
            LineNumber = lineNumber;
        }

        /// <summary>
        /// Gets the file path.
        /// </summary>
        /// <value>File path.</value>
        public string FilePath
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the member name.
        /// </summary>
        /// <value>Member name.</value>
        public string MemberName
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the line number.
        /// </summary>
        /// <value>Line number.</value>
        public int LineNumber
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the hash code.
        /// </summary>
        /// <returns>A hash code for the current object.</returns>
        public override int GetHashCode()
        {
            return FilePath != null
                ? FilePath.GetHashCode() ^ LineNumber
                : base.GetHashCode();
        }
    }
}


text:
package org.apache.commons.compress.archivers.tar;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.compress.archivers.zip.ZipEncoding;
import org.apache.commons.compress.archivers.zip.ZipEncodingHelper;
import org.apache.commons.compress.utils.ArchiveUtils;
import org.apache.commons.compress.utils.BoundedArchiveInputStream;
import org.apache.commons.compress.utils.BoundedInputStream;
import org.apache.commons.compress.utils.BoundedSeekableByteChannelInputStream;
import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;

/**
 * The TarFile provides random access to UNIX archives.
 * @since 1.21
 */
public class TarFile implements Closeable {

    private static final int SMALL_BUFFER_SIZE = 256;

    private final byte[] smallBuf = new byte[SMALL_BUFFER_SIZE];

    private final SeekableByteChannel archive;

    /**
     * The encoding of the tar file
     */
    private final ZipEncoding zipEncoding;

    private final LinkedList<TarArchiveEntry> entries = new LinkedList<>();

    private final int blockSize;

    private final boolean lenient;

    private final int recordSize;

    private final ByteBuffer recordBuffer;

    // the global sparse headers, this is only used in PAX Format 0.X
    private final List<TarArchiveStructSparse> globalSparseHeaders = new ArrayList<>();

    private boolean hasHitEOF;

    /**
     * The meta-data about the current entry
     */
    private TarArchiveEntry currEntry;

    // the global PAX header
    private Map<String, String> globalPaxHeaders = new HashMap<>();

    private final Map<String, List<InputStream>> sparseInputStreams = new HashMap<>();

    /**
     * Constructor for TarFile.
     *
     * @param content the content to use
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final byte[] content) throws IOException {
        this(new SeekableInMemoryByteChannel(content));
    }

    /**
     * Constructor for TarFile.
     *
     * @param content  the content to use
     * @param encoding the encoding to use
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final byte[] content, final String encoding) throws IOException {
        this(new SeekableInMemoryByteChannel(content), TarConstants.DEFAULT_BLKSIZE, TarConstants.DEFAULT_RCDSIZE, encoding, false);
    }

    /**
     * Constructor for TarFile.
     *
     * @param content the content to use
     * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
     *                ignored and the fields set to {@link TarArchiveEntry#UNKNOWN}. When set to false such illegal fields cause an
     *                exception instead.
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final byte[] content, final boolean lenient) throws IOException {
        this(new SeekableInMemoryByteChannel(content), TarConstants.DEFAULT_BLKSIZE, TarConstants.DEFAULT_RCDSIZE, null, lenient);
    }

    /**
     * Constructor for TarFile.
     *
     * @param archive the file of the archive to use
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final File archive) throws IOException {
        this(archive.toPath());
    }

    /**
     * Constructor for TarFile.
     *
     * @param archive  the file of the archive to use
     * @param encoding the encoding to use
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final File archive, final String encoding) throws IOException {
        this(archive.toPath(), encoding);
    }

    /**
     * Constructor for TarFile.
     *
     * @param archive the file of the archive to use
     * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
     *                ignored and the fields set to {@link TarArchiveEntry#UNKNOWN}. When set to false such illegal fields cause an
     *                exception instead.
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final File archive, final boolean lenient) throws IOException {
        this(archive.toPath(), lenient);
    }

    /**
     * Constructor for TarFile.
     *
     * @param archivePath the path of the archive to use
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final Path archivePath) throws IOException {
        this(Files.newByteChannel(archivePath), TarConstants.DEFAULT_BLKSIZE, TarConstants.DEFAULT_RCDSIZE, null, false);
    }

    /**
     * Constructor for TarFile.
     *
     * @param archivePath the path of the archive to use
     * @param encoding    the encoding to use
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final Path archivePath, final String encoding) throws IOException {
        this(Files.newByteChannel(archivePath), TarConstants.DEFAULT_BLKSIZE, TarConstants.DEFAULT_RCDSIZE, encoding, false);
    }

    /**
     * Constructor for TarFile.
     *
     * @param archivePath the path of the archive to use
     * @param lenient     when set to true illegal values for group/userid, mode, device numbers and timestamp will be
     *                    ignored and the fields set to {@link TarArchiveEntry#UNKNOWN}. When set to false such illegal fields cause an
     *                    exception instead.
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final Path archivePath, final boolean lenient) throws IOException {
        this(Files.newByteChannel(archivePath), TarConstants.DEFAULT_BLKSIZE, TarConstants.DEFAULT_RCDSIZE, null, lenient);
    }

    /**
     * Constructor for TarFile.
     *
     * @param content the content to use
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final SeekableByteChannel content) throws IOException {
        this(content, TarConstants.DEFAULT_BLKSIZE, TarConstants.DEFAULT_RCDSIZE, null, false);
    }

    /**
     * Constructor for TarFile.
     *
     * @param archive    the seekable byte channel to use
     * @param blockSize  the blocks size to use
     * @param recordSize the record size to use
     * @param encoding   the encoding to use
     * @param lenient    when set to true illegal values for group/userid, mode, device numbers and timestamp will be
     *                   ignored and the fields set to {@link TarArchiveEntry#UNKNOWN}. When set to false such illegal fields cause an
     *                   exception instead.
     * @throws IOException when reading the tar archive fails
     */
    public TarFile(final SeekableByteChannel archive, final int blockSize, final int recordSize, final String encoding, final boolean lenient) throws IOException {
        this.archive = archive;
        this.hasHitEOF = false;
        this.zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
        this.recordSize = recordSize;
        this.recordBuffer = ByteBuffer.allocate(this.recordSize);
        this.blockSize = blockSize;
        this.lenient = lenient;

        TarArchiveEntry entry;
        while ((entry = getNextTarEntry()) != null) {
            entries.add(entry);
        }
    }

    /**
     * Get the next entry in this tar archive. This will skip
     * to the end of the current entry, if there is one, and
     * place the position of the channel at the header of the
     * next entry, and read the header and instantiate a new
     * TarEntry from the header bytes and return that entry.
     * If there are no more entries in the archive, null will
     * be returned to indicate that the end of the archive has
     * been reached.
     *
     * @return The next TarEntry in the archive, or null if there is no next entry.
     * @throws IOException when reading the next TarEntry fails
     */
    private TarArchiveEntry getNextTarEntry() throws IOException {
        if (isAtEOF()) {
            return null;
        }

        if (currEntry != null) {
            // Skip to the end of the entry
            repositionForwardTo(currEntry.getDataOffset() + currEntry.getSize());
            throwExceptionIfPositionIsNotInArchive();
            skipRecordPadding();
        }

        final ByteBuffer headerBuf = getRecord();
        if (null == headerBuf) {
            /* hit EOF */
            currEntry = null;
            return null;
        }

        try {
            final long position = archive.position();
            currEntry = new TarArchiveEntry(globalPaxHeaders, headerBuf.array(), zipEncoding, lenient, position);
        } catch (final IllegalArgumentException e) {
            throw new IOException("Error detected parsing the header", e);
        }

        if (currEntry.isGNULongLinkEntry()) {
            final byte[] longLinkData = getLongNameData();
            if (longLinkData == null) {
                // Bugzilla: 40334
                // Malformed tar file - long link entry name not followed by
                // entry
                return null;
            }
            currEntry.setLinkName(zipEncoding.decode(longLinkData));
        }

        if (currEntry.isGNULongNameEntry()) {
            final byte[] longNameData = getLongNameData();
            if (longNameData == null) {
                // Bugzilla: 40334
                // Malformed tar file - long entry name not followed by
                // entry
                return null;
            }

            // COMPRESS-509 : the name of directories should end with '/'
            final String name = zipEncoding.decode(longNameData);
            currEntry.setName(name);
            if (currEntry.isDirectory() && !name.endsWith("/")) {
                currEntry.setName(name + "/");
            }
        }

        if (currEntry.isGlobalPaxHeader()) { // Process Global Pax headers
            readGlobalPaxHeaders();
        }

        try {
            if (currEntry.isPaxHeader()) { // Process Pax headers
                paxHeaders();
            } else if (!globalPaxHeaders.isEmpty()) {
                applyPaxHeadersToCurrentEntry(globalPaxHeaders, globalSparseHeaders);
            }
        } catch (NumberFormatException e) {
            throw new IOException("Error detected parsing the pax header", e);
        }

        if (currEntry.isOldGNUSparse()) { // Process sparse files
            readOldGNUSparse();
        }

        return currEntry;
    }

    /**
     * Adds the sparse chunks from the current entry to the sparse chunks,
     * including any additional sparse entries following the current entry.
     *
     * @throws IOException when reading the sparse entry fails
     */
    private void readOldGNUSparse() throws IOException {
        if (currEntry.isExtended()) {
            TarArchiveSparseEntry entry;
            do {
                final ByteBuffer headerBuf = getRecord();
                if (headerBuf == null) {
                    throw new IOException("premature end of tar archive. Didn't find extended_header after header with extended flag.");
                }
                entry = new TarArchiveSparseEntry(headerBuf.array());
                currEntry.getSparseHeaders().addAll(entry.getSparseHeaders());
                currEntry.setDataOffset(currEntry.getDataOffset() + recordSize);
            } while (entry.isExtended());
        }

        // sparse headers are all done reading, we need to build
        // sparse input streams using these sparse headers
        buildSparseInputStreams();
    }

    /**
     * Build the input streams consisting of all-zero input streams and non-zero input streams.
     * When reading from the non-zero input streams, the data is actually read from the original input stream.
     * The size of each input stream is introduced by the sparse headers.
     *
     * @implNote Some all-zero input streams and non-zero input streams have the size of 0. We DO NOT store the
     *        0 size input streams because they are meaningless.
     */
    private void buildSparseInputStreams() throws IOException {
        final List<InputStream> streams = new ArrayList<>();

        final List<TarArchiveStructSparse> sparseHeaders = currEntry.getOrderedSparseHeaders();

        // Stream doesn't need to be closed at all as it doesn't use any resources
        final InputStream zeroInputStream = new TarArchiveSparseZeroInputStream(); //NOSONAR
        // logical offset into the extracted entry
        long offset = 0;
        long numberOfZeroBytesInSparseEntry = 0;
        for (TarArchiveStructSparse sparseHeader : sparseHeaders) {
            final long zeroBlockSize = sparseHeader.getOffset() - offset;
            if (zeroBlockSize < 0) {
                // sparse header says to move backwards inside of the extracted entry
                throw new IOException("Corrupted struct sparse detected");
            }

            // only store the zero block if it is not empty
            if (zeroBlockSize > 0) {
                streams.add(new BoundedInputStream(zeroInputStream, zeroBlockSize));
                numberOfZeroBytesInSparseEntry += zeroBlockSize;
            }

            // only store the input streams with non-zero size
            if (sparseHeader.getNumbytes() > 0) {
                final long start =
                    currEntry.getDataOffset() + sparseHeader.getOffset() - numberOfZeroBytesInSparseEntry;
                if (start + sparseHeader.getNumbytes() < start) {
                    // possible integer overflow
                    throw new IOException("Unreadable TAR archive, sparse block offset or length too big");
                }
                streams.add(new BoundedSeekableByteChannelInputStream(start, sparseHeader.getNumbytes(), archive));
            }

            offset = sparseHeader.getOffset() + sparseHeader.getNumbytes();
        }

        sparseInputStreams.put(currEntry.getName(), streams);
    }

    /**
     * Update the current entry with the read pax headers
     * @param headers Headers read from the pax header
     * @param sparseHeaders Sparse headers read from pax header
     */
    private void applyPaxHeadersToCurrentEntry(final Map<String, String> headers, final List<TarArchiveStructSparse> sparseHeaders)
        throws IOException {
        currEntry.updateEntryFromPaxHeaders(headers);
        currEntry.setSparseHeaders(sparseHeaders);
    }

    /**
     *

     * For PAX Format 0.0, the sparse headers(GNU.sparse.offset and GNU.sparse.numbytes)
     * may appear multi times, and they look like:
     *

     * GNU.sparse.size=size
     * GNU.sparse.numblocks=numblocks
     * repeat numblocks times
     *   GNU.sparse.offset=offset
     *   GNU.sparse.numbytes=numbytes
     * end repeat
     *

     *
     *

     * For PAX Format 0.1, the sparse headers are stored in a single variable : GNU.sparse.map
     *

     * GNU.sparse.map
     *    Map of non-null data chunks. It is a string consisting of comma-separated values "offset,size[,offset-1,size-1...]"
     *

     *
     *

     * For PAX Format 1.X:
     *

     * The sparse map itself is stored in the file data block, preceding the actual file data.
     * It consists of a series of decimal numbers delimited by newlines. The map is padded with nulls to the nearest block boundary.
     * The first number gives the number of entries in the map. Following are map entries, each one consisting of two numbers
     * giving the offset and size of the data block it describes.
     * @throws IOException
     */
    private void paxHeaders() throws IOException {
        List<TarArchiveStructSparse> sparseHeaders = new ArrayList<>();
        final Map<String, String> headers;
        try (final InputStream input = getInputStream(currEntry)) {
            headers = TarUtils.parsePaxHeaders(input, sparseHeaders, globalPaxHeaders, currEntry.getSize());
        }

        // for 0.1 PAX Headers
        if (headers.containsKey("GNU.sparse.map")) {
            sparseHeaders = new ArrayList<>(TarUtils.parseFromPAX01SparseHeaders(headers.get("GNU.sparse.map")));
        }
        getNextTarEntry(); // Get the actual file entry
        if (currEntry == null) {
            throw new IOException("premature end of tar archive. Didn't find any entry after PAX header.");
        }
        applyPaxHeadersToCurrentEntry(headers, sparseHeaders);

        // for 1.0 PAX Format, the sparse map is stored in the file data block
        if (currEntry.isPaxGNU1XSparse()) {
            try (final InputStream input = getInputStream(currEntry)) {
                sparseHeaders = TarUtils.parsePAX1XSparseHeaders(input, recordSize);
            }
            currEntry.setSparseHeaders(sparseHeaders);
            // data of the entry is after the pax gnu entry. So we need to update the data position once again
            currEntry.setDataOffset(currEntry.getDataOffset() + recordSize);
        }

        // sparse headers are all done reading, we need to build
        // sparse input streams using these sparse headers
        buildSparseInputStreams();
    }

    private void readGlobalPaxHeaders() throws IOException {
        try (InputStream input = getInputStream(currEntry)) {
            globalPaxHeaders = TarUtils.parsePaxHeaders(input, globalSparseHeaders, globalPaxHeaders,
                currEntry.getSize());
        }
        getNextTarEntry(); // Get the actual file entry

        if (currEntry == null) {
            throw new IOException("Error detected parsing the pax header");
        }
    }

    /**
     * Get the next entry in this tar archive as longname data.
     *
     * @return The next entry in the archive as longname data, or null.
     * @throws IOException on error
     */
    private byte[] getLongNameData() throws IOException {
        final ByteArrayOutputStream longName = new ByteArrayOutputStream();
        int length;
        try (final InputStream in = getInputStream(currEntry)) {
            while ((length = in.read(smallBuf)) >= 0) {
                longName.write(smallBuf, 0, length);
            }
        }
        getNextTarEntry();
        if (currEntry == null) {
            // Bugzilla: 40334
            // Malformed tar file - long entry name not followed by entry
            return null;
        }
        byte[] longNameData = longName.toByteArray();
        // remove trailing null terminator(s)
        length = longNameData.length;
        while (length > 0 && longNameData[length - 1] == 0) {
            --length;
        }
        if (length != longNameData.length) {
            final byte[] l = new byte[length];
            System.arraycopy(longNameData, 0, l, 0, length);
            longNameData = l;
        }
        return longNameData;
    }

    /**
     * The last record block should be written at the full size, so skip any
     * additional space used to fill a record after an entry
     *
     * @throws IOException when skipping the padding of the record fails
     */
    private void skipRecordPadding() throws IOException {
        if (!isDirectory() && currEntry.getSize() > 0 && currEntry.getSize() % recordSize != 0) {
            final long numRecords = (currEntry.getSize() / recordSize) + 1;
            final long padding = (numRecords * recordSize) - currEntry.getSize();
            repositionForwardBy(padding);
            throwExceptionIfPositionIsNotInArchive();
        }
    }

    private void repositionForwardTo(final long newPosition) throws IOException {
        final long currPosition = archive.position();
        if (newPosition < currPosition) {
            throw new IOException("trying to move backwards inside of the archive");
        }
        archive.position(newPosition);
    }

    private void repositionForwardBy(final long offset) throws IOException {
        repositionForwardTo(archive.position() + offset);
    }

    /**
     * Checks if the current position of the SeekableByteChannel is in the archive.
     * @throws IOException If the position is not in the archive
     */
    private void throwExceptionIfPositionIsNotInArchive() throws IOException {
        if (archive.size() < archive.position()) {
            throw new IOException("Truncated TAR archive");
        }
    }

    /**
     * Get the next record in this tar archive. This will skip
     * over any remaining data in the current entry, if there
     * is one, and place the input stream at the header of the
     * next entry.
     *
     *
If there are no more entries in the archive, null will be
     * returned to indicate that the end of the archive has been
     * reached.  At the same time the {@code hasHitEOF} marker will be
     * set to true.

     *
     * @return The next TarEntry in the archive, or null if there is no next entry.
     * @throws IOException when reading the next TarEntry fails
     */
    private ByteBuffer getRecord() throws IOException {
        ByteBuffer headerBuf = readRecord();
        setAtEOF(isEOFRecord(headerBuf));
        if (isAtEOF() && headerBuf != null) {
            // Consume rest
            tryToConsumeSecondEOFRecord();
            consumeRemainderOfLastBlock();
            headerBuf = null;
        }
        return headerBuf;
    }

    /**
     * Tries to read the next record resetting the position in the
     * archive if it is not a EOF record.
     *
     *
This is meant to protect against cases where a tar
     * implementation has written only one EOF record when two are
     * expected. Actually this won't help since a non-conforming
     * implementation likely won't fill full blocks consisting of - by
     * default - ten records either so we probably have already read
     * beyond the archive anyway.

     *
     * @throws IOException if reading the record of resetting the position in the archive fails
     */
    private void tryToConsumeSecondEOFRecord() throws IOException {
        boolean shouldReset = true;
        try {
            shouldReset = !isEOFRecord(readRecord());
        } finally {
            if (shouldReset) {
                archive.position(archive.position() - recordSize);
            }
        }
    }

    /**
     * This method is invoked once the end of the archive is hit, it
     * tries to consume the remaining bytes under the assumption that
     * the tool creating this archive has padded the last block.
     */
    private void consumeRemainderOfLastBlock() throws IOException {
        final long bytesReadOfLastBlock = archive.position() % blockSize;
        if (bytesReadOfLastBlock > 0) {
            repositionForwardBy(blockSize - bytesReadOfLastBlock);
        }
    }

    /**
     * Read a record from the input stream and return the data.
     *
     * @return The record data or null if EOF has been hit.
     * @throws IOException if reading from the archive fails
     */
    private ByteBuffer readRecord() throws IOException {
        recordBuffer.rewind();
        final int readNow = archive.read(recordBuffer);
        if (readNow != recordSize) {
            return null;
        }
        return recordBuffer;
    }

    /**
     * Get all TAR Archive Entries from the TarFile
     *
     * @return All entries from the tar file
     */
    public List<TarArchiveEntry> getEntries() {
        return new ArrayList<>(entries);
    }

    private boolean isEOFRecord(final ByteBuffer headerBuf) {
        return headerBuf == null || ArchiveUtils.isArrayZero(headerBuf.array(), recordSize);
    }

    protected final boolean isAtEOF() {
        return hasHitEOF;
    }

    protected final void setAtEOF(final boolean b) {
        hasHitEOF = b;
    }

    private boolean isDirectory() {
        return currEntry != null && currEntry.isDirectory();
    }

    /**
     * Gets the input stream for the provided Tar Archive Entry.
     * @param entry Entry to get the input stream from
     * @return Input stream of the provided entry
     * @throws IOException Corrupted TAR archive. Can't read entry.
     */
    public InputStream getInputStream(final TarArchiveEntry entry) throws IOException {
        try {
            return new BoundedTarEntryInputStream(entry, archive);
        } catch (RuntimeException ex) {
            throw new IOException("Corrupted TAR archive. Can't read entry", ex);
        }
    }

    @Override
    public void close() throws IOException {
        archive.close();
    }

    private final class BoundedTarEntryInputStream extends BoundedArchiveInputStream {

        private final SeekableByteChannel channel;

        private final TarArchiveEntry entry;

        private long entryOffset;

        private int currentSparseInputStreamIndex;

        BoundedTarEntryInputStream(final TarArchiveEntry entry, final SeekableByteChannel channel) throws IOException {
            super(entry.getDataOffset(), entry.getRealSize());
            if (channel.size() - entry.getSize() < entry.getDataOffset()) {
                throw new IOException("entry size exceeds archive size");
            }
            this.entry = entry;
            this.channel = channel;
        }

        @Override
        protected int read(final long pos, final ByteBuffer buf) throws IOException {
            if (entryOffset >= entry.getRealSize()) {
                return -1;
            }

            final int totalRead;
            if (entry.isSparse()) {
                totalRead = readSparse(entryOffset, buf, buf.limit());
            } else {
                totalRead = readArchive(pos, buf);
            }

            if (totalRead == -1) {
                if (buf.array().length > 0) {
                    throw new IOException("Truncated TAR archive");
                }
                setAtEOF(true);
            } else {
                entryOffset += totalRead;
                buf.flip();
            }
            return totalRead;
        }

        private int readSparse(final long pos, final ByteBuffer buf, final int numToRead) throws IOException {
            // if there are no actual input streams, just read from the original archive
            final List<InputStream> entrySparseInputStreams = sparseInputStreams.get(entry.getName());
            if (entrySparseInputStreams == null || entrySparseInputStreams.isEmpty()) {
                return readArchive(entry.getDataOffset() + pos, buf);
            }

            if (currentSparseInputStreamIndex >= entrySparseInputStreams.size()) {
                return -1;
            }

            final InputStream currentInputStream = entrySparseInputStreams.get(currentSparseInputStreamIndex);
            final byte[] bufArray = new byte[numToRead];
            final int readLen = currentInputStream.read(bufArray);
            if (readLen != -1) {
                buf.put(bufArray, 0, readLen);
            }

            // if the current input stream is the last input stream,
            // just return the number of bytes read from current input stream
            if (currentSparseInputStreamIndex == entrySparseInputStreams.size() - 1) {
                return readLen;
            }

            // if EOF of current input stream is meet, open a new input stream and recursively call read
            if (readLen == -1) {
                currentSparseInputStreamIndex++;
                return readSparse(pos, buf, numToRead);
            }

            // if the rest data of current input stream is not long enough, open a new input stream
            // and recursively call read
            if (readLen < numToRead) {
                currentSparseInputStreamIndex++;
                final int readLenOfNext = readSparse(pos + readLen, buf, numToRead - readLen);
                if (readLenOfNext == -1) {
                    return readLen;
                }

                return readLen + readLenOfNext;
            }

            // if the rest data of current input stream is enough(which means readLen == len), just return readLen
            return readLen;
        }

        private int readArchive(final long pos, final ByteBuffer buf) throws IOException {
            channel.position(pos);
            return channel.read(buf);
        }
    }
}


text:
layout: about
comments: false

title: About
imageurl: /assets/image/fb-img-about.jpg
---

## a composer for video game, film, tv, advertising & show

the founding member of [J3ZZ](http://www.j3zz.com) (experimental sound creations & performances) and [Watcha Studios](http://www.watchastudios.com) (an audio video services company). I am a violinist, producer, composer and coaches interdisciplinary improvisation. I enjoy working in an international and multicultural environment, always looking for exchanges and collaborations between different artists and societies. In 1999 I graduated from the conservatoire national de région de musique, danse et art dramatique de a Réunion and in 2006 I graduated with a master of sciences in information systems and software engineering from [EPITA](http://www.epita.fr/).

## a sound artist & music producer

Born in Reunion Island, I am traveling the world with my violin. From the Mascarenes islands in Indian ocean to Paris, Warsaw, Prague and more (Asia, USA and Africa), I happily joined many bands as improviser, nourishing my joy to meet people and share as much as possible. Festival au desert 2011 and 2013, in Florence with the Tartit and the Tadalat as violinist but also artistic director of talking heArts and Hybris, two experimental formations focusing on interdisciplinary improvisation.

## a session violinist & live performer

When not on stage, I enjoy composing soundtracks for films/documentaries and dance shows (working with Zoltan Grecso - Willany Leo, Noemi Kulcsar - Tellabor or ENKNAP). Last but not least, I am a voice artist and singer songwriter. From classical to contemporary music, spoken word, barn rock, bluegrass and pop music, I like to jump from one world to another.

## a French male voice artist

As a culture and arts worker, I was involved with european network ROOTS & ROUTES (2010-2015: artist and coach ; 2011-2012: artists' community representative and board member ; 2013-2015: secretary general). I am supporting entrepreneurship, creative industry, youth mobility and intercultural dialogue being a member of several european associations / networks and active at an international level.

## an interdisciplinary improvisation coach


text:
package org.jetbrains.idea.devkit.inspections;

import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInspection.LocalInspectionEP;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.util.registry.RegistryKeyBean;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.testFramework.TestDataPath;
import com.intellij.testFramework.builders.JavaModuleFixtureBuilder;
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
import com.intellij.ui.components.JBList;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.PathUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.idea.devkit.DevkitJavaTestsUtil;

import java.nio.file.Paths;
import java.util.List;

@TestDataPath("$CONTENT_ROOT/testData/references/pluginConfigReference")
public class PluginConfigReferenceTest extends JavaCodeInsightFixtureTestCase {

  @Override
  protected String getBasePath() {
    return DevkitJavaTestsUtil.TESTDATA_PATH + "references/pluginConfigReference";
  }

  @Override
  protected void tuneFixture(JavaModuleFixtureBuilder moduleBuilder) {
    moduleBuilder.setLanguageLevel(LanguageLevel.JDK_1_8);
    moduleBuilder.addLibrary("platform-ide", PathUtil.getJarPathForClass(JBList.class));
    moduleBuilder.addLibrary("platform-impl", PathUtil.getJarPathForClass(RegistryKeyBean.class));
    moduleBuilder.addLibrary("platform-util", PathUtil.getJarPathForClass(IncorrectOperationException.class));
    moduleBuilder.addLibrary("platform-analysis", PathUtil.getJarPathForClass(LocalInspectionEP.class));
    moduleBuilder.addLibrary("platform-resources", Paths.get(PathUtil.getJarPathForClass(LocalInspectionEP.class))
      .resolveSibling("intellij.platform.resources").toString());
  }

  public void testRegistryKeyIdHighlighting() {
    doHighlightingTest("RegistryKeyId.java",
                       "registryKeyId.xml");
  }

  public void testRegistryKeyIdCompletion() {
    final List<String> variants = myFixture.getCompletionVariants("RegistryKeyIdCompletion.java",
                                                                  "registryKeyId.xml");
    assertContainsElements(variants,
                           "my.plugin.key",
                           "vcs.showConsole");

    final LookupElementPresentation plugin = getLookupElementPresentation("my.plugin.key");
    assertEquals(" My description", plugin.getTailText());
    assertEquals("myDefaultValue", plugin.getTypeText());
    assertEquals(AllIcons.Nodes.PluginRestart, plugin.getIcon());

    final LookupElementPresentation properties = getLookupElementPresentation("vcs.showConsole");
    assertEquals(" Show 'Console' tab in VCS toolwindow that logs all write-commands performed by IDE.", properties.getTailText());
    assertEquals("true", properties.getTypeText());
    assertEquals(AllIcons.Nodes.Plugin, properties.getIcon());
  }

  public void testExperimentalFeatureIdHighlighting() {
    doHighlightingTest("ExperimentalFeatureId.java",
                       "experimentalFeatureId.xml");
  }

  public void testExperimentalFeatureIdCompletion() {
    final List<String> variants = myFixture.getCompletionVariants("ExperimentalFeatureIdCompletion.java",
                                                                  "experimentalFeatureId.xml");
    assertContainsElements(variants,
                           "my.feature.id",
                           "my.internal.feature.id");

    final LookupElementPresentation feature = getLookupElementPresentation("my.feature.id");
    assertFalse(feature.isItemTextBold());
    assertEquals(" Feature ID Description", feature.getTailText());
    assertEquals("100%", feature.getTypeText());
    assertEquals(AllIcons.Nodes.PluginRestart, feature.getIcon());

    final LookupElementPresentation internal = getLookupElementPresentation("my.internal.feature.id");
    assertTrue(internal.isItemTextBold());
    assertEquals(" No Description", internal.getTailText());
    assertEquals("", internal.getTypeText());
    assertEquals(AllIcons.Nodes.Plugin, internal.getIcon());
  }

  public void testNotificationGroupIdHighlighting() {
    doHighlightingTest("NotificationGroupId.java",
                       "notificationGroupId.xml");
  }

  public void testNotificationGroupIdCompletion() {
    final List<String> variants = myFixture.getCompletionVariants("NotificationGroupIdCompletion.java",
                                                                  "notificationGroupId.xml");
    assertContainsElements(variants,
                           "my.balloon",
                           "my.toolwindow");

    final LookupElementPresentation balloon = getLookupElementPresentation("my.balloon");
    assertNull(balloon.getTailText());
    assertEquals("BALLOON", balloon.getTypeText());
    assertEquals(AllIcons.Ide.Notification.NoEvents, balloon.getTypeIcon());

    final LookupElementPresentation toolwindow = getLookupElementPresentation("my.toolwindow");
    assertEquals(" (my.toolwindow.id)", toolwindow.getTailText());
    assertEquals("TOOL_WINDOW", toolwindow.getTypeText());
    assertNull(toolwindow.getTypeIcon());
  }

  private void doHighlightingTest(String... filePaths) {
    myFixture.enableInspections(new UnresolvedPluginConfigReferenceInspection());
    myFixture.testHighlighting(filePaths);
  }

  private LookupElementPresentation getLookupElementPresentation(String lookupString) {
    final LookupElement lookupElement = ContainerUtil.find(myFixture.getLookupElements(),
                                                           element -> element.getLookupString().equals(lookupString));
    assertNotNull(lookupString, lookupElement);
    return LookupElementPresentation.renderElement(lookupElement);
  }
}


text:
var path = require('path');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.hot.config');

new WebpackDevServer(webpack(config), {
  contentBase: path.resolve(__dirname, './src'),
  hot: true,
  historyApiFallback: true
}).listen(3000, 'localhost', function (err) {
  if (err) {
    console.log(err); //eslint-disable-line no-console
  }

  console.log('Listening at localhost:3000'); //eslint-disable-line no-console
});


text:
package publish

import (
	"database/sql"
	"fmt"
	"reflect"
	"strings"

	"github.com/jinzhu/gorm"
)

type resolver struct {
	Records      []interface{}
	Dependencies map[string]*dependency
	DB           *gorm.DB
}

type dependency struct {
	Type                reflect.Type
	ManyToManyRelations []*gorm.Relationship
	PrimaryValues       [][][]interface{}
}

func includeValue(value [][]interface{}, values [][][]interface{}) bool {
	for _, v := range values {
		if fmt.Sprintf("%v", v) == fmt.Sprintf("%v", value) {
			return true
		}
	}
	return false
}

func (resolver *resolver) AddDependency(dep *dependency) {
	name := dep.Type.String()
	var newPrimaryKeys [][][]interface{}

	// append primary keys to dependency
	if d, ok := resolver.Dependencies[name]; ok {
		for _, primaryKey := range dep.PrimaryValues {
			if !includeValue(primaryKey, d.PrimaryValues) {
				newPrimaryKeys = append(newPrimaryKeys, primaryKey)
				d.PrimaryValues = append(d.PrimaryValues, primaryKey)
			}
		}
	} else {
		resolver.Dependencies[name] = dep
		newPrimaryKeys = dep.PrimaryValues
	}

	if len(newPrimaryKeys) > 0 {
		resolver.GetDependencies(dep, newPrimaryKeys)
	}
}

func (resolver *resolver) GetDependencies(dep *dependency, primaryKeys [][][]interface{}) {
	value := reflect.New(dep.Type)
	fromScope := resolver.DB.NewScope(value.Interface())

	draftDB := resolver.DB.Set("publish:draft_mode", true).Unscoped()
	for _, field := range fromScope.Fields() {
		if relationship := field.Relationship; relationship != nil {
			if isPublishableModel(field.Field.Interface()) {
				toType := modelType(field.Field.Interface())
				toScope := draftDB.NewScope(reflect.New(toType).Interface())
				draftTable := draftTableName(toScope.TableName())
				var dependencyKeys [][][]interface{}
				var rows *sql.Rows
				var err error
				var selectPrimaryKeys []string

				for _, field := range toScope.PrimaryFields() {
					selectPrimaryKeys = append(selectPrimaryKeys, fmt.Sprintf("%v", toScope.Quote(field.DBName)))
				}

				if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
					sql := fmt.Sprintf("%v IN (%v)", toQueryCondition(toScope, relationship.ForeignDBNames), toQueryMarks(primaryKeys, relationship.AssociationForeignDBNames...))
					rows, err = draftDB.Table(draftTable).Select(selectPrimaryKeys).Where("publish_status = ?", DIRTY).Where(sql, toQueryValues(primaryKeys, relationship.AssociationForeignDBNames...)...).Rows()
				} else if relationship.Kind == "belongs_to" {
					fromTable := draftTableName(fromScope.TableName())
					// toTable := toScope.TableName()

					sql := fmt.Sprintf("%v IN (SELECT %v FROM %v WHERE %v IN (%v))",
						strings.Join(relationship.AssociationForeignDBNames, ","), strings.Join(relationship.ForeignDBNames, ","), fromTable, scopePrimaryKeys(fromScope, fromTable), toQueryMarks(primaryKeys))

					rows, err = draftDB.Table(draftTable).Select(selectPrimaryKeys).Where("publish_status = ?", DIRTY).Where(sql, toQueryValues(primaryKeys)...).Rows()
				}

				if rows != nil && err == nil {
					defer rows.Close()
					columns, _ := rows.Columns()
					for rows.Next() {
						var primaryValues = make([]interface{}, len(columns))
						for idx := range primaryValues {
							var value interface{}
							primaryValues[idx] = &value
						}
						rows.Scan(primaryValues...)

						var currentDependencyKeys [][]interface{}
						for idx, value := range primaryValues {
							currentDependencyKeys = append(currentDependencyKeys, []interface{}{columns[idx], value})
						}

						dependencyKeys = append(dependencyKeys, currentDependencyKeys)
					}

					resolver.AddDependency(&dependency{Type: toType, PrimaryValues: dependencyKeys})
				}
			}

			if relationship.Kind == "many_to_many" {
				dep.ManyToManyRelations = append(dep.ManyToManyRelations, relationship)
			}
		}
	}
}

func (resolver *resolver) GenerateDependencies() {
	var addToDependencies = func(data interface{}) {
		if isPublishableModel(data) {
			scope := resolver.DB.NewScope(data)
			var primaryValues [][]interface{}
			for _, field := range scope.PrimaryFields() {
				primaryValues = append(primaryValues, []interface{}{field.DBName, field.Field.Interface()})
			}
			resolver.AddDependency(&dependency{Type: modelType(data), PrimaryValues: [][][]interface{}{primaryValues}})
		}
	}

	for _, record := range resolver.Records {
		reflectValue := reflect.Indirect(reflect.ValueOf(record))
		if reflectValue.Kind() == reflect.Slice {
			for i := 0; i < reflectValue.Len(); i++ {
				addToDependencies(reflectValue.Index(i).Interface())
			}
		} else {
			addToDependencies(record)
		}
	}
}

func (resolver *resolver) Publish() error {
	resolver.GenerateDependencies()
	tx := resolver.DB.Begin()

	for _, dep := range resolver.Dependencies {

		value := reflect.New(dep.Type).Elem()
		productionScope := resolver.DB.Set("publish:draft_mode", false).NewScope(value.Addr().Interface())
		productionTable := productionScope.TableName()
		draftTable := draftTableName(productionTable)
		productionPrimaryKey := scopePrimaryKeys(productionScope, productionTable)
		draftPrimaryKey := scopePrimaryKeys(productionScope, draftTable)

		var columns []string
		for _, field := range productionScope.Fields() {
			if field.IsNormal {
				columns = append(columns, field.DBName)
			}
		}

		var productionColumns, draftColumns []string
		for _, column := range columns {
			productionColumns = append(productionColumns, productionScope.Quote(column))
			draftColumns = append(draftColumns, productionScope.Quote(column))
		}

		if len(dep.PrimaryValues) > 0 {
			// delete old records
			deleteSql := fmt.Sprintf("DELETE FROM %v WHERE %v IN (%v)", productionTable, productionPrimaryKey, toQueryMarks(dep.PrimaryValues))
			tx.Exec(deleteSql, toQueryValues(dep.PrimaryValues)...)

			// insert new records
			publishSql := fmt.Sprintf("INSERT INTO %v (%v) SELECT %v FROM %v WHERE %v IN (%v)",
				productionTable, strings.Join(productionColumns, " ,"), strings.Join(draftColumns, " ,"),
				draftTable, draftPrimaryKey, toQueryMarks(dep.PrimaryValues))
			tx.Exec(publishSql, toQueryValues(dep.PrimaryValues)...)

			// publish join table data
			for _, relationship := range dep.ManyToManyRelations {
				productionTable := relationship.JoinTableHandler.Table(tx.Set("publish:draft_mode", false))
				draftTable := relationship.JoinTableHandler.Table(tx.Set("publish:draft_mode", true))
				var productionJoinKeys, draftJoinKeys []string
				var productionCondition, draftCondition string
				for _, foreignKey := range relationship.JoinTableHandler.SourceForeignKeys() {
					productionJoinKeys = append(productionJoinKeys, fmt.Sprintf("%v.%v", productionTable, productionScope.Quote(foreignKey.DBName)))
					draftJoinKeys = append(draftJoinKeys, fmt.Sprintf("%v.%v", draftTable, productionScope.Quote(foreignKey.DBName)))
				}

				if len(productionJoinKeys) > 1 {
					productionCondition = fmt.Sprintf("(%v)", strings.Join(productionJoinKeys, ","))
					draftCondition = fmt.Sprintf("(%v)", strings.Join(draftJoinKeys, ","))
				} else {
					productionCondition = strings.Join(productionJoinKeys, ",")
					draftCondition = strings.Join(draftJoinKeys, ",")
				}

				sql := fmt.Sprintf("DELETE FROM %v WHERE %v IN (%v)", productionTable, productionCondition, toQueryMarks(dep.PrimaryValues, relationship.ForeignFieldNames...))
				tx.Exec(sql, toQueryValues(dep.PrimaryValues, relationship.ForeignFieldNames...)...)

				rows, _ := tx.Raw(fmt.Sprintf("SELECT * FROM %s", draftTable)).Rows()
				joinColumns, _ := rows.Columns()
				rows.Close()
				if len(joinColumns) == 0 {
					continue
				}

				var productionJoinTableColumns, draftJoinTableColumns []string
				for _, column := range joinColumns {
					productionJoinTableColumns = append(productionJoinTableColumns, productionScope.Quote(column))
					draftJoinTableColumns = append(draftJoinTableColumns, productionScope.Quote(column))
				}

				publishSql := fmt.Sprintf("INSERT INTO %v (%v) SELECT %v FROM %v WHERE %v IN (%v)",
					productionTable, strings.Join(productionJoinTableColumns, " ,"), strings.Join(draftJoinTableColumns, " ,"),
					draftTable, draftCondition, toQueryMarks(dep.PrimaryValues, relationship.ForeignFieldNames...))
				tx.Exec(publishSql, toQueryValues(dep.PrimaryValues, relationship.ForeignFieldNames...)...)
			}

			// set status to published
			updateStateSql := fmt.Sprintf("UPDATE %v SET publish_status = ? WHERE %v IN (%v)", draftTable, draftPrimaryKey, toQueryMarks(dep.PrimaryValues))

			var params = []interface{}{bool(PUBLISHED)}
			params = append(params, toQueryValues(dep.PrimaryValues)...)
			tx.Exec(updateStateSql, params...)
		}
	}

	if err := tx.Error; err == nil {
		return tx.Commit().Error
	} else {
		tx.Rollback()
		return err
	}
}

func (resolver *resolver) Discard() error {
	resolver.GenerateDependencies()
	tx := resolver.DB.Begin()

	for _, dep := range resolver.Dependencies {
		value := reflect.New(dep.Type).Elem()
		productionScope := resolver.DB.Set("publish:draft_mode", false).NewScope(value.Addr().Interface())
		productionTable := productionScope.TableName()
		draftTable := draftTableName(productionTable)

		productionPrimaryKey := scopePrimaryKeys(productionScope, productionTable)
		draftPrimaryKey := scopePrimaryKeys(productionScope, draftTable)

		var columns []string
		for _, field := range productionScope.Fields() {
			if field.IsNormal {
				columns = append(columns, field.DBName)
			}
		}

		var productionColumns, draftColumns []string
		for _, column := range columns {
			productionColumns = append(productionColumns, productionScope.Quote(column))
			draftColumns = append(draftColumns, productionScope.Quote(column))
		}

		// delete data from draft db
		deleteSql := fmt.Sprintf("DELETE FROM %v WHERE %v IN (%v)", draftTable, draftPrimaryKey, toQueryMarks(dep.PrimaryValues))
		tx.Exec(deleteSql, toQueryValues(dep.PrimaryValues)...)

		// delete join table
		for _, relationship := range dep.ManyToManyRelations {
			productionTable := relationship.JoinTableHandler.Table(tx.Set("publish:draft_mode", false))
			draftTable := relationship.JoinTableHandler.Table(tx.Set("publish:draft_mode", true))
			var productionJoinKeys, draftJoinKeys []string
			var productionCondition, draftCondition string
			for _, foreignKey := range relationship.JoinTableHandler.SourceForeignKeys() {
				productionJoinKeys = append(productionJoinKeys, fmt.Sprintf("%v.%v", productionTable, productionScope.Quote(foreignKey.DBName)))
				draftJoinKeys = append(draftJoinKeys, fmt.Sprintf("%v.%v", draftTable, productionScope.Quote(foreignKey.DBName)))
			}

			if len(productionJoinKeys) > 1 {
				productionCondition = fmt.Sprintf("(%v)", strings.Join(productionJoinKeys, ","))
				draftCondition = fmt.Sprintf("(%v)", strings.Join(draftJoinKeys, ","))
			} else {
				productionCondition = strings.Join(productionJoinKeys, ",")
				draftCondition = strings.Join(draftJoinKeys, ",")
			}

			sql := fmt.Sprintf("DELETE FROM %v WHERE %v IN (%v)", draftTable, draftCondition, toQueryMarks(dep.PrimaryValues))
			tx.Exec(sql, toQueryValues(dep.PrimaryValues)...)

			rows, _ := tx.Raw(fmt.Sprintf("select * from %v", draftTable)).Rows()
			joinColumns, _ := rows.Columns()
			rows.Close()
			if len(joinColumns) == 0 {
				continue
			}
			var productionJoinTableColumns, draftJoinTableColumns []string
			for _, column := range joinColumns {
				productionJoinTableColumns = append(productionJoinTableColumns, productionScope.Quote(column))
				draftJoinTableColumns = append(draftJoinTableColumns, productionScope.Quote(column))
			}

			publishSql := fmt.Sprintf("INSERT INTO %v (%v) SELECT %v FROM %v WHERE %v IN (%v)",
				draftTable, strings.Join(draftJoinTableColumns, " ,"), strings.Join(productionJoinTableColumns, " ,"),
				productionTable, productionCondition, toQueryMarks(dep.PrimaryValues))
			tx.Exec(publishSql, toQueryValues(dep.PrimaryValues)...)
		}

		// copy data from production to draft
		discardSql := fmt.Sprintf("INSERT INTO %v (%v) SELECT %v FROM %v WHERE %v IN (%v)",
			draftTable, strings.Join(draftColumns, " ,"),
			strings.Join(productionColumns, " ,"), productionTable,
			productionPrimaryKey, toQueryMarks(dep.PrimaryValues))
		tx.Exec(discardSql, toQueryValues(dep.PrimaryValues)...)
	}

	if err := tx.Error; err == nil {
		return tx.Commit().Error
	} else {
		tx.Rollback()
		return err
	}
}

func scopePrimaryKeys(scope *gorm.Scope, tableName string) string {
	var primaryKeys []string
	for _, field := range scope.PrimaryFields() {
		key := fmt.Sprintf("%v.%v", scope.Quote(tableName), scope.Quote(field.DBName))
		primaryKeys = append(primaryKeys, key)
	}
	if len(primaryKeys) > 1 {
		return fmt.Sprintf("(%v)", strings.Join(primaryKeys, ","))
	}
	return strings.Join(primaryKeys, "")
}

func toQueryCondition(scope *gorm.Scope, columns []string) string {
	var newColumns []string
	for _, column := range columns {
		newColumns = append(newColumns, scope.Quote(column))
	}

	if len(columns) > 1 {
		return fmt.Sprintf("(%v)", strings.Join(newColumns, ","))
	} else {
		return strings.Join(columns, ",")
	}
}

func toQueryMarks(primaryValues [][][]interface{}, columns ...string) string {
	var results []string

	for _, primaryValue := range primaryValues {
		var marks []string
		for _, value := range primaryValue {
			if len(columns) == 0 {
				marks = append(marks, "?")
			} else {
				for _, column := range columns {
					if fmt.Sprintf("%v", value[0]) == fmt.Sprintf("%v", column) {
						marks = append(marks, "?")
					}
					break
				}
			}
		}

		if len(marks) > 1 {
			results = append(results, fmt.Sprintf("(%v)", strings.Join(marks, ",")))
		} else {
			results = append(results, strings.Join(marks, ""))
		}
	}
	return strings.Join(results, ",")
}

func toQueryValues(primaryValues [][][]interface{}, columns ...string) (values []interface{}) {
	for _, primaryValue := range primaryValues {
		for _, value := range primaryValue {
			if len(columns) == 0 {
				values = append(values, value[1])
			} else {
				for _, column := range columns {
					if fmt.Sprintf("%v", value[0]) == fmt.Sprintf("%v", column) {
						values = append(values, value[1])
					}
					break
				}
			}
		}
	}
	return values
}


text:
import Ember from 'ember';

export default Ember.Mixin.create({
    activate: function() {
        this._super();
        window.scrollTo(0, 0);
    }
});


text:
package ru.makkarpov.scalingua.pofile

import java.io.File

object MessageLocation {
  implicit case object LocationOrdering extends Ordering[MessageLocation] {
    override def compare(x: MessageLocation, y: MessageLocation): Int = {
      //fs independent comparison
      val r = x.file.toString.compareTo(y.file.toString) match {
        case 0 => x.line.compare(y.line)
        case x => x
      }
      r
    }
  }

  def apply(file: String): MessageLocation = MessageLocation(new File(file), -1)
}

case class MessageLocation(file: File, line: Int) {
  def fileString: String = file.toString.replace("""\""", "/")
}


text:
package ru.tulupov.nsuconnect.protocol.commands;

import android.content.Intent;

import ru.tulupov.nsuconnect.helper.BroadcastHelper;
import ru.tulupov.nsuconnect.util.Log;

import java.sql.SQLException;
import java.util.Date;

import ru.tulupov.nsuconnect.database.ContentUriHelper;
import ru.tulupov.nsuconnect.database.DatabaseConstants;
import ru.tulupov.nsuconnect.database.HelperFactory;
import ru.tulupov.nsuconnect.model.Message;
import ru.tulupov.nsuconnect.protocol.Command;
import ru.tulupov.nsuconnect.protocol.CommandContext;
import ru.tulupov.nsuconnect.service.DataService;

public class StartTypingCommand implements Command {
    private static final String TAG = StartTypingCommand.class.getSimpleName();

    @Override
    public void execute(CommandContext context) {
        context.getApplicationContext().sendBroadcast(BroadcastHelper.getChatTypingIntent(context.getChat().getId(), true));
    }
}