Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
    *
    * Copyright (c) 2009-2013 Oracle and/or its affiliates. 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_1_1.html
   * or packager/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 packager/legal/LICENSE.txt.
   *
   * GPL Classpath Exception:
   * Oracle designates this particular file as subject to the "Classpath"
   * exception as provided by Oracle in the GPL Version 2 section of the License
   * file that accompanied this code.
   *
   * Modifications:
   * If applicable, add the following below the License Header, with the fields
   * enclosed by brackets [] replaced by your own identifying information:
   * "Portions Copyright [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 org.glassfish.admin.rest.utils;
  
  import java.net.URI;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Locale;
  import java.util.Map;
  import java.util.Set;
  import java.util.TreeMap;
  import static org.glassfish.admin.rest.provider.ProviderUtil.getElementLink;
  import static org.glassfish.admin.rest.utils.Util.eleminateHypen;
  import static org.glassfish.admin.rest.utils.Util.getHtml;
  import static org.glassfish.admin.rest.utils.Util.localStrings;
  import static org.glassfish.admin.rest.utils.Util.methodNameFromDtdName;
  import  org.glassfish.hk2.api.MultiException;
  import  org.glassfish.hk2.api.ServiceLocator;
 import  org.glassfish.jersey.media.sse.EventOutput;
 
 import  org.jvnet.hk2.config.Attribute;
 import  org.jvnet.hk2.config.ConfigBeanProxy;
 import  org.jvnet.hk2.config.ConfigModel;
 import  org.jvnet.hk2.config.Dom;
 import  org.jvnet.hk2.config.DomDocument;

Resource utilities class. Used by resource templates, TemplateListOfResource and TemplateRestResource

