<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.jackrabbit.commons;

import static java.net.URLDecoder.decode;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

import javax.imageio.spi.ServiceRegistry;
import javax.jcr.Binary;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.PropertyType;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.RepositoryFactory;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.nodetype.NodeType;
import javax.jcr.query.QueryResult;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;

import org.apache.jackrabbit.commons.iterator.NodeIterable;
import org.apache.jackrabbit.commons.iterator.PropertyIterable;
import org.apache.jackrabbit.commons.iterator.RowIterable;

/**
 * Collection of static utility methods for use with the JCR API.
 *
 * @since Apache Jackrabbit 2.0
 */
public class JcrUtils {

    /**
     * The repository URI parameter name used by the
     * {@link #getRepository(String)} method. All {@link RepositoryFactory}
     * implementations that want to support this repository access convention
     * should implement processing of this parameter.
     * <p>
     * Client applications are recommended to use the
     * {@link #getRepository(String)} method instead of directly referencing
     * this constant unless they explicitly want to pass also other
     * {@link RepositoryFactory} parameters through the
     * {@link #getRepository(Map)} method.
     */
    public static final String REPOSITORY_URI =
        "org.apache.jackrabbit.repository.uri";

    /**
     * A pre-allocated empty array of values.
     *
     * @since Apache Jackrabbit 2.3
     */
    public static final Value[] NO_VALUES = new Value[0];

    /**
     * Private constructor to prevent instantiation of this class.
     */
    private JcrUtils() {
    }

    /**
     * Returns the default repository of the current environment.
     * Implemented by calling {@link #getRepository(Map)} with a
     * <code>null</code> parameter map.
     *
     * @see RepositoryFactory#getRepository(Map)
     * @return default repository
     * @throws RepositoryException if a default repository is not available
     *                             or can not be accessed
     */
    public static Repository getRepository() throws RepositoryException {
        return getRepository((Map<String, String>) null);
    }

    /**
     * Looks up the available {@link RepositoryFactory repository factories}
     * and returns the {@link Repository repository} that one of the factories
     * returns for the given settings.
     * <p>
     * Note that unlike {@link RepositoryFactory#getRepository(Map)} this
     * method will throw an exception instead of returning <code>null</code>
     * if the given parameters can not be interpreted.
     *
     * @param parameters repository settings
     * @return repository reference
     * @throws RepositoryException if the repository can not be accessed,
     *                             or if an appropriate repository factory
     *                             is not available
     */
    public static Repository getRepository(Map<String, String> parameters)
            throws RepositoryException {
        String newline = System.getProperty("line.separator");

        // Prepare the potential error message (JCR-2459)
        StringBuilder log = new StringBuilder("Unable to access a repository");
        if (parameters != null) {
            log.append(" with the following settings:");
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                log.append(newline);
                log.append("    ");
                log.append(entry.getKey());
                log.append(": ");
                log.append(entry.getValue());
            }
        } else {
            log.append(" with the default settings.");
        }

        // Use the query part of a repository URI as additional parameters
        if (parameters != null
                && parameters.containsKey(JcrUtils.REPOSITORY_URI)) {
            String uri = parameters.get(JcrUtils.REPOSITORY_URI);
            try {
                URI u = new URI(uri);
                String query = u.getRawQuery();
                if (query != null) {
                   Map<String, String> copy = new HashMap<String, String>(parameters);
                   for (String entry : query.split("&")) {
                        int i = entry.indexOf('=');
                        if (i != -1) {
                            copy.put(
                                    decode(entry.substring(0, i), "UTF-8"),
                                    decode(entry.substring(i + 1), "UTF-8"));
                        } else {
                            copy.put(
                                    decode(entry, "UTF-8"),
                                    Boolean.TRUE.toString());
                        }
                    }
                    copy.put(
                            JcrUtils.REPOSITORY_URI,
                            new URI(u.getScheme(), u.getRawAuthority(),
                                    u.getRawPath(), null, u.getRawFragment()
                                    ).toASCIIString());
                    parameters = copy;
                }
            } catch (URISyntaxException e) {
                log.append(newline);
                log.append("Note that the given repository URI was invalid:");
                log.append(newline);
                log.append("        " + uri);
                log.append(newline);
                log.append("        " + e.getMessage());
            } catch (UnsupportedEncodingException e) {
                throw new RepositoryException("UTF-8 is not supported!", e);
            }
        }

