コード例 #1
0
 protected IMessagePublication createMessagePublication(T message) {
   Collection<Subscription> subscriptions = getSubscriptionsByMessageType(message.getClass());
   if ((subscriptions == null || subscriptions.isEmpty())
       && !message.getClass().equals(DeadMessage.class)) {
     // DeadMessage Event
     subscriptions = getSubscriptionsByMessageType(DeadMessage.class);
     return getPublicationFactory()
         .createPublication(runtime, subscriptions, new DeadMessage(message));
   } else {
     return getPublicationFactory().createPublication(runtime, subscriptions, message);
   }
 }
コード例 #2
0
ファイル: TestUtil.java プロジェクト: fenderstr/ernie
  /**
   * Checks equality of two objects based on the equality of their fields, items, or .equals()
   * method.
   *
   * @param obj1
   * @param obj2
   * @return
   */
  public static <T> boolean equal(T obj1, T obj2) {
    if (obj1 == null || obj2 == null) {
      // If they're both null, we call this equal
      if (obj1 == null && obj2 == null) return true;
      else return false;
    }

    if (!obj1.getClass().equals(obj2.getClass())) return false;

    if (obj1.equals(obj2)) return true;

    List<Pair> vals = new ArrayList<Pair>();

    // If obj1 and obj2 are Collections, get the objects in them
    if (Collection.class.isAssignableFrom(obj1.getClass())) {

      Collection c1 = (Collection) obj1;
      Collection c2 = (Collection) obj2;

      if (c1.size() != c2.size()) return false;

      Iterator itr1 = c1.iterator();
      Iterator itr2 = c2.iterator();

      while (itr1.hasNext() && itr2.hasNext()) {
        vals.add(new Pair(itr1.next(), itr2.next()));
      }
    }

    // Get field values from obj1 and obj2
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj1);
    for (PropertyDescriptor property : properties) {

      // ignore getClass() and isEmpty()
      if (property.getName().equals("class") || property.getName().equals("empty")) continue;

      Object val1 = invokeMethod(obj1, property.getReadMethod(), null, property.getName());
      Object val2 = invokeMethod(obj2, property.getReadMethod(), null, property.getName());

      vals.add(new Pair(val1, val2));
    }

    if (vals.isEmpty()) return false;

    for (Pair pair : vals) {
      if (!equal(pair.left, pair.right)) return false;
    }

    return true;
  }
コード例 #3
0
 @Override
 public <T> T getService(Class<T> serviceClass) {
   //noinspection unchecked
   T service = (T) myServices.get(serviceClass);
   if (service == null) {
     final Iterator<T> iterator =
         ServiceLoader.load(serviceClass, serviceClass.getClassLoader()).iterator();
     if (!iterator.hasNext()) {
       throw new ServiceConfigurationError("Implementation for " + serviceClass + " not found");
     }
     service = iterator.next();
     if (iterator.hasNext()) {
       throw new ServiceConfigurationError(
           "More than one implementation for "
               + serviceClass
               + " found: "
               + service.getClass()
               + " and "
               + iterator.next().getClass());
     }
     myServices.putIfAbsent(serviceClass, service);
     //noinspection unchecked
     service = (T) myServices.get(serviceClass);
   }
   return service;
 }
コード例 #4
0
  /** Set the value for the key in this context. */
  public <T> void put(Key<T> key, T data) {
    DEBUG.P(this, "put(Key<T> key, T data)");
    if (data != null) DEBUG.P("data=" + data.getClass().getName());
    else DEBUG.P("data=" + data);
    // DEBUG.P("context前="+toString());

    /*例如:
       Context context = new Context();
       Context.Key<Context.Factory> factoryKey =new Context.Key<Context.Factory>();
    context.put(factoryKey,new Context.Factory<String>(){public String make() {return "";}});

       出现如下类似异常:
       Exception in thread "main" java.lang.AssertionError: T extends Context.Factory

       因为Context.Key<T>的参数化类型不允许是Context.Key<Context.Factory>
       */
    if (data instanceof Factory) throw new AssertionError("T extends Context.Factory");
    checkState(ht);
    Object old = ht.put(key, data);
    if (old != null && !(old instanceof Factory) && old != data && data != null)
      throw new AssertionError("duplicate context value");

    DEBUG.P("context后=" + toString());
    DEBUG.P(0, this, "put(Key<T> key, T data)");
  }
コード例 #5
0
 public BatchOptions(T options) {
   super(options.getClass());
   this.options = options;
   numParametersLabel = this.options.addLabel("");
   addFirstOptions();
   addChildOptions(WRAPPED_OPTIONS_KEY, "", null, options);
   SimpleListener listener =
       new SimpleListener() {
         @Override
         public void objectChanged() {
           int batchSize = getBatchSize();
           numParametersLabel.setValue("Total number of parameter sets: " + batchSize);
           if (batchSize > 10000) {
             numParametersLabel.setWarningMessage(
                 "Too many results can cause Geneious to become unusable");
           } else if (batchSize > 500) {
             numParametersLabel.setWarningMessage(
                 "A lot of results will cause Geneious to slow down");
           } else {
             numParametersLabel.setWarningMessage(null);
           }
         }
       };
   addMinMaxOptionsAndHideOriginal(options, listener);
 }
