code
stringlengths
73
34.1k
label
stringclasses
1 value
@SuppressWarnings("unchecked") public static <T> T cleanse(T list, T element) { if (list == null || list == element) { return null; } else if (list instanceof Pair) { Pair<T, T> pair = (Pair<T, T>)list; if (pair.first == element) { return pair.seco...
java
@SuppressWarnings("unchecked") public static <T> boolean includes(T list, T element) { if (list == null) { return false; } else if (list == element) { return true; } else if (list instanceof Pair) { Pair<T, T> pair = (Pair<T, T>)list; if (pair....
java
@SuppressWarnings("unchecked") public static <T> int count(T list) { if (list == null) { return 0; } else if (list instanceof Pair) { return 1 + count(((Pair<T, T>)list).second); } else { return 1; } }
java
@SuppressWarnings("unchecked") public static <T> int traverse(T list, Functor<?, T> func) { if (list == null) { return 0; } else if (list instanceof Pair) { Pair<T, T> pair = (Pair<T, T>)list; func.invoke(pair.first); return 1 + traverse(pair.second, f...
java
public JSONBuilder quote(String value) { _sb.append('"'); for (int i = 0; i < value.length(); ++i) { char c = value.charAt(i); switch (c) { case '"': _sb.append("\\\""); break; case '\\': _sb.append("\\\\"); ...
java
public JSONBuilder serialize(Object value) { if (value == null) { _sb.append("null"); } else { Class<?> t = value.getClass(); if (t.isArray()) { _sb.append('['); boolean hasElements = false; for (int i = 0, ii = Array.ge...
java
protected String createExceptionMessage(final String message, final Object... messageParameters) { if (ArrayUtils.isEmpty(messageParameters)) { return message; } else { return String.format(message, messageParameters); } }
java
public static ApruveResponse<PaymentRequest> get(String paymentRequestId) { return ApruveClient.getInstance().get( PAYMENT_REQUESTS_PATH + paymentRequestId, PaymentRequest.class); }
java
public String toSecureHash() { String apiKey = ApruveClient.getInstance().getApiKey(); String shaInput = apiKey + toValueString(); return ShaUtil.getDigest(shaInput); }
java
public AnnotationValue defaultValue() { return (sym.defaultValue == null) ? null : new AnnotationValueImpl(env, sym.defaultValue); }
java
public void sessionReady(boolean isReady) { if (isReady) { speedSlider.setValue(session.getClockPeriod()); } startAction.setEnabled(isReady); speedSlider.setEnabled(isReady); stepAction.setEnabled(isReady); reloadAction.setEnabled(isReady); }
java
@Override public synchronized void mark(final int limit) { try { in.mark(limit); } catch (IOException ioe) { throw new RuntimeException(ioe.getMessage()); } }
java
@Override public synchronized void reset() throws IOException { if (in == null) { throw new IOException("Stream Closed"); } slack = null; in.reset(); }
java
@Override public synchronized void close() throws IOException { if(in != null) in.close(); slack = null; in = null; }
java
public Collection<String> getValues(String property) { Multimap<Optional<String>, String> values = properties.get(property); if (values == null) { return Collections.emptyList(); } return values.values(); }
java
public String getValue(String property, String language) { Multimap<Optional<String>, String> values = properties.get(property); if (values == null) { return null; } Iterator<String> it = values.get(Optional.of(language)).iterator(); return it.hasNext() ? it.next() ...
java
public String getFirstPropertyValue(String property) { Iterator<String> it = getValues(property).iterator(); return it.hasNext() ? it.next() : null; }
java
public DConnection findByAccessToken(java.lang.String accessToken) { return queryUniqueByField(null, DConnectionMapper.Field.ACCESSTOKEN.getFieldName(), accessToken); }
java
public Iterable<DConnection> queryByExpireTime(java.util.Date expireTime) { return queryByField(null, DConnectionMapper.Field.EXPIRETIME.getFieldName(), expireTime); }
java
public Iterable<DConnection> queryByImageUrl(java.lang.String imageUrl) { return queryByField(null, DConnectionMapper.Field.IMAGEURL.getFieldName(), imageUrl); }
java
public Iterable<DConnection> queryByProfileUrl(java.lang.String profileUrl) { return queryByField(null, DConnectionMapper.Field.PROFILEURL.getFieldName(), profileUrl); }
java
public Iterable<DConnection> queryByProviderId(java.lang.String providerId) { return queryByField(null, DConnectionMapper.Field.PROVIDERID.getFieldName(), providerId); }
java
public Iterable<DConnection> queryByProviderUserId(java.lang.String providerUserId) { return queryByField(null, DConnectionMapper.Field.PROVIDERUSERID.getFieldName(), providerUserId); }
java
public DConnection findByRefreshToken(java.lang.String refreshToken) { return queryUniqueByField(null, DConnectionMapper.Field.REFRESHTOKEN.getFieldName(), refreshToken); }
java
public Iterable<DConnection> queryBySecret(java.lang.String secret) { return queryByField(null, DConnectionMapper.Field.SECRET.getFieldName(), secret); }
java
public Iterable<DConnection> queryByUserId(java.lang.Long userId) { return queryByField(null, DConnectionMapper.Field.USERID.getFieldName(), userId); }
java
public Iterable<DConnection> queryByUserRoles(java.lang.String userRoles) { return queryByField(null, DConnectionMapper.Field.USERROLES.getFieldName(), userRoles); }
java
public void add(Collection<Label> labels) { for(Label label : labels) this.labels.put(label.getKey(), label); }
java
public final void sendGlobal(String handler, String data) { try { connection.sendMessage("{\"id\":-1,\"type\":\"global\",\"handler\":" + Json.escapeString(handler) + ",\"data\":" + data + "}"); } catch (IOException e) { e.printStackTrace(); } }
java
public void replaceWith(final ThriftEnvelope thriftEnvelope) { this.typeName = thriftEnvelope.typeName; this.name = thriftEnvelope.name; this.payload.clear(); this.payload.addAll(thriftEnvelope.payload); }
java
protected void addFrameWarning(Content contentTree) { Content noframes = new HtmlTree(HtmlTag.NOFRAMES); Content noScript = HtmlTree.NOSCRIPT( HtmlTree.DIV(getResource("doclet.No_Script_Message"))); noframes.addContent(noScript); Content noframesHead = HtmlTree.HEADING(Ht...
java
private void addAllPackagesFrameTag(Content contentTree) { HtmlTree frame = HtmlTree.FRAME(DocPaths.OVERVIEW_FRAME.getPath(), "packageListFrame", configuration.getText("doclet.All_Packages")); contentTree.addContent(frame); }
java
private void addAllClassesFrameTag(Content contentTree) { HtmlTree frame = HtmlTree.FRAME(DocPaths.ALLCLASSES_FRAME.getPath(), "packageFrame", configuration.getText("doclet.All_classes_and_interfaces")); contentTree.addContent(frame); }
java
private void addClassFrameTag(Content contentTree) { HtmlTree frame = HtmlTree.FRAME(configuration.topFile.getPath(), "classFrame", configuration.getText("doclet.Package_class_and_interface_descriptions"), SCROLL_YES); contentTree.addContent(frame); }
java
public static JCTree declarationFor(final Symbol sym, final JCTree tree) { class DeclScanner extends TreeScanner { JCTree result = null; public void scan(JCTree tree) { if (tree!=null && result==null) tree.accept(this); } public...
java
public static List<Type> types(List<? extends JCTree> trees) { ListBuffer<Type> ts = new ListBuffer<Type>(); for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) ts.append(l.head.type); return ts.toList(); }
java
protected void configure(Properties properties) { _properties = properties; _recipients = properties.getProperty("mail.smtp.to").split(" *[,;] *"); _authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new Passwor...
java
private void initStandardTagsLowercase() { Iterator<String> it = standardTags.iterator(); while (it.hasNext()) { standardTagsLowercase.add(StringUtils.toLowerCase(it.next())); } }
java
public static ApruveResponse<Subscription> get(String suscriptionId) { return ApruveClient.getInstance().get( getSubscriptionsPath() + suscriptionId, Subscription.class); }
java
public static ApruveResponse<SubscriptionCancelResponse> cancel( String subscriptionId) { return ApruveClient.getInstance().post(getCancelPath(subscriptionId), "", SubscriptionCancelResponse.class); }
java
public boolean handleNextTask() { Runnable task = this.getNextTask(); if (task != null) { synchronized (this.tasksReachesZero) { this.runningTasks++; } try { task.run(); } catch (Throwable t) { t.printStackTrace(); } synchronized (this.tasksReachesZero) { this.runningTasks--; ...
java
public <T extends Runnable> T executeSync(T runnable) { synchronized (runnable) { this.executeAsync(runnable); try { runnable.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } return runnable; }
java
public <T extends Runnable> T executeSyncTimed(T runnable, long inMs) { try { Thread.sleep(inMs); this.executeSync(runnable); } catch (InterruptedException e) { e.printStackTrace(); } return runnable; }
java
public <T extends Runnable> T executeAsyncTimed(T runnable, long inMs) { final Runnable theRunnable = runnable; // This implementation is not really suitable for now as the timer uses its own thread // The TaskQueue itself should be able in the future to handle this without using a new thread Timer timer = new...
java
protected boolean waitForTasks() { synchronized (this.tasks) { while (!this.closed && !this.hasTaskPending()) { try { this.tasks.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } return !this.closed; }
java
public void waitAllTasks() { synchronized (this.tasks) { while (this.hasTaskPending()) { try { this.tasks.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized (this.tasksReachesZero) { if (this.runningTasks > 0) { try { this.tasksReachesZero.wa...
java
protected List<SchemaDescriptor> scanConnection(String url, String user, String password, String infoLevelName, String bundledDriverName, Properties properties, Store store) throws IOException { LOGGER.info("Scanning schema '{}'", url); Catalog catalog...
java
protected Catalog getCatalog(String url, String user, String password, String infoLevelName, String bundledDriverName, Properties properties) throws IOException { // Determine info level InfoLevel level = InfoLevel.valueOf(infoLevelName.toLowerCase()); SchemaInfoLevel schemaInfoLevel...
java
private SchemaCrawlerOptions getOptions(String bundledDriverName, InfoLevel level) throws IOException { for (BundledDriver bundledDriver : BundledDriver.values()) { if (bundledDriver.name().toLowerCase().equals(bundledDriverName.toLowerCase())) { return bundledDriver.getOptions(level...
java
private List<SchemaDescriptor> createSchemas(Catalog catalog, Store store) throws IOException { List<SchemaDescriptor> schemaDescriptors = new ArrayList<>(); Map<String, ColumnTypeDescriptor> columnTypes = new HashMap<>(); Map<Column, ColumnDescriptor> allColumns = new HashMap<>(); Set<F...
java
private void createTables(Catalog catalog, Schema schema, SchemaDescriptor schemaDescriptor, Map<String, ColumnTypeDescriptor> columnTypes, Map<Column, ColumnDescriptor> allColumns, Set<ForeignKey> allForeignKeys, Store store) { for (Table table : catalog.getTables(schema)) { ...
java
private <T extends BaseColumnDescriptor> T createColumnDescriptor(BaseColumn column, Class<T> descriptorType, Map<String, ColumnTypeDescriptor> columnTypes, Store store) { T columnDescriptor = store.create(descriptorType); columnDescr...
java
private void createForeignKeys(Set<ForeignKey> allForeignKeys, Map<Column, ColumnDescriptor> allColumns, Store store) { // Foreign keys for (ForeignKey foreignKey : allForeignKeys) { ForeignKeyDescriptor foreignKeyDescriptor = store.create(ForeignKeyDescriptor.class); foreignKeyD...
java
private void createRoutines(Collection<Routine> routines, SchemaDescriptor schemaDescriptor, Map<String, ColumnTypeDescriptor> columnTypes, Store store) throws IOException { for (Routine routine : routines) { RoutineDescriptor routineDescriptor; String returnType; ...
java
private void createSequences(Collection<Sequence> sequences, SchemaDescriptor schemaDescriptor, Store store) { for (Sequence sequence : sequences) { SequenceDesriptor sequenceDesriptor = store.create(SequenceDesriptor.class); sequenceDesriptor.setName(sequence.getName()); seq...
java
private TableDescriptor getTableDescriptor(Table table, SchemaDescriptor schemaDescriptor, Store store) { TableDescriptor tableDescriptor; if (table instanceof View) { View view = (View) table; ViewDescriptor viewDescriptor = store.create(ViewDescriptor.class); viewDe...
java
private <I extends IndexDescriptor> I storeIndex(Index index, TableDescriptor tableDescriptor, Map<String, ColumnDescriptor> columns, Class<I> indexType, Class<? extends OnColumnDescriptor> onColumnType, Store store) { I indexDescriptor = store.create(indexTy...
java
private ColumnTypeDescriptor getColumnTypeDescriptor(ColumnDataType columnDataType, Map<String, ColumnTypeDescriptor> columnTypes, Store store) { String databaseSpecificTypeName = columnDataType.getDatabaseSpecificTypeName(); ColumnTypeDescriptor columnTypeDescriptor = columnTypes.get(databaseSpecificTy...
java
public static ProfilePackageSummaryBuilder getInstance(Context context, PackageDoc pkg, ProfilePackageSummaryWriter profilePackageWriter, Profile profile) { return new ProfilePackageSummaryBuilder(context, pkg, profilePackageWriter, profile); }
java
public void addItem(Point coordinates, Drawable item) { assertEDT(); if (coordinates == null || item == null) { throw new IllegalArgumentException("Coordinates and added item cannot be null"); } log.trace("[addItem] New item added @ {}", coordinates); getPanelAt(coordinates).addModel(item); getPanelAt(coordi...
java
public void moveItem(Point oldCoordinates, Point newCoordinates) { assertEDT(); if (oldCoordinates == null || newCoordinates == null) { throw new IllegalArgumentException("Coordinates cannot be null"); } if (getPanelAt(newCoordinates).hasModel()) { throw new IllegalStateException( "New position cont...
java
public void clear() { assertEDT(); log.debug("[clear] Cleaning board"); for (int row = 0; row < SIZE; row++) { for (int col = 0; col < SIZE; col++) { removeItem(new Point(col, row)); } } }
java
public void refresh(Point coordinates) { assertEDT(); if (coordinates == null) { throw new IllegalArgumentException("Coordinates cannot be null"); } getPanelAt(coordinates).repaint(); }
java
public TablePanel removeAll() { for (int i = 0; i < content.length; ++i) for (int j = 0; j < content[i].length; ++j) content[i][j] = null; this.sendElement(); return this; }
java
public TablePanel remove(Widget widget) { for (int i = 0; i < content.length; ++i) for (int j = 0; j < content[i].length; ++j) if (content[i][j] == widget) content[i][j] = null; this.sendElement(); return this; }
java
public TablePanel put(Widget widget, int x, int y) { if (x < 0 || y < 0 || x >= content.length || y >= content[x].length) throw new IndexOutOfBoundsException(); attach(widget); content[x][y] = widget; this.sendElement(); return this; }
java
private Map<String, String> loadProperties(ServiceReference reference) { log.trace("loadProperties"); Map<String, String> properties = new HashMap<String, String>(); properties.put("id", OsgiUtil.toString( reference.getProperty(Constants.SERVICE_ID), "")); properties.put("class", OsgiUtil.toString( ref...
java
private void renderBlock(HttpServletResponse res, String templateName, Map<String, String> properties) throws IOException { InputStream is = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); String template = null; try { is = getClass().getClassLoader().getResourceAsStream(templateName); ...
java
private void unmarshall() { sheetData = sheet.getJaxbElement().getSheetData(); rows = sheetData.getRow(); if(rows != null && rows.size() > 0) { Row r = (Row)rows.get(0); numColumns = r.getC().size(); } }
java
public int getRows() { if(sheetData == null) unmarshall(); int ret = 0; if(rows != null) ret = rows.size(); return ret; }
java
public static ManifestVersion get(final Class<?> clazz) { final String manifestUrl = ClassExtensions.getManifestUrl(clazz); try { return of(manifestUrl != null ? new URL(manifestUrl) : null); } catch (final MalformedURLException ignore) { return of(null); } }
java
@Override public Object processTask(String taskName, Map<String, String[]> parameterMap) { if ("createAdmin".equalsIgnoreCase(taskName)) { return userService.createDefaultAdmin(); } return null; }
java
public ValueType get(final KeyType... keys) { if (ArrayUtils.isEmpty(keys)) { return null; } int keysLength = keys.length; if (keysLength == 1) { return get(keys[0]); } else { StorageComponent<KeyType, ValueType> storageComponent = this; ...
java
public void put(final ValueType value, final KeyType... keys) { if (ArrayUtils.isEmpty(keys)) { return; } int keysLength = keys.length; if (keysLength == 1) { put(value, keys[0]); } else { StorageComponent<KeyType, ValueType> childStorageCompo...
java
public StorageComponent<KeyType, ValueType> getStorageComponent(final KeyType key) { KeyToStorageComponent<KeyType, ValueType> storage = getkeyToStorage(); StorageComponent<KeyType, ValueType> storageComponent = storage.get(key); if (storageComponent == null) { storageComponent = ne...
java
public boolean add(T element, Class<?> accessibleClass) { boolean added = false; while (accessibleClass != null && accessibleClass != this.baseClass) { added |= this.addSingle(element, accessibleClass); for (Class<?> interf : accessibleClass.getInterfaces()) { this.addSingle(element, interf); } a...
java
public void remove(T element, Class<?> accessibleClass) { while (accessibleClass != null && accessibleClass != this.baseClass) { this.removeSingle(element, accessibleClass); for (Class<?> interf : accessibleClass.getInterfaces()) { this.removeSingle(element, interf); } accessibleClass = accessibleCl...
java
private static void _readIBANDataFromXML () { final IMicroDocument aDoc = MicroReader.readMicroXML (new ClassPathResource ("codelists/iban-country-data.xml")); if (aDoc == null) throw new InitializationException ("Failed to read IBAN country data [1]"); if (aDoc.getDocumentElement () == null) ...
java
@Nullable public static IBANCountryData getCountryData (@Nonnull final String sCountryCode) { ValueEnforcer.notNull (sCountryCode, "CountryCode"); return s_aIBANData.get (sCountryCode.toUpperCase (Locale.US)); }
java
@Nullable public static String unifyIBAN (@Nullable final String sIBAN) { if (sIBAN == null) return null; // to uppercase String sRealIBAN = sIBAN.toUpperCase (Locale.US); // kick all non-IBAN chars sRealIBAN = RegExHelper.stringReplacePattern ("[^0-9A-Z]", sRealIBAN, ""); if (sRealI...
java
public static boolean isValidIBAN (@Nullable final String sIBAN, final boolean bReturnCodeIfNoCountryData) { // kick all non-IBAN chars final String sRealIBAN = unifyIBAN (sIBAN); if (sRealIBAN == null) return false; // is the country supported? final IBANCountryData aData = s_aIBANData.get...
java
public void buildContent(XMLNode node, Content contentTree) { Content packageContentTree = packageWriter.getContentHeader(); buildChildren(node, packageContentTree); contentTree.addContent(packageContentTree); }
java
public JavaFileObject asJavaFileObject(File file) { JavacFileManager fm = (JavacFileManager)context.get(JavaFileManager.class); return fm.getRegularFile(file); }
java
public Iterable<? extends CompilationUnitTree> parse() throws IOException { try { prepareCompiler(); List<JCCompilationUnit> units = compiler.parseFiles(fileObjects); for (JCCompilationUnit unit: units) { JavaFileObject file = unit.getSourceFile(); ...
java
public static ClassLoader findMostCompleteClassLoader(Class<?> target) { // Try the most complete class loader we can get ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Then fallback to the class loader from a specific class given if (classLoader == null &&...
java
@Override public void emit(Level level, String message, long sequence) { if (_broadcaster != null) _broadcaster.sendNotification(new Notification( level.toString(), _name != null ? _name : this, sequence, message )); }
java
@Override public <T extends Throwable> T emit(T throwable, String message, long sequence) { if (_broadcaster != null) _broadcaster.sendNotification(new Notification( Level.WARNING.toString(), _name != null ? _name : this, sequence, message == null ? Throwables...
java
@Override public void emit(Level level, String message, long sequence, Logger logger) { emit(level, message, sequence); logger.log(level, message); }
java
@Override public <T extends Throwable> T emit(T throwable, String message, long sequence, Logger logger) { message = message == null ? Throwables.getFullMessage(throwable) : message + ": " + Throwables.getFullMessage(throwable); emit(Level.WARNING, message, sequence, logger); return throwabl...
java
public ArrayList<SchemaField> getSchema() { final ArrayList<SchemaField> items = new ArrayList<SchemaField>(schemaFields.values()); Collections.sort(items, new Comparator<SchemaField>() { @Override public int compare(final SchemaField left, final SchemaField right) ...
java
PlatformControl bind(ServicePlatform p, XmlWebApplicationContext c, ClassLoader l) { _platform = p; _root = c; _cloader = l; return this; }
java
public static boolean isSafeMediaType(final String mediaType) { return mediaType != null && VALID_MIME_TYPE.matcher(mediaType).matches() && !DANGEROUS_MEDIA_TYPES.contains(mediaType); }
java
public WriteStream writeStream() { detachReader(); if (writer == null) { writer = new BytesWriteStream(bytes, maxCapacity); } return writer; }
java
public ReadStream readStream() { detachWriter(); if (reader == null) { reader = new BytesReadStream(bytes, 0, length); } return reader; }
java
public void add(Collection<Entity> entities) { for(Entity entity : entities) this.entities.put(entity.getId(), entity); }
java
@Override public Class<?> loadClass(String classname) throws ClassNotFoundException { return getClass().getClassLoader().loadClass(classname); }
java
@Override public ResourceSchema getSchema(final String location, final Job job) throws IOException { final List<Schema.FieldSchema> schemaList = new ArrayList<Schema.FieldSchema>(); for (final GoodwillSchemaField field : schema.getSchema()) { schemaList.add(new Schema.FieldSchema(fie...
java
public static String getUserApplicationConfigurationFilePath( @NonNull final String applicationName, @NonNull final String configFileName) { return System.getProperty(USER_HOME_PROPERTY_KEY) + File.separator + applicationName + File.separator + configFileName; }
java
public static String getTemporaryApplicationConfigurationFilePath( @NonNull final String applicationName, @NonNull final String fileName) { return System.getProperty(JAVA_IO_TPMDIR_PROPERTY_KEY) + File.separator + applicationName + File.separator + fileName; }
java
public static <T> T instantiateClass(final Class<T> clazz) throws IllegalArgumentException, BeanInstantiationException { return instantiateClass(clazz, MethodUtils.EMPTY_PARAMETER_CLASSTYPES, MethodUtils.EMPTY_PARAMETER_VALUES); }
java