code
stringlengths
73
34.1k
label
stringclasses
1 value
public static String param(JavaScriptObject js) { Properties prop = js.cast(); String ret = ""; for (String k : prop.keys()) { ret += ret.isEmpty() ? "" : "&"; JsCache o = prop.getArray(k).cast(); if (o != null) { for (int i = 0, l = o.length(); i < l; i++) { ret += i > 0...
java
@Override public void setStyleProperty(Element e, String prop, String val) { if ("opacity".equals(prop)) { setOpacity(e, val); } else { super.setStyleProperty(e, prop, val); } }
java
public static IsProperties create(String s, boolean fixJson) { return getFactory().create(fixJson ? Properties.wrapPropertiesString(s) : s); }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) private <T> T getCustomMarshalledValue(T toReturn, Method getter, AttributeValue value) { DynamoDBMarshalling annotation = getter.getAnnotation(DynamoDBMarshalling.class); Class<? extends DynamoDBMarshaller<? extends Object>> marshallerClass = annotatio...
java
@SuppressWarnings({ "rawtypes", "unchecked" }) private AttributeValue getCustomerMarshallerAttributeValue(Method getter, Object getterReturnResult) { DynamoDBMarshalling annotation = getter.getAnnotation(DynamoDBMarshalling.class); Class<? extends DynamoDBMarshaller<? extends Object>> marshallerClas...
java
private boolean parseBoolean(String s) { if ( "1".equals(s) ) { return true; } else if ( "0".equals(s) ) { return false; } else { throw new IllegalArgumentException("Expected 1 or 0 for boolean value, was " + s); } }
java
ArgumentMarshaller getVersionedArgumentMarshaller(final Method getter, Object getterReturnResult) { synchronized (versionArgumentMarshallerCache) { if ( !versionArgumentMarshallerCache.containsKey(getter) ) { ArgumentMarshaller marshaller = null; final Class<?> ret...
java
ArgumentMarshaller getAutoGeneratedKeyArgumentMarshaller(final Method getter) { synchronized (keyArgumentMarshallerCache) { if ( !keyArgumentMarshallerCache.containsKey(getter) ) { ArgumentMarshaller marshaller = null; Class<?> returnType = getter.getReturnType(); ...
java
protected boolean mouseDown(Element element, GqEvent event) { // test if an other plugin handle the mouseStart if (isEventAlreadyHandled(event)) { return false; } if (started) { // case where we missed a mouseup mouseUp(element, event); } // calculate all interesting variables ...
java
protected boolean mouseMove(Element element, GqEvent event) { if (started) { event.getOriginalEvent().preventDefault(); return mouseDrag(element, event); } if (delayConditionMet() && distanceConditionMet(event)) { started = mouseStart(element, startEvent); if (started) { mo...
java
protected boolean mouseUp(Element element, GqEvent event) { unbindOtherEvents(); if (started) { started = false; preventClickEvent = event.getCurrentEventTarget() == startEvent.getCurrentEventTarget(); mouseStop(element, event); } return true; }
java
private String getContent(TreeLogger logger, String path, String src) throws UnableToCompleteException { HttpURLConnection connection = null; InputStream in = null; try { if (!src.matches("(?i)https?://.*")) { String file = path + "/" + src; in = this.getClass().getClassLoader()....
java
public <T extends Object> T load(Class<T> clazz, Object hashKey, DynamoDBMapperConfig config) { return load(clazz, hashKey, null, config); }
java
public <T extends Object> T load(Class<T> clazz, Object hashKey, Object rangeKey, DynamoDBMapperConfig config) { config = mergeConfig(config); String tableName = getTableName(clazz, config); // Fill in the hash key element in the service request Method hashKeyGetter = reflector.getHash...
java
public <T> List<T> marshallIntoObjects(Class<T> clazz, List<Map<String, AttributeValue>> itemAttributes) { List<T> result = new ArrayList<T>(); for (Map<String, AttributeValue> item : itemAttributes) { result.add(marshallIntoObject(clazz, item)); } return result; }
java
private <T> void setValue(final T toReturn, final Method getter, AttributeValue value) { Method setter = reflector.getSetter(getter); ArgumentUnmarshaller unmarhsaller = reflector.getArgumentUnmarshaller(toReturn, getter, setter); unmarhsaller.typeCheck(value, setter); Object argument;...
java
public void delete(Object object, DynamoDBMapperConfig config) { config = mergeConfig(config); Class<?> clazz = object.getClass(); String tableName = getTableName(clazz, config); Method hashKeyGetter = reflector.getHashKeyGetter(clazz); AttributeValue hashKeyElement = getHashK...
java
private boolean validBatchGetRequest(Map<Class<?>, List<KeyPair>> itemsToGet) { if (itemsToGet == null || itemsToGet.size() == 0) { return false; } for (Class<?> clazz : itemsToGet.keySet()) { if (itemsToGet.get(clazz) != null && itemsToGet.get(clazz).size() > 0) { ...
java
private AttributeValue getAutoGeneratedKeyAttributeValue(Method getter, Object getterResult) { ArgumentMarshaller marshaller = reflector.getAutoGeneratedKeyArgumentMarshaller(getter); return marshaller.marshall(getterResult); }
java
public <T> ScanResultPage<T> scanPage(Class<T> clazz, DynamoDBScanExpression scanExpression, DynamoDBMapperConfig config) { config = mergeConfig(config); ScanRequest scanRequest = createScanRequestFromExpression(clazz, scanExpression, config); ScanResult scanResult = db.scan(applyUserAgent(sca...
java
public <T> PaginatedQueryList<T> query(Class<T> clazz, DynamoDBQueryExpression queryExpression) { return query(clazz, queryExpression, config); }
java
public int count(Class<?> clazz, DynamoDBQueryExpression queryExpression, DynamoDBMapperConfig config) { config = mergeConfig(config); QueryRequest queryRequest = createQueryRequestFromExpression(clazz, queryExpression, config); queryRequest.setCount(true); // Count queries can also be...
java
private DynamoDBMapperConfig mergeConfig(DynamoDBMapperConfig config) { if ( config != this.config ) config = new DynamoDBMapperConfig(this.config, config); return config; }
java
private Map<String, AttributeValueUpdate> transformAttributeUpdates(Class<?> clazz, Key objectKey, Map<String, AttributeValueUpdate> updateValues) { Map<String, AttributeValue> item = convertToItem(updateValues); boolean hashKeyAdded = false; boolean rangeKeyAdded = false; S...
java
public static void rebind(Element e) { EventsListener ret = getGQueryEventListener(e); if (ret != null) { DOM.setEventListener((com.google.gwt.user.client.Element) e, ret); } }
java
public boolean hasHandlers(int eventBits, String eventName, Function handler) { for (int i = 0, j = elementEvents.length(); i < j; i++) { BindFunction function = elementEvents.get(i); if ((function.hasEventType(eventBits) || function.isTypeOf(eventName)) && (handler == null || function.isEquals...
java
public void storeCookies(URLConnection conn) throws IOException { // let's determine the domain from where these cookies are being sent String domain = getDomainFromHost(conn.getURL().getHost()); Map<String, Map<String, String>> domainStore; // this is where we will store cookies for this domain // no...
java
public void setCookies(URLConnection conn) throws IOException { // let's determine the domain and path to retrieve the appropriate cookies URL url = conn.getURL(); String domain = getDomainFromHost(url.getHost()); if (domain.equals("localhost")) { domain = "linkedin.com"; } String path = ...
java
public static boolean matchesTags(Element e, String... tagNames) { assert e != null : "Element cannot be null"; StringBuilder regExp = new StringBuilder("^("); int tagNameLenght = tagNames != null ? tagNames.length : 0; for (int i = 0; i < tagNameLenght; i++) { regExp.append(tagNames[i].toUpperC...
java
public static void attachWidget(Widget widget, Widget firstParentWidget) { if (widget != null && widget.getParent() == null) { if (firstParentWidget == null) { firstParentWidget = getFirstParentWidget(widget); if (firstParentWidget == null) { RootPanel.detachOnWindowClose(widget); ...
java
public static Iterator<Widget> getChildren(Widget w) { if (w instanceof Panel) { return ((Panel) w).iterator(); } if (w instanceof Composite) { return getChildren(compositeGetWidget((Composite) w)); } return null; }
java
public final int pageX() { if (getTouches() != null && getTouches().length() > 0) { return getTouches().get(0).getPageX(); } else { return getClientX() + GQuery.document.getScrollLeft(); } }
java
public final int pageY() { if (getTouches() != null && getTouches().length() > 0) { return getTouches().get(0).getPageY(); } else { return getClientY() + GQuery.document.getScrollTop(); } }
java
public void setTableNames(java.util.Collection<String> tableNames) { if (tableNames == null) { this.tableNames = null; return; } java.util.List<String> tableNamesCopy = new java.util.ArrayList<String>(tableNames.size()); tableNamesCopy.addAll(tableNames); ...
java
public Object getContext(Class<?> key) { if (key == null) { throw new NullPointerException("key is null"); } if (context == null) { return null; } return context.get(key); }
java
public void putContext(Class<?> key, Object contextObject) { if (key == null) { throw new NullPointerException("key is null"); } if (context == null) { context = new HashMap<Class<?>, Object>(); } context.put(key, contextObject); }
java
public static void main(String[] args) throws SAXException, IOException { // create our expression context ELContext context = new SimpleContext(); // set value for top-level property "home" context.getELResolver().setValue(context, null, "home", "/foo/bar"); // create our filtered reader XMLReader re...
java
public <T> T convert(Object value, Class<T> type) { return converter.convert(value, type); }
java
public static String getStorageDir(DataSegment segment) { return JOINER.join( segment.getDataSource(), String.format( "%s_%s", segment.getInterval().getStart(), segment.getInterval().getEnd() ), segment.getVersion(), segment.getShardSpec(...
java
void update(JsonObject dp){ for(int i = 0; i < dp.names().size(); i++){ datapoint.put(dp.names().get(i), dp.get(dp.names().get(i))); } }
java
public String [] getFieldsArray(){ Object [] obj = datapoint.keySet().toArray(); String [] out = new String[obj.length]; for(int i=0; i<obj.length; i++) out[i] = String.valueOf(obj[i]); return out; }
java
public String getByKey(String key){ String out = ""; if(key.equals("time")) return time(); if(key.contains("Time")){ DateFormat dfm = new SimpleDateFormat("HH:mm:ss"); dfm.setTimeZone(TimeZone.getTimeZone(timezone)); out = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get(key))) * 1000 ); ...
java
public void setHTTPProxy(String PROXYNAME, int PROXYPORT) { if (PROXYNAME == null) { this.proxy_to_use = null; } else { this.proxy_to_use = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXYNAME, PROXYPORT)); } }
java
public boolean update(){ boolean b = getForecast(String.valueOf(getLatitude()), String.valueOf(getLongitude())); return b; }
java
public boolean getForecast(String LATITUDE, String LONGITUDE) { try { String reply = httpGET( urlBuilder(LATITUDE, LONGITUDE) ); if(reply == null) return false; this.forecast = Json.parse(reply).asObject(); //this.forecast = JsonObject.readFrom(reply); } catch (NullPointerException e) { System....
java
public boolean getForecast(String http_response) { this.forecast = Json.parse(http_response).asObject(); //this.forecast = JsonObject.readFrom(http_response); return getForecast(this.forecast); }
java
protected void listen() { if (!connectedFlag.get() || releaseNeeded.get()) { return; } releaseNeeded.set(true); try { send(pushListener, new OnFinishedHandler() { @Override public void onFinished() { releaseNeed...
java
protected void release() { if (!releaseNeeded.get()) { return; // there is no point in releasing if we do not wait. Avoid excessive releasing. } releaseNeeded.set(false);// release is under way backgroundExecutor.execute(new Runnable() { @Override pub...
java
public List<Command> receive(final Command command) { Assert.requireNonNull(command, "command"); LOG.trace("Received command of type {}", command.getClass().getSimpleName()); List<Command> response = new LinkedList();// collecting parameter pattern if (!(command instanceof InterruptLon...
java
public static <S extends Styleable, V> DefaultPropertyBasedCssMetaData<S, V> createMetaData(String property, StyleConverter<?, V> converter, String propertyName, V defaultValue) { return new DefaultPropertyBasedCssMetaData<S, V>(property, converter, propertyName, defaultValue); }
java
public static <S extends Control, V> SkinPropertyBasedCssMetaData<S, V> createSkinMetaData(String property, StyleConverter<?, V> converter, String propertyName, V defaultValue) { return new SkinPropertyBasedCssMetaData<S, V>(property, converter, propertyName, defaultValue); }
java
public Subscription registerDolphinContext(ClientSession session, GarbageCollector garbageCollector) { Assert.requireNonNull(session, "session"); Assert.requireNonNull(garbageCollector, "garbageCollector"); DolphinSessionInfoMBean mBean = new DolphinSessionInfo(session, garbageCollector); ...
java
public Subscription registerController(Class<?> controllerClass, String controllerId, ModelProvider modelProvider) { Assert.requireNonNull(controllerClass, "controllerClass"); Assert.requireNonBlank(controllerId, "controllerId"); Assert.requireNonNull(modelProvider, "modelProvider"); Dol...
java
@Override public final void init() throws Exception { FxToolkit.init(); applicationInit(); PlatformClient.getClientConfiguration().setUncaughtExceptionHandler((Thread thread, Throwable exception) -> { PlatformClient.getClientConfiguration().getUiExecutor().execute(() -> { ...
java
protected void onRuntimeError(final Stage primaryStage, final DolphinRuntimeException runtimeException) { Assert.requireNonNull(runtimeException, "runtimeException"); LOG.error("Dolphin Platform runtime error in thread " + runtimeException.getThread().getName(), runtimeException); Platform.exit(...
java
public boolean isReferencedByRoot() { if(rootBean) { return true; } for(Reference reference : references) { Instance parent = reference.getParent(); if(parent.isReferencedByRoot()) { return true; } } return false; ...
java
public static <T, R> SwitchBuilder<T, R> switchBinding(ObservableValue<T> observable, Class<R> bindingType) { return new SwitchBuilder<>(observable); }
java
public CompletableFuture<Void> destroy() { CompletableFuture<Void> ret; if (controllerProxy != null) { ret = controllerProxy.destroy(); controllerProxy = null; } else { ret = new CompletableFuture<>(); ret.complete(null); } return r...
java
protected CompletableFuture<Void> invoke(String actionName, Param... params) { Assert.requireNonBlank(actionName, "actionName"); actionInProcess.set(true); return controllerProxy.invoke(actionName, params).whenComplete((v, e) -> { try { if (e != null) { ...
java
public void silently(final Runnable applyChange) { boolean temp = notifyClient; notifyClient = false; try { applyChange.run(); } finally { notifyClient = temp; } }
java
protected void verbosely(final Runnable applyChange) { boolean temp = notifyClient; notifyClient = true; try { applyChange.run(); } finally { notifyClient = temp; } }
java
@SafeVarargs public static BooleanBinding and(ObservableValue<Boolean>...values) { return Bindings.createBooleanBinding( ()-> !Arrays.stream(values) .filter(observable -> !observable.getValue()) .findAny() .isPresent(), values); }
java
public static NumberBinding sum(final ObservableList<? extends Number> numbers) { return Bindings.createDoubleBinding(() -> numbers.stream().mapToDouble(Number::doubleValue).sum(), numbers); }
java
public static StringBinding join(final ObservableList<?> items, final ObservableValue<String> delimiter) { return Bindings.createStringBinding(() -> items.stream().map(String::valueOf).collect(Collectors.joining(delimiter.getValue())), items, delimiter); }
java
@SafeVarargs public static <T> ObservableList<T> concat(ObservableList<T>... lists) { ObservableList<T> result = FXCollections.observableArrayList(); // todo: think about a smarter solution for (ObservableList<T> list : lists) { list.addListener((Observable observable) -> { ...
java
public static BooleanBinding matches(final ObservableValue<String> text, final String pattern) { return Bindings.createBooleanBinding(() -> { final String textToVerify = text.getValue(); return textToVerify != null && textToVerify.matches(pattern); }, text); }
java
public static StringBinding transforming(ObservableValue<String> text, Function<String, String> transformer) { return Bindings.createStringBinding(() -> { Function<String, String> func = transformer == null ? Function.identity() : transformer; return text.getValue() == null ? "" : func.apply(text.getValue())...
java
public boolean remove(final ServerPresentationModel pm) { boolean deleted = super.remove(pm); if (!deleted) { throw new IllegalStateException("Model " + pm + " not found on the server!"); } deleteCommand(getCurrentResponse(), pm.getId()); return deleted; }
java
@Deprecated public static void deleteCommand(final List<Command> response, final String pmId) { if (response == null || Assert.isBlank(pmId)) { return; } response.add(new DeletePresentationModelCommand(pmId)); }
java
@Deprecated public static void changeValueCommand(final List<Command> response, final ServerAttribute attribute, final Object value) { if (response == null) { return; } if (attribute == null) { LOG.error("Cannot change value on a null attribute to '{}'", value); ...
java
public ServerPresentationModel presentationModel(final String id, final String presentationModelType, final DTO dto) { List<ServerAttribute> attributes = new ArrayList<ServerAttribute>(); for (final Slot slot : dto.getSlots()) { final ServerAttribute result = new ServerAttribute(slot.getProp...
java
public Subscription register(final Object mBean, final MBeanDescription description) { Assert.requireNonNull(description, "description"); return register(mBean, description.getMBeanName(getNextId())); }
java
public Subscription register(final Object mBean, final String name){ try { if (mbeanSupport.get()) { final ObjectName objectName = new ObjectName(name); server.registerMBean(mBean, objectName); return new Subscription() { @Override ...
java
@Deprecated public void sync(final Runnable runnable) { clientConnector.send(new EmptyCommand(), new OnFinishedHandler() { public void onFinished() { runnable.run(); } }); }
java
public synchronized Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation) { Assert.requireNonNull(annotation, "annotation"); return reflections.getTypesAnnotatedWith(annotation); }
java
private int combineFlags(final Pattern.Flag[] flags) { int combined = 0; for (Pattern.Flag f : flags) { combined |= f.getValue(); } return combined; }
java
public static <S, R> ObjectBinding<R> map(ObservableValue<S> source, Function<? super S, ? extends R> function) { return map(source, function, null); }
java
public static <S, R> ObjectBinding<R> map(ObservableValue<S> source, Function<? super S, ? extends R> function, R defaultValue){ return Bindings.createObjectBinding(()->{ S sourceValue = source.getValue(); if(sourceValue == null){ return defaultValue; }else{ ...
java
public static <T, S extends T> ObjectBinding<T> cast(final ObservableValue<S> source) { return Bindings.createObjectBinding(source::getValue, source); }
java
private static String createAnnotationCollectionId(Collection<Annotation> annotations) { if (annotations.isEmpty()) return ""; return annotations.stream() .sorted(comparing(a -> a.annotationType().getName())) .map(CdiSpiHelper::createAnnotationId) .collec...
java
public static Object getValue(Object exp, Object root) { return getValue(exp, root, null, 0); }
java
public static Object getValue(Object exp, Map ctx, Object root) { return getValue(exp, ctx, root, null, 0); }
java
public static Object getValue(Object exp, Map ctx, Object root, String path, int lineNumber) { try { OgnlContext context = new OgnlContext(null, null, new DefaultMemberAccess(true)); return Ognl.getValue(exp, context, root); } catch (OgnlException ex) { throw new...
java
public static Object parseExpression(String expression, String path, int lineNumber) { try { return Ognl.parseExpression(expression); } catch (Exception ex) { throw new OgnlRuntimeException(ex, path, lineNumber); } }
java
public <T> T getSingleResult(Class<T> clazz, String sql, Object[] params) { PreparedStatement stmt = null; ResultSet rs = null; try { stmt = connectionProvider.getConnection().prepareStatement(sql); setParameters(stmt, params); if (logger.isDebugEnable...
java
public int executeUpdateSql(String sql, PropertyDesc[] propDescs, Object entity){ PreparedStatement stmt = null; ResultSet rs = null; try { Connection conn = connectionProvider.getConnection(); if (logger.isDebugEnabled()) { printSql(sql); ...
java
public int executeBatchUpdateSql(String sql, List<PropertyDesc[]> propDescsList, Object[] entities) { PreparedStatement stmt = null; ResultSet rs = null; try { Connection conn = connectionProvider.getConnection(); if (logger.isDebugEnabled()) { pri...
java
@SuppressWarnings("unchecked") protected void fillIdentityPrimaryKeys(Object entity, ResultSet rs) throws SQLException { BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass()); int size = beanDesc.getPropertyDescSize(); for(int i=0; i < size; i++){ PropertyDesc...
java
public static String buildDeleteSql(BeanDescFactory beanDescFactory, EntityOperator entityOperator, Class<?> entityType, NameConverter nameConverter, List<PropertyDesc> propDescs){ StringBuilder sb = new StringBuilder(); sb.append("DELETE FROM ").append(getTableName(entityType, nameConver...
java
private void fillPrimaryKeysBySequence(Object entity){ if(!dialect.supportsGenerationType(GenerationType.SEQUENCE)){ return; } BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass()); int size = beanDesc.getPropertyDescSize(); for(int i=0; i < siz...
java
public void setValueTypes(List<ValueType<?>> valueTypes) { Validate.noNullElements(valueTypes); this.sqlExecutor.setValueTypes(valueTypes); this.callExecutor.setValueTypes(valueTypes); }
java
protected String getSql(int version){ Dialect dialect = ((SqlManagerImpl) sqlManager).getDialect(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream in = classLoader.getResourceAsStream( String.format("%s/%s_%d.sql", packageName, dialect.g...
java
protected boolean existsTable(){ try { int count = sqlManager.getSingleResult(Integer.class, new StringSqlResource(String.format("SELECT COUNT(*) FROM %s", tableName))); if(count == 0){ // TODO Should insert an initial record? r...
java
protected void createTable(){ sqlManager.executeUpdate( new StringSqlResource(String.format("CREATE TABLE %s (VERSION NUMERIC NOT NULL)", tableName))); sqlManager.executeUpdate( new StringSqlResource(String.format("INSERT INTO %s (0))", tableName))); }
java
public synchronized static Session getSession() { if(session == null){ Properties properties = IOUtil.loadProperties("jdbc.properties"); session = getSession(properties); } return session; }
java
public static boolean isUncountable(String word) { for (String w : UNCOUNTABLE) { if (w.equalsIgnoreCase(word)) { return true; } } return false; }
java
public static String singularize(String word) { if (isUncountable(word)) { return word; } else { for (Inflection inflection : SINGULAR) { if (inflection.match(word)) { return inflection.replace(word); } } } ...
java
public boolean match(String word) { int flags = 0; if (ignoreCase) { flags = flags | Pattern.CASE_INSENSITIVE; } return Pattern.compile(pattern, flags).matcher(word).find(); }
java
public String replace(String word) { int flags = 0; if (ignoreCase) { flags = flags | Pattern.CASE_INSENSITIVE; } return Pattern.compile(pattern, flags).matcher(word).replaceAll(replacement); }
java
public static Dialect getDialect(String url){ if(url.startsWith("jdbc:mysql:")){ return new MySQLDialect(); } else if(url.startsWith("jdbc:postgresql:")){ return new PostgreSQLDialect(); } else if(url.startsWith("jdbc:oracle:")){ return new OracleDialect...
java