_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q163600
AuditService.getAudit
train
public Audit getAudit(BigInteger id) throws IOException, TokenExpiredException { String requestUrl = RESOURCE + "/" + id.toString(); ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.GET, requestUrl, null); assertValidResponse(response, requestUrl); return fromJson(response.getResult(), Audit.class); }
java
{ "resource": "" }
q163601
AnnotationQuery.setTag
train
@JsonIgnore public void setTag(String key, String value) { requireArgument(key != null && !key.trim().isEmpty(), "Tag key cannot be null."); requireArgument(!ReservedField.isReservedField(key), "Tag is a reserved tag name."); if (value == null || value.isEmpty()) { _tags.remove(key); } else { _tags.put(key, value); } }
java
{ "resource": "" }
q163602
AnnotationQuery.getTag
train
@JsonIgnore public String getTag(String key) { return (!Metric.ReservedField.isReservedField(key)) ? _tags.get(key) : null; }
java
{ "resource": "" }
q163603
AnnotationQuery.setTags
train
public final void setTags(Map<String, String> tags) { Map<String, String> updatedTags = new TreeMap<>(); if (tags != null) { for (Map.Entry<String, String> entry : tags.entrySet()) { String key = entry.getKey(); requireArgument(!Metric.ReservedField.isReservedField(key), MessageFormat.format("Tag {0} is a reserved tag name.", key)); updatedTags.put(key, entry.getValue()); } } _tags.clear(); _tags.putAll(updatedTags); }
java
{ "resource": "" }
q163604
AnnotationQuery.setScope
train
protected void setScope(String scope) { requireArgument(scope != null && !scope.isEmpty(), "Scope cannot be null or empty."); _scope = scope; }
java
{ "resource": "" }
q163605
AnnotationQuery.setMetric
train
protected void setMetric(String metric) { requireArgument(metric != null && !metric.isEmpty(), "Metric name cannot be null or empty."); _metric = metric; }
java
{ "resource": "" }
q163606
AnnotationQuery.toTagParameterArray
train
protected String toTagParameterArray(Map<String, String> tags) throws UnsupportedEncodingException { if(tags == null || tags.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(encode("{", "UTF-8")); for (Map.Entry<String, String> tagEntry : tags.entrySet()) { sb.append(tagEntry.getKey()).append("="); String tagV = tagEntry.getValue().replaceAll("\\|", encode("|", "UTF-8")); sb.append(tagV).append(","); } sb.replace(sb.length() - 1, sb.length(), encode("}", "UTF-8")); return sb.toString(); }
java
{ "resource": "" }
q163607
AnomalyDetectionTransform.getMinMax
train
private Map<String, Double> getMinMax(Map<Long, Double> metricData) { double min = 0.0; double max = 0.0; boolean isMinMaxSet = false; for (Double value : metricData.values()) { double valueDouble = value; if (!isMinMaxSet) { min = valueDouble; max = valueDouble; isMinMaxSet = true; } else { if (valueDouble < min) { min = valueDouble; } else if (valueDouble > max) { max = valueDouble; } } } Map<String, Double> minMax = new HashMap<>(); minMax.put("min", min); minMax.put("max", max); return minMax; }
java
{ "resource": "" }
q163608
Main.main
train
static void main(String[] args, PrintStream out) throws IOException { try { Main main = null; Option[] options = Option.parseCLArgs(args, TEMPLATES); Option helpOption = (options == null) ? null : findOption(HELP_OPTION.getName(), options); Option installOption = (options == null) ? null : findOption(INSTALL_OPTION.getName(), options); Option configOption = (options == null) ? null : findOption(CONFIG_OPTION.getName(), options); Option typeOption = (options == null) ? null : findOption(TYPE_OPTION.getName(), options); if (helpOption != null) { out.println(usage()); } else if (installOption != null) { SystemConfiguration.generateConfiguration(System.in, out, new File(installOption.getValue())); } else if (configOption != null) { FileInputStream fis = null; Properties props = new Properties(); try { fis = new FileInputStream(configOption.getValue()); props.load(fis); } finally { if (fis != null) { fis.close(); } } main = new Main(props); } else { main = new Main(); } if (main != null) { ClientType type; try { type = typeOption == null ? COMMIT_METRICS : ClientType.valueOf(typeOption.getValue()); } catch (Exception ex) { type = COMMIT_METRICS; } final Thread mainThread = Thread.currentThread(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { mainThread.interrupt(); try { mainThread.join(); } catch (InterruptedException ex) { LOGGER.warn("Interrupted while shutting down. Giving up."); } } })); main.invoke(type); } } catch (IllegalArgumentException ex) { out.println(usage()); } // end try-catch }
java
{ "resource": "" }
q163609
Main.invoke
train
void invoke(ClientType clientType) { try { LOGGER.info("Starting service."); ExecutorService service = ClientServiceFactory.startClientService(_system, clientType, _jobCounter); LOGGER.info("Service started."); Thread currentThread = Thread.currentThread(); while (!currentThread.isInterrupted()) { try { Thread.sleep(500); } catch (InterruptedException ex) { currentThread.interrupt(); break; } } LOGGER.info("Stopping service."); service.shutdownNow(); try { if (!service.awaitTermination(60000, TimeUnit.MILLISECONDS)) { LOGGER.warn("Shutdown timed out after 60 seconds. Exiting."); } } catch (InterruptedException iex) { LOGGER.warn("Forcing shutdown."); } LOGGER.info("Service stopped."); } catch (Exception ex) { throw new SystemException("There was a problem invoking the committer.", ex); } finally { if (_system != null) { _system.stop(); } LOGGER.info("Finished"); } // end try-catch-finally }
java
{ "resource": "" }
q163610
Barrier.enter
train
public boolean enter() throws KeeperException, InterruptedException{ zooKeeper.create(rootPath + "/" + name, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); while (true) { synchronized (mutex) { List<String> list = zooKeeper.getChildren(rootPath, true); if (list.size() < size) { mutex.wait(); } else { return true; } } } }
java
{ "resource": "" }
q163611
Barrier.leave
train
public boolean leave() throws KeeperException, InterruptedException{ zooKeeper.delete(rootPath + "/" + name, 0); while (true) { synchronized (mutex) { List<String> list = zooKeeper.getChildren(rootPath, true); if (list.size() > 0) { mutex.wait(); } else { return true; } } } }
java
{ "resource": "" }
q163612
MetricService.getMetrics
train
public List<Metric> getMetrics(List<String> expressions) throws IOException, TokenExpiredException { StringBuilder requestUrl = new StringBuilder(RESOURCE); for (int i = 0; i < expressions.size(); i++) { requestUrl.append(i == 0 ? "?" : "&"); requestUrl.append("expression=").append(expressions.get(i)); } ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.GET, requestUrl.toString(), null); assertValidResponse(response, requestUrl.toString()); return fromJson(response.getResult(), new TypeReference<List<Metric>>() { }); }
java
{ "resource": "" }
q163613
GlobalInterlock.obtainLock
train
public static String obtainLock(EntityManager em, long expiration, long type, String note) { EntityTransaction tx = null; /* remove the existing lock if it's expired */ try { long now = System.currentTimeMillis(); tx = em.getTransaction(); tx.begin(); GlobalInterlock lock = _findAndRefreshLock(em, type); if (lock != null && now - lock.lockTime > expiration) { em.remove(lock); em.flush(); } tx.commit(); } catch (Exception ex) { LOGGER.warn("An error occurred trying to refresh the type {} lock: {}", type, ex.getMessage()); LOGGER.debug(ex.getMessage(), ex); if (tx != null && tx.isActive()) { tx.rollback(); } } /* attempt to obtain a lock */ try { tx = em.getTransaction(); tx.begin(); GlobalInterlock lock = em.merge(new GlobalInterlock(type, note)); em.flush(); tx.commit(); return Long.toHexString(lock.lockTime); } catch (Exception ex) { throw new GlobalInterlockException("Could not obtain " + type + " lock", ex); } finally { if (tx != null && tx.isActive()) { tx.rollback(); } } }
java
{ "resource": "" }
q163614
GlobalInterlock.releaseLock
train
public static void releaseLock(EntityManager em, long type, String key) { EntityTransaction tx = null; /* remove the existing lock if it matches the key. */ try { tx = em.getTransaction(); tx.begin(); GlobalInterlock lock = _findAndRefreshLock(em, type); if (lock == null) { throw new GlobalInterlockException("No lock of type " + type + " exists for key " + key + "."); } String ref = Long.toHexString(lock.lockTime); if (ref.equalsIgnoreCase(key)) { em.remove(lock); em.flush(); tx.commit(); } else { throw new GlobalInterlockException("This process doesn't own the type " + type + " lock having key " + key + "."); } } finally { if (tx != null && tx.isActive()) { tx.rollback(); } } }
java
{ "resource": "" }
q163615
GlobalInterlock.refreshLock
train
public static String refreshLock(EntityManager em, long type, String key, String note) { EntityTransaction tx = null; /* refresh the existing lock if it matches the key. */ try { tx = em.getTransaction(); tx.begin(); GlobalInterlock lock = _findAndRefreshLock(em, type); if (lock == null) { throw new GlobalInterlockException("No lock of type " + type + " exists for key " + key + "."); } String ref = Long.toHexString(lock.lockTime); if (ref.equalsIgnoreCase(key)) { lock.lockTime = System.currentTimeMillis(); lock.note = note; em.merge(lock); em.flush(); tx.commit(); return Long.toHexString(lock.lockTime); } throw new GlobalInterlockException("This process doesn't own the type " + type + " lock having key " + key + "."); } finally { if (tx != null && tx.isActive()) { tx.rollback(); } } }
java
{ "resource": "" }
q163616
AuditDto.transformToDto
train
public static AuditDto transformToDto(Audit audit) { if (audit == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } AuditDto auditDto = new AuditDto(); try { auditDto.setId(audit.getId()); auditDto.setHostName(audit.getHostName()); auditDto.setMessage(audit.getMessage()); auditDto.setCreatedDate(audit.getCreatedDate()); auditDto.setEntityId(audit.getEntityId()); } catch (Exception ex) { throw new WebApplicationException("DTO transformation failed.", Status.INTERNAL_SERVER_ERROR); } return auditDto; }
java
{ "resource": "" }
q163617
AuditDto.transformToDto
train
public static List<AuditDto> transformToDto(List<Audit> audits) { if (audits == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } List<AuditDto> result = new ArrayList<AuditDto>(); for (Audit audit : audits) { result.add(transformToDto(audit)); } return result; }
java
{ "resource": "" }
q163618
SuspensionRecord.findInfractionCount
train
public static int findInfractionCount(EntityManager em, PrincipalUser user, SubSystem subSystem, long startTime) { List<SuspensionRecord> records; if (subSystem == null) { records = findByUser(em, user); } else { SuspensionRecord record = findByUserAndSubsystem(em, user, subSystem); records = record == null ? new ArrayList<SuspensionRecord>(0) : Arrays.asList(new SuspensionRecord[] { record }); } int count = 0; for (SuspensionRecord record : records) { List<Long> timestamps = record.getInfractionHistory(); for (Long timestamp : timestamps) { if (timestamp > startTime) { count++; } } } return count; }
java
{ "resource": "" }
q163619
SuspensionRecord.findByUserAndSubsystem
train
public static SuspensionRecord findByUserAndSubsystem(EntityManager em, PrincipalUser user, SubSystem subSystem) { TypedQuery<SuspensionRecord> query = em.createNamedQuery("SuspensionRecord.findByUserAndSubsystem", SuspensionRecord.class); try { query.setParameter("user", user); query.setParameter("subSystem", subSystem); query.setHint("javax.persistence.cache.storeMode", "REFRESH"); return query.getSingleResult(); } catch (NoResultException ex) { return null; } }
java
{ "resource": "" }
q163620
SuspensionRecord.findByUser
train
public static List<SuspensionRecord> findByUser(EntityManager em, PrincipalUser user) { TypedQuery<SuspensionRecord> query = em.createNamedQuery("SuspensionRecord.findByUser", SuspensionRecord.class); try { query.setParameter("user", user); return query.getResultList(); } catch (NoResultException ex) { return new ArrayList<>(0); } }
java
{ "resource": "" }
q163621
SuspensionRecord.setInfractionHistory
train
public void setInfractionHistory(List<Long> history) { SystemAssert.requireArgument(history != null && !history.isEmpty(), "Infraction History cannot be set to null or empty."); this.infractionHistory = history; }
java
{ "resource": "" }
q163622
TSDBEntity.getTags
train
public Map<String, String> getTags() { Map<String, String> result = new HashMap<>(); for (Map.Entry<String, String> entry : _tags.entrySet()) { String key = entry.getKey(); if (!ReservedField.isReservedField(key)) { result.put(key, entry.getValue()); } } return Collections.unmodifiableMap(result); }
java
{ "resource": "" }
q163623
TSDBEntity.setTags
train
public void setTags(Map<String, String> tags) { TSDBEntity.validateTags(tags); _tags.clear(); if (tags != null) { _tags.putAll(tags); } }
java
{ "resource": "" }
q163624
Annotation.setType
train
private void setType(String type) { requireArgument(type != null && !type.trim().isEmpty(), "Type cannot be null or empty."); _type = type; }
java
{ "resource": "" }
q163625
Annotation.setSource
train
private void setSource(String source) { requireArgument(source != null && !source.trim().isEmpty(), "Source cannot be null or empty."); _source = source; }
java
{ "resource": "" }
q163626
Annotation.setId
train
private void setId(String id) { requireArgument(id != null && !id.trim().isEmpty(), "ID cannot be null or empty."); _id = id; }
java
{ "resource": "" }
q163627
Annotation.setFields
train
public void setFields(Map<String, String> fields) { _fields.clear(); if (fields != null) { _fields.putAll(fields); } }
java
{ "resource": "" }
q163628
PolicyLimit.findPolicyLimitByUserAndCounter
train
public static PolicyLimit findPolicyLimitByUserAndCounter(EntityManager em, PrincipalUser user, PolicyCounter counter) { TypedQuery<PolicyLimit> query = em.createNamedQuery("PolicyLimit.findPolicyLimitByUserAndCounter", PolicyLimit.class); try { query.setParameter("user", user); query.setParameter("counter", counter); return query.getSingleResult(); } catch (NoResultException ex) { return null; } }
java
{ "resource": "" }
q163629
PolicyLimit.getLimitByUserAndCounter
train
public static double getLimitByUserAndCounter(EntityManager em, PrincipalUser user, PolicyCounter counter) { PolicyLimit pLimit = findPolicyLimitByUserAndCounter(em, user, counter); if (pLimit != null) { return pLimit.getLimit(); } return counter.getDefaultValue(); }
java
{ "resource": "" }
q163630
ServiceManagementRecord.findServiceManagementRecord
train
public static ServiceManagementRecord findServiceManagementRecord(EntityManager em, Service service) { requireArgument(em != null, "Entity manager can not be null."); requireArgument(service != null, "Service cannot be null."); TypedQuery<ServiceManagementRecord> query = em.createNamedQuery("ServiceManagementRecord.findByService", ServiceManagementRecord.class); try { query.setParameter("service", service); return query.getSingleResult(); } catch (NoResultException ex) { return null; } }
java
{ "resource": "" }
q163631
ServiceManagementRecord.isServiceEnabled
train
public static boolean isServiceEnabled(EntityManager em, Service service) { ServiceManagementRecord record = findServiceManagementRecord(em, service); return record == null ? true : record.isEnabled(); }
java
{ "resource": "" }
q163632
ServiceManagementRecord.updateServiceManagementRecord
train
@Transactional public static ServiceManagementRecord updateServiceManagementRecord(EntityManager em, ServiceManagementRecord record) { SystemAssert.requireArgument(em != null, "Entity manager can not be null."); SystemAssert.requireArgument(record != null, "ServiceManagementRecord cannot be null."); TypedQuery<ServiceManagementRecord> query = em.createNamedQuery("ServiceManagementRecord.findByService", ServiceManagementRecord.class); query.setParameter("service", record.getService()); try { ServiceManagementRecord oldRecord = query.getSingleResult(); oldRecord.setEnabled(record.isEnabled()); return em.merge(oldRecord); } catch (NoResultException ex) { return em.merge(record); } }
java
{ "resource": "" }
q163633
DefaultAlertService._processNotification
train
private void _processNotification(Alert alert, History history, List<Metric> metrics, Map<BigInteger, Map<Metric, Long>> triggerFiredTimesAndMetricsByTrigger, Notification notification, Long alertEnqueueTimestamp) { //refocus notifier does not need cool down logic, and every evaluation needs to send notification boolean isRefocusNotifier = SupportedNotifier.REFOCUS.getName().equals(notification.getNotifierName()); for(Trigger trigger : notification.getTriggers()) { Map<Metric, Long> triggerFiredTimesForMetrics = triggerFiredTimesAndMetricsByTrigger.get(trigger.getId()); for(Metric m : metrics) { if(triggerFiredTimesForMetrics!=null && triggerFiredTimesForMetrics.containsKey(m)) { String logMessage = MessageFormat.format("The trigger {0} was evaluated against metric {1} and it is fired.", trigger.getName(), m.getIdentifier()); history.appendMessageNUpdateHistory(logMessage, null, 0); if (isRefocusNotifier) { sendNotification(trigger, m, history, notification, alert, triggerFiredTimesForMetrics.get(m), alertEnqueueTimestamp); continue; } if(!notification.onCooldown(trigger, m)) { _updateNotificationSetActiveStatus(trigger, m, history, notification); sendNotification(trigger, m, history, notification, alert, triggerFiredTimesForMetrics.get(m), alertEnqueueTimestamp); } else { logMessage = MessageFormat.format("The notification {0} is on cooldown until {1}.", notification.getName(), getDateMMDDYYYY(notification.getCooldownExpirationByTriggerAndMetric(trigger, m))); history.appendMessageNUpdateHistory(logMessage, null, 0); } } else { String logMessage = MessageFormat.format("The trigger {0} was evaluated against metric {1} and it is not fired.", trigger.getName(), m.getIdentifier()); history.appendMessageNUpdateHistory(logMessage, null, 0); if (isRefocusNotifier) { sendClearNotification(trigger, m, history, notification, alert, alertEnqueueTimestamp); continue; } if(notification.isActiveForTriggerAndMetric(trigger, m)) { // This is case when the notification was active for the given trigger, metric combination // and the metric did not violate triggering condition on current evaluation. Hence we must clear it. _updateNotificationClearActiveStatus(trigger, m, notification); sendClearNotification(trigger, m, history, notification, alert, alertEnqueueTimestamp); } } } } }
java
{ "resource": "" }
q163634
DefaultAlertService._processMissingDataNotification
train
private void _processMissingDataNotification(Alert alert, History history, Set<Trigger> triggers, Notification notification, boolean isDataMissing, Long alertEnqueueTimestamp) { //refocus notifier does not need cool down logic, and every evaluation needs to send notification boolean isRefocusNotifier = SupportedNotifier.REFOCUS.getName().equals(notification.getNotifierName()); for(Trigger trigger : notification.getTriggers()) { if(triggers.contains(trigger)) { Metric m = new Metric("argus","argus"); if(isDataMissing) { String logMessage = MessageFormat.format("The trigger {0} was evaluated and it is fired as data for the metric expression {1} does not exist", trigger.getName(), alert.getExpression()); history.appendMessageNUpdateHistory(logMessage, null, 0); if(isRefocusNotifier) { sendNotification(trigger, m, history, notification, alert, System.currentTimeMillis(), alertEnqueueTimestamp); continue; } if (!notification.onCooldown(trigger, m)) { _updateNotificationSetActiveStatus(trigger, m, history, notification); sendNotification(trigger, m, history, notification, alert, System.currentTimeMillis(), alertEnqueueTimestamp); } else { logMessage = MessageFormat.format("The notification {0} is on cooldown until {1}.", notification.getName(), getDateMMDDYYYY(notification.getCooldownExpirationByTriggerAndMetric(trigger, m))); history.appendMessageNUpdateHistory(logMessage, null, 0); } } else { // Data is not missing String logMessage = MessageFormat.format("The trigger {0} was evaluated and it is not fired as data exists for the expression {1}", trigger.getName(), alert.getExpression()); history.appendMessageNUpdateHistory(logMessage, null, 0); if(isRefocusNotifier) { sendClearNotification(trigger, m, history, notification, alert, alertEnqueueTimestamp); continue; } if (notification.isActiveForTriggerAndMetric(trigger, m)) { // This is case when the notification was active for the given trigger, metric combination // and the metric did not violate triggering condition on current evaluation. Hence we must clear it. _updateNotificationClearActiveStatus(trigger, m, notification); sendClearNotification(trigger, m, history, notification, alert, alertEnqueueTimestamp); } } } } }
java
{ "resource": "" }
q163635
DefaultAlertService._shouldEvaluateAlert
train
private boolean _shouldEvaluateAlert(Alert alert, BigInteger alertId) { if (alert == null) { _logger.warn(MessageFormat.format("Could not find alert ID {0}", alertId)); return false; } if(!alert.isEnabled()) { _logger.warn(MessageFormat.format("Alert {0} has been disabled. Will not evaluate.", alert.getId().intValue())); return false; } return true; }
java
{ "resource": "" }
q163636
DefaultAlertService._evaluateTriggers
train
private Map<BigInteger, Map<Metric, Long>> _evaluateTriggers(Set<Trigger> triggers, List<Metric> metrics, String queryExpression, Long alertEnqueueTimestamp) { Map<BigInteger, Map<Metric, Long>> triggerFiredTimesAndMetricsByTrigger = new HashMap<>(); for(Trigger trigger : triggers) { Map<Metric, Long> triggerFiredTimesForMetrics = new HashMap<>(metrics.size()); for(Metric metric : metrics) { Long triggerFiredTime = getTriggerFiredDatapointTime(trigger, metric, queryExpression, alertEnqueueTimestamp); if (triggerFiredTime != null) { triggerFiredTimesForMetrics.put(metric, triggerFiredTime); Map<String, String> tags = new HashMap<>(); tags.put(USERTAG, trigger.getAlert().getOwner().getUserName()); _monitorService.modifyCounter(Counter.TRIGGERS_VIOLATED, 1, tags); } } triggerFiredTimesAndMetricsByTrigger.put(trigger.getId(), triggerFiredTimesForMetrics); } return triggerFiredTimesAndMetricsByTrigger; }
java
{ "resource": "" }
q163637
DefaultAlertService.getNotifier
train
@Override public Notifier getNotifier(SupportedNotifier notifier) { switch (notifier) { case CALLBACK: return _notifierFactory.getCallbackNotifier(); case EMAIL: return _notifierFactory.getEmailNotifier(); case GOC: return _notifierFactory.getGOCNotifier(); case DATABASE: return _notifierFactory.getDBNotifier(); case WARDENAPI: return _notifierFactory.getWardenApiNotifier(); case WARDENPOSTING: return _notifierFactory.getWardenPostingNotifier(); case GUS: return _notifierFactory.getGusNotifier(); case REFOCUS: return _notifierFactory.getRefocusNotifier(); default: return _notifierFactory.getDBNotifier(); } }
java
{ "resource": "" }
q163638
PerfFilter.doFilter
train
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = HttpServletRequest.class.cast(request); long start = System.currentTimeMillis(); try { chain.doFilter(request, response); } finally { long delta = System.currentTimeMillis() - start; HttpServletResponse resp = HttpServletResponse.class.cast(response); updateCounters(req, resp, delta); } }
java
{ "resource": "" }
q163639
MetricDistiller.setCommonAttributes
train
public static void setCommonAttributes(List<Metric> metrics, Metric result) { MetricDistiller distiller = new MetricDistiller(); distiller.distill(metrics); result.setDisplayName(distiller.getDisplayName()); result.setUnits(distiller.getUnits()); result.setTags(distiller.getTags()); }
java
{ "resource": "" }
q163640
MetricDistiller.getTags
train
public Map<String, String> getTags() { Map<String, String> distilledTags = new HashMap<String, String>(); for (Map.Entry<String, String> entry : potentialTags.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (tagCounts.get(key).equals(totalAdds)) { distilledTags.put(key, value); } } return distilledTags; }
java
{ "resource": "" }
q163641
EntityDTO.createDtoObject
train
public static <D extends EntityDTO, E extends JPAEntity> D createDtoObject(Class<D> clazz, E entity) { D result = null; try { result = clazz.newInstance(); BeanUtils.copyProperties(result, entity); // Now set IDs of JPA entity result.setCreatedById(entity.getCreatedBy() != null ? entity.getCreatedBy().getId() : null); result.setModifiedById(entity.getModifiedBy() != null ? entity.getModifiedBy().getId() : null); } catch (Exception ex) { throw new WebApplicationException("DTO transformation failed.", Status.INTERNAL_SERVER_ERROR); } return result; }
java
{ "resource": "" }
q163642
RunnableJob.execute
train
@Override public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap map = context.getJobDetail().getJobDataMap(); AlertService alertService = (AlertService) map.get("AlertService"); AuditService auditService = (AuditService) map.get("AuditService"); if (map.containsKey(LOCK_TYPE)) { lockType = (LockType) map.get(LOCK_TYPE); } if (map.containsKey(CRON_JOB)) { job = (CronJob) map.get(CRON_JOB); } try { if (!alertService.isDisposed()) { if (LockType.ALERT_SCHEDULING.equals(lockType)) { alertService.enqueueAlerts(Arrays.asList(new Alert[] { Alert.class.cast(job) })); } else { throw new SystemException("Unsupported lock type " + lockType); } } } catch (Exception ex) { auditService.createAudit("Could not enqueue scheduled job. " + ex.getMessage(), JPAEntity.class.cast(job)); } }
java
{ "resource": "" }
q163643
LoggingFilter.doFilter
train
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = HttpServletRequest.class.cast(request); String url = req.getRequestURI(); LoggerFactory.getLogger(getClass()).debug("Request started: {}", url); long start = System.currentTimeMillis(); try { chain.doFilter(request, response); } finally { long delta = System.currentTimeMillis() - start; LoggerFactory.getLogger(getClass()).info("Request completed in {}ms: {}", delta, url); } }
java
{ "resource": "" }
q163644
Producer.enqueue
train
public <T extends Serializable> int enqueue(final String topic, List<T> objects) { int messagesBuffered = 0; for (T object : objects) { final String value; if (String.class.isAssignableFrom(object.getClass())) { value = String.class.cast(object); } else { try { value = _mapper.writeValueAsString(object); } catch (JsonProcessingException e) { _logger.warn("Exception while serializing the object to a string. Skipping this object.", e); continue; } } try { boolean addedToBuffer = _executorService.submit(new ProducerWorker(topic, value)).get(); if (addedToBuffer) { messagesBuffered++; } } catch (InterruptedException e) { _logger.warn("Enqueue operation was interrupted by calling code."); Thread.currentThread().interrupt(); } catch (ExecutionException e) { throw new SystemException(e); } } return messagesBuffered; }
java
{ "resource": "" }
q163645
Producer.shutdown
train
public void shutdown() { if (_producer != null) { _producer.close(); } _executorService.shutdown(); try { if (!_executorService.awaitTermination(10, TimeUnit.SECONDS)) { _logger.warn("Shutdown of Kafka executor service timed out after 10 seconds."); _executorService.shutdownNow(); } } catch (InterruptedException ex) { _logger.warn("Shutdown of executor service was interrupted."); Thread.currentThread().interrupt(); } }
java
{ "resource": "" }
q163646
Notification.getMetricToAnnotate
train
public static Metric getMetricToAnnotate(String metric) { Metric result = null; if (metric != null && !metric.isEmpty()) { Pattern pattern = Pattern.compile( "([\\w,\\-,\\.,/]+):([\\w,\\-,\\.,/]+)(\\{(?:[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)(?:,[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)*\\})?:([\\w,\\-,\\.,/]+)"); Matcher matcher = pattern.matcher(metric.replaceAll("\\s", "")); if (matcher.matches()) { String scopeName = matcher.group(1); String metricName = matcher.group(2); String tagString = matcher.group(3); Map<String, String> tags = new HashMap<>(); if (tagString != null) { tagString = tagString.replaceAll("\\{", "").replaceAll("\\}", ""); for (String tag : tagString.split(",")) { String[] entry = tag.split("="); tags.put(entry[0], entry[1]); } } result = new Metric(scopeName, metricName); result.setTags(tags); } } return result; }
java
{ "resource": "" }
q163647
Notification.setSubscriptions
train
public void setSubscriptions(List<String> subscriptions) { this.subscriptions.clear(); if(subscriptions == null) return; for(String currentSubscription: subscriptions) { if (this.getNotifierName().equals(AlertService.SupportedNotifier.GUS.getName())) { if (currentSubscription.isEmpty() || currentSubscription.length() < 10) throw new IllegalArgumentException("GUS Subscription has to contain subjectId with more than 10 characters."); } else if (this.getNotifierName().equals(AlertService.SupportedNotifier.EMAIL.getName())) { if (currentSubscription.isEmpty() || !currentSubscription.contains("@")) { String errorMessage = MessageFormat.format("Email Address {0} is not allowed as @ not present.", currentSubscription); throw new IllegalArgumentException(errorMessage); } } else if (this.getNotifierName().equals(AlertService.SupportedNotifier.CALLBACK.getName()) && currentSubscription.isEmpty()) { throw new IllegalArgumentException("Callback Notifier Subscription cannot be empty."); } } if (subscriptions != null && !subscriptions.isEmpty()) { this.subscriptions.addAll(subscriptions); } }
java
{ "resource": "" }
q163648
Notification.getCooldownExpirationByTriggerAndMetric
train
public long getCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric) { String key = _hashTriggerAndMetric(trigger, metric); return this.cooldownExpirationByTriggerAndMetric.containsKey(key) ? this.cooldownExpirationByTriggerAndMetric.get(key) : 0; }
java
{ "resource": "" }
q163649
Notification.setCooldownExpirationByTriggerAndMetric
train
public void setCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric, long cooldownExpiration) { requireArgument(cooldownExpiration >= 0, "Cool down expiration time cannot be negative."); String key = _hashTriggerAndMetric(trigger, metric); this.cooldownExpirationByTriggerAndMetric.put(key, cooldownExpiration); }
java
{ "resource": "" }
q163650
Notification.setMetricsToAnnotate
train
public void setMetricsToAnnotate(List<String> metricsToAnnotate) { this.metricsToAnnotate.clear(); if (metricsToAnnotate != null && !metricsToAnnotate.isEmpty()) { for (String metric : metricsToAnnotate) { requireArgument(getMetricToAnnotate(metric) != null, "Metrics to annotate should be of the form 'scope:metric[{[tagk=tagv]+}]"); this.metricsToAnnotate.add(metric); } } }
java
{ "resource": "" }
q163651
Notification.setTriggers
train
public void setTriggers(List<Trigger> triggers) { this.triggers.clear(); if (triggers != null) { this.triggers.addAll(triggers); } }
java
{ "resource": "" }
q163652
Notification.isActiveForTriggerAndMetric
train
public boolean isActiveForTriggerAndMetric(Trigger trigger, Metric metric) { String key = _hashTriggerAndMetric(trigger, metric); return this.activeStatusByTriggerAndMetric.containsKey(key) ? activeStatusByTriggerAndMetric.get(key) : false; }
java
{ "resource": "" }
q163653
Notification.setActiveForTriggerAndMetric
train
public void setActiveForTriggerAndMetric(Trigger trigger, Metric metric, boolean active) { String key = _hashTriggerAndMetric(trigger, metric); this.activeStatusByTriggerAndMetric.put(key, active); }
java
{ "resource": "" }
q163654
Option.createFlag
train
public static Option createFlag(String name, String description) { return new Option(Type.FLAG, name, 0, description); }
java
{ "resource": "" }
q163655
Option.createOption
train
public static Option createOption(String name, String description) { return new Option(Type.OPTION, name, 1, description); }
java
{ "resource": "" }
q163656
Option.findListOption
train
public static Option findListOption(Option[] options) { for (int i = 0; i < options.length; i++) { if (options[i].getType() == Type.LIST) { return options[i]; } } return null; }
java
{ "resource": "" }
q163657
Option.findOption
train
public static Option findOption(String name, Option[] options) { for (int i = 0; i < options.length; i++) { if (options[i].getName().equals(name)) { return options[i]; } } return null; }
java
{ "resource": "" }
q163658
Option.parseCLArgs
train
public static Option[] parseCLArgs(String[] args, Option[] templates) { int i = 0; List<Option> options = new ArrayList<Option>(args.length); try { while (i < args.length) { String name = args[i++]; Option template = findTemplate(name, templates); StringBuilder values = new StringBuilder(); if (!Type.LIST.equals(template.getType())) { for (int j = 0; j < template.getLen(); j++) { values.append(args[i++]).append(" "); } } else if (hasMoreFlags(args, --i, templates)) { throw new IllegalArgumentException(); } else { for (String arg : Arrays.copyOfRange(args, i, args.length)) { values.append(arg).append(" "); } template.setValue(values.toString().trim()); Option[] result = new Option[options.size() + 1]; result = options.toArray(result); result[result.length - 1] = template; return result; } template.setValue(values.toString().trim()); options.add(template); } // end while return options.toArray(new Option[options.size()]); } catch (Exception e) { throw new IllegalArgumentException(e); } }
java
{ "resource": "" }
q163659
Option.findTemplate
train
private static Option findTemplate(String name, Option[] templates) { boolean listAllowed = false; Option listOption = null; for (int i = 0; i < templates.length; i++) { if (templates[i].getName().equals(name)) { return templates[i]; } if (Type.LIST.equals(templates[i].getType())) { listAllowed = true; listOption = templates[i]; } } if (listAllowed) { return listOption; } return null; }
java
{ "resource": "" }
q163660
Option.getValues
train
public String[] getValues() { return value == null || value.isEmpty() ? new String[0] : len == 1 ? new String[] { value } : value.split("\\s+"); }
java
{ "resource": "" }
q163661
RefocusNotifier.sendMessage
train
private void sendMessage(String aspectPath, boolean fired) { if (Boolean.valueOf(_config.getValue(SystemConfiguration.Property.REFOCUS_ENABLED))) { int refreshMaxTimes = Integer.parseInt(_config.getValue(Property.REFOCUS_CONNECTION_REFRESH_MAX_TIMES.getName(), Property.REFOCUS_CONNECTION_REFRESH_MAX_TIMES.getDefaultValue())); try { //TODO: get customer specified refocus sample values when UI is ready, currently use '1' for active trigger and '0' for non-active trigger RefocusSample refocusSample = new RefocusSample(aspectPath, fired ? "1" : "0"); RefocusTransport refocusTransport = RefocusTransport.getInstance(); HttpClient httpclient = refocusTransport.getHttpClient(_config); PostMethod post = null; try { post = new PostMethod(String.format("%s/v1/samples/upsert", endpoint)); post.setRequestHeader("Authorization", token); post.setRequestEntity(new StringRequestEntity(refocusSample.toJSON(), "application/json", null)); for (int i = 0; i < 1 + refreshMaxTimes; i++) { int respCode = httpclient.executeMethod(post); // Check for success if (respCode == 200 || respCode == 201 || respCode == 204) { _logger.info("Success - send Refocus sample '{}'.", refocusSample.toJSON()); break; } else if (respCode == 401) { // Indication that the session timedout, Need to refresh and retry continue; } else { _logger.error("Failure - send Refocus sample '{}'. Response code '{}' response '{}'", refocusSample.toJSON(), respCode, post.getResponseBodyAsString()); break; } } } catch (Exception e) { _logger.error("Failure - send Refocus sample '{}'. Exception '{}'", refocusSample.toJSON(), e); } finally { if (post != null) { post.releaseConnection(); } } } catch (RuntimeException ex) { throw new SystemException("Failed to send an Refocus notification.", ex); } } else { _logger.info("Sending Refocus notification is disabled. Not sending message for aspect '{}'.", aspectPath); } }
java
{ "resource": "" }
q163662
NamespaceDto.transformToDto
train
public static NamespaceDto transformToDto(Namespace namespace) { if (namespace == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } NamespaceDto result = createDtoObject(NamespaceDto.class, namespace); for (PrincipalUser user : namespace.getUsers()) { result.addUsername(user.getUserName()); } return result; }
java
{ "resource": "" }
q163663
NamespaceDto.addUsername
train
public void addUsername(String username) { SystemAssert.requireArgument(username != null && !username.isEmpty(), "Username cannot be null or empty."); this.usernames.add(username); }
java
{ "resource": "" }
q163664
MetricSchemaRecordQuery.setScope
train
public void setScope(String scope) { SystemAssert.requireArgument(scope != null && !scope.isEmpty(), "Scope cannot be null or empty."); this.scope = scope; }
java
{ "resource": "" }
q163665
MetricSchemaRecordQuery.setMetric
train
public void setMetric(String metric) { SystemAssert.requireArgument(metric != null && !metric.isEmpty(), "Metric cannot be null or empty."); this.metric = metric; }
java
{ "resource": "" }
q163666
AlertResources.getSharedAlertsObj
train
private List<Alert> getSharedAlertsObj(boolean populateMetaFieldsOnly, PrincipalUser owner, Integer limit) { Set<Alert> result = new HashSet<>(); result.addAll(populateMetaFieldsOnly ? alertService.findSharedAlerts(true, owner, limit) : alertService.findSharedAlerts(false, owner, limit)); return new ArrayList<>(result); }
java
{ "resource": "" }
q163667
Audit.setCreatedDate
train
public void setCreatedDate(Date createdDate) { _createdDate = createdDate == null ? null : new Date(createdDate.getTime()); }
java
{ "resource": "" }
q163668
TriggerDto.transformToDto
train
public static TriggerDto transformToDto(Trigger trigger) { TriggerDto result = createDtoObject(TriggerDto.class, trigger); // Now copy ID fields result.setAlertId(trigger.getAlert().getId()); for (Notification notification : trigger.getNotifications()) { result.addNotificationIds(notification); } return result; }
java
{ "resource": "" }
q163669
TriggerDto.transformToDto
train
public static List<TriggerDto> transformToDto(List<Trigger> triggers) { List<TriggerDto> result = new ArrayList<TriggerDto>(); for (Trigger trigger : triggers) { result.add(transformToDto(trigger)); } return result; }
java
{ "resource": "" }
q163670
HistoryDTO.transformToDto
train
public static HistoryDTO transformToDto(History history) { if (history == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } HistoryDTO historyDto = new HistoryDTO(); try { BeanUtils.copyProperties(historyDto, history); } catch (Exception ex) { throw new WebApplicationException("DTO transformation failed.", Status.INTERNAL_SERVER_ERROR); } return historyDto; }
java
{ "resource": "" }
q163671
HistoryDTO.transformToDto
train
public static List<HistoryDTO> transformToDto(List<History> list) { if (list == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } List<HistoryDTO> result = new ArrayList<HistoryDTO>(); for (History history : list) { result.add(transformToDto(history)); } return result; }
java
{ "resource": "" }
q163672
DefaultJPAService.mergeEntity
train
public <E extends Identifiable> E mergeEntity(EntityManager em, E entity) { requireArgument(em != null, "The entity manager cannot be null."); requireArgument(entity != null, "The entity cannot be null."); E ret = em.merge(entity); return ret; }
java
{ "resource": "" }
q163673
DefaultJPAService.deleteEntity
train
protected <E extends Identifiable> void deleteEntity(EntityManager em, E entity) { requireArgument(em != null, "The entity manager cannot be null."); requireArgument(entity != null, "The entity cannot be null."); if (!em.contains(entity)) { Identifiable attached = findEntity(em, entity.getId(), entity.getClass()); em.remove(attached); } else { em.remove(entity); } }
java
{ "resource": "" }
q163674
DefaultJPAService.findEntity
train
protected <E extends Identifiable> E findEntity(EntityManager em, BigInteger id, Class<E> type) { requireArgument(em != null, "The entity manager cannot be null."); requireArgument(id != null && id.compareTo(ZERO) > 0, "ID must be positive and non-zero"); requireArgument(type != null, "The entity cannot be null."); em.getEntityManagerFactory().getCache().evictAll(); return em.find(type, id); }
java
{ "resource": "" }
q163675
DefaultJPAService.findEntitiesMarkedForDeletion
train
protected <E extends Identifiable> List<E> findEntitiesMarkedForDeletion(EntityManager em, Class<E> type, final int limit) { requireArgument(em != null, "The entity manager cannot be null."); requireArgument(type != null, "The entity cannot be null."); requireArgument(limit == -1 || limit > 0, "Limit if not -1, must be greater than 0."); em.getEntityManagerFactory().getCache().evictAll(); return JPAEntity.findEntitiesMarkedForDeletion(em, type, limit); }
java
{ "resource": "" }
q163676
AnomalyDetectionGaussianTransform.fitParameters
train
private void fitParameters(Map<Long, Double> metricData) { mean = getMetricMean(metricData); variance = getMetricVariance(metricData); }
java
{ "resource": "" }
q163677
AnomalyDetectionGaussianTransform.predictAnomalies
train
private Metric predictAnomalies(Map<Long, Double> metricData) { Metric predictions = new Metric(getResultScopeName(), getResultMetricName()); Map<Long, Double> predictionDatapoints = new HashMap<>(); if (variance == 0.0) { /** * If variance is 0, there are no anomalies. * Also, using 0 for variance would cause divide by zero operations * in Gaussian anomaly formulas. This condition avoids such operations. */ for (Entry<Long, Double> entry : metricData.entrySet()) { Long timestamp = entry.getKey(); predictionDatapoints.put(timestamp, 0.0); } } else { for (Entry<Long, Double> entry : metricData.entrySet()) { Long timestamp = entry.getKey(); double value = entry.getValue(); try { double anomalyScore = calculateAnomalyScore(value); predictionDatapoints.put(timestamp, anomalyScore); } catch (ArithmeticException e) { continue; } } } predictions.setDatapoints(predictionDatapoints); return predictions; }
java
{ "resource": "" }
q163678
DefaultWardenService._constructWardenAlertForUser
train
private Alert _constructWardenAlertForUser(PrincipalUser user, PolicyCounter counter) { String metricExp = _constructWardenMetricExpression("-1h", user, counter); Alert alert = new Alert(_adminUser, _adminUser, _constructWardenAlertName(user, counter), metricExp, "*/5 * * * *"); List<Trigger> triggers = new ArrayList<>(); EntityManager em = emf.get(); double limit = PolicyLimit.getLimitByUserAndCounter(em, user, counter); Trigger trigger = new Trigger(alert, counter.getTriggerType(), "counter-value-" + counter.getTriggerType().toString() + "-policy-limit", limit, 0.0, 0L); triggers.add(trigger); List<Notification> notifications = new ArrayList<>(); Notification notification = new Notification(NOTIFICATION_NAME, alert, _getWardenNotifierClass(counter), new ArrayList<String>(), 3600000); List<String> metricAnnotationList = new ArrayList<String>(); String wardenMetricAnnotation = MessageFormat.format("{0}:{1}'{'user={2}'}':sum", Counter.WARDEN_TRIGGERS.getScope(), Counter.WARDEN_TRIGGERS.getMetric(), user.getUserName()); metricAnnotationList.add(wardenMetricAnnotation); notification.setMetricsToAnnotate(metricAnnotationList); notification.setTriggers(triggers); notifications.add(notification); alert.setTriggers(triggers); alert.setNotifications(notifications); return alert; }
java
{ "resource": "" }
q163679
DefaultWardenService._startScheduledExecutorService
train
private void _startScheduledExecutorService() { DisableWardenAlertsThread disableWardenAlertThread = new DisableWardenAlertsThread(); _scheduledExecutorService.scheduleAtFixedRate(disableWardenAlertThread, 0L, TIME_BETWEEN_WARDEN_ALERT_DISABLEMENT_MILLIS, TimeUnit.MILLISECONDS); }
java
{ "resource": "" }
q163680
DefaultWardenService._shutdownScheduledExecutorService
train
private void _shutdownScheduledExecutorService() { _logger.info("Shutting down scheduled disable warden alerts executor service"); _scheduledExecutorService.shutdown(); try { if (!_scheduledExecutorService.awaitTermination(5, TimeUnit.SECONDS)) { _logger.warn("Shutdown of scheduled disable warden alerts executor service timed out after 5 seconds."); _scheduledExecutorService.shutdownNow(); } } catch (InterruptedException ex) { _logger.warn("Shutdown of executor service was interrupted."); Thread.currentThread().interrupt(); } }
java
{ "resource": "" }
q163681
GOCNotifier._sendAdditionalNotification
train
protected void _sendAdditionalNotification(NotificationContext context, NotificationStatus status) { requireArgument(context != null, "Notification context cannot be null."); if(status == NotificationStatus.TRIGGERED) { super.sendAdditionalNotification(context); }else { super.clearAdditionalNotification(context); } Notification notification = null; Trigger trigger = null; for (Notification tempNotification : context.getAlert().getNotifications()) { if (tempNotification.getName().equalsIgnoreCase(context.getNotification().getName())) { notification = tempNotification; break; } } requireArgument(notification != null, "Notification in notification context cannot be null."); for (Trigger tempTrigger : context.getAlert().getTriggers()) { if (tempTrigger.getName().equalsIgnoreCase(context.getTrigger().getName())) { trigger = tempTrigger; break; } } requireArgument(trigger != null, "Trigger in notification context cannot be null."); String body = getGOCMessageBody(notification, trigger, context, status); Severity sev = status == NotificationStatus.CLEARED ? Severity.OK : Severity.ERROR; sendMessage(sev, TemplateReplacer.applyTemplateChanges(context, context.getNotification().getName()), TemplateReplacer.applyTemplateChanges(context, context.getAlert().getName()), TemplateReplacer.applyTemplateChanges(context, context.getTrigger().getName()), body, context.getNotification().getSeverityLevel(),context.getNotification().getSRActionable(), context.getTriggerFiredTime(), context.getTriggeredMetric()); }
java
{ "resource": "" }
q163682
JPAEntity.findByPrimaryKey
train
public static <E extends Identifiable> E findByPrimaryKey(EntityManager em, BigInteger id, Class<E> type) { requireArgument(em != null, "The entity manager cannot be null."); requireArgument(id != null && id.compareTo(ZERO) > 0, "ID cannot be null and must be positive and non-zero"); requireArgument(type != null, "The entity type cannot be null."); TypedQuery<E> query = em.createNamedQuery("JPAEntity.findByPrimaryKey", type); query.setHint("javax.persistence.cache.storeMode", "REFRESH"); try { query.setParameter("id", id); query.setParameter("deleted", false); return query.getSingleResult(); } catch (NoResultException ex) { return null; } }
java
{ "resource": "" }
q163683
JPAEntity.findByPrimaryKeys
train
public static <E extends Identifiable> List<E> findByPrimaryKeys(EntityManager em, List<BigInteger> ids, Class<E> type) { requireArgument(em != null, "The entity manager cannot be null."); requireArgument(ids != null && !ids.isEmpty(), "IDs cannot be null or empty."); requireArgument(type != null, "The entity type cannot be null."); TypedQuery<E> query = em.createNamedQuery("JPAEntity.findByPrimaryKeys", type); query.setHint("javax.persistence.cache.storeMode", "REFRESH"); try { query.setParameter("ids", ids); query.setParameter("deleted", false); return query.getResultList(); } catch (NoResultException ex) { return new ArrayList<>(0); } }
java
{ "resource": "" }
q163684
JPAEntity.findEntitiesMarkedForDeletion
train
public static <E extends Identifiable> List<E> findEntitiesMarkedForDeletion(EntityManager em, Class<E> type, final int limit) { requireArgument(em != null, "Entity Manager cannot be null"); requireArgument(limit == -1 || limit > 0, "Limit if not -1, must be greater than 0."); TypedQuery<E> query = em.createNamedQuery("JPAEntity.findByDeleteMarker", type); query.setHint("javax.persistence.cache.storeMode", "REFRESH"); try { query.setParameter("deleted", true); if(limit > 0) { query.setMaxResults(limit); } return query.getResultList(); } catch (NoResultException ex) { return new ArrayList<>(0); } }
java
{ "resource": "" }
q163685
AnnotationService.putAnnotations
train
public PutResult putAnnotations(List<Annotation> annotations) throws IOException, TokenExpiredException { String requestUrl = COLLECTION_RESOURCE + RESOURCE; ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.POST, requestUrl, annotations); assertValidResponse(response, requestUrl); Map<String, Object> map = fromJson(response.getResult(), new TypeReference<Map<String, Object>>() { }); List<String> errorMessages = (List<String>) map.get("Error Messages"); return new PutResult(String.valueOf(map.get("Success")), String.valueOf(map.get("Errors")), errorMessages); }
java
{ "resource": "" }
q163686
DownsampleTransform.downsamplerReducer
train
public static Double downsamplerReducer(List<Double> values, String reducerType) { List<Double> operands = new ArrayList<Double>(); for (Double value : values) { if (value == null) { operands.add(0.0); } else { operands.add(value); } } InternalReducerType type = InternalReducerType.fromString(reducerType); switch (type) { case AVG: return new Mean().evaluate(Doubles.toArray(operands)); case MIN: return Collections.min(operands); case MAX: return Collections.max(operands); case SUM: return new Sum().evaluate(Doubles.toArray(operands), 0, operands.size()); case DEVIATION: return new StandardDeviation().evaluate(Doubles.toArray(operands)); case COUNT: values.removeAll(Collections.singleton(null)); return (double) values.size(); case PERCENTILE: return new Percentile().evaluate(Doubles.toArray(operands), Double.parseDouble(reducerType.substring(1))); default: throw new UnsupportedOperationException("Illegal type: " + reducerType + ". Please provide a valid type."); } }
java
{ "resource": "" }
q163687
AuthFilter.doFilter
train
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String user = null; if (HttpServletRequest.class.isAssignableFrom(request.getClass())) { HttpServletRequest req = HttpServletRequest.class.cast(request); String authorizationHeader = req.getHeader(HttpHeaders.AUTHORIZATION); //Only perform authentication check for endpoints that require it and if the req is not an OPTIONS request. if(_requiresAuthentication(req) && !"options".equalsIgnoreCase(req.getMethod())) { if(authorizationHeader != null && authorizationHeader.startsWith("Bearer")) { try { String jwt = authorizationHeader.substring("Bearer ".length()).trim(); user = JWTUtils.validateTokenAndGetSubj(jwt, JWTUtils.TokenType.ACCESS); } catch(UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) { HttpServletResponse httpresponse = HttpServletResponse.class.cast(response); httpresponse.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); httpresponse.setHeader("Access-Control-Allow-Credentials", "true"); httpresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unsupported or Malformed JWT. Please provide a valid JWT."); } catch(SignatureException e) { HttpServletResponse httpresponse = HttpServletResponse.class.cast(response); httpresponse.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); httpresponse.setHeader("Access-Control-Allow-Credentials", "true"); httpresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Signature Exception. Please provide a valid JWT."); } catch(ExpiredJwtException e) { HttpServletResponse httpresponse = HttpServletResponse.class.cast(response); httpresponse.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); httpresponse.setHeader("Access-Control-Allow-Credentials", "true"); httpresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JWT has expired. Please obtain a new token."); } } else { HttpServletResponse httpresponse = HttpServletResponse.class.cast(response); httpresponse.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); httpresponse.setHeader("Access-Control-Allow-Credentials", "true"); httpresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, HttpHeaders.AUTHORIZATION + " Header is either not proivded or incorrectly formatted."); } } } try { MDC.put(USER_ATTRIBUTE_NAME, user); request.setAttribute(USER_ATTRIBUTE_NAME, user); chain.doFilter(request, response); } finally { MDC.remove(USER_ATTRIBUTE_NAME); } }
java
{ "resource": "" }
q163688
SubsystemSuspensionLevels.findBySubsystem
train
public static SubsystemSuspensionLevels findBySubsystem(EntityManager em, SubSystem subSystem) { SystemAssert.requireArgument(em != null, "Entity manager can not be null."); SystemAssert.requireArgument(subSystem != null, "Subsystem cannot be null."); TypedQuery<SubsystemSuspensionLevels> query = em.createNamedQuery("SubsystemSuspensionLevels.findBySubsystem", SubsystemSuspensionLevels.class); try { query.setParameter("subSystem", subSystem); return query.getSingleResult(); } catch (NoResultException ex) { Map<Integer, Long> levels = new HashMap<>(); levels.put(1, 60 * 60 * 1000L); levels.put(2, 10 * 60 * 60 * 1000L); levels.put(3, 24 * 60 * 60 * 1000L); levels.put(4, 3 * 24 * 60 * 60 * 1000L); levels.put(5, 10 * 24 * 60 * 60 * 1000L); SubsystemSuspensionLevels suspensionLevels = new SubsystemSuspensionLevels(null, subSystem, levels); return em.merge(suspensionLevels); } }
java
{ "resource": "" }
q163689
SubsystemSuspensionLevels.getSuspensionLevelsBySubsystem
train
public static Map<Integer, Long> getSuspensionLevelsBySubsystem(EntityManager em, SubSystem subSystem) { return findBySubsystem(em, subSystem).getLevels(); }
java
{ "resource": "" }
q163690
SubsystemSuspensionLevels.setLevels
train
public void setLevels(Map<Integer, Long> levels) { SystemAssert.requireArgument(levels != null, "Levels cannot be null"); this.levels.clear(); this.levels.putAll(levels); }
java
{ "resource": "" }
q163691
SystemMain.getInstance
train
public static SystemMain getInstance(Properties config) { return Guice.createInjector(new SystemInitializer(config)).getInstance(SystemMain.class); }
java
{ "resource": "" }
q163692
SystemMain.doStart
train
@Override protected void doStart() { try { String build = _configuration.getValue(SystemConfiguration.Property.BUILD); String version = _configuration.getValue(SystemConfiguration.Property.VERSION); String year = new SimpleDateFormat("yyyy").format(new Date()); _log.info("Argus version {} build {}.", version, build); _log.info("Copyright Salesforce.com, {}.", year); _log.info("{} started.", getName()); _persistService.start(); _serviceFactory.getUserService().findAdminUser(); _serviceFactory.getUserService().findDefaultUser(); } catch (Throwable ex) { _log.error(getName() + " startup aborted.", ex); } finally { _mergeServiceConfiguration(); _mergeNotifierConfiguration(); _log.info(_configuration.toString()); } }
java
{ "resource": "" }
q163693
SystemMain.doStop
train
@Override protected void doStop() { try { _dispose(_serviceFactory.getWardenService()); _dispose(_serviceFactory.getMonitorService()); _dispose(_serviceFactory.getSchedulingService()); _dispose(_serviceFactory.getGlobalInterlockService()); _dispose(_serviceFactory.getMQService()); _dispose(_serviceFactory.getSchemaService()); _dispose(_serviceFactory.getTSDBService()); _dispose(_serviceFactory.getCacheService()); _dispose(_serviceFactory.getHistoryService()); _persistService.stop(); _log.info("{} stopped.", getName()); } catch (Exception ex) { _log.error(getName() + " shutdown aborted.", ex); } }
java
{ "resource": "" }
q163694
MetricDto.transformToDto
train
public static MetricDto transformToDto(Metric metric) { if (metric == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } MetricDto result = createDtoObject(MetricDto.class, metric); return result; }
java
{ "resource": "" }
q163695
HBaseUtils._9sComplement
train
public static long _9sComplement(long creationTime) { String time = String.valueOf(creationTime); char[] timeArr = time.toCharArray(); StringBuilder sb = new StringBuilder(); for(char c : timeArr) { sb.append(9 - Character.getNumericValue(c)); } return Long.parseLong(sb.toString()); }
java
{ "resource": "" }
q163696
DashboardService.getDashboard
train
public Dashboard getDashboard(BigInteger dashboardId) throws IOException, TokenExpiredException { String requestUrl = RESOURCE + "/" + dashboardId.toString(); ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.GET, requestUrl, null); assertValidResponse(response, requestUrl); return fromJson(response.getResult(), Dashboard.class); }
java
{ "resource": "" }
q163697
MetricFilterWithInteralReducerTransform.internalReducer
train
public static String internalReducer(Metric metric, String reducerType) { Map<Long, Double> sortedDatapoints = new TreeMap<>(); List<Double> operands = new ArrayList<Double>(); if(!reducerType.equals(InternalReducerType.NAME.getName())) { if(metric.getDatapoints()!=null && metric.getDatapoints().size()>0) { sortedDatapoints.putAll(metric.getDatapoints()); for (Double value : sortedDatapoints.values()) { if (value == null) { operands.add(0.0); } else { operands.add(value); } } }else { return null; } } InternalReducerType type = InternalReducerType.fromString(reducerType); switch (type) { case AVG: return String.valueOf((new Mean()).evaluate(Doubles.toArray(operands))); case MIN: return String.valueOf(Collections.min(operands)); case MAX: return String.valueOf(Collections.max(operands)); case RECENT: return String.valueOf(operands.get(operands.size() - 1)); case MAXIMA: return String.valueOf(Collections.max(operands)); case MINIMA: return String.valueOf(Collections.min(operands)); case NAME: return metric.getMetric(); case DEVIATION: return String.valueOf((new StandardDeviation()).evaluate(Doubles.toArray(operands))); default: throw new UnsupportedOperationException(reducerType); } }
java
{ "resource": "" }
q163698
MetricFilterWithInteralReducerTransform.sortByValue
train
public static Map<Metric, String> sortByValue(Map<Metric, String> map, final String reducerType) { List<Map.Entry<Metric, String>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<Metric, String>>() { @Override public int compare(Map.Entry<Metric, String> o1, Map.Entry<Metric, String> o2) { if(reducerType.equals("name")) { return o1.getValue().compareTo(o2.getValue()); } Double d1 = Double.parseDouble(o1.getValue()); Double d2 = Double.parseDouble(o2.getValue()); return (d1.compareTo(d2)); } }); Map<Metric, String> result = new LinkedHashMap<>(); for (Map.Entry<Metric, String> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; }
java
{ "resource": "" }
q163699
NotificationDto.transformToDto
train
public static NotificationDto transformToDto(Notification notification) { if (notification == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } NotificationDto result = createDtoObject(NotificationDto.class, notification); result.setAlertId(notification.getAlert().getId()); for (Trigger trigger : notification.getTriggers()) { result.addTriggersIds(trigger); } return result; }
java
{ "resource": "" }