Java Code Examples for org.apache.commons.lang3.ArrayUtils.isNotEmpty()

The following are Jave code examples for showing how to use isNotEmpty() of the org.apache.commons.lang3.ArrayUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: elasticsearch-aem   File: PageContentBuilder.java   View Source Code Vote up 10 votes
@Override
public IndexEntry create(String path, @Nonnull ResourceResolver resolver) {
  String[] indexRules = getIndexRules(PRIMARY_TYPE_VALUE);
  if (ArrayUtils.isNotEmpty(indexRules)) {
    PageManager pageManager = resolver.adaptTo(PageManager.class);
    if (pageManager != null) {
      Page page = pageManager.getPage(path);
      if (page != null) {
        IndexEntry ret = new IndexEntry("idx", "page", path);
        Resource res = page.getContentResource();
        if (res != null) {
          ret.addContent(getProperties(res, indexRules));
        }
        return ret;
      }
    }
  }
  else {
    LOG.warn("Could not load indexRules for " + PRIMARY_TYPE_VALUE);
  }
  return null;
}
 
Example 2
Project: elasticsearch-aem   File: DAMAssetContentBuilder.java   View Source Code Vote up 8 votes
@Override
public IndexEntry create(String path, @Nonnull ResourceResolver resolver) {
  String[] indexRules = getIndexRules(PRIMARY_TYPE_VALUE);
  if (ArrayUtils.isNotEmpty(indexRules)) {
  Resource res = resolver.getResource(path);
  if (res != null) {
    Asset asset = res.adaptTo(Asset.class);
    if (asset != null) {
      IndexEntry ret = new IndexEntry("idx", "asset", path);
      ret.addContent(getProperties(res, indexRules));
      return ret;
    }
    LOG.error("Could not adapt asset");
    }
  }
  return null;
}
 
Example 3
Project: bluegreen-manager   File: RdsClientTest.java   View Source Code Vote up 7 votes
/**
 * Test helper - makes describe result with a named instance.
 */
private DescribeDBInstancesResult makeDescribeDBInstancesResult(String... instanceNames)
{
  DescribeDBInstancesResult result = new DescribeDBInstancesResult();
  List<DBInstance> dbInstances = new ArrayList<DBInstance>();
  if (ArrayUtils.isNotEmpty(instanceNames))
  {
    for (String instanceName : instanceNames)
    {
      DBInstance dbInstance = new DBInstance();
      dbInstance.setDBInstanceIdentifier(instanceName);
      dbInstances.add(dbInstance);
    }
  }
  result.setDBInstances(dbInstances);
  return result;
}
 
Example 4
Project: wechat-mall   File: AuthResource.java   View Source Code Vote up 6 votes
@POST
@Path("token")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response token(Authentication auth) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
    String entity = ErrorCode.NOT_AUTHED.toString();
    NettyRemotingClient client = RPCServices.getAuthService();
    RemotingCommand request = RemotingCommand.createRequestCommand();
    byte[] body = JsonUtil.toBytes(auth);
    request.setBody(body);
    request.getExtFields().put("action", "token");
    RemotingCommand responce = client.invokeSync(request);
    if (ArrayUtils.isNotEmpty(responce.getBody())) {
        entity = JsonUtil.toJson(responce.getBody());
    }
    return ResponseUtil.defaultRes(entity);

}
 
Example 5
Project: bluegreen-manager   File: ElbClientTest.java   View Source Code Vote up 6 votes
/**
 * Test helper - makes describe result with one or more named instances.
 */
private DescribeInstanceHealthResult makeDescribeInstanceHealthResult(String... instanceIds)
{
  DescribeInstanceHealthResult result = new DescribeInstanceHealthResult();
  if (ArrayUtils.isNotEmpty(instanceIds))
  {
    List<InstanceState> instanceStates = new ArrayList<InstanceState>();
    for (String instanceId : instanceIds)
    {
      InstanceState instanceState = new InstanceState();
      instanceState.setInstanceId(instanceId);
      instanceStates.add(instanceState);
    }
    result.setInstanceStates(instanceStates);
  }
  return result;
}
 
Example 6
Project: bluegreen-manager   File: RdsAnalyzerTest.java   View Source Code Vote up 6 votes
/**
 * Test helper - makes a DBInstance having the specified paramgroup names.
 */