コード例 #6
0
  /**
   * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually
   * should go to struct.
   *
   * @param from
   * @param to
   * @param excludes
   * @return
   * @throws Exception
   */
  public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception {
    Arrays.sort(excludes);
    for (Field f : from.fields()) {
      if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue;

      Object o = f.get(from);
      if (o == null) continue;

      Field tof = to.getField(f.getName());
      if (tof != null)
        try {
          tof.set(to, Converter.cnv(tof.getGenericType(), o));
        } catch (Exception e) {
          System.out.println(
              "Failed to convert "
                  + f.getName()
                  + " from "
                  + from.getClass()
                  + " to "
                  + to.getClass()
                  + " value "
                  + o
                  + " exception "
                  + e);
        }
    }

    return to;
  }
コード例 #7
0
  /**
   * Sets up the mocks defined in the given mock class.
   *
   * <p>If the type {@linkplain MockClass#realClass referred to} by the mock class is actually an
   * interface, then a {@linkplain #newEmptyProxy(ClassLoader, Class) new empty proxy} is created.
   *
   * @param mockClassOrInstance the mock class itself (given by its {@code Class} literal), or an
   *     instance of the mock class
   * @return the new proxy instance created for the mocked interface, or {@code null} otherwise
   * @throws IllegalArgumentException if a given mock class fails to specify the corresponding real
   *     class using the {@code @MockClass(realClass = ...)} annotation; or if a mock class defines
   *     a mock method for which no corresponding real method or constructor exists in the real
   *     class; or if the real method matching a mock method is {@code abstract}
   * @see #setUpMock(Class, Object)
   * @see #setUpMocks(Object...)
   * @see <a
   *     href="http://code.google.com/p/jmockit/source/browse/trunk/main/test/mockit/MockAnnotationsTest.java#696">
   *     Example</a>
   */
  public static <T> T setUpMock(Object mockClassOrInstance) {
    Class<?> mockClass;
    Object mock;

    if (mockClassOrInstance instanceof Class<?>) {
      mockClass = (Class<?>) mockClassOrInstance;
      mock = null;
    } else {
      mockClass = mockClassOrInstance.getClass();
      mock = mockClassOrInstance;
    }

    MockClassSetup setup = new MockClassSetup(mock, mockClass);
    Class<?> realClass = setup.getRealClass();
    T proxy = null;

    if (realClass.isInterface()) {
      //noinspection unchecked
      proxy = (T) newEmptyProxy(mockClass.getClassLoader(), realClass);
      setup.setRealClass(proxy.getClass());
    }

    setup.redefineMethods();

    return proxy;
  }
コード例 #8
0
  /**
   * Method to convert a List of beans to a List of Array of Strings.
   *
   * @param beans the List of Beans.
   * @param addNewHeader the new String Array for the Header row.
   * @param <T> generic value.
   * @return the List of Array of String content of the csv.
   */
  @SuppressWarnings("unchecked")
  public static <T> List<String[]> toStringArray(List<T> beans, String[] addNewHeader) {
    List<String[]> records = new ArrayList<>();
    // add header record
    // records.add(new String[]{"ID","Name","Role","Salary"});
    if (addNewHeader != null) records.add(addNewHeader);
    for (T bean : beans) {
      // beans.stream().map((bean) -> {
      List<String> record = new ArrayList<>();
      // invoke getter method and convert to String
      Class<T> clazz = (Class<T>) bean.getClass();
      // T t = ReflectionUtilities.invokeConstructor(clazz);
      List<Method> getter = (List<Method>) ReflectionUtilities.findGetters(clazz, true);

      for (Method method : getter) {
        record.add(String.valueOf(ReflectionUtilities.invokeGetter(bean, method)));
      }
      // getter.stream().forEach((method) ->
      // record.add(String.valueOf(ReflectionUtilities.invokeGetter(bean,method))));
      // return record;
      // }).forEach((record) -> records.add(ListUtilities.toArray(record)));
      records.add(ListUtilities.toArray(record));
    }
    return records;
  }
コード例 #9
0
 /** Adds the given listener to this ServletContext. */
 @Override
 public <T extends EventListener> void addListener(T t) {
   if (SecurityUtil.isPackageProtectionEnabled()) {
     doPrivileged(
         "addListener", new Class[] {EventListener.class}, new Object[] {t.getClass().getName()});
   } else {
     context.addListener(t);
   }
 }
コード例 #10
0
  /**
   * This function returns a map whose entries hold the coordinates of the sequence as keys and the
   * coordinates of the target sequences as values.</br> If a coordinate in sequence corresponds to
   * a gap in another sequence, then -1 is assigned to that position.</br> For example suppose we
   * have the sequences:</br> seq1: AAT-GCT-TCG</br> seq2: G--C-CTCT-C</br> seq3: A-T--GT-AG-</br>
   * Then, if we wish to find the mapping of seq1's coordinates to seq2's coordinates, this will
   * give us: 0 -> 0, 1 -> -1, 2 -> -1, 3 -> -1, 4 -> 2, 5 -> 3, 6 -> 5, 7 -> -1, 8 -> 6.</br> Also,
   * if we wish to find the mapping of seq1's coordinates to seq2's and seq3's coordinates, this
   * will give us: 0 -> {0, 0}, 1 -> {-1, -1}, 2 -> {-1, 1}, 3 -> {-1, -1}, 4 -> {2, 2}, 5 -> {3,
   * 3}, 6 -> {5, 4}, 7 -> {-1, 5}, 8 -> {6, -1}.
   *
   * @param <T> This could be either the serial number of the sequence (valid range: [0,
   *     sequences.length-1]) or the sequence names
   * @param <E>
   * @param seqID The sequence ID (either serial number or name) which we wish to map</br> Note that
   *     the valid range of serial numbers is [0, sequences.length-1]
   * @param targetSeqIDs The (target) sequences IDs (either serial numbers or names)
   * @return A map whose keys are the sequence coordinates and values the corresponding coordinates
   *     of the target sequences
   * @throws IllegalArgumentException
   * @see GappedAlignmentString
   */
  public <T extends Object> Map mapSeqCoords2SeqsCoords(
      T generic_seqID, Vector<T> generic_targetSeqIDs)
      throws IllegalArgumentException, IndexOutOfBoundsException {
    GappedAlignmentString gas_seq;
    GappedAlignmentString[] gas_targetSeqs;

    String[] speciesNames = species();

    // Check if generic_seqID is mistakenly included in the generic_targetSeqIDs set
    if (generic_targetSeqIDs.contains(generic_seqID)) generic_targetSeqIDs.remove(generic_seqID);

    if (generic_targetSeqIDs.size() + 1 > speciesNames.length)
      throw new IndexOutOfBoundsException("You entered more sequences than are in the file.");

    Map map = new HashMap();
    // Check whether sequence IDs are inputed as serial numbers or as names
    String seqsClassName = generic_seqID.getClass().getSimpleName();

    // if( generic_seqID.getClass() instanceof java.lang.Integer )
    // System.out.println("XAXA");

    if (seqsClassName.equals("Integer")) {
      Integer seqID = (Integer) generic_seqID;
      Integer[] seqIDs = generic_targetSeqIDs.toArray(new Integer[generic_targetSeqIDs.size()]);

      if ((StatUtil.findMax(seqIDs).getFirst() > speciesNames.length - 1)
          || (StatUtil.findMin(seqIDs).getFirst() < 0))
        throw new IndexOutOfBoundsException(
            "The sequence IDs (aka, serial numbers have to lie inside"
                + " the range 0 to speciesNames.length -1");

      gas_seq = getGappedAlignment(speciesNames[seqID]);
      gas_targetSeqs = new GappedAlignmentString[seqIDs.length];
      for (int i = 0; i < seqIDs.length; i++)
        gas_targetSeqs[i] = getGappedAlignment(speciesNames[seqIDs[i]]);
    } else if (seqsClassName.equals("String")) {
      String seqID = (String) generic_seqID;
      String[] seqIDs = generic_targetSeqIDs.toArray(new String[generic_targetSeqIDs.size()]);

      gas_seq = getGappedAlignment(seqID);
      gas_targetSeqs = new GappedAlignmentString[seqIDs.length];
      for (int i = 0; i < seqIDs.length; i++) gas_targetSeqs[i] = getGappedAlignment(seqIDs[i]);
    } else {
      throw new IllegalArgumentException("Sequence IDs should be either of type Integer or String");
    }

    // Pairwise Alignment
    if (gas_targetSeqs.length == 1) {
      map = doMapSeq2Seq(gas_seq, gas_targetSeqs);
    }
    // Multiple Alignment
    else {
      map = doMapSeq2Seqs(gas_seq, gas_targetSeqs);
    }

    return map;
  } // end of mapSeqCoords2SeqsCoords method
コード例 #11
0
 /**
  * Computes the display string for any value.
  *
  * @param t the value to print
  * @return the formatted string
  */
 public static <T> String print(T t) {
   if (t == null) {
     return "";
   }
   if (conversion.canConvert(t.getClass(), String.class)) {
     return conversion.convert(t, String.class);
   } else {
     return t.toString();
   }
 }
