Project

General

Profile

« Previous | Next » 

Revision 045a007b

Added by Andreas Kohlbecker almost 12 years ago

xsl stylesheets for rest service api endpoints

View differences:

cdmlib-print/src/main/java/eu/etaxonomy/cdm/print/LocalXMLEntityFactory.java
437 437

  
438 438
			PrintWriter writer = new PrintWriter(tmpFile, "UTF-8");
439 439

  
440
			xmlView.render(HibernateProxyHelper.deproxy(result), writer);
440
			xmlView.render(HibernateProxyHelper.deproxy(result), writer, null);
441 441

  
442 442
			document = builder.build(tmpFile);
443 443

  
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/config/AbstractWebApplicationConfigurer.java
1 1
// $Id$
2 2
/**
3 3
 * Copyright (C) 2009 EDIT
4
 * European Distributed Institute of Taxonomy 
4
 * European Distributed Institute of Taxonomy
5 5
 * http://www.e-taxonomy.eu
6
 * 
6
 *
7 7
 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 8
 * See LICENSE.TXT at the top of this package for the full license terms.
9 9
 */
......
26 26

  
27 27
    private static final String ATTRIBUTE_ERROR_MESSAGES = "cdm.errorMessages";
28 28

  
29
	public static final Logger logger = Logger.getLogger(AbstractWebApplicationConfigurer.class);
30
	
31
	WebApplicationContext webApplicationContext;
29
    public static final Logger logger = Logger.getLogger(AbstractWebApplicationConfigurer.class);
30

  
31
    WebApplicationContext webApplicationContext;
32

  
33

  
34
    @Autowired
35
    public void setApplicationContext(ApplicationContext applicationContext){
36

  
37
        if(WebApplicationContext.class.isAssignableFrom(applicationContext.getClass())) {
38
            this.webApplicationContext = (WebApplicationContext)applicationContext;
39
        } else {
40
            logger.error("The " + this.getClass().getSimpleName() + " only can be used within a WebApplicationContext");
41
        }
42
    }
32 43

  
33
	
34
	@Autowired
35
	public void setApplicationContext(ApplicationContext applicationContext){
44
    /**
45
     * Find a property primarily in the ServletContext and secondarily
46
     * in the environment variables of the OS. So a property can be set
47
     * by two means:
48
     * <ol>
49
     * <li>As attribute to the ServletContext (the cdm-server makes use of this method)</li>
50
     * <li>as system property e.g. by setting the jvm commandline option like for example
51
     * <code>-Dcdm.rootpathprefix=my/cdm/remote-instance<code></li>
52
     * </ol>
53
     *
54
     * @param property usually a string constant defined in a subclass of
55
     * 		<code>AbstractWebApplicationConfigurer</code> names <code>ATTRIBUTE_*</code>
56
     * @param required
57
     * @return
58
     */
59
    protected String findProperty(String property, boolean required) {
60
        // 1. look for the property in the ServletContext
61
        Object obj = webApplicationContext.getServletContext().getAttribute(property);
62
        String value = (String)obj;
63
        // 2. look for the property in environment variables of the OS
64
        if(value == null){
65
            value = System.getProperty(property);
66
        }
67
        if(value == null && required){
68
            logger.error("property {" + property + "} not found.");
69
            logger.error("--> This property can be set in two ways:");
70
            logger.error("--> 		1. as attribute to the ServletContext");
71
            logger.error("--> 		2. as system property e.g. -D" + property);
72
            logger.error("Stopping application ...");
73
            System.exit(-1);
74
        }
75
        return value;
76
    }
36 77

  
37
		if(WebApplicationContext.class.isAssignableFrom(applicationContext.getClass())) {
38
			this.webApplicationContext = (WebApplicationContext)applicationContext;
39
		} else {
40
			logger.error("The " + this.getClass().getSimpleName() + " only can be used within a WebApplicationContext");
41
		}
42
	}
78
    protected void addErrorMessageToServletContextAttributes(String errorMessage) {
79
        Object o = webApplicationContext.getServletContext().getAttribute(ATTRIBUTE_ERROR_MESSAGES);
80
        List<String> messages;
81
        if(o != null  && o instanceof List<?>){
82
            messages = (List<String>) o;
83
        } else {
84
            messages = new ArrayList<String>();
85
        }
86
        messages.add(errorMessage);
87
        webApplicationContext.getServletContext().setAttribute(ATTRIBUTE_ERROR_MESSAGES, messages);
88
    }
