Пример #1
2
    private static boolean isSetException(Score score)
        throws NoSuchMethodException, NoSuchFieldException, IllegalAccessException,
            InvocationTargetException {
      Object craftScore = CRAFT_SCORE.cast(score);

      Object craftObjective = CRAFT_OBJECTIVE.cast(score.getObjective());
      Method craftHandle = CRAFT_OBJECTIVE.getDeclaredMethod("getHandle");
      craftHandle.setAccessible(true);
      Object craftObjectiveHandle = craftHandle.invoke(craftObjective);

      Field objective = CRAFT_SCORE.getDeclaredField("objective");
      objective.setAccessible(true);
      Object craftScoreboard = checkState(objective.get(craftScore));

      Field craftBoard = CRAFT_SCOREBOARD.getDeclaredField("board");
      craftBoard.setAccessible(true);
      Object scoreboard = craftBoard.get(craftScoreboard);
      Method playerObjectives = SCOREBOARD.getDeclaredMethod("getPlayerObjectives", String.class);
      playerObjectives.setAccessible(true);

      Field playerField = CRAFT_SCORE.getDeclaredField("entry");
      playerField.setAccessible(true);
      String playerName = (String) playerField.get(craftScore);
      Map map = (Map) playerObjectives.invoke(scoreboard, playerName);

      // return
      // objective.checkState().board.getPlayerObjectives(playerName).containsKey(objective.getHandle());
      return map.containsKey(craftObjectiveHandle);
    }
Пример #2
1
  private <T extends View> T instanceView(Class<T> view) {
    if (view.isAssignableFrom(JSONSerialization.class)) {
      serialization =
          new GsonJSONSerialization(
              response, extractor, gsonBuilder, environment, reflectionProvider);
      return view.cast(serialization);
    }

    if (view.isAssignableFrom(XMLSerialization.class)) {
      serialization = new XStreamXMLSerialization(response, xstreambuilder, environment);
      return view.cast(serialization);
    }

    if (view.isAssignableFrom(RepresentationResult.class)) {
      serialization = new XStreamXMLSerialization(response, xstreambuilder, environment);
      return view.cast(
          new DefaultRepresentationResult(
              new FormatResolver() {
                @Override
                public String getAcceptFormat() {
                  return "xml";
                }
              },
              this,
              new MockInstanceImpl<>(this.serialization)));
    }

    return proxifier.proxify(view, returnOnFinalMethods(view));
  }
  /**
   * Adapts the source object to a view object.
   *
   * @param mapper An action that is invoked for each source object in the graph that is to be
   *     adapted. The action can influence how the source object is adapted via the provided {@link
   *     SourceObjectMapping}.
   */
  public <T, S> T adapt(
      Class<T> targetType, S sourceObject, Action<? super SourceObjectMapping> mapper) {
    if (sourceObject == null) {
      return null;
    }
    Class<? extends T> wrapperType = targetTypeProvider.getTargetType(targetType, sourceObject);
    DefaultSourceObjectMapping mapping =
        new DefaultSourceObjectMapping(sourceObject, targetType, wrapperType);
    mapper.execute(mapping);
    wrapperType = mapping.wrapperType.asSubclass(targetType);
    if (wrapperType.isInstance(sourceObject)) {
      return wrapperType.cast(sourceObject);
    }
    if (targetType.isEnum()) {
      return adaptToEnum(targetType, sourceObject);
    }

    MixInMethodInvoker mixInMethodInvoker = null;
    if (mapping.mixInType != null) {
      mixInMethodInvoker =
          new MixInMethodInvoker(
              mapping.mixInType, new AdaptingMethodInvoker(mapper, new ReflectionMethodInvoker()));
    }
    MethodInvoker overrideInvoker = chainInvokers(mixInMethodInvoker, mapping.overrideInvoker);
    Object proxy =
        Proxy.newProxyInstance(
            wrapperType.getClassLoader(),
            new Class<?>[] {wrapperType},
            new InvocationHandlerImpl(sourceObject, overrideInvoker, mapper));
    if (mixInMethodInvoker != null) {
      mixInMethodInvoker.setProxy(proxy);
    }
    return wrapperType.cast(proxy);
  }
  /**
   * Method description
   *
   * @param ht_def_key
   * @param ht_dev_val
   * @param st_def_key
   * @param st_def_val
   * @param prop_key
   * @param prop_val_class
   * @param params
   * @param props
   * @param <T>
   */
  protected <T> void checkHighThroughputProperty(
      String ht_def_key,
      T ht_dev_val,
      String st_def_key,
      T st_def_val,
      String prop_key,
      Class<T> prop_val_class,
      Map<String, Object> params,
      Map<String, Object> props) {
    T tmp = st_def_val;
    String str_tmp = null;

    if (isHighThroughput()) {
      tmp = ht_dev_val;
      str_tmp = (String) params.get(ht_def_key);
    } else {
      tmp = st_def_val;
      str_tmp = (String) params.get(st_def_key);
    }
    if (prop_val_class.isAssignableFrom(Integer.class)) {
      tmp = prop_val_class.cast(DataTypes.parseNum(str_tmp, Integer.class, (Integer) tmp));
    }
    if (prop_val_class.isAssignableFrom(Long.class)) {
      tmp = prop_val_class.cast(DataTypes.parseNum(str_tmp, Long.class, (Long) tmp));
    }
    if (prop_val_class.isAssignableFrom(String.class)) {
      tmp = prop_val_class.cast(str_tmp);
    }
    props.put(prop_key, tmp);
  }
