org.apache.commons.lang3.Validate Java Examples

The following examples show how to use org.apache.commons.lang3.Validate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BrownianMotionFromRandomNumberGenerator.java    From finmath-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a Brownian motion.
 *
 * The constructor allows to set the factory to be used for the construction of
 * random variables. This allows to generate Brownian increments represented
 * by different implementations of the RandomVariable (e.g. the RandomVariableFromFloatArray internally
 * using float representations).
 *
 * @param timeDiscretization The time discretization used for the Brownian increments.
 * @param numberOfFactors Number of factors.
 * @param numberOfPaths Number of paths to simulate.
 * @param randomNumberGenerator A random number generator for n-dimensional uniform random numbers (n = numberOfTimeSteps*numberOfFactors).
 * @param abstractRandomVariableFactory Factory to be used to create random variable.
 */
public BrownianMotionFromRandomNumberGenerator(
		final TimeDiscretization timeDiscretization,
		final int numberOfFactors,
		final int numberOfPaths,
		final RandomNumberGenerator randomNumberGenerator,
		final RandomVariableFactory abstractRandomVariableFactory) {
	super();
	this.timeDiscretization = timeDiscretization;
	this.numberOfFactors	= numberOfFactors;
	this.numberOfPaths		= numberOfPaths;
	this.randomNumberGenerator = randomNumberGenerator;

	this.abstractRandomVariableFactory = abstractRandomVariableFactory;

	brownianIncrements	= null; 	// Lazy initialization

	Validate.notNull(timeDiscretization);
	Validate.notNull(randomNumberGenerator);
	int requiredDimension = numberOfFactors*timeDiscretization.getNumberOfTimeSteps();
	Validate.isTrue(randomNumberGenerator.getDimension() >= requiredDimension, "Dimension of RandomNumberGenerator required to be at least %d.", requiredDimension);
}
 
Example #2
Source File: TagUtils.java    From feilong-taglib with Apache License 2.0 6 votes vote down vote up
/**
 * Determines the scope for a given input {@code String}.
 * 
 * <p>
 * If the {@code String} does not match 'request', 'session', 'page' or 'application', the method will return
 * {@link PageContext#PAGE_SCOPE}.
 * </p>
 * 
 * @param scope
 *            the {@code String} to inspect
 * @return the scope found, or {@link PageContext#PAGE_SCOPE} if no scope matched
 *         如果 <code>scope</code> 是null,抛出 {@link NullPointerException}<br>
 *         如果 <code>scope</code> 是blank,抛出 {@link IllegalArgumentException}<br>
 */
public static int getScope(String scope){
    Validate.notBlank(scope, "scope can't be blank!");

    if (scope.equalsIgnoreCase(SCOPE_REQUEST)){
        return PageContext.REQUEST_SCOPE;
    }

    if (scope.equalsIgnoreCase(SCOPE_SESSION)){
        return PageContext.SESSION_SCOPE;
    }

    if (scope.equalsIgnoreCase(SCOPE_APPLICATION)){
        return PageContext.APPLICATION_SCOPE;
    }

    return PageContext.PAGE_SCOPE;
}
 
Example #3
Source File: WsdlParserUtils.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Find the first compatible port type class name of the root.
 * <p>
 * Compatible port type should be SOAP protocol version 1.1 and 1.2.
 * </p>
 * 
 * @param root Root element of wsdl
 * @param sense Communication sense type
 * @return First compatible port type class name
 */
private static String findFirstCompatiblePortTypeClassName(Element root,
        WsType sense) {

    Validate.notNull(root, ROOT_ELEMENT_REQUIRED);

    Element binding = findFirstCompatibleBinding(root);

    // Find all port types elements
    List<Element> portTypes = XmlUtils.findElements(PORT_TYPES_XPATH, root);
    Validate.notEmpty(portTypes, "No valid port type format");
    String portTypeRef = binding.getAttribute(TYPE_ATTRIBUTE);
    StringUtils.isNotEmpty(portTypeRef);
    Element portType = getReferencedElement(root, portTypes, portTypeRef);
    Validate.notNull(portType, "No valid port type reference");
    String portTypeName = portType.getAttribute(NAME_ATTRIBUTE);
    StringUtils.isNotEmpty(portTypeName);

    return convertNameToJavaFormat(portTypeName, sense);
}
 
