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

The following examples show how to use org.apache.commons.lang.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 check out the related API usage on the sidebar.
Example #1
Source Project: micro-integrator   Author: wso2   File: SoapHeaderBlocksTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks if a CAR file is deployed.
 *
 * @param carFileName CAR file name.
 * @return True if exists, False otherwise.
 */
private Callable<Boolean> isCarFileDeployed(final String carFileName) {
    return new Callable<Boolean>() {
        @Override
        public Boolean call() throws ApplicationAdminExceptionException, RemoteException {
            log.info("waiting " + MAX_TIME + " millis for car deployment " + carFileName);
            Calendar startTime = Calendar.getInstance();
            long time = Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis();
            String[] applicationList = applicationAdminClient.listAllApplications();
            if (applicationList != null) {
                if (ArrayUtils.contains(applicationList, carFileName)) {
                    log.info("car file deployed in " + time + " milliseconds");
                    return true;
                }
            }
            return false;
        }
    };
}
 
Example #2
/**
 * Recursively go through UIPermissionNode.
 *
 * @param node UIPermissionNode of permissions.
 * @return  Permission[] of permissions.
 */
private Permission[] getAllPermissions(UIPermissionNode node) {

    List<Permission> permissions = new ArrayList<>();
    UIPermissionNode[] childNodes = node.getNodeList();
    Permission permission = new Permission();
    permission.setDisplayName(node.getDisplayName());
    permission.setResourcePath(node.getResourcePath());
    permissions.add(permission);
    if (ArrayUtils.isNotEmpty(childNodes)) {
        for (UIPermissionNode childNode : childNodes) {
            permissions.addAll(Arrays.asList(getAllPermissions(childNode)));
        }
    }
    return permissions.toArray(new Permission[0]);
}
 
Example #3
Source Project: carbon-identity-framework   Author: wso2   File: IdPManagementUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Use this method to replace original passwords with random passwords before sending to UI front-end
 * @param identityProvider
 * @return
 */
public static void removeOriginalPasswords(IdentityProvider identityProvider) {

    if (identityProvider == null || identityProvider.getProvisioningConnectorConfigs() == null) {
        return;
    }

    for (ProvisioningConnectorConfig provisioningConnectorConfig : identityProvider
            .getProvisioningConnectorConfigs()) {
        Property[] properties = provisioningConnectorConfig.getProvisioningProperties();
        if (ArrayUtils.isEmpty(properties)) {
            continue;
        }
        properties = RandomPasswordProcessor.getInstance().removeOriginalPasswords(properties);
        provisioningConnectorConfig.setProvisioningProperties(properties);
    }
}
 
Example #4
Source Project: carbon-identity-framework   Author: wso2   File: RandomPasswordProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Remove random passwords with original passwords when sending password properties to Service Back-end
 *
 * @param properties
 */
public Property[] removeRandomPasswords(Property[] properties, boolean withCacheClear) {

    if (ArrayUtils.isEmpty(properties)) {
        return new Property[0];
    }

    String uuid = IdentityApplicationManagementUtil.getPropertyValue(properties,
            IdentityApplicationConstants.UNIQUE_ID_CONSTANT);
    if (StringUtils.isBlank(uuid)) {
        if (log.isDebugEnabled()) {
            log.debug("Cache Key not found for Random Password Container");
        }
    } else {
        properties = removeUniqueIdProperty(properties);
        RandomPassword[] randomPasswords = getRandomPasswordContainerFromCache(uuid, withCacheClear);
        if (!ArrayUtils.isEmpty(randomPasswords)) {
            replaceRandomPasswordsWithOriginalPasswords(properties,
                    randomPasswords);
        }
    }
    return properties;
}
 