43 89

  
44
	/**
45
	 * Find a property in the ServletContext if not found search in a second
46
	 * step in the environment variables of the OS
47
	 * 
48
	 * @param property
49
	 * @param required
50
	 * @return
51
	 */
52
	protected String findProperty(String property, boolean required) {
53
		// 1. look for the property in the ServletContext
54
		Object obj = webApplicationContext.getServletContext().getAttribute(property);
55
		String value = (String)obj;
56
		// 2. look for the property in environment variables of the OS
57
		if(value == null){
58
			value = System.getProperty(property);
59
		}
60
		if(value == null && required){
61
			logger.error("property {" + property + "} not found.");
62
			logger.error("--> This property can be set in two ways:");
63
			logger.error("--> 		1. as attribute to the ServletContext");
64
			logger.error("--> 		2. as system property e.g. -D" + property);
65
			logger.error("Stopping application ...");
66
			System.exit(-1);
67
		}
68
		return value;
69
	}
70 90

  
71
	protected void addErrorMessageToServletContextAttributes(String errorMessage) {
72
		Object o = webApplicationContext.getServletContext().getAttribute(ATTRIBUTE_ERROR_MESSAGES);
73
		List<String> messages;
74
		if(o != null  && o instanceof List<?>){
75
			messages = (List<String>) o;
76
		} else {
77
			messages = new ArrayList<String>();
78
		}
79
		messages.add(errorMessage);
80
		webApplicationContext.getServletContext().setAttribute(ATTRIBUTE_ERROR_MESSAGES, messages);
81
	}
82
	
83
   
84 91

  
85 92
}
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/config/DataSourceConfigurer.java
71 71

  
72 72
    public static final Logger logger = Logger.getLogger(DataSourceConfigurer.class);
73 73

  
74
    private static final String ATTRIBUTE_JDBC_JNDI_NAME = "cdm.jdbcJndiName";
75
    private static final String HIBERNATE_DIALECT = "hibernate.dialect";
76
    private static final String HIBERNATE_SEARCH_DEFAULT_INDEX_BASE = "hibernate.search.default.indexBase";
77
    private static final String CDM_BEAN_DEFINITION_FILE = "cdm.beanDefinitionFile";
78
    private static final String ATTRIBUTE_DATASOURCE_NAME = "cdm.datasource";
79

  
80
    private static final String DATASOURCE_BEANDEF_DEFAULT = CdmUtils.getCdmHomeDir().getPath() + File.separator + "datasources.xml";
81

  
82
    private static String beanDefinitionFile = DATASOURCE_BEANDEF_DEFAULT;
74
    protected static final String ATTRIBUTE_JDBC_JNDI_NAME = "cdm.jdbcJndiName";
75
    protected static final String HIBERNATE_DIALECT = "hibernate.dialect";
76
    protected static final String HIBERNATE_SEARCH_DEFAULT_INDEX_BASE = "hibernate.search.default.indexBase";
77
    protected static final String CDM_BEAN_DEFINITION_FILE = "cdm.beanDefinitionFile";
78
    /**
79
     * Attribute to configure the name of the data source as set as bean name in the datasources.xml.
80
     * This name usually is used as the prefix for the webapplication root path.
81
     * <br>
82
     * <b>This is a required attribute!</b>
83
     *
84
     * @see AbstractWebApplicationConfigurer#findProperty(String, boolean)
85
     */
86
    protected static final String ATTRIBUTE_DATASOURCE_NAME = "cdm.datasource";
87

  
88
    protected static final String DATASOURCE_BEANDEF_DEFAULT = CdmUtils.getCdmHomeDir().getPath() + File.separator + "datasources.xml";
89

  
90
    protected static String beanDefinitionFile = DATASOURCE_BEANDEF_DEFAULT;