Example #4
Source File: TestUtils.java    From coroutines with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Load up a ZIP resource from the classpath and generate a {@link ClassNode} for each file with a class extension in that ZIP.
 * Behaviour is ZIP or classes within are not a parseable.
 * @param path path of ZIP resource
 * @return {@link ClassNode} representation of class files in ZIP
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if any IO error occurs
 * @throws IllegalArgumentException if {@code path} cannot be found
 */
public static Map<String, ClassNode> readZipResourcesAsClassNodes(String path) throws IOException {
    Validate.notNull(path);
    
    Map<String, byte[]> files = readZipFromResource(path);
    Map<String, ClassNode> ret = new LinkedHashMap<>();
    for (Entry<String, byte[]> entry : files.entrySet()) {
        if (!entry.getKey().toLowerCase().endsWith(".class")) {
            continue;
        }
        
        ClassReader cr = new ClassReader(new ByteArrayInputStream(entry.getValue()));
        ClassNode classNode = new ClassNode();
        cr.accept(classNode, 0);
        
        ret.put(entry.getKey(), classNode);
    }

    return ret;
}
 
Example #5
Source File: Elixir_008_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public final void appendTo(StringBuffer buffer, int value) {
    if (value < 100) {
        for (int i = mSize; --i >= 2; ) {
            buffer.append('0');
        }
        buffer.append((char)(value / 10 + '0'));
        buffer.append((char)(value % 10 + '0'));
    } else {
        int digits;
        if (value < 1000) {
            digits = 3;
        } else {
            Validate.isTrue(value > -1, "Negative values should not be possible", value);
            digits = Integer.toString(value).length();
        }
        for (int i = mSize; --i >= digits; ) {
            buffer.append('0');
        }
        buffer.append(Integer.toString(value));
    }
}
 
Example #6
Source File: HandlingEvent.java    From pragmatic-microservices-lab with MIT License 6 votes vote down vote up
/**
 * @param cargo cargo
 * @param completionTime completion time, the reported time that the event
 * actually happened (e.g. the receive took place).
 * @param registrationTime registration time, the time the message is
 * received
 * @param type type of event
 * @param location where the event took place
 */
public HandlingEvent(Cargo cargo, Date completionTime,
        Date registrationTime, Type type, Location location) {
    Validate.notNull(cargo, "Cargo is required");
    Validate.notNull(completionTime, "Completion time is required");
    Validate.notNull(registrationTime, "Registration time is required");
    Validate.notNull(type, "Handling event type is required");
    Validate.notNull(location, "Location is required");

    if (type.requiresVoyage()) {
        throw new IllegalArgumentException(
                "Voyage is required for event type " + type);
    }

    this.completionTime = (Date) completionTime.clone();
    this.registrationTime = (Date) registrationTime.clone();
    this.type = type;
    this.location = location;
    this.cargo = cargo;
    this.voyage = null;
}
 
Example #7
Source File: PluginHelper.java    From coroutines with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Given a source and destination path, scans the source path for class files and translates them to the destination path. This
 * method recursively scans the path.
 * <p>
 * For example, imagine source path of {@code /src} and a destination path of {@code /dst}...
 * <pre>
 * /src/A.class -&gt; /dst/A.class
 * /src/a/B.class -&gt; /dst/B.class
 * /src/a/b/c/d/e/C.class -&gt; /dst/a/b/c/d/e/C.class
 * /src/a/b/c/d/e/D.class -&gt; /dst/a/b/c/d/e/D.class
 * </pre>
 * @param srcDir source directory
 * @param dstDir destination directory
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if either of the paths passed in are not directories
 * @return source class to destination class mapping
 */
public static Map<File, File> mapPaths(File srcDir, File dstDir) {
    Validate.notNull(srcDir);
    Validate.notNull(dstDir);
    Validate.isTrue(srcDir.isDirectory());
    Validate.isTrue(dstDir.isDirectory());

    Map<File, File> ret = new HashMap<>();
    
    FileUtils.listFiles(srcDir, new String[]{"class"}, true).forEach((inputFile) -> {
        Path relativePath = srcDir.toPath().relativize(inputFile.toPath());
        Path outputFilePath = dstDir.toPath().resolve(relativePath);
        File outputFile = outputFilePath.toFile();

        ret.put(inputFile, outputFile);
    });
    
    return ret;
}
 
Example #8
Source File: BusinessdayCalendar.java    From finmath-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Get the date offset unit enum for a string (using common synonyms like "d", "b", "bd", "w").
 *
 * @param string The date roll convention name.
 * @return The date roll convention enum.
 */