Author(s):
Rajeshwar Patil
 
 public class ResourceUtil {
     private static final String DAS_LOOK_FOR_CERT_PROPERTY_NAME = "org.glassfish.admin.DASCheckAdminCert";
     private static final String MESSAGE_PARAMETERS = "messageParameters";
     private static RestConfig restConfig = null;
     // TODO: this is copied from org.jvnet.hk2.config.Dom. If we are not able to encapsulate the conversion in Dom,
     // need to make sure that the method convertName is refactored into smaller methods such that trimming of prefixes
     // stops. We will need a promotion of HK2 for this.
     static final Pattern TOKENIZER;
 
     static {
         String pattern = or(
                 split("x""X"), // AbcDef -> Abc|Def
                 split("X""Xx"), // USArmy -> US|Army
                 //split("\\D","\\d"), // SSL2 -> SSL|2
                 split("\\d""\\D"// SSL2Connector -> SSL|2|Connector
                 );
         pattern = pattern.replace("x""\\p{Lower}").replace("X""\\p{Upper}");
          = Pattern.compile(pattern);
     }
 
     protected static byte[] getBytesFromStream(final InputStream is) {
         final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
         byte[] bytes = null;
         int nRead;
         byte[] data = new byte[16384];
         try {
             while ((nRead = is.read(data, 0, data.length)) != -1) {
                 buffer.write(data, 0, nRead);
             }
             buffer.flush();
             bytes = buffer.toByteArray();
             buffer.close();
         } catch (IOException ex) {
             ..log(.nullex);
         }
 
         return bytes;
     }
 
     private ResourceUtil() {
     }

    
Adjust the input parameters. In case of POST and DELETE methods, user can provide name, id or DEFAULT parameter for primary parameter(i.e the object to create or delete). This method is used to rename primary parameter name to DEFAULT irrespective of what user provides.
 
     public static void adjustParameters(Map<StringStringdata) {
         if (data != null) {
             if (!(data.containsKey("DEFAULT"))) {
                 boolean isRenamed = renameParameter(data"id""DEFAULT");
                 if (!isRenamed) {
                     renameParameter(data"name""DEFAULT");
                 }
             }
         }
     }

    
Adjust the input parameters. In case of POST and DELETE methods, user can provide id or DEFAULT parameter for primary parameter(i.e the object to create or delete). This method is used to rename primary parameter name to DEFAULT irrespective of what user provides.
 
     public static void defineDefaultParameters(Map<StringStringdata) {
         if (data != null) {
             if (!(data.containsKey("DEFAULT"))) {
                 renameParameter(data"id""DEFAULT");
             }
         }
     }

    
Returns the name of the command associated with this resource,if any, for the given operation.

Parameters:
type the given resource operation
Returns:
String the associated command name for the given operation.
 
     public static String getCommand(RestRedirect.OpType type, ConfigModel model) {
 
         Class<? extends ConfigBeanProxy> cbp = null;
         try {
             cbp = (Class<? extends ConfigBeanProxy>) model.classLoaderHolder.loadClass(model.targetTypeName);
         } catch (MultiException e) {
             e.printStackTrace();
         }
 
         if (cbp != null) {
             RestRedirects restRedirects = cbp.getAnnotation(RestRedirects.class);
             if (restRedirects != null) {
                 RestRedirect[] values = restRedirects.value();
                 for (RestRedirect r : values) {
                     if (r.opType().equals(type)) {
                         return r.commandName();
                     }
                 }
             }
         }
         return null;
     }

    
Executes the specified __asadmin command.

Parameters:
commandName
parameters
subject
Returns:
 
     public static RestActionReporter runCommand(String commandName,
                                                 ParameterMap parameters,
                                                 Subject subject) {
         CommandRunner cr = Globals.getDefaultHabitat().getService(CommandRunner.class);
         RestActionReporter ar = new RestActionReporter();
         final CommandInvocation commandInvocation =
                 cr.getCommandInvocation(commandNamearsubject);
         commandInvocation.parameters(parameters).execute();
         addCommandLog(arcommandNameparameters);
 
         return ar;
     }

    
Executes the specified __asadmin command.

Parameters:
commandName the command to execute
parameters the command parameters
subject Subject
Returns:
ActionReport object with command execute status details.
 
     public static RestActionReporter runCommand(String commandName,
                                                 Map<StringStringparameters,
                                                 Subject subject) {
         ParameterMap p = new ParameterMap();
         for (Map.Entry<StringStringentry : parameters.entrySet()) {
             p.set(entry.getKey(), entry.getValue());
         }
 
         return runCommand(commandNamepsubject);
     }
 
     public static EventOutput runCommandWithSse(final String commandName,
                                                 final ParameterMap parameters,
                                                 final Subject subject,
                                                 final SseCommandHelper.ActionReportProcessor processor) {
         CommandRunner cr = Globals.getDefaultHabitat().getService(CommandRunner.class);
         final RestActionReporter ar = new RestActionReporter();
         final CommandInvocation commandInvocation =
             cr.getCommandInvocation(commandNamearsubject).
             parameters(parameters);
         return SseCommandHelper.invokeAsync(commandInvocation,
                     new SseCommandHelper.ActionReportProcessor() {
                             @Override
                             public ActionReport process(ActionReport report, EventOutput ec) {
                                 addCommandLog(arcommandNameparameters);
                                 if (processor != null) {
                                     return processor.process(reportec);
                                 }
                                 return ar;
                             }
                         });
     }
 
 
     public static void addCommandLog(RestActionReporter arString commandNameParameterMap parameters) {
         List<Stringlogs = (List<String>) ar.getExtraProperties().get("commandLog");
         if (logs == null) {
             logs = new ArrayList<String>();
             ar.getExtraProperties().put("commandLog"logs);
         }
         final String parameterList = encodeString(getParameterList(parameters));
 
         logs.add(commandName + parameterList);
     }
 
     public static String encodeString(String text) {
         if (text == null) {
             return "";
         }
         String result = text.replaceAll("<""&lt;").replaceAll(">""&gt;");
         result = result.replaceAll("eval\\((.*)\\)""");
         result = result.replaceAll("[\\\"\\\'][\\s]*((?i)javascript):(.*)[\\\"\\\']""\"\"");
         result = result.replaceAll("((?i)script)""");
         return result;
     }
 
     public static String getParameterList(ParameterMap parameters) {
         StringBuilder sb = new StringBuilder();
 
         for (Map.Entry<StringList<String>> entry : parameters.entrySet()) {
             String paramName = entry.getKey();
             for (String param : entry.getValue()) {
                 sb.append(" --").append(paramName).append(" ").append(param);
             }
         }
 
         return sb.toString();
     }

    
Constructs and returns the resource method meta-data.

Parameters:
command the command associated with the resource method
habitat the habitat
logger the logger to use
Returns:
MethodMetaData the meta-data store for the resource method.
 
     public static MethodMetaData getMethodMetaData(String command, ServiceLocator habitatLogger logger) {
         return getMethodMetaData(commandnullhabitatlogger);
     }

    
Constructs and returns the resource method meta-data.

Parameters:
command the command associated with the resource method
commandParamsToSkip the command parameters for which not to include the meta-data.
habitat the habitat
logger the logger to use
Returns:
MethodMetaData the meta-data store for the resource method.
 
     public static MethodMetaData getMethodMetaData(String commandHashMap<StringStringcommandParamsToSkip,
             ServiceLocator habitatLogger logger) {
         MethodMetaData methodMetaData = new MethodMetaData();
 
         if (command != null) {
             Collection<CommandModel.ParamModelparams;
             if (commandParamsToSkip == null) {
                 params = getParamMetaData(commandhabitatlogger);
             } else {
                 params = getParamMetaData(commandcommandParamsToSkip.keySet(), habitatlogger);
             }
 
             if (params != null) {
                 Iterator<CommandModel.ParamModeliterator = params.iterator();
                 CommandModel.ParamModel paramModel;
                 while (iterator.hasNext()) {
                     paramModel = iterator.next();
                     Param param = paramModel.getParam();
                     ParameterMetaData parameterMetaData = getParameterMetaData(paramModel);
 
                     String parameterName = (param.primary()) ? "id" : paramModel.getName();
 
                     // If the Param has an alias, use it instead of the name
                     String alias = param.alias();
                     if (alias != null && (!alias.isEmpty())) {
                         parameterName = alias;
                     }
 
 
                     methodMetaData.putParameterMetaData(parameterNameparameterMetaData);
                 }
             }
         }
 
         return methodMetaData;
     }
 
     public static void resolveParamValues(Map<StringStringcommandParamsUriInfo uriInfo) {
         List<PathSegmentpathSegments = uriInfo.getPathSegments();
         Map<StringStringprocessParams = new HashMap<StringString>();
         processParams.putAll(commandParams);
 
         for (Map.Entry<StringStringentry : commandParams.entrySet()) {
             String value = entry.getValue();
             if (value.equals(.)) {
                 processParams.put(entry.getKey(), pathSegments.get(pathSegments.size() - 2).getPath());
             } else if (value.startsWith(.)) {
                 int number =
                         (value.equals(.))
                         ? 1 : // no number given
                         Integer.parseInt(value.substring(..length()));
 
                 processParams.put(entry.getKey(), pathSegments.get(pathSegments.size() - (number + 2)).getPath());
             }
         }
 
         commandParams.clear();
         commandParams.putAll(processParams);
     }

    
Constructs and returns the resource method meta-data. This method is called to get meta-data in case of update method (POST).

Parameters:
configBeanModel the config bean associated with the resource.
Returns:
MethodMetaData the meta-data store for the resource method.
 
     public static MethodMetaData getMethodMetaData(ConfigModel configBeanModel) {
         MethodMetaData methodMetaData = new MethodMetaData();
 
         Class<? extends ConfigBeanProxy> configBeanProxy = null;
         try {
             configBeanProxy = (Class<? extends ConfigBeanProxy>) configBeanModel.classLoaderHolder
                     .loadClass(configBeanModel.targetTypeName);
 
             Set<StringattributeNames = configBeanModel.getAttributeNames();
             for (String attributeName : attributeNames) {
                 String methodName = getAttributeMethodName(attributeName);
                 Method method = null;
                 try {
                     method = configBeanProxy.getMethod(methodName);
                 } catch (NoSuchMethodException e) {
                     // Method not found, so let's try a brute force method if the method
                     // can't be found via the method above.  For example: for
                     // Ssl.getSSLInactivityTimeout(), we calculate getSslInactivityTimeout,
                     // which doesn't match due to case.
                     for (Method m : configBeanProxy.getMethods()) {
                         if (m.getName().equalsIgnoreCase(methodName)) {
                             method = m;
                         }
                     }
                 }
                 Attribute attribute = method.getAnnotation(Attribute.class);
                 if (attribute != null) {
                     ParameterMetaData parameterMetaData = getParameterMetaData(attribute);
                     if (method.getAnnotation(Deprecated.class) != null) {
                         parameterMetaData.putAttribute(."true");
                     }
 
                     //camelCase the attributeName before passing out
                     attributeName = eleminateHypen(attributeName);
 
                     methodMetaData.putParameterMetaData(attributeNameparameterMetaData);
 
                 }
             }
         } catch (MultiException e) {
             e.printStackTrace();
         }
 
         return methodMetaData;
     }
 
     public static MethodMetaData getMethodMetaData2(Dom parent, ConfigModel childModelint parameterType) {
         MethodMetaData methodMetaData = new MethodMetaData();
         List<Class<?>> interfaces = new ArrayList<Class<?>>();
         Map<StringParameterMetaDataparams = new HashMap<StringParameterMetaData>();
 
         try {
             Class<? extends ConfigBeanProxy> configBeanProxy =
                     (Class<? extends ConfigBeanProxy>) childModel.classLoaderHolder.loadClass(childModel.targetTypeName);
             getInterfaces(configBeanProxyinterfaces);
 
             Set<StringattributeNames = childModel.getAttributeNames();
             for (String attributeName : attributeNames) {
                 String methodName = ResourceUtil.getAttributeMethodName(attributeName);
 
                 //camelCase the attributeName before passing out
                 attributeName = Util.eleminateHypen(attributeName);
 
                 ParameterMetaData parameterMetaData = params.get(attributeName);
                 if (parameterMetaData == null) {
                     parameterMetaData = new ParameterMetaData();
                     params.put(attributeNameparameterMetaData);
                 }
                 // Check parent interfaces
                 for (int i = interfaces.size() - 1; i >= 0; i--) {
                     Class<?> intf = interfaces.get(i);
                     try {
                         Method method = intf.getMethod(methodName);
                         Attribute attribute = method.getAnnotation(Attribute.class);
                         if (attribute != null) {
                             ParameterMetaData localParam = ResourceUtil.getParameterMetaData(attribute);
                             copyParameterMetaDataAttribute(localParamparameterMetaData.);
                             copyParameterMetaDataAttribute(localParamparameterMetaData.);
                             copyParameterMetaDataAttribute(localParamparameterMetaData.);
                             copyParameterMetaDataAttribute(localParamparameterMetaData.);
                         }
                     } catch (NoSuchMethodException e) {
                     }
                 }
 
                 // Check ConfigBean
                 try {
                     Method method = configBeanProxy.getMethod(methodName);
                     Attribute attribute = method.getAnnotation(Attribute.class);
                     if (attribute != null) {
                         ParameterMetaData localParam = ResourceUtil.getParameterMetaData(attribute);
                         copyParameterMetaDataAttribute(localParamparameterMetaData.);
                         copyParameterMetaDataAttribute(localParamparameterMetaData.);
                         copyParameterMetaDataAttribute(localParamparameterMetaData.);
                         copyParameterMetaDataAttribute(localParamparameterMetaData.);
                     }
                 } catch (NoSuchMethodException e) {
                 }
 
 
                 methodMetaData.putParameterMetaData(attributeNameparameterMetaData);
 
             }
         } catch (MultiException cnfe) {
             throw new RuntimeException(cnfe);
         }
 
         return methodMetaData;
     }
 
     protected static void copyParameterMetaDataAttribute(ParameterMetaData fromParameterMetaData toString key) {
         if (from.getAttributeValue(key) != null) {
             to.putAttribute(keyfrom.getAttributeValue(key));
         }
     }
 
     protected static void getInterfaces(Class<?> clazzList<Class<?>> interfaces) {
         for (Class<?> intf : clazz.getInterfaces()) {
             interfaces.add(intf);
             getInterfaces(intfinterfaces);
         }
     }
 
     /*
      * test if a command really exists in the current runningVM
      */
     public static boolean commandIsPresent(ServiceLocator habitatString commandName) {
         try {
             habitat.getService(AdminCommand.classcommandName);
             return true;
         } catch (Exception e) {
 
         }
         return false;
     }

    
Constructs and returns the parameter meta-data.

Parameters:
commandName the command associated with the resource method
habitat the habitat
logger the logger to use
Returns:
Collection the meta-data for the parameter of the resource method.
 
             String commandName, ServiceLocator habitatLogger logger) {
         final CommandModel model = habitat.<CommandRunner>getService(CommandRunner.class).getModel(commandNamelogger);
         if (model == null) {
             return null;
         }
 
         return model.getParameters();
     }

    
Constructs and returns the parameter meta-data.

Parameters:
commandName the command associated with the resource method
commandParamsToSkip the command parameters for which not to include the meta-data.
habitat the habitat
logger the logger to use
Returns:
Collection the meta-data for the parameter of the resource method.
 
             String commandNameCollection<StringcommandParamsToSkip,
             ServiceLocator habitatLogger logger) {
         CommandModel cm = habitat.<CommandRunner>getService(CommandRunner.class).getModel(commandNamelogger);
         Collection<StringparameterNames = cm.getParametersNames();
 
         ArrayList<CommandModel.ParamModelmetaData = new ArrayList<CommandModel.ParamModel>();
         CommandModel.ParamModel paramModel;
         for (String name : parameterNames) {
             paramModel = cm.getModelFor(name);
             String parameterName = (paramModel.getParam().primary()) ? "id" : paramModel.getName();
 
             boolean skipParameter = false;
             try {
                 skipParameter = commandParamsToSkip.contains(parameterName);
             } catch (Exception e) {
                 // TODO: logging bundle lookup?
                 String errorMessage = .getLocalString("rest.metadata.skip.error",
                         "Parameter \"{0}\" may be redundant and not required.",
                         new Object[]{parameterName});
                 // TODO: Why are we logging twice?
                 ..log(.nullerrorMessage);
                 ..log(.nulle);
             }
 
             if (!skipParameter) {
                 metaData.add(paramModel);
             }
         }
 
         //print(metaData);
         return metaData;
     }
 
     //removes entries with empty value from the given Map
     public static void purgeEmptyEntries(Map<StringStringdata) {
 
         //hack-2 : remove empty entries if the form has a hidden param for __remove_empty_entries__
 
         if ("true".equals(data.get("__remove_empty_entries__"))) {
             data.remove("__remove_empty_entries__");
             //findbug
             for (Iterator<Map.Entry<StringString>> i = data.entrySet().iterator(); i.hasNext();) {
                 Map.Entry<StringStringentry = i.next();
                 String value = entry.getValue();
                 if ((value == null) || (value.length() < 1)) {
                     i.remove();
                 }
             }
         }
     }

    