83 91

  
84 92
    public void setBeanDefinitionFile(String filename){
85 93
        beanDefinitionFile = filename;
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/view/BaseView.java
1 1
// $Id$
2 2
/**
3 3
* Copyright (C) 2007 EDIT
4
* European Distributed Institute of Taxonomy 
4
* European Distributed Institute of Taxonomy
5 5
* http://www.e-taxonomy.eu
6
* 
6
*
7 7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8 8
* See LICENSE.TXT at the top of this package for the full license terms.
9 9
*/
......
12 12
import java.io.PrintWriter;
13 13
import java.util.Map;
14 14

  
15
import javax.servlet.http.HttpServletRequest;
16
import javax.servlet.http.HttpServletResponse;
17

  
15 18
public abstract class BaseView {
16
	
17
	protected Object getResponseData(Map model){
18
		// Retrieve data from model
19
		Object data = null;
20
		if (model!=null && model.values().size()>0){
21
			data = model.values().toArray()[0];
22
		}
23
		return data;
24
	}
25
	
26
	/**
27
	 * Basic render method that may be used to render content with the cdmlib-remote api but without beeing in
28
	 * a webapplication context.
29
	 * 
30
	 * @param model
31
	 * @param writer
32
	 * @throws Exception
33
	 */
34
	public abstract void render (Object entity, PrintWriter writer) throws Exception;
19

  
20
    protected Object getResponseData(Map model){
21
        // Retrieve data from model
22
        Object data = null;
23
        if (model!=null && model.values().size()>0){
24
            data = model.values().toArray()[0];
25
        }
26
        return data;
27
    }
28

  
29
    /**
30
     * Basic render method that may be used to render content with the cdmlib-remote api but without beeing in
31
     * a webapplication context.
32
     * @param entity
33
     * @param writer
34
     * @param documentContextPath usually <code>request.getContextPath()</code>
35
     *
36
     * @throws Exception
37
     */
38
    public abstract void render (Object entity, PrintWriter writer, String documentContextPath) throws Exception;
35 39
}
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/view/JsonView.java
1 1
// $Id$
2 2
/**
3 3
* Copyright (C) 2007 EDIT
4
* European Distributed Institute of Taxonomy 
4
* European Distributed Institute of Taxonomy
5 5
* http://www.e-taxonomy.eu
6
* 
6
*
7 7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8 8
* See LICENSE.TXT at the top of this package for the full license terms.
9 9
*/
......
27 27

  
28 28

  
29 29
public class JsonView extends BaseView implements View{
30
	
31
	public static final Logger logger = Logger.getLogger(JsonView.class);
32

  
33
	private JsonConfig jsonConfig;
34
	
35
	public enum Type{
36
		JSON("application/json"),
37
		XML("application/xml");
38
		
39
		private String contentType;
40
		
41
		Type(String contentType){
42
			this.contentType = contentType;
43
		}
44
		
45
		public String getContentType(){
46
			return contentType;
47
		}
48
	}
49

  
50
	private Type type = Type.JSON;
51

  
52
	private String xsl;
53
	
54
	public void setXsl(String xsl) {
55
		this.xsl = xsl;
56
	}
57

  
58
	public Type getType() {
59
		return type;
60
	}
61

  
62
	/**
63
	 * Default is Type.JSON
64
	 * @param type
65
	 */
66
	public void setType(Type type) {
67
		this.type = type;
68
	}
69

  
70
	public void setJsonConfig(JsonConfig jsonConfig) {
71
		this.jsonConfig = jsonConfig;
72
	}
73

  
74
	/*
75
	 * (non-Javadoc)
76
	 * @see org.springframework.web.servlet.View#getContentType()
77
	 */
78
	public String getContentType() {
79
		return type.getContentType();
80
	}
81
	
82
	public void render(Object entity, PrintWriter writer) throws Exception {
83
		
84
		
85
		// create JSON Object
86
		boolean isCollectionType = false;
87
		JSON jsonObj;
88
		if (entity == null){
89
		  jsonObj = JSONObject.fromObject("{}");
90
		} else if(Collection.class.isAssignableFrom(entity.getClass())){
91
			isCollectionType = true;
92
			jsonObj = JSONArray.fromObject(entity, jsonConfig);
93
		}else if(entity instanceof String){
94
			jsonObj = JSONObject.fromObject("{\"String\":\""+entity.toString().replace("\"", "\\\"")+"\"}");
95
		} else if(entity instanceof Integer){
96
			jsonObj = JSONObject.fromObject("{\"Integer\":"+((Integer)entity).intValue()+"}");
97
		} else if(entity instanceof Boolean){
98
			jsonObj = JSONObject.fromObject("{\"Boolean\":"+((Boolean)entity).toString()+"}");
99
		} else {
100
			jsonObj = JSONObject.fromObject(entity, jsonConfig);
101
		}
102
		
103
		if(type.equals(Type.XML)){
104
			XMLSerializer xmlSerializer = new XMLSerializer();
105
			if(isCollectionType){
106
				xmlSerializer.setArrayName(entity.getClass().getSimpleName());
107
				Class elementType = Object.class;
108
				Collection c = (Collection)entity;
109
				if(c.size() > 0){
110
					elementType = c.iterator().next().getClass();
111
				}
112
				xmlSerializer.setObjectName(elementType.getSimpleName());
113
			} else if(entity != null){
114
				xmlSerializer.setObjectName(entity.getClass().getSimpleName());
115
			}
116
			String xml = xmlSerializer.write( jsonObj );
117
			if(xsl != null){
118
				String xslInclude = "\r\n<?xml-stylesheet type=\"text/xsl\" href=\"human.xsl\"?>\r\n";
119
				xml = xml.replaceFirst("\r\n", xslInclude);
120
			}
121
			writer.append(xml);
122
		} else {
123
			// assuming json
124
			writer.append(jsonObj.toString());
125
		}
126
		//TODO resp.setContentType(type);
127
		writer.flush();
128
	}
129
	
130
	/*
131
	 * (non-Javadoc)
132
	 * @see org.springframework.web.servlet.View#render(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
133
	 */
134
	public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
135
				
136
		// Retrieve data from model
137
		Object entity = getResponseData(model);
138
		
139
		// set content type 
140
		response.setContentType(type.getContentType());
141
		
142
		// render
143
		render(entity, response.getWriter());
144
		
145
	}	
30

  
31
    public static final Logger logger = Logger.getLogger(JsonView.class);
32

  
33
    private JsonConfig jsonConfig;
34

  
35
    public enum Type{
36
        JSON("application/json"),
37
        XML("application/xml");
38

  
39
        private String contentType;
40

  
41
        Type(String contentType){
42
            this.contentType = contentType;
43
        }
44

  
45
        public String getContentType(){
46
            return contentType;
47
        }
48
    }
49

  
50
    private Type type = Type.JSON;
51

  
52
    private String xsl = null;
53

  
54
    public void setXsl(String xsl) {
55
        this.xsl = xsl;
56
    }
57

  
58
    public String getXsl() {
59
        return xsl;
60
    }
61

  
62
    public Type getType() {
63
        return type;
64
    }
65

  
66
    /**
67
     * Default is Type.JSON
68
     * @param type
69
     */
70
    public void setType(Type type) {
71
        this.type = type;
72
    }
73

  
74
    public void setJsonConfig(JsonConfig jsonConfig) {
75
        this.jsonConfig = jsonConfig;
76
    }
77

  
78
    /*
79
     * (non-Javadoc)
80
     * @see org.springframework.web.servlet.View#getContentType()
81
     */
82
    public String getContentType() {
83
        return type.getContentType();
84
    }
85

  
86
    public void render(Object entity, PrintWriter writer, String documentContextPath) throws Exception {
87

  
88
        if(jsonConfig == null){
89
            logger.error("The jsonConfig must not be null. It must be set in the applicationContext.");
90
        }
91

  
92
        // create JSON Object
93
        boolean isCollectionType = false;
94
        JSON jsonObj;
95
        if (entity == null){
96
          jsonObj = JSONObject.fromObject("{}");
97
        } else if(Collection.class.isAssignableFrom(entity.getClass())){
98
            isCollectionType = true;
99
            jsonObj = JSONArray.fromObject(entity, jsonConfig);
100
        }else if(entity instanceof String){
101
            jsonObj = JSONObject.fromObject("{\"String\":\""+entity.toString().replace("\"", "\\\"")+"\"}");
102
        } else if(entity instanceof Integer){
103
            jsonObj = JSONObject.fromObject("{\"Integer\":"+((Integer)entity).intValue()+"}");
104
        } else if(entity instanceof Boolean){
105
            jsonObj = JSONObject.fromObject("{\"Boolean\":"+((Boolean)entity).toString()+"}");
106
        } else {
107
            jsonObj = JSONObject.fromObject(entity, jsonConfig);
108
        }
109

  
110
        if(type.equals(Type.XML)){
111
            XMLSerializer xmlSerializer = new XMLSerializer();
112
            if(isCollectionType){
113
                xmlSerializer.setArrayName(entity.getClass().getSimpleName());
114
                Class elementType = Object.class;
115
                Collection c = (Collection)entity;
116
                if(c.size() > 0){
117
                    elementType = c.iterator().next().getClass();
118
                }
119
                xmlSerializer.setObjectName(elementType.getSimpleName());
120
            } else if(entity != null){
121
                xmlSerializer.setObjectName(entity.getClass().getSimpleName());
122
            }
123
            String xml = xmlSerializer.write( jsonObj );
124
            if(type.equals(Type.XML) && xsl != null){
125
                if(documentContextPath == null){
126
                    documentContextPath = "";
127
                }
128
                String replace = "\r\n<?xml-stylesheet type=\"text/xsl\" href=\"" + documentContextPath + "/" + xsl + "\"?>\r\n";
129
                xml = xml.replaceFirst("\r\n", replace);
130
            }
131
            writer.append(xml);
132
        } else {
133
            // assuming json
134
            writer.append(jsonObj.toString());
135
        }
136
        //TODO resp.setContentType(type);
137
        writer.flush();
138
    }
139

  
140
    /*
141
     * (non-Javadoc)
142
     * @see org.springframework.web.servlet.View#render(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
143
     */
144
    public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
145

  
146
        // Retrieve data from model
147
        Object entity = getResponseData(model);
148

  
149
        // set content type
150
        response.setContentType(type.getContentType());
151

  
152
        PrintWriter writer = response.getWriter();
153

  
154
        // render
155
        render(entity, writer, request.getContextPath());
156
    }