public static DateOffsetUnit getEnum(final String string) {
	Validate.notNull(string, "Date offset unit string must not be null.");

	if(string.equalsIgnoreCase("d")) {
		return DAYS;
	}
	if(string.equalsIgnoreCase("b")) {
		return BUSINESS_DAYS;
	}
	if(string.equalsIgnoreCase("bd")) {
		return BUSINESS_DAYS;
	}
	if(string.equalsIgnoreCase("w")) {
		return WEEKS;
	}
	if(string.equalsIgnoreCase("m")) {
		return MONTHS;
	}
	if(string.equalsIgnoreCase("y")) {
		return YEARS;
	}

	return DateOffsetUnit.valueOf(string.toUpperCase());
}
 
Example #9
Source File: FilesDelegator.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
@Override
public List<IFileSpec> getDepotFiles(@Nonnull final List<IFileSpec> fileSpecs,
        final GetDepotFilesOptions opts) throws P4JavaException {

    Validate.notNull(fileSpecs);
    List<IFileSpec> fileList = new ArrayList<>();
    List<Map<String, Object>> resultMaps = execMapCmdList(FILES,
            processParameters(opts, fileSpecs, server), null);

    if (nonNull(resultMaps)) {
        for (Map<String, Object> map : resultMaps) {
            fileList.add(ResultListBuilder.handleFileReturn(map, server));
        }
    }
    return fileList;
}
 
Example #10
Source File: Selector.java    From baleen with Apache License 2.0 6 votes vote down vote up
/**
 * Find nodes matching selector.
 *
 * @param query CSS selector
 * @param roots root nodes to descend into
 * @return matching nodes, empty if none
 */
public static <T> Nodes<T> select(String query, Iterable<Node<T>> roots) {
  Validate.notEmpty(query);
  Validate.notNull(roots);
  Evaluator<T> evaluator = QueryParser.parse(query);
  ArrayList<Node<T>> nodes = new ArrayList<>();
  IdentityHashMap<Node<T>, Boolean> seenNodes = new IdentityHashMap<>();
  // dedupe nodes by identity, not equality

  for (Node<T> root : roots) {
    final Nodes<T> found = select(evaluator, root);
    for (Node<T> el : found) {
      if (!seenNodes.containsKey(el)) {
        nodes.add(el);
        seenNodes.put(el, Boolean.TRUE);
      }
    }
  }
  return new Nodes<>(nodes);
}
 
Example #11
Source File: IdType.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
@Override
public IIdType setParts(String theBaseUrl, String theResourceType, String theIdPart, String theVersionIdPart) {
  if (isNotBlank(theVersionIdPart)) {
    Validate.notBlank(theResourceType, "If theVersionIdPart is populated, theResourceType and theIdPart must be populated");
    Validate.notBlank(theIdPart, "If theVersionIdPart is populated, theResourceType and theIdPart must be populated");
  }
  if (isNotBlank(theBaseUrl) && isNotBlank(theIdPart)) {
    Validate.notBlank(theResourceType, "If theBaseUrl is populated and theIdPart is populated, theResourceType must be populated");
  }

  setValue(null);

  myBaseUrl = theBaseUrl;
  myResourceType = theResourceType;
  myUnqualifiedId = theIdPart;
  myUnqualifiedVersionId = StringUtils.defaultIfBlank(theVersionIdPart, null);
  myHaveComponentParts = true;

  return this;
}
 
Example #12
Source File: TerminologyLoaderTest.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
private void addEntry(ZipOutputStream zos, String theClasspathPrefix, String theFileName) throws IOException {
    ourLog.info("Adding {} to test zip", theFileName);
    zos.putNextEntry(new ZipEntry("SnomedCT_Release_INT_20160131_Full/codeSystem/" + theFileName));
    byte[] byteArray = IOUtils.toByteArray(getClass().getResourceAsStream(theClasspathPrefix + theFileName));
    Validate.notNull(byteArray);
    zos.write(byteArray);
    zos.closeEntry();
}
 
Example #13
Source File: Command.java    From riiablo with Apache License 2.0 5 votes vote down vote up
public boolean addAssignmentListener(AssignmentListener l) {
  Validate.isTrue(l != null, "l cannot be null");
  boolean added = ASSIGNMENT_LISTENERS.add(l);
  if (added) {
    l.onAssigned(this, ALIAS);
    if (aliases != null) {
      for (String alias : aliases) l.onAssigned(this, alias);
    }
  }

  return added;
}
 
