TransfertListener.java

package org.docascode.api.listener;

import org.docascode.api.event.Event;
import org.eclipse.aether.transfer.AbstractTransferListener;
import org.eclipse.aether.transfer.TransferCancelledException;
import org.eclipse.aether.transfer.TransferEvent;
import org.eclipse.aether.transfer.TransferResource;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class TransfertListener extends AbstractTransferListener implements EventListener {
    @Override
    public void transferInitiated( TransferEvent event )
            throws TransferCancelledException
    {
        String msg = event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading";
        msg += " " + event.getResource().getRepositoryUrl() + event.getResource().getResourceName();
        Event e = new Event(this);
        e.setMessage(msg);
        fireEvent(e);
    }

    @Override
    public void transferCorrupted( TransferEvent event )
            throws TransferCancelledException
    {
        TransferResource resource = event.getResource();

        String msg = event.getException().getMessage() + " for " + resource.getRepositoryUrl()
                + resource.getResourceName();
        Event e = new Event(this);
        e.setMessage(msg);
        fireEvent(e);
    }

    @Override
    public void transferSucceeded( TransferEvent event )
    {
        String msg = event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded";
        msg += " " + event.getResource().getRepositoryUrl() + event.getResource().getResourceName();

        long contentLength = event.getTransferredBytes();
        if ( contentLength >= 0 )
        {
            String len = contentLength >= 1024 ? ( ( contentLength + 1023 ) / 1024 ) + " KB" : contentLength + " B";

            String throughput = "";
            long duration = System.currentTimeMillis() - event.getResource().getTransferStartTime();
            if ( duration > 0 )
            {
                DecimalFormat format = new DecimalFormat( "0.0", new DecimalFormatSymbols( Locale.ENGLISH ) );
                double kbPerSec = ( contentLength / 1024.0 ) / ( duration / 1000.0 );
                throughput = " at " + format.format( kbPerSec ) + " KB/sec";
            }

            msg += " (" + len + throughput + ")";
        }
        Event e = new Event(this);
        e.setMessage(msg);
        fireEvent(e);
    }

    private List<EventListener> listeners = new ArrayList<>();

    public TransfertListener addListener(EventListener listener){
        this.listeners.add(listener);
        return this;
    }

    @Override
    public void fireEvent(Event e){
        for (EventListener l : this.listeners){
            l.fireEvent(e);
        }
    }
}