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

org.cyclopsgroup.cym2.flatsite.XmlTool Maven / Gradle / Ivy

package org.cyclopsgroup.cym2.flatsite;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.plexus.util.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

/**
 * A utility for XML manipulation using Dom4j internally
 *
 * @author Jiaqi Guo
 */
public class XmlTool
{
    public static final String TOOL_NAME = "xmltool";

    private final File resourceRoot;

    XmlTool( File resourceRoot )
    {
        this.resourceRoot = resourceRoot;
    }

    private SAXReader saxReader = new SAXReader();

    /**
     * Split big list into list of small site-limited lists
     *
     * @param  Type of element
     * @param list Input big list
     * @param groupSize Size of small list(group)
     * @return List of groups
     */
    public  List> groupBy( List list, int groupSize )
    {
        List> groups =
            new ArrayList>( list.size() / groupSize + 1 );
        for ( int index = 0; index < list.size(); index++ )
        {
            List group;
            if ( index % groupSize == 0 )
            {
                group = new ArrayList( groupSize );
                groups.add( group );
            }
            else
            {
                group = groups.get( index / groupSize );
            }
            group.add( list.get( index ) );
        }

        return groups;
    }

    /**
     * Parse a File into Dom4j Document
     *
     * @param filePath Path of file
     * @return Dom4j document object
     * @throws DocumentException
     */
    public Document parseFile( String filePath )
        throws DocumentException
    {
        File file = new File( resourceRoot, filePath );
        if ( !file.exists() )
        {
            return null;
        }
        return saxReader.read( file );
    }

    /**
     * Parse a URL into Dom4j Document
     *
     * @param urlString URL of resource
     * @return Dom4j document
     * @throws DocumentException
     * @throws MalformedURLException
     */
    public Document parseUrl( String urlString )
        throws DocumentException, MalformedURLException
    {
        if ( StringUtils.isBlank( urlString ) )
        {
            return null;
        }
        return saxReader.read( new URL( urlString ) );
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy