示例#1
0
  private void loadCustomAMF3Serializer(XMap element, boolean custom) {
    XMap amf3Serializer = element.getOne("amf3-serializer");
    if (amf3Serializer != null) {
      String type = amf3Serializer.get("@type");
      try {
        Class<AMF3Serializer> amf3SerializerClass = TypeUtil.forName(type, AMF3Serializer.class);
        amf3SerializerConstructor =
            TypeUtil.getConstructor(amf3SerializerClass, new Class<?>[] {OutputStream.class});
      } catch (Exception e) {
        throw new GraniteConfigException(
            "Could not get constructor for AMF3 serializer: " + type, e);
      }
    }

    XMap amf3Deserializer = element.getOne("amf3-deserializer");
    if (amf3Deserializer != null) {
      String type = amf3Deserializer.get("@type");
      try {
        Class<AMF3Deserializer> amf3DeserializerClass =
            TypeUtil.forName(type, AMF3Deserializer.class);
        amf3DeserializerConstructor =
            TypeUtil.getConstructor(amf3DeserializerClass, new Class<?>[] {InputStream.class});
      } catch (Exception e) {
        throw new GraniteConfigException(
            "Could not get constructor for AMF3 deserializer: " + type, e);
      }
    }
  }
示例#2
0
  public Externalizer getExternalizer(String type) {
    Externalizer externalizer =
        getElementByType(
            type,
            EXTERNALIZER_FACTORY,
            externalizersByType,
            externalizersByInstanceOf,
            externalizersByAnnotatedWith,
            scannedExternalizers);
    if (externalizer != null) return externalizer;

    if ("java".equals(GraniteContext.getCurrentInstance().getClientType())) {
      // Force use of number externalizers when serializing from/to a Java client
      if (Long.class.getName().equals(type)) return LONG_EXTERNALIZER;
      else if (BigInteger.class.getName().equals(type)) return BIGINTEGER_EXTERNALIZER;
      else if (BigDecimal.class.getName().equals(type)) return BIGDECIMAL_EXTERNALIZER;
      else {
        try {
          Class<?> clazz = TypeUtil.forName(type);
          if (Map.class.isAssignableFrom(clazz) && !Externalizable.class.isAssignableFrom(clazz))
            return MAP_EXTERNALIZER;
        } catch (Exception e) {

        }
      }
    }

    return null;
  }
示例#3
0
  private boolean handleProperties(Properties properties) {
    if (properties.getProperty("dependsOn") != null) {
      String dependsOn = properties.getProperty("dependsOn");
      try {
        TypeUtil.forName(dependsOn);
      } catch (ClassNotFoundException e) {
        // Class not found, skip scan for this package
        return true;
      }
    }

    String classGetterName = properties.getProperty("classGetter");
    if (!classGetterSet && classGetterName != null) {
      try {
        classGetter = TypeUtil.newInstance(classGetterName, ClassGetter.class);
      } catch (Throwable t) {
        log.error(t, "Could not create instance of: %s", classGetterName);
      }
    }

    String amf3MessageInterceptorName = properties.getProperty("amf3MessageInterceptor");
    if (amf3MessageInterceptor == null && amf3MessageInterceptorName != null) {
      try {
        amf3MessageInterceptor =
            TypeUtil.newInstance(amf3MessageInterceptorName, AMF3MessageInterceptor.class);
      } catch (Throwable t) {
        log.error(t, "Could not create instance of: %s", amf3MessageInterceptorName);
      }
    }

    for (Map.Entry<?, ?> me : properties.entrySet()) {
      if (me.getKey().toString().startsWith("converter.")) {
        String converterName = me.getValue().toString();
        try {
          converterClasses.add(TypeUtil.forName(converterName, Converter.class));
        } catch (Exception e) {
          throw new GraniteConfigException(
              "Could not get converter class for: " + converterName, e);
        }
      }
    }

    return false;
  }
示例#4
0
 private void loadCustomMethodMatcher(XMap element, boolean custom) {
   XMap methodMatcher = element.getOne("method-matcher");
   if (methodMatcher != null) {
     String type = methodMatcher.get("@type");
     try {
       this.methodMatcher = (MethodMatcher) TypeUtil.newInstance(type);
     } catch (Exception e) {
       throw new GraniteConfigException("Could not construct method matcher: " + type, e);
     }
   }
 }
