com.codahale.metrics.Timer.Context Java Examples

The following examples show how to use com.codahale.metrics.Timer.Context. 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: StatementExecutor.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
/**
 * 执行SQL查询.
 * 
 * @return 结果集列表
 */
public List<ResultSet> executeQuery() {
    Context context = MetricsContext.start("ShardingStatement-executeQuery");
    List<ResultSet> result;
    try {
        result = executorEngine.executeStatement(sqlType, statementUnits, new ExecuteCallback<ResultSet>() {
            
            @Override
            public ResultSet execute(final BaseStatementUnit baseStatementUnit) throws Exception {
                return baseStatementUnit.getStatement().executeQuery(baseStatementUnit.getSqlExecutionUnit().getSql());
            }
        });
    } finally {
        MetricsContext.stop(context);
    }
    return result;
}
 
Example #2
Source File: PersonDAOImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public Login findLogin(String username) {
   Row row;
   try(Context ctxt = findLoginTimer.time()) {
      row = findLoginRowByUsername(username);
   }

   if(row == null) {
      return null;
   }

   Login login = new Login();
   login.setPassword(row.getString(LoginColumns.PASSWORD));
   login.setPasswordSalt(row.getString(LoginColumns.PASSWORD_SALT));
   login.setUserId(row.getUUID(LoginColumns.USERID));
   login.setUsername(username);
   login.setLastPasswordChange(row.getTimestamp(LoginColumns.LAST_PASS_CHANGE));
   return login;
}
 
Example #3
Source File: ImportRunner.java    From newts with Apache License 2.0 6 votes vote down vote up
private Observable<Boolean> directPoster(Observable<List<Sample>> samples, MetricRegistry metrics) {

        final SampleRepository repository = repository();
        final Timer timer = metrics.timer("writes");
        final Meter completions = metrics.meter("samples-completed");
        

        Func1<List<Sample>, Boolean> insert = new Func1<List<Sample>, Boolean>() {

            @Override
            public Boolean call(List<Sample> s) {
                int sz = s.size();
                try (Context timerCtx = timer.time()) {
                    repository.insert(s);
                    return true;
                } finally {
                    completions.mark(sz);
                }
            }
        };
        
        
        return (m_threadCount == 1 ? samples.map(insert) : parMap(samples, metrics, insert)).all(Functions.<Boolean>identity());
        
        
    }
 
Example #4
Source File: PersonDAOImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public Person deletePinAtPlace(Person person, UUID placeId)
{
   Preconditions.checkArgument(person != null, "person cannot be null");
   Preconditions.checkArgument(placeId != null, "placeId cannot be null");

   try (Context timerContext = updatePinAtPlaceTimer.time())
   {
      Date modified = new Date();

      boolean isCurrentPlace = Objects.equal(person.getCurrPlace(), placeId);

      Statement deleteStatement = isCurrentPlace ?
         new BoundStatement(updatePinAtPlaceAndPin2).bind(modified, placeId.toString(), null, null, person.getId()) :
         new BoundStatement(updatePinAtPlace).bind(modified, placeId.toString(), null, person.getId());

      session.execute(deleteStatement);

      Person copy = person.copy();
      copy.setModified(modified);
      copy.clearPin(placeId);

      return copy;
   }
}
 
Example #5
Source File: PreparedStatementExecutor.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
/**
 * 执行SQL请求.
 * 
 * @return true表示执行DQL, false表示执行的DML
 */
public boolean execute() {
    Context context = MetricsContext.start("ShardingPreparedStatement-execute");
    try {
        List<Boolean> result = executorEngine.executePreparedStatement(sqlType, preparedStatementUnits, parameters, new ExecuteCallback<Boolean>() {
            
            @Override
            public Boolean execute(final BaseStatementUnit baseStatementUnit) throws Exception {
                return ((PreparedStatement) baseStatementUnit.getStatement()).execute();
            }
        });
        if (null == result || result.isEmpty() || null == result.get(0)) {
            return false;
        }
        return result.get(0);
    } finally {
        MetricsContext.stop(context);
    }
}
 
Example #6
Source File: BaseCassandraCRUDDao.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void delete(T entity) {
   if(entity == null || entity.getId() == null) {
      return;
   }

   Statement statement = new BoundStatement(delete).bind(entity.getId());

   List<Statement> indexDeletes = prepareIndexDeletes(entity);
   if(!indexDeletes.isEmpty()) {
      BatchStatement batch = new BatchStatement();
      batch.add(statement);
      addToBatch(batch, indexDeletes);
      statement = batch;
   }
   try(Context ctxt = deleteTimer.time()) {
 	  session.execute(statement);
   }
}
 
