uk.co.sdev.undertow.rx.services.news.NewsItemDigestible.java Source code

Java tutorial

Introduction

Here is the source code for uk.co.sdev.undertow.rx.services.news.NewsItemDigestible.java

Source

/**
 * Copyright 2014 Andy Godwin
 *
 * 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 uk.co.sdev.undertow.rx.services.news;

import org.apache.commons.lang3.StringEscapeUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NewsItemDigestible {

    private String headline;

    private String description;

    private String link;

    private List<Image> images = new ArrayList<>();

    public void setHeadline(String headline) {
        this.headline = headline;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public void addImage(Image image) {
        images.add(image);
    }

    public boolean hasImage() {
        return !images.isEmpty();
    }

    public NewsItem toNewsItem() {
        NewsItem item = new NewsItem();
        item.setHeadline(this.headline);
        item.setStandFirst(getStandFirst());
        item.setLink(this.link);
        if (!images.isEmpty()) {
            item.setImage(getLargestImage().getUrl());
        }
        return item;
    }

    private Image getLargestImage() {
        if (images.size() == 1) {
            return images.get(0);
        }
        Collections.sort(images);
        return images.get(0);
    }

    private String getStandFirst() {
        String unescaped = StringEscapeUtils.unescapeHtml4(description);
        if (unescaped.startsWith("<p>")) {
            unescaped = unescaped.substring(3, unescaped.indexOf('<', 3));
        } else {
            unescaped = unescaped.substring(0, unescaped.indexOf('<'));
        }
        return stripWhitespace(unescaped).trim();
    }

    private String stripWhitespace(String s) {
        return s.replaceAll("\\s+", " ");
    }
}