<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.syncope.client.lib;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.cxf.jaxrs.client.Client;
import org.apache.cxf.jaxrs.client.ClientConfiguration;
import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.common.gzip.GZIPInInterceptor;
import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor;
import org.apache.cxf.transport.http.URLConnectionHTTPConduit;
import org.apache.syncope.common.lib.SyncopeConstants;
import org.apache.syncope.common.lib.search.AnyObjectFiqlSearchConditionBuilder;
import org.apache.syncope.common.lib.search.OrderByClauseBuilder;
import org.apache.syncope.common.lib.search.GroupFiqlSearchConditionBuilder;
import org.apache.syncope.common.lib.search.UserFiqlSearchConditionBuilder;
import org.apache.syncope.common.lib.to.UserTO;
import org.apache.syncope.common.rest.api.Preference;
import org.apache.syncope.common.rest.api.RESTHeaders;
import org.apache.syncope.common.rest.api.service.AccessTokenService;
import org.apache.syncope.common.rest.api.service.UserSelfService;

/**
 * Entry point for client access to all REST services exposed by Syncope core; obtain instances via
 * {@link SyncopeClientFactoryBean}.
 */
public class SyncopeClient {

    private static final String HEADER_SPLIT_PROPERTY = "org.apache.cxf.http.header.split";

    private final MediaType mediaType;

    private final JAXRSClientFactoryBean restClientFactory;

    private final RestClientExceptionMapper exceptionMapper;

    private final boolean useCompression;

    public SyncopeClient(
            final MediaType mediaType,
            final JAXRSClientFactoryBean restClientFactory,
            final RestClientExceptionMapper exceptionMapper,
            final AuthenticationHandler handler,
            final boolean useCompression) {

        this.mediaType = mediaType;
        this.restClientFactory = restClientFactory;
        if (this.restClientFactory.getHeaders() == null) {
            this.restClientFactory.setHeaders(new HashMap<String, String>());
        }
        this.exceptionMapper = exceptionMapper;
        init(handler);
        this.useCompression = useCompression;
    }

    /**
     * Initializes the provided {@code restClientFactory} with the authentication capabilities of the provided
     * {@code handler}.
     *
     * Currently supports:
     * <ul>
     * <li>{@link JWTAuthenticationHandler}</li>
     * <li>{@link AnonymousAuthenticationHandler}</li>
     * <li>{@link BasicAuthenticationHandler}</li>
     * </ul>
     * More can be supported by subclasses.
     *
     * @param handler authentication handler
     */
    protected void init(final AuthenticationHandler handler) {
        cleanup();

        if (handler instanceof AnonymousAuthenticationHandler) {
            restClientFactory.setUsername(((AnonymousAuthenticationHandler) handler).getUsername());
            restClientFactory.setPassword(((AnonymousAuthenticationHandler) handler).getPassword());
        } else if (handler instanceof BasicAuthenticationHandler) {
            restClientFactory.setUsername(((BasicAuthenticationHandler) handler).getUsername());
            restClientFactory.setPassword(((BasicAuthenticationHandler) handler).getPassword());

            String jwt = getService(AccessTokenService.class).login().getHeaderString(RESTHeaders.TOKEN);
            restClientFactory.getHeaders().put(RESTHeaders.TOKEN, Collections.singletonList(jwt));

            restClientFactory.setUsername(null);
            restClientFactory.setPassword(null);
        } else if (handler instanceof JWTAuthenticationHandler) {
            restClientFactory.getHeaders().put(
                    RESTHeaders.TOKEN, Collections.singletonList(((JWTAuthenticationHandler) handler).getJwt()));
        }
    }

    protected void cleanup() {
        restClientFactory.getHeaders().remove(RESTHeaders.TOKEN);
        restClientFactory.setUsername(null);
        restClientFactory.setPassword(null);
    }

    /**
     * Attempts to extend the lifespan of the JWT currently in use.
     */
    public void refresh() {
        getService(AccessTokenService.class).refresh();
    }

    /**
     * Invalidates the JWT currently in use.
     */
    public void logout() {
        getService(AccessTokenService.class).logout();
        cleanup();
    }

    /**
     * (Re)initializes the current instance with the authentication capabilities of the provided {@code handler}.
     *
     * @param handler authentication handler
     */
    public void login(final AuthenticationHandler handler) {
        init(handler);
    }