コード例 #12
0
  public <T> void put(Class<T> clazz, T data) {
    DEBUG.P(this, "put(Class<T> clazz, T data)");
    if (data != null) DEBUG.P("data=" + data.getClass().getName());
    else DEBUG.P("data=" + data);
    // DEBUG.P("context前="+toString());

    put(key(clazz), data);

    // DEBUG.P("context后="+toString());
    DEBUG.P(0, this, "put(Class<T> clazz, T data)");
  }
コード例 #13
0
 private void assertEQ(T t, Object returned) {
   if (rtype.isArray()) {
     Asserts.assertEQ(t.getClass(), returned.getClass());
     int n = Array.getLength(t);
     Asserts.assertEQ(n, Array.getLength(returned));
     for (int i = 0; i < n; ++i) {
       Asserts.assertEQ(Array.get(t, i), Array.get(returned, i));
     }
   } else {
     Asserts.assertEQ(t, returned);
   }
 }
コード例 #14
0
ファイル: AnnotationUtils.java プロジェクト: nilpoint/griffon
 @Nonnull
 public static <T> T requireAnnotation(
     @Nonnull T instance, @Nonnull Class<? extends Annotation> annotationType) {
   if (!isAnnotatedWith(instance, annotationType)) {
     throw new IllegalArgumentException(
         "Instance of "
             + instance.getClass()
             + " is not annotated with "
             + annotationType.getName());
   }
   return instance;
 }
コード例 #15
0
 private static <T extends UnnamedConfigurable> T createConfigurable(
     @NotNull ConfigurableEP<T> ep, boolean log) {
   long time = System.currentTimeMillis();
   T configurable = ep.createConfigurable();
   if (configurable instanceof Configurable) {
     ConfigurableCardPanel.warn((Configurable) configurable, "init", time);
     if (log) {
       LOG.debug("cannot create configurable wrapper for " + configurable.getClass());
     }
   }
   return configurable;
 }
コード例 #16
0
 /**
  * Computes the display string for any value, for a specific type.
  *
  * @param desc the field descriptor - custom formatters are extracted from this descriptor.
  * @param t the value to print
  * @return the formatted string
  */
 public static <T> String print(TypeDescriptor desc, T t) {
   if (t == null) {
     return "";
   }
   if (desc != null && conversion.canConvert(desc, TypeDescriptor.valueOf(String.class))) {
     return (String) conversion.convert(t, desc, TypeDescriptor.valueOf(String.class));
   } else if (conversion.canConvert(t.getClass(), String.class)) {
     return conversion.convert(t, String.class);
   } else {
     return t.toString();
   }
 }
コード例 #17
0
ファイル: BeanUtil.java プロジェクト: gmeurant/benerator
 @SuppressWarnings("unchecked")
 public static <T> T clone(T object) {
   try {
     Method cloneMethod = object.getClass().getMethod("clone");
     return (T) cloneMethod.invoke(object);
   } catch (NoSuchMethodException e) {
     throw new RuntimeException("Unexpected exception", e); // This is not supposed to happen
   } catch (IllegalAccessException e) {
     throw new RuntimeException("Unexpected exception", e); // This is not supposed to happen
   } catch (InvocationTargetException e) {
     throw new RuntimeException("Execption occured in clone() method", e);
   }
 }
コード例 #18
0
  @Override
  public <T extends Enum> void listen(EventListener<T, ?> el, T... events) {
    if (events == null || events.length == 0) {
      throw new IllegalArgumentException("Must subscribe to at least one event type");
    }

    for (T event : events) {
      if (event != null) {
        regsiterListener(el, (Class<T>) event.getClass(), Arrays.asList(events));
        break;
      }
    }
  }
コード例 #19
0
  /**
   * Convenience method for testing purposes. If you know that the type of the value is correct, it
   * is preferable to create a ConfigEntry object and apply it to the component (no type checking
   * necessary).
   *
   * @param <T> Type of the config option (Integer, String etc.).
   * @param component A component.
   * @param optionName The name of the config option.
   * @param value The value of the config option.
   */
  @SuppressWarnings("unchecked")
  public <T> void applyConfigEntry(AbstractComponent component, String optionName, T value) {
    logger.trace(component);
    logger.trace(optionName);
    logger.trace(value);
    logger.trace(value.getClass());
    // first we look whether the component is registered
    if (components.contains(component.getClass())) {

      // look for a config option with the specified name
      ConfigOption<?> option =
          (ConfigOption<?>) componentOptionsByName.get(component.getClass()).get(optionName);
      if (option != null) {
        // check whether the given object has the correct type
        if (!option.checkType(value)) {
          System.out.println(
              "Warning: value "
                  + value
                  + " is not valid for option "
                  + optionName
                  + " in component "
                  + component
                  + ". It does not have the correct type.");
          return;
        }

        // we have checked the type, hence it should now be safe to
        // typecast and
        // create a ConfigEntry object
        ConfigEntry<T> entry = null;
        try {
          entry = new ConfigEntry<T>((ConfigOption<T>) option, value);
          component.applyConfigEntry(entry);
          pool.addConfigEntry(component, entry, true);
        } catch (InvalidConfigOptionValueException e) {
          pool.addConfigEntry(component, entry, false);
          System.out.println(
              "Warning: value "
                  + value
                  + " is not valid for option "
                  + optionName
                  + " in component "
                  + component);
        }
      } else {
        logger.warn("Warning: undefined option " + optionName + " in component " + component);
      }
    } else {
      logger.warn("Warning: unregistered component " + component);
    }
  }
