<commit_before>package org.carlspring.strongbox.rest;

import org.carlspring.maven.commons.util.ArtifactUtils;
import org.carlspring.strongbox.io.MultipleDigestInputStream;
import org.carlspring.strongbox.security.jaas.authentication.AuthenticationException;
import org.carlspring.strongbox.storage.checksum.ChecksumCacheManager;
import org.carlspring.strongbox.storage.resolvers.ArtifactResolutionException;
import org.carlspring.strongbox.storage.resolvers.ArtifactResolutionService;
import org.carlspring.strongbox.util.MessageDigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author <NAME>
 */
@Component
@Path("/storages")
public class ArtifactRestlet
        extends BaseRestlet
{

    private static final Logger logger = LoggerFactory.getLogger(ArtifactRestlet.class);

    @Autowired
    private ChecksumCacheManager checksumCacheManager;


    @PUT
    @Path("{storage}/{repository}/{path:.*}")
    public Response upload(@PathParam("storage") String storage,
                           @PathParam("repository") String repository,
                           @PathParam("path") String path,
                           @Context HttpHeaders headers,
                           @Context HttpServletRequest request,
                           InputStream is)
            throws IOException,
                   AuthenticationException,
                   NoSuchAlgorithmException
    {
        String protocol = request.getRequestURL().toString().split(":")[0];

        handleAuthentication(storage, repository, path, headers, protocol);

        boolean fileIsChecksum = path.endsWith(".md5") || path.endsWith(".sha1");
        MultipleDigestInputStream mdis = new MultipleDigestInputStream(is, new String[]{ "MD5", "SHA-1" });

        // TODO: Do something with the artifact
        // Repository r = getDataCenter().getStorage(storage).getRepository(repository);
        // TODO: If the repository's type is In-Memory, do nothing.
        // TODO: For all other type of repositories, invoke the respective storage provider.

        // TODO: If this is not a checksum file, store the file.
        // TODO: If this is a checksum file, keep the hash in a String.
        ByteArrayOutputStream baos = null;
        if (fileIsChecksum)
        {
            baos = new ByteArrayOutputStream();
        }

        int readLength;
        byte[] bytes = new byte[4096];

        while ((readLength = mdis.read(bytes, 0, bytes.length)) != -1)
        {
            if (fileIsChecksum)
            {
                // Buffer the checksum for later validation
                baos.write(bytes, 0, readLength);
                baos.flush();
            }

            // r.storeArtifact();
            // Write the artifact
        }

        final String artifactPath = storage + "/" + repository + "/" + path;
        if (!fileIsChecksum)
        {
            addChecksumsToCacheManager(mdis, artifactPath);
        }
        else
        {
            validateUploadedChecksumAgainstCache(baos, artifactPath);
        }

        return Response.ok().build();
    }

    private void validateUploadedChecksumAgainstCache(ByteArrayOutputStream baos,
                                                      String artifactPath)
    {
        logger.debug("Received checksum: " + baos.toString());

        String artifactBasePath = artifactPath.substring(0, artifactPath.lastIndexOf("."));
        String algorithm = null;

        final String checksumExtension = artifactPath.substring(artifactPath.lastIndexOf(".") + 1, artifactPath.length());<commit_msg>Sonar check fix: Use Index Of Char.<commit_after>package org.carlspring.strongbox.rest;

import org.carlspring.maven.commons.util.ArtifactUtils;
import org.carlspring.strongbox.io.MultipleDigestInputStream;
import org.carlspring.strongbox.security.jaas.authentication.AuthenticationException;
import org.carlspring.strongbox.storage.checksum.ChecksumCacheManager;
import org.carlspring.strongbox.storage.resolvers.ArtifactResolutionException;
import org.carlspring.strongbox.storage.resolvers.ArtifactResolutionService;
import org.carlspring.strongbox.util.MessageDigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author <NAME>
 */
@Component
@Path("/storages")
public class ArtifactRestlet
        extends BaseRestlet
{

    private static final Logger logger = LoggerFactory.getLogger(ArtifactRestlet.class);

    @Autowired
    private ChecksumCacheManager checksumCacheManager;


    @PUT
    @Path("{storage}/{repository}/{path:.*}")
    public Response upload(@PathParam("storage") String storage,
                           @PathParam("repository") String repository,
                           @PathParam("path") String path,
                           @Context HttpHeaders headers,
                           @Context HttpServletRequest request,
                           InputStream is)
            throws IOException,
                   AuthenticationException,
                   NoSuchAlgorithmException
    {
        String protocol = request.getRequestURL().toString().split(":")[0];

        handleAuthentication(storage, repository, path, headers, protocol);

        boolean fileIsChecksum = path.endsWith(".md5") || path.endsWith(".sha1");
        MultipleDigestInputStream mdis = new MultipleDigestInputStream(is, new String[]{ "MD5", "SHA-1" });

        // TODO: Do something with the artifact
        // Repository r = getDataCenter().getStorage(storage).getRepository(repository);
        // TODO: If the repository's type is In-Memory, do nothing.
        // TODO: For all other type of repositories, invoke the respective storage provider.

        // TODO: If this is not a checksum file, store the file.
        // TODO: If this is a checksum file, keep the hash in a String.
        ByteArrayOutputStream baos = null;
        if (fileIsChecksum)
        {
            baos = new ByteArrayOutputStream();
        }

        int readLength;
        byte[] bytes = new byte[4096];

        while ((readLength = mdis.read(bytes, 0, bytes.length)) != -1)
        {
            if (fileIsChecksum)
            {
                // Buffer the checksum for later validation
                baos.write(bytes, 0, readLength);
                baos.flush();
            }

            // r.storeArtifact();
            // Write the artifact
        }

        final String artifactPath = storage + "/" + repository + "/" + path;
        if (!fileIsChecksum)
        {
            addChecksumsToCacheManager(mdis, artifactPath);
        }
        else
        {
            validateUploadedChecksumAgainstCache(baos, artifactPath);
        }

        return Response.ok().build();
    }

    private void validateUploadedChecksumAgainstCache(ByteArrayOutputStream baos,
                                                      String artifactPath)
    {
        logger.debug("Received checksum: " + baos.toString());

        String artifactBasePath = artifactPath.substring(0, artifactPath.lastIndexOf('.'));
        String algorithm = null;

        final String checksumExtension = artifactPath.substring(artifactPath.lastIndexOf('.') + 1, artifactPath.length());
{'fraction_non_alphanumeric': 0.09874415168677665, 'fraction_numerical': 0.003939916276779119, 'mean_word_length': 2.603815439219166, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5835453', 'n_tokens_mistral': 2156, 'n_tokens_neox': 2089, 'n_words': 475}