List of usage examples for com.google.common.collect Iterables tryFind
public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate)
From source file:com.github.sevntu.checkstyle.checks.design.StaticMethodCandidateCheck.java
/** * Check types in the given frame for being acceptable in static methods. * @param frame the frame to check.//from w w w.j a v a 2 s . co m * @return true if the currently checked method * is still a static method candidate. */ private static boolean isFrameTypesAcceptable(final Frame frame) { Predicate<String> predicate = new Predicate<String>() { @Override public boolean apply(String type) { final Optional<Frame> typeFrame = findFrameByName(frame, type); return typeFrame.isPresent() && !typeFrame.get().isShouldBeChecked || findTypeVariable(frame, type); } }; final Optional<String> result = Iterables.tryFind(frame.types, predicate); return !result.isPresent(); }
From source file:org.zanata.seam.SeamAutowire.java
/** * Autowires and returns the bean instance for the provided class. * * @param beanClass// w ww. j a va2 s .co m * The bean class to create - may be an interface if useImpl * was called, otherwise must have a no-arg constructor per Seam * spec. * @return The autowired bean. */ public <T> T autowire(Class<T> beanClass) { // We could use getComponentName(Class) to simulate Seam's lookup // (by the @Named annotation on the injection point's class), but // this would just move us further away from CDI semantics. // TODO don't create multiple instances of a class // TODO abort if multiple matches Optional<?> instanceOrClass = Iterables.tryFind(namedComponents.values(), o -> beanClass.isInstance(o) || o instanceof Class && beanClass.isAssignableFrom((Class<?>) o)); if (instanceOrClass.isPresent()) { Object val = instanceOrClass.get(); if (val instanceof Class) { try { T autowired = ((Class<T>) val).newInstance(); autowire(autowired); // store it for future lookups namedComponents.put(beanClass, autowired); return autowired; } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } else { return (T) val; } } // FIXME beanImpls.values are Classes, not instances of beanClass! // try Predicates.assignableFrom // TODO what if there's more than one match?! // Optional<Class<?>> implOptional = // Iterables.tryFind(beanImpls.values(), predicate); // if (implOptional.isPresent()) { // return (T) implOptional.get(); // } String beanPath = beanClass.getSimpleName(); T autowired = create(beanClass, beanPath); autowire(autowired, beanPath); // store it for future lookups namedComponents.put(beanClass, autowired); return autowired; }
From source file:com.adobe.epubcheck.ocf.OCFChecker.java
public void runChecks() { // Create a new validation context builder from the parent context // It will be augmented with detected validation version, profile, etc. ValidationContextBuilder newContextBuilder = new ValidationContextBuilder(context); ocf.setReport(report);//from w w w. j a v a 2 s . co m if (!ocf.hasEntry(OCFData.containerEntry)) { report.message(MessageId.RSC_002, EPUBLocation.create(ocf.getName())); return; } long l = ocf.getTimeEntry(OCFData.containerEntry); if (l > 0) { Date d = new Date(l); String formattedDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(d); report.info(OCFData.containerEntry, FeatureEnum.CREATION_DATE, formattedDate); } OCFData containerData = ocf.getOcfData(); // retrieve the paths of root files List<String> opfPaths = containerData.getEntries(OPFData.OPF_MIME_TYPE); if (opfPaths == null || opfPaths.isEmpty()) { report.message(MessageId.RSC_003, EPUBLocation.create(OCFData.containerEntry)); return; } else if (opfPaths.size() > 0) { if (opfPaths.size() > 1) { report.info(null, FeatureEnum.EPUB_RENDITIONS_COUNT, Integer.toString(opfPaths.size())); } // test every element for empty or missing @full-path attribute // bugfix for issue 236 / issue 95 int rootfileErrorCounter = 0; for (String opfPath : opfPaths) { if (opfPath == null) { ++rootfileErrorCounter; report.message(MessageId.OPF_016, EPUBLocation.create(OCFData.containerEntry)); } else if (opfPath.isEmpty()) { ++rootfileErrorCounter; report.message(MessageId.OPF_017, EPUBLocation.create(OCFData.containerEntry)); } else if (!ocf.hasEntry(opfPath)) { report.message(MessageId.OPF_002, EPUBLocation.create(OCFData.containerEntry), opfPath); return; } } if (rootfileErrorCounter == opfPaths.size()) { // end validation at this point when @full-path attribute is missing in // container.xml // otherwise, tons of errors would be thrown // ("XYZ exists in the zip file, but is not declared in the OPF file") return; } } // // Compute the validation version // ------------------------------ // Detect the version of the first root file // and compare with the asked version (if set) EPUBVersion detectedVersion = null; final EPUBVersion validationVersion; OPFData opfData = ocf.getOpfData().get(opfPaths.get(0)); if (opfData == null) return;// The error must have been reported during // parsing detectedVersion = opfData.getVersion(); report.info(null, FeatureEnum.FORMAT_VERSION, detectedVersion.toString()); assert (detectedVersion != null); if (context.version != EPUBVersion.Unknown && context.version != detectedVersion) { report.message(MessageId.PKG_001, EPUBLocation.create(opfPaths.get(0)), context.version, detectedVersion); validationVersion = context.version; } else { validationVersion = detectedVersion; } newContextBuilder.version(validationVersion); // // Compute the validation profile // ------------------------------ EPUBProfile validationProfile = context.profile; // FIXME get profile from metadata.xml if available if (validationVersion == EPUBVersion.VERSION_2 && validationProfile != EPUBProfile.DEFAULT) { // Validation profile is unsupported for EPUB 2.0 report.message(MessageId.PKG_023, EPUBLocation.create(opfPaths.get(0))); } else if (validationVersion == EPUBVersion.VERSION_3) { // Override the given validation profile depending on the primary OPF // dc:type validationProfile = EPUBProfile.makeOPFCompatible(validationProfile, opfData, opfPaths.get(0), report); } newContextBuilder.profile(validationProfile); // // Check multiple renditions // ------------------------------ // EPUB 2.0 says there SHOULD be only one OPS rendition if (validationVersion == EPUBVersion.VERSION_2 && opfPaths.size() > 1) { report.message(MessageId.PKG_013, EPUBLocation.create(OCFData.containerEntry)); } // EPUB 3.0 Multiple Renditions recommends the presence of a metadata file if (validationVersion == EPUBVersion.VERSION_3 && opfPaths.size() > 1) { newContextBuilder.addProperty(EpubCheckVocab.VOCAB.get(EpubCheckVocab.PROPERTIES.MULTIPLE_RENDITION)); if (!ocf.hasEntry(OCFData.metadataEntry)) { report.message(MessageId.RSC_019, EPUBLocation.create(ocf.getName())); } if (containerData.getMapping().isPresent()) { validateRenditionMapping(new ValidationContextBuilder(newContextBuilder.build()) .mimetype("application/xhtml+xml").path(containerData.getMapping().get()) .addProperty(EpubCheckVocab.VOCAB.get(EpubCheckVocab.PROPERTIES.RENDITION_MAPPING)) .build()); } } // // Check the mimetype file // ------------------------------ // InputStream mimetype = null; try { mimetype = ocf.getInputStream("mimetype"); StringBuilder sb = new StringBuilder(2048); if (ocf.hasEntry("mimetype") && !CheckUtil.checkTrailingSpaces(mimetype, validationVersion, sb)) { report.message(MessageId.PKG_007, EPUBLocation.create("mimetype")); } if (sb.length() != 0) { report.info(null, FeatureEnum.FORMAT_NAME, sb.toString().trim()); } } catch (IOException ignored) { // missing file will be reported later } finally { try { if (mimetype != null) { mimetype.close(); } } catch (IOException ignored) { // eat it } } // // Check the META-INF files // ------------------------------ // validateMetaFiles(newContextBuilder.mimetype("xml").build()); // // Check each OPF (i.e. Rendition) // ------------------------------- // // Validate each OPF and keep a reference of the OPFHandler List<OPFHandler> opfHandlers = new LinkedList<OPFHandler>(); for (String opfPath : opfPaths) { OPFChecker opfChecker = OPFCheckerFactory.getInstance().newInstance(newContextBuilder.path(opfPath) .mimetype(OPFData.OPF_MIME_TYPE).featureReport(new FeatureReport()).build()); opfChecker.runChecks(); opfHandlers.add(opfChecker.getOPFHandler()); } // // Check container integrity // ------------------------------- // try { Set<String> entriesSet = new HashSet<String>(); Set<String> normalizedEntriesSet = new HashSet<String>(); for (final String entry : ocf.getFileEntries()) { if (!entriesSet.add(entry.toLowerCase(Locale.ENGLISH))) { report.message(MessageId.OPF_060, EPUBLocation.create(ocf.getPackagePath()), entry); } else if (!normalizedEntriesSet.add(Normalizer.normalize(entry, Form.NFC))) { report.message(MessageId.OPF_061, EPUBLocation.create(ocf.getPackagePath()), entry); } ocf.reportMetadata(entry, report); // if the entry is not in the whitelist (META-INF/* + mimetype) // and not declared in (one of) the OPF document(s) if (!entry.startsWith("META-INF/") && !entry.startsWith("META-INF\\") && !entry.equals("mimetype") && !containerData.getEntries().contains(entry) && !entry.equals(containerData.getMapping().orNull()) && !Iterables.tryFind(opfHandlers, new Predicate<OPFHandler>() { @Override public boolean apply(OPFHandler opfHandler) { // found if declared as an OPF item // or in an EPUB 3 link element return opfHandler.getItemByPath(entry).isPresent() || (validationVersion == EPUBVersion.VERSION_3 && ((OPFHandler30) opfHandler).getLinkedResources().hasPath(entry)); } }).isPresent()) { report.message(MessageId.OPF_003, EPUBLocation.create(ocf.getName()), entry); } OCFFilenameChecker.checkCompatiblyEscaped(entry, report, validationVersion); } for (String directory : ocf.getDirectoryEntries()) { boolean hasContents = false; for (String file : ocf.getFileEntries()) { if (file.startsWith(directory)) { hasContents = true; break; } } if (!hasContents) { report.message(MessageId.PKG_014, EPUBLocation.create(ocf.getName()), directory); } } } catch (IOException e) { report.message(MessageId.PKG_015, EPUBLocation.create(ocf.getName()), e.getMessage()); } }
From source file:com.smoketurner.notification.application.store.NotificationStore.java
/** * Return the parent notification that matches the given ID or is the parent * of a child notification./* ww w. j a v a 2 s. c om*/ * * @param notifications * Notifications to search through * @param id * Notification ID to find * @return the notification */ public static Optional<Notification> tryFind(@Nonnull final Iterable<Notification> notifications, final long id) { final com.google.common.base.Optional<Notification> result = Iterables.tryFind(notifications, notification -> { // first check that the ID matches final Optional<Long> notificationId = notification.getId(); if (!notificationId.isPresent()) { return false; } else if (notificationId.get() == id) { return true; } // Check to see if the notification is included in any // rolled up notifications. This code should not be hit as // tryFind() is called prior to the rollups happening, but // we include this here for completeness. final Collection<Notification> children = notification.getNotifications() .orElse(Collections.emptyList()); if (children.isEmpty()) { return false; } return (tryFind(children, id)).isPresent(); }); if (result.isPresent()) { return Optional.of(result.get()); } return Optional.empty(); }
From source file:com.eucalyptus.compute.vpc.VpcManager.java
public AssociateRouteTableResponseType associateRouteTable(final AssociateRouteTableType request) throws EucalyptusCloudException { final AssociateRouteTableResponseType reply = request.getReply(); final Context ctx = Contexts.lookup(); final AccountFullName accountFullName = ctx.getUserFullName().asAccountFullName(); final String routeTableId = Identifier.rtb.normalize(request.getRouteTableId()); final String subnetId = Identifier.subnet.normalize(request.getSubnetId()); try {/* w ww .ja v a 2 s. c om*/ final RouteTable routeTable = routeTables.updateByExample( RouteTable.exampleWithName(accountFullName, routeTableId), accountFullName, request.getRouteTableId(), new Callback<RouteTable>() { @Override public void fire(final RouteTable routeTable) { if (RestrictedTypes.filterPrivileged().apply(routeTable)) try { final Subnet subnet = subnets.lookupByName(accountFullName, subnetId, Functions.<Subnet>identity()); if (!subnet.getVpc().getDisplayName() .equals(routeTable.getVpc().getDisplayName())) { throw Exceptions .toUndeclared(new ClientComputeException("InvalidParameterValue", "Route table " + routeTableId + " and subnet " + subnetId + " belong to different networks")); } if (!Iterables .tryFind(routeTable.getRouteTableAssociations(), CollectionUtils.propertyPredicate(subnetId, RouteTables.AssociationFilterStringFunctions.SUBNET_ID)) .isPresent()) { routeTable.associate(subnet); } } catch (VpcMetadataNotFoundException e) { throw Exceptions .toUndeclared(new ClientComputeException("InvalidSubnetID.NotFound", "Subnet (" + request.getSubnetId() + ") not found")); } catch (Exception e) { throw Exceptions.toUndeclared(e); } else { throw Exceptions.toUndeclared(new ClientUnauthorizedComputeException( "Not authorized to associate route table")); } } }); final RouteTableAssociation association = Iterables.find(routeTable.getRouteTableAssociations(), CollectionUtils.propertyPredicate(subnetId, RouteTables.AssociationFilterStringFunctions.SUBNET_ID)); reply.setAssociationId(association.getAssociationId()); invalidate(subnetId); } catch (VpcMetadataNotFoundException e) { throw new ClientComputeException("InvalidRouteTableID.NotFound", "Route table not found '" + request.getRouteTableId() + "'"); } catch (Exception e) { if (Exceptions.isCausedBy(e, ConstraintViolationException.class)) { throw new ClientComputeException("InvalidParameterValue", "Subnet " + subnetId + " already associated."); } throw handleException(e); } return reply; }
From source file:org.opentestsystem.authoring.testitembank.service.impl.ZipXMLServiceImpl.java
@Override public ApipManifest consolidateManifests(final String targetIdentifier, final List<ApipManifest> manifests) { final ApipManifest consolidatedManifest = new ApipManifest(); consolidatedManifest.setIdentifier(targetIdentifier); consolidatedManifest.setResources(new ArrayList<ApipManifestResource>()); for (final ApipManifest manifest : manifests) { for (final ApipManifestResource resource : manifest.getResources()) { final boolean containsIdentifier = Iterables.tryFind(consolidatedManifest.getResources(), APIP_RESOURCE_IDENTIFIER_FILTER.getInstance(resource.getIdentifier())).isPresent(); if (!containsIdentifier) { consolidatedManifest.getResources().add(resource); }//from w w w .j a v a 2 s . c o m } } Collections.sort(consolidatedManifest.getResources(), ApipManifestResource.BY_IDENTIFIER_ORDERING); return consolidatedManifest; }
From source file:brooklyn.entity.monitoring.zabbix.ZabbixFeed.java
@Override protected void preStart() { final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER); final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR); final Integer groupId = getConfig(GROUP_ID); final Integer templateId = getConfig(TEMPLATE_ID); final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS); log.info("starting zabbix feed for {}", entity); // TODO if supplier returns null, we may wish to defer initialization until url available? // TODO for https should we really trust all? final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll() .clientConnectionManager(new ThreadSafeClientConnManager()) .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build(); // Registration job, calls Zabbix host.create API final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() { @Override// ww w .ja va 2 s. c o m public HttpToolResponse call() throws Exception { if (!registered.get()) { // Find the first machine, if available Optional<Location> location = Iterables.tryFind(entity.getLocations(), Predicates.instanceOf(MachineLocation.class)); if (!location.isPresent()) { return null; // Do nothing until location is present } MachineLocation machine = (MachineLocation) location.get(); String host = uniqueHostnameGenerator.apply(entity); // Select address and port using port-forwarding if available String address = entity.getAttribute(Attributes.ADDRESS); Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT); if (machine instanceof SupportsPortForwarding) { Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR); HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management, port); address = forwarded.getHostText(); port = forwarded.getPort(); } // Fill in the JSON template and POST it byte[] body = JSON_HOST_CREATE .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{host}}", host).replace("{{ip}}", address) .replace("{{port}}", Integer.toString(port)) .replace("{{groupId}}", Integer.toString(groupId)) .replace("{{templateId}}", Integer.toString(templateId)) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } return null; } }; // The handler for the registration job PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() { @Override public void onSuccess(HttpToolResponse val) { if (registered.get() || val == null) { return; // Skip if we are registered already or no data from job } JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject(); if (response.has("error")) { // Parse the JSON error object and log the message JsonObject error = response.get("error").getAsJsonObject(); String message = error.get("message").getAsString(); String data = error.get("data").getAsString(); log.warn("zabbix failed registering host - {}: {}", message, data); } else if (response.has("result")) { // Parse the JSON result object and save the hostId JsonObject result = response.get("result").getAsJsonObject(); String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString(); // Update the registered status if not set if (registered.compareAndSet(false, true)) { entity.setAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId); log.info("zabbix registered host as id {}", hostId); } } else { throw new IllegalStateException(String .format("zabbix host registration returned invalid result: %s", response.toString())); } } @Override public boolean checkSuccess(HttpToolResponse val) { return (val.getResponseCode() == 200); } @Override public void onFailure(HttpToolResponse val) { log.warn("zabbix sever returned failure code: {}", val.getResponseCode()); } @Override public void onException(Exception exception) { log.warn("zabbix exception registering host", exception); } @Override public String toString() { return super.toString() + "[" + getDescription() + "]"; } @Override public String getDescription() { return "Zabbix rest poll"; } }; // Schedule registration attempt once per second getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable // Create a polling job for each Zabbix metric for (final ZabbixPollConfig<?> config : polls) { Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() { @Override public HttpToolResponse call() throws Exception { if (registered.get()) { if (log.isTraceEnabled()) log.trace("zabbix polling {} for {}", entity, config); byte[] body = JSON_ITEM_GET .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID)) .replace("{{itemKey}}", config.getItemKey()) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } else { throw new IllegalStateException("zabbix agent not yet registered"); } } }; // Schedule the Zabbix polling job AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>( config, entity, this); long minPeriod = Integer.MAX_VALUE; // TODO make configurable if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod()); getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod); } }
From source file:brooklyn.networking.sdn.mesos.CalicoModuleImpl.java
@Override public void deallocateNetwork(VirtualNetwork network) { String networkId = network.sensors().get(VirtualNetwork.NETWORK_ID); Optional<Entity> found = Iterables.tryFind(sensors().get(SDN_APPLICATIONS).getMembers(), EntityPredicates.attributeEqualTo(VirtualNetwork.NETWORK_ID, networkId)); if (found.isPresent()) { Entity group = found.get(); sensors().get(SDN_APPLICATIONS).removeMember(group); sensors().get(SDN_APPLICATIONS).removeChild(group); Entities.unmanage(group);/*from ww w .j a va2 s . c o m*/ } else { LOG.warn("Cannot find group containing {} network entities", networkId); } sensors().get(SDN_NETWORKS).removeMember(network); // TODO actually deprovision the network if possible? }
From source file:org.apache.brooklyn.entity.monitoring.zabbix.ZabbixFeed.java
@Override protected void preStart() { final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER); final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR); final Integer groupId = getConfig(GROUP_ID); final Integer templateId = getConfig(TEMPLATE_ID); final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS); log.info("starting zabbix feed for {}", entity); // TODO if supplier returns null, we may wish to defer initialization until url available? // TODO for https should we really trust all? final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll() .clientConnectionManager(new ThreadSafeClientConnManager()) .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build(); // Registration job, calls Zabbix host.create API final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() { @Override// w w w.j av a2s. c om public HttpToolResponse call() throws Exception { if (!registered.get()) { // Find the first machine, if available Optional<Location> location = Iterables.tryFind(entity.getLocations(), Predicates.instanceOf(MachineLocation.class)); if (!location.isPresent()) { return null; // Do nothing until location is present } MachineLocation machine = (MachineLocation) location.get(); String host = uniqueHostnameGenerator.apply(entity); // Select address and port using port-forwarding if available String address = entity.getAttribute(Attributes.ADDRESS); Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT); if (machine instanceof SupportsPortForwarding) { Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR); HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management, port); address = forwarded.getHostText(); port = forwarded.getPort(); } // Fill in the JSON template and POST it byte[] body = JSON_HOST_CREATE .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{host}}", host).replace("{{ip}}", address) .replace("{{port}}", Integer.toString(port)) .replace("{{groupId}}", Integer.toString(groupId)) .replace("{{templateId}}", Integer.toString(templateId)) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } return null; } }; // The handler for the registration job PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() { @Override public void onSuccess(HttpToolResponse val) { if (registered.get() || val == null) { return; // Skip if we are registered already or no data from job } JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject(); if (response.has("error")) { // Parse the JSON error object and log the message JsonObject error = response.get("error").getAsJsonObject(); String message = error.get("message").getAsString(); String data = error.get("data").getAsString(); log.warn("zabbix failed registering host - {}: {}", message, data); } else if (response.has("result")) { // Parse the JSON result object and save the hostId JsonObject result = response.get("result").getAsJsonObject(); String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString(); // Update the registered status if not set if (registered.compareAndSet(false, true)) { entity.sensors().set(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId); log.info("zabbix registered host as id {}", hostId); } } else { throw new IllegalStateException(String .format("zabbix host registration returned invalid result: %s", response.toString())); } } @Override public boolean checkSuccess(HttpToolResponse val) { return (val.getResponseCode() == 200); } @Override public void onFailure(HttpToolResponse val) { log.warn("zabbix sever returned failure code: {}", val.getResponseCode()); } @Override public void onException(Exception exception) { log.warn("zabbix exception registering host", exception); } @Override public String toString() { return super.toString() + "[" + getDescription() + "]"; } @Override public String getDescription() { return "Zabbix rest poll"; } }; // Schedule registration attempt once per second getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable // Create a polling job for each Zabbix metric for (final ZabbixPollConfig<?> config : polls) { Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() { @Override public HttpToolResponse call() throws Exception { if (registered.get()) { if (log.isTraceEnabled()) log.trace("zabbix polling {} for {}", entity, config); byte[] body = JSON_ITEM_GET .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID)) .replace("{{itemKey}}", config.getItemKey()) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } else { throw new IllegalStateException("zabbix agent not yet registered"); } } }; // Schedule the Zabbix polling job AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>( config, entity, this); long minPeriod = Integer.MAX_VALUE; // TODO make configurable if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod()); getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod); } }
From source file:brooklyn.location.jclouds.networking.JcloudsLocationSecurityGroupCustomizer.java
/** * Loads the security group to be shared between nodes in the same application in the * given Location. If no such security group exists it is created. * * @param location The location in which the security group will be found * @param securityApi The API to use to list and create security groups * @return the security group to share between instances in the given location in this application *//*from ww w . ja va 2 s.c om*/ private SecurityGroup getOrCreateSharedSecurityGroup(Location location, SecurityGroupExtension securityApi) { final String groupName = getNameForSharedSecurityGroup(); // Could sort-and-search if straight search is too expensive Optional<SecurityGroup> shared = Iterables.tryFind(securityApi.listSecurityGroupsInLocation(location), new Predicate<SecurityGroup>() { @Override public boolean apply(final SecurityGroup input) { // endsWith because Jclouds prepends 'jclouds#' to security group names. return input.getName().endsWith(groupName); } }); if (shared.isPresent()) { LOG.info("Found existing shared security group in {} for app {}: {}", new Object[] { location, applicationId, groupName }); return shared.get(); } else { LOG.info("Creating new shared security group in {} for app {}: {}", new Object[] { location, applicationId, groupName }); return createBaseSecurityGroupInLocation(groupName, location, securityApi); } }