br.com.objectos.blog.PostTemplateLoaderGuice.java Source code

Java tutorial

Introduction

Here is the source code for br.com.objectos.blog.PostTemplateLoaderGuice.java

Source

/*
 * Copyright 2011 Objectos, Fbrica de Software LTDA.
 *
 * Licensed 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.
 */
package br.com.objectos.blog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;

/**
 * @author marcio.endo@objectos.com.br (Marcio Endo)
 */
class PostTemplateLoaderGuice implements PostTemplateLoader {

    @Override
    public PostTemplate load(String template) {
        return new TemplateBuilder(template).get();
    }

    @Override
    public PostTemplate loadFromFile(File template) throws BlogException {
        try {

            BufferedReader reader = Files.newReader(template, Charsets.UTF_8);
            String _template = CharStreams.toString(reader);
            return load(_template);

        } catch (FileNotFoundException e) {
            throw Throwables.propagate(e);

        } catch (IOException e) {
            throw new PostTemplateException(e);

        }
    }

    private class TemplateBuilder implements PostTemplate.Builder {

        private final Document doc;

        private TemplateBuilder(String template) {
            this.doc = Jsoup.parse(template);
        }

        @Override
        public PostTemplate get() {
            return new PostTemplateImpl(this);
        }

        @Override
        public Document getDoc() {
            return doc;
        }

        @Override
        public Multimap<PostTag, Element> getTags() {
            Multimap<PostTag, Element> tags = ArrayListMultimap.create();

            for (PostTag tag : PostTag.values()) {
                Elements elements = tag.selectFrom(doc);
                for (Element el : elements) {
                    if (el != null) {
                        tags.put(tag, el);
                    }
                }
            }

            return tags;
        }

    }

}