<commit_before>/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.spine3.server.storage.jdbc.entity;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.FieldMask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spine3.server.entity.EntityRecord;
import org.spine3.server.storage.RecordStorage;
import org.spine3.server.storage.jdbc.DatabaseException;
import org.spine3.server.storage.jdbc.JdbcStorageFactory;
import org.spine3.server.storage.jdbc.builder.StorageBuilder;
import org.spine3.server.storage.jdbc.entity.query.RecordStorageQueryFactory;
import org.spine3.server.storage.jdbc.entity.query.SelectBulkQuery;
import org.spine3.server.storage.jdbc.query.DeleteRecordQuery;
import org.spine3.server.storage.jdbc.util.DataSourceWrapper;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * The implementation of the entity storage based on the RDBMS.
 *
 * @param <I> the type of entity IDs
 * @author <NAME>
 * @see JdbcStorageFactory
 */
public class JdbcRecordStorage<I> extends RecordStorage<I> {

    private final DataSourceWrapper dataSource;

    private final RecordStorageQueryFactory<I> queryFactory;

    protected JdbcRecordStorage(DataSourceWrapper dataSource, boolean multitenant,
                                RecordStorageQueryFactory<I> queryFactory)
            throws DatabaseException {
        super(multitenant);
        this.dataSource = dataSource;
        this.queryFactory = queryFactory;
        queryFactory.setLogger(LogSingleton.INSTANCE.value);
        queryFactory.newCreateEntityTableQuery()
                    .execute();
    }

    private JdbcRecordStorage(Builder<I> builder) {
        this(builder.getDataSource(), builder.isMultitenant(), builder.getQueryFactory());
    }

    @SuppressWarnings("ProhibitedExceptionThrown") // NPE by the contract
    @Override
    public void markArchived(I id) {
        checkNotNull(id);
        final boolean recordExists = queryFactory.newMarkArchivedQuery(id)
                                                 .execute();
        if (!recordExists) {
            // The NPE is required by the contract of the method
            final String errorMessage =
                    String.format("Trying to mark not existing record with id %s archived.", id);
            throw new NullPointerException(errorMessage); // NOPMD
        }
    }

    @SuppressWarnings("ProhibitedExceptionThrown") // NPE by the contract
    @Override
    public void markDeleted(I id) {
        checkNotNull(id);
        final boolean recordExists = queryFactory.newMarkDeletedQuery(id)
                                                 .execute();
        if (!recordExists) {
            // The NPE is required by the contract of the method
            final String errorMessage =
                    String.format("Trying to mark not existing record with id %s deleted.", id);
            throw new NullPointerException(errorMessage); // NOPMD
        }
    }

    @Override
    public boolean delete(I id) {
        checkNotNull(id);

        final DeleteRecordQuery<I> query = queryFactory.newDeleteRowQuery(id);
        final boolean result = query.execute();
        return result;
    }

    /**
     * {@inheritDoc}
     *<commit_msg>Remove custom PMD suppressions.<commit_after>/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.spine3.server.storage.jdbc.entity;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.FieldMask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spine3.server.entity.EntityRecord;
import org.spine3.server.storage.RecordStorage;
import org.spine3.server.storage.jdbc.DatabaseException;
import org.spine3.server.storage.jdbc.JdbcStorageFactory;
import org.spine3.server.storage.jdbc.builder.StorageBuilder;
import org.spine3.server.storage.jdbc.entity.query.RecordStorageQueryFactory;
import org.spine3.server.storage.jdbc.entity.query.SelectBulkQuery;
import org.spine3.server.storage.jdbc.query.DeleteRecordQuery;
import org.spine3.server.storage.jdbc.util.DataSourceWrapper;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * The implementation of the entity storage based on the RDBMS.
 *
 * @param <I> the type of entity IDs
 * @author <NAME>
 * @see JdbcStorageFactory
 */
public class JdbcRecordStorage<I> extends RecordStorage<I> {

    private final DataSourceWrapper dataSource;

    private final RecordStorageQueryFactory<I> queryFactory;

    protected JdbcRecordStorage(DataSourceWrapper dataSource, boolean multitenant,
                                RecordStorageQueryFactory<I> queryFactory)
            throws DatabaseException {
        super(multitenant);
        this.dataSource = dataSource;
        this.queryFactory = queryFactory;
        queryFactory.setLogger(LogSingleton.INSTANCE.value);
        queryFactory.newCreateEntityTableQuery()
                    .execute();
    }

    private JdbcRecordStorage(Builder<I> builder) {
        this(builder.getDataSource(), builder.isMultitenant(), builder.getQueryFactory());
    }

    @SuppressWarnings("ProhibitedExceptionThrown") // NPE by the contract
    @Override
    public void markArchived(I id) {
        checkNotNull(id);
        final boolean recordExists = queryFactory.newMarkArchivedQuery(id)
                                                 .execute();
        if (!recordExists) {
            // The NPE is required by the contract of the method
            final String errorMessage =
                    String.format("Trying to mark not existing record with id %s archived.", id);
            throw new NullPointerException(errorMessage);
        }
    }

    @SuppressWarnings("ProhibitedExceptionThrown") // NPE by the contract
    @Override
    public void markDeleted(I id) {
        checkNotNull(id);
        final boolean recordExists = queryFactory.newMarkDeletedQuery(id)
                                                 .execute();
        if (!recordExists) {
            // The NPE is required by the contract of the method
            final String errorMessage =
                    String.format("Trying to mark not existing record with id %s deleted.", id);
            throw new NullPointerException(errorMessage);
        }
    }

    @Override
    public boolean delete(I id) {
        checkNotNull(id);

        final DeleteRecordQuery<I> query = queryFactory.newDeleteRowQuery(id);
        final boolean result = query.execute();
        return result;
    }

    /**
     * {@inheritDoc}
     *
{'fraction_non_alphanumeric': 0.08101851851851852, 'fraction_numerical': 0.003527336860670194, 'mean_word_length': 3.1676619200734955, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7324242', 'n_tokens_mistral': 2440, 'n_tokens_neox': 2309, 'n_words': 717}