Constructs and returns the appropriate response object based on the client.

Parameters:
status the http status code for the response
message message for the response
requestHeaders request headers of the request
Returns:
Response the response object to be returned to the client
 
     public static Response getResponse(int statusString messageHttpHeaders requestHeadersUriInfo uriInfo) {
         if (isBrowser(requestHeaders)) {
             message = getHtml(messageuriInfofalse);
         }
         return Response.status(status).entity(message).build();
     }
 
     public static ActionReportResult getActionReportResult(ActionReport.ExitCode statusString messageHttpHeaders requestHeadersUriInfo uriInfo) {
         RestActionReporter ar = new RestActionReporter();
         ar.setActionExitCode(status);
         return getActionReportResult(armessagerequestHeadersuriInfo);
     }
 
     public static ActionReportResult getActionReportResult(RestActionReporter arString messageHttpHeaders requestHeadersUriInfo uriInfo) {
         if (isBrowser(requestHeaders)) {
             message = getHtml(messageuriInfofalse);
         }
         ActionReport.ExitCode status = ar.getActionExitCode();
         ActionReportResult result = new ActionReportResult(ar);
 
         if (status != .. && status != ..) {
             result.setErrorMessage(message);
             result.setIsError(true);
         }
 
         ar.setActionExitCode(status);
         ar.setMessage(message);
         return result;
     }

    
