Java Code Examples for org.apache.commons.lang3.ArrayUtils

The following examples show how to use org.apache.commons.lang3.ArrayUtils. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Add properties from all files found in a given directory
 * 
 * @param strRelativePath
 *            Relative path from the root path
 */
public void addPropertiesDirectory( String strRelativePath )
{
    File directory = new File( _strRootPath + strRelativePath );

    if ( directory.exists( ) )
    {
        File [ ] listFile = directory.listFiles( );

        if ( ArrayUtils.isNotEmpty( listFile ) )
        {
            for ( File file : listFile )
            {
                if ( file.getName( ).endsWith( ".properties" ) )
                {
                    String strFullPath = file.getAbsolutePath( );
                    _mapPropertiesFiles.put( file.getName( ), strFullPath );
                    loadFile( strFullPath );
                }
            }
        }
    }
}
 
Example 2
Source Project: cas-mfa   Source File: CasMultiFactorWebflowConfigurer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@PostConstruct
public void afterPropertiesSet() throws Exception {
    try {

        String[] flowIds = flowDefinitionRegistry.getFlowDefinitionIds();
        flowIds = ArrayUtils.removeElement(flowIds, FLOW_ID_LOGIN);
        flowIds = ArrayUtils.removeElement(flowIds, FLOW_ID_LOGOUT);

        LOGGER.debug("Detected {} flow configurations: [{}]",
                flowIds.length,
                Arrays.toString(flowIds));

        LOGGER.debug("Configuring webflow for multifactor authentication...");
        setupWebflow(flowIds);
        LOGGER.debug("Configured webflow for multifactor authentication.");

        LOGGER.debug("Registering default credentials-to-principal resolver...");
        registerDefaultCredentialsToPrincipalResolver();
        LOGGER.debug("Registered default credentials-to-principal resolver.");
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
}
 
Example 3
Source Project: deeplearning4j   Source File: TestLayerSpace.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleConv() {
    ConvolutionLayer conv2d = new Convolution2D.Builder().dilation(1,2).kernelSize(2,2).nIn(2).nOut(3).build();
    ConvolutionLayerSpace conv2dSpace = new ConvolutionLayerSpace.Builder().dilation(1,2).kernelSize(2,2).nIn(2).nOut(3).build();
    assertEquals(0,conv2dSpace.getNumParameters());
    assertEquals(conv2d, conv2dSpace.getValue(new double[0]));

    Deconvolution2DLayerSpace deconvd2dls = new Deconvolution2DLayerSpace.Builder().dilation(2,1).nIn(2).nOut(2).hasBias(new BooleanSpace()).build();
    assertEquals(1, deconvd2dls.getNumParameters());
    //Set the parameter numbers...
    List<ParameterSpace> list = deconvd2dls.collectLeaves();
    int k = 0;
    for(
            int j = 0; j<list.size();j++)

    {
        if (list.get(j).numParameters() > 0) {
            list.get(j).setIndices(k++);
        }
    }
    Deconvolution2D actual = deconvd2dls.getValue(new double[]{0.9});
    assertTrue(!actual.hasBias());
    assertEquals(ArrayUtils.toString(new int[] {2,1} ),ArrayUtils.toString(actual.getDilation()));
}
 
Example 4
Source Project: gvnix   Source File: QuerydslUtilsBeanImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> Class<?> getFieldType1(String fieldName, PathBuilder<T> entity) {
    Class<?> entityType = entity.getType();
    String fieldNameToFindType = fieldName;

    // Makes the array of classes to find fieldName agains them
    Class<?>[] classArray = ArrayUtils.<Class<?>> toArray(entityType);
    if (fieldName.contains(SEPARATOR_FIELDS)) {
        String[] fieldNameSplitted = StringUtils.split(fieldName,
                SEPARATOR_FIELDS);
        for (int i = 0; i < fieldNameSplitted.length - 1; i++) {
            Class<?> fieldType = BeanUtils.findPropertyType(
                    fieldNameSplitted[i],
                    ArrayUtils.<Class<?>> toArray(entityType));
            classArray = ArrayUtils.add(classArray, fieldType);
            entityType = fieldType;
        }
        fieldNameToFindType = fieldNameSplitted[fieldNameSplitted.length - 1];
    }

    return BeanUtils.findPropertyType(fieldNameToFindType, classArray);
}
 
Example 5
Source Project: hadoop-ozone   Source File: ContainerKeyPrefixCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ContainerKeyPrefix fromPersistedFormat(byte[] rawData)
    throws IOException {

  // First 8 bytes is the containerId.
  long containerIdFromDB = ByteBuffer.wrap(ArrayUtils.subarray(
      rawData, 0, Long.BYTES)).getLong();
  // When reading from byte[], we can always expect to have the containerId,
  // key and version parts in the byte array.
  byte[] keyBytes = ArrayUtils.subarray(rawData,
      Long.BYTES + 1,
      rawData.length - Long.BYTES - 1);
  String keyPrefix = new String(keyBytes, UTF_8);

  // Last 8 bytes is the key version.
  byte[] versionBytes = ArrayUtils.subarray(rawData,
      rawData.length - Long.BYTES,
      rawData.length);
  long version = ByteBuffer.wrap(versionBytes).getLong();
  return new ContainerKeyPrefix(containerIdFromDB, keyPrefix, version);
}
 
Example 6
Source Project: deeplearning4j   Source File: NumpyArray.java    License: Apache License 2.0 6 votes vote down vote up
public NumpyArray(INDArray nd4jArray) {
    Nd4j.getAffinityManager().ensureLocation(nd4jArray, AffinityManager.Location.HOST);
    DataBuffer buff = nd4jArray.data();
    address = buff.pointer().address();
    shape = nd4jArray.shape();
    long[] nd4jStrides = nd4jArray.stride();
    strides = new long[nd4jStrides.length];
    int elemSize = buff.getElementSize();
    for (int i = 0; i < strides.length; i++) {
        strides[i] = nd4jStrides[i] * elemSize;
    }
    dtype = nd4jArray.dataType();
    this.nd4jArray = nd4jArray;
    String cacheKey = address + "_" + nd4jArray.length() + "_" + dtype + "_" + ArrayUtils.toString(strides);
    arrayCache.put(cacheKey, nd4jArray);
}
 
Example 7
private void updateRates(int tempTableID, int targetGroupIndex, int base, int... categories) throws Exception {
	if (categories.length == 0) {
		return;
	} else {
		StringBuilder sqlUpdateRatesBuilder = new StringBuilder();

		sqlUpdateRatesBuilder.append("UPDATE ").append(getTemporaryTableName(tempTableID)).append(" SET rate = ");

		if (base <= 0) {
			// Negative value tells that rate isn't available
			sqlUpdateRatesBuilder.append(base < 0 ? -1 : 0);
		} else {
			sqlUpdateRatesBuilder.append("(value * 1.0) / ").append(base);
		}

		sqlUpdateRatesBuilder.append(" WHERE category_index IN (" + StringUtils.join(ArrayUtils.toObject(categories), ", ") + ") AND targetgroup_index = ?");

		updateEmbedded(logger, sqlUpdateRatesBuilder.toString(), targetGroupIndex);
	}
}
 
Example 8
Source Project: bird-java   Source File: PagedQueryParam.java    License: MIT License 6 votes vote down vote up
public PagedQueryParam withDataRule(String... tables) {
    if (ArrayUtils.isEmpty(tables)) return this;
    try {
        IDataRuleStore store = SpringContextHolder.getBean(IDataRuleStore.class);

        Long userId = SessionContext.getUserId();
        if (NumberHelper.isPositive(userId)) {
            this.filterGroup = store.get(userId, tables);
        } else {
            logger.error("当前用户未登录");
        }
    } catch (NoSuchBeanDefinitionException exception) {
        logger.error("IDataRuleStore未注入,数据权限规则无效", exception);
    } catch (NumberFormatException ex) {
        logger.error("当前用户未登录", ex);
    }
    return this;
}
 
Example 9
Source Project: joyqueue   Source File: ExtensionMessageFactoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Message createMessage(String queueName, byte[] body) {
    try {
        Preconditions.checkArgument(StringUtils.isNotBlank(queueName), "queueName can not be null");
        Preconditions.checkArgument(ArrayUtils.isNotEmpty(body), "body can not be null");
    } catch (Throwable cause) {
        throw ExceptionConverter.convertProduceException(cause);
    }

    OMSProduceMessage omsProduceMessage = new OMSProduceMessage();
    omsProduceMessage.setTopic(queueName);
    omsProduceMessage.setBodyBytes(body);

    MessageAdapter messageAdapter = new MessageAdapter(omsProduceMessage);
    omsProduceMessage.setOmsMessage(messageAdapter);
    return messageAdapter;
}
 
Example 10
Source Project: gsc-core   Source File: Wallet.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public Transaction triggerConstantContract(TriggerSmartContract triggerSmartContract,
                                           TransactionWrapper trxCap, Builder builder,
                                           Return.Builder retBuilder)
        throws ContractValidateException, ContractExeException, HeaderNotFound, VMIllegalException {

    ContractStore contractStore = dbManager.getContractStore();
    byte[] contractAddress = triggerSmartContract.getContractAddress().toByteArray();
    byte[] isContractExiste = contractStore.findContractByHash(contractAddress);

    if (ArrayUtils.isEmpty(isContractExiste)) {
        throw new ContractValidateException("No contract or not a smart contract");
    }

    if (!Args.getInstance().isSupportConstant()) {
        throw new ContractValidateException("this node don't support constant");
    }

    return callConstantContract(trxCap, builder, retBuilder);
}
 
Example 11
Source Project: astor   Source File: StrTokenizerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test1() {

    final String input = "a;b;c;\"d;\"\"e\";f; ; ;  ";
    final StrTokenizer tok = new StrTokenizer(input);
    tok.setDelimiterChar(';');
    tok.setQuoteChar('"');
    tok.setIgnoredMatcher(StrMatcher.trimMatcher());
    tok.setIgnoreEmptyTokens(false);
    final String tokens[] = tok.getTokenArray();

    final String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", "", "", "",};

    assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
    for (int i = 0; i < expected.length; i++) {
        assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
                ObjectUtils.equals(expected[i], tokens[i]));
    }

}
 