Example #7
Source File: PreparedStatementExecutor.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
/**
 * 执行SQL查询.
 * 
 * @return 结果集列表
 */
public List<ResultSet> executeQuery() {
    Context context = MetricsContext.start("ShardingPreparedStatement-executeQuery");
    List<ResultSet> result;
    try {
        result = executorEngine.executePreparedStatement(sqlType, preparedStatementUnits, parameters, new ExecuteCallback<ResultSet>() {
            
            @Override
            public ResultSet execute(final BaseStatementUnit baseStatementUnit) throws Exception {
                return ((PreparedStatement) baseStatementUnit.getStatement()).executeQuery();
            }
        });
    } finally {
        MetricsContext.stop(context);
    }
    return result;
}
 
Example #8
Source File: PreferencesDAOImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> findById(UUID personId, UUID placeId)
{
   BoundStatement boundStatement = new BoundStatement(findByIdStatement)
      .setUUID(Cols.PERSON_ID, personId)
      .setUUID(Cols.PLACE_ID, placeId);

   Row row;

   try (Context context = findByIdTimer.time())
   {
      row = session.execute(boundStatement).one();
   }

   if (row == null)
   {
      return null;
   }

   Map<String, String> prefsEncoded = row.getMap(Cols.PREFS, String.class, String.class);

   return decodeAttributesFromJson(prefsEncoded, Preferences.TYPE);
}
 
Example #9
Source File: ShardingConnection.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
/**
     * 根据数据源名称获取全部数据库连接.
     *
     * @param dataSourceName 数据源名称
     * @return 数据库连接集合
     * @throws SQLException SQL异常
     */
    public Collection<Connection> getConnectionForDDL(final String dataSourceName) throws SQLException {
        final Context metricsContext = MetricsContext.start(Joiner.on("-").join("ShardingConnection-getConnectionForDDL", dataSourceName));
//        从分片规则的数据库分片规则中获取数据源
        DataSource dataSource = shardingContext.getShardingRule().getDataSourceRule().getDataSource(dataSourceName);
        Preconditions.checkState(null != dataSource, "Missing the rule of %s in DataSourceRule", dataSourceName);
        Collection<DataSource> dataSources = new LinkedList<>();
        if (dataSource instanceof MasterSlaveDataSource) {
            dataSources.add(((MasterSlaveDataSource) dataSource).getMasterDataSource());
            dataSources.addAll(((MasterSlaveDataSource) dataSource).getSlaveDataSources());
        } else {
            dataSources.add(dataSource);
        }
        Collection<Connection> result = new LinkedList<>();
        for (DataSource each : dataSources) {
//            根据数据源获取数据库连接
            Connection connection = each.getConnection();
            replayMethodsInvocation(connection);//重新调用调用过的方法动作
            result.add(connection);
        }
        MetricsContext.stop(metricsContext);
        return result;
    }
 
Example #10
Source File: FrontierManager.java    From ache with Apache License 2.0 6 votes vote down vote up
public LinkRelevance nextURL(boolean asyncLoad) throws FrontierPersistentException, DataNotFoundException {
    Context timerContext = selectTimer.time();
    try {
        LinkRelevance link = scheduler.nextLink(asyncLoad);
        if (link == null) {
            if (scheduler.hasPendingLinks()) {
                throw new DataNotFoundException(false, "No links available for selection right now.");
            } else {
                throw new DataNotFoundException(true, "Frontier run out of links.");
            }
        }
        frontier.delete(link);

        schedulerLog.printf("%d\t%.5f\t%s\n", System.currentTimeMillis(),
                            link.getRelevance(), link.getURL().toString());
        return link;
    } finally {
        timerContext.stop();
    }
}
 
Example #11
Source File: BaseCassandraCRUDDao.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public T findById(I id) {
   if(id == null) {
      return null;
   }

   BoundStatement boundStatement = new BoundStatement(findById);

   Row row;
 	try(Context ctxt = findByIdTimer.time()) {
 		row = session.execute(boundStatement.bind(id)).one();
 	}

   if(row == null) {
      return null;
   }

   return buildEntity(row);
}
 
Example #12
Source File: CassandraSchedulerModelDao.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void updateAttributes(Address address, Map<String, Object> attributes) {
   if(attributes == null || attributes.isEmpty()) {
      return;
   }

   try(Context cx = SchedulerMetrics.updateAttributesTimer.time()) {
      updateAttributes(address, new Date(), attributes.keySet(), (name) -> attributes.get(name));
   }
}
 