special case for the delete operation: we need to give back the URI of the parent since the resource we are on is deleted

Parameters:
status
message
requestHeaders
uriInfo
Returns:
 
     // FIXME: This doesn't do what the javadoc says it should
     public static Response getDeleteResponse(int statusString message,
             HttpHeaders requestHeadersUriInfo uriInfo) {
         if (isBrowser(requestHeaders)) {
             message = getHtml(messageuriInfotrue);
         }
         return Response.status(status).entity(message).build();
     }

    

This method takes any query string parameters and adds them to the specified map. This is used, for example, with the delete operation when cascading deletes are required:

DELETE http://localhost:4848/.../foo?cascade=true

The reason we need to use query parameters versus "body" variables is the limitation that HttpURLConnection has in this regard.

Parameters:
data
 
     public static void addQueryString(MultivaluedMap<StringStringqsMap<StringStringdata) {
         for (Map.Entry<StringList<String>> entry : qs.entrySet()) {
             String key = entry.getKey();
             for (String value : entry.getValue()) {
                 try {
                     data.put(URLDecoder.decode(key"UTF-8"), URLDecoder.decode(value"UTF-8")); // TODO: Last one wins? Can't imagine we'll see List.size() > 1, but...
                 } catch (UnsupportedEncodingException ex) {
                     Logger.getLogger(ResourceUtil.class.getName()).log(.nullex);
                 }
             }
         }
     }
 
     public static void addQueryString(MultivaluedMap<StringStringqsProperties data) {
         for (Map.Entry<StringList<String>> entry : qs.entrySet()) {
             String key = entry.getKey();
             for (String value : entry.getValue()) {
                 data.put(keyvalue); // TODO: Last one wins? Can't imagine we'll see List.size() > 1, but...
             }
         }
     }
 
     //Construct parameter meta-data from the model
         Param param = paramModel.getParam();
         ParameterMetaData parameterMetaData = new ParameterMetaData();
 
         parameterMetaData.putAttribute(.getXsdType(paramModel.getType().toString()));
         parameterMetaData.putAttribute(., Boolean.toString(param.optional()));
         String val = param.defaultValue();
         if ((val != null) && (!val.equals("\u0000"))) {
             parameterMetaData.putAttribute(.param.defaultValue());
         }
         parameterMetaData.putAttribute(.param.acceptableValues());
 
         return parameterMetaData;
     }
 
     //Construct parameter meta-data from the attribute annotation
     static ParameterMetaData getParameterMetaData(Attribute attribute) {
         ParameterMetaData parameterMetaData = new ParameterMetaData();
         parameterMetaData.putAttribute(.getXsdType(attribute.dataType().toString()));
         parameterMetaData.putAttribute(., Boolean.toString(!attribute.required()));
         if (!(attribute.defaultValue().equals("\u0000"))) {
             parameterMetaData.putAttribute(.attribute.defaultValue());
         }
         parameterMetaData.putAttribute(., Boolean.toString(attribute.key()));
         //FIXME - Currently, Attribute class does not provide acceptable values.
         //parameterMetaData.putAttribute(Contants.ACCEPTABLE_VALUES,
         //    getXsdType(attribute.acceptableValues()));
 
         return parameterMetaData;
     }
 
     //rename the given input parameter
     private static boolean renameParameter(Map<StringStringdata,
             String parameterToRenameString newName) {
         if ((data.containsKey(parameterToRename))) {
             String value = data.get(parameterToRename);
             data.remove(parameterToRename);
             data.put(newNamevalue);
             return true;
         }
         return false;
     }
 
     //returns true only if the request is from browser
     private static boolean isBrowser(HttpHeaders requestHeaders) {
         boolean isClientAcceptsHtml = false;
         MediaType media = requestHeaders.getMediaType();
         java.util.List<StringacceptHeaders =
                 requestHeaders.getRequestHeader(.);
 
         for (String header : acceptHeaders) {
             if (header.contains(.)) {
                 isClientAcceptsHtml = true;
                 break;
             }
         }
 
         if (media != null) {
             if ((media.equals(.))
                     && (isClientAcceptsHtml)) {
                 return true;
             }
         }
 
         return false;
     }
 
     private static String getXsdType(String javaType) {
         if (javaType.indexOf(.) != -1) {
             return .;
         }
         if (javaType.indexOf(.) != -1) {
             return .;
         }
         if (javaType.indexOf(.) != -1) {
             return .;
         }
         if (javaType.indexOf(.) != -1) {
             return .;
         }
         return javaType;
     }
 
     public static String getAttributeMethodName(String attributeName) {
         return methodNameFromDtdName(attributeName"get");
     }
 
     private static String split(String lookbackString lookahead) {
         return "((?<=" + lookback + ")(?=" + lookahead + "))";
     }
 
     private static String or(String... tokens) {
         StringBuilder buf = new StringBuilder();
         for (String t : tokens) {
             if (buf.length() > 0) {
                 buf.append('|');
             }
             buf.append(t);
         }
         return buf.toString();
     }
 
     public static String convertToXMLName(String name) {
         // tokenize by finding 'x|X' and 'X|Xx' then insert '-'.
         StringBuilder buf = new StringBuilder(name.length() + 5);
         for (String t : .split(name)) {
             if (buf.length() > 0) {
                 buf.append('-');
             }
             buf.append(t.toLowerCase(.));
         }
         return buf.toString();
     }

    

Returns:
A copy of given sourceData where key of each entry from it is converted to xml name
 
     public static HashMap<StringStringtranslateCamelCasedNamesToXMLNames(Map<StringStringsourceData) {
         HashMap<StringStringconvertedData = new HashMap<StringString>(sourceData.size());
         for (Map.Entry<StringStringentry : sourceData.entrySet()) {
             String camelCasedKeyName = entry.getKey();
             String xmlKeyName = convertToXMLName(camelCasedKeyName);
             convertedData.put(xmlKeyNameentry.getValue());
         }
         return convertedData;
     }
 
     /*
      * we try to prefer html by default for all browsers (safari, chrome,
      * firefox). Same if the request is asking for "*" among all the possible
      * AcceptableMediaTypes
      */
     public static String getResultType(HttpHeaders requestHeaders) {
         String result = "html";
         String firstOne = null;
         List<MediaTypelmt = requestHeaders.getAcceptableMediaTypes();
         for (MediaType mt : lmt) {
             if (mt.getSubtype().equals("html")) {
                 return result;
             }
             if (mt.getSubtype().equals("*")) {
                 return result;
             }
             if (firstOne == null) { //default to the first one if many are there.
                 firstOne = mt.getSubtype();
             }
         }
 
         if (firstOne != null) {
             return firstOne;
         } else {
             return result;
         }
     }
 
     public static Map buildMethodMetadataMap(MethodMetaData mmd) { // yuck
         Map<StringMapmap = new TreeMap<StringMap>();
         Set<Stringparams = mmd.parameters();
         Iterator<Stringiterator = params.iterator();
         String param;
         while (iterator.hasNext()) {
             param = iterator.next();
             ParameterMetaData parameterMetaData = mmd.getParameterMetaData(param);
             map.put(paramprocessAttributes(parameterMetaData.attributes(), parameterMetaData));
         }
 
         return map;
     }
 
     private static Map<StringStringprocessAttributes(Set<StringattributesParameterMetaData parameterMetaData) {
         Map<StringStringpmdm = new HashMap<StringString>();
 
         Iterator<Stringattriter = attributes.iterator();
         String attributeName;
         while (attriter.hasNext()) {
             attributeName = attriter.next();
             String attributeValue = parameterMetaData.getAttributeValue(attributeName);
             pmdm.put(attributeNameattributeValue);
         }
 
         return pmdm;
     }
 
     /*
      * REST can now be configured via RestConfig to show or hide the deprecated
      * elements and attributes @return true if this model is deprecated
      */
     static public boolean isDeprecated(ConfigModel model) {
         try {
             Class<? extends ConfigBeanProxy> cbp = (Class<? extends ConfigBeanProxy>) model.classLoaderHolder.loadClass(model.targetTypeName);
             Deprecated dep = cbp.getAnnotation(Deprecated.class);
             return dep != null;
         } catch (MultiException e) {
             //e.printStackTrace();
         }
         return false;
 
     }
 
     public static Map<StringStringgetResourceLinks(Dom domUriInfo uriInfoboolean canShowDeprecated) {
         Map<StringStringlinks = new TreeMap<StringString>();
 
         for (String elementName : dom.model.getElementNames()) { //for each element
             if (elementName.equals("*")) {
                 ConfigModel.Node node = (ConfigModel.Node) dom.model.getElement(elementName);
                 ConfigModel childModel = node.getModel();
                 List<ConfigModel> lcm = getRealChildConfigModels(childModeldom.document);
 
                 Collections.sort(lcmnew ConfigModelComparator());
                 if (lcm != null) {
                     for (ConfigModel cmodel : lcm) {
                         if ((!isDeprecated(cmodel) || canShowDeprecated)) {
                             links.put(cmodel.getTagName(), ProviderUtil.getElementLink(uriInfocmodel.getTagName()));
                         }
                     }
                 }
 
             } else {
                 ConfigModel.Property childElement = dom.model.getElement(elementName);
                 boolean deprec = false;
 
                 if (childElement instanceof ConfigModel.Node) {
                     ConfigModel.Node node = (ConfigModel.Node) childElement;
                     deprec = isDeprecated(node.getModel());
                 }
                 for (String annotation : childElement.getAnnotations()) {
                     if (annotation.equals(Deprecated.class.getName())) {
                         deprec = true;
                     }
                 }
                 if ((!deprec || canShowDeprecated)) {
                     links.put(elementName, ProviderUtil.getElementLink(uriInfoelementName));
                 }
 
             }
         }
 
         String beanName = getUnqualifiedTypeName(dom.model.targetTypeName);
 
         for (CommandResourceMetaData cmd : CommandResourceMetaData.getCustomResourceMapping(beanName)) {
             links.put(cmd.resourcePath, ProviderUtil.getElementLink(uriInfocmd.resourcePath));
         }
 
         return links;
     }

    