Example #14
Source File: GraphObject.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
public GraphObject(String sha, String type) {
	Validate.notBlank(sha, "SHA should not be null or empty");
	Validate.notBlank(type, "Type should not be null or empty");

	this.sha = sha;
	this.type = type;
}
 
Example #15
Source File: ConfigurationSerialization.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
public ConfigurationSerializable deserialize(Map<String, ?> args) {
    Validate.notNull(args, "Args must not be null");

    ConfigurationSerializable result = null;
    Method method = null;

    if (result == null) {
        method = getMethod("deserialize", true);

        if (method != null) {
            result = deserializeViaMethod(method, args);
        }
    }

    if (result == null) {
        method = getMethod("valueOf", true);

        if (method != null) {
            result = deserializeViaMethod(method, args);
        }
    }

    if (result == null) {
        Constructor<? extends ConfigurationSerializable> constructor = getConstructor();

        if (constructor != null) {
            result = deserializeViaCtor(constructor, args);
        }
    }

    return result;
}
 
Example #16
Source File: TrackerDeleteStorageRequest.java    From FastDFS_Client with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取文件源服务器
 *
 * @param groupName
 * @param storageIpAddr
 */
public TrackerDeleteStorageRequest(String groupName, String storageIpAddr) {
    Validate.notBlank(groupName, "分组不能为空");
    Validate.notBlank(storageIpAddr, "文件路径不能为空");
    this.groupName = groupName;
    this.storageIpAddr = storageIpAddr;
    head = new ProtoHead(CmdConstants.TRACKER_PROTO_CMD_SERVER_DELETE_STORAGE);
}
 
Example #17
Source File: ServerListPingEvent.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
public ServerListPingEvent(final InetAddress address, final String motd, final int numPlayers, final int maxPlayers) {
    Validate.isTrue(numPlayers >= 0, "Cannot have negative number of players online", numPlayers);
    this.address = address;
    this.motd = motd;
    this.numPlayers = numPlayers;
    this.maxPlayers = maxPlayers;
}
 
Example #18
Source File: AuthCookie.java    From auth0-java-mvc-common with MIT License 5 votes vote down vote up
/**
 * Create a new instance.
 *
 * @param key The cookie key
 * @param value The cookie value
 */
AuthCookie(String key, String value) {
    Validate.notNull(key, "Key must not be null");
    Validate.notNull(value, "Value must not be null");

    this.key = key;
    this.value = value;
}
 
Example #19
Source File: HashCodeArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public HashCodeArguments(JCodeModel codeModel, JVar currentHashCode,
		int multiplier, JVar value, JExpression hasSetValue) {
	this.codeModel = Validate.notNull(codeModel);
	this.currentHashCode = Validate.notNull(currentHashCode);
	this.multiplier = multiplier;
	this.value = Validate.notNull(value);
	this.hasSetValue = Validate.notNull(hasSetValue);
}
 
Example #20
Source File: Validator.java    From alexa-utterance-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Validates intent name against ASK conventions. Throws an exception in case the convention is not met
 * @param intentName name of an intent
 */
public static void validateIntentName(final String intentName) {
    // look for reserved intent keyword "invocation" which indicates invocation name definition
    if (StringUtils.equalsIgnoreCase("invocation", intentName)) {
        // validate invocation name requirements
        validateInvocationName(intentName);
    } else {
        // validate intent name requirements
        Validate.isTrue(intentNamePattern.matcher(intentName).matches(), "Your intent " + intentName + " does not meet intent name conventions. The name of an intent can only contain case-insensitive alphabetical characters and underscores.");
    }
}
 
Example #21
Source File: Digests.java    From jee-universal-bms with Apache License 2.0 5 votes vote down vote up
/**
 * 生成随机的Byte[]作为salt.
 * 
 * @param numBytes byte数组的大小
 */
public static byte[] generateSalt(int numBytes) {
	Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);

	byte[] bytes = new byte[numBytes];
	random.nextBytes(bytes);
	return bytes;
}
 
Example #22
Source File: DefaultFastFileStorageClient.java    From FastDFS_Client with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 上传文件
 * <pre>
 * 可通过fastFile对象配置
 * 1. 上传图像分组
 * 2. 上传元数据metaDataSet
 * <pre/>
 * @param fastFile
 * @return
 */