Example #5
Source Project: aion-germany   Author: AionGermany   File: BonusService.java    License: GNU General Public License v3.0 6 votes vote down vote up
public BonusItemGroup[] getGroupsByType(BonusType type) {
	switch (type) {
		case BOSS:
			return itemGroups.getBossGroups();
		case ENCHANT:
			return itemGroups.getEnchantGroups();
		case FOOD:
			return itemGroups.getFoodGroups();
		case GATHER:
			return (BonusItemGroup[]) ArrayUtils.addAll(itemGroups.getOreGroups(), itemGroups.getGatherGroups());
		case MANASTONE:
			return itemGroups.getManastoneGroups();
		case MEDICINE:
			return itemGroups.getMedicineGroups();
		case TASK:
			return itemGroups.getCraftGroups();
		case MOVIE:
			return null;
		default:
			log.warn("Bonus of type " + type + " is not implemented");
			return null;
	}
}
 
Example #6
Source Project: carbon-identity   Author: wso2-attic   File: RandomPasswordProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Remove original passwords with random passwords when sending password properties to UI front-end
 * @param properties
 */
public Property[] removeOriginalPasswords(Property[] properties){

    if (ArrayUtils.isEmpty(properties)){
        return new Property[0];
    }

    properties = addUniqueIdProperty(properties);
    String uuid = IdentityApplicationManagementUtil
            .getPropertyValue(properties, IdentityApplicationConstants.UNIQUE_ID_CONSTANT);
    String randomPhrase = IdentityApplicationConstants.RANDOM_PHRASE_PREFIX + uuid;
    RandomPassword[] randomPasswords = replaceOriginalPasswordsWithRandomPasswords(
            randomPhrase, properties);
    if (!ArrayUtils.isEmpty(randomPasswords)) {
        addPasswordContainerToCache(randomPasswords, uuid);
    }

    return properties;
}
 
