package org.jboss.windup.rules.apps.java.archives.identify;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang.StringUtils;
import org.jboss.forge.addon.dependencies.Coordinate;
import org.jboss.forge.addon.dependencies.builder.CoordinateBuilder;
import org.jboss.windup.util.exception.WindupException;

/**
 * In-memory implementation of {@link ChecksumIdentifier}.
 *
 * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
 * @author Ondrej Zizka, ozizka at redhat.com
 */
public class InMemoryChecksumIdentifier implements ChecksumIdentifier
{
    private final Map<String, String> map = new TreeMap<>();

    @Override
    public Coordinate getCoordinate(String checksum)
    {
        if (checksum == null)
            return null;

        String coordinate = map.get(checksum);

        if (coordinate == null)
            return null;

        return CoordinateBuilder.create(coordinate);
    }

    public void addMapping(String checksum, String coordinate)
    {
        map.put(checksum, coordinate);
    }

    public void addMappingsFrom(File file)
    {
        try (FileInputStream inputStream = new FileInputStream(file))
        {
            LineIterator it = IOUtils.lineIterator(inputStream, "UTF-8");
            while (it.hasNext())
            {
                String line = it.next();
                if (line.startsWith("#") || line.trim().isEmpty())
                    continue;
                String[] parts = StringUtils.split(line, ' ');
                if (parts.length < 2)
                    throw new IllegalArgumentException("Expected 'SHA1 GROUP_ID:ARTIFACT_ID:[PACKAGING:[COORDINATE:]]VERSION', but was: \n" + line
                                + "\n\tin [" + file + "]");

                addMapping(parts[0], parts[1]);
            }
        }
        catch (IOException e)
        {
            throw new WindupException("Failed to load SHA1 to " + Coordinate.class.getSimpleName() + " definitions from [" + file + "]", e);
        }
    }

}
@@ -1381,16 +1381,22 @@
 rator it
+erator
  = IOUti
@@ -1434,16 +1434,48 @@
 TF-8%22);%0A
+            int lineNumber = 0;%0A
         
@@ -1487,16 +1487,22 @@
 hile (it
+erator
 .hasNext
@@ -1511,32 +1511,62 @@
 )%0A            %7B%0A
+                lineNumber++;%0A
                 
@@ -1581,16 +1581,22 @@
 ine = it
+erator
 .next();
@@ -1930,18 +1930,17 @@
 ut was: 
-%5Cn
+%5B
 %22 + line
@@ -1979,24 +1979,51 @@
  + %22
-%5Cn%5Ct
+%5D in %5B%22 + file + %22%5D at l
 in
+e
  %5B%22 + 
-file
+lineNumber
  + %22

Remove multiline exception