示例#5
0
 private void loadCustomMessageSelector(XMap element, boolean custom) {
   XMap selector = element.getOne("message-selector");
   if (selector != null) {
     String type = selector.get("@type");
     try {
       messageSelectorConstructor = TypeUtil.getConstructor(type, new Class<?>[] {String.class});
     } catch (Exception e) {
       throw new GraniteConfigException("Could not construct message selector: " + type, e);
     }
   }
 }
示例#6
0
 private void loadCustomClassGetter(XMap element, boolean custom) {
   XMap classGetter = element.getOne("class-getter");
   if (classGetter != null) {
     String type = classGetter.get("@type");
     try {
       this.classGetter = (ClassGetter) TypeUtil.newInstance(type);
       classGetterSet = true;
     } catch (Exception e) {
       throw new GraniteConfigException("Could not instantiate ClassGetter: " + type, e);
     }
   }
 }
示例#7
0
 private void loadCustomInvocationListener(XMap element, boolean custom) {
   XMap invocationListener = element.getOne("invocation-listener");
   if (invocationListener != null) {
     String type = invocationListener.get("@type");
     try {
       this.invocationListener = (ServiceInvocationListener) TypeUtil.newInstance(type);
     } catch (Exception e) {
       throw new GraniteConfigException(
           "Could not instantiate ServiceInvocationListener: " + type, e);
     }
   }
 }
示例#8
0
 private void loadCustomDistributedDataFactory(XMap element, boolean custom) {
   XMap distributedDataFactory = element.getOne("distributed-data-factory");
   if (distributedDataFactory != null) {
     String type = distributedDataFactory.get("@type");
     try {
       this.distributedDataFactory = (DistributedDataFactory) TypeUtil.newInstance(type);
     } catch (Exception e) {
       throw new GraniteConfigException(
           "Could not construct build distributed data factory: " + type, e);
     }
   }
 }
示例#9
0
 /** Read custom class exception converters Converter must have 'type' attribute */
 private void loadCustomExceptionConverters(XMap element, boolean custom) {
   for (XMap exceptionConverter : element.getAll("exception-converters/exception-converter")) {
     String type = exceptionConverter.get("@type");
     ExceptionConverter converter = null;
     try {
       converter = (ExceptionConverter) TypeUtil.newInstance(type);
       exceptionConverters.add(converter);
     } catch (Exception e) {
       throw new GraniteConfigException("Could not construct exception converter: " + type, e);
     }
   }
 }
示例#10
0
 private void loadCustomAMF3MessageInterceptor(XMap element, boolean custom) {
   XMap interceptor = element.getOne("amf3-message-interceptor");
   if (interceptor != null) {
     String type = interceptor.get("@type");
     try {
       amf3MessageInterceptor = (AMF3MessageInterceptor) TypeUtil.newInstance(type);
     } catch (Exception e) {
       throw new GraniteConfigException(
           "Could not construct amf3 message interceptor: " + type, e);
     }
   }
 }
示例#11
0
  private void handleClass(Class<?> clazz) {
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) return;

    if (Externalizer.class.isAssignableFrom(clazz)) {
      try {
        scannedExternalizers.add(TypeUtil.newInstance(clazz, Externalizer.class));
      } catch (Exception e) {
        log.error(e, "Could not create new instance of: %s", clazz);
      }
    }

    if (ExceptionConverter.class.isAssignableFrom(clazz)) {
      try {
        exceptionConverters.add(TypeUtil.newInstance(clazz, ExceptionConverter.class));
      } catch (Exception e) {
        if (!clazz
            .getName()
            .equals("org.granite.tide.hibernate.HibernateValidatorExceptionConverter")) // GDS-582
        log.error(e, "Could not create new instance of: %s", clazz);
      }
    }
  }
示例#12
0
 private void loadCustomJMFReflection(XMap element, boolean custom) {
   String jmfReflection = element.get("jmf-reflection/@type");
   if (jmfReflection == null)
     this.jmfReflection = new Reflection(Thread.currentThread().getContextClassLoader());
   else {
     try {
       this.jmfReflection = (Reflection) TypeUtil.newInstance(jmfReflection);
     } catch (Exception e) {
       throw new GraniteConfigException(
           "Could not instantiate JMF reflection: " + jmfReflection, e);
     }
   }
 }