Пример #5
1
  /**
   * Coerce the given object to targetType.
   *
   * @param value object to be coerced
   * @param targetType which should be object coerced into
   * @return the given value coerced to targetType
   */
  public static <T> T coerce(Object value, Class<T> targetType) {
    if (value == null) {
      return null;
    }

    if (targetType.isInstance(value)) {
      return targetType.cast(value);
    }

    if (value instanceof String) {
      PropertyEditor editor = PropertyEditorManager.findEditor(targetType);
      if (editor == null && Primitives.isWrapperType(targetType)) {
        editor = PropertyEditorManager.findEditor(Primitives.unwrap(targetType));
      }

      if (editor != null) {

        editor.setAsText((String) value);
        return targetType.cast(editor.getValue());
      } else if (targetType.isEnum()) {
        return targetType.cast(Enum.valueOf((Class<Enum>) targetType, (String) value));
      }
    }

    throw new IllegalArgumentException(
        MessageFormat.format(
            "Cannot convert {0} to object of {1} type", value, targetType.getName()));
  }
  public BuildComparisonSpec createSpec(Set<BuildOutcome> from, Set<BuildOutcome> to) {
    BuildComparisonSpecBuilder builder = new DefaultBuildComparisonSpecBuilder();

    Set<BuildOutcome> toCopy = new HashSet<BuildOutcome>(to);

    for (BuildOutcome fromBuildOutcome : from) {
      BuildOutcome toBuildOutcome = null;
      Class<? extends BuildOutcome> associationType = null;

      for (BuildOutcome buildOutcome : toCopy) {
        toBuildOutcome = buildOutcome;
        associationType = associator.findAssociationType(fromBuildOutcome, toBuildOutcome);

        if (associationType != null) {
          break;
        }
      }

      if (associationType == null) {
        builder.addUnassociatedFrom(fromBuildOutcome);
      } else {
        builder.associate(
            associationType.cast(fromBuildOutcome),
            associationType.cast(toBuildOutcome),
            (Class<BuildOutcome>) associationType);
        toCopy.remove(toBuildOutcome);
      }
    }

    for (BuildOutcome buildOutcome : toCopy) {
      builder.addUnassociatedTo(buildOutcome);
    }

    return builder.build();
  }