Parameters:
qualifiedTypeName
Returns:
unqualified type name for given qualified type name. This is a substring of qualifiedTypeName after last "."
 
     public static String getUnqualifiedTypeName(String qualifiedTypeName) {
         return qualifiedTypeName.substring(qualifiedTypeName.lastIndexOf(".") + 1, qualifiedTypeName.length());
     }
 
     public static boolean isOnlyATag(ConfigModel model) {
         return (model.getAttributeNames().isEmpty()) && (model.getElementNames().isEmpty());
     }
 
     public static List<ConfigModel> getRealChildConfigModels(ConfigModel childModel, DomDocument domDocument) {
         List<ConfigModel> retlist = new ArrayList<ConfigModel>();
         try {
             Class<?> subType = childModel.classLoaderHolder.loadClass(childModel.targetTypeName);
             List<ConfigModel> list = domDocument.getAllModelsImplementing(subType);
 
             if (list != null) {
                 for (ConfigModel el : list) {
                     if (isOnlyATag(el)) { //this is just a tag element
                         retlist.addAll(getRealChildConfigModels(eldomDocument));
                     } else {
                         retlist.add(el);
                     }
                 }
             } else {//https://glassfish.dev.java.net/issues/show_bug.cgi?id=12654
                 if (!isOnlyATag(childModel)) { //this is just a tag element
                     retlist.add(childModel);
                 }
 
             }
         } catch (ClassNotFoundException e) {
             throw new RuntimeException(e);
         }
         return retlist;
    }

    