示例#13
0
 public void registerExceptionConverter(
     Class<? extends ExceptionConverter> exceptionConverterClass, boolean first) {
   for (ExceptionConverter ec : exceptionConverters) {
     if (ec.getClass() == exceptionConverterClass) return;
   }
   try {
     ExceptionConverter exceptionConverter =
         TypeUtil.newInstance(exceptionConverterClass, ExceptionConverter.class);
     if (first) exceptionConverters.add(0, exceptionConverter);
     else exceptionConverters.add(exceptionConverter);
   } catch (Exception e) {
     log.error(e, "Could not instantiate exception converter: %s", exceptionConverterClass);
   }
 }
示例#14
0
  private void loadCustomConverters(XMap element, boolean custom) {
    XMap converters = element.getOne("converters");
    if (converters != null) {
      // Should we override standard config converters?
      String override = converters.get("@override");
      if (Boolean.TRUE.toString().equals(override)) converterClasses.clear();

      int i = 0;
      for (XMap converter : converters.getAll("converter")) {
        String type = converter.get("@type");
        try {
          // For custom config, shifts any standard converters to the end of the list...
          converterClasses.add(i++, TypeUtil.forName(type, Converter.class));
        } catch (Exception e) {
          throw new GraniteConfigException("Could not get converter class for: " + type, e);
        }
      }
    }
  }
示例#15
0
 private void loadCustomAMF3DeserializerSecurizer(XMap element, boolean custom) {
   XMap securizer = element.getOne("amf3-deserializer-securizer");
   if (securizer != null) {
     String type = securizer.get("@type");
     try {
       amf3DeserializerSecurizer = (AMF3DeserializerSecurizer) TypeUtil.newInstance(type);
     } catch (Exception e) {
       throw new GraniteConfigException(
           "Could not construct amf3 deserializer securizer: " + type, e);
     }
     String param = securizer.get("@param");
     try {
       amf3DeserializerSecurizer.setParam(param);
     } catch (Exception e) {
       throw new GraniteConfigException(
           "Could not set param of amf3 deserializer securizer: " + type + ", param: " + param, e);
     }
   }
 }
示例#16
0
  private void loadCustomJMFExtendedCodecs(XMap element, boolean custom) {
    String jmfExtendedCodecsMode = element.get("jmf-extended-codecs/@mode");
    if (jmfExtendedCodecsMode != null) {
      try {
        this.jmfExtendedCodecsMode =
            JMF_EXTENSIONS_MODE.valueOf(jmfExtendedCodecsMode.toLowerCase());
      } catch (Exception e) {
        throw new GraniteConfigException(
            "Illegal JMF extended codecs mode: " + jmfExtendedCodecsMode, e);
      }
    }

    for (XMap codec : element.getAll("jmf-extended-codecs/jmf-extended-codec")) {
      String codecType = codec.get("@type");

      try {
        jmfExtendedCodecs.add((ExtendedObjectCodec) TypeUtil.newInstance(codecType));
      } catch (Exception e) {
        throw new GraniteConfigException(
            "Could not instantiate JMF extended codec: " + codecType, e);
      }
    }
  }
示例#17
0
  @SuppressWarnings("unchecked")
  public <C extends Channel> C getChannel(ChannelFactory<C> channelFactory, String clientId) {
    if (clientId == null) return null;

    TimeChannel<C> timeChannel = (TimeChannel<C>) channels.get(clientId);
    if (timeChannel == null) {
      // Look for existing channel id/subscriptions in distributed data (clustering).
      log.debug("Lookup channel %s in distributed data", clientId);
      try {
        DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance();
        if (gdd != null && gdd.hasChannelId(clientId)) {
          log.debug("Found channel id in distributed data: %s", clientId);
          String channelFactoryClassName = gdd.getChannelFactoryClassName(clientId);
          String clientType = gdd.getChannelClientType(clientId);
          channelFactory =
              (ChannelFactory<C>)
                  TypeUtil.newInstance(
                      channelFactoryClassName, new Class<?>[] {Gravity.class}, new Object[] {this});
          C channel = channelFactory.newChannel(clientId, clientType);
          timeChannel = new TimeChannel<C>(channel);
          if (channels.putIfAbsent(clientId, timeChannel) == null) {
            for (CommandMessage subscription : gdd.getSubscriptions(clientId)) {
              log.debug("Resubscribing channel: %s - %s", clientId, subscription);
              handleSubscribeMessage(channelFactory, subscription, false);
            }
            access(clientId);
          }
        }
      } catch (Exception e) {
        log.error(
            e, "Could not recreate channel/subscriptions from distributed data: %s", clientId);
      }
    }

    return (timeChannel != null ? timeChannel.getChannel() : null);
  }