Пример #7
0
 public static <T> T getInstance(
     Class<T> expectedType,
     String className,
     Collection<?> ctorObjs,
     Class<? extends T> defaultClass)
     throws TranslatorException {
   try {
     if (className == null) {
       if (defaultClass == null) {
         throw new TranslatorException(
             DataPlugin.Event.TEIID60004, DataPlugin.Util.gs(DataPlugin.Event.TEIID60004));
       }
       return expectedType.cast(defaultClass.newInstance());
     }
     return expectedType.cast(
         ReflectionHelper.create(
             className, ctorObjs, Thread.currentThread().getContextClassLoader()));
   } catch (TeiidException e) {
     throw new TranslatorException(DataPlugin.Event.TEIID60005, e);
   } catch (IllegalAccessException e) {
     throw new TranslatorException(DataPlugin.Event.TEIID60005, e);
   } catch (InstantiationException e) {
     throw new TranslatorException(DataPlugin.Event.TEIID60005, e);
   }
 }
Пример #8
0
  @Override
  protected <T> T internalValueOfString(
      final String value,
      final EdmLiteralKind literalKind,
      final EdmFacets facets,
      final Class<T> returnType)
      throws EdmSimpleTypeException {
    Calendar valueCalendar;
    if (literalKind == EdmLiteralKind.URI) {
      if (value.length() > 6 && value.startsWith("time'") && value.endsWith("'")) {
        valueCalendar = parseLiteral(value.substring(5, value.length() - 1), facets);
      } else {
        throw new EdmSimpleTypeException(
            EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value));
      }
    } else {
      valueCalendar = parseLiteral(value, facets);
    }

    if (returnType.isAssignableFrom(Calendar.class)) {
      return returnType.cast(valueCalendar);
    } else if (returnType.isAssignableFrom(Long.class)) {
      return returnType.cast(valueCalendar.getTimeInMillis());
    } else if (returnType.isAssignableFrom(Date.class)) {
      return returnType.cast(valueCalendar.getTime());
    } else {
      throw new EdmSimpleTypeException(
          EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
    }
  }