コード例 #20
0
  @SuppressWarnings({"unchecked"})
  @NotNull
  public static <T extends PsiType> T originalize(@NotNull T type) {
    if (!type.isValid()) {
      return type;
    }

    T result =
        new PsiTypeMapper() {
          private final Set<PsiClassType> myVisited = ContainerUtil.newIdentityTroveSet();

          @Override
          public PsiType visitClassType(final PsiClassType classType) {
            if (!myVisited.add(classType)) return classType;

            final PsiClassType.ClassResolveResult classResolveResult = classType.resolveGenerics();
            final PsiClass psiClass = classResolveResult.getElement();
            final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();
            if (psiClass == null) return classType;

            return new PsiImmediateClassType(
                CompletionUtil.getOriginalOrSelf(psiClass), originalizeSubstitutor(substitutor));
          }

          private PsiSubstitutor originalizeSubstitutor(final PsiSubstitutor substitutor) {
            PsiSubstitutor originalSubstitutor = PsiSubstitutor.EMPTY;
            for (final Map.Entry<PsiTypeParameter, PsiType> entry :
                substitutor.getSubstitutionMap().entrySet()) {
              final PsiType value = entry.getValue();
              originalSubstitutor =
                  originalSubstitutor.put(
                      CompletionUtil.getOriginalOrSelf(entry.getKey()),
                      value == null ? null : mapType(value));
            }
            return originalSubstitutor;
          }

          @Override
          public PsiType visitType(PsiType type) {
            return type;
          }
        }.mapType(type);
    if (result == null) {
      throw new AssertionError("Null result for type " + type + " of class " + type.getClass());
    }
    return result;
  }
コード例 #21
0
  @Override
  public <T> T cloneInternal(T o, Map<Object, Object> clones) throws IllegalAccessException {
    if (o == null) {
      return null;
    }

    @SuppressWarnings("unchecked")
    T clone = (T) cache.get(o);
    if (clone != null) {
      return clone;
    }

    T t = super.cloneInternal(o, clones);
    if (t != null && t != o && !t.getClass().isArray()) {
      cache.put(t, t);
    }
    return t;
  }
コード例 #22
0
  /** Return the value of an enum of the given type. Prefix allows a shortened form of the enum */
  @SuppressWarnings("unchecked")
  public <T extends Enum<T>> T getEnum(String prop, String prefix, T dflt) {
    Enum<?> v = dflt;
    String s = getProperty(prop);
    if (s == null || s.length() == 0) return dflt;
    if (prefix != null && !s.startsWith(prefix)) s = prefix + s;
    Object[] vals = dflt.getClass().getEnumConstants();
    if (vals == null) return dflt;
    for (int i = 0; i < vals.length; ++i) {
      Enum<?> e = (Enum<?>) vals[i];
      if (e.name().equalsIgnoreCase(s)) {
        v = e;
        break;
      }
    }

    return (T) v;
  }
コード例 #23
0
ファイル: ObjectMirror.java プロジェクト: andershong/jinghong
  @SuppressWarnings("unchecked")
  private <T> T clone(final T o, final Map<Object, Object> clones) throws IllegalAccessException {
    if (o == null) return null;
    if (ignoredInstances.containsKey(o)) return o;

    final Class<T> clz = (Class<T>) o.getClass();
    if (clz.isEnum()) return o;
    // skip cloning ignored classes
    if (ignored.contains(clz)) return o;
    final Object clonedPreviously = clones != null ? clones.get(o) : null;
    if (clonedPreviously != null) return (T) clonedPreviously;

    if (clz.isArray()) {
      final int length = Array.getLength(o);
      final T newInstance = (T) Array.newInstance(clz.getComponentType(), length);
      clones.put(o, newInstance);
      for (int i = 0; i < length; i++) {
        final Object v = Array.get(o, i);
        final Object clone = clones != null ? clone(v, clones) : v;
        Array.set(newInstance, i, clone);
      }
      return newInstance;
    }

    T newInstance = null;
    try {
      newInstance = newInstance(clz);
    } catch (InstantiationException e) {
      e.printStackTrace();
    }
    if (clones != null) {
      clones.put(o, newInstance);
    }
    final List<Field> fields = allFields(clz);
    for (final Field field : fields) {
      if (!Modifier.isStatic(field.getModifiers())) {
        field.setAccessible(true);
        final Object fieldObject = field.get(o);
        final Object fieldObjectClone = clones != null ? clone(fieldObject, clones) : fieldObject;
        field.set(newInstance, fieldObjectClone);
      }
    }
    return newInstance;
  }