private DBInstance makeDBInstanceWithParamGroups(RdsParameterApplyStatus parameterApplyStatus,
                                                 String... paramGroupNames)
{
  DBInstance dbInstance = new DBInstance();
  dbInstance.setDBInstanceIdentifier(INSTANCE_NAME);
  if (ArrayUtils.isNotEmpty(paramGroupNames))
  {
    Collection<DBParameterGroupStatus> paramGroups = new ArrayList<DBParameterGroupStatus>();
    for (String paramGroupName : paramGroupNames)
    {
      paramGroups.add(makeDBParameterGroupStatus(paramGroupName, parameterApplyStatus));
    }
    dbInstance.setDBParameterGroups(paramGroups);
  }
  return dbInstance;
}
 
Example 7
Project: beaker-notebook-archive   File: GraphicsSerializer.java   View Source Code Vote up 6 votes
@Override
public void serialize(T graphics, JsonGenerator jgen, SerializerProvider sp)
        throws IOException, JsonProcessingException {
    jgen.writeObjectField("type", graphics.getClass().getSimpleName());
    jgen.writeObjectField("uid", graphics.getUid());
    jgen.writeObjectField("visible", graphics.getVisible());
    jgen.writeObjectField("yAxis", graphics.getYAxis());
    jgen.writeObjectField("hasClickAction", graphics.hasClickAction());
    if(StringUtils.isNotEmpty(graphics.getClickTag())) {
        jgen.writeObjectField("clickTag", graphics.getClickTag());
    }
    Map<String, String> keyTags = graphics.getKeyTags();
    if(keyTags != null && !keyTags.isEmpty()) {
        jgen.writeObjectField("keyTags", keyTags);
    }
    Object[] keys = graphics.getKeys();
    if(ArrayUtils.isNotEmpty(keys)) {
        jgen.writeObjectField("keys", keys);
    }
}
 
Example 8
Project: jvm-sandbox   File: GaEnumUtils.java   View Source Code Vote up 6 votes
public static <T extends Enum<T>> Set<T> valuesOf(Class<T> enumClass, String[] enumNameArray, T[] defaultEnumArray) {
    final Set<T> enumSet = new LinkedHashSet<T>();
    if (ArrayUtils.isNotEmpty(enumNameArray)) {
        for (final String enumName : enumNameArray) {
            final T enumValue = EnumUtils.getEnum(enumClass, enumName);
            if (null != enumValue) {
                enumSet.add(enumValue);
            }
        }
    }
    if (CollectionUtils.isEmpty(enumSet)
            && ArrayUtils.isNotEmpty(defaultEnumArray)) {
        Collections.addAll(enumSet, defaultEnumArray);
    }
    return enumSet;
}
 
Example 9
Project: bluegreen-manager   File: RdsAnalyzerTest.java   View Source Code Vote up 6 votes
/**
 * Test helper - makes a DBInstance having the specified security group names.
 */
private DBInstance makeDBInstanceWithSecurityGroups(String... securityGroupIds)
{
  DBInstance dbInstance = new DBInstance();
  dbInstance.setDBInstanceIdentifier(INSTANCE_NAME);
  if (ArrayUtils.isNotEmpty(securityGroupIds))
  {
    List<VpcSecurityGroupMembership> securityGroups = new ArrayList<VpcSecurityGroupMembership>();
    for (String securityGroupId : securityGroupIds)
    {
      securityGroups.add(makeVpcSecurityGroupMembership(securityGroupId));
    }
    dbInstance.setVpcSecurityGroups(securityGroups);
  }
  return dbInstance;
}
 
Example 10
Project: wechat-mall   File: JsonUtil.java   View Source Code Vote up 5 votes
/**
 * 直接解析json
 */
public static String toJson(final byte[] data) {
    if (ArrayUtils.isNotEmpty(data)) {
        return new String(data, Charset.forName("UTF-8"));
    }
    return "";
}
 
Example 11
Project: headless-chrome   File: HeadlessDriverUtils.java   View Source Code Vote up 5 votes
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 12
Project: beaker-notebook-archive   File: CategoryGraphics.java   View Source Code Vote up 5 votes
public void setValue(Object[] value) {
  if(value != null && ArrayUtils.isNotEmpty(value)){
    if(value[0] instanceof List){
      this.value = new Number[value.length][];
      for(int i=0; i < value.length; i++){
        List<?> a = (List<?>)value[i];
        this.value[i] = a.toArray(new Number[a.size()]);
      }
    }else{
      this.value = new Number[][]{Arrays.copyOf(value, value.length, Number[].class)};
    }
  }
}
 