Example #13
Source File: PlaceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean getUpdateFlag(UUID placeId) {
   Preconditions.checkArgument(placeId != null, "The place id cannot be null");
   BoundStatement statement = new BoundStatement(getUpdateFlag);
   ResultSet resultSet;
   try(Context ctxt = getUpdateFlagTimer.time()) {
      resultSet = session.execute(statement.bind(placeId));
   }
   Row row = resultSet.one();
   return row.getBool(UPDATEFLAG);
}
 
Example #14
Source File: PreferencesDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(UUID personId, UUID placeId)
{
   BoundStatement boundStatement = new BoundStatement(deleteStatement)
      .setUUID(Cols.PERSON_ID, personId)
      .setUUID(Cols.PLACE_ID, placeId);

   try (Context context = deleteTimer.time())
   {
      session.execute(boundStatement);
   }
}
 
Example #15
Source File: AbstractApiServlet.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected final void doPut(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  log(req);

  Context context = getTimer(req).time();
  try {
    put(req, resp);
  } catch (ServletException | IOException e) {
    logger.warn("put error", e);
  } finally {
    context.close();
  }
}
 
Example #16
Source File: DeviceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public DeviceDriverStateHolder loadDriverState(Device device) {
   Preconditions.checkNotNull(device, "device cannot be null");
   Preconditions.checkNotNull(device.getId(), "device must have an id");

   BoundStatement bound = new BoundStatement(loadState);
   Row r;
   try(Context ctxt = loadDriverStateTimer.time()) {
      r = session.execute(bound.bind(device.getId())).one();
   }

   if(r == null) {
      return null;
   }

   Map<String,String> encoded = r.getMap(NonEntityColumns.ATTRIBUTES, String.class, String.class);
   AttributeMap attributes = AttributeMap.newMap();
   for(Map.Entry<String, String> entry: encoded.entrySet()) {
      AttributeKey<?> key = key(entry.getKey());
      if(key == null) {
         continue;
      }
      Object value = deserialize(key, entry.getValue());
      // this shouldn't be necessary...
      attributes.add(key.coerceToValue(value));
   }


   Map<String,Object> variables = new HashMap<>();
   ByteBuffer buf = r.getBytes(NonEntityColumns.VARIABLES);
   if (buf != null) {
      variables = SerializationUtils.deserialize(Bytes.getArray(buf));
   }

   return new DeviceDriverStateHolder(attributes, variables);
}
 
Example #17
Source File: PlaceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public PagedResults<Place> listPlaces(PlaceQuery query) {
	   BoundStatement bs = null;
	   if (query.getToken() != null) {
		   bs = listPagedContinue.bind(UUID.fromString(query.getToken()), query.getLimit() + 1);
	   } else {
		   bs = listPagedNull.bind( );
	   }
	   try(Context ctxt = listPlacesTimer.time()) {
           return doList(bs, query.getLimit());
        }
}
 
Example #18
Source File: PersonDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private List<Person> listByPlaceId(UUID placeId)
{
   try (Context timerContext = listByPlaceIdTimer.time())
   {
      Set<UUID> personIds = personPlaceAssocDAO.findPersonIdsByPlace(placeId);

      Function<ResultSet, Person> entityTransform =
         resultSet -> buildEntity(resultSet.one());

      return listByIdsAsync(personIds, entityTransform, asyncTimeoutMs);
   }
}
 
Example #19
Source File: PersonDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Person updatePinAtPlace(Person person, UUID placeId, String newPin) throws PinNotUniqueAtPlaceException
{
   Preconditions.checkArgument(person != null, "person cannot be null");
   Preconditions.checkArgument(placeId != null, "placeId cannot be null");
   Preconditions.checkArgument(StringUtils.isNotBlank(newPin), "newPin cannot be blank");

   try (Context timerContext = updatePinAtPlaceTimer.time())
   {
      List<Person> personsAtPlace = listByPlaceId(placeId);

      verifyNewPinUniqueness(personsAtPlace, placeId, newPin);

      Date modified = new Date();

      String encryptedNewPin = aes.encrypt(person.getId().toString(), newPin);

      boolean isCurrentPlace = Objects.equal(person.getCurrPlace(), placeId);

      Statement updateStatement = isCurrentPlace ?
         new BoundStatement(updatePinAtPlaceAndPin2)
            .bind(modified, placeId.toString(), encryptedNewPin, encryptedNewPin, person.getId()) :
         new BoundStatement(updatePinAtPlace)
            .bind(modified, placeId.toString(), encryptedNewPin, person.getId());

      session.execute(updateStatement);

      Person copy = person.copy();
      copy.setModified(modified);
      copy.setPinAtPlace(placeId, newPin);

      return copy;
   }
}
 
Example #20
Source File: InvitationDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Invitation find(String code) {
   Preconditions.checkNotNull(code, "code is required");

   try(Context timer = findTimer.time()) {
      BoundStatement stmt = new BoundStatement(select);
      stmt.setString(Column.code.name(), StringUtils.lowerCase(code));
      return build(session.execute(stmt).one());
   }
}
 