コード例 #24
0
ファイル: XOManagerImpl.java プロジェクト: jexp/cdo-neo4j
 private <S, R, T> R createByExample(
     S from,
     Class<R> relationType,
     T to,
     Map<PrimitivePropertyMethodMetadata<PropertyMetadata>, Object> example) {
   MetadataProvider<EntityMetadata, EntityDiscriminator, RelationMetadata, RelationDiscriminator>
       metadataProvider = sessionContext.getMetadataProvider();
   AbstractRelationPropertyMethodMetadata<?> fromProperty =
       metadataProvider.getPropertyMetadata(from.getClass(), relationType, FROM);
   AbstractRelationPropertyMethodMetadata<?> toProperty =
       metadataProvider.getPropertyMetadata(to.getClass(), relationType, TO);
   Entity entity = sessionContext.getEntityInstanceManager().getDatastoreType(from);
   R instance =
       sessionContext
           .getEntityPropertyManager()
           .createRelationReference(entity, fromProperty, to, toProperty, example);
   sessionContext.getInstanceListenerService().postCreate(instance);
   return instance;
 }
コード例 #25
0
  /**
   * Creates an iterator that returns an {@link Options} containing each possible parameter set
   * defined by these {@link
   * com.biomatters.plugins.barcoding.validator.research.options.BatchOptions}. Note that the {@link
   * Options} object returned is always the same to save on initializing multiple copies. Each time
   * {@link java.util.Iterator#next()} is called the next parameter set is set on the {@link
   * Options}.
   *
   * @return An iterator that will iterate over all possible parameter sets specified by this {@link
   *     com.biomatters.plugins.barcoding.validator.research.options.BatchOptions}
   * @throws DocumentOperationException if there is a problem creating the {@link Options} object
   */
  public Iterator<T> iterator() throws DocumentOperationException {
    List<Set<OptionToSet>> possibleValues = new ArrayList<Set<OptionToSet>>();

    Map<String, MultiValueOption<?>> multiValueOptions = getMultiValueOptions("", options);
    for (Map.Entry<String, MultiValueOption<?>> entry : multiValueOptions.entrySet()) {
      possibleValues.add(getOptionsToSet(entry.getKey(), entry.getValue()));
    }
    Set<List<OptionToSet>> lists = Sets.cartesianProduct(possibleValues);
    final Iterator<List<OptionToSet>> possibilityIterator = lists.iterator();

    final T template;
    try {
      //noinspection unchecked
      template = (T) options.getClass().newInstance(); // getClass() doesn't return Class<T> :(
      template.valuesFromXML(options.valuesToXML(XMLSerializable.ROOT_ELEMENT_NAME));
    } catch (InstantiationException e) {
      throw new DocumentOperationException("Failed to create Options: " + e.getMessage(), e);
    } catch (IllegalAccessException e) {
      throw new DocumentOperationException("Failed to create Options: " + e.getMessage(), e);
    }

    return new Iterator<T>() {
      @Override
      public boolean hasNext() {
        return possibilityIterator.hasNext();
      }

      @Override
      public T next() {
        List<OptionToSet> possibility = possibilityIterator.next();
        for (OptionToSet optionToSet : possibility) {
          template.setValue(optionToSet.name, optionToSet.value);
        }
        return template;
      }

      @Override
      public void remove() {
        new UnsupportedOperationException();
      }
    };
  }
コード例 #26
0
 @SuppressWarnings("unchecked")
 public static <T extends JsonElement> T deepCopy(T from) {
   if (from == null) {
     throw new IllegalArgumentException("from must not be null");
   }
   if (from instanceof JsonObject) {
     return (T) deepCopyObj((JsonObject) from);
   }
   if (from instanceof JsonArray) {
     return (T) deepCopyArr((JsonArray) from);
   }
   if (from instanceof JsonNull) {
     return (T) JsonNull.INSTANCE;
   }
   if (from instanceof JsonPrimitive) {
     // Nulls and primitives are immutable
     return from;
   }
   throw new AssertionError("Unknown element type " + from.getClass().getName());
 }
