package org.apache.archiva.repository.metadata;

/*
 * 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.
 */

import org.apache.archiva.model.ArchivaRepositoryMetadata;
import org.apache.archiva.model.Plugin;
import org.apache.archiva.xml.XMLException;
import org.apache.archiva.xml.XMLWriter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;

/**
 * RepositoryMetadataWriter
 *
 *
 */
public class RepositoryMetadataWriter
{
    public static void write( ArchivaRepositoryMetadata metadata, File outputFile )
        throws RepositoryMetadataException
    {
        boolean thrown = false;
        FileWriter writer = null;
        try
        {
            writer = new FileWriter( outputFile );
            write( metadata, writer );
            writer.flush();
        }
        catch ( IOException e )
        {
            thrown = true;
            throw new RepositoryMetadataException(
                "Unable to write metadata file: " + outputFile.getAbsolutePath() + " - " + e.getMessage(), e );
        }
        finally
        {
            IOUtils.closeQuietly( writer );
            if ( thrown )
            {
                FileUtils.deleteQuietly( outputFile );
            }
        }
    }

    public static void write( ArchivaRepositoryMetadata metadata, Writer writer )
        throws RepositoryMetadataException
    {
        Document doc = DocumentHelper.createDocument();

        Element root = DocumentHelper.createElement( "metadata" );
        doc.setRootElement( root );

        addOptionalElementText( root, "groupId", metadata.getGroupId() );
        addOptionalElementText( root, "artifactId", metadata.getArtifactId() );
        addOptionalElementText( root, "version", metadata.getVersion() );

        if ( CollectionUtils.isNotEmpty( metadata.getPlugins() ) )
        {
            Element plugins = root.addElement( "plugins" );
            for ( Plugin plugin : metadata.getPlugins() )
            {
                Element p = plugins.addElement( "plugin" );
                p.addElement( "prefix" ).setText( plugin.getPrefix() );
                p.addElement( "artifactId" ).setText( plugin.getArtifactId() );
                addOptionalElementText( p, "name", plugin.getName() );
            }
        }

        if ( CollectionUtils.isNotEmpty( metadata.getAvailableVersions() ) || StringUtils.isNotBlank(
            metadata.getReleasedVersion() ) || StringUtils.isNotBlank( metadata.getLatestVersion() )
            || StringUtils.isNotBlank( metadata.getLastUpdated() ) || ( metadata.getSnapshotVersion() != null ) )
        {
            Element versioning = root.addElement( "versioning" );

            addOptionalElementText( versioning, "latest", metadata.getLatestVersion() );
            addOptionalElementText( versioning, "release", metadata.getReleasedVersion() );

            if ( metadata.getSnapshotVersion() != null )
            {
                Element snapshot = versioning.addElement( "snapshot" );
                String bnum = String.valueOf( metadata.getSnapshotVersion().getBuildNumber() );
                addOptionalElementText( snapshot, "buildNumber", bnum );
                addOptionalElementText( snapshot, "timestamp", metadata.getSnapshotVersion().getTimestamp() );
            }

            if ( CollectionUtils.isNotEmpty( metadata.getAvailableVersions() ) )
            {
                Element versions = versioning.addElement( "versions" );
                Iterator<String> it = metadata.getAvailableVersions().iterator();
                while ( it.hasNext() )
                {
                    String version = it.next();
                    versions.addElement( "version" ).setText( version );
                }
            }

            addOptionalElementText( versioning, "lastUpdated", metadata.getLastUpdated() );
        }

        try
        {
            XMLWriter.write( doc, writer );
        }
        catch ( XMLException e )
        {
            throw new RepositoryMetadataException( "Unable to write xml contents to writer: " + e.getMessage(), e );
        }
    }

    private static void addOptionalElementText( Element elem, String elemName, String text )
    {
        if ( StringUtils.isBlank( text ) )
        {
            return;
        }

        elem.addElement( elemName ).setText( text );
    }
}

@@ -1414,24 +1414,106 @@
 va.util.
-Iterator
+Collections;%0Aimport java.util.Comparator;%0Aimport java.util.Iterator;%0Aimport java.util.List
 ;%0A%0A/**%0A 
@@ -1543,14 +1543,8 @@
 ter%0A
- *%0A *%0A
  */%0A
@@ -3024,24 +3024,158 @@
 plugins%22 );%0A
+%0A            List%3CPlugin%3E pluginList = metadata.getPlugins();%0A            Collections.sort( pluginList, PluginComparator.INSTANCE );%0A%0A
             
@@ -3612,24 +3612,39 @@
 Versions() )
+ //%0A           
  %7C%7C StringUt
@@ -3658,28 +3658,16 @@
 otBlank(
-%0A           
  metadat
@@ -3686,24 +3686,39 @@
 dVersion() )
+ //%0A           
  %7C%7C StringUt
@@ -3758,24 +3758,27 @@
 tVersion() )
+ //
 %0A           
@@ -3832,16 +3832,31 @@
 ated() )
+ //%0A           
  %7C%7C ( me
@@ -5583,32 +5583,32 @@
 urn;%0A        %7D%0A%0A
-
         elem.add
@@ -5649,11 +5649,788 @@
 );%0A    %7D
+%0A%0A    private static class PluginComparator%0A        implements Comparator%3CPlugin%3E%0A    %7B%0A        private static final PluginComparator INSTANCE = new PluginComparator();%0A%0A        @Override%0A        public int compare( Plugin plugin, Plugin plugin2 )%0A        %7B%0A            if ( plugin.getPrefix() != null && plugin2.getPrefix() != null )%0A            %7B%0A                return plugin.getPrefix().compareTo( plugin2.getPrefix() );%0A            %7D%0A            if ( plugin.getName() != null && plugin2.getName() != null )%0A            %7B%0A                return plugin.getName().compareTo( plugin2.getName() );%0A            %7D%0A            // we assume artifactId is not null which sounds good :-)%0A            return plugin.getArtifactId().compareTo( plugin2.getArtifactId() );%0A        %7D%0A    %7D
 %0A%7D%0A

fix jdk1.8 build