Example 12
Source Project: sakai   Source File: DBLTIService.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 *
 * {@inheritDoc}
 * 
 * @see org.sakaiproject.lti.api.LTIService#countContentsDao(java.lang.String,
 *      java.lang.String, boolean)
 */
public int countContentsDao(String search, String siteId, boolean isAdminRole) {
	// It is important that any tables/columns added for the purposes of display or searching be
	// LEFT JOIN - *any* INNER JOIN will function as a WHERE clause and will hide content
	// items from the admin UI - so they will not be seen and cannot be repaired
       String joinClause = "LEFT JOIN SAKAI_SITE ON lti_content.SITE_ID = SAKAI_SITE.SITE_ID"
       		+ " LEFT JOIN SAKAI_SITE_PROPERTY ssp1 ON (lti_content.SITE_ID = ssp1.SITE_ID AND ssp1.name = 'contact-name')"
       		+ " LEFT JOIN SAKAI_SITE_PROPERTY ssp2 ON (lti_content.SITE_ID = ssp2.SITE_ID AND ssp2.name = 'contact-email')"
		+ " LEFT JOIN lti_tools ON (lti_content.tool_id = lti_tools.id)";
       final String propertyKey = serverConfigurationService.getString(LTI_SITE_ATTRIBUTION_PROPERTY_KEY, LTI_SITE_ATTRIBUTION_PROPERTY_KEY_DEFAULT);
       if (StringUtils.isNotEmpty(propertyKey)) {
           joinClause = joinClause + " LEFT JOIN SAKAI_SITE_PROPERTY ssp3 ON (lti_content.SITE_ID = ssp3.SITE_ID AND ssp3.name = '" + propertyKey + "')";
       }
       String[] fields = (String[])ArrayUtils.addAll(LTIService.CONTENT_MODEL, LTIService.CONTENT_EXTRA_FIELDS);
       search = foorm.searchCheck(search, "lti_content", fields);
       return countThingsDao("lti_content", LTIService.CONTENT_MODEL, joinClause, search, null, siteId, isAdminRole);
   }
 
