Java Code Examples for com.amazonaws.util.CollectionUtils#isNullOrEmpty()

The following examples show how to use com.amazonaws.util.CollectionUtils#isNullOrEmpty() . 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: VmwareManagerImpl.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public List<Pair<String, Long>> getSecondaryStorageStoresUrlAndIdList(long dcId) {
    List<Pair<String, Long>> urlIdList = new ArrayList<>();
    List<DataStore> secStores = _dataStoreMgr.listImageStoresWithFreeCapacity(dcId);
    if (!CollectionUtils.isNullOrEmpty(secStores)) {
        for (DataStore secStore : secStores) {
            if (secStore != null) {
                urlIdList.add(new Pair<>(secStore.getUri(), secStore.getId()));
            }
        }
    }

    if (urlIdList.isEmpty()) {
        // we are using non-NFS image store, then use cache storage instead
        s_logger.info("Secondary storage is not NFS, we need to use staging storage");
        DataStore cacheStore = _dataStoreMgr.getImageCacheStore(dcId);
        if (cacheStore != null) {
            urlIdList.add(new Pair<>(cacheStore.getUri(), cacheStore.getId()));
        } else {
            s_logger.warn("No staging storage is found when non-NFS secondary storage is used");
        }
    }

    return urlIdList;
}
 
Example 2
Source File: RingUtil.java    From smartthings-ringalarm with MIT License 6 votes vote down vote up
private String callWebSocketForStatus(int delayInMillis) {
    String statusResponse = RingConstants.ERROR;
    LinkedList<String> response = new LinkedList<>();
    String wsResponse = runWebSocketRequest(this.deviceInfoData, delayInMillis, response);
    if (wsResponse.equals(RingConstants.SUCCESS)) {
        if (CollectionUtils.isNullOrEmpty(response)) {
            return statusResponse;
        } else {
            String message = StringUtils.removeEnd(StringUtils.substringAfter(response.getLast(), "message\","), "]");
            JSONObject messageJsonObject = new JSONObject(message);
            JSONArray bodyJsonArray = messageJsonObject.getJSONArray("body");
            for (Object object : bodyJsonArray) {
                JSONObject deviceJsonObject = ((JSONObject) object).getJSONObject("device");
                if (deviceJsonObject != null && deviceJsonObject.getJSONObject("v1") != null && !deviceJsonObject.getJSONObject("v1").isNull("mode")) {
                    statusResponse = deviceJsonObject.getJSONObject("v1").getString("mode");
                    break;
                }
            }
        }
    }

    return statusResponse;
}
 
Example 3
Source File: RingUtil.java    From smartthings-ringalarm with MIT License 6 votes vote down vote up
private String callWebSocketForDeviceZid(int delayInMillis) {
    String statusResponse = RingConstants.ERROR;
    LinkedList<String> response = new LinkedList<>();
    String wsResponse = runWebSocketRequest(this.deviceInfoData, delayInMillis, response);
    if (wsResponse.equals(RingConstants.SUCCESS)) {
        if (CollectionUtils.isNullOrEmpty(response)) {
            return statusResponse;
        } else {
            String message = StringUtils.removeEnd(StringUtils.substringAfter(response.getLast(), "message\","), "]");
            JSONObject messageJsonObject = new JSONObject(message);
            JSONArray bodyJsonArray = messageJsonObject.getJSONArray("body");
            for (Object object : bodyJsonArray) {
                JSONObject deviceJsonObject = ((JSONObject) object).getJSONObject("general");
                if (deviceJsonObject != null && deviceJsonObject.getJSONObject("v2") != null
                        && !deviceJsonObject.getJSONObject("v2").isNull("deviceType")
                        && deviceJsonObject.getJSONObject("v2").getString("deviceType").equals("access-code")) {
                    statusResponse = deviceJsonObject.getJSONObject("v2").getString("adapterZid");
                    break;
                }
            }
        }
    }

    return statusResponse;
}
 
Example 4
Source File: AutoFixManager.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the max exception expiry.
 *
 * @param annotationId the annotation id
 * @param resourceId the resource id
 * @param exemptedResourcesForRule the exempted resources for rule
 * @param individuallyExcemptedIssues the individually excempted issues
 * @return the max exception expiry
 * @throws Exception the exception
 */
private String getMaxExceptionExpiry(String annotationId, String resourceId,
        Map<String, List<IssueException>> exemptedResourcesForRule,
        Map<String, IssueException> individuallyExcemptedIssues) throws Exception {

    // check if resource exempted using sticky exception
    List<IssueException> issueExceptions = exemptedResourcesForRule.get(resourceId);
    if (!CollectionUtils.isNullOrEmpty(issueExceptions)) {
        // get the max expiry date exception
    }
    // get individual exception details
    IssueException issueException = individuallyExcemptedIssues.get(annotationId);
    if (issueException != null) {
        return issueException.getExpiryDate();
    } else {
        throw new Exception("unable to find expiry date");
    }
}
 
Example 5
Source File: S3PacbotUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * @param awsS3Client
 * @param s3BucketName
 * @param accessType
 * @return
 */
public static Set<Permission> checkACLPermissions(AmazonS3Client awsS3Client, String s3BucketName, String accessType) {
	AccessControlList bucketAcl;
	Set<Permission> permissionList = new HashSet<>();
	try {
		bucketAcl = awsS3Client.getBucketAcl(s3BucketName);
		List<Grant> grants = bucketAcl.getGrantsAsList();
		if (!CollectionUtils.isNullOrEmpty(grants)) {
			permissionList = checkAnyGrantHasOpenToReadOrWriteAccess(grants, accessType);
		}
	} catch (AmazonS3Exception s3Exception) {
		logger.error("error : ", s3Exception);
		throw new RuleExecutionFailedExeption(s3Exception.getMessage());
	}
	return permissionList;
}
 
Example 6
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public static boolean checkACLAccess(AmazonS3Client awsS3Client, String s3BucketName, String accessType) {
    logger.info("inside the checkACLAccess method");
    Boolean openAcces = false;
    AccessControlList bucketAcl;
    List<Permission> permissionList = null;
    try {
        bucketAcl = awsS3Client.getBucketAcl(s3BucketName);

        List<Grant> grants = bucketAcl.getGrantsAsList();

        // Check grants has which permission
        if (!CollectionUtils.isNullOrEmpty(grants)) {

            permissionList = checkAnyGrantHasOpenToReadOrWriteAccess(grants, accessType);
            if (!CollectionUtils.isNullOrEmpty(permissionList)) {
                openAcces = true;
            }
        }

    } catch (AmazonS3Exception s3Exception) {
        logger.error("error : ", s3Exception);
        throw new RuleExecutionFailedExeption(s3Exception.getMessage());
    }
    return openAcces;
}
 
Example 7
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if is igw found.
 *
 * @param cidrIp the cidr ip
 * @param id the id
 * @param type the type
 * @param issue the issue
 * @param routeTableIdSet the route table id set
 * @param routetableRoutesEsURL the routetable routes es URL
 * @param internetGateWay the internet gate way
 * @param cidrIpv6 the cidr ipv 6
 * @return the boolean
 * @throws Exception the exception
 */
public static Boolean isIgwFound(String cidrIp, String id, String type, Map<String, Object> issue,
        Set<String> routeTableIdSet, String routetableRoutesEsURL, String internetGateWay,String cidrIpv6) throws Exception {
    Boolean isIgwExists = false;
    List<String> routeTableIdList = new ArrayList<>();
    if (!CollectionUtils.isNullOrEmpty(routeTableIdSet)) {
        isIgwExists = getRouteTableRoutesId(routeTableIdList, routeTableIdSet, routetableRoutesEsURL,
        		cidrIp, internetGateWay,cidrIpv6);
        if ("VPC".equals(type)) {
            issue.put(PacmanRuleConstants.VPCID, id);
        } else {
            issue.put(PacmanRuleConstants.SUBID, id);
        }
        if (isIgwExists) {
            issue.put(PacmanRuleConstants.IGW_OPENED, type);
            issue.put(PacmanRuleConstants.ROUTE_TABLEID, String.join(",", routeTableIdList));
            return isIgwExists;
        }

    }
    return isIgwExists;
}
 
Example 8
Source File: S3GlobalAccessAutoFix.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * revokes all ACL permissions.
 *
 * @param awsS3Client the aws S 3 client
 * @param s3BucketName the s 3 bucket name
 */
private void revokeACLPublicPermission(AmazonS3Client awsS3Client, String s3BucketName) {
    AccessControlList bucketAcl;
    try {
        bucketAcl = awsS3Client.getBucketAcl(s3BucketName);
        List<Grant> grants = bucketAcl.getGrantsAsList();
        if (!CollectionUtils.isNullOrEmpty(grants)) {
            for (Grant grant : grants) {
                if ((PacmanSdkConstants.ANY_S3_AUTHENTICATED_USER_URI
                        .equalsIgnoreCase(grant.getGrantee().getIdentifier())
                        || PacmanSdkConstants.ALL_S3_USER_URI.equalsIgnoreCase(grant.getGrantee().getIdentifier()))

                        &&

                        (grant.getPermission().toString().equalsIgnoreCase(PacmanSdkConstants.READ_ACCESS) || (grant
                                .getPermission().toString().equalsIgnoreCase(PacmanSdkConstants.WRITE_ACCESS)
                                || (grant.getPermission().toString()
                                        .equalsIgnoreCase(PacmanSdkConstants.READ_ACP_ACCESS)
                                        || (grant.getPermission().toString()
                                                .equalsIgnoreCase(PacmanSdkConstants.WRITE_ACP_ACCESS)
                                                || grant.getPermission().toString()
                                                        .equalsIgnoreCase(PacmanSdkConstants.FULL_CONTROL)))))) {
                    bucketAcl.revokeAllPermissions(grant.getGrantee());
                }
            }
            awsS3Client.setBucketAcl(s3BucketName, bucketAcl);
        }

    } catch (AmazonS3Exception s3Exception) {
        LOGGER.error(String.format("AmazonS3Exception in revokeACLPublicPermission: %s", s3Exception.getMessage()));
        throw new RuleEngineRunTimeException(s3Exception);
    }
}
 
Example 9
Source File: Util.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Sort on last vuln scan.
 *
 * @param resp the resp
 * @return the list
 */
public static List<Map<String, Object>> sortOnLastVulnScan(List<Map<String, Object>> resp) {

    List<Map<String, Object>> respData = resp.stream().filter(host -> host.get(LAST_VULN_SCAN) != null)
            .collect(Collectors.toList());
    if (!CollectionUtils.isNullOrEmpty(respData)) {
        respData.sort((obj1, obj2) -> 
             LocalDateTime.parse(obj2.get(LAST_VULN_SCAN).toString(), DateTimeFormatter.ISO_DATE_TIME)
                    .compareTo(LocalDateTime.parse(obj1.get(LAST_VULN_SCAN).toString(),
                            DateTimeFormatter.ISO_DATE_TIME))
        );

    }
    return respData;
}
 
Example 10
Source File: HostAssetsEsIndexer.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * Post host asset to ES.
 *
 * @param qualysInfo the qualys info
 * @param type the type
 */