Example #21
Source File: PersonDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Person findByEmail(String email) {
   if(StringUtils.isBlank(email)) {
      return null;
   }
   try(Context ctxt = findByEmailTimer.time()) {
 	  UUID personId = findIdByEmail(email);
       return personId == null ? null : findById(personId);
   }
}
 
Example #22
Source File: DeviceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public ModelEntity modelById(UUID id) {
   if(id == null) {
      return null;
   }
   try(Context ctxt = modelByIdTimer.time()) {
      BoundStatement stmt = new BoundStatement(findById).bind(id);
      Row r = session.execute(stmt).one();
      if(r == null) {
         return null;
      }
      return toModel(r, true);
   }
}
 
Example #23
Source File: MobileDeviceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(MobileDevice device) {
   if (device != null){
      try(Context ctxt = deleteTimer.time()){
         BatchStatement batch = new BatchStatement();
         batch.add(new BoundStatement(deleteStatement).bind(device.getPersonId(), device.getDeviceIndex()));
         addTokenIndexDeleteToBatch(batch, device);
         session.execute(batch);
      }
   }
}
 
Example #24
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public <T, U, R> R timed(@NotNull BiFunction<T, U, R> bf, T arg1, U arg2, @NotNull String timerName) {
    final Context context = getNamedTimer(timerName).time();
    try {
        return bf.apply(arg1, arg2);
    }
    finally {
        context.stop();
    }

}
 
Example #25
Source File: CassandraActivityDao.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void append(ActivityEvent event) {
	try(Context c = activitySystemLogTimer.time()) {
		Date timeBucket = bucket(event.getTimestamp());
		BoundStatement bs = upsert.bind(
				event.getTimestamp().getTime() * 1000,
				event.getActiveDevices(),
				event.getInactivateDevices(),
				event.getPlaceId(),
				timeBucket
		);
		session.execute( bs );
	}
}
 
Example #26
Source File: HubRegistrationDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Stream<HubRegistration> streamAll() {
	try(Context ctxt = streamAllTimer.time()) {
		Iterator<Row> rows = session.execute(new BoundStatement(streamAll)).iterator();
		return CassandraQueryExecutor.stream(rows, (row) -> buildEntity(row));			
	}
}
 
Example #27
Source File: CassandraSchedulerModelDao.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(ModelEntity model) {
   try(Context cx = SchedulerMetrics.deleteTimer.time()) {
      UUID modelId = UUID.fromString(model.getId());
      String placeId = SchedulerModel.getPlaceId(model);
      String targetAddress = SchedulerModel.getTarget(model);
      String placeAddress =
            Address
               .platformService(placeId, PlaceCapability.NAMESPACE)
               .getRepresentation();

      session().execute( deleteById.bind(modelId) );
      deleteIndices(modelId, targetAddress, placeAddress);
   }
}
 
Example #28
Source File: PersonPlaceAssocDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Set<UUID> findPersonIdsByPlace(UUID placeId) {
   try(Context ctxt = findPersonIdsByPlaceTimer.time()) {
      List<AuthorizationGrant> grantsForPlace = grantDao.findForPlace(placeId);
      return grantsForPlace.stream().map(AuthorizationGrant::getEntityId).collect(Collectors.toSet());
   }
}
 
Example #29
Source File: BaseCassandraCRUDDao.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected T doInsert(I id, T entity) {
   Date created = new Date();

   List<Object> allValues = new LinkedList<Object>();
   allValues.add(id);
   allValues.add(created);
   allValues.add(created); // modified date
   allValues.add(entity.getTags());
   allValues.add(entity.getImages());
   allValues.addAll(getValues(entity));

   Statement statement = new BoundStatement(insert).bind(allValues.toArray());

   List<Statement> indexInserts = prepareIndexInserts(id, entity);
   if(!indexInserts.isEmpty()) {
      BatchStatement batch = new BatchStatement();
      batch.add(statement);
      addToBatch(batch, indexInserts);
      statement = batch;
   }

   try(Context ctxt = insertTimer.time()) {
 	  session.execute(statement);
   }

   T copy = entity.copy();
   copy.setId(id);
   copy.setCreated(created);
   copy.setModified(created);
   return copy;
}
 
Example #30
Source File: PreferencesDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteForPerson(UUID personId)
{
   BoundStatement boundStatement = new BoundStatement(deleteForPersonStatement)
      .setUUID(Cols.PERSON_ID, personId);

   try (Context context = deleteForPersonTimer.time())
   {
      session.execute(boundStatement);
   }
}