Пример #9
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  private final Object bindResourceToContainer(
      final Class resource, final Object containerInstance) {
    final ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(resource);
    factory.setFilter(method -> Modifier.isAbstract(method.getModifiers()));

    final MethodHandler handler =
        (b, thisMethod, proceed, args) -> {
          final Method containerMethod = resourceToContainer.get(thisMethod);
          if (containerMethod != null) {
            return containerMethod.invoke(containerInstance, args);
          } else {
            throw new IllegalAccessException(
                thisMethod
                    + " is not implemented in "
                    + containerInstance.getClass()
                    + " via interface");
          }
        };

    try {
      final Object resourceInstance =
          resource.cast(factory.create(new Class<?>[0], new Object[0], handler));
      bind(resource).toInstance(resource.cast(resourceInstance));
      return resourceInstance;
    } catch (NoSuchMethodException
        | IllegalArgumentException
        | InstantiationException
        | IllegalAccessException
        | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
  }
Пример #10
0
  /**
   * resolves n to node of type R or S, via declaration returns null if n's declaration can't be
   * cast to R/S
   */
  private Pair<R, S> resolve(IdentNode n) {
    if (n instanceof PackageIdentNode) {
      if (!resolveOwner((PackageIdentNode) n)) {
        return null;
      }
    }

    Pair<R, S> pair = new Pair<R, S>();
    DeclNode resolved = n.getDecl();
    if (clsR.isInstance(resolved)) {
      pair.fst = clsR.cast(resolved);
    }
    if (clsS.isInstance(resolved)) {
      pair.snd = clsS.cast(resolved);
    }
    if (pair.fst != null || pair.snd != null) {
      return pair;
    }

    n.reportError(
        "\""
            + n
            + "\" is a "
            + resolved.getUseString()
            + " but a "
            + Util.getStrListWithOr(classes, BaseNode.class, "getUseStr")
            + " is expected");
    return null;
  }
Пример #11
0
 protected void internalReceive(HttpResponseStatus status, HttpHeaders headers, ByteBuf content) {
   try {
     if (status.code() > 399) {
       byte[] b = new byte[content.readableBytes()];
       content.readBytes(b);
       onErrorResponse(status, headers, new String(b, CharsetUtil.UTF_8));
       return;
     }
     if (type == ByteBuf.class) {
       _doReceive(status, headers, type.cast(content));
     } else if (type == String.class || type == CharSequence.class) {
       byte[] b = new byte[content.readableBytes()];
       content.readBytes(b);
       _doReceive(status, headers, type.cast(new String(b, CharsetUtil.UTF_8)));
     } else if (type == byte[].class) {
       byte[] b = new byte[content.readableBytes()];
       content.readBytes(b);
       _doReceive(status, headers, type.cast(b));
     } else {
       ObjectMapper mapper = new ObjectMapper();
       byte[] b = new byte[content.readableBytes()];
       content.readBytes(b);
       try {
         Object o = mapper.readValue(b, type);
         _doReceive(status, headers, type.cast(o));
       } catch (Exception ex) {
         Exceptions.chuck(ex);
       }
     }
   } finally {
     latch.countDown();
   }
 }
Пример #12
0
  /**
   * resolves n to node of type R, via declaration if n is an identifier, via simple cast otherwise
   * returns null if n's declaration or n can't be cast to R or S
   */
  public Pair<R, S> resolve(BaseNode n, BaseNode parent) {
    if (n instanceof IdentNode) {
      Pair<R, S> pair = resolve((IdentNode) n);
      if (pair != null) {
        assert pair.fst == null || pair.snd == null;
        parent.becomeParent(pair.fst);
        parent.becomeParent(pair.snd);
      }
      return pair;
    }

    Pair<R, S> pair = new Pair<R, S>();
    if (clsR.isInstance(n)) {
      pair.fst = clsR.cast(n);
    }
    if (clsS.isInstance(n)) {
      pair.snd = clsS.cast(n);
    }
    if (pair.fst != null || pair.snd != null) {
      assert pair.fst == null || pair.snd == null;
      return pair;
    }

    n.reportError(
        "\""
            + n
            + "\" is a "
            + n.getUseString()
            + " but a "
            + Util.getStrListWithOr(classes, BaseNode.class, "getUseStr")
            + " is expected");
    return null;
  }
Пример #13
0
  /**
   * Convert {@code Object} value to a value of the specified class type.
   *
   * @param value {@code Object} value to convert.
   * @param type conversion type.
   * @param <T> converted value type.
   * @return value converted to the specified class type.
   */
  public static <T> T convertValue(Object value, Class<T> type) {
    if (!type.isInstance(value)) {
      // TODO: Move string value readers from server to common and utilize them here
      final Constructor constructor =
          AccessController.doPrivileged(ReflectionHelper.getStringConstructorPA(type));
      if (constructor != null) {
        try {
          return type.cast(constructor.newInstance(value));
        } catch (Exception e) {
          // calling the constructor wasn't successful - ignore and try valueOf()
        }
      }

      final Method valueOf =
          AccessController.doPrivileged(ReflectionHelper.getValueOfStringMethodPA(type));
      if (valueOf != null) {
        try {
          return type.cast(valueOf.invoke(null, value));
        } catch (Exception e) {
          // calling valueOf wasn't successful
        }
      }

      // at this point we don't know what to return -> return null
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.warning(
            LocalizationMessages.PROPERTIES_HELPER_GET_VALUE_NO_TRANSFORM(
                String.valueOf(value), value.getClass().getName(), type.getName()));
      }

      return null;
    }

    return type.cast(value);
  }
 private static <T> T decodePropertyValue(
     String fullPropertyName,
     @Nullable String propertyValue,
     Class<T> type,
     PropertyMetadata<?> metadata) {
   if (metadata.getJavaType() != type) {
     throw new PrestoException(
         INVALID_SESSION_PROPERTY,
         format(
             "Property %s is type %s, but requested type was %s",
             fullPropertyName, metadata.getJavaType().getName(), type.getName()));
   }
   if (propertyValue == null) {
     return type.cast(metadata.getDefaultValue());
   }
   Object objectValue = deserializeSessionProperty(metadata.getSqlType(), propertyValue);
   try {
     return type.cast(metadata.decode(objectValue));
   } catch (PrestoException e) {
     throw e;
   } catch (Exception e) {
     // the system property decoder can throw any exception
     throw new PrestoException(
         INVALID_SESSION_PROPERTY,
         format("%s is invalid: %s", fullPropertyName, propertyValue),
         e);
   }
 }
Пример #15
0
  /*
   * Required adaptions: <ul> <li>IGeoResourceInfo.class <li>IService.class
   * </ul>
   *
   * @see net.refractions.udig.catalog.IResolve#resolve(java.lang.Class,
   * org.eclipse.core.runtime.IProgressMonitor)
   */
  public <T> T resolve(Class<T> adaptee, IProgressMonitor monitor) throws IOException {
    if (adaptee == null) return null;

    if (adaptee.isAssignableFrom(IGeoResourceInfo.class)) {
      return adaptee.cast(createInfo(monitor));
    }
    if (adaptee.isAssignableFrom(IGeoResource.class)) {
      return adaptee.cast(this);
    }

    JDBCDataStore dataStore = parent.getDataStore();
    if (adaptee.isAssignableFrom(DataStore.class)) {
      return adaptee.cast(dataStore);
    }
    if (adaptee.isAssignableFrom(SimpleFeatureStore.class)) {
      FeatureSource<SimpleFeatureType, SimpleFeature> fs = dataStore.getFeatureSource(typename);
      if (fs instanceof FeatureStore) {
        readOnly = false;
        return adaptee.cast(fs);
      } else {
        readOnly = true;
      }
      if (adaptee.isAssignableFrom(SimpleFeatureSource.class)) {
        return adaptee.cast(dataStore.getFeatureSource(typename));
      }
    }
    if (adaptee.isAssignableFrom(Connection.class)) {
      return service.resolve(adaptee, monitor);
    }

    return super.resolve(adaptee, monitor);
  }
Пример #16
0
  public <T> T decodeProperty(String name, @Nullable String value, Class<T> type) {
    requireNonNull(name, "name is null");
    requireNonNull(type, "type is null");

    SessionProperty<?> sessionProperty = allSessionProperties.get(name);
    if (sessionProperty == null) {
      throw new PrestoException(INVALID_SESSION_PROPERTY, "Unknown session property " + name);
    }
    PropertyMetadata<?> metadata = sessionProperty.getMetadata();
    if (metadata.getJavaType() != type) {
      throw new PrestoException(
          INVALID_SESSION_PROPERTY,
          format(
              "Property %s is type %s, but requested type was %s",
              name, metadata.getJavaType().getName(), type.getName()));
    }
    if (value == null) {
      return type.cast(metadata.getDefaultValue());
    }
    Object objectValue = deserializeSessionProperty(metadata.getSqlType(), value);
    try {
      return type.cast(metadata.decode(objectValue));
    } catch (PrestoException e) {
      throw e;
    } catch (Exception e) {
      // the system property decoder can throw any exception
      throw new PrestoException(
          INVALID_SESSION_PROPERTY, format("%s is invalid: %s", name, value), e);
    }
  }
