List of usage examples for com.google.common.base Functions constant
public static <E> Function<Object, E> constant(@Nullable E value)
From source file:net.dmulloy2.swornguns.listeners.EntityListener.java
@EventHandler(priority = EventPriority.MONITOR) public void onProjectileHit(ProjectileHitEvent event) { Projectile proj = event.getEntity(); Bullet bullet = plugin.getBullet(proj); if (bullet != null) { // Attempt to determine which Entity (if any) we hit. // This is necessary because while the ProjectileHitEvent fires reliably, // the EntityDamageByEntityEvent only fires once per round / bullet. // This seems to work well enough, although I hope to find a better solution. Damageable hurt = null;// ww w .j a v a2s . c o m double hurtDistance = -1.0D; Location loc = proj.getLocation(); Location nLoc = new Location(null, 0, 0, 0); double radius = 2.0D; List<Entity> nearbyEntities = proj.getNearbyEntities(radius, radius, radius); for (Entity nearby : nearbyEntities) { if (nearby instanceof Damageable) { if (nearby.equals(bullet.getShooter().getPlayer())) continue; // Don't shoot ourselves nearby.getLocation(nLoc); // Exact match if (Util.coordsEqual(loc, nLoc)) { hurt = (Damageable) nearby; break; } // Find closest entity double distance = nLoc.distance(loc); if (hurt == null || distance < hurtDistance) { hurt = (Damageable) nearby; hurtDistance = distance; } } } if (hurt != null) { // Call the damage event, which will be handled below // Note: This is the same code from the EntityDamageByEntityEvent constructor, just non-deprecated EntityDamageByEntityEvent damageEvent = new EntityDamageByEntityEvent(proj, hurt, DamageCause.PROJECTILE, new EnumMap<DamageModifier, Double>(ImmutableMap.of(DamageModifier.BASE, 0.0D)), new EnumMap<DamageModifier, Function<? super Double, Double>>( ImmutableMap.of(DamageModifier.BASE, Functions.constant(-0.0)))); plugin.getServer().getPluginManager().callEvent(damageEvent); } bullet.onHit(); bullet.setDestroyNextTick(true); // ---- Effects Block block = loc.getBlock(); Material mat = block.getType(); // Try to get a non-AIR block // TODO Maybe use a BlockIterator? double i = 0.2D; while (mat == Material.AIR && i < 4.0D) { block = block.getLocation().add(proj.getVelocity().normalize().multiply(i)).getBlock(); mat = block.getType(); i += 0.2D; } if (mat != Material.AIR) { block.getLocation().getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, mat); } // Block cracking if (blockCrack && mat == Material.STONE) { BlockBreakEvent blockBreak = new BlockBreakEvent(block, bullet.getShooter().getPlayer()); plugin.getServer().getPluginManager().callEvent(blockBreak); if (!blockBreak.isCancelled()) block.setType(Material.COBBLESTONE); } // Block shattering if (blockShatter && shatterBlocks.contains(mat)) { BlockBreakEvent blockBreak = new BlockBreakEvent(block, bullet.getShooter().getPlayer()); plugin.getServer().getPluginManager().callEvent(blockBreak); if (!blockBreak.isCancelled()) block.breakNaturally(); } } }
From source file:brooklyn.entity.nosql.mongodb.MongoDBServerImpl.java
@Override protected void connectSensors() { super.connectSensors(); connectServiceUpIsRunning();//from ww w.java 2 s .c o m int port = getAttribute(MongoDBServer.PORT); HostAndPort accessibleAddress = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port); setAttribute(MONGO_SERVER_ENDPOINT, String.format("http://%s:%d", accessibleAddress.getHostText(), accessibleAddress.getPort())); int httpConsolePort = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(HTTP_PORT)) .getPort(); setAttribute(HTTP_INTERFACE_URL, String.format("http://%s:%d", accessibleAddress.getHostText(), httpConsolePort)); try { client = MongoDBClientSupport.forServer(this); } catch (UnknownHostException e) { LOG.warn("Unable to create client connection to {}, not connecting sensors: {} ", this, e.getMessage()); return; } serviceStats = FunctionFeed.builder().entity(this) .poll(new FunctionPollConfig<Object, BasicBSONObject>(STATUS_BSON).period(2, TimeUnit.SECONDS) .callable(new Callable<BasicBSONObject>() { @Override public BasicBSONObject call() throws Exception { return MongoDBServerImpl.this.getAttribute(SERVICE_UP) ? client.getServerStatus() : null; } }).onException(Functions.<BasicBSONObject>constant(null))) .build(); if (isReplicaSetMember()) { replicaSetStats = FunctionFeed.builder().entity(this) .poll(new FunctionPollConfig<Object, ReplicaSetMemberStatus>(REPLICA_SET_MEMBER_STATUS) .period(2, TimeUnit.SECONDS).callable(new Callable<ReplicaSetMemberStatus>() { /** * Calls {@link MongoDBClientSupport#getReplicaSetStatus} and * extracts <code>myState</code> from the response. * @return * The appropriate {@link brooklyn.entity.nosql.mongodb.ReplicaSetMemberStatus} * if <code>myState</code> was non-null, {@link ReplicaSetMemberStatus#UNKNOWN} otherwise. */ @Override public ReplicaSetMemberStatus call() { BasicBSONObject serverStatus = client.getReplicaSetStatus(); int state = serverStatus.getInt("myState", -1); return ReplicaSetMemberStatus.fromCode(state); } }).onException(Functions.constant(ReplicaSetMemberStatus.UNKNOWN))) .build(); } else { setAttribute(IS_PRIMARY_FOR_REPLICA_SET, false); setAttribute(IS_SECONDARY_FOR_REPLICA_SET, false); } // Take interesting details from STATUS. subscribe(this, STATUS_BSON, new SensorEventListener<BasicBSONObject>() { @Override public void onEvent(SensorEvent<BasicBSONObject> event) { BasicBSONObject map = event.getValue(); if (map != null && !map.isEmpty()) { setAttribute(UPTIME_SECONDS, map.getDouble("uptime", 0)); // Operations BasicBSONObject opcounters = (BasicBSONObject) map.get("opcounters"); setAttribute(OPCOUNTERS_INSERTS, opcounters.getLong("insert", 0)); setAttribute(OPCOUNTERS_QUERIES, opcounters.getLong("query", 0)); setAttribute(OPCOUNTERS_UPDATES, opcounters.getLong("update", 0)); setAttribute(OPCOUNTERS_DELETES, opcounters.getLong("delete", 0)); setAttribute(OPCOUNTERS_GETMORE, opcounters.getLong("getmore", 0)); setAttribute(OPCOUNTERS_COMMAND, opcounters.getLong("command", 0)); // Network stats BasicBSONObject network = (BasicBSONObject) map.get("network"); setAttribute(NETWORK_BYTES_IN, network.getLong("bytesIn", 0)); setAttribute(NETWORK_BYTES_OUT, network.getLong("bytesOut", 0)); setAttribute(NETWORK_NUM_REQUESTS, network.getLong("numRequests", 0)); // Replica set stats BasicBSONObject repl = (BasicBSONObject) map.get("repl"); if (isReplicaSetMember() && repl != null) { setAttribute(IS_PRIMARY_FOR_REPLICA_SET, repl.getBoolean("ismaster")); setAttribute(IS_SECONDARY_FOR_REPLICA_SET, repl.getBoolean("secondary")); setAttribute(REPLICA_SET_PRIMARY_ENDPOINT, repl.getString("primary")); } } } }); }
From source file:edu.uci.ics.jung.algorithms.shortestpath.DijkstraDistance.java
/** * <p>Creates an instance of <code>DijkstraShortestPath</code> for * the specified unweighted graph (that is, all weights 1) which * caches results locally./*www . ja va 2 s .c o m*/ * * @param g the graph on which distances will be calculated * @param cached specifies whether the results are to be cached */ public DijkstraDistance(Graph<V, E> g, boolean cached) { this(g, Functions.constant(1), cached); }
From source file:brooklyn.event.feed.FeedConfig.java
public F setOnFailure(T val) { return onFailure(Functions.constant(val)); }
From source file:com.palantir.atlasdb.stream.AbstractPersistentStreamStore.java
@Override public Map<Long, Sha256Hash> storeStreams(final Transaction t, final Map<Long, InputStream> streams) { if (streams.isEmpty()) { return ImmutableMap.of(); }/* w w w . j av a 2 s. c om*/ Map<Long, StreamMetadata> idsToEmptyMetadata = Maps.transformValues(streams, Functions.constant(getEmptyMetadata())); putMetadataAndHashIndexTask(t, idsToEmptyMetadata); Map<Long, StreamMetadata> idsToMetadata = Maps.transformEntries(streams, new Maps.EntryTransformer<Long, InputStream, StreamMetadata>() { @Override public StreamMetadata transformEntry(Long id, InputStream stream) { return storeBlocksAndGetFinalMetadata(t, id, stream); } }); putMetadataAndHashIndexTask(t, idsToMetadata); Map<Long, Sha256Hash> hashes = Maps.transformValues(idsToMetadata, new Function<StreamMetadata, Sha256Hash>() { @Override public Sha256Hash apply(StreamMetadata metadata) { return new Sha256Hash(metadata.getHash().toByteArray()); } }); return hashes; }
From source file:org.apache.brooklyn.core.feed.FeedConfig.java
public F setOnSuccess(T val) { return onSuccess(Functions.constant(val)); }
From source file:org.apache.brooklyn.entity.cloudfoundry.webapp.java.JavaCloudFoundryPaasWebAppImpl.java
private void connectServiceLatencySensor() { serverLatencyFeed = FunctionFeed.builder().entity(this).period(Duration.seconds(2)) .poll(new FunctionPollConfig<Double, Double>(SERVER_LATENCY).onException(Functions.constant(0.0)) .callable(new Callable<Double>() { public Double call() { Double total = getAttribute(SERVER_PROCESSING_TIME); Double num = getAttribute(SERVER_REQUESTS); return total / num; }/*from w w w . ja v a 2s .co m*/ })) .build(); }
From source file:org.apache.brooklyn.entity.php.httpd.PhpHttpdServerImpl.java
@Override protected void connectSensors() { super.connectSensors(); functionFeed = FunctionFeed.builder().entity(this).poll(new FunctionPollConfig<Object, Boolean>(SERVICE_UP) .period(500, TimeUnit.MILLISECONDS).callable(new Callable<Boolean>() { public Boolean call() throws Exception { return getDriver().isRunning(); }/*from w ww . j av a 2s . co m*/ }).onException(Functions.constant(Boolean.FALSE))).build(); String monitorUri = String.format("http://%s:%s/%s", getAttribute(Attributes.HOSTNAME), getHttpPort(), getConfig(SERVER_STATUS_URL)); httpFeed = HttpFeed.builder().entity(this).period(200).baseUri(monitorUri) .poll(new HttpPollConfig<Boolean>(SERVER_STATUS_IS_UP) .onSuccess(HttpValueFunctions.responseCodeEquals(200)) .onFailureOrException(Functions.constant(false))) .poll(new HttpPollConfig<Integer>(REQUEST_COUNT) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("Total Accesses"), cast(Integer.class)))) .poll(new HttpPollConfig<Long>(TOTAL_KBYTE) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("Total kBytes"), cast(Long.class)))) .poll(new HttpPollConfig<Double>(CPU_LOAD) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("CPULoad"), cast(Double.class)))) .poll(new HttpPollConfig<Integer>(TOTAL_PROCESSING_TIME) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("Uptime"), cast(Integer.class)))) .poll(new HttpPollConfig<Double>(REQUEST_PER_SEC) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("ReqPerSec"), cast(Double.class)))) .poll(new HttpPollConfig<Double>(BYTES_PER_SEC) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("BytesPerSec"), cast(Double.class)))) .poll(new HttpPollConfig<Double>(BYTES_PER_REQ) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("BytesPerReq"), cast(Double.class)))) .poll(new HttpPollConfig<Integer>(BUSY_WORKERS) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("BusyWorkers"), cast(Integer.class)))) .build(); }
From source file:brooklyn.entity.webapp.apache.ApacheServerImpl.java
@Override protected void connectSensors() { super.connectSensors(); functionFeed = FunctionFeed.builder().entity(this).poll(new FunctionPollConfig<Object, Boolean>(SERVICE_UP) .period(500, TimeUnit.MILLISECONDS).callable(new Callable<Boolean>() { public Boolean call() throws Exception { return getDriver().isRunning(); }// w w w . jav a2 s . com }).onException(Functions.constant(Boolean.FALSE))).build(); String monitorUri = String.format("http://%s:%s/%s", getAttribute(Attributes.HOSTNAME), getHttpPort(), getConfig(MONITOR_URL)); httpFeed = HttpFeed.builder().entity(this).period(200).baseUri(monitorUri) .poll(new HttpPollConfig<Boolean>(MONITOR_URL_UP) .onSuccess(HttpValueFunctions.responseCodeEquals(200)) .onFailureOrException(Functions.constant(false))) .poll(new HttpPollConfig<Integer>(REQUEST_COUNT) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("Total Accesses"), cast(Integer.class)))) .poll(new HttpPollConfig<Long>(TOTAL_KBYTE) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("Total kBytes"), cast(Long.class)))) .poll(new HttpPollConfig<Double>(CPU_LOAD) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("CPULoad"), cast(Double.class)))) .poll(new HttpPollConfig<Integer>(TOTAL_PROCESSING_TIME) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("Uptime"), cast(Integer.class)))) .poll(new HttpPollConfig<Double>(REQUEST_PER_SEC) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("ReqPerSec"), cast(Double.class)))) .poll(new HttpPollConfig<Double>(BYTES_PER_SEC) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("BytesPerSec"), cast(Double.class)))) .poll(new HttpPollConfig<Double>(BYTES_PER_REQ) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("BytesPerReq"), cast(Double.class)))) .poll(new HttpPollConfig<Integer>(BUSY_WORKERS) .onSuccess(Functionals.chain(HttpValueFunctions.stringContentsFunction(), parseApacheStatus("BusyWorkers"), cast(Integer.class)))) .build(); }
From source file:org.apache.brooklyn.entity.nosql.mongodb.MongoDBServerImpl.java
@Override protected void connectSensors() { super.connectSensors(); connectServiceUpIsRunning();/*from w w w .j av a 2 s . c om*/ int port = sensors().get(MongoDBServer.PORT); HostAndPort accessibleAddress = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port); sensors().set(MONGO_SERVER_ENDPOINT, String.format("%s:%d", accessibleAddress.getHostText(), accessibleAddress.getPort())); int httpConsolePort = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, sensors().get(HTTP_PORT)) .getPort(); sensors().set(HTTP_INTERFACE_URL, String.format("http://%s:%d", accessibleAddress.getHostText(), httpConsolePort)); if (clientAccessEnabled()) { try { client = MongoDBClientSupport.forServer(this); } catch (UnknownHostException e) { LOG.warn("Unable to create client connection to {}, not connecting sensors: {} ", this, e.getMessage()); return; } serviceStats = FunctionFeed.builder().entity(this) .poll(new FunctionPollConfig<Object, BasicBSONObject>(STATUS_BSON).period(2, TimeUnit.SECONDS) .callable(new Callable<BasicBSONObject>() { @Override public BasicBSONObject call() throws Exception { return MongoDBServerImpl.this.sensors().get(SERVICE_UP) ? client.getServerStatus() : null; } }).onException(Functions.<BasicBSONObject>constant(null))) .build(); if (isReplicaSetMember()) { replicaSetStats = FunctionFeed.builder().entity(this) .poll(new FunctionPollConfig<Object, ReplicaSetMemberStatus>(REPLICA_SET_MEMBER_STATUS) .period(2, TimeUnit.SECONDS).callable(new Callable<ReplicaSetMemberStatus>() { /** * Calls {@link MongoDBClientSupport#getReplicaSetStatus} and * extracts <code>myState</code> from the response. * @return * The appropriate {@link org.apache.brooklyn.entity.nosql.mongodb.ReplicaSetMemberStatus} * if <code>myState</code> was non-null, {@link ReplicaSetMemberStatus#UNKNOWN} otherwise. */ @Override public ReplicaSetMemberStatus call() { BasicBSONObject serverStatus = client.getReplicaSetStatus(); int state = serverStatus.getInt("myState", -1); return ReplicaSetMemberStatus.fromCode(state); } }).onException(Functions.constant(ReplicaSetMemberStatus.UNKNOWN)) .suppressDuplicates(true)) .build(); } else { sensors().set(IS_PRIMARY_FOR_REPLICA_SET, false); sensors().set(IS_SECONDARY_FOR_REPLICA_SET, false); } } else { LOG.info("Not monitoring " + this + " to retrieve state via client API"); } // Take interesting details from STATUS. subscriptions().subscribe(this, STATUS_BSON, new SensorEventListener<BasicBSONObject>() { @Override public void onEvent(SensorEvent<BasicBSONObject> event) { BasicBSONObject map = event.getValue(); if (map != null && !map.isEmpty()) { sensors().set(UPTIME_SECONDS, map.getDouble("uptime", 0)); // Operations BasicBSONObject opcounters = (BasicBSONObject) map.get("opcounters"); sensors().set(OPCOUNTERS_INSERTS, opcounters.getLong("insert", 0)); sensors().set(OPCOUNTERS_QUERIES, opcounters.getLong("query", 0)); sensors().set(OPCOUNTERS_UPDATES, opcounters.getLong("update", 0)); sensors().set(OPCOUNTERS_DELETES, opcounters.getLong("delete", 0)); sensors().set(OPCOUNTERS_GETMORE, opcounters.getLong("getmore", 0)); sensors().set(OPCOUNTERS_COMMAND, opcounters.getLong("command", 0)); // Network stats BasicBSONObject network = (BasicBSONObject) map.get("network"); sensors().set(NETWORK_BYTES_IN, network.getLong("bytesIn", 0)); sensors().set(NETWORK_BYTES_OUT, network.getLong("bytesOut", 0)); sensors().set(NETWORK_NUM_REQUESTS, network.getLong("numRequests", 0)); // Replica set stats BasicBSONObject repl = (BasicBSONObject) map.get("repl"); if (isReplicaSetMember() && repl != null) { sensors().set(IS_PRIMARY_FOR_REPLICA_SET, repl.getBoolean("ismaster")); sensors().set(IS_SECONDARY_FOR_REPLICA_SET, repl.getBoolean("secondary")); sensors().set(REPLICA_SET_PRIMARY_ENDPOINT, repl.getString("primary")); } } } }); }