code
stringlengths
73
34.1k
label
stringclasses
1 value
boolean checkAccessTopicGlobalAC(UserContext ctx, String topic) throws IllegalAccessException { logger.debug("Looking for accessController for topic '{}' from GlobalAccess", topic); Iterable<JsTopicAccessController> accessControls = topicAccessController.select(DEFAULT_AT); return checkAccessTopicFromControllers(...
java
boolean checkAccessTopicFromJsTopicAccessControllers(UserContext ctx, String topic, Iterable<JsTopicAccessController> controllers) throws IllegalAccessException { logger.debug("Looking for accessController for topic '{}' from JsTopicAccessControllers", topic); for (JsTopicAccessController jsTopicAccessController : ...
java
boolean checkAccessTopicFromController(UserContext ctx, String topic, JsTopicAccessController jsTopicAccessController) throws IllegalAccessException { logger.debug("Looking for accessController for topic '{}' from JsTopicAccessController {}", topic, jsTopicAccessController); JsTopicControls jsTopicControls = jsTopi...
java
boolean checkAccessTopicFromControllers(UserContext ctx, String topic, Iterable<JsTopicAccessController> accessControls) throws IllegalAccessException { logger.debug("Looking for accessController for topic '{}' : '{}'", topic, accessControls); boolean tacPresent = false; if (null != accessControls) { for (JsTo...
java
boolean isJsonPayload(Method method) { if(null == method || !method.isAnnotationPresent(JsTopic.class) ) { return false; } JsTopic jsTopic = method.getAnnotation(JsTopic.class); return jsTopic.jsonPayload(); }
java
JsTopicName getJsTopicNameAnnotation(Annotation[] parameterAnnotations) { for (Annotation parameterAnnotation : parameterAnnotations) { if (parameterAnnotation.annotationType().equals(JsTopicName.class)) { return (JsTopicName) parameterAnnotation; } } return null; }
java
String computeTopic(JsTopicName jsTopicName, String topic) { StringBuilder result = new StringBuilder(); if (!jsTopicName.prefix().isEmpty()) { result.append(jsTopicName.prefix()).append(Constants.Topic.COLON); } result.append(topic); if (!jsTopicName.postfix().isEmpty()) { result.append(Constant...
java
Object proceedAndSendMessage(InvocationContext ctx, String topic, boolean jsonPayload) throws Exception { MessageToClient messageToClient = new MessageToClient(); messageToClient.setId(topic); Object result = ctx.proceed(); if(jsonPayload) { if(!String.class.isInstance(result)) { throw new Unsuppor...
java
public ComplexPixel mult(double r, double i){ double thisr = real(), thisi = imag(); return setComplex(thisr*r-thisi*i, thisr*i+thisi*r); }
java
public static void savePrivateKey(OutputStream os, PrivateKey key, PrivateKeyEncoding encoding) throws IOException { switch (encoding) { case PKCS_1: savePrivateKeyPKCS1(os, key); break; case PKCS_8: savePrivateKeyPKCS8(os, key); break; default: throw new IllegalArgume...
java
private static void savePrivateKeyPKCS8(OutputStream os, PrivateKey key) throws IllegalArgumentException, IOException { CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, null); }
java
private static void savePrivateKeyPKCS1(OutputStream os, PrivateKey key) throws IllegalArgumentException, IOException { CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, new char[0], true); }
java
public static void saveProxyCredentials(String proxyFileName, X509Credential uc, PrivateKeyEncoding encoding) throws IOException { File f = new File(proxyFileName); RandomAccessFile raf = new RandomAccessFile(f, "rws"); FileChannel channel = raf.getChannel(); FilePermissionHelper.setProxyPer...
java
Collection<Session> getValidSessionsElseRemove(String httpid, Predicate<Session> predicat) { Collection<Session> wss = new ArrayList(); if(httpid_wss.containsKey(httpid)) { Collection<Session> befores = httpid_wss.get(httpid); for (Session before : befores) { if(predicat.test(before)) { wss.add(befor...
java
public static void checkPrivateKeyPermissions(String privateKeyFile) throws IOException { for (PosixFilePermission p : PRIVATE_KEY_PERMS) { try { matchesFilePermissions(privateKeyFile, p); return; } catch (FilePermissionError e) { } } final String errorMessage = Strin...
java
public static void matchesFilePermissions(String filename, PosixFilePermission p) throws IOException { filenameSanityChecks(filename); if (p == null) throw new NullPointerException("null permission passed as argument"); File f = new File(filename); // Don't get fooled by symlinks... St...
java
public String getMd5(String msg) { MessageDigest md; try { md = getMessageDigest(); byte[] hash = md.digest(msg.getBytes(StandardCharsets.UTF_8)); //converting byte array to Hexadecimal String StringBuilder sb = new StringBuilder(2 * hash.length); for (byte b : hash) { sb.append(String.fo...
java
Locale getLocale(HandshakeRequest request) { if(null != request) { Map<String, List<String>> headers = request.getHeaders(); if(null != headers) { List<String> accepts = headers.get(HttpHeaders.ACCEPT_LANGUAGE); logger.debug("Get accept-language from client headers : {}", accepts); if (null != accep...
java
@Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { sec.getUserProperties().put(Constants.HANDSHAKEREQUEST, request); super.modifyHandshake(sec, request, response); }
java
@Override public boolean sendMessageToClient(MessageFromClient message, Session client) { MessageToClient mtc = messageToClientService.createMessageToClient(message, client); if (mtc != null) { client.getAsyncRemote().sendObject(mtc); return true; } return false; }
java
protected void onBlock(ConnectionFilter filter, String remoteAddr, int connections, int requests, int bytes) { filter.disconnect(); filter.onDisconnect(); }
java
public void setParameters(int period, int connections, int requests, int bytes) { this.period = period; this.connections_ = connections; this.requests_ = requests; this.bytes_ = bytes; }
java
public void sendObjectToTopic(@Observes @JsTopicEvent("") Object payload, EventMetadata metadata) { MessageToClient msg = new MessageToClient(); InjectionPoint injectionPoint = metadata.getInjectionPoint(); Annotated annotated = injectionPoint.getAnnotated(); JsTopicEvent jte = annotated.getAnnotation(JsTop...
java
public void processJsCacheRemoveAll() { logger.debug("Process JsCacheRemoveAll annotation"); MessageToClient messageToClient = new MessageToClient(); messageToClient.setId(Constants.Cache.CLEANCACHE_TOPIC); messageToClient.setResponse(Constants.Cache.ALL); wsEvent.fire(messageToClient); }
java
public void processJsCacheRemove(JsCacheRemove jcr, List<String> paramNames, List<String> jsonArgs) { logger.debug("Process JsCacheRemove annotation : {}", jcr); MessageToClient messageToClient = new MessageToClient(); messageToClient.setId(Constants.Cache.CLEANCACHE_TOPIC); String argpart = cacheArgumentSe...
java
String computeCacheKey(Class cls, String methodName, String argpart) { String cachekey = keyMaker.getMd5(cls.getName() + "." + methodName); if (!argpart.isEmpty()) { cachekey += "_" + keyMaker.getMd5(argpart); } logger.debug("CACHEID : {}.{}_{} = {}", cls.getName(), methodName, argpart, cachekey); re...
java
public long processCacheAnnotations(Method nonProxiedMethod, List<String> parameters) { if (isJsCached(nonProxiedMethod)) { return jsCacheAnnotationServices.getJsCacheResultDeadline(nonProxiedMethod.getAnnotation(JsCacheResult.class)); } return 0L; }
java
boolean isJsCached(Method nonProxiedMethod) { boolean cached = nonProxiedMethod.isAnnotationPresent(JsCacheResult.class); logger.debug("The result of the method {} should be cached on client side {}.", nonProxiedMethod.getName(), cached); return cached; }
java
public void readDashboardRolesConfig(@Observes @Initialized(ApplicationScoped.class) ServletContext sc) { readFromConfigurationRoles(); readFromInitParameter(sc); logger.debug("'{}' value : '{}'.", Constants.Options.DASHBOARD_ROLES, roles); }
java
public Fault buildFault(Throwable ex) { Fault fault; int stacktracelength = configuration.getStacktracelength(); if (stacktracelength == 0 || logger.isDebugEnabled()) { logger.error("Invocation failed", ex); } fault = new Fault(ex, stacktracelength); return fault; }
java
public void print(final PrintStream out, final ICodingAnnotationStudy study, final ICodingAnnotationItem item) { Map<Object, Map<Object, Double>> coincidence = CodingAnnotationStudy.countCategoryCoincidence(item); doPrint(out, study, coincidence); }
java
public void print(final PrintStream out, final Iterable<Object> categories, final IDistanceFunction distanceFunction) { doPrint(out, categories, null, distanceFunction); }
java
public void print(final PrintStream out, final ICodingAnnotationStudy study, final IDistanceFunction distanceFunction) { doPrint(out, study.getCategories(), study, distanceFunction); }
java
private boolean isViewElementFindableOrList(Field field) { Class<?> fieldType = field.getType(); return View.class.isAssignableFrom(fieldType) || Element.class.isAssignableFrom(fieldType) || Findable.class.isAssignableFrom(fieldType) || List.class.isAssign...
java
private boolean isRequired(Field field) { return field.getAnnotation(Require.class) != null // Use the field's declaring class for RequireAll; may be a super class || (field.getDeclaringClass().getAnnotation(RequireAll.class) != null && field.getAnnotation(NotRequ...
java
public String getLiteralType(Type type) { String result = ""; if (type != null) { if (ParameterizedType.class.isAssignableFrom(type.getClass())) { ParameterizedType parameterizedType = (ParameterizedType) type; result = parameterizedType.toString(); } else { result = ((Class) type).getCanon...
java
public IJsonMarshaller getJsonMarshaller(Annotation[] annotations) throws JsonMarshallerException { if (annotations != null) { for (Annotation annotation : annotations) { if (JsonUnmarshaller.class.isAssignableFrom(annotation.annotationType())) { return getJsonMarshallerFromAnnotation((JsonUnmarshalle...
java
public IJsonMarshaller getJsonMarshallerFromAnnotation(JsonUnmarshaller jua) throws JsonMarshallerException { if (jua != null) { return argumentServices.getIJsonMarshallerInstance(jua.value()); } return null; }
java
public String getInstanceNameFromDataservice(Class cls) { DataService dataService = (DataService) cls.getAnnotation(DataService.class); String clsName = dataService.name(); if (clsName.isEmpty()) { clsName = cls.getSimpleName(); } return getInstanceName(clsName); }
java
public boolean isConsiderateMethod(Method method) { if (method.isAnnotationPresent(TransientDataService.class) || method.isAnnotationPresent(WsDataService.class) || method.getDeclaringClass().isAssignableFrom(Object.class)) { return false; } int modifiers = method.getModifiers(); return Modifier.isPubli...
java
Object getInstanceOfClass(Class cls) { if (Boolean.class.isAssignableFrom(cls) || Boolean.TYPE.isAssignableFrom(cls)) { return Boolean.FALSE; } else if (Integer.TYPE.isAssignableFrom(cls) || Short.TYPE.isAssignableFrom(cls) || Integer.class.isAssignableFrom(cls) || Short.class.isAssignableFrom(cls)) { ret...
java
Object getObjectFromConstantFields(Class cls) { Field[] fields = cls.getFields(); Object instance = null; for (Field field : fields) { instance = getObjectFromConstantField(cls, field); if(instance!=null) { break; } } return instance; }
java
String getTemplateOfParameterizedType(ParameterizedType parameterizedType, IJsonMarshaller jsonMarshaller) { Class cls = (Class) parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); String res; if (Iterable.class.isAssignableFrom(cls)) { res = getTempl...
java
String getTemplateOfIterable(Type[] actualTypeArguments, IJsonMarshaller jsonMarshaller) { String res = "["; for (Type actualTypeArgument : actualTypeArguments) { String template = _getTemplateOfType(actualTypeArgument, jsonMarshaller); res += template + "," + template; break; } return res + "]"...
java
String getTemplateOfMap(Type[] actualTypeArguments, IJsonMarshaller jsonMarshaller) { StringBuilder res = new StringBuilder("{"); boolean first = true; for (Type actualTypeArgument : actualTypeArguments) { if (!first) { res.append(":"); } res.append(_getTemplateOfType(actualTypeArgument, jsonM...
java
String getInstanceName(String clsName) { return clsName.substring(0, 1).toLowerCase(Locale.ENGLISH) + clsName.substring(1); }
java
public static <T> Builder<T, ItemListBox<T>> builder () { return new Builder<T, ItemListBox<T>>(new ItemListBox<T>()); }
java
public boolean removeItem (T item) { int index = _items.indexOf(item); if (index == -1) { return false; } _items.remove(index); removeItem(index); return true; }
java
protected static boolean addRow (SmartTable table, List<Widget> widgets) { if (widgets == null) { return false; } int row = table.getRowCount(); for (int col=0; col<widgets.size(); ++col) { table.setWidget(row, col, widgets.get(col)); table.getFlex...
java
protected Field findField() throws FinderFieldNotFoundException { try { if (fieldName != null) { return beanType.getField(fieldName); } try { return beanType.getField("find"); } catch (NoSuchFieldException e) { return beanType.getField("FIND"); } } catch ...
java
public void setCellAlignment (HasAlignment.HorizontalAlignmentConstant horiz, HasAlignment.VerticalAlignmentConstant vert) { _cellHorizAlign = horiz; _cellVertAlign = vert; }
java
protected void formatCell (HTMLTable.CellFormatter formatter, int row, int col, int limit) { formatter.setHorizontalAlignment(row, col, _cellHorizAlign); formatter.setVerticalAlignment(row, col, _cellVertAlign); formatter.setStyleName(row, col, "Cell"); if (row == (limit-1)/_cols) { ...
java
@SuppressWarnings("unchecked") <C, T> Stage<T> doCollectEmpty( final Function<? super Collection<C>, ? extends T> collector ) { try { return this.completed(collector.apply((Collection<C>) EMPTY_RESULTS)); } catch (Exception e) { return failed(e); } }
java
<T, U> Stage<U> doStreamCollectEmpty( final Consumer<? super T> consumer, final Supplier<? extends U> supplier ) { try { return this.completed(supplier.get()); } catch (Exception e) { return failed(e); } }
java
<T, U> Stage<U> doStreamCollect( final Collection<? extends Stage<? extends T>> stages, final Consumer<? super T> consumer, final Supplier<? extends U> supplier ) { final Completable<U> target = completable(); final StreamCollectHelper<? super T, ? extends U> done = new StreamCollectHelpe...
java
<T, U> Stage<U> doEventuallyCollect( final Collection<? extends Callable<? extends Stage<? extends T>>> tasks, final Consumer<? super T> consumer, Supplier<? extends U> supplier, int parallelism ) { final ExecutorService executor = executor(); final Completable<U> stage = completable(); execut...
java
Stage<Void> doCollectAndDiscard( Collection<? extends Stage<?>> stages ) { final Completable<Void> target = completable(); final CollectAndDiscardHelper done = new CollectAndDiscardHelper(stages.size(), target); for (final Stage<?> q : stages) { q.handle(done); } bindSignals(target,...
java
void bindSignals( final Stage<?> target, final Collection<? extends Stage<?>> stages ) { target.whenCancelled(() -> { for (final Stage<?> f : stages) { f.cancel(); } }); }
java
public void onFailure (Throwable cause) { Console.log("Callback failure", "for", _trigger, cause); setEnabled(true); reportFailure(cause); }
java
public ClickCallback<T> setConfirmChoices (String confirm, String abort) { _confirmChoices = new String[] { confirm, abort }; return this; }
java
protected void showError (Throwable cause, Widget near) { if (near == null) { Popups.error(formatError(cause)); } else { Popups.errorBelow(formatError(cause), near); } }
java
protected int addConfirmPopupMessage (SmartTable contents, int row) { if (_confirmHTML) { contents.setHTML(row, 0, _confirmMessage, 2, "Message"); } else { contents.setText(row, 0, _confirmMessage, 2, "Message"); } return row + 1; }
java
private void createEnhancingMethods(final Class<?> resourceClass, final Object resourceInstance, final List<ModelProcessorUtil.Method> newMethods) { final Template template = resourceClass.getAnnotation(Template.class); if (template != null) { final C...
java
public void setHref (String href) { if (_forceProtocol) { // This will correct URLs that don't have http:// as well // as provide protection against JS injection if ( ! href.matches("^\\s*\\w+://.*")) { href = "http://" + href; } } els...
java
public static Document prepareForCloning(Document domainXml) { XPathFactory xpf = XPathFactory.instance(); // remove uuid so it will be generated domainXml.getRootElement().removeChild("uuid"); // remove mac address, so it will be generated XPathExpression<Element> macExpr = xp...
java
public static void join(Object strand, long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException { Strand.join(strand, timeout, unit); }
java
static void log(Object targetObj, String msg) { if (EventsParams.isDebug()) { Log.d(TAG, toLogStr(targetObj, msg)); } }
java
static void logE(Object targetObj, String msg) { Log.e(TAG, toLogStr(targetObj, msg)); }
java
static void logE(String eventKey, String msg) { Log.e(TAG, toLogStr(eventKey, msg)); }
java
private static JFreeChart createChart( String title, String xAxis, String yAxis1, XYDataset dataset1, String yAxis2, XYDataset dataset2 ) { JFreeChart chart = ChartFactory.createXYLineChart(title, xAxis, yAxis1, dataset1, PlotOrientation.VERTICAL, true, true, false); final XYP...
java
public static void showChart( String name, String xAxis, String yAxis1, XYDataset dataset1, String yAxis2, XYDataset dataset2 ) { final JFreeChart chart = createChart(name, xAxis, yAxis1, dataset1, yAxis2, dataset2); final ChartPanel chartPanel = createPanel(chart); final ApplicationFrame app...
java
public void submit(final Metric metric) { if (metric != null) { LOGGER.debug("Collecting metric: {}", metric); queue.offer(metric); } }
java
public int flush(final MetricSender sender) throws IOException, HttpException { Preconditions.checkNotNull(sender); // aggregate metrics that were enqueued before the current minute long currentMinute = (System.currentTimeMillis() / MS_IN_MIN) * MS_IN_MIN; LOGGER.debug("Flushing metrics < {}", curren...
java
public static InfoPopup infoOn (String message, Widget target) { return centerOn(new InfoPopup(message), target); }
java
public static <T extends PopupPanel> T show (T popup, Position pos, Widget target) { popup.setVisible(false); popup.show(); int left, top; switch (pos) { case RIGHT: left = target.getAbsoluteLeft() + target.getOffsetWidth() + NEAR_GAP; break; ...
java
public static <T extends PopupPanel> T showAbove (T popup, Widget target) { return show(popup, Position.ABOVE, target); }
java
public static <T extends PopupPanel> T showOver (T popup, Widget target) { return show(popup, Position.OVER, target); }
java
public static <T extends PopupPanel> T showBelow (T popup, Widget target) { return show(popup, Position.BELOW, target); }
java
public static PopupPanel newPopup (String styleName, Widget contents) { PopupPanel panel = new PopupPanel(); panel.setStyleName(styleName); panel.setWidget(contents); return panel; }
java
public static PopupPanel newPopup (String styleName, Widget contents, Position pos, Widget target) { PopupPanel panel = newPopup(styleName, contents); show(panel, pos, target); return panel; }
java
public static ClickHandler createHider (final PopupPanel popup) { return new ClickHandler() { public void onClick (ClickEvent event) { popup.hide(); } }; }
java
public static void makeDraggable (HasAllMouseHandlers dragHandle, PopupPanel target) { DragHandler dragger = new DragHandler(target); dragHandle.addMouseDownHandler(dragger); dragHandle.addMouseUpHandler(dragger); dragHandle.addMouseMoveHandler(dragger); }
java
public void setHTML (int row, int column, String text, int colSpan, String... styles) { setHTML(row, column, text); if (colSpan > 0) { getFlexCellFormatter().setColSpan(row, column, colSpan); } setStyleNames(row, column, styles); }
java
public int addText (Object text, int colSpan, String... styles) { int row = getRowCount(); setText(row, 0, text, colSpan, styles); return row; }
java
public int addWidget (Widget widget, int colSpan, String... styles) { int row = getRowCount(); setWidget(row, 0, widget, colSpan, styles); return row; }
java
public void setStyleNames (int row, int column, String... styles) { int idx = 0; for (String style : styles) { if (idx++ == 0) { getFlexCellFormatter().setStyleName(row, column, style); } else { getFlexCellFormatter().addStyleName(row, column, ...
java
public void setColumnCellStyles (int column, String... styles) { int rowCount = getRowCount(); for (int row = 0; row < rowCount; ++row) { setStyleNames(row, column, styles); } }
java
public void removeStyleNames (int row, int column, String... styles) { for (String style : styles) { getFlexCellFormatter().removeStyleName(row, column, style); } }
java
public MethodCall with(String name1, Object arg1) { return with(name1, arg1, null, null, null, null); }
java
public MethodCall with(String name1, Object arg1, String name2, Object arg2) { return with(name1, arg1, name2, arg2, null, null); }
java
public MethodCall with(String name1, Object arg1, String name2, Object arg2, String name3, Object arg3, String name4, Object arg4) { args.put(name1, arg1); if (name2 != null) { args.put(name2, arg2); if (name3 != null) { args.put(name3, arg3); if (name4 != null) { args.put(...
java
public static <K, V> Function<K, V> forMap (final Map<K, ? extends V> map, final V defaultValue) { return new Function<K, V>() { public V apply (K key) { V value = map.get(key); return (value != null || map.containsKey(key)) ? value : defaultValue; } ...
java
public static <T> Function<T, Boolean> forPredicate (final Predicate<T> predicate) { return new Function<T, Boolean>() { public Boolean apply (T arg) { return predicate.apply(arg); } }; }
java
public static Set<String> getOvercastPropertyNames(final String path) { Config overcastConfig = getOvercastConfig(); if (!overcastConfig.hasPath(path)) { return new HashSet<>(); } Config cfg = overcastConfig.getConfig(path); Set<String> result = new HashSet<>(); ...
java
public static int getScrollIntoView (Widget target) { int top = Window.getScrollTop(), height = Window.getClientHeight(); int ttop = target.getAbsoluteTop(), theight = target.getOffsetHeight(); // if the target widget is taller than the browser window, or is above the current scroll ...
java
public static int getScrollToMiddle (Widget target) { int wheight = Window.getClientHeight(), theight = target.getOffsetHeight(); int ttop = target.getAbsoluteTop(); return Math.max(ttop, ttop + (wheight - theight)); }
java
public static boolean isScrolledIntoView (Widget target, int minPixels) { int wtop = Window.getScrollTop(), wheight = Window.getClientHeight(); int ttop = target.getAbsoluteTop(); if (ttop > wtop) { return (wtop + wheight - ttop > minPixels); } else { return (...
java
public static MetricAggregate fromMetricIdentity(final MetricIdentity identity, final long currentMinute) { Preconditions.checkNotNull(identity); return new MetricAggregate(identity, currentMinute); }
java
public static void log (String message, Object... args) { StringBuilder sb = new StringBuilder(); sb.append(message); if (args.length > 1) { sb.append(" ["); for (int ii = 0, ll = args.length/2; ii < ll; ii++) { if (ii > 0) { sb.app...
java
public static void main (String[] args) { if (args.length <= 1) { System.err.println("Usage: I18nSyncTask rootDir rootDir/com/mypackage/Foo.properties " + "[.../Bar.properties ...]"); System.exit(255); } File rootDir = new File(args[0])...
java