Parameters:
model
Returns:
name of the key attribute for the given model.
    private static String getKey(Dom model) {
        String key = model.getKey();
        if (key == null) {
            for (String s : model.getAttributeNames()) {//no key, by default use the name attr
                if (s.equals("name")) {
                    key = model.attribute(s);
                }
            }
            if (key == null)//nothing, so pick the first one
            {
                Set<StringattributeNames = model.getAttributeNames();
                if (!attributeNames.isEmpty()) {
                    key = model.attribute(attributeNames.iterator().next());
                } else {
                    //TODO carried forward from old generator. Should never reach here. But we do for ConfigExtension and WebModuleConfig
                    key = "ThisIsAModelBug:NoKeyAttr"//no attr choice fo a key!!! Error!!!
                    key = "";
                }
            }
        }
        return key;
    }
    public static Map<StringStringgetResourceLinks(List<Dom> proxyListUriInfo uriInfo) {
        Map<StringStringlinks = new TreeMap<StringString>();
        Collections.sort(proxyListnew DomConfigurator());
        for (Dom proxy : proxyList) { //for each element
            try {
                links.put(
                        getKey(proxy),
                        getElementLink(uriInfogetKey(proxy)));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return links;
    }
    public static List<Map<StringString>> getCommandLinks(String[][] commandResourcesPaths) {
        List<Map<StringString>> commands = new ArrayList<Map<StringString>>();
        for (String[] array : commandResourcesPaths) {
            Map<StringStringcommand = new HashMap<StringString>();
            command.put("command"array[0]);
            command.put("method"array[1]);
            command.put("path"array[2]);
            commands.add(command);
        }
        return commands;
    }
    public static void addMethodMetaData(ActionReport arMap<StringMethodMetaDatammd) {
        List<MapmethodMetaData = new ArrayList<Map>();
        MethodMetaData getMetaData = mmd.get("GET");
        methodMetaData.add(new HashMap() {
            {
                put("name""GET");
            }
        });
        if (getMetaData != null) { //are they extra params for a GET command?
            Map<StringObjectgetMetaDataMap = new HashMap<StringObject>();
            if (getMetaData.sizeParameterMetaData() > 0) {
                getMetaDataMap.put(buildMethodMetadataMap(getMetaData));
            }
            methodMetaData.add(getMetaDataMap);
        }
        MethodMetaData postMetaData = mmd.get("POST");
        Map<StringObjectpostMetaDataMap = new HashMap<StringObject>();
        if (postMetaData != null) {
            postMetaDataMap.put("name""POST");
//            if (postMetaData.sizeQueryParamMetaData() > 0) {
//                postMetaDataMap.put(QUERY_PARAMETERS, buildMethodMetadataMap(postMetaData, true));
//            }
            if (postMetaData.sizeParameterMetaData() > 0) {
                postMetaDataMap.put(buildMethodMetadataMap(postMetaData));
            }
            methodMetaData.add(postMetaDataMap);
        }
        MethodMetaData deleteMetaData = mmd.get("DELETE");
        if (deleteMetaData != null) {
            Map<StringObjectdeleteMetaDataMap = new HashMap<StringObject>();
            deleteMetaDataMap.put("name""DELETE");
            deleteMetaDataMap.put(buildMethodMetadataMap(deleteMetaData));
            methodMetaData.add(deleteMetaDataMap);
        }
        ar.getExtraProperties().put("methods"methodMetaData);
    }
    public static synchronized RestConfig getRestConfig(ServiceLocator habitat) {
        if ( == null) {
            if (habitat == null) {
                return null;
            }
            Domain domain = habitat.getService(Domain.class);
            if (domain != null) {
                Config config = domain.getConfigNamed("server-config");
                if (config != null) {
                     = config.getExtensionByType(RestConfig.class);
                }
            }
        }
        return ;
    }
    /*
     * returns true if the HTML viewer displays the deprecated elements or
     * attributes of a config bean
     */
    public static boolean canShowDeprecatedItems(ServiceLocator habitat) {
        RestConfig rg = getRestConfig(habitat);
        if ((rg != null) && (rg.getShowDeprecatedItems().equalsIgnoreCase("true"))) {
            return true;
        }
        return false;