Example 13
/**
 * Walk along the reference path in the graph and pull out the corresponding bases
 * @param fromVertex    starting vertex
 * @param toVertex      ending vertex
 * @param includeStart  should the starting vertex be included in the path
 * @param includeStop   should the ending vertex be included in the path
 * @return              byte[] array holding the reference bases, this can be null if there are no nodes between the starting and ending vertex (insertions for example)
 */
public final byte[] getReferenceBytes( final V fromVertex, final V toVertex, final boolean includeStart, final boolean includeStop ) {
    Utils.nonNull(fromVertex, "Starting vertex in requested path cannot be null.");
    Utils.nonNull(toVertex, "From vertex in requested path cannot be null.");

    byte[] bytes = null;
    V v = fromVertex;
    if( includeStart ) {
        bytes = ArrayUtils.addAll(bytes, getAdditionalSequence(v));
    }
    v = getNextReferenceVertex(v); // advance along the reference path
    while( v != null && !v.equals(toVertex) ) {
        bytes = ArrayUtils.addAll(bytes, getAdditionalSequence(v));
        v = getNextReferenceVertex(v); // advance along the reference path
    }
    if( includeStop && v != null && v.equals(toVertex)) {
        bytes = ArrayUtils.addAll(bytes, getAdditionalSequence(v));
    }
    return bytes;
}
 
