FreeMarker代码分析第三篇

2021SC@SDUSC

jython包

JythonVersionAdapter.java

代码分析

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 freemarker.ext.jython;

import org.python.core.PyObject;

/**
 * Functions that has a different implementation depending on the Jython version
 * used. This was introduced to work around class-loading errors because of
 * different classes/methods being present in different Jython versions.
 */
public abstract class JythonVersionAdapter {

    /*
    判断是否为PyInstance
     */
    public abstract boolean isPyInstance(Object obj);
    
    /*
    返回pyInstance转化的java对象
     */
    public abstract Object pyInstanceToJava(Object pyInstance);
    
    /*
    获得相应的Python类的名称
     */
    public abstract String getPythonClassName(PyObject pyObject);
}

JythonVersionAdapterHolder.java

代码分析

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 freemarker.ext.jython;

import org.python.core.PySystemState;

import freemarker.template.utility.StringUtil;

/**
 * Holds the {@link JythonVersionAdapter} so that it's only initialized when this class is accessed.
 * This utilizes that the JVM is required to initialize the fields of a class not earlier than the class is
 * first accessed. Furthermore, it utilizes that the JVM guarantees that the objects created as part of the class
 * initialization will be visible with their after-initialization state for the threads that access it. 
 */
class JythonVersionAdapterHolder {
    
    final static JythonVersionAdapter INSTANCE;
    static {
        // Note: Only the textual version number is available in Jython 2.0. 
        int version;
        try {
            // Although PySystemState.version is present in all versions,
            // its type changes, so we must use reflection to get it.
            version = StringUtil.versionStringToInt(
                    PySystemState.class.getField("version").get(null).toString());
        } catch (Exception e) {
            throw new RuntimeException("Failed to get Jython version: " + e);
        }
        ClassLoader cl = JythonVersionAdapter.class.getClassLoader();
        try {
            if (version >= 2005000) {
                INSTANCE = (JythonVersionAdapter) cl.loadClass(
                        "freemarker.ext.jython._Jython25VersionAdapter")
                    .newInstance();
            } else if (version >= 2002000) {
                INSTANCE = (JythonVersionAdapter) cl.loadClass(
                        "freemarker.ext.jython._Jython22VersionAdapter")
                    .newInstance();
            } else {
                INSTANCE = (JythonVersionAdapter) cl.loadClass(
                        "freemarker.ext.jython._Jython20And21VersionAdapter")
                    .newInstance();
            }
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            throw adapterCreationException(e);
        }
    }

    private static RuntimeException adapterCreationException(Exception e) {
        return new RuntimeException("Unexpected exception when creating JythonVersionAdapter", e);
    }

}

JythonWrapper.java

代码分析

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 freemarker.ext.jython;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.python.core.Py;
import org.python.core.PyDictionary;
import org.python.core.PyFloat;
import org.python.core.PyInteger;
import org.python.core.PyLong;
import org.python.core.PyObject;
import org.python.core.PySequence;
import org.python.core.PyString;
import org.python.core.PyStringMap;

import freemarker.ext.util.ModelCache;
import freemarker.ext.util.WrapperTemplateModel;
import freemarker.template.AdapterTemplateModel;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateHashModelEx;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelAdapter;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;
import freemarker.template.TemplateScalarModel;
import freemarker.template.TemplateSequenceModel;
import freemarker.template.utility.OptimizerUtil;

/**
 * An object wrapper that wraps Jython objects into FreeMarker template models
 * and vice versa.
 */
public class JythonWrapper implements ObjectWrapper {
    private static final Class PYOBJECT_CLASS = PyObject.class;
    public static final JythonWrapper INSTANCE = new JythonWrapper();

    private final ModelCache modelCache = new JythonModelCache(this);

    private boolean attributesShadowItems = true;

    public JythonWrapper() {
    }
    
    /**
     * Sets whether this wrapper caches model instances. Default is false.
     * When set to true, calling {@link #wrap(Object)} multiple times for
     * the same object will return the same model.
     */
    public void setUseCache(boolean useCache) {
        modelCache.setUseCache(useCache);
    }
    
    /**
     * Sets whether attributes shadow items in wrapped objects. When true 
     * (this is the default value), <code>${object.name}</code> will first 
     * try to locate a python attribute with the specified name on the object
     * using {@link PyObject#__findattr__(java.lang.String)}, and only if it 
     * doesn't find the attribute will it call 
     * {@link PyObject#__getitem__(org.python.core.PyObject)}.
     * When set to false, the lookup order is reversed and items
     * are looked up before attributes.
     */
    public synchronized void setAttributesShadowItems(boolean attributesShadowItems) {
        this.attributesShadowItems = attributesShadowItems;
    }
    
    boolean isAttributesShadowItems() {
        return attributesShadowItems;
    }
    
    /**
     * Wraps the passed Jython object into a FreeMarker template model. If
     * the object is not a Jython object, it's first coerced into one using
     * {@link Py#java2py(java.lang.Object)}. {@link PyDictionary} and {@link
     * PyStringMap} are wrapped into a hash model, {@link PySequence}
     * descendants are wrapped into a sequence model, {@link PyInteger}, {@link
     * PyLong}, and {@link PyFloat} are wrapped into a number model. All objects
     * are wrapped into a scalar model (using {@link Object#toString()} and a
     * boolean model (using {@link PyObject#__nonzero__()}. For internal
     * general-purpose {@link PyObject}s returned from a call to {@link
     * #unwrap(TemplateModel)}, the template model that was passed to
     * <code>unwrap</code> is returned.
     */
    @Override
    public TemplateModel wrap(Object obj) {
        if (obj == null) {
            return null;
        }
        return modelCache.getInstance(obj);
    }
    