public void postHostAssetToES(Map<String, Map<String, Object>> qualysInfo, String ds,String type,List<Map<String,String>> errorList) {
    LOGGER.info("Uploading");
    String index = ds+"_" + type;
    ElasticSearchManager.createType(index, "qualysinfo", type);
    ElasticSearchManager.createType(index, "vulninfo", type);

    String createTemplate = "{ \"index\" : { \"_index\" : \"%s\", \"_type\" : \"%s\", \"_id\" : \"%s\", \"_parent\" : \"%s\" } }%n";

    Iterator<Entry<String, Map<String, Object>>> it = qualysInfo.entrySet().iterator();
    int i = 0;
    StringBuilder createRequest = new StringBuilder();
    StringBuilder vulnRequest = new StringBuilder();

    while (it.hasNext()) {
        Entry<String, Map<String, Object>> entry = it.next();
        String parent = entry.getKey();
        Map<String, Object> asset = entry.getValue();
        String assetDoc = createESDoc(asset,errorList);
        createRequest.append(String.format(createTemplate, index, "qualysinfo", asset.get(DOC_ID), parent));
        createRequest.append(assetDoc + "\n");
        List<Map<String, Object>> vulnInfo = fetchVulnInfo(asset,errorList);
        if (!CollectionUtils.isNullOrEmpty(vulnInfo)) {
            for (Map<String, Object> vuln : vulnInfo) {
                vulnRequest
                        .append(String.format(createTemplate, index, "vulninfo", vuln.get("@id"), parent));
                vuln.remove("@id");
                vulnRequest.append(createESDoc(vuln,errorList) + "\n");
            }
        }
        i++;

        if (i % 50 == 0) {
            bulkUpload(createRequest.toString(),errorList);
            bulkUpload(vulnRequest.toString(),errorList);
            createRequest = new StringBuilder();
            vulnRequest = new StringBuilder();
        }
    }

    if (createRequest.length() > 0) {
       
        bulkUpload(createRequest.toString(),errorList);
    }
    if (vulnRequest.length() > 0) {
        bulkUpload(vulnRequest.toString(),errorList);
    }

}
 
Example 11
Source File: DeployConfig.java    From aws-lambda-jenkins-plugin with MIT License 4 votes vote down vote up
public List<String> getSecurityGroups() {
    return CollectionUtils.isNullOrEmpty(securityGroups) ? new ArrayList<String>() : securityGroups;
}
 
Example 12
Source File: DeployConfig.java    From aws-lambda-jenkins-plugin with MIT License 4 votes vote down vote up
public List<String> getSubnets() {
    return CollectionUtils.isNullOrEmpty(subnets) ? new ArrayList<String>() : subnets;
}
 
Example 13
Source File: CheckAWSConfigEnabled.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * @param ruleParam
 *
 * ************* Following are the Rule Parameters********* <br><br>
 *
 * ruleKey : check-aws-config-enabled <br><br>
 *
 * severity : Enter the value of severity <br><br>
 *
 * ruleCategory : Enter the value of category <br><br>
 *
 * roleIdentifyingString : Configure it as role/pac_ro <br><br>
 *
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided y execution engine
 *
 */


public RuleResult execute(Map<String, String> ruleParam,Map<String, String> resourceAttributes) {

	logger.debug("========CheckAWSConfigEnabled started=========");
	Map<String, Object> map = null;
	AmazonConfigClient awsConfigClient = null;
	String roleIdentifyingString = ruleParam.get(PacmanSdkConstants.Role_IDENTIFYING_STRING);
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);

	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex

	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();

	if (!PacmanUtils.doesAllHaveValue(severity,category,roleIdentifyingString)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	Annotation annotation = null;
	try {
		map = getClientFor(AWSService.CONFIG, roleIdentifyingString, ruleParam);
		awsConfigClient = (AmazonConfigClient) map.get(PacmanSdkConstants.CLIENT);
		// Check AWS Config Enabled
           DescribeConfigurationRecordersResult describeConfigurationRecordersResult = awsConfigClient.describeConfigurationRecorders();
           List<ConfigurationRecorder> configurationRecorders = describeConfigurationRecordersResult.getConfigurationRecorders();
           if (CollectionUtils.isNullOrEmpty(configurationRecorders)) {
               // Create an annotation if config is not enabled
               annotation = Annotation.buildAnnotation(ruleParam, Annotation.Type.ISSUE);
               annotation.put(PacmanSdkConstants.DESCRIPTION,"AWS Config not enabled");
               annotation.put(PacmanRuleConstants.SEVERITY, severity);
               annotation.put(PacmanRuleConstants.CATEGORY, category);
               issue.put(PacmanRuleConstants.VIOLATION_REASON, "AWS Config not enabled");
               issueList.add(issue);
               annotation.put("issueDetails",issueList.toString());
               logger.debug("========CheckAWSConfigEnabled ended with annotation {} :=========",annotation);
               return new RuleResult(PacmanSdkConstants.STATUS_FAILURE, PacmanRuleConstants.FAILURE_MESSAGE, annotation);
           } else {
               logger.info("AWS Config enabled");
           }
	} catch (UnableToCreateClientException e) {
	    logger.error("unable to get client for following input", e);
		throw new InvalidInputException(e.getMessage());
	}

	logger.debug("========CheckAWSConfigEnabled ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);

}
 
Example 14
Source File: DynamoSpaceConfigClient.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
@Override
public void getSelectedSpaces(Marker marker, SpaceAuthorizationCondition authorizedCondition, SpaceSelectionCondition selectedCondition,
    Handler<AsyncResult<List<Space>>> handler) {
  logger.info(marker, "Getting selected spaces");

  if (authorizedCondition == null || selectedCondition == null) {
    throw new NullPointerException("authorizedCondition and selectedCondition are required");
  }

  final List<Space> result = new ArrayList<>();
  logger.debug(marker, "authorizedCondition: spaceIds: {}, ownerIds {}, packages: {}", authorizedCondition.spaceIds, authorizedCondition.ownerIds, authorizedCondition.packages);
  logger.debug(marker, "selectedCondition: spaceIds: {}, ownerIds {}, packages: {}, shared: {}, negateOwnerIds: {}", selectedCondition.spaceIds, selectedCondition.ownerIds, selectedCondition.packages, selectedCondition.shared, selectedCondition.negateOwnerIds);

  try {
    final Set<String> authorizedSpaces = getAuthorizedSpaces(marker, authorizedCondition);

    // get all shared spaces if the selection for shared spaces is enabled
    if (selectedCondition.shared) {
      spaces.getIndex("shared-index").query(new QuerySpec().withHashKey("shared", 1).withProjectionExpression("id")).pages()
          .forEach(p -> p.forEach(i -> {
            authorizedSpaces.add(i.getString("id"));
          }));
      logger.debug(marker, "Number of space IDs after addition of shared spaces: {}", authorizedSpaces.size());
    }

    // filter out the ones not present in the selectedCondition (null or empty represents 'do not filter')
    if (!CollectionUtils.isNullOrEmpty(selectedCondition.spaceIds)) {
      authorizedSpaces.removeIf(i -> !selectedCondition.spaceIds.contains(i));
      logger.debug(marker, "Number of space IDs after removal of the ones not selected by ID: {}", authorizedSpaces.size());
    }

    // now filter all spaceIds with the ones being selected in the selectedCondition (by checking the space's ownership) (
    if (!CollectionUtils.isNullOrEmpty(selectedCondition.ownerIds)) {
      final Set<String> ownersSpaces = new HashSet<>();
      selectedCondition.ownerIds.forEach(o ->
          spaces.getIndex("owner-index").query(new QuerySpec().withHashKey("owner", o).withProjectionExpression("id")).pages()
              .forEach(p -> p.forEach(i -> ownersSpaces.add(i.getString("id")))));

      // HINT: A ^ TRUE == !A (negateOwnerIds: keep or remove the spaces contained in the owner's spaces list)
      authorizedSpaces.removeIf(i -> !selectedCondition.negateOwnerIds ^ ownersSpaces.contains(i));
      logger.debug(marker, "Number of space IDs after removal of the ones not selected by owner: {}", authorizedSpaces.size());
    }

    // TODO selection per packages is not yet supported: selectedCondition.packages

    logger.info(marker, "Final number of space IDs to be retrieved from DynamoDB: {}", authorizedSpaces.size());
    if (!authorizedSpaces.isEmpty()) {
      int batches = (int) Math.ceil((double) authorizedSpaces.size()/100);
      for (int i=0; i<batches; i++) {
        final TableKeysAndAttributes keys = new TableKeysAndAttributes(dynamoClient.tableName);
        authorizedSpaces.stream().skip(i*100).limit(100).forEach(id -> keys.addHashOnlyPrimaryKey("id", id));

        BatchGetItemOutcome outcome = dynamoClient.db.batchGetItem(keys);
        processOutcome(outcome, result);

        while (!outcome.getUnprocessedKeys().isEmpty()) {
          outcome = dynamoClient.db.batchGetItemUnprocessed(outcome.getUnprocessedKeys());
          processOutcome(outcome, result);
        }
      }
    }

    logger.info(marker, "Number of spaces retrieved from DynamoDB: {}", result.size());
    handler.handle(Future.succeededFuture(result));
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure getting authorized spaces", e);
    handler.handle(Future.failedFuture(e));
  }
}
 
Example 15
Source File: NextStepManager.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the next step.
 *
 * @param ruleId the rule id
 * @param resourceId the resource id
 * @param resourceId 
 * @param clientMap the client map
 * @param serviceType the service type
 * @return the next step
 */
@SuppressWarnings("unchecked")
public AutoFixAction getNextStep(Map<String, String> ruleParam , String normalizedResourceId,  String resourceId, Map<String, Object> clientMap, 
        AWSService serviceType) {

    
    String ruleId = ruleParam.get(PacmanSdkConstants.RULE_ID);
    
    try {
        
       //silent fix can only be aplied to tagging rules , where exception does not makes much sense 
       if(isSilentFixEnabledForRule(ruleId)){
            return AutoFixAction.AUTOFIX_ACTION_FIX;
        }
        // if the resource was ever exempted we will send mail to CSR and
        // Exception Owner
        if (isServiceTaggable(serviceType) && null != wasResourceEverExempted(normalizedResourceId, clientMap, serviceType)) {
            return AutoFixAction.AUTOFIX_ACTION_EMAIL_REMIND_EXCEPTION_EXPIRY;
        }
        String url = CommonUtils.getPropValue(PacmanSdkConstants.RESOURCE_GET_LASTACTION);
        url = url.concat("?resourceId=").concat(resourceId);
        String response;
        try{
            response = CommonUtils.doHttpGet(url);
        }catch (Exception e) {
            // this is an api failure
            logger.error("uable to call API",e);
            new SlackMessageRelay().sendMessage(CommonUtils.getPropValue(PacmanSdkConstants.AUTH_API_OWNER_SLACK_HANDLE), e.getMessage());
            return AutoFixAction.UNABLE_TO_DETERMINE; 
        }
        Map<String, Object> resourceDetailsMap = (Map<String, Object>) CommonUtils.deSerializeToObject(response);
        Double responseCode = Double.valueOf((resourceDetailsMap.get("responseCode").toString()));
        int autoFixDelay = getAutoFixDelay(ruleId);
        int maxEmails = getMaxNotifications(ruleId);
       
        List<String> lastActions = (List<String>) resourceDetailsMap.get("lastActions");
        
        if(CollectionUtils.isNullOrEmpty(lastActions)){
                //no action taken yet, and silent fix is not enabled , first action should be email
                return AutoFixAction.AUTOFIX_ACTION_EMAIL;
        }else{
                Collections.sort(lastActions);//sort based on date and find the first action time
                //LocalDateTime lastActionTime =  LocalDateTime.parse(lastActions.get(lastActions.size() - 1), DateTimeFormatter.ofPattern(DATE_TIME_FORMAT));
                LocalDateTime firstActionTime =  LocalDateTime.parse(lastActions.get(0), DateTimeFormatter.ofPattern(DATE_TIME_FORMAT));
                LocalDateTime currentTime = LocalDateTime.now();
                long elapsedHours = ChronoUnit.HOURS.between(firstActionTime, currentTime);

                if (lastActions.size() >= maxEmails) {
                    
                    if (elapsedHours >= autoFixDelay) {
                        return AutoFixAction.AUTOFIX_ACTION_FIX;
                    } else {
                        return AutoFixAction.DO_NOTHING;
                    }
                }else{
                    long nextActionTime = getNextActionTime(maxEmails,autoFixDelay,lastActions.size());
                    if(elapsedHours>=nextActionTime){
                        return AutoFixAction.AUTOFIX_ACTION_EMAIL;
                    }else{
                            return AutoFixAction.DO_NOTHING;
                    }
                }
            }
    } catch (Exception exception) {
        logger.error("Exception in getNextStep:" + exception.getMessage());
        return AutoFixAction.UNABLE_TO_DETERMINE; 
    }
}
 
Example 16
Source File: DynamoSpaceConfigClient.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
private Set<String> getAuthorizedSpaces(Marker marker, SpaceAuthorizationCondition authorizedCondition) throws AmazonDynamoDBException {
  final Set<String> authorizedSpaces = new LinkedHashSet<>();

  logger.info(marker, "Getting authorized spaces by condition");

  try {
    // get the space ids which are authorized by the authorizedCondition
    if (authorizedCondition.spaceIds != null) {
      authorizedSpaces.addAll(authorizedCondition.spaceIds);
      logger.debug(marker, "Number of space IDs after addition from authorized condition space IDs: {}", authorizedSpaces.size());
    }

    // then get the owners which are authorized by the authorizedCondition
    if (authorizedCondition.ownerIds != null) {
      authorizedCondition.ownerIds.forEach(owner ->
          spaces.getIndex("owner-index").query("owner", owner).pages().forEach(p -> p.forEach(i -> {
            authorizedSpaces.add(i.getString("id"));
          }))
      );
      logger.debug(marker, "Number of space IDs after addition from owners: {}", authorizedSpaces.size());
    }

    // then get the packages which are authorized by the authorizedCondition
    if (authorizedCondition.packages != null) {
      authorizedCondition.packages.forEach(packageName ->
          packages.query("packageName", packageName).pages().forEach(p -> p.forEach(i -> {
            authorizedSpaces.add(i.getString("spaceId"));
          }))
      );
      logger.debug(marker, "Number of space IDs after addition from packages: {}", authorizedSpaces.size());
    }

    // then get the "empty" case, when no spaceIds or ownerIds os packages are provided, meaning select ALL spaces
    if (CollectionUtils.isNullOrEmpty(authorizedCondition.spaceIds)
        && CollectionUtils.isNullOrEmpty(authorizedCondition.ownerIds)
        && CollectionUtils.isNullOrEmpty(authorizedCondition.packages)) {
      spaces.scan(new ScanSpec().withProjectionExpression("id")).pages()
          .forEach(p -> p.forEach(i -> authorizedSpaces.add(i.getString("id"))));
    }
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure to get the authorized spaces", e);
    throw e;
  }

  logger.info(marker, "Returning the list of authorized spaces with size of: {}", authorizedSpaces.size());
  return authorizedSpaces;
}
 
Example 17
Source File: SourceSerializerChain.java    From aws-cloudtrail-processing-library with Apache License 2.0 3 votes vote down vote up
/**
 * Constructs a new <code>SourceSerializerChain</code> with the specified source serializers.
 * <p>
 * Use {@link SourceSerializerFactory#createSourceSerializerChain()} for default construction.
 * </p>
 * <p>
 * When source are required from this serializer, it will call each of these source serializers in the same order
 * specified here until one of them return {@link CloudTrailSource}.
 * </p>
 *
 * @param sourceSerializers A list of at least one {@link SourceSerializer} implementation instance.
 */
public SourceSerializerChain(List<? extends SourceSerializer> sourceSerializers) {
    if (CollectionUtils.isNullOrEmpty(sourceSerializers) || sourceSerializers.contains(null)) {
        throw new IllegalArgumentException("No source serializer specified or contains null serializers.");
    }
    this.sourceSerializers = new LinkedList<>(sourceSerializers);
}