Example 14
Source Project: PacketProxy   Source File: HttpHeader.java    License: Apache License 2.0 6 votes vote down vote up
static public boolean isHTTPHeader(byte[] data) {
	// Headerサイズは正
	if (calcHeaderSize(data) == -1) { return false; }
	// first line取得
	int index = ArrayUtils.indexOf(data, (byte)'\n');
	if (index < 0) { return false; }
	if (index > 0 && data[index - 1] == '\r') { index--; }
	byte[] line = Arrays.copyOfRange(data, 0, index);
	// first lineに制御文字は無い
	for (int i = 0; i < line.length; i++) {
		if (line[i] < 0x20 || 0x7f <= line[i]) { return false; }
	}
	// first lineはスペース区切りでmethod pas, HTTP/?.?になってる
	String[] strs = new String(line).split(" ");
	if (strs.length != 3) { return false; }
	if (!strs[2].matches("HTTP/[0-9.]+")) { return false; }
	return true;
}
 
Example 15
Source Project: hbase   Source File: Export.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int run(String[] args) throws Exception {
  if (!ExportUtils.isValidArguements(args)) {
    ExportUtils.usage("Wrong number of arguments: " + ArrayUtils.getLength(args));
    System.err.println("   -D " + JOB_NAME_CONF_KEY
            + "=jobName - use the specified mapreduce job name for the export");
    System.err.println("For MR performance consider the following properties:");
    System.err.println("   -D mapreduce.map.speculative=false");
    System.err.println("   -D mapreduce.reduce.speculative=false");
    return -1;
  }
  Job job = createSubmittableJob(getConf(), args);
  return (job.waitForCompletion(true) ? 0 : 1);
}
 
Example 16
Source Project: plugins   Source File: HerbiboarPlugin.java    License: GNU General Public License v3.0 5 votes vote down vote up
private boolean checkArea()
{
	final int[] mapRegions = client.getMapRegions();
	for (int region : HERBIBOAR_REGIONS)
	{
		if (ArrayUtils.contains(mapRegions, region))
		{
			return true;
		}
	}
	return false;
}
 
Example 17
Source Project: springmvc-raml-plugin   Source File: RamlInterpreterTest.java    License: Apache License 2.0 5 votes vote down vote up
private void checkIfFieldContainsAnnotation(boolean expected, JDefinedClass classToCheck, Class<?> annotationClass, String... fields) {
	for (JFieldVar field : classToCheck.fields().values()) {
		if ((fields == null || fields.length == 0 || ArrayUtils.contains(fields, field.name()))
				&& !field.name().equals("serialVersionUID")) {
			boolean found = false;
			for (JAnnotationUse annotation : field.annotations()) {
				if (annotation.getAnnotationClass().name().equals(annotationClass.getSimpleName())) {
					found = true;
				}
			}
			assertThat(found, is(expected));
		}
	}
}
 
Example 18
Source Project: Walrus   Source File: CardActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void startWriteOrEmulateCardSetup(boolean write) {
    if (card.cardData == null) {
        Toast.makeText(this, R.string.no_card_data, Toast.LENGTH_LONG).show();
        return;
    }

    if (CardDeviceManager.INSTANCE.getCardDevices().isEmpty()) {
        Toast.makeText(this, R.string.no_card_devices, Toast.LENGTH_LONG).show();
        return;
    }

    final List<CardDevice> cardDevices = new ArrayList<>();
    for (CardDevice cardDevice : CardDeviceManager.INSTANCE.getCardDevices().values()) {
        CardDevice.Metadata metadata = cardDevice.getClass().getAnnotation(
                CardDevice.Metadata.class);
        if (ArrayUtils.contains(write ? metadata.supportsWrite() : metadata.supportsEmulate(),
                card.cardData.getClass())) {
            cardDevices.add(cardDevice);
        }
    }

    if (cardDevices.isEmpty()) {
        Toast.makeText(this,
                write ? R.string.no_device_can_write : R.string.no_device_can_emulate,
                Toast.LENGTH_LONG).show();
        return;
    }

    PickCardDataTargetDialogFragment.create(
            card.cardData.getClass(),
            write ? CardDeviceAdapter.CardDataFilterMode.WRITABLE :
                    CardDeviceAdapter.CardDataFilterMode.EMULATABLE,
            false,
            write ? 1 : 2)
            .show(getSupportFragmentManager(), PICK_CARD_DEVICE_DIALOG_FRAGMENT_TAG);
}
 
