Example #1
0
 /**
  * Create a new instance.
  *
  * @param zipkinCollectorHost Host for zipkin collector.
  * @param zipkinCollectorPort Port for zipkin collector.
  * @param params Zipkin Span Collector parameters.
  */
 public ZipkinSpanCollector(
     final String zipkinCollectorHost,
     final int zipkinCollectorPort,
     final ZipkinSpanCollectorParams params) {
   Validate.notEmpty(zipkinCollectorHost);
   Validate.notNull(params);
   clientProvider =
       new ZipkinCollectorClientProvider(
           zipkinCollectorHost, zipkinCollectorPort, params.getSocketTimeout());
   try {
     clientProvider.setup();
   } catch (final TException e) {
     if (params.failOnSetup()) {
       throw new IllegalStateException(e);
     } else {
       LOGGER.warn("Connection could not be established during setup.", e);
     }
   }
   spanQueue = new ArrayBlockingQueue<Span>(params.getQueueSize());
   executorService = Executors.newFixedThreadPool(params.getNrOfThreads());
   for (int i = 1; i <= params.getNrOfThreads(); i++) {
     final SpanProcessingThread spanProcessingThread =
         new SpanProcessingThread(spanQueue, clientProvider, params.getBatchSize());
     spanProcessingThreads.add(spanProcessingThread);
     futures.add(executorService.submit(spanProcessingThread));
   }
 }
  public PlaybackServiceMediaPlayer(Context context, PSMPCallback callback) {
    Validate.notNull(context);
    Validate.notNull(callback);

    this.context = context;
    this.callback = callback;
    this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    this.playerLock = new ReentrantLock();
    this.startWhenPrepared = new AtomicBoolean(false);
    executor =
        new ThreadPoolExecutor(
            1,
            1,
            5,
            TimeUnit.MINUTES,
            new LinkedBlockingDeque<Runnable>(),
            new RejectedExecutionHandler() {
              @Override
              public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                if (BuildConfig.DEBUG) Log.d(TAG, "Rejected execution of runnable");
              }
            });

    mediaSession = new MediaSessionCompat(context, TAG);
    mediaSession.setCallback(sessionCallback);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);

    mediaPlayer = null;
    statusBeforeSeeking = null;
    pausedBecauseOfTransientAudiofocusLoss = false;
    mediaType = MediaType.UNKNOWN;
    playerStatus = PlayerStatus.STOPPED;
    videoSize = null;
  }
    private RootFinderChainItem(RootFinder rootFinder, RootFinderPolicy rootFinderPolicy) {
      Validate.notNull(rootFinder);
      Validate.notNull(rootFinderPolicy);

      this.rootFinder = rootFinder;
      this.rootFinderPolicy = rootFinderPolicy;
    }
 public void addOrderBy(
     final SingularAttribute<? extends Persistable, ? extends Serializable> attribute,
     final OrderByDirection direction) {
   Validate.notNull(attribute, "fieldName must not be null");
   Validate.notNull(direction, "direction must not be null");
   orders.add(new OrderBy(attribute, direction));
 }
  /**
   * Inserts the provided {@code statement} after the the node this inserter was created for. Tries
   * to put the {@code statement} as close to the {@code marker} as possible.
   *
   * @param statement The statement to insert after the insertion node.
   */
  void insertAfter(final Statement statement) {
    Validate.notNull(statement);
    Validate.validState(
        this.insertionList != null,
        "Insertion is only possible after the inserter has been set up.");
    Validate.validState(
        this.insertionList.isPresent(),
        "Insertion is only possible if setting up the inserter succeeded.");

    if (this.differentAfterList) {
      this.afterList.add(0, statement);
    } else if (this.breakDetector.containsControlFlowBreakingStatement(this.markedStatement)) {
      // we are trying to insert after a control flow breaking statement. That’s
      // dangerous, better surround with try…finally

      final AST factory = this.markedStatement.getAST();
      final TryStatement tryStatement = factory.newTryStatement();
      tryStatement.setFinally(factory.newBlock());

      @SuppressWarnings("unchecked")
      final List<Statement> tryBodyStatements = tryStatement.getBody().statements();
      @SuppressWarnings("unchecked")
      final List<Statement> finallyStatements = tryStatement.getFinally().statements();
      final Statement copy = (Statement) ASTNode.copySubtree(factory, this.markedStatement);
      tryBodyStatements.add(copy);
      finallyStatements.add(statement);
      this.insertionList.get().set(this.markerIndex, tryStatement);
      this.markedStatement = tryStatement;
      this.differentAfterList = true;
      this.afterList = finallyStatements;
    } else {
      this.insertionList.get().add(this.markerIndex, statement);
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * com.proserus.stocks.bo.transactions.Transaction#setCommission(java.math
   * .BigDecimal)
   */
  @Override
  public void setCommission(BigDecimal commission) {
    Validate.notNull(commission);
    Validate.isTrue(BigDecimalUtils.isNotNegative(commission));

    this.commission = BigDecimalUtils.setDecimalWithScale(commission);
  }
 /**
  * Attempts to locate the field which is represented by the presented java bean method.
  *
  * <p>Not every JavaBean getter or setter actually backs to a field with an identical name. In
  * such cases, null will be returned.
  *
  * @param memberDetails the member holders to scan (required)
  * @param method the method name (required)
  * @return the field if found, or null if it could not be found
  */
 public static FieldMetadata getFieldForJavaBeanMethod(
     final MemberDetails memberDetails, final MethodMetadata method) {
   Validate.notNull(memberDetails, "Member details required");
   Validate.notNull(method, "Method is required");
   final JavaSymbolName propertyName = getPropertyNameForJavaBeanMethod(method);
   return getFieldForPropertyName(memberDetails, propertyName);
 }
Example #8
0
 @Override
 public CharRanges minus(String name, Char that) {
   Validate.notNull(name);
   Validate.notNull(that);
   final char thatChar = that.getChar();
   final char thisFrom = this.getFrom();
   final char thisTo = this.getTo();
   if (thisFrom > thatChar || this.getTo() < thatChar) {
     return this;
   } else {
     if (thisFrom == thatChar) {
       final char newFrom = (char) (thisFrom + 1);
       if (newFrom == thisTo) {
         return new CharImpl(name, newFrom);
       } else {
         return new CharRangeImpl(name, newFrom, thisTo);
       }
     } else if (thisTo == thatChar) {
       final char newTo = (char) (thisTo - 1);
       if (newTo == thisFrom) {
         return new CharImpl(name, newTo);
       } else {
         return new CharRangeImpl(name, thisFrom, newTo);
       }
     } else {
       return new CharRangesImpl(
           name,
           new CharRangeImpl(name + "_BELOW", thisFrom, (char) (thatChar - 1)),
           new CharRangeImpl(name + "_ABOVE", (char) (thatChar + 1), thisTo));
     }
   }
 }
  @Override
  public ClassOrInterfaceTypeDetails getTypeFromString(
      final String fileContents, final String declaredByMetadataId, final JavaType typeName) {
    if (StringUtils.isBlank(fileContents)) {
      return null;
    }

    Validate.notBlank(declaredByMetadataId, "Declaring metadata ID required");
    Validate.notNull(typeName, "Java type to locate required");
    try {
      final CompilationUnit compilationUnit =
          JavaParser.parse(new ByteArrayInputStream(fileContents.getBytes()));
      final TypeDeclaration typeDeclaration =
          JavaParserUtils.locateTypeDeclaration(compilationUnit, typeName);
      if (typeDeclaration == null) {
        return null;
      }
      return JavaParserClassOrInterfaceTypeDetailsBuilder.getInstance(
              compilationUnit,
              null,
              typeDeclaration,
              declaredByMetadataId,
              typeName,
              metadataService,
              typeLocationService)
          .build();
    } catch (final IOException e) {
      throw new IllegalStateException(e);
    } catch (final ParseException e) {
      throw new IllegalStateException("Failed to parse " + typeName + " : " + e.getMessage());
    }
  }
 /**
  * Utility method which copies all entries from source into target. Entries with the same keys
  * from target will be overridden with entries from source. This operation is similar to {@link
  * Map#putAll(Map)}, but it doesn't require changing generics to construction like
  *
  * <pre>
  * <? extends String, ? extends S>
  * </pre>
  *
  * @param source the map from where the entries will be copied into target.
  * @param target the map where to put entries from source.
  */
 protected final void copyAll(final Map<String, S> source, final Map<String, S> target) {
   Validate.notNull(source);
   Validate.notNull(target);
   for (Map.Entry<String, S> entry : source.entrySet()) {
     target.put(entry.getKey(), entry.getValue());
   }
 }
  /** @param countryAndLocation Location string. */
  public UnLocode(String countryAndLocation) {
    Validate.notNull(countryAndLocation, "Country and location may not be null");
    Validate.isTrue(
        VALID_PATTERN.matcher(countryAndLocation).matches(),
        countryAndLocation + " is not a valid UN/LOCODE (does not match pattern)");

    this.unlocode = countryAndLocation.toUpperCase();
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * com.proserus.stocks.bo.transactions.Transaction#removeLabel(com.proserus
   * .stocks.bo.transactions.Label)
   */
  @Override
  public void removeLabel(Label label) {
    Validate.notNull(label);
    Validate.notEmpty(label.getName());

    labels.remove(label);
    label.removeTransaction(this);
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * com.proserus.stocks.bo.transactions.Transaction#addLabel(com.proserus
   * .stocks.bo.transactions.Label)
   */
  @Override
  public void addLabel(Label label) {
    Validate.notNull(label);
    Validate.notEmpty(label.getName());

    this.labels.add(label);
    label.addTransaction(this);
  }
Example #14
0
  /**
   * This method may be used to register a custom resource or datatype. Note that by using custom
   * types, you are creating a system that will not interoperate with other systems that do not know
   * about your custom type. There are valid reasons however for wanting to create custom types and
   * this method can be used to enable them.
   *
   * <p><b>THREAD SAFETY WARNING:</b> This method is not thread safe. It should be called before any
   * threads are able to call any methods on this context.
   *
   * @param theTypes The custom types to add (must not be <code>null</code> or contain null elements
   *     in the collection)
   */
  public void registerCustomTypes(Collection<Class<? extends IBase>> theTypes) {
    Validate.notNull(theTypes, "theTypes must not be null");
    Validate.noNullElements(theTypes.toArray(), "theTypes must not contain any null elements");

    ensureCustomTypeList();

    myCustomTypes.addAll(theTypes);
  }
Example #15
0
 public CharRangeImpl(String name, char from, char to) {
   super(Validate.notNull(name));
   Validate.isTrue(from <= to, "Character [from] must not be greater that [to].");
   this.from = from;
   this.to = to;
   this.charRanges = Collections.<CharRange>singletonList(this);
   this.unmodifiableCharRanges = Collections.unmodifiableList(this.charRanges);
 }
Example #16
0
 protected void func_174859_a(EnumFacing p_174859_1_) {
   Validate.notNull(p_174859_1_);
   Validate.isTrue(p_174859_1_.getAxis().isHorizontal());
   this.field_174860_b = p_174859_1_;
   this.prevRotationYaw =
       this.rotationYaw = (float) (this.field_174860_b.getHorizontalIndex() * 90);
   this.func_174856_o();
 }
Example #17
0
  private String normalize(String text) {
    Validate.notNull(text, "Text cannot be null");

    String normalized = text.trim();
    Validate.notBlank(normalized, "Text cannot be blank");

    return normalized;
  }
  public PredicateValidator(Predicate<? super T> predicate, String errorKey) {
    super();
    Validate.notNull(predicate, "predicate must not be null");
    Validate.notEmpty(errorKey, "errorKey must not be empty");

    this.predicate = predicate;
    this.errorKey = errorKey;
  }
  public DefaultModelBuildingResult setEffectiveModel(final String modelId, final Model model) {
    // Intentionally notNull because Super POM may not contain a modelId
    Validate.notNull(modelId, "modelId must not be null");
    Validate.notNull(model, "model must not be null");

    this.effectiveModels.put(modelId, model);

    return this;
  }
Example #20
0
 /**
  * Create a new RecursiveEvaluation.
  *
  * @param function initial, potentially recursive NullaryFunction
  * @param functionType as long as result is an instance, keep processing.
  */
 public RecursiveEvaluation(NullaryFunction<?> function, Class<?> functionType) {
   Validate.notNull(function, "NullaryFunction argument was null");
   if (!NullaryFunction.class.isAssignableFrom(functionType)) {
     throw new IllegalArgumentException(
         NullaryFunction.class + " is not assignable from " + functionType);
   }
   this.function = function;
   this.functionType = Validate.notNull(functionType, "FunctionType argument was null");
 }
  @Override
  public String updateAndGetCompilationUnitContents(
      final String fileIdentifier, final ClassOrInterfaceTypeDetails cid) {
    // Validate parameters
    Validate.notBlank(fileIdentifier, "Oringinal unit path required");
    Validate.notNull(cid, "Type details required");

    // Load original compilation unit from file
    final File file = new File(fileIdentifier);
    String fileContents = "";
    try {
      fileContents = FileUtils.readFileToString(file);
    } catch (final IOException ignored) {
    }
    if (StringUtils.isBlank(fileContents)) {
      return getCompilationUnitContents(cid);
    }
    CompilationUnit compilationUnit;
    try {
      compilationUnit = JavaParser.parse(new ByteArrayInputStream(fileContents.getBytes()));

    } catch (final IOException e) {
      throw new IllegalStateException(e);
    } catch (final ParseException e) {
      throw new IllegalStateException(e);
    }

    // Load new compilation unit from cid information
    final String cidContents = getCompilationUnitContents(cid);
    CompilationUnit cidCompilationUnit;
    try {
      cidCompilationUnit = JavaParser.parse(new ByteArrayInputStream(cidContents.getBytes()));

    } catch (final IOException e) {
      throw new IllegalStateException(e);
    } catch (final ParseException e) {
      throw new IllegalStateException(e);
    }

    // Update package
    if (!compilationUnit
        .getPackage()
        .getName()
        .getName()
        .equals(cidCompilationUnit.getPackage().getName().getName())) {
      compilationUnit.setPackage(cidCompilationUnit.getPackage());
    }

    // Update imports
    UpdateCompilationUnitUtils.updateCompilationUnitImports(compilationUnit, cidCompilationUnit);

    // Update types
    UpdateCompilationUnitUtils.updateCompilationUnitTypes(compilationUnit, cidCompilationUnit);

    // Return new contents
    return compilationUnit.toString();
  }
Example #22
0
  public TransferFile(Integer modifiedTime, String filename, File file) {
    Validate.notNull(modifiedTime, "modifiedTime cannot be null");
    Validate.notBlank(filename, "filename cannot be blank");
    Validate.notNull(file, "file cannot be null");

    this.modifiedTime = modifiedTime;
    this.filename = filename;
    this.file = file;
  }
Example #23
0
 /**
  * Returns the portion of the child identifier that is relative to the parent {@link FileDetails}
  * instance. Note that this instance must be the parent.
  *
  * <p>If an empty string is returned from this method, it denotes the child was actually the same
  * identifier as the parent.
  *
  * @param childCanonicalPath the confirmed child of this instance (required; use canonical path)
  * @return the relative path within the parent instance (never null)
  */
 public String getRelativeSegment(final String childCanonicalPath) {
   Validate.notNull(childCanonicalPath, "Child identifier is required");
   Validate.isTrue(
       isParentOf(childCanonicalPath),
       "Identifier '%s' is not a child of '%s'",
       childCanonicalPath,
       this);
   return childCanonicalPath.substring(getCanonicalPath().length());
 }
  /** {@inheritDoc} */
  public void annotateType(final JavaType type, final JavaPackage javaPackage) {
    // TODO check for existing controller

    // Use Roo's Assert type for null checks
    Validate.notNull(type, "Java type required");
    Validate.notNull(javaPackage, "Java package required, web mvc all command package required");

    // Obtain ClassOrInterfaceTypeDetails for this java type
    ClassOrInterfaceTypeDetails entityDetails = typeLocationService.getTypeDetails(type);

    // Test if the annotation already exists on the target type
    if (entityDetails != null
        && MemberFindingUtils.getAnnotationOfType(
                entityDetails.getAnnotations(), new JavaType(RooEnvers.class.getName()))
            == null) {
      ClassOrInterfaceTypeDetailsBuilder classOrInterfaceTypeDetailsBuilder =
          new ClassOrInterfaceTypeDetailsBuilder(entityDetails);

      // Create JavaType instance for the add-ons trigger annotation
      JavaType rooEnvers = new JavaType(RooEnvers.class.getName());

      // Create Annotation metadata
      AnnotationMetadataBuilder annotationBuilder = new AnnotationMetadataBuilder(rooEnvers);

      // Add annotation to target type
      classOrInterfaceTypeDetailsBuilder.addAnnotation(annotationBuilder.build());

      // Save changes to disk
      typeManagementService.createOrUpdateTypeOnDisk(classOrInterfaceTypeDetailsBuilder.build());
    }

    // Get details for existing controller
    JavaType typeController =
        new JavaType(
            javaPackage.getFullyQualifiedPackageName()
                + "."
                + type.getSimpleTypeName()
                + "Controller");
    ClassOrInterfaceTypeDetails typeControllerDetails =
        typeLocationService.getTypeDetails(typeController);

    // Add annotation @RooEnversController to existing controller
    ClassOrInterfaceTypeDetailsBuilder classOrInterfaceTypeDetailsBuilder =
        new ClassOrInterfaceTypeDetailsBuilder(typeControllerDetails);
    JavaType rooEnversController =
        new JavaType("de.eightbitboy.roo.envers.controller.RooEnversController");

    final List<AnnotationAttributeValue<?>> rooEnversControllerAttributes =
        new ArrayList<AnnotationAttributeValue<?>>();
    rooEnversControllerAttributes.add(new ClassAttributeValue(new JavaSymbolName("type"), type));

    AnnotationMetadataBuilder annotationBuilder =
        new AnnotationMetadataBuilder(rooEnversController, rooEnversControllerAttributes);
    classOrInterfaceTypeDetailsBuilder.addAnnotation(annotationBuilder.build());

    typeManagementService.createOrUpdateTypeOnDisk(classOrInterfaceTypeDetailsBuilder.build());
  }
  public void setDisplayName(String displayName)
      throws IllegalStateException, IllegalArgumentException {
    checkValid();
    Validate.notNull(displayName, "displayName cannot be null");
    Validate.isTrue(displayName.length() <= 32, "displayName cannot be longer than 32 characters");

    this.displayName = displayName;
    scoreboard.broadcast(ScoreboardObjectiveMessage.update(name, displayName, renderType));
  }
 /**
  * Returns the accessor name for the given field name and field type.
  *
  * @param fieldName the field name used to determine the accessor name
  * @param fieldType the field type
  * @return the accessor method name
  */
 public static JavaSymbolName getAccessorMethodName(
     final JavaSymbolName fieldName, final JavaType fieldType) {
   Validate.notNull(fieldName, "Field name required");
   Validate.notNull(fieldType, "Field type required");
   final String capitalizedFieldName = StringUtils.capitalize(fieldName.getSymbolName());
   return fieldType.equals(JavaType.BOOLEAN_PRIMITIVE)
       ? new JavaSymbolName("is" + capitalizedFieldName)
       : new JavaSymbolName("get" + capitalizedFieldName);
 }
Example #27
0
  /** Register an object on this registry. */
  public void putObject(Object p_82595_1_, Object p_82595_2_) {
    Validate.notNull(p_82595_1_);
    Validate.notNull(p_82595_2_);

    if (this.registryObjects.containsKey(p_82595_1_)) {
      logger.debug("Adding duplicate key \'" + p_82595_1_ + "\' to registry");
    }

    this.registryObjects.put(p_82595_1_, p_82595_2_);
  }
  public void addNotificationListener(final MetadataNotificationListener listener) {
    Validate.notNull(listener, "Metadata notification listener required");

    if (listener instanceof MetadataService) {
      Validate.isTrue(metadataService == null, "Cannot register more than one MetadataListener");
      metadataService = (MetadataService) listener;
      return;
    }

    listeners.add(listener);
  }
  public static String deleteWidget(OpalForm<?> argOF, String argSize) {
    Validate.notNull(argOF);
    Validate.notEmpty(argSize);

    return "<div class=\"switch "
        + argSize
        + "\">"
        + argOF.delete()
        + argOF.label("Delete", "")
        + "</div>";
  }
Example #30
0
  public LoadTimeLine(
      String conceptName, List<LoadPeriod> loadPeriods, String type, TimeLineRole<?> role) {
    Validate.notEmpty(conceptName);
    Validate.notNull(loadPeriods);

    this.loadPeriods = LoadPeriod.sort(loadPeriods);
    this.conceptName = conceptName;
    this.timeLineRole = role;
    this.type = type;
    this.children = Collections.unmodifiableList(new ArrayList<LoadTimeLine>());
  }