Java Code Examples for org.apache.commons.lang3.Validate#isTrue()

The following examples show how to use org.apache.commons.lang3.Validate#isTrue() . 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: TestResourceUtil.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 6 votes vote down vote up
public static byte[] getTestInputByteArray(String name) throws IOException {
    //First check if we are running in maven.
    InputStream inputStream = ClassLoader.getSystemResourceAsStream(name);
    if (inputStream == null) {
        inputStream = Files.newInputStream(Paths.get("testdata", name));
    }
    Validate.isTrue(inputStream != null, "Could not read input file " + name);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte []buf = new byte [8192];

    int readBytes;
    do {
        readBytes = inputStream.read(buf);
        if (readBytes > 0) {
            outputStream.write(buf, 0, readBytes);
        }
    }while (readBytes >= 0);

    return outputStream.toByteArray();
}
 
Example 2
Source File: EventManager.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
public void deleteCategory(String eventName, int categoryId, String username) {
    var optionalEvent = getOptionalEventAndOrganizationIdByName(eventName, username);
    if(optionalEvent.isEmpty()) {
        throw new IllegalArgumentException("Event not found");
    }
    int eventId = optionalEvent.get().getId();
    var optionalCategory = getOptionalByIdAndActive(categoryId, eventId);
    if(optionalCategory.isEmpty()) {
        throw new IllegalArgumentException("Category not found");
    }
    var category = optionalCategory.get();
    int result = ticketCategoryRepository.deleteCategoryIfEmpty(category.getId());
    if(result != 1) {
        log.debug("cannot delete category. Expected result 1, got {}", result);
        throw new IllegalStateException("Cannot delete category");
    }
    if(category.isBounded()) {
        int ticketsCount = category.getMaxTickets();
        var ticketIds = ticketRepository.selectTicketInCategoryForUpdate(eventId, categoryId, ticketsCount, List.of(TicketStatus.FREE.name(), TicketStatus.RELEASED.name()));
        Validate.isTrue(ticketIds.size() == ticketsCount, "Error while deleting category. Please ensure that there is no pending reservation.");
        ticketRepository.resetTickets(ticketIds);
        Validate.isTrue(ticketsCount == ticketRepository.unbindTicketsFromCategory(eventId, categoryId, ticketIds), "Cannot remove tickets from category.");
    }
}
 
Example 3
Source File: FSProviderSpringFacade.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {

	if(QiniuProvider.NAME.equals(provider)){
		Validate.notBlank(accessKey, "[accessKey] not defined");
		Validate.notBlank(secretKey, "[secretKey] not defined");
		fsProvider = new QiniuProvider(urlprefix, groupName, accessKey, secretKey,privated);
	}else if(FdfsProvider.NAME.equals(provider)){
		Validate.isTrue(servers != null && servers.matches("^.+[:]\\d{1,5}\\s*$"),"[servers] is not valid");
		Properties properties = new Properties();
		fsProvider = new FdfsProvider(groupName,properties);
	}else if(AliyunossProvider.NAME.equals(provider)){
		Validate.notBlank(endpoint, "[endpoint] not defined");
		
	}else{
		throw new RuntimeException("Provider[" + provider + "] not support");
	}
}
 
Example 4
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 5
Source File: InstrumentTaskTest.java    From coroutines with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Map<String, byte[]> readZipFromResource(String path) throws IOException {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL url = cl.getResource(path);
    Validate.isTrue(url != null);
    
    Map<String, byte[]> ret = new LinkedHashMap<>();
    
    try (InputStream is = url.openStream();
            ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) {
        ZipArchiveEntry entry;
        while ((entry = zais.getNextZipEntry()) != null) {
            ret.put(entry.getName(), IOUtils.toByteArray(zais));
        }
    }
    
    return ret;
}
 
Example 6
Source File: elixir1_one_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 7
Source File: DatatablesOperationsImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param controller
 * @param controllerPath
 * @param uriMap
 * @param jspxName
 */