Example 19
Source Project: jhdf   Source File: Utils.java    License: MIT License 5 votes vote down vote up
/**
 * This method is used when the length required is awkward i.e. no support
 * directly from {@link ByteBuffer}
 *
 * @param buffer to read from
 * @param length the number of bytes to read
 * @return the long value read from the buffer
 * @throws ArithmeticException if the data cannot be safely converted to an
 *                             unsigned long
 */
private static int readArbitraryLengthBytesAsUnsignedInt(ByteBuffer buffer, int length) {
	// Here we will use BigInteger to convert a byte array
	byte[] bytes = new byte[length];
	buffer.get(bytes);
	// BigInteger needs big endian so flip the order if needed
	if (buffer.order() == LITTLE_ENDIAN) {
		ArrayUtils.reverse(bytes);
	}
	// Convert to a unsigned long throws if it overflows
	return new BigInteger(1, bytes).intValueExact();
}
 
Example 20
Source Project: base-framework   Source File: BasicHibernateDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取全部对象
 *
 * @param orders 排序对象,不需要排序,可以不传
 * 
 * @return List
 */
public List<T> getAll(Order ...orders) {
	Criteria c = createCriteria();
	if(ArrayUtils.isNotEmpty(orders)) {
		setOrderToCriteria(c, orders);
	}
	return c.list();
}
 
Example 21
/**
 * 设置候选启动人、组
 * @param processDefinitionId
 * @param userArray
 * @param groupArray
 */
public void setStartables(String processDefinitionId, String[] userArray, String[] groupArray) {

    // 1、清理现有的设置
    List<IdentityLink> links = repositoryService.getIdentityLinksForProcessDefinition(processDefinitionId);
    for (IdentityLink link : links) {
        if (StringUtils.isNotBlank(link.getUserId())) {
            repositoryService.deleteCandidateStarterUser(processDefinitionId, link.getUserId());
        }
        if (StringUtils.isNotBlank(link.getGroupId())) {
            repositoryService.deleteCandidateStarterGroup(processDefinitionId, link.getGroupId());
        }
    }

    // 2.1、循环添加候选人
    if (!ArrayUtils.isEmpty(userArray)) {
        for (String user : userArray) {
            repositoryService.addCandidateStarterUser(processDefinitionId, user);
        }
    }

    // 2.2、循环添加候选组
    if (!ArrayUtils.isEmpty(groupArray)) {
        for (String group : groupArray) {
            repositoryService.addCandidateStarterGroup(processDefinitionId, group);
        }
    }
}
 
Example 22
Source Project: coming   Source File: Lang_32_HashCodeBuilder_t.java    License: MIT License 5 votes vote down vote up
/**
 * <p>
 * Appends the fields and values defined by the given object of the given <code>Class</code>.
 * </p>
 * 
 * @param object
 *            the object to append details of
 * @param clazz
 *            the class to append details of
 * @param builder
 *            the builder to append to
 * @param useTransients
 *            whether to use transient fields
 * @param excludeFields
 *            Collection of String field names to exclude from use in calculation of hash code
 */
private static void reflectionAppend(Object object, Class<?> clazz, HashCodeBuilder builder, boolean useTransients,
        String[] excludeFields) {
    if (isRegistered(object)) {
        return;
    }
    try {
        register(object);
        Field[] fields = clazz.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        for (Field field : fields) {
            if (!ArrayUtils.contains(excludeFields, field.getName())
                && (field.getName().indexOf('$') == -1)
                && (useTransients || !Modifier.isTransient(field.getModifiers()))
                && (!Modifier.isStatic(field.getModifiers()))) {
                try {
                    Object fieldValue = field.get(object);
                    builder.append(fieldValue);
                } catch (IllegalAccessException e) {
                    // this can't happen. Would get a Security exception instead
                    // throw a runtime exception in case the impossible happens.
                    throw new InternalError("Unexpected IllegalAccessException");
                }
            }
        }
    } finally {
        unregister(object);
    }
}
 