Пример #17
0
 public static <E1 extends Exception, E2 extends Exception, E3 extends Exception>
     ValueOrException3<E1, E2, E3> downconvert(
         ValueOrException4<E1, E2, E3, BottomException> voe,
         Class<E1> exceptionClass1,
         Class<E2> exceptionClass2,
         Class<E3> exceptionClass3) {
   Exception e = voe.getException();
   if (e == null) {
     return new ValueOrException3ValueImpl<>(voe.getValue());
   }
   if (exceptionClass1.isInstance(e)) {
     return new ValueOrException3Exn1Impl<>(exceptionClass1.cast(e));
   }
   if (exceptionClass2.isInstance(e)) {
     return new ValueOrException3Exn2Impl<>(exceptionClass2.cast(e));
   }
   if (exceptionClass3.isInstance(e)) {
     return new ValueOrException3Exn3Impl<>(exceptionClass3.cast(e));
   }
   throw new IllegalStateException(
       "shouldn't reach here "
           + e.getClass()
           + " "
           + exceptionClass1
           + " "
           + exceptionClass2
           + " "
           + exceptionClass3,
       e);
 }
  @Override
  protected <T> T internalValueOfString(
      final String value,
      final Boolean isNullable,
      final Integer maxLength,
      final Integer precision,
      final Integer scale,
      final Boolean isUnicode,
      final Class<T> returnType)
      throws EdmPrimitiveTypeException {

    if (!Base64.isBase64(value)) {
      throw new EdmPrimitiveTypeException(
          "EdmPrimitiveTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value)");
    }
    if (!validateMaxLength(value, maxLength)) {
      throw new EdmPrimitiveTypeException(
          "EdmPrimitiveTypeException.LITERAL_FACETS_NOT_MATCHED.addContent(value, facets)");
    }

    final byte[] result = Base64.decodeBase64(value);

    if (returnType.isAssignableFrom(byte[].class)) {
      return returnType.cast(result);
    } else if (returnType.isAssignableFrom(Byte[].class)) {
      final Byte[] byteArray = new Byte[result.length];
      for (int i = 0; i < result.length; i++) {
        byteArray[i] = result[i];
      }
      return returnType.cast(byteArray);
    } else {
      throw new EdmPrimitiveTypeException(
          "EdmPrimitiveTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType)");
    }
  }
  @Override
  protected <T> T internalValueOfString(
      final String value,
      final Boolean isNullable,
      final Integer maxLength,
      final Integer precision,
      final Integer scale,
      final Boolean isUnicode,
      final Class<T> returnType)
      throws EdmPrimitiveTypeException {

    Double result = null;
    BigDecimal bigDecimalValue = null;
    // Handle special values first.
    if (value.equals(NEGATIVE_INFINITY)) {
      result = Double.NEGATIVE_INFINITY;
    } else if (value.equals(POSITIVE_INFINITY)) {
      result = Double.POSITIVE_INFINITY;
    } else if (value.equals(NaN)) {
      result = Double.NaN;
    } else {
      // Now only "normal" numbers remain.
      if (!PATTERN.matcher(value).matches()) {
        throw new EdmPrimitiveTypeException(
            "EdmPrimitiveTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value)");
      }

      // The number format is checked above, so we don't have to catch NumberFormatException.
      bigDecimalValue = new BigDecimal(value);
      result = bigDecimalValue.doubleValue();
      // "Real" infinite values have been treated already above, so we can throw an exception
      // if the conversion to a double results in an infinite value.
      if (result.isInfinite() || BigDecimal.valueOf(result).compareTo(bigDecimalValue) != 0) {
        throw new EdmPrimitiveTypeException(
            "EdmPrimitiveTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value)");
      }
    }

    if (returnType.isAssignableFrom(Double.class)) {
      return returnType.cast(result);
    } else if (result.isInfinite() || result.isNaN()) {
      if (returnType.isAssignableFrom(Float.class)) {
        return returnType.cast(result.floatValue());
      } else {
        throw new EdmPrimitiveTypeException(
            "EdmPrimitiveTypeException.LITERAL_UNCONVERTIBLE_TO_VALUE_TYPE.addContent(value, returnType)");
      }
    } else {
      try {
        return EdmDecimal.convertDecimal(bigDecimalValue, returnType);
      } catch (final IllegalArgumentException e) {
        throw new EdmPrimitiveTypeException(
            "EdmPrimitiveTypeException.LITERAL_UNCONVERTIBLE_TO_VALUE_TYPE.addContent(value, returnType), e");
      } catch (final ClassCastException e) {
        throw new EdmPrimitiveTypeException(
            "EdmPrimitiveTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType), e");
      }
    }
  }