private void updateJspx(JavaType controller, String controllerPath,
        Map<String, String> uriMap, String jspxName) {
    Validate.notBlank(controllerPath,
            "Path is not specified in the @RooWebScaffold annotation for '"
                    + controller.getSimpleTypeName() + "'");
    Validate.isTrue(controllerPath != null && !controllerPath.isEmpty(),
            "Path is not specified in the @RooWebScaffold annotation for '"
                    + controller.getSimpleTypeName() + "'");

    if (controllerPath != null) {
        getWebProjectUtils().updateTagxUriInJspx(controllerPath, jspxName,
                uriMap, getProjectOperations(), fileManager);
    }
}
 
Example 8
Source File: AdminReservationManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
private void removeTicketsFromReservation(TicketReservation reservation, Event event, List<Integer> ticketIds, boolean notify, String username, boolean removeReservation, boolean forceInvoiceReceiptUpdate) {
    String reservationId = reservation.getId();
    if(notify && !ticketIds.isEmpty()) {
        Organization o = eventManager.loadOrganizer(event, username);
        ticketRepository.findByIds(ticketIds).forEach(t -> {
            if(StringUtils.isNotBlank(t.getEmail())) {
                sendTicketHasBeenRemoved(event, o, t);
            }
        });
    }

    billingDocumentManager.ensureBillingDocumentIsPresent(event, reservation, username, () -> ticketReservationManager.orderSummaryForReservation(reservation, event));

    Integer userId = userRepository.findIdByUserName(username).orElse(null);
    Date date = new Date();

    ticketIds.forEach(id -> auditingRepository.insert(reservationId, userId, event.getId(), CANCEL_TICKET, date, TICKET, id.toString()));

    ticketRepository.resetCategoryIdForUnboundedCategoriesWithTicketIds(ticketIds);
    ticketFieldRepository.deleteAllValuesForTicketIds(ticketIds);
    specialPriceRepository.resetToFreeAndCleanupForTickets(ticketIds);

    List<String> reservationIds = ticketRepository.findReservationIds(ticketIds);
    List<String> ticketUUIDs = ticketRepository.findUUIDs(ticketIds);
    int[] results = ticketRepository.batchReleaseTickets(reservationId, ticketIds, event);
    Validate.isTrue(Arrays.stream(results).sum() == ticketIds.size(), "Failed to update tickets");
    if(!removeReservation) {
        if(forceInvoiceReceiptUpdate) {
            auditingRepository.insert(reservationId, userId, event.getId(), FORCED_UPDATE_INVOICE, date, RESERVATION, reservationId);
            internalRegenerateBillingDocument(event, reservationId, username);
        }
        extensionManager.handleTicketCancelledForEvent(event, ticketUUIDs);
    } else {
        extensionManager.handleReservationsCancelledForEvent(event, reservationIds);
    }
}
 
Example 9
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 10
Source File: Key.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new public key.
 *
 * @param bytes The raw key value.
 * @param expectedSize the expected byte array size.
 */
public Key(final byte[] bytes, int expectedSize) {
    Validate.notNull(bytes, "bytes must not be null");
    Validate.isTrue(bytes.length == expectedSize, "Bytes Array size " + bytes.length + " is not " + expectedSize);
    this.value = bytes;

}
 
Example 11
Source File: Potion.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Applies the effects of this potion to the given {@link ItemStack}. The
 * ItemStack must be a potion.
 *
 * @param to The itemstack to apply to
 */
public void apply(ItemStack to) {
    Validate.notNull(to, "itemstack cannot be null");
    Validate.isTrue(to.hasItemMeta(), "given itemstack is not a potion");
    Validate.isTrue(to.getItemMeta() instanceof PotionMeta, "given itemstack is not a potion");
    PotionMeta meta = (PotionMeta) to.getItemMeta();
    meta.setBasePotionData(new PotionData(type, extended, level == 2));
    to.setItemMeta(meta);
}
 
Example 12
Source File: WSConfigServiceImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check if pom.xml file exists in the project and return the path.
 * <p>
 * Checks if exists pom.xml config file. If not exists, null will be
 * returned.
 * </p>
 * 
 * @return Path to the pom.xml file or null if not exists.
 */
private String getPomFilePath() {

    // Project ID
    String prjId = ProjectMetadata
            .getProjectIdentifier(getProjectOperations()
                    .getFocusedModuleName());
    ProjectMetadata projectMetadata = (ProjectMetadata) getMetadataService()
            .get(prjId);
    Validate.isTrue(projectMetadata != null, "Project metadata required");

    String pomFileName = "pom.xml";

    // Checks for pom.xml
    String pomPath = getProjectOperations().getPathResolver()
            .getIdentifier(LogicalPath.getInstance(Path.ROOT, ""),
                    pomFileName);

    boolean pomInstalled = getFileManager().exists(pomPath);

    if (pomInstalled) {

        return pomPath;
    }
    else {

        return null;
    }
}
 