コード例 #27
0
  @Nullable
  public static <T extends PsiElement> T getOriginalElement(@NotNull T psi) {
    final PsiFile file = psi.getContainingFile();
    if (file != null && file != file.getOriginalFile() && psi.getTextRange() != null) {
      TextRange range = psi.getTextRange();
      Integer start = range.getStartOffset();
      Integer end = range.getEndOffset();
      final Document document = file.getViewProvider().getDocument();
      if (document != null) {
        Document hostDocument =
            document instanceof DocumentWindowImpl
                ? ((DocumentWindowImpl) document).getDelegate()
                : document;
        OffsetTranslator translator = hostDocument.getUserData(RANGE_TRANSLATION);
        if (translator != null) {
          if (document instanceof DocumentWindowImpl) {
            start = ((DocumentWindowImpl) document).injectedToHost(start);
            end = ((DocumentWindowImpl) document).injectedToHost(end);
          }

          start = translator.translateOffset(start);
          end = translator.translateOffset(end);
          if (start == null || end == null) {
            return null;
          }

          if (document instanceof DocumentWindowImpl) {
            start = ((DocumentWindowImpl) document).hostToInjected(start);
            end = ((DocumentWindowImpl) document).hostToInjected(end);
          }
        }
      }
      //noinspection unchecked
      return (T)
          PsiTreeUtil.findElementOfClassAtRange(file.getOriginalFile(), start, end, psi.getClass());
    }

    return psi;
  }
コード例 #28
0
 /**
  * Method use OpenCsv Library for
  *
  * @param clazz the Class of the Bean.
  * @param fileInputCsv the File CSV to parse.
  * @param separator the char separator.
  * @param <T> the generic variable.
  * @return the List of Bean parsed from the CSV file.
  */
 public static <T> List<T> parseCSVFileAsList(Class<T> clazz, File fileInputCsv, char separator) {
   try {
     List<T> beans;
     try ( // create CSVReader object
     CSVReader reader = new CSVReader(new FileReader(fileInputCsv), separator)) {
       beans = new ArrayList<>();
       // read line by line
       String[] record;
       // skip header row
       String[] headers = reader.readNext();
       // read content
       while ((record = reader.readNext()) != null) {
         T t = ReflectionUtilities.invokeConstructor(clazz);
         for (int i = 0; i < record.length; i++) {
           String nameMethod = "set" + org.apache.commons.lang3.StringUtils.capitalize(headers[i]);
           // invoke setter method
           if (ReflectionUtilities.checkMethod(clazz, nameMethod)) {
             ReflectionUtilities.invokeSetter(t, nameMethod, record[i]);
           } else {
             logger.warn(
                 "Not exists the Method with name:"
                     + nameMethod
                     + " on the Bean:"
                     + t.getClass().getName());
           }
         }
         beans.add(t);
       }
     }
     return beans;
   } catch (IOException e) {
     logger.error(
         "Can't parse the CSV file:" + fileInputCsv.getAbsolutePath() + " -> " + e.getMessage(),
         e);
     return new ArrayList<>();
   }
 }
コード例 #29
0
  @NotNull
  public static <T extends DomElement> T getOriginalElement(@NotNull final T domElement) {
    final XmlElement psiElement = domElement.getXmlElement();
    if (psiElement == null) return domElement;

    final PsiFile psiFile = psiElement.getContainingFile().getOriginalFile();
    final TextRange range = psiElement.getTextRange();
    final PsiElement element = psiFile.findElementAt(range.getStartOffset());
    final int maxLength = range.getLength();
    final boolean isAttribute = psiElement instanceof XmlAttribute;
    final Class<? extends XmlElement> clazz = isAttribute ? XmlAttribute.class : XmlTag.class;
    final DomManager domManager = domElement.getManager();
    DomElement current = null;
    for (XmlElement next = PsiTreeUtil.getParentOfType(element, clazz, false);
        next != null && next.getTextLength() <= maxLength;
        next = PsiTreeUtil.getParentOfType(next, clazz, true)) {
      current =
          isAttribute
              ? domManager.getDomElement((XmlAttribute) next)
              : domManager.getDomElement((XmlTag) next);
      if (current != null && domElement.getClass() != current.getClass()) current = null;
    }
    return (T) current;
  }