Пример #20
0
 @Override
 public boolean run(Object a, Object b) {
   T tInstance = tK.cast(tK.isInstance(a) ? a : (tK.isInstance(b) ? b : null));
   V vInstance = vK.cast(vK.isInstance(b) ? b : (vK.isInstance(a) ? a : null));
   if (tInstance != null && vInstance != null && tInstance != vInstance) {
     return conflicts(tInstance, vInstance);
   } else return false;
 }
Пример #21
0
 @SuppressWarnings("unchecked")
 public static <K, V> Map<K, V> castMap(Map<?, ?> map, Class<K> kClass, Class<V> vClass) {
   for (Map.Entry<?, ?> entry : map.entrySet()) {
     kClass.cast(entry.getKey());
     vClass.cast(entry.getValue());
   }
   return (Map<K, V>) map;
 }
  @Override
  public <T extends BlockObject> T ingestBlockObjects(
      IngestionRequestContext requestContext, Class<T> clazz) throws IngestionException {

    UnManagedVolume unManagedVolume = requestContext.getCurrentUnmanagedVolume();

    String volumeNativeGuid =
        unManagedVolume
            .getNativeGuid()
            .replace(VolumeIngestionUtil.UNMANAGEDVOLUME, VolumeIngestionUtil.VOLUME);
    BlockObject blockObject =
        VolumeIngestionUtil.checkIfVolumeExistsInDB(volumeNativeGuid, _dbClient);

    // validate srdf blockObjects.
    validateUnManagedVolumeProperties(
        unManagedVolume,
        requestContext.getVarray(unManagedVolume),
        requestContext.getVpool(unManagedVolume),
        requestContext.getProject());
    // Check if ingested volume has exportmasks pending for ingestion.
    if (isExportIngestionPending(
        blockObject,
        unManagedVolume.getId(),
        requestContext.getVolumeContext().isVolumeExported())) {
      return clazz.cast(blockObject);
    }

    if (null == blockObject) {
      blockObject = super.ingestBlockObjects(requestContext, clazz);

      if (null == blockObject) {
        _logger.warn(
            "SRDF Volume ingestion failed for unmanagedVolume {}", unManagedVolume.getNativeGuid());
        throw IngestionException.exceptions.unmanagedVolumeMasksNotIngested(
            unManagedVolume.getNativeGuid(), "none.");
      }
    } else {
      // blockObject already ingested, now just update internalflags &
      // srdf relationships. Run this logic always when volume NO_PUBLIC_ACCESS
      if (markUnManagedVolumeInactive(requestContext, blockObject)) {
        _logger.info(
            "All the related replicas and parent of unManagedVolume {} has been ingested ",
            unManagedVolume.getNativeGuid());
        unManagedVolume.setInactive(true);
        requestContext.getUnManagedVolumesToBeDeleted().add(unManagedVolume);
      } else {
        _logger.info(
            "Not all the parent/replicas of unManagedVolume {} have been ingested , hence marking as internal",
            unManagedVolume.getNativeGuid());
        blockObject.addInternalFlags(INTERNAL_VOLUME_FLAGS);
      }
    }
    // Decorate blockobjects with SRDF Properties.
    decorateBlockObjectWithSRDFProperties(blockObject, unManagedVolume);

    return clazz.cast(blockObject);
  }
Пример #23
0
  public static <T> T getService(Class<T> serviceClass) {

    if (MessageService.class.isAssignableFrom(serviceClass)) {
      return serviceClass.cast(MessageServiceImpl.instance());
    } else if (ChatService.class.isAssignableFrom(serviceClass)) {
      return serviceClass.cast(ChatServiceImpl.instance());
    }
    return null;
  }