Example 13
Source File: JpaOrmEntityListenerMetadata.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
public JpaOrmEntityListenerMetadata(String identifier,
        JpaOrmEntityListener entityListener) {
    super(getBaseId(identifier));
    Validate.isTrue(isValid(identifier), "Metadata identification string '"
            + identifier + "' does not appear to be a valid");
    Validate.notNull(entityListener, "JpaOrmEntityListener required");

    this.entityListener = entityListener;
}
 
Example 14
Source File: ShapedRecipe.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets the material that a character in the recipe shape refers to.
 *
 * @param key        The character that represents the ingredient in the shape.
 * @param ingredient The ingredient.
 * @param raw        The raw material data as an integer.
 * @return The changed recipe, so you can chain calls.
 * @deprecated Magic value
 */
@Deprecated
public ShapedRecipe setIngredient(char key, Material ingredient, int raw) {
    Validate.isTrue(ingredients.containsKey(key), "Symbol does not appear in the shape:", key);

    // -1 is the old wildcard, map to Short.MAX_VALUE as the new one
    if (raw == -1) {
        raw = Short.MAX_VALUE;
    }

    ingredients.put(key, new ItemStack(ingredient, 1, (short) raw));
    return this;
}
 
Example 15
Source File: FileLogCollector.java    From docker-compose-rule with Apache License 2.0 5 votes vote down vote up
public FileLogCollector(File logDirectory) {
    checkArgument(!logDirectory.isFile(), "Log directory cannot be a file");
    if (!logDirectory.exists()) {
        Validate.isTrue(logDirectory.mkdirs(), "Error making log directory: " + logDirectory.getAbsolutePath());
    }
    this.logDirectory = logDirectory;
}
 
Example 16
Source File: GeoOperationsImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method adds reference in laod-script.tagx to use
 * jquery.loupeField.ext.gvnix.js
 */
public void addToLoadScripts(String varName, String url, boolean isCSS) {
    // Modify Roo load-scripts.tagx
    String docTagxPath = getPathResolver().getIdentifier(getWebappPath(),
            "WEB-INF/tags/util/load-scripts.tagx");

    Validate.isTrue(fileManager.exists(docTagxPath),
            "load-script.tagx not found: ".concat(docTagxPath));

    MutableFile docTagxMutableFile = null;
    Document docTagx;

    try {
        docTagxMutableFile = fileManager.updateFile(docTagxPath);
        docTagx = XmlUtils.getDocumentBuilder().parse(
                docTagxMutableFile.getInputStream());
    }
    catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Element root = docTagx.getDocumentElement();

    boolean modified = false;

    if (isCSS) {
        modified = getWebProjectUtils().addCssToTag(docTagx, root, varName,
                url)
                || modified;
    }
    else {
        modified = getWebProjectUtils().addJSToTag(docTagx, root, varName,
                url)
                || modified;
    }

    if (modified) {
        XmlUtils.writeXml(docTagxMutableFile.getOutputStream(), docTagx);
    }

}
 
Example 17
Source File: ContinuationGenerators.java    From coroutines with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Generates instructions that returns a dummy value. Return values are as follows:
 * <ul>
 * <li>void -&gt; no value</li>
 * <li>boolean -&gt; false</li>
 * <li>byte/short/char/int -&gt; 0</li>
 * <li>long -&gt; 0L</li>
 * <li>float -&gt; 0.0f</li>
 * <li>double -&gt; 0.0</li>
 * <li>Object -&gt; null</li>
 * </ul>
 *
 * @param returnType return type of the method this generated bytecode is for
 * @return instructions to return a dummy value
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if {@code returnType}'s sort is of {@link Type#METHOD}
 */
