All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.zeroinstall.publish.FeedUtils Maven / Gradle / Ivy

The newest version!
package net.zeroinstall.publish;

import static com.google.common.io.BaseEncoding.base64;
import java.io.*;
import java.util.Scanner;
import net.zeroinstall.model.InterfaceDocument;
import org.apache.xmlbeans.*;

/**
 * Utility class for performing operations on feed files.
 */
public final class FeedUtils {

    private FeedUtils() {
    }

    /**
     * Serializes a feed to an XML string with a stylesheet declaration and an
     * optional GnuPG signature.
     *
     * @param feed     Thee feed to be serialized.
     * @param gnuPGKey The name of the GnuPG key to use for
     *                 signing. null for no signature.
     * @return The generated XML string.
     * @throws IOException A problem occurred while calling the GnuPG executable.
     */
    public static String getFeedString(InterfaceDocument feed, String gnuPGKey) throws IOException {
        addStylesheet(feed);
        String xmlText = toXmlText(feed);
        return (gnuPGKey == null) ? xmlText : appendSignature(xmlText, gnuPGKey);
    }

    /**
     * Reads the entire content of a stream to a string.
     *
     * @param stream The stream to read.
     * @return The string read from the stream or null if the stream was empty.
     */
    public static String readAll(InputStream stream) {
        Scanner scanner = new Scanner(stream).useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : null;
    }

    static void addStylesheet(InterfaceDocument feed) {
        XmlCursor cursor = feed.newCursor();
        cursor.toNextToken();
        cursor.insertProcInst("xml-stylesheet", "type='text/xsl' href='feed.xsl'");
    }

    static String toXmlText(InterfaceDocument feed) {
        return "\n"
                + feed.xmlText(new XmlOptions().setUseDefaultNamespace().setSavePrettyPrint());
    }

    static String appendSignature(String xmlText, String gnuPGKey) throws IOException {
        xmlText += "\n";

        String signature = base64().encode(GnuPG.detachSign(xmlText, gnuPGKey));
        return xmlText + "\n";
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy