code
stringlengths
73
34.1k
label
stringclasses
1 value
@MainThread private void handleUnRegistration(Object targetObj) { if (targetObj == null) { throw new NullPointerException("Target cannot be null"); } EventTarget target = null; for (Iterator<EventTarget> iterator = targets.iterator(); iterator.hasNext(); ) { EventTarget listTarget = iterator.next(); if (listTarget.targetObj == targetObj) { iterator.remove(); target = listTarget; target.targetObj = null; break; } } if (target == null) { Utils.logE(targetObj, "Was not registered"); } Utils.log(targetObj, "Unregistered"); }
java
@MainThread private void handleEventPost(Event event) { Utils.log(event.getKey(), "Handling posted event"); int sizeBefore = executionQueue.size(); scheduleStatusUpdates(event, EventStatus.STARTED); scheduleSubscribersInvocation(event); if (((EventBase) event).handlersCount == 0) { Utils.log(event.getKey(), "No subscribers found"); // Removing all scheduled STARTED status callbacks while (executionQueue.size() > sizeBefore) { executionQueue.removeLast(); } } else { activeEvents.add(event); executeTasks(false); } }
java
@MainThread private void handleEventResult(Event event, EventResult result) { if (!activeEvents.contains(event)) { Utils.logE(event.getKey(), "Cannot send result of finished event"); return; } scheduleResultCallbacks(event, result); executeTasks(false); }
java
@MainThread private void handleEventFailure(Event event, EventFailure failure) { if (!activeEvents.contains(event)) { Utils.logE(event.getKey(), "Cannot send failure callback of finished event"); return; } scheduleFailureCallbacks(event, failure); executeTasks(false); }
java
@MainThread private void handleTaskFinished(Task task) { if (task.method.type != EventMethod.Type.SUBSCRIBE) { // We are not interested in finished callbacks, only finished subscriber calls return; } if (task.method.isSingleThread) { Utils.log(task, "Single-thread method is no longer in use"); task.method.isInUse = false; } Event event = task.event; if (!activeEvents.contains(event)) { Utils.logE(event.getKey(), "Cannot finish already finished event"); return; } ((EventBase) event).handlersCount--; if (((EventBase) event).handlersCount == 0) { // No more running handlers activeEvents.remove(event); scheduleStatusUpdates(event, EventStatus.FINISHED); executeTasks(false); } }
java
@MainThread private void handleTasksExecution() { if (isExecuting || executionQueue.isEmpty()) { return; // Nothing to dispatch } try { isExecuting = true; handleTasksExecutionWrapped(); } finally { isExecuting = false; } }
java
public static <T> ValueLabel<T> create (Value<T> value, String... styles) { return new ValueLabel<T>(value, styles); }
java
private boolean isApply(ChangeSet changeSet) { // 必须包含 PENDING_DROPS 不然无法在只删除列时产生变更脚本 return (changeSet.getType() == ChangeSetType.APPLY || changeSet.getType() == ChangeSetType.PENDING_DROPS) && !changeSet.getChangeSetChildren().isEmpty(); }
java
protected void writeApplyDdl(DdlWrite write) { scriptInfo.setApplyDdl( "-- drop dependencies\n" + write.applyDropDependencies().getBuffer() + "\n" + "-- apply changes\n" + write.apply().getBuffer() + write.applyForeignKeys().getBuffer() + write.applyHistoryView().getBuffer() + write.applyHistoryTrigger().getBuffer() ); }
java
public void show (PopupPanel popup, Widget onCenter) { // determine the ypos of our onCenter target in case it's in the currently popped up popup, // because after we hide that popup we won't be able to compute it int ypos = (onCenter == null) ? 0 : (onCenter.getAbsoluteTop() + onCenter.getOffsetHeight()/2); PopupPanel showing = _showingPopup.get(); if (showing != null) { // null _showingPopup before hiding to avoid triggering the close handler logic _popups.add(showing); _showingPopup.update(null); showing.hide(true); } if (onCenter == null) { popup.center(); // this will show the popup } else { Popups.centerOn(popup, ypos).show(); } // now that we've centered and shown our popup (which may have involved showing, hiding and // showing it again), we can add a close handler and listen for it to actually close popup.addCloseHandler(new CloseHandler<PopupPanel>() { public void onClose (CloseEvent<PopupPanel> event) { if (_showingPopup.get() == event.getTarget()) { if (_popups.size() > 0) { _showingPopup.update(_popups.remove(_popups.size()-1)); _showingPopup.get().show(); } else { _showingPopup.update(null); } } } }); _showingPopup.update(popup); }
java
public void clear () { _popups.clear(); if (_showingPopup.get() != null) { _showingPopup.get().hide(true); _showingPopup.update(null); } }
java
public static String escapeAttribute (String value) { for (int ii = 0; ii < ATTR_ESCAPES.length; ++ii) { value = value.replace(ATTR_ESCAPES[ii][0], ATTR_ESCAPES[ii][1]); } return value; }
java
public static String sanitizeAttribute (String value) { for (int ii = 0; ii < ATTR_ESCAPES.length; ++ii) { value = value.replace(ATTR_ESCAPES[ii][0], ""); } return value; }
java
public static String truncate (String str, int limit, String appendage) { if (str == null || str.length() <= limit) { return str; } return str.substring(0, limit - appendage.length()) + appendage; }
java
public static String join (Iterable<?> items, String sep) { Iterator<?> i = items.iterator(); if (!i.hasNext()) { return ""; } StringBuilder buf = new StringBuilder(String.valueOf(i.next())); while (i.hasNext()) { buf.append(sep).append(i.next()); } return buf.toString(); }
java
public String createDefinition (WidgetUtil.FlashObject obj) { String transparent = obj.transparent ? "transparent" : "opaque"; String params = "<param name=\"movie\" value=\"" + obj.movie + "\">" + "<param name=\"allowFullScreen\" value=\"true\">" + "<param name=\"wmode\" value=\"" + transparent + "\">" + "<param name=\"bgcolor\" value=\"" + obj.bgcolor + "\">"; if (obj.flashVars != null) { params += "<param name=\"FlashVars\" value=\"" + obj.flashVars + "\">"; } String tag = "<object id=\"" + obj.ident + "\" type=\"application/x-shockwave-flash\""; if (obj.width.length() > 0) { tag += " width=\"" + obj.width + "\""; } if (obj.height.length() > 0) { tag += " height=\"" + obj.height + "\""; } tag += " allowFullScreen=\"true\" allowScriptAccess=\"sameDomain\">" + params + "</object>"; return tag; }
java
public HTML createApplet (String ident, String archive, String clazz, String width, String height, boolean mayScript, String ptags) { String html = "<object classid=\"java:" + clazz + ".class\" " + "type=\"application/x-java-applet\" archive=\"" + archive + "\" " + "width=\"" + width + "\" height=\"" + height + "\">"; if (mayScript) { html += "<param name=\"mayscript\" value=\"true\"/>"; } html += ptags; html += "</object>"; return new HTML(html); }
java
@Override public void run() { synchronized (lock) { if (!callables.hasNext()) { checkEnd(); return; } for (int i = 0; i < parallelism && callables.hasNext(); i++) { setupNext(callables.next()); } } future.whenCancelled(() -> { cancel = true; checkNext(); }); }
java
public static HandlerRegistration bind (HasKeyDownHandlers target, ClickHandler onEnter) { return target.addKeyDownHandler(new EnterClickAdapter(onEnter)); }
java
public void onKeyDown (KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { _onEnter.onClick(null); } }
java
boolean isMatch(Class<?> beanType, Object id) { return beanType.equals(this.beanType) && idMatch(id); }
java
public static void set (String path, int expires, String name, String value, String domain) { String extra = ""; if (path.length() > 0) { extra += "; path=" + path; } if (domain != null) { extra += "; domain=" + domain; } doSet(name, value, expires, extra); }
java
public void show (Popups.Position pos, Widget target) { Popups.show(this, pos, target); }
java
public String get (String key, Object... args) { // First make the key for GWT-friendly return fetch(key.replace('.', '_'), args); }
java
@Deprecated public static void configure (TextBoxBase target, String defaultText) { DefaultTextListener listener = new DefaultTextListener(target, defaultText); target.addFocusHandler(listener); target.addBlurHandler(listener); }
java
@Deprecated public static String getText (TextBoxBase target, String defaultText) { String text = target.getText().trim(); return text.equals(defaultText.trim()) ? "" : text; }
java
public void onBlur (BlurEvent event) { if (_target.getText().trim().equals("")) { _target.setText(_defaultText); } }
java
static Object workObject(Map<String, Object> workList, String name, boolean isArray) { logger.trace("get working object for {}", name); if (workList.get(name) != null) return workList.get(name); else { String[] parts = splitName(name); // parts: (parent, name, isArray) Map<String, Object> parentObj = (Map<String, Object>) workObject(workList, parts[0], false); Object theObj = isArray ? new ArrayList<String>() : new HashMap<String, Object>(); parentObj.put(parts[1], theObj); workList.put(name, theObj); return theObj; } }
java
public static <T> Constraint checking(Function<String, T> check, String messageOrKey, boolean isKey, String... extraMessageArgs) { return mkSimpleConstraint(((label, vString, messages) -> { logger.debug("checking for {}", vString); if (isEmptyStr(vString)) return null; else { try { check.apply(vString); return null; } catch (Exception ex) { String msgTemplate = isKey ? messages.get(messageOrKey) : messageOrKey; List<String> messageArgs = appendList(Arrays.asList(vString), extraMessageArgs); return String.format(msgTemplate, messageArgs.toArray()); } } }), null); }
java
public static Constraint anyPassed(Constraint... constraints) { return ((name, data, messages, options) -> { logger.debug("checking any passed for {}", name); List<Map.Entry<String, String>> errErrors = new ArrayList<>(); for(Constraint constraint : constraints) { List<Map.Entry<String, String>> errors = constraint.apply(name, data, messages, options); if (errors.isEmpty()) return Collections.emptyList(); else { errErrors.addAll(errors); } } String label = getLabel(name, messages, options); String errStr = errErrors.stream().map(e -> e.getValue()) .collect(Collectors.joining(", ", "[", "]")); return Arrays.asList(entry(name, String.format(messages.get("error.anypassed"), label, errStr))); }); }
java
public static List<Integer> indexes(String name, Map<String, String> data) { logger.debug("get indexes for {}", name); // matches: 'prefix[index]...' Pattern keyPattern = Pattern.compile("^" + Pattern.quote(name) + "\\[(\\d+)\\].*$"); return data.keySet().stream() .map(key -> { Matcher m = keyPattern.matcher(key); return m.matches() ? Integer.parseInt(m.group(1)) : -1; }).filter(i -> i >= 0) .distinct() .sorted() .collect(Collectors.toList()); }
java
public static List<String> keys(String prefix, Map<String, String> data) { logger.debug("get keys for {}", prefix); // matches: 'prefix.xxx...' | 'prefix."xxx.t"...' Pattern keyPattern = Pattern.compile("^" + Pattern.quote(prefix) + "\\.(\"[^\"]+\"|[^\\.]+).*$"); return data.keySet().stream() .map(key -> { Matcher m = keyPattern.matcher(key); return m.matches() ? m.group(1) : null; }).filter(k -> k != null) .distinct() .collect(Collectors.toList()); }
java
public static Map<String, String> json2map(String prefix, JsonNode json) { logger.trace("json to map - prefix: {}", prefix); if (json.isArray()) { Map<String, String> result = new HashMap<>(); for(int i=0; i <json.size(); i++) { result.putAll(json2map(prefix +"["+i+"]", json.get(i))); } return result; } else if (json.isObject()) { Map<String, String> result = new HashMap<>(); json.fields().forEachRemaining(e -> { String newPrefix = isEmptyStr(prefix) ? e.getKey() : prefix + "." + e.getKey(); result.putAll(json2map(newPrefix, e.getValue())); }); return result; } else { return newmap(entry(prefix, json.asText())); } }
java
private String getVersion(MigrationModel migrationModel) { String version = migrationConfig.getVersion(); if (version == null) { version = migrationModel.getNextVersion(initialVersion); } return version; }
java
public <T> Predicate<T> in (final Collection<? extends T> target) { return new Predicate<T>() { public boolean apply (T arg) { try { return target.contains(arg); } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } }; }
java
public CommandResponse doVagrant(String vagrantVm, final String... vagrantCommand) { CommandResponse response = commandProcessor.run( aCommand("vagrant").withArguments(vagrantCommand).withOptions(vagrantVm) ); if(!response.isSuccessful()) { throw new RuntimeException("Errors during vagrant execution: \n" + response.getErrors()); } // Check for puppet errors. Not vagrant still returns 0 when puppet fails // May not be needed after this PR released: https://github.com/mitchellh/vagrant/pull/1175 for (String line : response.getOutput().split("\n\u001B")) { if (line.startsWith("[1;35merr:")) { throw new RuntimeException("Error in puppet output: " + line); } } return response; }
java
private LzoIndex readIndex(Path file, FileSystem fs) throws IOException { FSDataInputStream indexIn = null; try { Path indexFile = new Path(file.toString() + LZO_INDEX_SUFFIX); if (!fs.exists(indexFile)) { // return empty index, fall back to the unsplittable mode return new LzoIndex(); } long indexLen = fs.getFileStatus(indexFile).getLen(); int blocks = (int) (indexLen / 8); LzoIndex index = new LzoIndex(blocks); indexIn = fs.open(indexFile); for (int i = 0; i < blocks; i++) { index.set(i, indexIn.readLong()); } return index; } finally { if (indexIn != null) { indexIn.close(); } } }
java
public static void createIndex(FileSystem fs, Path lzoFile) throws IOException { Configuration conf = fs.getConf(); CompressionCodecFactory factory = new CompressionCodecFactory(fs.getConf()); CompressionCodec codec = factory.getCodec(lzoFile); ((Configurable) codec).setConf(conf); InputStream lzoIs = null; FSDataOutputStream os = null; Path outputFile = new Path(lzoFile.toString() + LzoTextInputFormat.LZO_INDEX_SUFFIX); Path tmpOutputFile = outputFile.suffix(".tmp"); try { FSDataInputStream is = fs.open(lzoFile); os = fs.create(tmpOutputFile); LzopDecompressor decompressor = (LzopDecompressor) codec .createDecompressor(); // for reading the header lzoIs = codec.createInputStream(is, decompressor); int numChecksums = decompressor.getChecksumsCount(); while (true) { // read and ignore, we just want to get to the next int int uncompressedBlockSize = is.readInt(); if (uncompressedBlockSize == 0) { break; } else if (uncompressedBlockSize < 0) { throw new EOFException(); } int compressedBlockSize = is.readInt(); if (compressedBlockSize <= 0) { throw new IOException("Could not read compressed block size"); } long pos = is.getPos(); // write the pos of the block start os.writeLong(pos - 8); // seek to the start of the next block, skip any checksums is.seek(pos + compressedBlockSize + (4 * numChecksums)); } } finally { if (lzoIs != null) { lzoIs.close(); } if (os != null) { os.close(); } } fs.rename(tmpOutputFile, outputFile); }
java
public static List<Domain> getDefinedDomains(Connect libvirt) { try { List<Domain> domains = new ArrayList<>(); String[] domainNames = libvirt.listDefinedDomains(); for (String name : domainNames) { domains.add(libvirt.domainLookupByName(name)); } return domains; } catch (LibvirtException e) { throw new LibvirtRuntimeException("Unable to list defined domains", e); } }
java
public static List<Domain> getRunningDomains(Connect libvirt) { try { List<Domain> domains = new ArrayList<>(); int[] ids = libvirt.listDomains(); for (int id : ids) { domains.add(libvirt.domainLookupByID(id)); } return domains; } catch (LibvirtException e) { throw new LibvirtRuntimeException("Unable to list defined domains", e); } }
java
public static Connect getConnection(String libvirtURL, boolean readOnly) { connectLock.lock(); try { return new Connect(libvirtURL, readOnly); } catch (LibvirtException e) { throw new LibvirtRuntimeException("Unable to connect to " + libvirtURL, e); } finally { connectLock.unlock(); } }
java
public void addInstance(Object instance) throws Exception { if (isDestroyed()) { throw new IllegalStateException("System already stopped"); } else { startInstance(instance); if (methodsMap.get(instance.getClass()).hasFor(PreDestroy.class)) { managedInstances.add(instance); } } }
java
public static <T> T bind (T service, String entryPoint) { ((ServiceDefTarget)service).setServiceEntryPoint(entryPoint); return service; }
java
@SuppressWarnings("deprecation") public static Date toUtc (Date date) { if (date == null) { return null; } return new Date(Date.UTC(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); }
java
public void add(final Metric metric) { Preconditions.checkNotNull(metric); // get the aggregate for this minute MetricAggregate aggregate = getAggregate(metric.getIdentity()); // add the current metric into the aggregate switch (metric.getIdentity().getType()) { case COUNTER: case TIMER: case AVERAGE: aggregate.setCount(aggregate.getCount() + 1); aggregate.setValue(aggregate.getValue() + metric.getValue()); break; case GAUGE: aggregate.setCount(1); if (metric.isIncrement()) { aggregate.setValue(aggregate.getValue() + metric.getValue()); } else { aggregate.setValue(metric.getValue()); } break; default: LOGGER.info("Unable to aggregate {} metric type", metric.getIdentity().getType()); break; } }
java
private boolean aggregateExistsForCurrentMinute(final MetricIdentity identity) { Preconditions.checkNotNull(identity); if (aggregates.containsKey(identity)) { if (aggregates.get(identity).containsKey(currentMinute)) { return true; } } return false; }
java
private MetricAggregate getAggregate(final MetricIdentity identity) { // get the map from utc minute to aggregate for this metric if (!aggregates.containsKey(identity)) { aggregates.put(identity, new HashMap<Long, MetricAggregate>()); } Map<Long, MetricAggregate> metricAggregates = aggregates.get(identity); // get the aggregate for this minute if (!metricAggregates.containsKey(currentMinute)) { MetricAggregate initialAggregate = MetricAggregate.fromMetricIdentity(identity, currentMinute); if (identity.getType().equals(MetricMonitorType.GAUGE)) { if (lastValues.containsKey(identity)) { initialAggregate.setValue(lastValues.get(identity)); } } metricAggregates.put(currentMinute, initialAggregate); } MetricAggregate aggregate = metricAggregates.get(currentMinute); return aggregate; }
java
public static <L> ListenerList<L> addListener (ListenerList<L> list, L listener) { if (list == null) { list = new ListenerList<L>(); } list.add(listener); return list; }
java
public static <L, K> void addListener (Map<K, ListenerList<L>> map, K key, L listener) { ListenerList<L> list = map.get(key); if (list == null) { map.put(key, list = new ListenerList<L>()); } list.add(listener); }
java
public static <L, K> void removeListener (Map<K, ListenerList<L>> map, K key, L listener) { ListenerList<L> list = map.get(key); if (list != null) { list.remove(listener); } }
java
public Migration read() { try (StringReader reader = new StringReader(info.getModelDiff())) { JAXBContext jaxbContext = JAXBContext.newInstance(Migration.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); return (Migration) unmarshaller.unmarshal(reader); } catch (JAXBException e) { throw new RuntimeException(e); } }
java
void add(final byte type, final Object value) { final int w = write.getAndIncrement(); if (w < size) { writeAt(w, type, value); } // countdown could wrap around, however we check the state of finished in here. // MUST be called after write to make sure that results and states are synchronized. final int c = countdown.decrementAndGet(); if (c < 0) { throw new IllegalStateException("already finished (countdown)"); } // if this thread is not the last thread to check-in, do nothing.. if (c != 0) { return; } // make sure this can only happen once. // This protects against countdown, and write wrapping around which should very rarely // happen. if (!done.compareAndSet(false, true)) { throw new IllegalStateException("already finished"); } done(collect()); }
java
public static synchronized void configure(final ApiConfiguration config) { ApiConfiguration.Builder builder = ApiConfiguration.newBuilder(); builder.apiUrl(config.getApiUrl()); builder.apiKey(config.getApiKey()); builder.application(config.getApplication()); builder.environment(config.getEnvironment()); if (config.getEnvDetail() == null) { builder.envDetail(EnvironmentDetails.getEnvironmentDetail(config.getApplication(), config.getEnvironment())); } else { builder.envDetail(config.getEnvDetail()); } CONFIG = builder.build(); }
java
private static synchronized void startup() { try { if (CONFIG == null) { CONFIG = ApiConfigurations.fromProperties(); } ObjectMapper objectMapper = new ObjectMapper(); AppIdentityService appIdentityService = new AppIdentityService(CONFIG, objectMapper, true); MetricMonitorService monitorService = new MetricMonitorService(CONFIG, objectMapper, appIdentityService); MetricSender sender = new MetricSender(CONFIG, objectMapper, monitorService); BACKGROUND_SERVICE = new MetricBackgroundService(COLLECTOR, sender); BACKGROUND_SERVICE.start(); } catch (Throwable t) { LOGGER.error("Exception starting Stackify Metrics API service", t); } }
java
public static synchronized void shutdown() { if (BACKGROUND_SERVICE != null) { try { BACKGROUND_SERVICE.stop(); } catch (Throwable t) { LOGGER.error("Exception stopping Stackify Metrics API service", t); } INITIALIZED.compareAndSet(true, false); } }
java
public <T> WithStaticFinder<T> withFinder(Class<T> beanType) { WithStaticFinder<T> withFinder = new WithStaticFinder<>(beanType); staticFinderReplacement.add(withFinder); return withFinder; }
java
RunnablePair takeAndClear() { RunnablePair entries; while ((entries = callbacks.get()) != END) { if (callbacks.compareAndSet(entries, END)) { return entries; } } return null; }
java
boolean add(Runnable runnable) { int spins = 0; RunnablePair entries; while ((entries = callbacks.get()) != END) { if (callbacks.compareAndSet(entries, new RunnablePair(runnable, entries))) { return true; } if (spins++ > MAX_SPINS) { Thread.yield(); spins = 0; } } return false; }
java
@SuppressWarnings("unchecked") T result(final Object r) { return (T) (r == NULL ? null : r); }
java
public static HTML createTransparentFlashContainer ( String ident, String movie, int width, int height, String flashVars) { FlashObject obj = new FlashObject(ident, movie, width, height, flashVars); obj.transparent = true; return createContainer(obj); }
java
public static HTML createFlashContainer ( String ident, String movie, int width, int height, String flashVars) { return createContainer(new FlashObject(ident, movie, width, height, flashVars)); }
java
public static String ensurePixels (String value) { int index = 0; for (int nn = value.length(); index < nn; index++) { char c = value.charAt(index); if (c < '0' || c > '9') { break; } } return value.substring(0, index); }
java
public static synchronized boolean isNativeLzoLoaded(Configuration conf) { if (!nativeLzoChecked) { if (GPLNativeCodeLoader.isNativeCodeLoaded()) { nativeLzoLoaded = LzoCompressor.isNativeLzoLoaded() && LzoDecompressor.isNativeLzoLoaded(); if (nativeLzoLoaded) { LOG.info("Successfully loaded & initialized native-lzo library"); } else { LOG.error("Failed to load/initialize native-lzo library"); } } else { LOG.error("Cannot load native-lzo without native-hadoop"); } nativeLzoChecked = true; } return nativeLzoLoaded && conf.getBoolean("hadoop.native.lib", true); }
java
@RequestMapping(path = "", method = RequestMethod.GET) public List<Product> getProducts(){ return productService.getProducts(); }
java
@RequestMapping(path = "/{productId}", method=RequestMethod.GET) public ResponseEntity<Product> getCustomer(@PathVariable("productId") Long productId){ Product product = productService.getProduct(productId); if(product != null){ return new ResponseEntity<Product>(product, HttpStatus.OK); } return new ResponseEntity<Product>(HttpStatus.NOT_FOUND); }
java
public Number getNumber () { String valstr = getText().length() == 0 ? "0" : getText(); return _allowFloatingPoint ? (Number)(new Double(valstr)) : (Number)(new Long(valstr)); }
java
public void send(final List<MetricAggregate> aggregates) throws IOException, HttpException { HttpClient httpClient = new HttpClient(apiConfig); // retransmit any metrics on the resend queue resendQueue.drain(httpClient, "/Metrics/SubmitMetricsByID"); // build the json objects List<JsonMetric> metrics = new ArrayList<JsonMetric>(aggregates.size()); for (MetricAggregate aggregate : aggregates) { Integer monitorId = monitorService.getMonitorId(aggregate.getIdentity()); if (monitorId != null) { JsonMetric.Builder builder = JsonMetric.newBuilder(); builder.monitorId(monitorId); builder.value(Double.valueOf(aggregate.getValue())); builder.count(Integer.valueOf(aggregate.getCount())); builder.occurredUtc(new Date(aggregate.getOccurredMillis())); builder.monitorTypeId(Integer.valueOf(aggregate.getIdentity().getType().getId())); builder.clientDeviceId(monitorService.getDeviceId()); metrics.add(builder.build()); } else { LOGGER.info("Unable to determine monitor id for aggregate metric {}", aggregate); } } if (metrics.isEmpty()) { return; } // post metrics to stackify byte[] jsonBytes = objectMapper.writer().writeValueAsBytes(metrics); try { httpClient.post("/Metrics/SubmitMetricsByID", jsonBytes); } catch (IOException t) { LOGGER.info("Queueing metrics for retransmission due to IOException"); resendQueue.offer(jsonBytes, t); throw t; } catch (HttpException t) { LOGGER.info("Queueing metrics for retransmission due to HttpException"); resendQueue.offer(jsonBytes, t); throw t; } }
java
public static Value<Boolean> not (Value<Boolean> value) { return value.map(Functions.NOT); }
java
protected static boolean computeAnd (Iterable<Value<Boolean>> values) { for (Value<Boolean> value : values) { if (!value.get()) { return false; } } return true; }
java
public static ClickHandler chain (final ClickHandler... handlers) { return new ClickHandler() { public void onClick (ClickEvent event) { for (ClickHandler handler : handlers) { try { handler.onClick(event); } catch (Exception e) { Console.log("Chained click handler failed", "handler", handler, e); } } } }; }
java
@RequestMapping(path = "", method = RequestMethod.GET) public Page<Customer> getCustomers(Pageable pageable){ return customerService.getCustomers(pageable); }
java
@RequestMapping(path = "/{customerId}", method=RequestMethod.GET) public ResponseEntity<Customer> getCustomer(@PathVariable("customerId") Long customerId, @RequestParam(required=true) String name){ Customer customer = customerService.getCustomer(customerId); if(customer != null){ return new ResponseEntity<Customer>(customer, HttpStatus.OK); } return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND); }
java
@RequestMapping(path = "/{customerId}", method = RequestMethod.DELETE) public ResponseEntity removeCustomer(@PathVariable("customerId") Long customerId){ boolean succeed = customerService.removeCustomer(customerId); if(succeed){ return new ResponseEntity(HttpStatus.OK); }else{ return new ResponseEntity(HttpStatus.NOT_FOUND); } }
java
@SafeVarargs private static void checkNoAnnotations(Method method, Class<? extends Annotation> foundAn, Class<? extends Annotation>... disallowedAn) { for (Class<? extends Annotation> an : disallowedAn) { if (method.isAnnotationPresent(an)) { throw new EventsException("Method " + Utils.methodToString(method) + " marked with @" + foundAn.getSimpleName() + " cannot be marked with @" + an.getSimpleName()); } } }
java
private static CacheProvider getCacheProvider(Method javaMethod) { if (!javaMethod.isAnnotationPresent(Cache.class)) { return null; } Cache an = javaMethod.getAnnotation(Cache.class); Class<? extends CacheProvider> cacheClazz = an.value(); try { Constructor<? extends CacheProvider> constructor = cacheClazz.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (Exception e) { throw new EventsException("Cannot instantiate cache provider " + cacheClazz.getSimpleName() + " for method " + Utils.methodToString(javaMethod), e); } }
java
protected void submit(final double value, final boolean isIncrement) { MetricCollector collector = MetricManager.getCollector(); if (collector != null) { Metric.Builder builder = Metric.newBuilder(); builder.identity(identity); builder.value(value); builder.isIncrement(isIncrement); Metric metric = builder.build(); collector.submit(metric); } }
java
protected void autoReportZero() { MetricCollector collector = MetricManager.getCollector(); if (collector != null) { collector.autoReportZero(identity); } }
java
protected void autoReportLast() { MetricCollector collector = MetricManager.getCollector(); if (collector != null) { collector.autoReportLast(identity); } }
java
public static MozuUrl updateLocalizedContentsUrl(String attributeFQN) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/LocalizedContent"); formatter.formatUrl("attributeFQN", attributeFQN); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl updateLocalizedContentUrl(String attributeFQN, String localeCode, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/LocalizedContent/{localeCode}?responseFields={responseFields}"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("localeCode", localeCode); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deleteLocalizedContentUrl(String attributeFQN, String localeCode) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/LocalizedContent/{localeCode}"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("localeCode", localeCode); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl applyCouponUrl(String checkoutId, String couponCode, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/checkouts/{checkoutId}/coupons/{couponCode}?responseFields={responseFields}"); formatter.formatUrl("checkoutId", checkoutId); formatter.formatUrl("couponCode", couponCode); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl removeCouponUrl(String checkoutId, String couponCode) { UrlFormatter formatter = new UrlFormatter("/api/commerce/checkouts/{checkoutId}/coupons/{couponcode}"); formatter.formatUrl("checkoutId", checkoutId); formatter.formatUrl("couponCode", couponCode); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getRandomAccessCursorUrl(String filter, Integer pageSize, String query, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/productsearch/randomAccessCursor/?query={query}&filter={filter}&pageSize={pageSize}&responseFields={responseFields}"); formatter.formatUrl("filter", filter); formatter.formatUrl("pageSize", pageSize); formatter.formatUrl("query", query); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getAccountNotesUrl(Integer accountId, String filter, Integer pageSize, String responseFields, String sortBy, Integer startIndex) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/notes?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&responseFields={responseFields}"); formatter.formatUrl("accountId", accountId); formatter.formatUrl("filter", filter); formatter.formatUrl("pageSize", pageSize); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("sortBy", sortBy); formatter.formatUrl("startIndex", startIndex); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl addAccountNoteUrl(Integer accountId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/notes?responseFields={responseFields}"); formatter.formatUrl("accountId", accountId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl updateAccountNoteUrl(Integer accountId, Integer noteId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/notes/{noteId}?responseFields={responseFields}"); formatter.formatUrl("accountId", accountId); formatter.formatUrl("noteId", noteId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deleteAccountNoteUrl(Integer accountId, Integer noteId) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/notes/{noteId}"); formatter.formatUrl("accountId", accountId); formatter.formatUrl("noteId", noteId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getFacetsUrl(String documentListName, String propertyName) { UrlFormatter formatter = new UrlFormatter("/api/content/documentlists/{documentListName}/facets/{propertyName}"); formatter.formatUrl("documentListName", documentListName); formatter.formatUrl("propertyName", propertyName); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getAttributeVocabularyValueLocalizedContentsUrl(String attributeFQN, String value) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues/{value}/LocalizedContent"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("value", value); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl addAttributeVocabularyValueUrl(String attributeFQN, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues?responseFields={responseFields}"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl updateAttributeVocabularyValueUrl(String attributeFQN, String responseFields, String value) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues/{value}?responseFields={responseFields}"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("value", value); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deleteAttributeVocabularyValueLocalizedContentUrl(String attributeFQN, String localeCode, String value) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues/{value}/LocalizedContent/{localeCode}"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("localeCode", localeCode); formatter.formatUrl("value", value); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl updateCheckoutAttributeUrl(String checkoutId, Boolean removeMissing) { UrlFormatter formatter = new UrlFormatter("/api/commerce/checkouts/{checkoutId}/attributes?removeMissing={removeMissing}"); formatter.formatUrl("checkoutId", checkoutId); formatter.formatUrl("removeMissing", removeMissing); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl createDeveloperUserAuthTicketUrl(Integer developerAccountId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/platform/developer/authtickets/?developerAccountId={developerAccountId}&responseFields={responseFields}"); formatter.formatUrl("developerAccountId", developerAccountId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ; }
java
@RequestMapping(value = "/tenants", method = RequestMethod.GET) public String getTenants(@RequestParam ("tenantId") Integer tenantId, Locale locale, ModelMap modelMap, Model model) { AuthenticationProfile authenticationProfile = (AuthenticationProfile)modelMap.get("tenantAuthorization"); //if there is no active user, go to the auth page. if (authenticationProfile == null) { setupHomePage (locale, model); return "home"; } // if no tenant id was supplied just use the active tenantID in the user auth. if (tenantId == null) { tenantId = authenticationProfile.getActiveScope().getId(); } // we need to get a new auth ticket for the tenant and update the authenticationProfile in session. if (tenantId != null && !tenantId.equals(authenticationProfile.getActiveScope().getId())) { authenticationProfile = UserAuthenticator.refreshUserAuthTicket(authenticationProfile.getAuthTicket(), tenantId); model.addAttribute("tenantAuthorization", authenticationProfile); } // Authorize user and get tenants List<Scope> tenants = authenticationProfile.getAuthorizedScopes(); if (tenants == null) { tenants = new ArrayList<Scope>(); tenants.add(authenticationProfile.getActiveScope()); } model.addAttribute("user", authenticationProfile.getUserProfile()); model.addAttribute("availableTenants", tenants); model.addAttribute("tenantId", tenantId); List<Site> sites = null; if (tenants != null && tenants.size() > 0) { sites = getAvailableTenantSites(tenantId); } else { sites = new ArrayList<Site>(); } model.addAttribute("sites", sites); return "tenants"; }
java
public static MozuUrl getTenantScopesForUserUrl(String responseFields, String userId) { UrlFormatter formatter = new UrlFormatter("/api/platform/adminuser/accounts/{userId}/tenants?responseFields={responseFields}"); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("userId", userId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ; }
java
public static MozuUrl getConfigurationUrl(String carrierId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/shipping/admin/carriers/{carrierId}?responseFields={responseFields}"); formatter.formatUrl("carrierId", carrierId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deleteConfigurationUrl(String carrierId) { UrlFormatter formatter = new UrlFormatter("/api/commerce/shipping/admin/carriers/{carrierId}"); formatter.formatUrl("carrierId", carrierId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getPackageUrl(String applicationKey, Boolean includeChildren, String responseFields, Boolean skipDevAccountCheck) { UrlFormatter formatter = new UrlFormatter("/api/platform/appdev/apppackages/{applicationKey}/?includeChildren={includeChildren}&skipDevAccountCheck={skipDevAccountCheck}&responseFields={responseFields}"); formatter.formatUrl("applicationKey", applicationKey); formatter.formatUrl("includeChildren", includeChildren); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("skipDevAccountCheck", skipDevAccountCheck); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java