コード例 #30
0
  public Query buildQuery(Integer type, T example, String... orden) {
    StringBuilder qry;
    List<String> ids = new ArrayList<String>();
    if (type == 1) {
      qry = new StringBuilder(SELECT_COUNT);
      qry.append(example.getClass().getSimpleName());
    } else {
      qry = new StringBuilder(SELECT);
      qry.append(example.getClass().getSimpleName());
      ids = this.obtenerId(example);
    }
    qry.append(FROM);
    qry.append(WHERE);
    List<Object> parametros = new ArrayList();
    Criterio criterio = new Criterio();
    Map<String, Object> propiedades = this.obtenerPropiedades(example);
    criterio.contruccion(propiedades);
    Set<String> igualdad = criterio.igualdad.keySet();
    Integer idx = 1;
    for (String key : igualdad) {
      if (idx > 1) {
        qry.append(AND);
      }
      qry.append(OBJ);
      qry.append(key);
      qry.append(EQ);
      qry.append(idx);
      parametros.add(criterio.igualdad.get(key));
      idx++;
    }

    Set<String> likeKeys = criterio.like.keySet();
    for (String key : likeKeys) {
      if (idx > 1) {
        qry.append(AND);
      }
      Object valor = criterio.like.get(key);
      if (valor instanceof String) {
        qry.append(LOWER);
        qry.append(OBJ);
        qry.append(key);
        qry.append(")");
        qry.append(LIKE);
        qry.append(idx);
        parametros.add(((String) valor).toLowerCase());
      } else {
        qry.append(OBJ);
        qry.append(key);
        qry.append(LIKE);
        qry.append(idx);
        parametros.add(valor);
      }
      idx++;
    }

    Set<String> compositeKeys = criterio.compuesto.keySet();
    for (String key : compositeKeys) {
      Object value = criterio.compuesto.get(key);
      try {
        if (value.toString().startsWith("class java.util")) {
          continue;
        } else if (StringUtils.containsIgnoreCase(key, "pk")) {
          Map<String, Object> propsComposites = this.obtenerPropiedades(value, key);
          Criterio criterioCompuesto = new Criterio();
          criterioCompuesto.contruccion(propsComposites);
          if (!criterioCompuesto.igualdad.isEmpty()) {
            Set<String> eqKeysPK = criterioCompuesto.igualdad.keySet();
            for (String keyPK : eqKeysPK) {
              if (idx > 1) {
                qry.append(AND);
              }
              qry.append(OBJ);
              qry.append(keyPK);
              qry.append(EQ);
              qry.append(idx);
              parametros.add(criterioCompuesto.igualdad.get(keyPK));
              idx++;
            }
          }
          if (!criterioCompuesto.like.isEmpty()) {
            Set<String> likeKeysPK = criterioCompuesto.like.keySet();
            for (String keyPK : likeKeysPK) {
              if (idx > 1) {
                qry.append(AND);
              }
              Object valor = criterioCompuesto.like.get(keyPK);
              if (valor instanceof String) {
                qry.append(LOWER);
                qry.append(OBJ);
                qry.append(keyPK);
                qry.append(")");
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(((String) valor).toLowerCase());
              } else {
                qry.append(OBJ);
                qry.append(keyPK);
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(valor);
              }
              idx++;
            }
          }
        } else {
          Map<String, Object> propsComposites = this.obtenerPropiedades(value);
          Criterio criterioCompuesto = new Criterio();
          criterioCompuesto.contruccion(propsComposites);
          if (!criterioCompuesto.igualdad.isEmpty()) {
            Set<String> eqKeysPK = criterioCompuesto.igualdad.keySet();
            for (String keyPK : eqKeysPK) {
              if (idx > 1) {
                qry.append(AND);
              }
              qry.append(OBJ);
              qry.append(key);
              qry.append(".");
              qry.append(keyPK);
              qry.append(EQ);
              qry.append(idx);
              parametros.add(criterioCompuesto.igualdad.get(keyPK));
              idx++;
            }
          }
          if (!criterioCompuesto.like.isEmpty()) {
            Set<String> likeKeysPK = criterioCompuesto.like.keySet();
            for (String keyPK : likeKeysPK) {
              System.out.println(
                  "Compuesto LIKE: " + keyPK + ", " + criterioCompuesto.igualdad.get(keyPK));
              if (idx > 1) {
                qry.append(AND);
              }
              Object valor = criterioCompuesto.like.get(keyPK);
              if (valor instanceof String) {
                qry.append(LOWER);
                qry.append(OBJ);
                qry.append(key);
                qry.append(".");
                qry.append(keyPK);
                qry.append(")");
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(((String) valor).toLowerCase());
              } else {
                qry.append(OBJ);
                qry.append(key);
                qry.append(".");
                qry.append(keyPK);
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(valor);
              }
              idx++;
            }
          }
        }
      } catch (RuntimeException e) {
        continue;
      }
    }

    if (idx == 1) {
      qry.append(" 1=1");
    }
    if (!ids.isEmpty()) {
      qry.append(ORDER);
    } else {
      qry.append("  ");
    }
    if (orden.length > 0) {
      for (String ord : orden) {
        qry.append(OBJ);
        qry.append(ord.substring(2));
        if (ord.startsWith("A,")) {
          qry.append(ASC);
        } else if (ord.startsWith("D,")) {
          qry.append(DESC);
        }
      }
    } else {
      for (String id : ids) {
        if (!id.contains("_persistence")) {
          qry.append(OBJ);
          qry.append(id);
          qry.append(ASC);
        }
      }
    }

    System.out.println(qry.substring(0, qry.length() - 2));
    Query query = this.em.createQuery(qry.substring(0, qry.length() - 2));
    if (!parametros.isEmpty()) {
      int i = 1;
      for (Object obj : parametros) {
        query.setParameter(i, obj);
        i++;
      }
    }
    return query;
  }