示例#18
0
  private void loadCustomSecurity(XMap element, boolean custom) {
    XMap security = element.getOne("security");
    if (security != null) {
      String type = security.get("@type");
      try {
        securityService = (SecurityService) TypeUtil.newInstance(type);
      } catch (Exception e) {
        throw new GraniteConfigException("Could not instantiate SecurityService: " + type, e);
      }

      Map<String, String> params = new HashMap<String, String>();
      for (XMap param : security.getAll("param")) {
        String name = param.get("@name");
        String value = param.get("@value");
        params.put(name, value);
      }
      try {
        securityService.configure(params);
      } catch (Exception e) {
        throw new GraniteConfigException(
            "Could not configure SecurityService " + type + " with: " + params, e);
      }
    }
  }
示例#19
0
  @SuppressWarnings("unchecked")
  private <T, C extends Config> T getElementByType(
      String type,
      ConfigurableFactory<T, C> factory,
      ConcurrentHashMap<String, T> elementsByType,
      Map<String, String> elementsByInstanceOf,
      Map<String, String> elementsByAnnotatedWith,
      List<T> scannedConfigurables) {

    // This NULL object is a Java null placeholder: ConcurrentHashMap doesn't allow
    // null values...
    final T NULL = factory.getNullInstance();

    T element = elementsByType.get(type);
    if (element != null) return (NULL == element ? null : element);
    element = NULL;

    Class<?> typeClass = null;
    try {
      typeClass = TypeUtil.forName(type);
    } catch (Exception e) {
      throw new GraniteConfigException("Could not load class: " + type, e);
    }

    if (elementsByAnnotatedWith != null && NULL == element) {
      for (Map.Entry<String, String> entry : elementsByAnnotatedWith.entrySet()) {
        String annotation = entry.getKey();
        try {
          Class<Annotation> annotationClass = TypeUtil.forName(annotation, Annotation.class);
          if (typeClass.isAnnotationPresent(annotationClass)) {
            element = factory.getInstance(entry.getValue(), (C) this);
            break;
          }
        } catch (Exception e) {
          throw new GraniteConfigException("Could not load class: " + annotation, e);
        }
      }
    }

    if (elementsByInstanceOf != null && NULL == element) {
      for (Map.Entry<String, String> entry : elementsByInstanceOf.entrySet()) {
        String instanceOf = entry.getKey();
        try {
          Class<?> instanceOfClass = TypeUtil.forName(instanceOf);
          if (instanceOfClass.isAssignableFrom(typeClass)) {
            element = factory.getInstance(entry.getValue(), (C) this);
            break;
          }
        } catch (Exception e) {
          throw new GraniteConfigException("Could not load class: " + instanceOf, e);
        }
      }
    }

    if (NULL == element)
      element = factory.getInstanceForBean(scannedConfigurables, typeClass, (C) this);

    T previous = elementsByType.putIfAbsent(type, element);
    if (previous != null) element = previous;

    return (NULL == element ? null : element);
  }
  @Override
  public List<Property> findOrderedFields(
      final Class<?> clazz, boolean returnSettersWhenAvailable) {
    List<Property> fields =
        !dynamicClass
            ? (returnSettersWhenAvailable
                ? orderedSetterFields.get(clazz)
                : orderedFields.get(clazz))
            : null;

    if (fields == null) {
      if (dynamicClass) {
        Introspector.flushFromCaches(clazz);
      }
      PropertyDescriptor[] propertyDescriptors = TypeUtil.getProperties(clazz);
      Converters converters =
          ((ConvertersConfig) GraniteContext.getCurrentInstance().getGraniteConfig())
              .getConverters();

      fields = new ArrayList<Property>();

      List<Property> idVersionFields = new ArrayList<Property>();

      Set<String> allFieldNames = new HashSet<String>();
      for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {

        List<Property> newFields = new ArrayList<Property>();

        // Standard declared fields.
        for (Field field : c.getDeclaredFields()) {
          if (!allFieldNames.contains(field.getName())
              && !Modifier.isTransient(field.getModifiers())
              && !Modifier.isStatic(field.getModifiers())
              && !field.isAnnotationPresent(Exclude.class)
              && !GrailsExternalizer.isIgnored(field)) {

            boolean found = false;
            if (returnSettersWhenAvailable && propertyDescriptors != null) {
              for (PropertyDescriptor pd : propertyDescriptors) {
                if (pd.getName().equals(field.getName()) && pd.getWriteMethod() != null) {
                  if ("id".equals(field.getName()) || "version".equals(field.getName())) {
                    if (c == clazz) {
                      idVersionFields.add(
                          new MethodProperty(
                              converters,
                              field.getName(),
                              pd.getWriteMethod(),
                              pd.getReadMethod()));
                    }
                  } else {
                    newFields.add(
                        new MethodProperty(
                            converters, field.getName(), pd.getWriteMethod(), pd.getReadMethod()));
                  }
                  found = true;
                  break;
                }
              }
            }
            if (!found) {
              if ("id".equals(field.getName()) || "version".equals(field.getName())) {
                idVersionFields.add(new FieldProperty(converters, field));
              } else {
                newFields.add(new FieldProperty(converters, field));
              }
            }
          }
          allFieldNames.add(field.getName());
        }

        // Getter annotated  by @ExternalizedProperty.
        if (propertyDescriptors != null) {
          for (PropertyDescriptor property : propertyDescriptors) {
            Method getter = property.getReadMethod();
            if (getter != null
                && getter.isAnnotationPresent(Include.class)
                && getter.getDeclaringClass().equals(c)
                && !allFieldNames.contains(property.getName())
                && !GrailsExternalizer.isIgnored(property)) {

              newFields.add(new MethodProperty(converters, property.getName(), null, getter));
              allFieldNames.add(property.getName());
            }
          }
        }

        if (isRoot(c)) {
          newFields.addAll(idVersionFields);
        }

        Collections.sort(
            newFields,
            new Comparator<Property>() {
              public int compare(Property o1, Property o2) {
                return o1.getName().compareTo(o2.getName());
              }
            });

        fields.addAll(0, newFields);
      }

      if (!dynamicClass) {
        List<Property> previousFields =
            (returnSettersWhenAvailable ? orderedSetterFields : orderedFields)
                .putIfAbsent(clazz, fields);
        if (previousFields != null) {
          fields = previousFields;
        }
      }
    }

    return fields;
  }