Пример #24
0
 @Override
 public <T> T narrow(Class<T> target) {
   if (target == Socket.class) {
     return target.cast(socket);
   } else if (target == TimeStampStream.class) {
     return target.cast(buffOut);
   }
   return super.narrow(target);
 }
 @Override
 public <T> T getAdapter(Class<T> adapter) {
   if (adapter == WebEngine.class) {
     return adapter.cast(engine);
   } else if (adapter == FileChangeNotifier.class) {
     return adapter.cast(notifier);
   }
   return null;
 }
 public <T> T unwrap(Class<T> iface) throws SQLException {
   if (iface.isAssignableFrom(getClass())) {
     return iface.cast(this);
   } else if (iface.isAssignableFrom(_meta.getClass())) {
     return iface.cast(_meta);
   } else {
     return _meta.unwrap(iface);
   }
 }
Пример #27
0
 @Override
 public <T extends Tool> T getTool(final Class<T> toolClass) {
   for (final Tool tool : alwaysActiveToolList) {
     if (toolClass.isInstance(tool)) return toolClass.cast(tool);
   }
   for (final Tool tool : toolList) {
     if (toolClass.isInstance(tool)) return toolClass.cast(tool);
   }
   return null;
 }
Пример #28
0
 @Override
 public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) {
   if (adapterType == IPropertySource.class && adaptableObject instanceof Todo) {
     return adapterType.cast(new TodoPropertySource((Todo) adaptableObject));
   } else if (adapterType.isAssignableFrom(WorkbenchAdapter.class)
       && adaptableObject instanceof Todo) {
     return adapterType.cast(new TodoWorkbenchAdapter());
   }
   return null;
 }
Пример #29
0
 private void invokeSecureMethod(Object obj) {
   borderPaint = new Paint();
   textPaint = new Paint();
   Class class1 = Class.forName("com.socialin.android.photo.textart.TextArtStyle");
   try {
     class1
         .getMethod("setFillColor", new Class[] {Integer.TYPE})
         .invoke(class1.cast(obj), new Object[] {Integer.valueOf(fillColor)});
     Class.forName("com.socialin.android.photo.textart.TextArt")
         .getMethod(
             "initTextArtForDrawing",
             new Class[] {
               android / content / Context,
               class1,
               android / graphics / Paint,
               android / graphics / Paint
             })
         .invoke(null, new Object[] {d.a(), class1.cast(obj), textPaint, borderPaint});
     return;
   }
   // Misplaced declaration of an exception variable
   catch (Object obj) {
   }
   // Misplaced declaration of an exception variable
   catch (Object obj) {
   }
   // Misplaced declaration of an exception variable
   catch (Object obj) {
   }
   try {
     com.socialin.android.d.b(
         TAG,
         new Object[] {
           (new StringBuilder("Got unexpected exception: "))
               .append(((Exception) (obj)).getMessage())
               .toString()
         });
     return;
   }
   // Misplaced declaration of an exception variable
   catch (Object obj) {
   }
   // Misplaced declaration of an exception variable
   catch (Object obj) {
   }
   com.socialin.android.d.b(
       TAG,
       new Object[] {
         (new StringBuilder("Got unexpected exception: "))
             .append(((ReflectiveOperationException) (obj)).getMessage())
             .toString()
       });
   return;
 }
  @SuppressWarnings("unchecked")
  private static <T> T[] parseArray(String string, Class<T> type) throws InvocationTargetException {
    String[] splitString;
    Method parser;
    Method allocator;
    Integer size;

    if (string == null || string.length() == 0) {
      size = 0;
      splitString = new String[0];
    } else {
      splitString = string.split(",");
      size = splitString.length;
    }

    allocator = allocatorMap.get(type);
    parser = parserMap.get(type);

    T[] array = null;
    try {
      array = (T[]) allocator.invoke(null, splitString.length);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }

    int i = 0;
    for (String sub : splitString) {
      if (sub.length() == 0) {
        break; // Skip over empties
      }

      try {
        T obj;
        if (parser == null) {
          obj = type.cast(sub); // Attempt to cast to T
        } else {
          obj = type.cast(parser.invoke(type, sub));
        }
        array[i] = obj;
        ++i;
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }

    return array;
  }