All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sun.mojarra.scales.util.ScalesUtil Maven / Gradle / Ivy

Go to download

This is the core for Mojarra Scales. It has everything that Scales offers minus the multi-file upload component dependencies due to their size.

The newest version!
/*
 * $Id: ScalesUtil.java,v 93287f23708f 2009/08/27 03:41:20 jason $
 */

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 * 
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 * 
 * Contributor(s):
 * 
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */
package com.sun.mojarra.scales.util;

import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.el.ELContext;
import javax.el.ValueExpression;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.servlet.http.HttpServletRequest;

/**
 * Util is a class ...
 * 

* Lifetime And Scope

* * @version $Id: ScalesUtil.java,v 93287f23708f 2009/08/27 03:41:20 jason $ */ public class ScalesUtil { /** * This array contains attributes that have a boolean value in JSP, * but have have no value in HTML. For example "disabled" or * "readonly".

*/ // private static String booleanPassthruAttributes[] = {"disabled", "readonly", "ismap"}; private static final String INVOCATION_PATH = "com.sun.mojarra.scales.INVOCATION_PATH"; /** * This array contains attributes whose value is just rendered * straight to the content. This array should only contain * attributes that require no interpretation by the Renderer. If an * attribute requires interpretation by a Renderer, it should be * removed from this array.

*/ private static String passthruAttributes[] = { "accept", "accesskey", "alt", "bgcolor", "border", "cellpadding", "cellspacing", "charset", "cols", "coords", "dir", "enctype", "frame", "height", "hreflang", "lang", "longdesc", "maxlength", "onblur", "onchange", "onclick", "ondblclick", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onload", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onreset", "onselect", "onsubmit", "onunload", "rel", "rev", "rows", "rules", "shape", "size", "style", "summary", "tabindex", "target", "title", "usemap", "width" }; // public static void loadDefaultAttributeValues(Map attributes, String[][] defaults) { // for (String[] field : defaults) { // attributes.put(field[0], field[1]); // } // } private ScalesUtil() { // } public static Logger getLogger() { return Logger.getLogger("com.sun.mojarra.scales"); } /** *

Returns the URL pattern of the * {@link javax.faces.webapp.FacesServlet} that * is executing the current request. If there are multiple * URL patterns, the value returned by * HttpServletRequest.getServletPath() and * HttpServletRequest.getPathInfo() is * used to determine which mapping to return.

* If no mapping can be determined, it most likely means * that this particular request wasn't dispatched through * the {@link javax.faces.webapp.FacesServlet}. * * @param context the {@link FacesContext} of the current request * * @return the URL pattern of the {@link javax.faces.webapp.FacesServlet} * or null if no mapping can be determined * * @throws NullPointerException if context is null */ public static String getFacesMapping(FacesContext context) { if (context == null) { throw new NullPointerException("The FacesContext was null."); } // Check for a previously stored mapping ExternalContext extContext = context.getExternalContext(); String mapping = (String) extContext.getRequestMap().get(INVOCATION_PATH); if (mapping == null) { Object request = extContext.getRequest(); String servletPath = null; String pathInfo = null; // first check for javax.servlet.forward.servlet_path // and javax.servlet.forward.path_info for non-null // values. if either is non-null, use this // information to generate determine the mapping. if (request instanceof HttpServletRequest) { servletPath = extContext.getRequestServletPath(); pathInfo = extContext.getRequestPathInfo(); } mapping = getMappingForRequest(servletPath, pathInfo); } if (mapping != null) { extContext.getRequestMap().put(INVOCATION_PATH, mapping); } return mapping; } /** * This will create a ValueExpression for the given string * @param valueRef The expresion to create. For example, "#{foo}" * @param type The expected return type * @return */ public static ValueExpression createValueExpression(String valueRef, Class type) { FacesContext fc = FacesContext.getCurrentInstance(); ELContext elc = fc.getELContext(); return fc.getApplication().getExpressionFactory().createValueExpression(elc, valueRef, Object.class); } /** *

Returns true if the provided url-mapping is * a prefix path mapping (starts with /).

* * @param mapping a url-pattern * @return true if the mapping starts with / */ public static boolean isPrefixMapped(String mapping) { return (mapping.charAt(0) == '/'); } public static void renderPassThruAttributes(ResponseWriter writer, UIComponent component) throws IOException { renderPassThruAttributes(writer, component, null); } /** * Render any "passthru" attributes, where we simply just output the * raw name and value of the attribute. This method is aware of the * set of HTML4 attributes that fall into this bucket. Examples are * all the javascript attributes, alt, rows, cols, etc.

*/ public static void renderPassThruAttributes(ResponseWriter writer, UIComponent component, String[] excludes) throws IOException { int i = 0, len = passthruAttributes.length, j, jLen = (null != excludes ? excludes.length : 0); Object value = null; boolean skip = false; for (i = 0; i < len; i++) { skip = false; if (null != excludes) { for (j = 0; j < jLen; j++) { if (null != excludes[j] && excludes[j].equals(passthruAttributes[i])) { skip = true; break; } } } if (skip) { continue; } value = component.getAttributes().get(passthruAttributes[i]); if (value != null && shouldRenderAttribute(value)) { if (!(value instanceof String)) { value = value.toString(); } writer.writeAttribute(passthruAttributes[i], value, passthruAttributes[i]); } } } /** *

Return the appropriate {@link javax.faces.webapp.FacesServlet} mapping * based on the servlet path of the current request.

* * @param servletPath the servlet path of the request * @param pathInfo the path info of the request * * @return the appropriate mapping based on the current request * * @see HttpServletRequest#getServletPath() */ public static String getMappingForRequest(String servletPath, String pathInfo) { if (servletPath == null) { return null; } // If the path returned by HttpServletRequest.getServletPath() // returns a zero-length String, then the FacesServlet has // been mapped to '/*'. if (servletPath.length() == 0) { return "/*"; } // presence of path info means we were invoked // using a prefix path mapping if (pathInfo != null) { return servletPath; } else if (servletPath.indexOf('.') < 0) { // if pathInfo is null and no '.' is present, assume the // FacesServlet was invoked using prefix path but without // any pathInfo - i.e. GET /contextroot/faces or // GET /contextroot/faces/ return servletPath; } else { // Servlet invoked using extension mapping return servletPath.substring(servletPath.lastIndexOf('.')); } } /** * @return true if and only if the argument * attributeVal is an instance of a wrapper for a * primitive type and its value is equal to the default value for * that type as given in the spec. */ protected static boolean shouldRenderAttribute(Object attributeVal) { if (attributeVal instanceof Boolean && ((Boolean) attributeVal).booleanValue() == Boolean.FALSE.booleanValue()) { return false; } else if (attributeVal instanceof Integer && ((Integer) attributeVal).intValue() == Integer.MIN_VALUE) { return false; } else if (attributeVal instanceof Double && ((Double) attributeVal).doubleValue() == Double.MIN_VALUE) { return false; } else if (attributeVal instanceof Character && ((Character) attributeVal).charValue() == Character.MIN_VALUE) { return false; } else if (attributeVal instanceof Float && ((Float) attributeVal).floatValue() == Float.MIN_VALUE) { return false; } else if (attributeVal instanceof Short && ((Short) attributeVal).shortValue() == Short.MIN_VALUE) { return false; } else if (attributeVal instanceof Byte && ((Byte) attributeVal).byteValue() == Byte.MIN_VALUE) { return false; } else if (attributeVal instanceof Long && ((Long) attributeVal).longValue() == Long.MIN_VALUE) { return false; } return true; } public static void appendToConfig(StringBuilder config, String key, Object value, boolean quote, boolean needsComma) { config.append(needsComma ? "," : "").append(key).append(":"); if (quote) { config.append("'"); } config.append(value.toString()); if (quote) { config.append("'"); } } public static void appendToConfigIfNotNull(StringBuilder config, String key, Object value, boolean quote, boolean needsComma) { if (value != null) { appendToConfig(config, key, value, quote, needsComma); } } public static ResourceBundle getBundle(String baseName, String localeName, Class fallback) { ResourceBundle bundle = null; try { if (localeName == null) { localeName = "en_US"; } Locale locale = new Locale("en", "US"); String language = localeName; String country = null; String variant = null; int countryIndex = language.indexOf("_"); if (countryIndex > -1) { language = localeName.substring(0, countryIndex); int variantIndex = localeName.indexOf("-"); if (variantIndex > -1) { country = localeName.substring(countryIndex + 1, variantIndex); variant = localeName.substring(variantIndex + 1); locale = new Locale(language, country, variant); } else { country = localeName.substring(countryIndex + 1); locale = new Locale(language, country); } } else { locale = new Locale(localeName); } // Get the ClassLoader ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { if (fallback != null) { loader = fallback.getClass().getClassLoader(); } } bundle = ResourceBundle.getBundle(baseName, locale, loader); } catch (MissingResourceException ex) { Logger.getLogger(fallback.getName()).warning("Can't find bundle: " + baseName); ex.printStackTrace(); } return bundle; } public static String createResourceUrl(FacesContext context, String path) { return StaticResourcePhaseListener.createResourceUrl(context, path); } public static String getStaticResourceUrl(FacesContext fc, String path) { String url = fc.getExternalContext().getRequestContextPath() + createResourceUrl(fc, path); return url; } public static String formatDate(Date date, String format, Boolean useDefault) { String formattedDate = ""; if ((date != null) || useDefault) { if (date == null) { date = new Date(); } formattedDate = (date != null) ? new SimpleDateFormat(format).format(date) : new SimpleDateFormat(format).format(new Date()); } return formattedDate; } } // end of class Util




© 2015 - 2025 Weber Informatics LLC | Privacy Policy