private static InsnList returnDummy(Type returnType) {
    Validate.notNull(returnType);
    Validate.isTrue(returnType.getSort() != Type.METHOD);

    InsnList ret = new InsnList();

    switch (returnType.getSort()) {
        case Type.VOID:
            ret.add(new InsnNode(Opcodes.RETURN));
            break;
        case Type.BOOLEAN:
        case Type.BYTE:
        case Type.SHORT:
        case Type.CHAR:
        case Type.INT:
            ret.add(new InsnNode(Opcodes.ICONST_0));
            ret.add(new InsnNode(Opcodes.IRETURN));
            break;
        case Type.LONG:
            ret.add(new InsnNode(Opcodes.LCONST_0));
            ret.add(new InsnNode(Opcodes.LRETURN));
            break;
        case Type.FLOAT:
            ret.add(new InsnNode(Opcodes.FCONST_0));
            ret.add(new InsnNode(Opcodes.FRETURN));
            break;
        case Type.DOUBLE:
            ret.add(new InsnNode(Opcodes.DCONST_0));
            ret.add(new InsnNode(Opcodes.DRETURN));
            break;
        case Type.OBJECT:
        case Type.ARRAY:
            ret.add(new InsnNode(Opcodes.ACONST_NULL));
            ret.add(new InsnNode(Opcodes.ARETURN));
            break;
        default:
            throw new IllegalStateException();
    }

    return ret;
}
 
Example 18
Source File: SortHelper.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
/**
 * 判断属性名称和排序因子数组是不是asc排序.
 * 
 * <h3>示例:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * SortHelper.isAsc(toArray("name", null)) = true;
 * 
 * SortHelper.isAsc(toArray("name", "asC")) = true;
 * SortHelper.isAsc(toArray("name", "AsC")) = true;
 * SortHelper.isAsc(toArray("name", "ASC")) = true;
 * 
 * SortHelper.isAsc(toArray("name", "dEsc")) = false;
 * SortHelper.isAsc(toArray("name", "desc")) = false;
 * </pre>
 * 
 * </blockquote>
 * 
 * @param propertyNameAndOrderArray
 *            属性名称和排序因子数组,length 是2<br>
 *            第一个元素是属性名称,比如 "name",第二个元素是排序因子,比如asc或者是desc或者是null<br>
 * @return 如果数组第二个值是null或者empty,或者值是asc(忽略大小写),那么判定是asc排序
 * @throws NullPointerException
 *             如果 <code>propertyNameAndOrderArray</code> 是null
 * @throws IllegalArgumentException
 *             如果 <code>propertyNameAndOrderArray</code> 是empty<br>
 *             或者<code>propertyNameAndOrderArray</code>的length不是2<br>
 *             或者解析出来的order值不是[null/ASC/DESC] 中的任意一个
 */
public static boolean isAsc(String[] propertyNameAndOrderArray){
    Validate.notEmpty(propertyNameAndOrderArray, "propertyNameAndOrderArray can't be null/empty!");

    Validate.isTrue(
                    2 == propertyNameAndOrderArray.length,
                    "propertyNameAndOrderArray.length must 2, but length is:[%s],propertyNameAndOrderArray:[%s]",
                    propertyNameAndOrderArray.length,
                    propertyNameAndOrderArray);

    //---------------------------------------------------------------

    String order = propertyNameAndOrderArray[1];

    Validate.isTrue(
                    null == order || ASC.equalsIgnoreCase(order) || DESC.equalsIgnoreCase(order),
                    "order value must one of [null/ASC/DESC], but is:[%s],propertyNameAndOrderArray:[%s]",
                    order,
                    propertyNameAndOrderArray);

    //---------------------------------------------------------------

    return null == order || ASC.equalsIgnoreCase(order);
}
 
Example 19
Source File: Generator.java    From alexa-utterance-generator with Apache License 2.0 4 votes vote down vote up
/**
 * builds the Generator object
 * @return generator object
 */
public Generator build() {
    Validate.noNullElements(Collections.singletonList(formatter), "Generator needs a Formatter instance to process.");
    Validate.isTrue(grammarFile == null || grammarFile.canRead(), "Could not obtain read access to grammar file.");
    return new Generator(this);
}
 
Example 20
Source File: CheckInApiController.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
private static void validateIdList(@RequestBody List<Integer> ids) {
    Validate.isTrue(ids!= null && !ids.isEmpty());
    Validate.isTrue(ids.size() <= 200, "Cannot ask more than 200 ids");
}