    /**
     * Returns a new instance of {@link UserFiqlSearchConditionBuilder}, for assisted building of FIQL queries.
     *<commit_msg>Actual takes the refreshed JWT<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.syncope.client.lib;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.cxf.jaxrs.client.Client;
import org.apache.cxf.jaxrs.client.ClientConfiguration;
import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.common.gzip.GZIPInInterceptor;
import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor;
import org.apache.cxf.transport.http.URLConnectionHTTPConduit;
import org.apache.syncope.common.lib.SyncopeConstants;
import org.apache.syncope.common.lib.search.AnyObjectFiqlSearchConditionBuilder;
import org.apache.syncope.common.lib.search.OrderByClauseBuilder;
import org.apache.syncope.common.lib.search.GroupFiqlSearchConditionBuilder;
import org.apache.syncope.common.lib.search.UserFiqlSearchConditionBuilder;
import org.apache.syncope.common.lib.to.UserTO;
import org.apache.syncope.common.rest.api.Preference;
import org.apache.syncope.common.rest.api.RESTHeaders;
import org.apache.syncope.common.rest.api.service.AccessTokenService;
import org.apache.syncope.common.rest.api.service.UserSelfService;

/**
 * Entry point for client access to all REST services exposed by Syncope core; obtain instances via
 * {@link SyncopeClientFactoryBean}.
 */
public class SyncopeClient {

    private static final String HEADER_SPLIT_PROPERTY = "org.apache.cxf.http.header.split";

    private final MediaType mediaType;

    private final JAXRSClientFactoryBean restClientFactory;

    private final RestClientExceptionMapper exceptionMapper;

    private final boolean useCompression;

    public SyncopeClient(
            final MediaType mediaType,
            final JAXRSClientFactoryBean restClientFactory,
            final RestClientExceptionMapper exceptionMapper,
            final AuthenticationHandler handler,
            final boolean useCompression) {

        this.mediaType = mediaType;
        this.restClientFactory = restClientFactory;
        if (this.restClientFactory.getHeaders() == null) {
            this.restClientFactory.setHeaders(new HashMap<String, String>());
        }
        this.exceptionMapper = exceptionMapper;
        init(handler);
        this.useCompression = useCompression;
    }

    /**
     * Initializes the provided {@code restClientFactory} with the authentication capabilities of the provided
     * {@code handler}.
     *
     * Currently supports:
     * <ul>
     * <li>{@link JWTAuthenticationHandler}</li>
     * <li>{@link AnonymousAuthenticationHandler}</li>
     * <li>{@link BasicAuthenticationHandler}</li>
     * </ul>
     * More can be supported by subclasses.
     *
     * @param handler authentication handler
     */
    protected void init(final AuthenticationHandler handler) {
        cleanup();

        if (handler instanceof AnonymousAuthenticationHandler) {
            restClientFactory.setUsername(((AnonymousAuthenticationHandler) handler).getUsername());
            restClientFactory.setPassword(((AnonymousAuthenticationHandler) handler).getPassword());
        } else if (handler instanceof BasicAuthenticationHandler) {
            restClientFactory.setUsername(((BasicAuthenticationHandler) handler).getUsername());
            restClientFactory.setPassword(((BasicAuthenticationHandler) handler).getPassword());

            String jwt = getService(AccessTokenService.class).login().getHeaderString(RESTHeaders.TOKEN);
            restClientFactory.getHeaders().put(RESTHeaders.TOKEN, Collections.singletonList(jwt));

            restClientFactory.setUsername(null);
            restClientFactory.setPassword(<PASSWORD>);
        } else if (handler instanceof JWTAuthenticationHandler) {
            restClientFactory.getHeaders().put(
                    RESTHeaders.TOKEN, Collections.singletonList(((JWTAuthenticationHandler) handler).getJwt()));
        }
    }

    protected void cleanup() {
        restClientFactory.getHeaders().remove(RESTHeaders.TOKEN);
        restClientFactory.setUsername(null);
        restClientFactory.setPassword(null);
    }

    /**
     * Attempts to extend the lifespan of the JWT currently in use.
     */
    public void refresh() {
        String jwt = getService(AccessTokenService.class).refresh().getHeaderString(RESTHeaders.TOKEN);
        restClientFactory.getHeaders().put(RESTHeaders.TOKEN, Collections.singletonList(jwt));
    }

    /**
     * Invalidates the JWT currently in use.
     */
    public void logout() {
        getService(AccessTokenService.class).logout();
        cleanup();
    }

    /**
     * (Re)initializes the current instance with the authentication capabilities of the provided {@code handler}.
     *
     * @param handler authentication handler
     */
    public void login(final AuthenticationHandler handler) {
        init(handler);
    }

    /**
     * Returns a new instance of {@link UserFiqlSearchConditionBuilder}, for assisted building of FIQL queries.
     *
{'fraction_non_alphanumeric': 0.09236915049730964, 'fraction_numerical': 0.0009783140388064568, 'mean_word_length': 3.6964012251148546, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4443407', 'n_tokens_mistral': 3217, 'n_tokens_neox': 3161, 'n_words': 790}