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(ctx, topic, accessControls);
} | 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 : controllers) {
if(checkAccessTopicFromController(ctx, topic, jsTopicAccessController)) {
return true;
}
}
return false;
} | java |
boolean checkAccessTopicFromController(UserContext ctx, String topic, JsTopicAccessController jsTopicAccessController) throws IllegalAccessException {
logger.debug("Looking for accessController for topic '{}' from JsTopicAccessController {}", topic, jsTopicAccessController);
JsTopicControls jsTopicControls = jsTopicControlsTools.getJsTopicControlsFromProxyClass(jsTopicAccessController.getClass());
logger.debug("Looking for accessController for topic '{}' from jsTopicControls {}", topic, jsTopicControls);
if(null != jsTopicControls) {
logger.debug("Looking for accessController for topic '{}' from jsTopicControls {}, {}", topic, jsTopicControls, jsTopicControls.value());
for (JsTopicControl jsTopicControl : jsTopicControls.value()) {
if(topic.equals(jsTopicControl.value())) {
logger.debug("Found accessController for topic '{}' from JsTopicControls annotation", topic);
checkAccessTopicFromControllers(ctx, topic, Arrays.asList(jsTopicAccessController));
return true;
}
}
}
return false;
} | 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 (JsTopicAccessController accessControl : accessControls) {
accessControl.checkAccess(ctx, topic);
tacPresent = true;
}
}
return tacPresent;
} | 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(Constants.Topic.COLON).append(jsTopicName.postfix());
}
return result.toString();
} | 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 UnsupportedOperationException("Method annotated JsTopic(jsonPayload=true) must return String type and correct Json.");
}
messageToClient.setJson((String) result);
} else {
messageToClient.setResponse(result);
}
wsEvent.fire(messageToClient);
return result;
} | 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 IllegalArgumentException("Unsupported private key encoding: "
+ encoding.name());
}
} | 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.setProxyPermissions(proxyFileName);
channel.truncate(0);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
saveProxyCredentials(baos, uc, encoding);
baos.close();
channel.write(ByteBuffer.wrap(baos.toByteArray()));
channel.close();
raf.close();
} | 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(before);
wsid_httpid.put(before.getId(), httpid);
} else {
wsid_httpid.remove(before.getId());
}
}
if(wss.isEmpty()) {
httpid_wss.remove(httpid);
} else {
httpid_wss.put(httpid, wss);
}
}
return wss;
} | 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 = String.format(
"Wrong file permissions on file %s. Required permissions are: %s ",
privateKeyFile, PRIVATE_KEY_PERMS_STR);
throw new FilePermissionError(errorMessage);
} | 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...
String canonicalPath = f.getCanonicalPath();
String filePerms = getFilePermissions(canonicalPath);
if (!filePerms.startsWith(p.statForm))
throw new FilePermissionError("Wrong file permissions on file "
+ filename + ". Required permissions are: " + p.chmodForm());
} | 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.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException ex) {
logger.error("Fail to get MD5 of String "+msg, ex);
}
return null;
} | 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 != accepts) {
for (String accept : accepts) {
try {
return localeExtractor.extractFromAccept(accept);
} catch (LocaleNotFoundException ex) {
}
}
}
}
}
return Locale.US;
} | 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(JsTopicEvent.class);
if (jte != null) {
String topic = jte.value();
msg.setId(topic);
JsonMarshaller jm = annotated.getAnnotation(JsonMarshaller.class);
try {
if (jm != null) {
msg.setJson(argumentServices.getJsonResultFromSpecificMarshaller(jm, payload));
} else if(jte.jsonPayload()) {
if(!String.class.isInstance(payload)) {
throw new UnsupportedOperationException("'"+payload+"' cannot be a json object. Field annotated JsTopicEvent(jsonPayload=true) must be Event<String> type and fire correct Json.");
}
msg.setJson((String) payload);
} else {
msg.setResponse(payload);
}
topicsMessagesBroadcaster.sendMessageToTopic(msg, payload);
} catch (JsonMarshallingException ex) {
logger.error("'"+payload+"' cannot be send to : '"+topic+"'. It cannot be serialized with marshaller "+jm, ex);
} catch (Throwable ex) {
logger.error("'"+payload+"' cannot be send to : '"+topic+"'.", ex);
}
}
} | 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 = cacheArgumentServices.computeArgPart(jcr.keys(), jsonArgs, paramNames);
String cachekey = computeCacheKey(jcr.cls(), jcr.methodName(), argpart);
if (logger.isDebugEnabled()) {
logger.debug("JsonArgs from Call : {}", Arrays.toString(jsonArgs.toArray(new String[jsonArgs.size()])));
logger.debug("ParamName from considerated method : {}", Arrays.toString(paramNames.toArray(new String[paramNames.size()])));
logger.debug("Computed key : {}", cachekey);
}
messageToClient.setResponse(cachekey);
if (jcr.userScope()) {
wsUserEvent.fire(messageToClient);
} else {
wsEvent.fire(messageToClient);
cacheEvent.fire(cachekey);
}
} | 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);
return cachekey;
} | 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.isAssignableFrom(fieldType);
} | 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(NotRequired.class) == null);
} | 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).getCanonicalName();
}
}
return result;
} | java |
public IJsonMarshaller getJsonMarshaller(Annotation[] annotations) throws JsonMarshallerException {
if (annotations != null) {
for (Annotation annotation : annotations) {
if (JsonUnmarshaller.class.isAssignableFrom(annotation.annotationType())) {
return getJsonMarshallerFromAnnotation((JsonUnmarshaller) annotation);
}
}
}
return null;
} | 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.isPublic(modifiers) && !Modifier.isStatic(modifiers);
} | 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)) {
return 0;
} else if (Long.TYPE.isAssignableFrom(cls) || Long.class.isAssignableFrom(cls)) {
return 0L;
} else if (Float.TYPE.isAssignableFrom(cls) || Float.class.isAssignableFrom(cls)) {
return 0.1F;
} else if (Double.TYPE.isAssignableFrom(cls) || Double.class.isAssignableFrom(cls)) {
return 0.1D;
} else if (cls.isArray()) {
Class<?> comp = cls.getComponentType();
Object instance = getInstanceOfClass(comp);
return new Object[]{instance, instance};
} else {
try {
return cls.newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
return getObjectFromConstantFields(cls);
}
}
} | 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 = getTemplateOfIterable(actualTypeArguments, jsonMarshaller);
} else if (Map.class.isAssignableFrom(cls)) {
res = getTemplateOfMap(actualTypeArguments, jsonMarshaller);
} else {
res = cls.getSimpleName().toLowerCase(Locale.ENGLISH);
}
return res;
} | 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, jsonMarshaller));
first = false;
}
res.append("}");
return res.toString();
} | 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.getFlexCellFormatter().setStyleName(row, col, "col"+col);
}
return true;
} | 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 (NoSuchFieldException e) {
throw new FinderFieldNotFoundException(e);
}
} | 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) {
formatter.addStyleName(row, col, "BottomCell");
} else if (row == 0) {
formatter.addStyleName(row, col, "TopCell");
} else {
formatter.addStyleName(row, col, "MiddleCell");
}
} | 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 StreamCollectHelper<>(caller, stages.size(), consumer, supplier, target);
for (final Stage<? extends T> q : stages) {
q.handle(done);
}
bindSignals(target, stages);
return target;
} | 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();
executor.execute(
new DelayedCollectCoordinator<>(caller, tasks, consumer, supplier, stage, parallelism));
return stage;
} | 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, stages);
return 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 Class<?> annotatedResourceClass = ModelHelper.getAnnotatedResourceClass(resourceClass);
final List<MediaType> produces = MediaTypes
.createQualitySourceMediaTypes(annotatedResourceClass.getAnnotation(Produces.class));
final List<MediaType> consumes = MediaTypes.createFrom(annotatedResourceClass.getAnnotation(Consumes.class));
final TemplateInflectorImpl inflector = new TemplateInflectorImpl(template.name(),
resourceClass, resourceInstance);
newMethods.add(new ModelProcessorUtil.Method(HttpMethod.GET, consumes, produces, inflector));
newMethods.add(new ModelProcessorUtil.Method(IMPLICIT_VIEW_PATH_PARAMETER_TEMPLATE, HttpMethod.GET,
consumes, produces, inflector));
}
} | 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;
}
} else {
// Always do some sort of JS protection
if (href.trim().toLowerCase().startsWith("javascript:")) {
// He's been a naughty boy
href = "#";
}
}
DOM.setElementProperty(getElement(), "href", href);
} | 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 = xpf.compile("/domain/devices/interface/mac", Filters.element());
for (Element mac : macExpr.evaluate(domainXml)) {
mac.getParentElement().removeChild("mac");
}
return domainXml;
} | 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 XYPlot plot = (XYPlot) chart.getPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
final XYItemRenderer r = plot.getRenderer();
int count = Math.min(dataset1.getSeriesCount(), dataset2.getSeriesCount());
if (r instanceof XYLineAndShapeRenderer) {
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
renderer.setBaseStroke(LINE);
renderer.setAutoPopulateSeriesPaint(false);
renderer.setBaseShapesVisible(false);
renderer.setBaseShapesFilled(false);
renderer.setDrawSeriesLineAsPath(true);
for (int i = 0; i < count; i++) {
renderer.setSeriesPaint(i, COLORS.get(i % COLORS.size()));
}
}
chart.setBackgroundPaint(Color.white);
// chart two
{
final NumberAxis axis2 = new NumberAxis(yAxis2);
axis2.setAutoRangeIncludesZero(false);
plot.setRangeAxis(1, axis2);
plot.setDataset(1, dataset2);
plot.mapDatasetToRangeAxis(1, 1);
final StandardXYItemRenderer renderer = new StandardXYItemRenderer();
renderer.setAutoPopulateSeriesPaint(false);
renderer.setAutoPopulateSeriesStroke(false);
renderer.setBaseShapesVisible(false);
renderer.setBaseShapesFilled(false);
renderer.setDrawSeriesLineAsPath(true);
renderer.setBaseStroke(DASHED);
for (int i = 0; i < count; i++) {
renderer.setSeriesPaint(i, COLORS.get(i % COLORS.size()));
}
plot.setRenderer(1, renderer);
}
return chart;
} | 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 = new ApplicationFrame(name);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
app.setContentPane(chartPanel);
app.pack();
RefineryUtilities.centerFrameOnScreen(app);
app.setVisible(true);
} | 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 < {}", currentMinute);
LOGGER.debug("Metrics queue size {}", queue.size());
MetricAggregator aggregator = new MetricAggregator(currentMinute, lastValues);
while ((!queue.isEmpty()) && (queue.peek().getOccurredMillis() < currentMinute)) {
aggregator.add(queue.remove());
}
// handle the auto reports
if (lastFlush < currentMinute) {
aggregator.autoReportZero(autoReportZeroMetrics);
aggregator.autoReportLast(autoReportLastMetrics);
}
lastFlush = currentMinute;
// get the aggregates
List<MetricAggregate> aggregates = aggregator.getAggregates();
// Save the values of gauge and average metrics for the next iteration
// Gauge last value = aggregate last value
// Average last value = aggregate last value / aggregate count
if ((aggregates != null) && (!aggregates.isEmpty())) {
for (MetricAggregate aggregate : aggregates) {
if (aggregate.getIdentity().getType().equals(MetricMonitorType.GAUGE)) {
lastValues.put(aggregate.getIdentity(), aggregate.getValue());
} else if (aggregate.getIdentity().getType().equals(MetricMonitorType.AVERAGE)) {
lastValues.put(aggregate.getIdentity(), aggregate.getValue() / aggregate.getCount());
}
}
}
// send the aggregates to Stackify
int numSent = 0;
if ((aggregates != null) && (!aggregates.isEmpty())) {
LOGGER.debug("Sending aggregate metrics: {}", aggregates);
sender.send(aggregates);
numSent = aggregates.size();
}
return numSent;
} | 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;
default:
left = target.getAbsoluteLeft();
break;
}
if (left + popup.getOffsetWidth() > Window.getClientWidth()) {
left = Math.max(0, Window.getClientWidth() - popup.getOffsetWidth());
}
switch (pos) {
case ABOVE:
top = target.getAbsoluteTop() - popup.getOffsetHeight() - NEAR_GAP;
break;
case OVER:
top = target.getAbsoluteTop();
break;
case RIGHT:
top = target.getAbsoluteTop() + (target.getOffsetHeight() - popup.getOffsetHeight())/2;
break;
default:
case BELOW:
top = target.getAbsoluteTop() + target.getOffsetHeight() + NEAR_GAP;
break;
}
popup.setPopupPosition(left, top);
popup.setVisible(true);
return popup;
} | 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, style);
}
}
} | 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(name4, arg4);
}
}
}
return this;
} | 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<>();
for (Map.Entry<String, ConfigValue> e : cfg.entrySet()) {
result.add(ConfigUtil.splitPath(e.getKey()).get(0));
}
return result;
} | 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
// position of the browser window, scroll the top of the widget to the top of the window
if (theight > height || ttop < top) {
return ttop;
// otherwise scroll the bottom of the widget to the bottom of the window
} else if (ttop + theight > top + height) {
return ttop - (height - theight);
} else {
return top; // no scrolling needed
}
} | 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 (ttop + target.getOffsetHeight() - wtop > minPixels);
}
} | 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.append(", ");
}
sb.append(args[2*ii]).append("=").append(args[2*ii+1]);
}
sb.append("]");
}
Object error = (args.length % 2 == 1) ? args[args.length-1] : null;
if (GWT.isScript()) {
if (error != null) {
sb.append(": ").append(error);
}
firebugLog(sb.toString(), error);
} else {
GWT.log(sb.toString(), (Throwable)error);
}
} | 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]);
if (!rootDir.isDirectory()) {
System.err.println("Invalid root directory: " + rootDir);
System.exit(255);
}
I18nSync tool = new I18nSync();
boolean errors = false;
for (int ii = 1; ii < args.length; ii++) {
try {
tool.process(rootDir, new File(args[ii]));
} catch (IOException ioe) {
System.err.println("Error processing '" + args[ii] + "': " + ioe);
errors = true;
}
}
System.exit(errors ? 255 : 0);
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.