Example #7
Source Project: astor   Author: SpoonLabs   File: StrTokenizerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void test3() {

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

        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 #8
Source Project: sunbird-lms-service   Author: project-sunbird   File: BaseRequestValidator.java    License: MIT License 6 votes vote down vote up
/**
 * Method to check whether given header fields present or not.
 *
 * @param data List of strings representing the header names in received request.
 * @param keys List of string represents the headers fields.
 */
public void checkMandatoryHeadersPresent(Map<String, String[]> data, String... keys) {
  if (MapUtils.isEmpty(data)) {
    throw new ProjectCommonException(
        ResponseCode.invalidRequestData.getErrorCode(),
        ResponseCode.invalidRequestData.getErrorMessage(),
        ResponseCode.CLIENT_ERROR.getResponseCode());
  }
  Arrays.stream(keys)
      .forEach(
          key -> {
            if (ArrayUtils.isEmpty(data.get(key))) {
              throw new ProjectCommonException(
                  ResponseCode.mandatoryHeadersMissing.getErrorCode(),
                  ResponseCode.mandatoryHeadersMissing.getErrorMessage(),
                  ResponseCode.CLIENT_ERROR.getResponseCode(),
                  key);
            }
          });
}
 
Example #9
Source Project: freehealth-connector   Author: taktik   File: CryptoImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private SigningCredential retrieveSigningCredential(String alias, KeyStore keyStore) {
   try {
      Certificate[] c = keyStore.getCertificateChain(alias);
      if (ArrayUtils.isEmpty(c)) {
         throw new IllegalArgumentException("The KeyStore doesn't contain the required key with alias [" + alias + "]");
      } else {
         X509Certificate[] certificateChain = (X509Certificate[])Arrays.copyOf(c, c.length, X509Certificate[].class);
         PrivateKey privateKey = (PrivateKey)keyStore.getKey(alias, (char[])null);
         return SigningCredential.create(privateKey, Iterables.newList(certificateChain));
      }
   } catch (KeyStoreException var6) {
      throw new IllegalArgumentException("Given keystore hasn't been initialized", var6);
   } catch (NoSuchAlgorithmException var7) {
      throw new IllegalStateException("There is a problem with the Security configuration... Check if all the required security providers are correctly registered", var7);
   } catch (UnrecoverableKeyException var8) {
      throw new IllegalStateException("The private key with alias [" + alias + "] could not be recovered from the given keystore", var8);
   }
}
 
Example #10
Source Project: govpay   Author: link-it   File: ConfigurazioniConverter.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static it.govpay.bd.configurazione.model.Mail getConfigurazioneMailPromemoriaDTO(MailTemplate mailPromemoria) throws ServiceException, ValidationException{
	it.govpay.bd.configurazione.model.Mail dto = new it.govpay.bd.configurazione.model.Mail();
	
	dto.setAllegaPdf(mailPromemoria.AllegaPdf());
	dto.setTipo(mailPromemoria.getTipo());
	if(mailPromemoria.getTipo() != null) {
		// valore tipo contabilita non valido
		if(it.govpay.backoffice.v1.beans.MailTemplate.TipoEnum.fromValue(mailPromemoria.getTipo()) == null) {
			throw new ValidationException("Codifica inesistente per tipo trasformazione. Valore fornito [" +
					mailPromemoria.getTipo() + "] valori possibili " + ArrayUtils.toString(it.govpay.backoffice.v1.beans.MailTemplate.TipoEnum.values()));
		}
	}
	
	dto.setMessaggio((ConverterUtils.toJSON(mailPromemoria.getMessaggio(),null)));
	dto.setOggetto(ConverterUtils.toJSON(mailPromemoria.getOggetto(),null));
	
	return dto;
}
 
Example #11
public Result<X509Certificate[]> getCertificate(byte[] publicKeyIdentifier) throws TechnicalConnectorException {
   GetCertificateRequest request = new GetCertificateRequest();
   RaUtils.setCommonAttributes(request);
   request.setPublicKeyIdentifier(publicKeyIdentifier);
   Result<GetCertificateResponse> resp = RaUtils.invokeCertRa(ConnectorXmlUtils.toString((Object)request), "urn:be:fgov:ehealth:etee:certra:protocol:v2:getcertificate", GetCertificateResponse.class);
   if (!resp.getStatus().equals(Status.OK)) {
      return resp.getStatus().equals(Status.PENDING) ? new Result(resp.getTime()) : new Result("Unable to obtain certificate", resp.getCause());
   } else {
      X509Certificate[] x509Certificates = new X509Certificate[0];

      byte[] x509Certificate;
      for(Iterator i$ = ((GetCertificateResponse)resp.getResult()).getX509Certificates().iterator(); i$.hasNext(); x509Certificates = (X509Certificate[])((X509Certificate[])ArrayUtils.add(x509Certificates, CertificateUtils.toX509Certificate(x509Certificate)))) {
         x509Certificate = (byte[])i$.next();
      }

      return new Result(x509Certificates);
   }
}
 
Example #12
public final List<String> getExceptionList(String... errorType) {
   List<String> exceptionList = new ArrayList();
   if (ArrayUtils.contains(errorType, "WARN")) {
      exceptionList.addAll(this.exceptionWarningList);
   }

   if (ArrayUtils.contains(errorType, "ERROR")) {
      exceptionList.addAll(this.exceptionErrorList);
   }

   if (ArrayUtils.contains(errorType, "FATAL")) {
      exceptionList.addAll(this.exceptionFatalList);
   }

   return exceptionList;
}
 
Example #13
Source Project: pentaho-kettle   Author: pentaho   File: MultiMergeJoinMeta.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getXML() {
  StringBuilder retval = new StringBuilder();

  String[] inputStepsNames  = inputSteps != null ? inputSteps : ArrayUtils.EMPTY_STRING_ARRAY;
  retval.append( "    " ).append( XMLHandler.addTagValue( "join_type", getJoinType() ) );
  for ( int i = 0; i < inputStepsNames.length; i++ ) {
    retval.append( "    " ).append( XMLHandler.addTagValue( "step" + i, inputStepsNames[ i ] ) );
  }

  retval.append( "    " ).append( XMLHandler.addTagValue( "number_input", inputStepsNames.length ) );
  retval.append( "    " ).append( XMLHandler.openTag( "keys" ) ).append( Const.CR );
  for ( int i = 0; i < keyFields.length; i++ ) {
    retval.append( "      " ).append( XMLHandler.addTagValue( "key", keyFields[i] ) );
  }
  retval.append( "    " ).append( XMLHandler.closeTag( "keys" ) ).append( Const.CR );

  return retval.toString();
}
 
Example #14
Source Project: sofa-acts   Author: sofastack   File: CSVApisUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get .csv file path based on the class
 *
 * @param objClass
 * @param csvPath
 * @return
 */
private static String getCsvFileName(Class<?> objClass, String csvPath) {

    if (isWrapClass(objClass)) {
        LOG.warn("do nothing when simple type");
        return null;
    }
    String[] paths = csvPath.split("/");
    ArrayUtils.reverse(paths);

    String className = objClass.getSimpleName() + ".csv";

    if (!StringUtils.equals(className, paths[0])) {
        csvPath = StringUtils.replace(csvPath, paths[0], className);
    }

    return csvPath;
}
 
Example #15
Source Project: govpay   Author: link-it   File: ConfigurazioniConverter.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static it.govpay.bd.configurazione.model.Mail getConfigurazioneMailPromemoriaDTOPatch(MailTemplate mailPromemoria) throws ServiceException, ValidationException{
		it.govpay.bd.configurazione.model.Mail dto = new it.govpay.bd.configurazione.model.Mail();
		
		dto.setAllegaPdf(mailPromemoria.AllegaPdf());
		dto.setTipo(mailPromemoria.getTipo());
		if(mailPromemoria.getTipo() != null) {
			// valore tipo contabilita non valido
			if(it.govpay.backoffice.v1.beans.MailTemplate.TipoEnum.fromValue(mailPromemoria.getTipo()) == null) {
				throw new ValidationException("Codifica inesistente per tipo trasformazione. Valore fornito [" +
						mailPromemoria.getTipo() + "] valori possibili " + ArrayUtils.toString(it.govpay.backoffice.v1.beans.MailTemplate.TipoEnum.values()));
			}
		}
		
//		if(mailPromemoria.getMessaggio() != null && mailPromemoria.getMessaggio() instanceof String)
//			dto.setMessaggio((String) mailPromemoria.getMessaggio());
//		else 
			dto.setMessaggio((ConverterUtils.toJSON(mailPromemoria.getMessaggio(),null)));
//		if(mailPromemoria.getOggetto() != null && mailPromemoria.getOggetto() instanceof String)
//			dto.setOggetto((String) mailPromemoria.getOggetto());
//		else 
			dto.setOggetto((ConverterUtils.toJSON(mailPromemoria.getOggetto(),null)));
		
		return dto;
	}
 
Example #16
Source Project: incubator-gobblin   Author: apache   File: FileListUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static List<FileStatus> listMostNestedPathRecursivelyHelper(FileSystem fs, List<FileStatus> files,
    FileStatus fileStatus, PathFilter fileFilter)
    throws IOException {
  if (fileStatus.isDirectory()) {
    FileStatus[] curFileStatus = fs.listStatus(fileStatus.getPath());
    if (ArrayUtils.isEmpty(curFileStatus)) {
      files.add(fileStatus);
    } else {
      for (FileStatus status : curFileStatus) {
        listMostNestedPathRecursivelyHelper(fs, files, status, fileFilter);
      }
    }
  } else if (fileFilter.accept(fileStatus.getPath())) {
    files.add(fileStatus);
  }
  return files;
}
 
Example #17
Source Project: astor   Author: SpoonLabs   File: StrTokenizerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void test2() {

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

        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 #18
Source Project: openhab1-addons   Author: openhab   File: SerialMessage.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Constructor. Creates a new instance of the SerialMessage class from a
 * specified buffer, and subsequently sets the node ID.
 *
 * @param nodeId the node the message is destined for
 * @param buffer the buffer to create the SerialMessage from.
 */
public SerialMessage(int nodeId, byte[] buffer) {
    logger.trace("NODE {}: Creating new SerialMessage from buffer = {}", nodeId, SerialMessage.bb2hex(buffer));
    messageLength = buffer.length - 2; // buffer[1];
    byte messageCheckSumm = calculateChecksum(buffer);
    byte messageCheckSummReceived = buffer[messageLength + 1];
    if (messageCheckSumm == messageCheckSummReceived) {
        logger.trace("NODE {}: Checksum matched", nodeId);
        isValid = true;
    } else {
        logger.trace("NODE {}: Checksum error. Calculated = 0x%02X, Received = 0x%02X", nodeId, messageCheckSumm,
                messageCheckSummReceived);
        isValid = false;
        return;
    }
    this.priority = SerialMessagePriority.High;
    this.messageType = buffer[2] == 0x00 ? SerialMessageType.Request : SerialMessageType.Response;
    this.messageClass = SerialMessageClass.getMessageClass(buffer[3] & 0xFF);
    this.messagePayload = ArrayUtils.subarray(buffer, 4, messageLength + 1);
    this.messageNode = nodeId;
    logger.trace("NODE {}: Message payload = {}", getMessageNode(), SerialMessage.bb2hex(messagePayload));
}
 
Example #19
Source Project: systemds   Author: tugraz-isds   File: TfMetaUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static int[] parseJsonObjectIDList(JSONObject spec, String[] colnames, String group) 
	throws JSONException
{
	int[] colList = new int[0];
	boolean ids = spec.containsKey("ids") && spec.getBoolean("ids");
	
	if( spec.containsKey(group) && spec.get(group) instanceof JSONArray )
	{
		JSONArray colspecs = (JSONArray)spec.get(group);
		colList = new int[colspecs.size()];
		for(int j=0; j<colspecs.size(); j++) {
			JSONObject colspec = (JSONObject) colspecs.get(j);
			colList[j] = ids ? colspec.getInt("id") : 
				(ArrayUtils.indexOf(colnames, colspec.get("name")) + 1);
			if( colList[j] <= 0 ) {
				throw new RuntimeException("Specified column '" +
					colspec.get(ids?"id":"name")+"' does not exist.");
			}
		}
		
		//ensure ascending order of column IDs
		Arrays.sort(colList);
	}
	
	return colList;
}
 
Example #20
Source Project: freehealth-connector   Author: taktik   File: HandlersLoader.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
static Handler<?>[] addingDefaultHandlers(Handler<?>[] result) {
   ArrayList<Class> requiredHandler = new ArrayList(defaultHandlers.size());
   requiredHandler.addAll(defaultHandlers);
   CollectionUtils.filter(requiredHandler, new HandlersLoader.DefaultHandlersPredicate(result));
   Iterator i$ = requiredHandler.iterator();

   while(i$.hasNext()) {
      Class handler = (Class)i$.next();

      try {
         LOG.debug("Adding required handler [{}]", handler.getName());
         result = (Handler[])((Handler[])ArrayUtils.add(result, handler.newInstance()));
      } catch (Exception var5) {
         LOG.warn("Unable to add required handler", var5);
      }
   }

   return result;
}
 
Example #21
Source Project: canal-1.1.3   Author: tianheframe   File: LengthCodedStringReader.java    License: Apache License 2.0 6 votes vote down vote up
public String readLengthCodedString(byte[] data) throws IOException {
    byte[] lengthBytes = ByteHelper.readBinaryCodedLengthBytes(data, getIndex());
    long length = ByteHelper.readLengthCodedBinary(data, getIndex());
    setIndex(getIndex() + lengthBytes.length);
    if (ByteHelper.NULL_LENGTH == length) {
        return null;
    }

    try {
        return new String(ArrayUtils.subarray(data, getIndex(), (int) (getIndex() + length)),
            encoding == null ? CODE_PAGE_1252 : encoding);
    } finally {
        setIndex((int) (getIndex() + length));
    }

}
 
Example #22
Source Project: OpenLabeler   Author: kinhong   File: TFTrainer.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isTraining() {
    List<Container> containers = dockerClient.listContainersCmd().withShowAll(true).exec();
    for (Container container : containers) {
        String name = Settings.getContainerName();
        if (ArrayUtils.isNotEmpty(container.getNames()) && container.getNames()[0].contains(name)) {
            return isRunning(container);
        }
    }
    return false;
}
 
Example #23
Source Project: Liudao   Author: ysrc   File: DimensionService.java    License: GNU General Public License v3.0 5 votes vote down vote up
public List distinct(Event event, String[] condDimensions, EnumTimePeriod enumTimePeriod, String aggrDimension) {
    if (event == null || ArrayUtils.isEmpty(condDimensions) || enumTimePeriod == null || aggrDimension == null) {
        logger.error("参数错误");
        return null;
    }

    Document query = new Document();
    for (String dimension : condDimensions) {
        Object value = getProperty(event, dimension);
        if (value == null || "".equals(value)) {
            return null;
        }
        query.put(dimension, value);
    }

    query.put(Event.OPERATETIME, new Document("$gte", enumTimePeriod.getMinTime(event.getOperateTime())).append("$lte", enumTimePeriod.getMaxTime(event.getOperateTime())));
    return mongoDao.distinct(event.getScene(), query, aggrDimension);
}
 
Example #24
Source Project: freehealth-connector   Author: taktik   File: ConnectorIOUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static byte[] base64Decode(byte[] input, boolean recursive) throws TechnicalConnectorException {
   byte[] result = ArrayUtils.clone(input);
   String content = toString(result, Charset.UTF_8);
   if (content.matches("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$")) {
      result = Base64.decode(result);
      if (recursive) {
         result = base64Decode(result, recursive);
      }
   }

   return result;
}
 
Example #25
Source Project: incubator-pinot   Author: apache   File: NoDictionaryEqualsPredicateEvaluatorsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLongPredicateEvaluators() {
  long longValue = _random.nextLong();
  String stringValue = Long.toString(longValue);

  EqPredicate eqPredicate = new EqPredicate(COLUMN_EXPRESSION, stringValue);
  PredicateEvaluator eqPredicateEvaluator =
      EqualsPredicateEvaluatorFactory.newRawValueBasedEvaluator(eqPredicate, FieldSpec.DataType.LONG);

  NotEqPredicate notEqPredicate = new NotEqPredicate(COLUMN_EXPRESSION, stringValue);
  PredicateEvaluator neqPredicateEvaluator =
      NotEqualsPredicateEvaluatorFactory.newRawValueBasedEvaluator(notEqPredicate, FieldSpec.DataType.LONG);

  Assert.assertTrue(eqPredicateEvaluator.applySV(longValue));
  Assert.assertFalse(neqPredicateEvaluator.applySV(longValue));

  long[] randomLongs = new long[NUM_MULTI_VALUES];
  PredicateEvaluatorTestUtils.fillRandom(randomLongs);
  randomLongs[_random.nextInt(NUM_MULTI_VALUES)] = longValue;

  Assert.assertTrue(eqPredicateEvaluator.applyMV(randomLongs, NUM_MULTI_VALUES));
  Assert.assertFalse(neqPredicateEvaluator.applyMV(randomLongs, NUM_MULTI_VALUES));

  for (int i = 0; i < 100; i++) {
    long random = _random.nextLong();
    Assert.assertEquals(eqPredicateEvaluator.applySV(random), (random == longValue));
    Assert.assertEquals(neqPredicateEvaluator.applySV(random), (random != longValue));

    PredicateEvaluatorTestUtils.fillRandom(randomLongs);
    Assert.assertEquals(eqPredicateEvaluator.applyMV(randomLongs, NUM_MULTI_VALUES),
        ArrayUtils.contains(randomLongs, longValue));
    Assert.assertEquals(neqPredicateEvaluator.applyMV(randomLongs, NUM_MULTI_VALUES),
        !ArrayUtils.contains(randomLongs, longValue));
  }
}
 
Example #26
Source Project: mall   Author: djkdeveloper   File: ShoppingCartServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 查询购物车信息
 *
 * @param customerId 会员ID
 * @param ids        购物车id
 * @return 返回购物车信息
 */
@Log
private List<ShoppingCart> queryShoppingCarts(long customerId, Long[] ids) {
    if (ArrayUtils.isEmpty(ids)) {
        return shoppingCartMapper.queryShoppingCart(customerId);
    } else {
        Map<String, Object> params = new HashMap<>();
        params.put("customerId", customerId);
        params.put("ids", ids);
        return shoppingCartMapper.queryShoppingCartByIds(params);
    }

}
 
Example #27
Source Project: freehealth-connector   Author: taktik   File: OcspRef.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
OcspRef(byte[] inOcspEncoded) {
   this.ocspEncoded = ArrayUtils.clone(inOcspEncoded);

   try {
      this.ocsp = (BasicOCSPResp)(new OCSPResp(this.ocspEncoded)).getResponseObject();
   } catch (Exception var3) {
      throw new IllegalArgumentException(var3);
   }
}
 
Example #28
Source Project: pentaho-kettle   Author: pentaho   File: StepMeta.java    License: Apache License 2.0 5 votes vote down vote up
private void setDeprecationAndSuggestedStep() {
  PluginRegistry registry = PluginRegistry.getInstance();
  final List<PluginInterface> deprecatedSteps = registry.getPluginsByCategory( StepPluginType.class,
    BaseMessages.getString( PKG, "BaseStep.Category.Deprecated" ) );
  for ( PluginInterface p : deprecatedSteps ) {
    String[] ids = p.getIds();
    if ( !ArrayUtils.isEmpty( ids ) && ids[0].equals( this.stepid ) ) {
      this.isDeprecated = true;
      this.suggestion = registry.findPluginWithId( StepPluginType.class, this.stepid ) != null
        ? registry.findPluginWithId( StepPluginType.class, this.stepid ).getSuggestion() : "";
      break;
    }
  }
}
 
Example #29
Source Project: systemds   Author: apache   File: FrameBlock.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Append a column of value type STRING as the last column of 
 * the data frame. The given array is wrapped but not copied 
 * and hence might be updated in the future.
 * 
 * @param col array of strings
 */
public void appendColumn(String[] col) {
	ensureColumnCompatibility(col.length);
	String[] colnames = getColumnNames(); //before schema modification
	_schema = (ValueType[]) ArrayUtils.add(_schema, ValueType.STRING);
	_colnames = (String[]) ArrayUtils.add(colnames, createColName(_schema.length));
	_coldata = (_coldata==null) ? new Array[]{new StringArray(col)} :
		(Array[]) ArrayUtils.add(_coldata, new StringArray(col));
	_numRows = col.length;

}
 
Example #30
Source Project: GyJdbc   Author: hope-for   File: Result.java    License: Apache License 2.0 5 votes vote down vote up
public PageResult<E> pageQuery(Page page) throws Exception {
    Object pageParams[] = {};
    String pageSql = "SELECT SQL_CALC_FOUND_ROWS * FROM (" + sql + ") temp ";
    pageSql = pageSql + " LIMIT ?,?";
    pageParams = ArrayUtils.addAll(params, new Object[]{page.getOffset(), page.getPageSize()});
    List<E> paged = jdbcTemplate.query(pageSql, pageParams, BeanPropertyRowMapper.newInstance(type));
    String countSql = "SELECT FOUND_ROWS() ";
    int count = jdbcTemplate.queryForObject(countSql, Integer.class);
    return new PageResult(paged, count);
}