Example 13
Project: TARA-Server   File: AuthenticationServiceAspect.java   View Source Code Vote up 5 votes
private void logArguments(Object... arguments) {
    if (ArrayUtils.isNotEmpty(arguments)) {
        if (arguments[0] != null) {
            RequestContext context = (RequestContext) arguments[0];
            this.log.info("Request: {}", context.getExternalContext().getRequestParameterMap());
        }
    }
}
 
Example 14
Project: dooo   File: CookieInterceptor.java   View Source Code Vote up 5 votes
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
	
	if (modelAndView!=null && ArrayUtils.isNotEmpty(request.getCookies())) {
		HashMap<String, Cookie> cookieMap = new HashMap<>(1<<4);
		for (Cookie ck : request.getCookies()) {
			cookieMap.put(ck.getName(), ck);
		}
		modelAndView.addObject("cookieMap", cookieMap);
	}
	
	super.postHandle(request, response, handler, modelAndView);
}
 
Example 15
Project: wisp   File: UnitTestTransactionalTestExecutionListener.java   View Source Code Vote up 5 votes
private void initTestData(TestContext testContext) {
    List<String> sqlFiles = new ArrayList<String>();
    /**
     * 读取测试类指定的sql文件
     */
    Class<?> testClass = testContext.getTestClass();
    SqlConfig sqlConfigInClass = testClass.getAnnotation(SqlConfig.class);
    if (sqlConfigInClass != null) {
        String[] sqlFilesInClass = sqlConfigInClass.sqlFiles();
        if (ArrayUtils.isNotEmpty(sqlFilesInClass)) {
            sqlFiles.addAll(Arrays.asList(sqlFilesInClass));
        }
    }
    /**
     * 读取测试方法指定的sql文件
     */
    Method method = testContext.getTestMethod();
    SqlConfig sqlConfigInMethod = method.getAnnotation(SqlConfig.class);
    if (sqlConfigInMethod != null) {
        String[] sqlFilesInMethod = sqlConfigInMethod.sqlFiles();
        if (ArrayUtils.isNotEmpty(sqlFilesInMethod)) {
            sqlFiles.addAll(Arrays.asList(sqlFilesInMethod));
        }
    }
    /**
     * 执行sql
     */
    for (String sqlFile : sqlFiles) {
        LOGGER.info(String.format("execute sql file [%s]", sqlFile));
        this.executeSqlScript(testContext, sqlFile, false);
    }
}
 
Example 16
Project: xm-commons   File: LogObjectPrinter.java   View Source Code Vote up 4 votes
/**
 * Gets join point input params description string.
 *
 * @param joinPoint         aspect join point
 * @param includeParamNames input parameters names to be printed. NOTE! can be overridden with @{@link
 *                          LoggingAspectConfig}
 * @return join point input params description string
 */
public static String printInputParams(JoinPoint joinPoint, String... includeParamNames) {
    try {
        if (joinPoint == null) {
            return "joinPoint is null";
        }

        Signature signature = joinPoint.getSignature();
        if (!(signature instanceof MethodSignature)) {
            return PRINT_EMPTY_LIST;
        }

        Optional<LoggingAspectConfig> config = AopAnnotationUtils.getConfigAnnotation(joinPoint);

        String[] includeParams = includeParamNames;
        String[] excludeParams = EMPTY_ARRAY;
        boolean inputCollectionAware = LoggingAspectConfig.DEFAULT_INPUT_COLLECTION_AWARE;

        if (config.isPresent()) {
            if (!config.get().inputDetails()) {
                return PRINT_HIDDEN;
            }
            inputCollectionAware = config.get().inputCollectionAware();
            if (ArrayUtils.isNotEmpty(config.get().inputIncludeParams())) {
                includeParams = config.get().inputIncludeParams();
            }
            if (ArrayUtils.isEmpty(includeParams) && ArrayUtils.isNotEmpty(config.get().inputExcludeParams())) {
                excludeParams = config.get().inputExcludeParams();
            }
        }

        MethodSignature ms = (MethodSignature) signature;
        String[] params = ms.getParameterNames();
        return ArrayUtils.isNotEmpty(params) ? renderParams(joinPoint,
                                                            params,
                                                            includeParams,
                                                            excludeParams,
                                                            inputCollectionAware) : PRINT_EMPTY_LIST;
    } catch (IndexOutOfBoundsException | IllegalArgumentException e) {
        log.warn("Error while print params: {}, params = {}", e, joinPoint.getArgs());
        return "printerror: " + e;
    }
}
 
Example 17
Project: pprxmtr   File: GifGeneratorHandler.java   View Source Code Vote up 4 votes
@Override
public ApiGatewayResponse handleRequest(SNSEvent input, Context context) {
	LOG.info("Loading Gif Generator Java Lambda handler.");

	ObjectMapper mapper = new ObjectMapper();

	if (CollectionUtils.isNotEmpty(input.getRecords())) {
		try {
			JsonNode json = mapper.readTree(input.getRecords().get(0).getSNS().getMessage());
			byte[] gif = ArrayUtils.EMPTY_BYTE_ARRAY;

			if (json.has("emojiUrl")) {
				HttpClient client = HttpClientBuilder.create().build();
				String emojiUrl = json.get("emojiUrl").asText();
				HttpGet getImageRequest = new HttpGet(emojiUrl);
				HttpResponse getImageResponse = client.execute(getImageRequest);
				int getImageStatus = getImageResponse.getStatusLine().getStatusCode();
				LOG.info("Get image status: {}.", getImageStatus);

				if (StringUtils.contains(getImageResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue(), "image")) {
					byte[] imageFile = IOUtils.toByteArray(getImageResponse.getEntity().getContent());
					gif = GifGenerator.generateGif(imageFile);
				} else {
					LOG.error("Given image URL did not return an image according to mime type!");
				}
			}

			if (ArrayUtils.isNotEmpty(gif)) {
				LOG.info("Gif created successfully, storing in S3.");
				String emoji = json.get("text").asText();
				String emojiName = StringUtils.removeEnd(StringUtils.removeStart(StringUtils.strip(emoji), ":"), ":");
				emojiName = emojiName.replaceAll("ä", "a").replaceAll("ö", "o").replaceAll("å", "o");

				InputStream is = new ByteArrayInputStream(gif);
				ObjectMetadata metadata = new ObjectMetadata();
				metadata.setContentLength(gif.length);
				metadata.setContentType("image/gif");

				if (UrlValidator.getInstance().isValid(emojiName)) {
					emojiName = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('0', '9'))
							.retainFrom(StringUtils.substringAfterLast(emojiName, "/"));
				}

				String filenamePrefix = emojiName + "_approximated_";
				if (!S3.fileExistsInBucket(filenamePrefix)) {
					S3.storeFileInBucket(filenamePrefix + System.currentTimeMillis() + ".gif", is, metadata);
				}

				LOG.info("Image stored in S3, publishing to topic s3-file-ready");
				SNS.publish("s3-file-ready", mapper.writeValueAsString(json)).get();
			} else {
				LOG.error("Gif generator returned an empty byte array, sending error response");
				SNS.publish("gif-generator-error", mapper.writeValueAsString(json)).get();
			}
		} catch (IOException | InterruptedException | ExecutionException e) {
			LOG.error("Exception occured when creating GIF.", e);
		}
	}

	Response responseBody = new Response("pprxmtr-gif-generator called.", new HashMap<>());
	return ApiGatewayResponse.builder().setStatusCode(200).setObjectBody(responseBody).build();
}
 
Example 18
Project: microservice   File: WorkflowProcessDefinitionService.java   View Source Code Vote up 4 votes
/**
 * 部署classpath下面的流程定义
 * <p>
 * 从属性配置文件中获取属性<b>workflow.modules</b>扫描**deployments**
 * </p>
 * <p>
 * 然后从每个**deployments/${module}**查找在属性配置文件中的属性**workflow.module.keys.${
 * submodule}**
 * <p>
 * 配置实例:
 * <p/>
 * <pre>
 * #workflow for deploy
 * workflow.modules=budget,erp,oa
 * workflow.module.keys.budget=budget
 * workflow.module.keys.erp=acceptInsurance,billing,effectInsurance,endorsement,payment
 * workflow.module.keys.oa=caruse,leave,officalstamp,officesupply,out,overtime
 * </pre>
 * <p/>
 * </p>
 *
 * @param processKey 流程定义KEY
 * @throws Exception
 */
public void deployFromClasspath(String exportDir, String... processKey) throws Exception {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    String[] processKeys = {"leave", "leave-dynamic-from", "leave-formkey", "dispatch"};
    for (String loopProcessKey : processKeys) {

  /*
   * 需要过滤指定流程
   */
        if (ArrayUtils.isNotEmpty(processKey)) {
            if (ArrayUtils.contains(processKey, loopProcessKey)) {
                logger.debug("hit module of {}", (Object[]) processKey);
                deploySingleProcess(resourceLoader, loopProcessKey, exportDir);
            } else {
                logger.debug("module: {} not equals process key: {}, ignore and continue find next.", loopProcessKey, processKey);
            }
        } else {
    /*
     * 所有流程
     */
            deploySingleProcess(resourceLoader, loopProcessKey, exportDir);
        }
    }
}
 
Example 19
Project: oneops   File: Dispatcher.java   View Source Code Vote up 4 votes
/**
 * Message dispatcher logic.
 *
 * @param msg the msg
 */
public void dispatch(NotificationMessage msg) {
    if (msg.getNsPath() == null) {
        String nsPath = getNsPath(msg);
        if (nsPath != null) {
            msg.setNsPath(nsPath);
        } else {
            logger.error("Can not figure out nsPath for msg " + gson.toJson(msg));
            return;
        }
    }

    List<BasicSubscriber> subscribers = sbrService.getSubscribersForNs(msg.getNsPath());
    try {
        for (BasicSubscriber sub : subscribers) {
            NotificationMessage nMsg = msg;

            if (sub.hasFilter() && !sub.getFilter().accept(nMsg)) {
                continue;
            }
            if (sub.hasTransformer()) {
                nMsg = sub.getTransformer().transform(nMsg);
            }
            if (sub instanceof EmailSubscriber) {
                eSender.postMessage(nMsg, sub);
            } else if (sub instanceof SNSSubscriber) {
                snsSender.postMessage(nMsg, sub);
            } else if (sub instanceof URLSubscriber) {
              if (sub.getFilter() instanceof NotificationFilter) {
                NotificationFilter nFilter = NotificationFilter.class.cast(sub.getFilter());
                if (nFilter.isIncludeCi() && ArrayUtils.isNotEmpty(nFilter.getClassNames())) {
                  final List<Long> ciIds = dpmtMapper
                      .getDeploymentRfcCIs(msg.getCmsId(), null, null, nFilter.getClassNames(),
                          nFilter.getActions())
                      .stream()
                      .map(rfc -> rfc.getCiId())
                      .collect(Collectors.toList());
                  if(ciIds.isEmpty()){
                    // There are no ci's which sink is subscribed to , skip notifications.
                    continue;
                  }
                  final List<CmsCISimple> cis = cmProcessor.getCiByIdList(ciIds).stream()
                      .map(ci -> cmsUtil.custCI2CISimple(ci, "df")).collect(
                          Collectors.toList());
                  nMsg.setCis(cis);
                }
              }
              if(logger.isDebugEnabled()){
                logger.debug("nMsg " + gson.toJson(nMsg));
              }
              urlSender.postMessage(nMsg, sub);
            } else if (sub instanceof XMPPSubscriber) {
                xmppSender.postMessage(nMsg, sub);
            } else if (sub instanceof SlackSubscriber) {
                slackSender.postMessage(nMsg, sub);
            }
        }
    } catch (Exception e) {
        logger.error("Message dispatching failed.", e);
    }
}
 
Example 20
Project: cryptotrader   File: BitbankDepth.java   View Source Code Vote up 3 votes
@VisibleForTesting
NavigableMap<BigDecimal, BigDecimal> convert(BigDecimal[][] quotes, Comparator<BigDecimal> c) {

    NavigableMap<BigDecimal, BigDecimal> map = new TreeMap<>(c);

    if (ArrayUtils.isNotEmpty(quotes)) {

        for (BigDecimal[] quote : quotes) {

            if (quote.length != 2) {
                continue;
            }

            if (quote[0] == null || quote[0].signum() == 0) {
                continue;
            }

            if (quote[1] == null || quote[1].signum() == 0) {
                continue;
            }

            map.put(quote[0], quote[1]);

        }

    }

    return Collections.unmodifiableNavigableMap(map);

}