        // Iterate through the available RepositoryFactories, with logging
        log.append(newline);
        log.append("The following RepositoryFactory classes were consulted:");
        Iterator<RepositoryFactory> iterator =
            ServiceRegistry.lookupProviders(RepositoryFactory.class);
        while (iterator.hasNext()) {
            RepositoryFactory factory = iterator.next();
            log.append(newline);
            log.append("    ");
            log.append(factory.getClass().getName());
            try {
                Repository repository = factory.getRepository(parameters);
                if (repository != null) {
                    // We found the requested repository! Return it
                    // and just ignore the error message being built.
                    return repository;
                } else {
                    log.append(": declined");
                }
            } catch (Exception e) {
                log.append(": failed");
                for (Throwable c = e; c != null; c = c.getCause()) {<commit_msg>use stringbuffer correctly<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.jackrabbit.commons;

import static java.net.URLDecoder.decode;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

import javax.imageio.spi.ServiceRegistry;
import javax.jcr.Binary;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.PropertyType;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.RepositoryFactory;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.nodetype.NodeType;
import javax.jcr.query.QueryResult;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;

import org.apache.jackrabbit.commons.iterator.NodeIterable;
import org.apache.jackrabbit.commons.iterator.PropertyIterable;
import org.apache.jackrabbit.commons.iterator.RowIterable;

/**
 * Collection of static utility methods for use with the JCR API.
 *
 * @since Apache Jackrabbit 2.0
 */
public class JcrUtils {

    /**
     * The repository URI parameter name used by the
     * {@link #getRepository(String)} method. All {@link RepositoryFactory}
     * implementations that want to support this repository access convention
     * should implement processing of this parameter.
     * <p>
     * Client applications are recommended to use the
     * {@link #getRepository(String)} method instead of directly referencing
     * this constant unless they explicitly want to pass also other
     * {@link RepositoryFactory} parameters through the
     * {@link #getRepository(Map)} method.
     */
    public static final String REPOSITORY_URI =
        "org.apache.jackrabbit.repository.uri";

    /**
     * A pre-allocated empty array of values.
     *
     * @since Apache Jackrabbit 2.3
     */
    public static final Value[] NO_VALUES = new Value[0];

    /**
     * Private constructor to prevent instantiation of this class.
     */
    private JcrUtils() {
    }

    /**
     * Returns the default repository of the current environment.
     * Implemented by calling {@link #getRepository(Map)} with a
     * <code>null</code> parameter map.
     *
     * @see RepositoryFactory#getRepository(Map)
     * @return default repository
     * @throws RepositoryException if a default repository is not available
     *                             or can not be accessed
     */
    public static Repository getRepository() throws RepositoryException {
        return getRepository((Map<String, String>) null);
    }

    /**
     * Looks up the available {@link RepositoryFactory repository factories}
     * and returns the {@link Repository repository} that one of the factories
     * returns for the given settings.
     * <p>
     * Note that unlike {@link RepositoryFactory#getRepository(Map)} this
     * method will throw an exception instead of returning <code>null</code>
     * if the given parameters can not be interpreted.
     *
     * @param parameters repository settings
     * @return repository reference
     * @throws RepositoryException if the repository can not be accessed,
     *                             or if an appropriate repository factory
     *                             is not available
     */
    public static Repository getRepository(Map<String, String> parameters)
            throws RepositoryException {
        String newline = System.getProperty("line.separator");

        // Prepare the potential error message (JCR-2459)
        StringBuilder log = new StringBuilder("Unable to access a repository");
        if (parameters != null) {
            log.append(" with the following settings:");
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                log.append(newline);
                log.append("    ");
                log.append(entry.getKey());
                log.append(": ");
                log.append(entry.getValue());
            }
        } else {
            log.append(" with the default settings.");
        }

        // Use the query part of a repository URI as additional parameters
        if (parameters != null
                && parameters.containsKey(JcrUtils.REPOSITORY_URI)) {
            String uri = parameters.get(JcrUtils.REPOSITORY_URI);
            try {
                URI u = new URI(uri);
                String query = u.getRawQuery();
                if (query != null) {
                   Map<String, String> copy = new HashMap<String, String>(parameters);
                   for (String entry : query.split("&")) {
                        int i = entry.indexOf('=');
                        if (i != -1) {
                            copy.put(
                                    decode(entry.substring(0, i), "UTF-8"),
                                    decode(entry.substring(i + 1), "UTF-8"));
                        } else {
                            copy.put(
                                    decode(entry, "UTF-8"),
                                    Boolean.TRUE.toString());
                        }
                    }
                    copy.put(
                            JcrUtils.REPOSITORY_URI,
                            new URI(u.getScheme(), u.getRawAuthority(),
                                    u.getRawPath(), null, u.getRawFragment()
                                    ).toASCIIString());
                    parameters = copy;
                }
            } catch (URISyntaxException e) {
                log.append(newline);
                log.append("Note that the given repository URI was invalid:");
                log.append(newline);
                log.append("        ").append(uri);
                log.append(newline);
                log.append("        ").append(e.getMessage());
            } catch (UnsupportedEncodingException e) {
                throw new RepositoryException("UTF-8 is not supported!", e);
            }
        }

        // Iterate through the available RepositoryFactories, with logging
        log.append(newline);
        log.append("The following RepositoryFactory classes were consulted:");
        Iterator<RepositoryFactory> iterator =
            ServiceRegistry.lookupProviders(RepositoryFactory.class);
        while (iterator.hasNext()) {
            RepositoryFactory factory = iterator.next();
            log.append(newline);
            log.append("    ");
            log.append(factory.getClass().getName());
            try {
                Repository repository = factory.getRepository(parameters);
                if (repository != null) {
                    // We found the requested repository! Return it
                    // and just ignore the error message being built.
                    return repository;
                } else {
                    log.append(": declined");
                }
            } catch (Exception e) {
                log.append(": failed");
                for (Throwable c = e; c != null; c = c.getCause()) {
{'fraction_non_alphanumeric': 0.09137557959814528, 'fraction_numerical': 0.002472952086553323, 'mean_word_length': 2.0400300695358013, 'pattern_counts': {'":': 6, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5399225', 'n_tokens_mistral': 3994, 'n_tokens_neox': 3861, 'n_words': 1252}