Example 23
Source Project: zuihou-admin-cloud   Source File: AttachmentController.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "查询附件", notes = "查询附件")
@ApiResponses(
        @ApiResponse(code = 60103, message = "文件id为空")
)
@GetMapping
@SysLog("根据业务类型查询附件")
public R<List<AttachmentResultDTO>> findAttachment(@RequestParam(value = "bizTypes", required = false) String[] bizTypes,
                                                   @RequestParam(value = "bizIds", required = false) String[] bizIds) {
    //不能同时为空
    BizAssert.isTrue(!(ArrayUtils.isEmpty(bizTypes) && ArrayUtils.isEmpty(bizIds)), BASE_VALID_PARAM.build("业务类型不能为空"));
    return R.success(baseService.find(bizTypes, bizIds));
}
 
Example 24
Source Project: timely   Source File: TabletRowAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static OptionalLong decodeRowOffset(Text row) {
    OptionalLong offset = OptionalLong.empty();
    byte[] bytes = row.getBytes();
    int delimidx = findRowDelimiterIndex(bytes);
    if (delimidx > 0) {
        try {
            byte[] buffer = Arrays.copyOfRange(bytes, delimidx + 1, bytes.length);
            buffer = ByteUtils.unescape(buffer);

            // key might not have all bytes for long decoding
            // ensure of sufficient length
            int extendBy = (MIN_OFFSET_LEN - (buffer.length));
            if (extendBy > 0) {
                buffer = ArrayUtils.addAll(buffer, new byte[extendBy]);
            }

            long decodedOffset = OFFSET_DECODER.decode(buffer);
            if (decodedOffset > 0) {
                offset = OptionalLong.of(decodedOffset);
            } else if (LOG.isTraceEnabled()) {
                Optional<String> prefix = decodeRowPrefix(row);
                LOG.trace(
                        "Delimiter identified but offset could not parse { prefix: {}, byte-len: {}, "
                                + "offset-len: {}, offset-bytes: {}, row-bytes: {} }",
                        prefix, bytes.length, buffer.length, Hex.encodeHex(buffer), Hex.encodeHex(bytes));
            }
        } catch (IllegalArgumentException e) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Unable to parse offset: " + e.getMessage(), e);
            }
        }
    }

    return offset;
}
 
Example 25
private int readNextChunk() throws IOException {
    final ByteBuffer ciphertextBuf = ByteBuffer.allocate(SDSSession.DEFAULT_CHUNKSIZE);
    final int read = IOUtils.read(proxy, ciphertextBuf.array());
    if(lastread == 0) {
        return IOUtils.EOF;
    }
    ciphertextBuf.position(read);
    ciphertextBuf.flip();
    try {
        final PlainDataContainer pDataContainer;
        if(read == 0) {
            final PlainDataContainer c1 = cipher.processBytes(createEncryptedDataContainer(ciphertextBuf.array(), read, null));
            final PlainDataContainer c2 = cipher.doFinal(new EncryptedDataContainer(null, tag));
            pDataContainer = new PlainDataContainer(ArrayUtils.addAll(c1.getContent(), c2.getContent()));
        }
        else {
            pDataContainer = cipher.processBytes(createEncryptedDataContainer(ciphertextBuf.array(), read, null));
        }
        final byte[] content = pDataContainer.getContent();
        buffer = ByteBuffer.allocate(content.length);
        buffer.put(content);
        buffer.flip();
        lastread = read;
        return content.length;
    }
    catch(CryptoException e) {
        throw new IOException(e);
    }
}
 
Example 26
Source Project: julongchain   Source File: Identity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public OUIdentifier[] getOrganizationalUnits() throws MspException {
    if (certificate == null) {
        throw new MspException("certificate is null");
    }
    byte[] cid = this.msp.getCertChainIdentifier(this);
    OUIdentifier[] res = null;
    Map<String, String> subject = MspUtil.parseFromString(certificate.getSubject().toString());
    OUIdentifier ouIdentifier = new OUIdentifier();
    ouIdentifier.setOrganizationalUnitIdentifier(subject.get(MspConstant.ORGANIZATION_UNIT));
    ouIdentifier.setCertifiersIdentifier(cid);

    res = (OUIdentifier[]) ArrayUtils.add(res, ouIdentifier);
    return res;
}
 
Example 27
Source Project: astor   Source File: ConstructorUtilsTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testGetAccessibleConstructor() throws Exception {
    assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class
            .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY)));
    assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.class
            .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY)));
}
 
