View Javadoc
1   /**
2    * Copyright 2011-2019 PrimeFaces Extensions
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.primefaces.extensions.config;
17  
18  import javax.faces.context.FacesContext;
19  import javax.servlet.ServletContext;
20  import org.primefaces.util.LangUtils;
21  
22  /**
23   * @since 8.0.1
24   */
25  public class PrimeExtensionsEnvironment {
26  
27      public static final String INSTANCE_KEY = PrimeExtensionsEnvironment.class.getName();
28  
29      private boolean libphonenumberAvailable;
30  
31      public PrimeExtensionsEnvironment(FacesContext facesContext) {
32          libphonenumberAvailable = LangUtils.tryToLoadClassForName("com.google.i18n.phonenumbers.Phonenumber") != null;
33      }
34  
35      public static PrimeExtensionsEnvironment getCurrentInstance(FacesContext context) {
36          if (context == null || context.getExternalContext() == null) {
37              return null;
38          }
39  
40          PrimeExtensionsEnvironment pfeEnv = getFromContext(context);
41          if (pfeEnv == null) {
42              pfeEnv = new PrimeExtensionsEnvironment(context);
43              setCurrentInstance(pfeEnv, context);
44          }
45  
46          return pfeEnv;
47      }
48  
49      private static PrimeExtensionsEnvironment getFromContext(FacesContext context) {
50          return (PrimeExtensionsEnvironment) context.getExternalContext().getApplicationMap().get(INSTANCE_KEY);
51      }
52  
53      public static void setCurrentInstance(PrimeExtensionsEnvironment pfeEnv, FacesContext context) {
54          context.getExternalContext().getApplicationMap().put(INSTANCE_KEY, pfeEnv);
55  
56          if (context.getExternalContext().getContext() instanceof ServletContext) {
57              ((ServletContext) context.getExternalContext().getContext()).setAttribute(INSTANCE_KEY, pfeEnv);
58          }
59      }
60  
61      public boolean isLibphonenumberAvailable() {
62          return libphonenumberAvailable;
63      }
64  
65  }