146 157
}
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/view/XmlView.java
20 20
 * @see com.ibm.lsid.MetadataResponse
21 21
 */
22 22
public class XmlView extends AbstractView {
23
	
24
	private Marshaller marshaller;
25
	
26
	private boolean locationHeader = false;
27
	
28
	private String locationPrefix = "";
29
	
30
	public void setLocationHeader(boolean locationHeader) {
31
		this.locationHeader = locationHeader;
32
	}
33

  
34
	public void setLocationPrefix(String locationPrefix) {
35
		this.locationPrefix = locationPrefix;
36
	}
37

  
38
	public XmlView() {
39
		
40
	}
41
	
42
	@Autowired
43
	public void setMarshaller(Marshaller marshaller) {
44
		this.marshaller = marshaller;
45
	}
46
	
47
	
48
	
49
	@Override
50
	protected void renderMergedOutputModel(Map model,HttpServletRequest request, HttpServletResponse response)
51
			throws Exception {
52
		
53
		for(Object object : model.values()) {
54
		    if(object instanceof IdentifiableEntity) {		    			    	
55
		        IdentifiableEntity identifiableEntity = (IdentifiableEntity)object;
23

  
24
    private Marshaller marshaller;
25

  
26
    private boolean locationHeader = false;
27

  
28
    private String locationPrefix = "";
29

  
30
    public void setLocationHeader(boolean locationHeader) {
31
        this.locationHeader = locationHeader;
32
    }
33

  
34
    public void setLocationPrefix(String locationPrefix) {
35
        this.locationPrefix = locationPrefix;
36
    }
37

  
38
    public XmlView() {
39

  
40
    }
41

  
42
    @Autowired
43
    public void setMarshaller(Marshaller marshaller) {
44
        this.marshaller = marshaller;
45
    }
46

  
47

  
48

  
49
    @Override
50
    protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
51
            throws Exception {
52

  
53
        for(Object object : model.values()) {
54
            if(object instanceof IdentifiableEntity) {
55
                IdentifiableEntity identifiableEntity = (IdentifiableEntity)object;
56 56
                if(locationHeader) {
57
		    		response.addHeader("Location", locationPrefix + identifiableEntity.getUuid().toString());
58
		    	}
59
		        marshaller.marshal(identifiableEntity, new StreamResult(response.getOutputStream()));
60
		    } else if(object instanceof Throwable) {  
61
		    	eu.etaxonomy.cdm.io.jaxb.Error error = new eu.etaxonomy.cdm.io.jaxb.Error((Throwable)object);
62
		    	marshaller.marshal(error, new StreamResult(response.getOutputStream()));
63
		    }
64
		}		
65
	}
57
                    response.addHeader("Location", locationPrefix + identifiableEntity.getUuid().toString());
58
                }
59
                marshaller.marshal(identifiableEntity, new StreamResult(response.getOutputStream()));
60
            } else if(object instanceof Throwable) {
61
                eu.etaxonomy.cdm.io.jaxb.Error error = new eu.etaxonomy.cdm.io.jaxb.Error((Throwable)object);
62
                marshaller.marshal(error, new StreamResult(response.getOutputStream()));
63
            }
64
        }
65
    }
66 66

  
67 67
}

Also available in: Unified diff