    /**
     * Coerces a template model into a {@link PyObject}.
     * @param model the model to coerce
     * @return the coerced model.
     * <ul>
     * <li>
     * <li>{@link AdapterTemplateModel}s (i.e. {@link freemarker.ext.beans.BeanModel}) are marshalled
     *   using the standard Python marshaller {@link Py#java2py(Object)} on 
     *   the result of <code>getWrappedObject(PyObject.class)</code>s. The 
     *   native JythonModel instances will just return the underlying PyObject. 
     * <li>All other models that are {@link TemplateScalarModel scalars} are 
     *   marshalled as {@link PyString}.
     * <li>All other models that are {@link TemplateNumberModel numbers} are 
     *   marshalled using the standard Python marshaller
     *   {@link Py#java2py(Object)} on their underlying <code>Number</code></li>
     * <li>All other models  are marshalled to a generic internal 
     *   <code>PyObject</code> subclass that'll correctly pass
     *   <code>__finditem__</code>, <code>__len__</code>,
     *   <code>__nonzero__</code>, and <code>__call__</code> invocations to 
     *   appropriate hash, sequence, and method models.</li>
     * </ul>
     */
    public PyObject unwrap(TemplateModel model) throws TemplateModelException {
        if (model instanceof AdapterTemplateModel) {
            return Py.java2py(((AdapterTemplateModel) model).getAdaptedObject(
                    PYOBJECT_CLASS));
        }
        if (model instanceof WrapperTemplateModel) {
            return Py.java2py(((WrapperTemplateModel) model).getWrappedObject());
        }

        // Scalars are marshalled to PyString.
        if (model instanceof TemplateScalarModel) {
            return new PyString(((TemplateScalarModel) model).getAsString());
        }
        
        // Numbers are wrapped to Python built-in numeric types.
        if (model instanceof TemplateNumberModel) {
            Number number = ((TemplateNumberModel) model).getAsNumber();
            if (number instanceof BigDecimal) {
                number = OptimizerUtil.optimizeNumberRepresentation(number);
            }
            if (number instanceof BigInteger) {
                // Py.java2py can't automatically coerce a BigInteger into
                // a PyLong. This will probably get fixed in later Jython
                // release.
                return new PyLong((BigInteger) number);
            } else {
                return Py.java2py(number);
            }
        }
        // Return generic TemplateModel-to-Python adapter
        return new TemplateModelToJythonAdapter(model);
    }

    private class TemplateModelToJythonAdapter extends PyObject 
    implements TemplateModelAdapter {
        private final TemplateModel model;
        
        TemplateModelToJythonAdapter(TemplateModel model) {
            this.model = model;
        }
        
        @Override
        public TemplateModel getTemplateModel() {
            return model;
        }
        
        @Override
        public PyObject __finditem__(PyObject key) {
            if (key instanceof PyInteger) {
                return __finditem__(((PyInteger) key).getValue());
            }
            return __finditem__(key.toString());
        }

        @Override
        public PyObject __finditem__(String key) {
            if (model instanceof TemplateHashModel) {
                try {
                    return unwrap(((TemplateHashModel) model).get(key));
                } catch (TemplateModelException e) {
                    throw Py.JavaError(e);
                }
            }
            throw Py.TypeError("item lookup on non-hash model (" + getModelClass() + ")");
        }
        
        @Override
        public PyObject __finditem__(int index) {
            if (model instanceof TemplateSequenceModel) {
                try {
                    return unwrap(((TemplateSequenceModel) model).get(index));
                } catch (TemplateModelException e) {
                    throw Py.JavaError(e);
                }
            }
            throw Py.TypeError("item lookup on non-sequence model (" + getModelClass() + ")");
        }
        
        @Override
        public PyObject __call__(PyObject args[], String keywords[]) {
            if (model instanceof TemplateMethodModel) {
                boolean isEx = model instanceof TemplateMethodModelEx;
                List list = new ArrayList(args.length);
                try {
                    for (int i = 0; i < args.length; ++i) {
                        list.add(
                            isEx 
                            ? wrap(args[i])
                            : args[i] == null
                            ? null
                            : args[i].toString());
                    }
                    return unwrap((TemplateModel) ((TemplateMethodModelEx) model).exec(list));
                } catch (TemplateModelException e) {
                    throw Py.JavaError(e);
                }
            }
            throw Py.TypeError("call of non-method model (" + getModelClass() + ")");
        }
        
        @Override
        public int __len__() {
            try {
                if (model instanceof TemplateSequenceModel) {
                    return ((TemplateSequenceModel) model).size();
                }
                if (model instanceof TemplateHashModelEx) {
                    return ((TemplateHashModelEx) model).size();
                }
            } catch (TemplateModelException e) {
                throw Py.JavaError(e);
            }
            
            return 0;
        }
        
        @Override
        public boolean __nonzero__() {
            try {
                if (model instanceof TemplateBooleanModel) {
                    return ((TemplateBooleanModel) model).getAsBoolean();
                }
                if (model instanceof TemplateSequenceModel) {
                    return ((TemplateSequenceModel) model).size() > 0;
                }
                if (model instanceof TemplateHashModel) {
                    return !((TemplateHashModelEx) model).isEmpty();
                }
            } catch (TemplateModelException e) {
                throw Py.JavaError(e);
            }
            return false;
        }
        
        private String getModelClass() {
            return model == null ? "null" : model.getClass().getName();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值