示例#21
0
  public GraniteConfig(
      String stdConfig,
      InputStream customConfigIs,
      Configuration configuration,
      String MBeanContextName)
      throws IOException, SAXException {
    try {
      amf3SerializerConstructor =
          TypeUtil.getConstructor(AMF3Serializer.class, new Class<?>[] {OutputStream.class});
      amf3DeserializerConstructor =
          TypeUtil.getConstructor(AMF3Deserializer.class, new Class<?>[] {InputStream.class});
    } catch (Exception e) {
      throw new GraniteConfigException("Could not get constructor for AMF3 (de)serializers", e);
    }

    this.MBeanContextName = MBeanContextName;

    ClassLoader loader = GraniteConfig.class.getClassLoader();

    final ByteArrayInputStream dtd =
        StreamUtil.getResourceAsStream("org/granite/config/granite-config.dtd", loader);
    final EntityResolver resolver =
        new EntityResolver() {
          public InputSource resolveEntity(String publicId, String systemId)
              throws SAXException, IOException {
            if (GRANITE_CONFIG_PUBLIC_ID.equals(publicId)) {
              dtd.reset();
              InputSource source = new InputSource(dtd);
              source.setPublicId(publicId);
              return source;
            }
            return null;
          }
        };

    // Load standard config.
    InputStream is = null;
    try {
      is = StreamUtil.getResourceAsStream("org/granite/config/granite-config.xml", loader);
      XMap doc = new XMap(is, resolver);
      forElement(doc, false, null);
    } finally {
      if (is != null) is.close();
    }

    if (stdConfig != null) {
      try {
        is = StreamUtil.getResourceAsStream(stdConfig, loader);
        XMap doc = new XMap(is, resolver);
        forElement(doc, false, null);
      } finally {
        if (is != null) is.close();
      }
    }

    // Load custom config (override).
    if (customConfigIs != null) {
      XMap doc = new XMap(customConfigIs, resolver);
      forElement(
          doc, true, configuration != null ? configuration.getGraniteConfigProperties() : null);
    }

    if (amf3DeserializerSecurizer == null)
      log.warn(
          "You should configure a deserializer securizer in your granite-config.xml file in order to prevent potential security exploits!");
  }