@Override
public StorePath uploadFile(FastFile fastFile) {
    Validate.notNull(fastFile.getInputStream(), "上传文件流不能为空");
    Validate.notBlank(fastFile.getFileExtName(), "文件扩展名不能为空");
    // 获取存储节点
    StorageNode client = getStorageNode(fastFile.getGroupName());
    // 上传文件
    return uploadFileAndMetaData(client, fastFile.getInputStream(),
            fastFile.getFileSize(), fastFile.getFileExtName(),
            fastFile.getMetaDataSet());
}
 
Example #23
Source File: GitlabApi.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IData<AwardEmoji> getV3ProjectsIssuesNotesAward_emojiAwardEmojiByAwardId(Integer awardId, Integer id, Integer issueId, Integer noteId){ 
	Validate.notNull(awardId);
	Validate.notNull(id);
	Validate.notNull(issueId);
	Validate.notNull(noteId);
	return entityClient.getV3ProjectsIssuesNotesAward_emojiAwardEmojiByAwardId(awardId, id, issueId, noteId);
}
 
Example #24
Source File: DocumentServiceImpl.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public CAS readAnnotationCas(AnnotationDocument aAnnotationDocument,
        CasUpgradeMode aUpgradeMode)
    throws IOException
{
    Validate.notNull(aAnnotationDocument, "Annotation document must be specified");
    
    SourceDocument aDocument = aAnnotationDocument.getDocument();
    String userName = aAnnotationDocument.getUser();
    
    return readAnnotationCas(aDocument, userName, aUpgradeMode);
}
 
Example #25
Source File: CMEnumConstantOutline.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public CMEnumConstantOutline(MEnumOutline enumOutline,
		MEnumConstantInfo<NType, NClass> target, JEnumConstant code) {
	Validate.notNull(enumOutline);
	Validate.notNull(target);
	Validate.notNull(code);
	this.enumOutline = enumOutline;
	this.target = target;
	this.code = code;
}
 
Example #26
Source File: TestEBMLParserCallback.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartElement(EBMLElementMetaData elementMetaData,
        long elementDataSize,
        ByteBuffer idAndSizeRawBytes,
        ElementPathSupplier pathSupplier) {
    long elementNumber = elementMetaData.getElementNumber();
    EBMLTypeInfo typeInfo = elementMetaData.getTypeInfo();
    log.info("On Start: elementNumber " + elementNumber + " typeInfo " + typeInfo.toString() + " size "
            + elementDataSize);
    if (log.isDebugEnabled()) {
        log.debug("Rawbytes { " + hexDump(idAndSizeRawBytes) + " }");
    }
    dumpByteBufferToRawOutput(idAndSizeRawBytes);

    if (checkExpectedCallbacks) {
        CallbackDescription expectedCallback = callbackDescriptions.remove();
        CallbackDescription actualCallback = CallbackDescription.builder()
                .elementCount(elementNumber)
                .callbackType(CallbackDescription.CallbackType.START)
                .typeInfo(typeInfo)
                .numBytes(OptionalLong.of(elementDataSize))
                .bytes(convertToByteArray(idAndSizeRawBytes))
                .build();
        Validate.isTrue(compareCallbackDescriptions(expectedCallback, actualCallback),
                getMismatchExpectationMessage(expectedCallback, actualCallback));
    }
}
 
Example #27
Source File: CraftMetaItem.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
public int getEnchantLevel(Enchantment ench) {
    Validate.notNull(ench, "Enchantment cannot be null");
    Integer level = hasEnchants() ? enchantments.get(ench) : null;
    if (level == null) {
        return 0;
    }
    return level;
}
 
Example #28
Source File: GitHubApi.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IDataSet<IssuesComments> getReposIssuesComments(String owner, String repo, Integer number){ 
	Validate.notNull(owner);
	Validate.notNull(repo);
	Validate.notNull(number);
	return entityClient.getReposIssuesComments(owner, repo, number);
}
 
Example #29
Source File: GitHubApi.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IDataSet<Pulls> getReposPullsFilesPulls(String owner, String repo, Integer number){ 
	Validate.notNull(owner);
	Validate.notNull(repo);
	Validate.notNull(number);
	return entityClient.getReposPullsFilesPulls(owner, repo, number);
}
 
Example #30
Source File: AttachmentsBean.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public File getFile() {
  String fileName = "EmailServiceTaskTest.testTextMailWithFileAttachment.bpmn20.xml";
  File file = new File(PACKAGE_DIR, fileName);
  Validate.isTrue(file.exists(), "file <" + fileName + "> does not exist in dir "
    + PACKAGE_DIR.getAbsolutePath());
  return file;
}