From 759ac5f42c6aff901dbeede4fbf1a1d2e08cad0f Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 4 Dec 2019 19:43:32 +0100 Subject: common EGIZ code-style refactoring --- .../gui/AbstractGUIFormBuilderConfiguration.java | 179 --------------- .../gui/AbstractGuiFormBuilderConfiguration.java | 195 ++++++++++++++++ .../gui/AbstractVelocityGUIFormBuilderImpl.java | 242 -------------------- .../gui/AbstractVelocityGuiFormBuilderImpl.java | 250 +++++++++++++++++++++ .../core/impl/gui/velocity/VelocityLogAdapter.java | 176 +++++++-------- .../core/impl/gui/velocity/VelocityProvider.java | 178 ++++++--------- 6 files changed, 607 insertions(+), 613 deletions(-) delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGUIFormBuilderConfiguration.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGuiFormBuilderConfiguration.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGUIFormBuilderImpl.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGuiFormBuilderImpl.java (limited to 'eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui') diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGUIFormBuilderConfiguration.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGUIFormBuilderConfiguration.java deleted file mode 100644 index dde5ab70..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGUIFormBuilderConfiguration.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.gui; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.gui.GroupDefinition; -import at.gv.egiz.eaaf.core.api.gui.GroupDefinition.TYPE; -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; - -/** - * @author tlenz - * - */ -public abstract class AbstractGUIFormBuilderConfiguration implements IGUIBuilderConfiguration { - private static final Logger log = LoggerFactory.getLogger(AbstractGUIFormBuilderConfiguration.class); - - public static final GroupDefinition PARAM_GROUP_FORM = GroupDefinition.getInstance("form", TYPE.MAP); - public static final GroupDefinition PARAM_GROUP_ACTIONS = GroupDefinition.getInstance("actions", TYPE.LIST); - public static final GroupDefinition PARAM_GROUP_PARAMS = GroupDefinition.getInstance("params", TYPE.MAP); - public static final GroupDefinition PARAM_GROUP_UIOPTIONS = GroupDefinition.getInstance("uiOptions", TYPE.MAP); - public static final GroupDefinition PARAM_GROUP_MSG = GroupDefinition.getInstance("msg", TYPE.MAP); - - - public static final String PARAM_VIEWNAME = "viewName"; - public static final String PARAM_AUTHCONTEXT = "contextPath"; - public static final String PARAM_FORMSUBMITENDPOINT = "submitEndpoint"; - @Deprecated public static final String PARAM_PENDINGREQUESTID_DEPRECATED = "pendingReqID"; - public static final String PARAM_PENDINGREQUESTID = "pendingid"; - - private String authURL = null; - private String viewName = null; - private String formSubmitEndpoint = null; - - private final Map params = new HashMap(); - - /** - * @param authURL IDP PublicURL-Prefix which should be used, but never null - * @param viewName Name of the template (with suffix) but never null - * @param formSubmitEndpoint EndPoint on which the form should be submitted, - * or null if the form must not submitted - * - */ - public AbstractGUIFormBuilderConfiguration(String authURL, String viewName, String formSubmitEndpoint) { - if (viewName.startsWith("/")) - this.viewName = viewName.substring(1); - else - this.viewName = viewName; - - if (authURL.endsWith("/")) - this.authURL = authURL.substring(0, authURL.length() - 1); - else - this.authURL = authURL; - - if (StringUtils.isNotEmpty(formSubmitEndpoint)) { - if (formSubmitEndpoint.startsWith("/")) - this.formSubmitEndpoint = formSubmitEndpoint; - else - this.formSubmitEndpoint = "/" + formSubmitEndpoint; - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration#getViewName() - */ - @Override - public final String getViewName() { - return this.viewName; - - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration#getViewParameters() - */ - @Override - public final Map getViewParameters() { - //set generic parameters - setViewParameter(getFromGroup(), PARAM_AUTHCONTEXT, this.authURL); - setViewParameter(getFromGroup(), PARAM_FORMSUBMITENDPOINT, this.formSubmitEndpoint); - setViewParameter(getFromGroup(), PARAM_VIEWNAME, this.viewName); - - //get parameters from detail implementation - putSpecificViewParameters(); - - try { - log.trace("Full view parameters: {}", StringUtils.join(params, ",")); - } catch (final Exception e) { - log.info("Can NOT trace view parameters. Reason: {}", e.getMessage() ); - } - - return params; - - } - - /** - * Define the parameters, which should be evaluated in the template
- * IMPORTANT: external HTML escapetion is required, because it is NOT done internally during the building process - * - */ - abstract protected void putSpecificViewParameters(); - - /** - * Get the Group for generic form elements - * - * @return {@link GroupDefinition} or null if no groups are used - */ - abstract protected GroupDefinition getFromGroup(); - - @SuppressWarnings("unchecked") - protected void setViewParameter(GroupDefinition groupDefinition, String key, Object value) { - - if (groupDefinition != null) { - log.trace("Adding group object ... "); - Object groupMap = params.get(groupDefinition.getName()); - if (groupMap == null) { - if (groupDefinition.getType().equals(TYPE.MAP)) { - groupMap = new HashMap();; - log.trace("Build new MAP based group element"); - - } else if (groupDefinition.getType().equals(TYPE.LIST)) { - groupMap = new ArrayList(); - log.trace("Build new List based group element"); - - } else - log.warn("GroupDefinition contains an unknown type: {}", groupDefinition.getType().name()); - - } - - params.put(groupDefinition.getName(), groupMap); - if (groupMap instanceof Map) - ((Map) groupMap).put(key, value); - - else if (groupMap instanceof List) - ((List)groupMap).add(value); - - else - log.warn("Can NOT add element: {} to group: {}, because group is of type: {}", - key, groupDefinition.getName(), groupMap.getClass().getName()); - - } else { - log.trace("Add root object ... "); - params.put(key, value); - - } - - } -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGuiFormBuilderConfiguration.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGuiFormBuilderConfiguration.java new file mode 100644 index 00000000..efb8c713 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGuiFormBuilderConfiguration.java @@ -0,0 +1,195 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.gui; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import at.gv.egiz.eaaf.core.api.gui.GroupDefinition; +import at.gv.egiz.eaaf.core.api.gui.GroupDefinition.Type; +import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfiguration; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Abstract Configuration implementation for GUI Builders. + * + * @author tlenz + * + */ +public abstract class AbstractGuiFormBuilderConfiguration implements IGuiBuilderConfiguration { + private static final Logger log = + LoggerFactory.getLogger(AbstractGuiFormBuilderConfiguration.class); + + public static final GroupDefinition PARAM_GROUP_FORM = + GroupDefinition.getInstance("form", Type.MAP); + public static final GroupDefinition PARAM_GROUP_ACTIONS = + GroupDefinition.getInstance("actions", Type.LIST); + public static final GroupDefinition PARAM_GROUP_PARAMS = + GroupDefinition.getInstance("params", Type.MAP); + public static final GroupDefinition PARAM_GROUP_UIOPTIONS = + GroupDefinition.getInstance("uiOptions", Type.MAP); + public static final GroupDefinition PARAM_GROUP_MSG = + GroupDefinition.getInstance("msg", Type.MAP); + + + public static final String PARAM_VIEWNAME = "viewName"; + public static final String PARAM_AUTHCONTEXT = "contextPath"; + public static final String PARAM_FORMSUBMITENDPOINT = "submitEndpoint"; + @Deprecated + public static final String PARAM_PENDINGREQUESTID_DEPRECATED = "pendingReqID"; + public static final String PARAM_PENDINGREQUESTID = "pendingid"; + + private String authUrl = null; + private String viewName = null; + private String formSubmitEndpoint = null; + + private final Map params = new HashMap<>(); + + /** + * Abstract GUI Builder config. + * + * @param authUrl IDP PublicURL-Prefix which should be used, but never null + * @param viewName Name of the template (with suffix) but never null + * @param formSubmitEndpoint EndPoint on which the form should be submitted, or null if the form + * must not submitted + * + */ + public AbstractGuiFormBuilderConfiguration(final String authUrl, final String viewName, + final String formSubmitEndpoint) { + if (viewName.startsWith("/")) { + this.viewName = viewName.substring(1); + } else { + this.viewName = viewName; + } + + if (authUrl.endsWith("/")) { + this.authUrl = authUrl.substring(0, authUrl.length() - 1); + } else { + this.authUrl = authUrl; + } + + if (StringUtils.isNotEmpty(formSubmitEndpoint)) { + if (formSubmitEndpoint.startsWith("/")) { + this.formSubmitEndpoint = formSubmitEndpoint; + } else { + this.formSubmitEndpoint = "/" + formSubmitEndpoint; + } + } + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration#getViewName() + */ + @Override + public final String getViewName() { + return this.viewName; + + } + + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration#getViewParameters() + */ + @Override + public final Map getViewParameters() { + // set generic parameters + setViewParameter(getFromGroup(), PARAM_AUTHCONTEXT, this.authUrl); + setViewParameter(getFromGroup(), PARAM_FORMSUBMITENDPOINT, this.formSubmitEndpoint); + setViewParameter(getFromGroup(), PARAM_VIEWNAME, this.viewName); + + // get parameters from detail implementation + putSpecificViewParameters(); + + try { + log.trace("Full view parameters: {}", StringUtils.join(params, ",")); + } catch (final Exception e) { + log.info("Can NOT trace view parameters. Reason: {}", e.getMessage()); + } + + return params; + + } + + /** + * Define the parameters, which should be evaluated in the template.
+ * IMPORTANT: external HTML escapetion is required, because it is NOT done internally + * during the building process + * + */ + protected abstract void putSpecificViewParameters(); + + /** + * Get the Group for generic form elements. + * + * @return {@link GroupDefinition} or null if no groups are used + */ + protected abstract GroupDefinition getFromGroup(); + + @SuppressWarnings("unchecked") + protected void setViewParameter(final GroupDefinition groupDefinition, final String key, + final Object value) { + + if (groupDefinition != null) { + log.trace("Adding group object ... "); + Object groupMap = params.get(groupDefinition.getName()); + if (groupMap == null) { + if (groupDefinition.getType().equals(Type.MAP)) { + groupMap = new HashMap(); + log.trace("Build new MAP based group element"); + + } else if (groupDefinition.getType().equals(Type.LIST)) { + groupMap = new ArrayList<>(); + log.trace("Build new List based group element"); + + } else { + log.warn("GroupDefinition contains an unknown type: {}", + groupDefinition.getType().name()); + groupMap = StringUtils.EMPTY; + + } + + } + + params.put(groupDefinition.getName(), groupMap); + if (groupMap instanceof Map) { + ((Map) groupMap).put(key, value); + } else if (groupMap instanceof List) { + ((List) groupMap).add(value); + } else { + log.warn("Can NOT add element: {} to group: {}, because group is of type: {}", key, + groupDefinition.getName(), groupMap.getClass().getName()); + } + + } else { + log.trace("Add root object ... "); + params.put(key, value); + + } + + } +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGUIFormBuilderImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGUIFormBuilderImpl.java deleted file mode 100644 index b9c16538..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGUIFormBuilderImpl.java +++ /dev/null @@ -1,242 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.gui; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IVelocityGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiFormBuilder; -import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; -import at.gv.egiz.eaaf.core.impl.gui.velocity.VelocityProvider; - -/** - * @author tlenz - * - */ -public abstract class AbstractVelocityGUIFormBuilderImpl implements IVelocityGuiFormBuilder { - private static final Logger log = LoggerFactory.getLogger(AbstractVelocityGUIFormBuilderImpl.class); - private static final String DEFAULT_CONTENT_TYPE = EAAFConstants.CONTENTTYPE_HTML_UTF8; - - private VelocityEngine engine; - - public AbstractVelocityGUIFormBuilderImpl() throws GUIBuildException { - try { - engine = VelocityProvider.getClassPathVelocityEngine(); - - } catch (final Exception e) { - log.error("Initialization of Velocity-Engine to render GUI components FAILED.", e); - throw new GUIBuildException("Initialization of Velocity-Engine to render GUI components FAILED.", e); - - } - - } - - @Override - public final void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IGUIBuilderConfiguration config, - String loggerName) throws GUIBuildException { - if (config instanceof IVelocityGUIBuilderConfiguration) - build(httpReq, httpResp, (IVelocityGUIBuilderConfiguration)config, loggerName); - else - throw new IllegalStateException(this.getClass().getName() + " needs a " + IVelocityGUIBuilderConfiguration.class.getName()); - - - } - - @Override - public final void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IGUIBuilderConfiguration config, - String contentType, String loggerName) throws GUIBuildException { - if (config instanceof IVelocityGUIBuilderConfiguration) - build(httpReq, httpResp, (IVelocityGUIBuilderConfiguration)config, contentType, loggerName); - else - throw new IllegalStateException(this.getClass().getName() + " needs a " + IVelocityGUIBuilderConfiguration.class.getName()); - - } - - @Override - public void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IVelocityGUIBuilderConfiguration config, String loggerName) throws GUIBuildException { - build(httpReq, httpResp, config, getInternalContentType(config), loggerName); - - } - - @Override - public void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IVelocityGUIBuilderConfiguration config, - String contentType, String loggerName) throws GUIBuildException { - - InputStream is = null; - try { - final String viewName = config.getViewName(); - is = getTemplateInputStream(config); - - //build Velocity Context from input paramters - final VelocityContext context = buildContextFromViewParams(config.getViewParameters()); - - //evaluate template - final StringWriter writer = new StringWriter(); - engine.evaluate(context, writer, loggerName, new BufferedReader(new InputStreamReader(is))); - - //write template to response - final byte[] content = writer.toString().getBytes("UTF-8"); - httpResp.setStatus(HttpServletResponse.SC_OK); - httpResp.setContentLength(content.length); - httpResp.setContentType(contentType); - httpResp.getOutputStream().write(content); - - if (log.isTraceEnabled()) { - log.trace("Write Content for viewName:" + viewName - + ". Contentsize:" + String.valueOf(content.length) - + " BufferSize:" + httpResp.getBufferSize() - + " ContentType:" + contentType); - for (final String el : httpResp.getHeaderNames()) - log.trace(" * Headername:" + el + " Value:" + httpResp.getHeader(el)); - - } - - } catch (final IOException e) { - log.error("GUI form-builder has an internal error.", e); - throw new GUIBuildException("GUI form-builder has an internal error.", e); - - } finally { - if (is != null) - try { - is.close(); - - } catch (final IOException e) { - log.error("Can NOT close GUI-Template InputStream.", e); - - } - } - - } - - /** - * Generate a new {@link VelocityContext} and populate it with MOA-ID GUI parameters - * - * @param config - * @return - */ - @Override - public VelocityContext generateVelocityContextFromConfiguration(IVelocityGUIBuilderConfiguration config) { - return buildContextFromViewParams(config.getViewParameters()); - - } - - /** - * Load the template from different resources - * - * @param config - * @return An {@link InputStream} but never null. The {@link InputStream} had to be closed be the invoking method - * @throws GUIBuildException - */ - @Override - public InputStream getTemplateInputStream(IVelocityGUIBuilderConfiguration config) throws GUIBuildException { - InputStream is = config.getTemplate(config.getViewName()); - if (is == null) { - log.trace("Loading GUI template:" + config.getViewName() + " from default resources ... "); - is = getInternalTemplate(config); - - if (is == null) { - log.warn("No GUI with viewName:" + config.getViewName() + " FOUND."); - throw new GUIBuildException("No GUI with viewName:" + config.getViewName() + " FOUND."); - - } - } - return is; - - } - - /** - * Load an internal template from default resources - * - * @param config - * @return - * @throws GUIBuildException - */ - abstract protected InputStream getInternalTemplate(IVelocityGUIBuilderConfiguration config) throws GUIBuildException; - - - /** - * @return - */ - protected String getInternalClasspathTemplateDir(IVelocityGUIBuilderConfiguration config, String defaultClassPathDir) { - String dir = config.getClasspathTemplateDir(); - if (dir != null) { - if (!dir.endsWith("/")) - dir += "/"; - - return dir; - - } else - return defaultClassPathDir; - } - - /** - * @param viewParams - * @return - */ - private VelocityContext buildContextFromViewParams(Map viewParams) { - final VelocityContext context = new VelocityContext(); - - if (viewParams != null) { - final Iterator> interator = viewParams.entrySet().iterator(); - while (interator.hasNext()) { - final Entry el = interator.next(); - context.put(el.getKey(), el.getValue()); - } - - } - - return context; - } - - private String getInternalContentType(IGUIBuilderConfiguration config) { - if (StringUtils.isEmpty(config.getDefaultContentType())) - return DEFAULT_CONTENT_TYPE; - - else - return config.getDefaultContentType(); - - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGuiFormBuilderImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGuiFormBuilderImpl.java new file mode 100644 index 00000000..0ab5fa49 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGuiFormBuilderImpl.java @@ -0,0 +1,250 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.gui; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiFormBuilder; +import at.gv.egiz.eaaf.core.exceptions.GuiBuildException; +import at.gv.egiz.eaaf.core.impl.gui.velocity.VelocityProvider; +import org.apache.commons.lang3.StringUtils; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Abstract VeloCity based GUI builder implementation. + * + * @author tlenz + * + */ +public abstract class AbstractVelocityGuiFormBuilderImpl implements IVelocityGuiFormBuilder { + private static final Logger log = + LoggerFactory.getLogger(AbstractVelocityGuiFormBuilderImpl.class); + private static final String DEFAULT_CONTENT_TYPE = EAAFConstants.CONTENTTYPE_HTML_UTF8; + + private VelocityEngine engine; + + /** + * Velocity based GUI builder. + * + * @throws GuiBuildException In case of a error + */ + public AbstractVelocityGuiFormBuilderImpl() throws GuiBuildException { + try { + engine = VelocityProvider.getClassPathVelocityEngine(); + + } catch (final Exception e) { + log.error("Initialization of Velocity-Engine to render GUI components FAILED.", e); + throw new GuiBuildException( + "Initialization of Velocity-Engine to render GUI components FAILED.", e); + + } + + } + + @Override + public final void build(final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IGuiBuilderConfiguration config, final String loggerName) throws GuiBuildException { + if (config instanceof IVelocityGuiBuilderConfiguration) { + build(httpReq, httpResp, (IVelocityGuiBuilderConfiguration) config, loggerName); + } else { + throw new IllegalStateException(this.getClass().getName() + " needs a " + + IVelocityGuiBuilderConfiguration.class.getName()); + } + + + } + + @Override + public final void build(final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IGuiBuilderConfiguration config, final String contentType, final String loggerName) + throws GuiBuildException { + if (config instanceof IVelocityGuiBuilderConfiguration) { + build(httpReq, httpResp, (IVelocityGuiBuilderConfiguration) config, contentType, loggerName); + } else { + throw new IllegalStateException(this.getClass().getName() + " needs a " + + IVelocityGuiBuilderConfiguration.class.getName()); + } + + } + + @Override + public void build(final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IVelocityGuiBuilderConfiguration config, final String loggerName) + throws GuiBuildException { + build(httpReq, httpResp, config, getInternalContentType(config), loggerName); + + } + + @Override + public void build(final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IVelocityGuiBuilderConfiguration config, final String contentType, + final String loggerName) throws GuiBuildException { + + InputStream is = null; + try { + final String viewName = config.getViewName(); + is = getTemplateInputStream(config); + + // build Velocity Context from input paramters + final VelocityContext context = buildContextFromViewParams(config.getViewParameters()); + + // evaluate template + final StringWriter writer = new StringWriter(); + engine.evaluate(context, writer, loggerName, new BufferedReader(new InputStreamReader(is, "UTF-8"))); + + // write template to response + final byte[] content = writer.toString().getBytes("UTF-8"); + httpResp.setStatus(HttpServletResponse.SC_OK); + httpResp.setContentLength(content.length); + httpResp.setContentType(contentType); + httpResp.getOutputStream().write(content); + + if (log.isTraceEnabled()) { + log.trace("Write Content for viewName:" + viewName + ". Contentsize:" + + String.valueOf(content.length) + " BufferSize:" + httpResp.getBufferSize() + + " ContentType:" + contentType); + for (final String el : httpResp.getHeaderNames()) { + log.trace(" * Headername:" + el + " Value:" + httpResp.getHeader(el)); + } + + } + + } catch (final IOException e) { + log.error("GUI form-builder has an internal error.", e); + throw new GuiBuildException("GUI form-builder has an internal error.", e); + + } finally { + if (is != null) { + try { + is.close(); + + } catch (final IOException e) { + log.error("Can NOT close GUI-Template InputStream.", e); + + } + } + } + + } + + /** + * Generate a new {@link VelocityContext} and populate it with MOA-ID GUI parameters. + * + * @param config GUI builder config + * @return Context of Velocity engine + */ + @Override + public VelocityContext generateVelocityContextFromConfiguration( + final IVelocityGuiBuilderConfiguration config) { + return buildContextFromViewParams(config.getViewParameters()); + + } + + /** + * Load the template from different resources. + * + * @param config GUI builder config + * @return An {@link InputStream} but never null. The {@link InputStream} had to be closed be the + * invoking method + * @throws GuiBuildException In case of an error + */ + @Override + public InputStream getTemplateInputStream(final IVelocityGuiBuilderConfiguration config) + throws GuiBuildException { + InputStream is = config.getTemplate(config.getViewName()); + if (is == null) { + log.trace("Loading GUI template:" + config.getViewName() + " from default resources ... "); + is = getInternalTemplate(config); + + if (is == null) { + log.warn("No GUI with viewName:" + config.getViewName() + " FOUND."); + throw new GuiBuildException("No GUI with viewName:" + config.getViewName() + " FOUND."); + + } + } + return is; + + } + + /** + * Load an internal template from default resources. + * + * @param config GUI builder config + * @return Template that should be used + * @throws GuiBuildException in case of an error + */ + protected abstract InputStream getInternalTemplate(IVelocityGuiBuilderConfiguration config) + throws GuiBuildException; + + + protected String getInternalClasspathTemplateDir(final IVelocityGuiBuilderConfiguration config, + final String defaultClassPathDir) { + String dir = config.getClasspathTemplateDir(); + if (dir != null) { + if (!dir.endsWith("/")) { + dir += "/"; + } + + return dir; + + } else { + return defaultClassPathDir; + } + } + + private VelocityContext buildContextFromViewParams(final Map viewParams) { + final VelocityContext context = new VelocityContext(); + + if (viewParams != null) { + final Iterator> interator = viewParams.entrySet().iterator(); + while (interator.hasNext()) { + final Entry el = interator.next(); + context.put(el.getKey(), el.getValue()); + } + + } + + return context; + } + + private String getInternalContentType(final IGuiBuilderConfiguration config) { + if (StringUtils.isEmpty(config.getDefaultContentType())) { + return DEFAULT_CONTENT_TYPE; + } else { + return config.getDefaultContentType(); + } + + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityLogAdapter.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityLogAdapter.java index a118d7e1..05cbaf58 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityLogAdapter.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityLogAdapter.java @@ -1,32 +1,26 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.gui.velocity; import org.apache.velocity.app.Velocity; +import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.RuntimeServices; import org.apache.velocity.runtime.log.LogChute; import org.slf4j.Logger; @@ -34,72 +28,78 @@ import org.slf4j.LoggerFactory; public class VelocityLogAdapter implements LogChute { - private static final Logger log = LoggerFactory.getLogger(VelocityLogAdapter.class); - - public VelocityLogAdapter() { - try - { - /* - * register this class as a logger with the Velocity singleton - * (NOTE: this would not work for the non-singleton method.) - */ - Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this ); - Velocity.init(); - } - catch (Exception e) - { - log.error("Failed to register Velocity logger"); - } - } - - public void init(RuntimeServices arg0) throws Exception { - } + private static final Logger log = LoggerFactory.getLogger(VelocityLogAdapter.class); + + /** + * VeloCity Logging adapter. + * + */ + public VelocityLogAdapter() { + try { + /* + * register this class as a logger with the Velocity singleton (NOTE: this would not work for + * the non-singleton method.) + */ + Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, this); + Velocity.init(); + } catch (final Exception e) { + log.error("Failed to register Velocity logger"); + } + } + + @Override + public void init(final RuntimeServices arg0) throws Exception { + + } + + @Override + public boolean isLevelEnabled(final int arg0) { + switch (arg0) { + case LogChute.DEBUG_ID: + return log.isDebugEnabled(); + case LogChute.TRACE_ID: + return log.isTraceEnabled(); + default: + return true; + } + } - public boolean isLevelEnabled(int arg0) { - switch(arg0) { - case LogChute.DEBUG_ID: - return log.isDebugEnabled(); - case LogChute.TRACE_ID: - return log.isTraceEnabled(); - default: - return true; - } - } + @Override + public void log(final int arg0, final String arg1) { + switch (arg0) { + case LogChute.DEBUG_ID: + log.debug(arg1); + break; + case LogChute.TRACE_ID: + log.trace(arg1); + break; + case LogChute.INFO_ID: + log.info(arg1); + break; + case LogChute.WARN_ID: + log.warn(arg1); + break; + case LogChute.ERROR_ID: + default: + log.error(arg1); + break; + } + } - public void log(int arg0, String arg1) { - switch(arg0) { - case LogChute.DEBUG_ID: - log.debug(arg1); - break; - case LogChute.TRACE_ID: - log.trace(arg1); - break; - case LogChute.INFO_ID: - log.info(arg1); - break; - case LogChute.WARN_ID: - log.warn(arg1); - break; - case LogChute.ERROR_ID: - default: - log.error(arg1); - break; - } - } + @Override + public void log(final int arg0, final String arg1, final Throwable arg2) { + switch (arg0) { + case LogChute.DEBUG_ID: + case LogChute.TRACE_ID: + case LogChute.INFO_ID: + case LogChute.WARN_ID: + log.warn(arg1, arg2); + break; + case LogChute.ERROR_ID: + default: + log.error(arg1, arg2); + break; + } + } - public void log(int arg0, String arg1, Throwable arg2) { - switch(arg0) { - case LogChute.DEBUG_ID: - case LogChute.TRACE_ID: - case LogChute.INFO_ID: - case LogChute.WARN_ID: - log.warn(arg1, arg2); - break; - case LogChute.ERROR_ID: - default: - log.error(arg1, arg2); - break; - } - } - } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityProvider.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityProvider.java index 5775e203..18594985 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityProvider.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityProvider.java @@ -1,121 +1,91 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ /* - * Copyright 2011 by Graz University of Technology, Austria - * The Austrian STORK Modules have been developed by the E-Government - * Innovation Center EGIZ, a joint initiative of the Federal Chancellery - * Austria and Graz University of Technology. + * Copyright 2014 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ -/** - * - */ package at.gv.egiz.eaaf.core.impl.gui.velocity; -import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; /** - * Gets a Velocity Engine - * + * Gets a Velocity Engine. + * * @author bzwattendorfer * */ public class VelocityProvider { - private static VelocityEngine velocityEngine = null; - - /** - * Gets velocityEngine from Classpath - * @return VelocityEngine - * @throws Exception - */ - public static VelocityEngine getClassPathVelocityEngine() throws Exception { - if (velocityEngine == null) { - velocityEngine = getBaseVelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); - velocityEngine.setProperty("classpath.resource.loader.class", - "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - velocityEngine.init(); - - } - - return velocityEngine; - } - - /** - * Gets VelocityEngine from File - * @param rootPath File Path to template file - * @return VelocityEngine - * @throws Exception - */ - public static VelocityEngine getFileVelocityEngine(String rootPath) throws Exception { - if (velocityEngine == null) { - velocityEngine = getBaseVelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); - velocityEngine.setProperty("file.resource.loader.class", - "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); - velocityEngine.setProperty("file.resource.loader.path", rootPath); - - velocityEngine.init(); - - } - - return velocityEngine; - } - - /** - * Gets a basic VelocityEngine - * @return VelocityEngine - */ - private static VelocityEngine getBaseVelocityEngine() { - VelocityEngine velocityEngine = new VelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8"); - velocityEngine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); -// velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, -// "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); - velocityEngine.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, new VelocityLogAdapter() ); - - return velocityEngine; - } - + private static VelocityEngine velocityEngine = null; + + /** + * Gets velocityEngine from Classpath. + * + * @return VelocityEngine + * @throws Exception In case of an error + */ + public static VelocityEngine getClassPathVelocityEngine() throws Exception { + if (velocityEngine == null) { + velocityEngine = getBaseVelocityEngine(); + velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); + velocityEngine.setProperty("classpath.resource.loader.class", + "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + velocityEngine.init(); + + } + + return velocityEngine; + } + + /** + * Gets VelocityEngine from File. + * + * @param rootPath File Path to template file + * @return VelocityEngine + * @throws Exception in case of an error + */ + public static VelocityEngine getFileVelocityEngine(final String rootPath) throws Exception { + if (velocityEngine == null) { + velocityEngine = getBaseVelocityEngine(); + velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); + velocityEngine.setProperty("file.resource.loader.class", + "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); + velocityEngine.setProperty("file.resource.loader.path", rootPath); + + velocityEngine.init(); + + } + + return velocityEngine; + } + + /** + * Gets a basic VelocityEngine. + * + * @return VelocityEngine + */ + private static VelocityEngine getBaseVelocityEngine() { + final VelocityEngine velocityEngine = new VelocityEngine(); + velocityEngine.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8"); + velocityEngine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); + // velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, + // "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); + velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new VelocityLogAdapter()); + + return velocityEngine; + } + } -- cgit v1.2.3