Example 28
Source Project: vertexium   Source File: GeoUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static LinearRing toJtsLinearRing(List<GeoPoint> geoPoints, boolean counterClockwise, boolean lenient) {
    if (geoPoints.size() < 4) {
        throw new VertexiumInvalidShapeException("A polygon must specify at least 4 points for each boundary and hole.");
    }

    Coordinate[] shellCoordinates = geoPoints.stream()
        .map(geoPoint -> new Coordinate(geoPoint.getLongitude(), geoPoint.getLatitude()))
        .toArray(Coordinate[]::new);

    if (!shellCoordinates[0].equals(shellCoordinates[shellCoordinates.length - 1])) {
        if (lenient) {
            LOGGER.info("Closing an unclosed GeoShape by appending the beginning coordinate");
            shellCoordinates = org.apache.commons.lang3.ArrayUtils.add(shellCoordinates, shellCoordinates[0].copy());
        } else {
            throw new VertexiumInvalidShapeException("All polygon boundaries and holes must begin and end at the same point.");
        }
    }
    if (Orientation.isCCW(shellCoordinates) != counterClockwise) {
        if (lenient) {
            LOGGER.info("Reversing the coordinates of a ring that has a backwards orientation");
            ArrayUtils.reverse(shellCoordinates);
        } else {
            throw new VertexiumInvalidShapeException("The outer shell of a polygon must be specified in counter-clockwise " +
                "orientation and all holes must be specified in the clockwise direction.");
        }
    }
    return GEOMETRY_FACTORY.createLinearRing(shellCoordinates);
}
 
Example 29
Source Project: tutorials   Source File: ArrayUtilsUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() {
    int[] oldArray = { 0, 1, 2 };
    int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5);
    int[] expectedArray = { 0, 1, 2, 3, 4, 5 };
    assertArrayEquals(expectedArray, newArray);
}
 
Example 30
Source Project: astor   Source File: MethodUtilsTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testGetAccessibleInterfaceMethod() throws Exception {
    Class<?>[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null };
    for (Class<?>[] element : p) {
        Method method = TestMutable.class.getMethod("getValue", element);
        Method accessibleMethod = MethodUtils.getAccessibleMethod(method);
        assertNotSame(accessibleMethod, method);
        assertSame(Mutable.class, accessibleMethod.getDeclaringClass());
    }
}
 
Example 31
Source Project: htmlunit   Source File: DownloadedContent.java    License: Apache License 2.0 5 votes vote down vote up
InMemory(final byte[] byteArray) {
    if (byteArray == null) {
        bytes_ = ArrayUtils.EMPTY_BYTE_ARRAY;
    }
    else {
        bytes_ = byteArray;
    }
}
 
Example 32
Source Project: svg2vector   Source File: Test_Svg2Vector_IS_SVG.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_SingleFile(){
	Svg2Vector_IS app = new Svg2Vector_IS();
	String[] args = ArrayUtils.addAll(STD_OPTIONS,
			"-f", "src/test/resources/svg-files/chomsky-hierarchy.svgz",
			"-o", OUT_DIR_PREFIX + "chomsky2"
	);
	assertEquals(0, app.executeApplication(args));
}
 
Example 33
Source Project: astor   Source File: MethodUtilsTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testGetAccessibleInterfaceMethod() throws Exception {

        Class<?>[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null };
        for (int i = 0; i < p.length; i++) {
            Method method = TestMutable.class.getMethod("getValue", p[i]);
            Method accessibleMethod = MethodUtils.getAccessibleMethod(method);
            assertNotSame(accessibleMethod, method);
            assertSame(Mutable.class, accessibleMethod.getDeclaringClass());
        }
    }
 
Example 34
Source Project: headless-chrome   Source File: HeadlessDriverUtils.java    License: MIT License 5 votes vote down vote up
public static void takeFullScreenshot(WebDriver webDriver, File pngFile, By... highlights)
        throws IOException {
    final PageSnapshot pageSnapshot = Shutterbug.shootPage(webDriver, BOTH_DIRECTIONS);
    if (ArrayUtils.isNotEmpty(highlights)) {
        Arrays.stream(highlights)
                .map(webDriver::findElements)
                .flatMap(Collection::stream)
                .forEach(pageSnapshot::highlight);
    }
    FileUtils.forceMkdirParent(pngFile);
    pageSnapshot.withName(pngFile.getName());
    pageSnapshot.save(pngFile.getParent());
    FileUtils.deleteQuietly(pngFile);
    FileUtils.moveFile(new File(pngFile.getPath() + ".png"), pngFile);
}
 
