fr.mael.microrss.util.js.MicroRSSGlobalFunctions.java Source code

Java tutorial

Introduction

Here is the source code for fr.mael.microrss.util.js.MicroRSSGlobalFunctions.java

Source

/*
   Copyright  2013 Mael Le Guvel
   This work is free. You can redistribute it and/or modify it under the
   terms of the Do What The Fuck You Want To Public License, Version 2,
   as published by Sam Hocevar. See the COPYING file for more details.
*/
package fr.mael.microrss.util.js;

import org.apache.commons.beanutils.PropertyUtils;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.mael.microrss.domain.Article;

public class MicroRSSGlobalFunctions {

    private static Logger LOG = LoggerFactory.getLogger(MicroRSSGlobalFunctions.class);

    public static boolean titleContains(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
        return matches(thisObj, args, "title", true);
    }

    public static boolean titleMatches(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
        return matches(thisObj, args, "title", false);
    }

    public static boolean contentContains(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
        return matches(thisObj, args, "content", true);
    }

    public static boolean contentMatches(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
        return matches(thisObj, args, "content", false);
    }

    public static boolean authorIs(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
        return matches(thisObj, args, "author", false);
    }

    private static boolean matches(Scriptable thisObj, Object[] args, String name, boolean contains) {
        Article article = getArticle(thisObj);
        if (article == null || args == null || args.length < 1) {
            return false;
        }
        Object val;
        try {
            val = PropertyUtils.getProperty(article, name);
            if (val == null) {
                return false;
            }
            String comparison = args[0].toString();
            if (contains) {
                comparison = ".*" + comparison + ".*";
            }
            return val.toString().matches(comparison);
        } catch (Exception e) {
            LOG.error("Error getting property " + name, e);
            return false;
        }

    }

    private static Article getArticle(Scriptable thisObj) {
        Object object = thisObj.get("article", thisObj);
        if (object instanceof RestrictedNativeJavaObject) {
            RestrictedNativeJavaObject nativeObject = (RestrictedNativeJavaObject) object;
            Article article = nativeObject.getObject();
            return article;
        }
        return null;
    }
}