Example 35
Source Project: ghidra   Source File: ChecksumAlgorithm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a long to a little-endian array.
 * 
 * @param l The long to convert.
 * @param numBytes The desired size of the resulting array.  Result is truncated or padded if 
 *                 numBytes is smaller or larger than size of long.
 * @return The little-endian array.
 */
public static byte[] toArray(long l, int numBytes) {
	ByteBuffer buffy = ByteBuffer.allocate(Long.BYTES);
	buffy.putLong(l);
	byte[] checksumArray = new byte[numBytes];
	int n = Math.min(Long.BYTES, numBytes);
	System.arraycopy(buffy.array(), Long.BYTES - n, checksumArray, numBytes - n, n);
	ArrayUtils.reverse(checksumArray);
	return checksumArray;
}
 
Example 36
Source Project: cuba   Source File: ValueBinder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set field's "required" flag to false if the value has been filtered by Row Level Security.
 * This is necessary to allow user to submit form with filtered attribute even if attribute is required.
 */
protected void resetRequiredIfAttributeFiltered(Field<?> field, EntityValueSource valueSource,
                                                MetaPropertyPath metaPropertyPath) {
    if (field.isRequired()
            && valueSource.getState() == BindingState.ACTIVE
            && valueSource.getItem() != null
            && metaPropertyPath.getMetaProperty().getRange().isClass()) {

        Entity rootItem = valueSource.getItem();
        Entity targetItem = rootItem;

        MetaProperty[] propertiesChain = metaPropertyPath.getMetaProperties();
        if (propertiesChain.length > 1) {
            String basePropertyItem = Arrays.stream(propertiesChain)
                    .limit(propertiesChain.length - 1)
                    .map(MetadataObject::getName)
                    .collect(Collectors.joining("."));

            targetItem = rootItem.getValueEx(basePropertyItem);
        }

        if (targetItem instanceof BaseGenericIdEntity) {
            String metaPropertyName = metaPropertyPath.getMetaProperty().getName();
            Object value = targetItem.getValue(metaPropertyName);

            BaseGenericIdEntity baseGenericIdEntity = (BaseGenericIdEntity) targetItem;
            String[] filteredAttributes = getFilteredAttributes(baseGenericIdEntity);

            if (value == null && filteredAttributes != null
                    && ArrayUtils.contains(filteredAttributes, metaPropertyName)) {
                field.setRequired(false);
            }
        }
    }
}
 
Example 37
Source Project: EasyReport   Source File: PermissionServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private String distinct(final String[] ids) {
    if (ArrayUtils.isEmpty(ids)) {
        return StringUtils.EMPTY;
    }
    final Set<String> idSet = new HashSet<>(ids.length);
    Collections.addAll(idSet, ids);
    return StringUtils.join(idSet, ',');
}
 
Example 38
Source Project: gsc-core   Source File: Value.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @return
 */
public TransactionWrapper getTransaction() {
    if (ArrayUtils.isEmpty(any)) {
        return null;
    }
    try {
        return new TransactionWrapper(any);
    } catch (BadItemException e) {
        return null;
    }
}
 
Example 39
/**
 * {@inheritDoc}
 */
public List<String> getStringList(String name, List<String> dflt) {

    String[] values = getStrings(name);
    if (ArrayUtils.isNotEmpty(values)) {
        return Arrays.asList(values);
    } else {
        return dflt != null ? dflt : new ArrayList<>();
    }
}
 
Example 40
Source Project: samza   Source File: StartpointManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Read the fanned out {@link Startpoint}s for the given {@link TaskName}
 * @param taskName to read the fan out Startpoints for
 * @return fanned out Startpoints
 */
public Map<SystemStreamPartition, Startpoint> getFanOutForTask(TaskName taskName) throws IOException {
  Preconditions.checkState(!stopped, "Underlying metadata store not available");
  Preconditions.checkNotNull(taskName, "TaskName cannot be null");

  byte[] fanOutBytes = fanOutStore.get(toFanOutStoreKey(taskName));
  if (ArrayUtils.isEmpty(fanOutBytes)) {
    return ImmutableMap.of();
  }
  StartpointFanOutPerTask startpointFanOutPerTask = objectMapper.readValue(fanOutBytes, StartpointFanOutPerTask.class);
  return ImmutableMap.copyOf(startpointFanOutPerTask.getFanOuts());
}