_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q177400
MapperComplex.setFieldValueFromMap
test
private void setFieldValueFromMap( final Object parentObject, final FieldAccess field, final Map mapInner ) { Class<?> fieldClassType = field.type(); Object value = null; /* Is the field not a map. */ if ( !Typ.isMap( fieldClassType ) ) { if ( !fieldClassType.isInterface() && !Typ.isAbstract( fieldClassType ) ) { value = fromMap( mapInner, field.type() ); } else { Object oClassName = mapInner.get( "class" ); if (oClassName != null) { value = fromMap( mapInner, Reflection.loadClass( oClassName.toString() )); } else { value = null; } } /* REFACTOR: This is at least the third time that I have seen this code in the class. It was either cut and pasted or I forgot I wrote it three times. REFACTOR: */ } else if (Typ.isMap( fieldClassType )) { Class keyType = (Class)field.getParameterizedType().getActualTypeArguments()[0]; Class valueType = (Class)field.getParameterizedType().getActualTypeArguments()[1]; Set<Map.Entry> set = mapInner.entrySet(); Map newMap = new LinkedHashMap( ); for (Map.Entry entry : set) { Object evalue = entry.getValue(); Object key = entry.getKey(); if (evalue instanceof ValueContainer) { evalue = ((ValueContainer) evalue).toValue(); } key = Conversions.coerce(keyType, key); evalue = Conversions.coerce( valueType, evalue ); newMap.put( key, evalue ); } value = newMap; } field.setValue(parentObject, value); }
java
{ "resource": "" }
q177401
MapperComplex.toList
test
@Override public List<?> toList(Object object) { TypeType instanceType = TypeType.getInstanceType(object); switch (instanceType) { case NULL: return Lists.list((Object)null); case ARRAY: case ARRAY_INT: case ARRAY_BYTE: case ARRAY_SHORT: case ARRAY_FLOAT: case ARRAY_DOUBLE: case ARRAY_LONG: case ARRAY_STRING: case ARRAY_OBJECT: return Conversions.toList(object); case INSTANCE: if (Reflection.respondsTo(object, "toList")) { return (List<?>) Reflection.invoke(object, "toList"); } break; } return Lists.list(object); }
java
{ "resource": "" }
q177402
BaseVersionedMySQLSupport.createLoadAllVersionDataSQL
test
protected void createLoadAllVersionDataSQL(String table) { CharBuf buf = CharBuf.create(100); buf.add("select kv_key, 1, version, update_timestamp, create_timestamp from `"); buf.add(table); buf.add("` where kv_key in ("); buf.multiply("?,", this.loadKeyCount); buf.removeLastChar(); buf.add(");"); this.loadAllVersionDataByKeysSQL = buf.toString(); }
java
{ "resource": "" }
q177403
Lists.deepCopy
test
@Universal public static <V> List<V> deepCopy( List<V> list ) { if ( list instanceof LinkedList ) { return deepCopyToList( list, new LinkedList<V>( ) ); } else if ( list instanceof CopyOnWriteArrayList ) { return deepCopyToList( list, new CopyOnWriteArrayList<V>( )); } else { return deepCopy( (Collection)list); } }
java
{ "resource": "" }
q177404
Fields.hasStringField
test
public static boolean hasStringField( final Object value1, final String name ) { Class<?> clz = value1.getClass(); return classHasStringField( clz, name ); }
java
{ "resource": "" }
q177405
Fields.classHasStringField
test
public static boolean classHasStringField( Class<?> clz, String name ) { List<Field> fields = Reflection.getAllFields( clz ); for ( Field field : fields ) { if ( field.getType().equals( Typ.string ) && field.getName().equals( name ) && !Modifier.isStatic( field.getModifiers() ) && field.getDeclaringClass() == clz ) { return true; } } return false; }
java
{ "resource": "" }
q177406
Fields.classHasField
test
public static boolean classHasField( Class<?> clz, String name ) { List<Field> fields = Reflection.getAllFields( clz ); for ( Field field : fields ) { if ( field.getName().equals( name ) && !Modifier.isStatic( field.getModifiers() ) && field.getDeclaringClass() == clz ) { return true; } } return false; }
java
{ "resource": "" }
q177407
Fields.getFirstComparableOrPrimitiveFromClass
test
public static String getFirstComparableOrPrimitiveFromClass( Class<?> clz ) { List<Field> fields = Reflection.getAllFields( clz ); for ( Field field : fields ) { if ( ( field.getType().isPrimitive() || Typ.isComparable( field.getType() ) && !Modifier.isStatic( field.getModifiers() ) && field.getDeclaringClass() == clz ) ) { return field.getName(); } } return null; }
java
{ "resource": "" }
q177408
Fields.getSortableField
test
public static String getSortableField( Object value1 ) { if (value1 instanceof Map) { return getSortableFieldFromMap( (Map<String, ?>) value1); } else { return getSortableFieldFromClass( value1.getClass() ); } }
java
{ "resource": "" }
q177409
CacheEntry.compareTo
test
@Override public final int compareTo( CacheEntry other ) { switch ( type ) { case LFU: return compareToLFU( other ); case LRU: return compareToLRU( other ); case FIFO: return compareToFIFO( other ); default: die(); return 0; } }
java
{ "resource": "" }
q177410
CacheEntry.compareTime
test
private final int compareTime( CacheEntry other ) { if ( time > other.time ) { //this time stamp is greater so it has higher priority return 1; } else if ( time < other.time ) {//this time stamp is lower so it has lower priority return -1; } else if ( time == other.time ) {//equal priority return 0; } die(); return 0; }
java
{ "resource": "" }
q177411
Sorting.sort
test
public static void sort(List list, Sort... sorts) { Sort.sorts(sorts).sort(list); }
java
{ "resource": "" }
q177412
Sorting.sort
test
public static void sort( List list, String sortBy, boolean ascending, boolean nullsFirst ) { if ( list == null || list.size() == 0 ) { return; } if (sortBy.equals("this")) { Collections.sort(list, thisUniversalComparator(ascending, nullsFirst)); return; } Iterator iterator = list.iterator(); Object object = iterator.next(); Map<String, FieldAccess> fields = null; if (object != null) { fields = BeanUtils.getFieldsFromObject( object ); } else { while(iterator.hasNext()) { object = iterator.next(); if (object!=null) { fields = BeanUtils.getFieldsFromObject( object ); break; } } } if (fields!=null) { final FieldAccess field = fields.get( sortBy ); if ( field != null ) { Collections.sort( list, Sorting.universalComparator(field, ascending, nullsFirst) ); } } }
java
{ "resource": "" }
q177413
Sorting.sortEntries
test
public static <K, V> Collection<Map.Entry<K, V>> sortEntries( Class<V> componentType, Map<K, V> map, String sortBy, boolean ascending, boolean nullsFirst ) { return sort ((Class) componentType, (Collection) map.entrySet() , sortBy, ascending, nullsFirst); }
java
{ "resource": "" }
q177414
Sorting.sortValues
test
public static <K, V> Collection<Map.Entry<K, V>> sortValues( Class<V> componentType, Map<K, V> map, String sortBy, boolean ascending, boolean nullsFirst ) { return sort ((Class) componentType, (Collection) map.values() , sortBy, ascending, nullsFirst); }
java
{ "resource": "" }
q177415
Sorting.sortKeys
test
public static <K, V> Collection<Map.Entry<K, V>> sortKeys( Class<V> componentType, Map<K, V> map, String sortBy, boolean ascending, boolean nullsFirst ) { return sort ((Class) componentType, (Collection) map.keySet() , sortBy, ascending, nullsFirst); }
java
{ "resource": "" }
q177416
Sorting.sort
test
public static <T> void sort( T[] array, String sortBy, boolean ascending, boolean nullsFirst ) { if ( array == null || array.length == 0 ) { return; } if (sortBy.equals("this")) { Arrays.sort(array, thisUniversalComparator(ascending, nullsFirst)); return; } Object object = array[0]; Map<String, FieldAccess> fields = null; if (object != null) { fields = BeanUtils.getFieldsFromObject( object ); } else { for (int index=1; index< array.length; index++) { object = array[index]; if (object!=null) { fields = BeanUtils.getFieldsFromObject( object ); break; } } } if (fields!=null) { final FieldAccess field = fields.get( sortBy ); if ( field != null ) { Arrays.sort( array, Sorting.universalComparator(field, ascending, nullsFirst) ); } } }
java
{ "resource": "" }
q177417
Sorting.universalComparator
test
public static Comparator universalComparator( final FieldAccess field, final boolean ascending, final boolean nullsFirst) { return new Comparator() { @Override public int compare( Object o1, Object o2 ) { Object value1 = null; Object value2 = null; if ( ascending ) { value1 = field.getValue( o1 ); value2 = field.getValue( o2 ); } else { value1 = field.getValue( o2 ); value2 = field.getValue( o1 ); } return Sorting.compare(value1, value2, nullsFirst); } }; }
java
{ "resource": "" }
q177418
Sorting.thisUniversalComparator
test
public static Comparator thisUniversalComparator( final boolean ascending, final boolean nullsFirst) { return new Comparator() { @Override public int compare( Object o1, Object o2 ) { Object value1; Object value2; if ( ascending ) { value1 = ( o1 ); value2 = ( o2 ); } else { value1 = ( o2 ); value2 = ( o1 ); } return Sorting.compare(value1, value2, nullsFirst); } }; }
java
{ "resource": "" }
q177419
FastConcurrentReadLruLfuFifoCache.get
test
public VALUE get( KEY key ) { CacheEntry<KEY, VALUE> cacheEntry = map.get( key ); if ( cacheEntry != null ) { cacheEntry.readCount.incrementAndGet(); return cacheEntry.value; } else { return null; } }
java
{ "resource": "" }
q177420
FastConcurrentReadLruLfuFifoCache.getSilent
test
public VALUE getSilent( KEY key ) { CacheEntry<KEY, VALUE> cacheEntry = map.get( key ); if ( cacheEntry != null ) { return cacheEntry.value; } else { return null; } }
java
{ "resource": "" }
q177421
FastConcurrentReadLruLfuFifoCache.order
test
private final int order() { int order = count.incrementAndGet(); if ( order > Integer.MAX_VALUE - 100 ) { count.set( 0 ); } return order; }
java
{ "resource": "" }
q177422
FastConcurrentReadLruLfuFifoCache.evictIfNeeded
test
private final void evictIfNeeded() { if ( list.size() > evictSize ) { final List<CacheEntry<KEY, VALUE>> killList = list.sortAndReturnPurgeList( 0.1f ); for ( CacheEntry<KEY, VALUE> cacheEntry : killList ) { map.remove( cacheEntry.key ); } } }
java
{ "resource": "" }
q177423
LongRangeValidator.dynamicallyInitIfNeeded
test
private void dynamicallyInitIfNeeded( Object value ) { /* Check to see if this class was already initialized, * if not, initialize it based on the type of the value. */ if ( !isInitialized() ) { if ( value instanceof Integer ) { init( new Integer( min.intValue() ), new Integer( max.intValue() ) ); } else if ( value instanceof Byte ) { init( new Byte( min.byteValue() ), new Byte( max.byteValue() ) ); } else if ( value instanceof Short ) { init( new Short( min.shortValue() ), new Short( max.shortValue() ) ); } else { init( min, max ); } } }
java
{ "resource": "" }
q177424
CollectorManager.allocateBuffer
test
public final ByteBuffer allocateBuffer(int size) { if (RECYCLE_BUFFER) { ByteBuffer spentBuffer = recycleChannel.poll(); if (spentBuffer == null) { spentBuffer = ByteBuffer.allocateDirect(size); } spentBuffer.clear(); return spentBuffer; } else { return ByteBuffer.allocateDirect(size); } }
java
{ "resource": "" }
q177425
CollectorManager.determineIfWeShouldExit
test
private boolean determineIfWeShouldExit() { boolean shouldStop = stop.get(); if (!shouldStop) { Thread.interrupted(); } else { System.out.println("Exiting processing loop as requested"); return true; } return false; }
java
{ "resource": "" }
q177426
CollectorManager.manageInputWriterChannel
test
private void manageInputWriterChannel() throws InterruptedException { try { ByteBuffer dataToWriteToFile; dataToWriteToFile = inputChannel.poll(); //no wait //If it is null, it means the inputChannel is empty and we need to flush. if (dataToWriteToFile == null) { queueEmptyMaybeFlush(); dataToWriteToFile = inputChannel.poll(); } //If it is still null, this means that we need to wait //for more items to show up in the inputChannel. if (dataToWriteToFile == null) { dataToWriteToFile = waitForNextDataToWrite(); } //We have to check for null again because we could have been interrupted. if (dataToWriteToFile != null) { //Write it writer.nextBufferToWrite(dataToWriteToFile); //Then give it back if (RECYCLE_BUFFER) { recycleChannel.offer(dataToWriteToFile); } } } catch (InterruptedException ex) { throw ex; } catch (Exception ex) { ex.printStackTrace(); ex.printStackTrace(System.err); } }
java
{ "resource": "" }
q177427
CollectorManager.queueEmptyMaybeFlush
test
private void queueEmptyMaybeFlush() { if (PERIODIC_FORCE_FLUSH) { long currentTime = time.get(); /* Try not to flush more than once every x times per mili-seconds time period. */ if ((currentTime - lastFlushTime) > FORCE_FLUSH_AFTER_THIS_MANY_MILI_SECONDS) { /* If the writer had things to flush, and we flushed then increment the number of flushes. */ if (writer.syncToDisk()) { //could take 100 ms to 1 second this.numberOfFlushesTotal.incrementAndGet(); } /* We update the flush time no matter what. */ lastFlushTime = time.get(); } } }
java
{ "resource": "" }
q177428
CollectorManager.startMonitor
test
private void startMonitor() { final ScheduledExecutorService monitor = Executors.newScheduledThreadPool(2, new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable); thread.setPriority(Thread.NORM_PRIORITY + 1); return thread; } } ); monitorFuture = monitor.scheduleAtFixedRate(new Runnable() { @Override public void run() { monitor(); } }, MONITOR_INTERVAL_SECONDS, MONITOR_INTERVAL_SECONDS, TimeUnit.SECONDS); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { System.err.println("shutting down...."); monitor(); } })); }
java
{ "resource": "" }
q177429
CollectorManager.start
test
public void start(final TimeAware receiver) { //This starts itself up again every 1/2 second if something really bad //happens like disk full. As soon as the problem gets corrected //then things start working again...happy day. Only // one is running per instance of CollectionManagerImpl. writerFuture = scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { processWrites(); } }, 0, 500, TimeUnit.MILLISECONDS); startMonitor(); tickTock = this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { long time = System.nanoTime() / 1_000_000; if (receiver != null) { receiver.tick(time); } tick(time); } }, 0, 20, TimeUnit.MILLISECONDS); }
java
{ "resource": "" }
q177430
LazyValueMap.get
test
@Override public final Object get( Object key ) { Object object=null; /* if the map is null, then we create it. */ if ( map == null ) { buildMap (); } object = map.get ( key ); lazyChopIfNeeded ( object ); return object; }
java
{ "resource": "" }
q177431
FilterDefault.mainQueryPlan
test
private ResultSet mainQueryPlan( Criteria[] expressions ) { ResultSetInternal results = new ResultSetImpl( this.fields ); if (expressions == null || expressions.length == 0) { results.addResults ( searchableCollection.all() ); } /* I am sure this looked easy to read when I wrote it. * If there is only one expression and first expression is a group then * the group is that first expression otherwise wrap * all of the expressions in an and clause. */ Group group = expressions.length == 1 && expressions[ 0 ] instanceof Group ? ( Group ) expressions[ 0 ] : ObjectFilter.and( expressions ); /** * Run the filter on the group. */ doFilterGroup( group, results ); return results; }
java
{ "resource": "" }
q177432
FilterDefault.doFilterGroup
test
private void doFilterGroup( Group group, ResultSetInternal results ) { /* The group was n or group so handle it that way. */ if ( group.getGrouping() == Grouping.OR ) { /* nice short method name, or. */ or( group.getExpressions(), fields, results ); } else { /* create a result internal (why?), wrap the fields in the result set internal, and pass that to the and method. */ ResultSetInternal resultsForAnd = new ResultSetImpl( fields ); and( group.getExpressions(), fields, resultsForAnd ); results.addResults( resultsForAnd.asList() ); } }
java
{ "resource": "" }
q177433
BatchFileWriter.tick
test
public void tick(long time) { this.time.set(time); long startTime = fileStartTime.get(); long duration = time - startTime; if (duration > FILE_TIMEOUT_MILISECONDS) { fileTimeOut.set(true); } }
java
{ "resource": "" }
q177434
BatchFileWriter.syncToDisk
test
public boolean syncToDisk() { /** if we have a stream and we are dirty then flush. */ if (outputStream != null && dirty) { try { //outputStream.flush (); if (outputStream instanceof FileChannel) { FileChannel channel = (FileChannel) outputStream; channel.force(true); } dirty = false; return true; } catch (Exception ex) { cleanupOutputStream(); return false; } } else { return false; } }
java
{ "resource": "" }
q177435
BatchFileWriter.cleanupOutputStream
test
private void cleanupOutputStream() { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(System.err); } finally { outputStream = null; } } }
java
{ "resource": "" }
q177436
BatchFileWriter.nextBufferToWrite
test
public void nextBufferToWrite(final ByteBuffer bufferOut) throws InterruptedException { dirty = true; final int size = bufferOut.limit(); write(bufferOut); /* only increment bytes transferred after a successful write. */ if (!error.get()) { totalBytesTransferred += size; bytesTransferred += size; bytesSinceLastFlush += size; buffersSent++; } if (this.bytesTransferred >= FILE_SIZE_BYTES || fileTimeOut.get()) { try { outputStream.close(); } catch (IOException e) { cleanupOutputStream(); e.printStackTrace(System.err); } finally { outputStream = null; } } }
java
{ "resource": "" }
q177437
BatchFileWriter.write
test
private void write(final ByteBuffer bufferOut) throws InterruptedException { initOutputStream(); try { if (outputStream != null) { outputStream.write(bufferOut); } else { error.set(true); } if (bytesSinceLastFlush > FLUSH_EVERY_N_BYTES) { syncToDisk(); bytesSinceLastFlush = 0; } } catch (ClosedByInterruptException cbie) { throw new InterruptedException("File closed by interruption"); } catch (Exception e) { cleanupOutputStream(); error.set(true); e.printStackTrace(System.err); diagnose(); Exceptions.handle(e); } }
java
{ "resource": "" }
q177438
BatchFileWriter.initOutputStream
test
private void initOutputStream() { long time = this.time.get(); if (error.get() || this.totalBytesTransferred == 0) { cleanupOutputStream(); error.set(false); time = System.nanoTime() / 1_000_000; } if (outputStream != null) { return; } fileName = LogFilesConfig.getLogFileName(FORMAT_PATTERN, outputDirPath(), numFiles, time, SERVER_NAME); try { fileTimeOut.set(false); outputStream = streamCreator(); fileStartTime.set(time); bytesTransferred = 0; bytesSinceLastFlush = 0; } catch (Exception ex) { cleanupOutputStream(); error.set(true); Exceptions.handle(ex); } finally { numFiles++; } }
java
{ "resource": "" }
q177439
BaseStringStringKeyValueStore.putAll
test
public void putAll(Map<K, V> values) { Set<Map.Entry<K, V>> entries = values.entrySet(); Map<String, String> map = new HashMap<>(values.size()); for (Map.Entry<K, V> entry : entries) { map.put(toKeyString(entry.getKey()), toValueString(entry.getValue())); } store.putAll(map); }
java
{ "resource": "" }
q177440
BaseSimpleSerializationKeyValueStore.toKeyBytes
test
protected byte[] toKeyBytes(K key) { byte[] keyBytes = keyCache.get(key); if (keyBytes == null) { keyBytes = this.keyToByteArrayConverter.apply(key); keyCache.put(key, keyBytes); } return keyBytes; }
java
{ "resource": "" }
q177441
PropertiesFileValidatorMetaDataReader.readMetaData
test
public List<ValidatorMetaData> readMetaData( Class<?> clazz, String propertyName ) { /* Load the properties file. */ Properties props = loadMetaDataPropsFile( clazz ); /* Get the raw validation data for the given property. */ String unparsedString = props.getProperty( propertyName ); /* Parse the string into a list of ValidationMetaData. */ return extractMetaDataFromString( clazz, propertyName, unparsedString ); }
java
{ "resource": "" }
q177442
PropertiesFileValidatorMetaDataReader.extractMetaDataFromString
test
private List<ValidatorMetaData> extractMetaDataFromString( Class<?> clazz, String propertyName, String unparsedString ) { String propertyKey = clazz.getName() + "." + propertyName; /* See if we parsed this bad boy already. */ List<ValidatorMetaData> validatorMetaDataList = metaDataCache.get( propertyKey ); /* If we did not find the list, then we have some work to do.*/ if ( validatorMetaDataList == null ) { /* Initialize a new list. */ validatorMetaDataList = new ArrayList<ValidatorMetaData>(); /* Remember we have a string that looks like this: * required; length min=10, max=100 * So we need to split on semi-colon. */ String[] validatorsParts = unparsedString.split( "[;]" ); /* Now we have the two strings as follows: * ["required", * ["length min=10, max=100"] * */ for ( String validatorString : validatorsParts ) { ValidatorMetaData validatorMetaData = new ValidatorMetaData(); validatorMetaDataList.add( validatorMetaData ); /* Now we split one of the string (we will use length) * as follows: * parts=["length", "min=10", "max=100"] * */ String[] parts = validatorString.trim().split( "[ ,]" ); /* The first part is the name of the validation, * e.g., "length". * */ validatorMetaData.setName( parts[ 0 ] ); /* If the string has more than one part, then there must * be arguments as in: ["min=10", "max=100"] * * Parse the arguments and addObject them to the list as well. */ if ( parts.length > 1 ) { /* This line converts: * * ["length", "min=10", "max=100"] * * into: * * ["min=10", "max=100"] */ List<String> values = Arrays.asList( parts ).subList( 1, parts.length ); /* For each value convert it into name value pairs. */ for ( String value : values ) { if ( value.indexOf( "=" ) != -1 ) { /* Split "min=10" into ["min", "10"] */ String[] valueParts = value.split( "[=]" ); /* Stick this value into validatorMetaData's * list of properties. */ validatorMetaData.getProperties().put( valueParts[ 0 ], valueParts[ 1 ] ); } } } } metaDataCache.put( propertyKey, validatorMetaDataList ); } return validatorMetaDataList; }
java
{ "resource": "" }
q177443
AnnotationValidatorMetaDataReader.readMetaData
test
public List<ValidatorMetaData> readMetaData( Class<?> clazz, String propertyName ) { /* Generate a key to the cache based on the classname and the propertyName. */ String propertyKey = clazz.getName() + "." + propertyName; /* Look up the validation meta data in the cache. */ List<ValidatorMetaData> validatorMetaDataList = metaDataCache.get( propertyKey ); /* If the meta-data was not found, then generate it. */ if ( validatorMetaDataList == null ) { // if not found validatorMetaDataList = extractValidatorMetaData( clazz, propertyName, validatorMetaDataList ); /* Put it in the cache to avoid the processing in the future. * Design notes: The processing does a lot of reflection, there * is no need to do this each time. */ metaDataCache.put( propertyKey, validatorMetaDataList ); } return validatorMetaDataList; }
java
{ "resource": "" }
q177444
AnnotationValidatorMetaDataReader.extractValidatorMetaData
test
private List<ValidatorMetaData> extractValidatorMetaData( Class<?> clazz, String propertyName, List<ValidatorMetaData> validatorMetaDataList ) { /* If the meta-data was not found, then generate it. */ if ( validatorMetaDataList == null ) { // if not found /* Read the annotation from the class based on the property name. */ Collection<AnnotationData> annotations = Annotations.getAnnotationDataForFieldAndProperty( clazz, propertyName, this.validationAnnotationPackages ); /* Extract the POJO based meta-data from the annotation. */ validatorMetaDataList = extractMetaDataFromAnnotations( annotations ); } return validatorMetaDataList; }
java
{ "resource": "" }
q177445
AnnotationValidatorMetaDataReader.extractMetaDataFromAnnotations
test
private List<ValidatorMetaData> extractMetaDataFromAnnotations( Collection<AnnotationData> annotations ) { List<ValidatorMetaData> list = new ArrayList<ValidatorMetaData>(); for ( AnnotationData annotationData : annotations ) { ValidatorMetaData validatorMetaData = convertAnnotationDataToValidatorMetaData( annotationData ); list.add( validatorMetaData ); } return list; }
java
{ "resource": "" }
q177446
AnnotationValidatorMetaDataReader.convertAnnotationDataToValidatorMetaData
test
private ValidatorMetaData convertAnnotationDataToValidatorMetaData( AnnotationData annotationData ) { ValidatorMetaData metaData = new ValidatorMetaData(); metaData.setName( annotationData.getName() ); metaData.setProperties( annotationData.getValues() ); return metaData; }
java
{ "resource": "" }
q177447
StringScanner.split
test
public static String[] split( final String string, final char split, final int limit ) { char[][] comps = CharScanner.split( FastStringUtils.toCharArray( string ), split, limit ); return Str.fromCharArrayOfArrayToStringArray( comps ); }
java
{ "resource": "" }
q177448
StringScanner.splitByWhiteSpace
test
public static String[] splitByWhiteSpace( final String string ) { char[][] comps = CharScanner.splitByChars( FastStringUtils.toCharArray( string ), WHITE_SPACE ); return Str.fromCharArrayOfArrayToStringArray( comps ); }
java
{ "resource": "" }
q177449
StringScanner.splitByDelimiters
test
public static String[] splitByDelimiters( final String string, final String delimiters ) { char[][] comps = CharScanner.splitByChars( FastStringUtils.toCharArray( string ), delimiters.toCharArray() ); return Str.fromCharArrayOfArrayToStringArray( comps ); }
java
{ "resource": "" }
q177450
StringScanner.removeChars
test
public static String removeChars( final String string, final char... delimiters ) { char[][] comps = CharScanner.splitByCharsNoneEmpty( FastStringUtils.toCharArray( string ), delimiters ); return new String(Chr.add ( comps )); }
java
{ "resource": "" }
q177451
StringScanner.splitByCharsNoneEmpty
test
public static String[] splitByCharsNoneEmpty( final String string, int start, int end, final char... delimiters ) { Exceptions.requireNonNull( string ); char[][] comps = CharScanner.splitByCharsNoneEmpty( FastStringUtils.toCharArray( string ), start, end, delimiters ); return Str.fromCharArrayOfArrayToStringArray( comps ); }
java
{ "resource": "" }
q177452
StringScanner.parseDouble
test
public static double parseDouble( String buffer, int from, int to ) { return CharScanner.parseDouble( FastStringUtils.toCharArray(buffer), from , to ); }
java
{ "resource": "" }
q177453
StringScanner.parseInt
test
public static int parseInt( String buffer, int from, int to ) { return CharScanner.parseInt( FastStringUtils.toCharArray(buffer), from , to ); }
java
{ "resource": "" }
q177454
StringScanner.parseLong
test
public static long parseLong( String buffer, int from, int to ) { return CharScanner.parseLong( FastStringUtils.toCharArray(buffer), from , to ); }
java
{ "resource": "" }
q177455
BeanUtils.getPropByPath
test
public static Object getPropByPath( Object item, String... path ) { Object o = item; for ( int index = 0; index < path.length; index++ ) { String propName = path[ index ]; if ( o == null ) { return null; } else if ( o.getClass().isArray() || o instanceof Collection ) { o = getCollectionProp(o, propName, index, path); break; } else { o = getProp( o, propName ); } } return Conversions.unifyListOrArray(o); }
java
{ "resource": "" }
q177456
BeanUtils.getFieldsFromObject
test
public static Map<String, FieldAccess> getFieldsFromObject( Object object ) { try { Map<String, FieldAccess> fields; if ( object instanceof Map ) { fields = getFieldsFromMap( ( Map<String, Object> ) object ); } else { fields = getPropertyFieldAccessMap( object.getClass() ); } return fields; } catch (Exception ex) { requireNonNull(object, "Item cannot be null" ); return handle(Map.class, ex, "Unable to get fields from object", className(object)); } }
java
{ "resource": "" }
q177457
BeanUtils.getPropertyType
test
public static Class<?> getPropertyType( final Object root, final String property ) { Map<String, FieldAccess> fields = getPropertyFieldAccessMap( root.getClass() ); FieldAccess field = fields.get( property ); return field.type(); }
java
{ "resource": "" }
q177458
BeanUtils.injectIntoProperty
test
public static void injectIntoProperty( Object object, String path, Object value ) { String[] properties = propertyPathAsStringArray(path); setPropertyValue( object, value, properties ); }
java
{ "resource": "" }
q177459
BeanUtils.idx
test
public static void idx( Class<?> cls, String path, Object value ) { String[] properties = propertyPathAsStringArray(path); setPropertyValue( cls, value, properties ); }
java
{ "resource": "" }
q177460
BeanUtils.getCollectionProp
test
private static Object getCollectionProp(Object o, String propName, int index, String[] path ) { o = _getFieldValuesFromCollectionOrArray(o, propName); if ( index + 1 == path.length ) { return o; } else { index++; return getCollectionProp(o, path[index], index, path); } }
java
{ "resource": "" }
q177461
BeanUtils.getProp
test
public static Object getProp( Object object, final String property ) { if ( object == null ) { return null; } if ( isDigits( property ) ) { /* We can index numbers and names. */ object = idx(object, StringScanner.parseInt(property)); } Class<?> cls = object.getClass(); /** Tries the getters first. */ Map<String, FieldAccess> fields = Reflection.getPropertyFieldAccessors( cls ); if ( !fields.containsKey( property ) ) { fields = Reflection.getAllAccessorFields( cls ); } if ( !fields.containsKey( property ) ) { return null; } else { return fields.get( property ).getValue( object ); } }
java
{ "resource": "" }
q177462
BeanUtils.getPropertyInt
test
public static int getPropertyInt( final Object root, final String... properties ) { final String lastProperty = properties[ properties.length - 1 ]; if ( isDigits( lastProperty ) ) { return Conversions.toInt(getPropertyValue(root, properties)); } Object object = baseForGetProperty( root, properties ); Map<String, FieldAccess> fields = getFieldsFromObject( object ); FieldAccess field = fields.get( lastProperty ); if ( field.type() == Typ.intgr ) { return field.getInt( object ); } else { return Conversions.toInt( field.getValue( object ) ); } }
java
{ "resource": "" }
q177463
MessageSpecification.init
test
public void init() { /* If the parent and name are equal to null, * use the classname to load listFromClassLoader. * */ if ( name == null && parent == null ) { this.setDetailMessage( "{" + this.getClass().getName() + DETAIL_KEY + "}" ); this.setSummaryMessage( "{" + this.getClass().getName() + SUMMARY_KEY + "}" ); /* If the parent is null and the name is not, * use the name to load listFromClassLoader. */ } else if ( name != null && parent == null ) { this.setDetailMessage( "{" + "message." + getName() + DETAIL_KEY + "}" ); this.setSummaryMessage( "{" + "message." + getName() + SUMMARY_KEY + "}" ); /* If the parent is present, initialize the message keys * with the parent name. */ } else if ( parent != null ) { this.setDetailMessage( "{" + "message." + parent + DETAIL_KEY + "}" ); this.setSummaryMessage( "{" + "message." + parent + SUMMARY_KEY + "}" ); } }
java
{ "resource": "" }
q177464
MessageSpecification.createMessage
test
public String createMessage( String key, List<String> argKeys, Object... args ) { /* Look up the message. */ String message = getMessage( key ); /* Holds the actual arguments. */ Object[] actualArgs; /* If they passed arguments, * then use this as the actual arguments. */ if ( args.length > 0 ) { actualArgs = args; /* If they did not pass arguments, use the configured ones. */ } else if ( argKeys != null ) { /* Convert the keys to values. */ actualArgs = keysToValues( argKeys ); } else { actualArgs = new Object[]{ }; } return doCreateMessage( message, actualArgs ); }
java
{ "resource": "" }
q177465
MessageSpecification.doCreateMessage
test
@SuppressWarnings ( "unchecked" ) private String doCreateMessage( String message, Object[] actualArgs ) { return ValidationContext.get().createMessage( message, getSubject(), actualArgs ); }
java
{ "resource": "" }
q177466
MessageSpecification.keysToValues
test
private Object[] keysToValues( List<String> argKeys ) { List<String> values = new ArrayList<>(); for ( String key : argKeys ) { values.add( getMessage( key ) ); } return values.toArray(); }
java
{ "resource": "" }
q177467
MessageSpecification.getSubject
test
public String getSubject() { return ValidationContext.get().getCurrentSubject() == null ? this.subject : ValidationContext.get().getCurrentSubject(); }
java
{ "resource": "" }
q177468
JsonSlurper.parseText
test
public Object parseText(String text) { if (text == null || text.length() == 0) { throw new IllegalArgumentException("The JSON input text should neither be null nor empty."); } return JsonFactory.create().fromJson ( text ); }
java
{ "resource": "" }
q177469
EtcdClient.sendHttpRequest
test
private void sendHttpRequest(final Request request, final org.boon.core.Handler<Response> responseHandler) { final HttpClientRequest httpClientRequest = httpClient.request(request.getMethod(), request.uri(), handleResponse(request, responseHandler)); final Runnable runnable = new Runnable() { @Override public void run() { if (!request.getMethod().equals("GET")) { httpClientRequest.putHeader("Content-Type", "application/x-www-form-urlencoded").end(request.paramBody()); } else { httpClientRequest.end(); } } }; if (closed.get()) { this.scheduledExecutorService.schedule(new Runnable() { @Override public void run() { connect(); int retry = 0; while (closed.get()) { Sys.sleep(1000); if (!closed.get()) { break; } retry++; if (retry>10) { break; } if ( retry % 3 == 0 ) { connect(); } } if (!closed.get()) { runnable.run(); } else { responseHandler.handle(new Response("TIMEOUT", -1, new Error(-1, "Timeout", "Timeout", -1L))); } } }, 10, TimeUnit.MILLISECONDS); } else { runnable.run(); } }
java
{ "resource": "" }
q177470
CouchDbContext.deleteDB
test
public void deleteDB(String dbName, String confirm) { assertNotEmpty(dbName, "dbName"); if(!"delete database".equals(confirm)) throw new IllegalArgumentException("Invalid confirm!"); dbc.delete(buildUri(dbc.getBaseUri()).path(dbName).build()); }
java
{ "resource": "" }
q177471
CouchDbContext.createDB
test
public void createDB(String dbName) { assertNotEmpty(dbName, "dbName"); InputStream getresp = null; HttpResponse putresp = null; final URI uri = buildUri(dbc.getBaseUri()).path(dbName).build(); try { getresp = dbc.get(uri); } catch (NoDocumentException e) { // db doesn't exist final HttpPut put = new HttpPut(uri); putresp = dbc.executeRequest(put); log.info(String.format("Created Database: '%s'", dbName)); } finally { close(getresp); close(putresp); } }
java
{ "resource": "" }
q177472
CouchDbContext.uuids
test
public List<String> uuids(long count) { final String uri = String.format("%s_uuids?count=%d", dbc.getBaseUri(), count); final JsonObject json = dbc.findAny(JsonObject.class, uri); return dbc.getGson().fromJson(json.get("uuids").toString(), new TypeToken<List<String>>(){}.getType()); }
java
{ "resource": "" }
q177473
CouchDbUtil.listResources
test
public static List<String> listResources(String path) { try { Class<CouchDbUtil> clazz = CouchDbUtil.class; URL dirURL = clazz.getClassLoader().getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) { return Arrays.asList(new File(dirURL.toURI()).list()); } if (dirURL != null && dirURL.getProtocol().equals("jar")) { String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); Set<String> result = new HashSet<String>(); while(entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(SPRING_BOOT_DIR)) { name = name.substring(SPRING_BOOT_DIR.length()); } if (name.startsWith(path)) { String entry = name.substring(path.length()); int checkSubdir = entry.indexOf("/"); if (checkSubdir >= 0) { entry = entry.substring(0, checkSubdir); } if(entry.length() > 0) { result.add(entry); } } } close(jar); return new ArrayList<String>(result); } return null; } catch (Exception e) { throw new CouchDbException(e); } }
java
{ "resource": "" }
q177474
Replication.trigger
test
public ReplicationResult trigger() { assertNotEmpty(source, "Source"); assertNotEmpty(target, "Target"); HttpResponse response = null; try { JsonObject json = createJson(); if(log.isDebugEnabled()) { log.debug(json); } final URI uri = buildUri(dbc.getBaseUri()).path("_replicate").build(); response = dbc.post(uri, json.toString()); final InputStreamReader reader = new InputStreamReader(getStream(response), Charsets.UTF_8); return dbc.getGson().fromJson(reader, ReplicationResult.class); } finally { close(response); } }
java
{ "resource": "" }
q177475
View.queryValue
test
private <V> V queryValue(Class<V> classOfV) { InputStream instream = null; try { Reader reader = new InputStreamReader(instream = queryForStream(), Charsets.UTF_8); JsonArray array = new JsonParser().parse(reader). getAsJsonObject().get("rows").getAsJsonArray(); if(array.size() != 1) { throw new NoDocumentException("Expecting a single result but was: " + array.size()); } return JsonToObject(gson, array.get(0), "value", classOfV); } finally { close(instream); } }
java
{ "resource": "" }
q177476
View.descending
test
public View descending(Boolean descending) { this.descending = Boolean.valueOf(gson.toJson(descending)); uriBuilder.query("descending", this.descending); return this; }
java
{ "resource": "" }
q177477
CouchDbDesign.synchronizeAllWithDb
test
public void synchronizeAllWithDb() { List<DesignDocument> documents = getAllFromDesk(); for (DesignDocument dd : documents) { synchronizeWithDb(dd); } }
java
{ "resource": "" }
q177478
CouchDbDesign.getFromDb
test
public DesignDocument getFromDb(String id) { assertNotEmpty(id, "id"); final URI uri = buildUri(dbc.getDBUri()).path(id).build(); return dbc.get(uri, DesignDocument.class); }
java
{ "resource": "" }
q177479
CouchDbDesign.getAllFromDesk
test
public List<DesignDocument> getAllFromDesk() { final List<DesignDocument> designDocsList = new ArrayList<DesignDocument>(); for (String docName : listResources(format("%s/", DESIGN_DOCS_DIR))) { designDocsList.add(getFromDesk(docName)); } return designDocsList; }
java
{ "resource": "" }
q177480
CouchDbDesign.getFromDesk
test
public DesignDocument getFromDesk(String id) { assertNotEmpty(id, "id"); final DesignDocument dd = new DesignDocument(); final String rootPath = format("%s/%s/", DESIGN_DOCS_DIR, id); final List<String> elements = listResources(rootPath); if(elements == null) { throw new IllegalArgumentException("Design docs directory cannot be empty."); } // Views Map<String, MapReduce> views = null; if(elements.contains(VIEWS)) { views = new HashMap<String, MapReduce>(); final String viewsPath = format("%s%s/", rootPath, VIEWS); for (String viewDirName : listResources(viewsPath)) { // views sub-dirs final MapReduce mr = new MapReduce(); final String viewPath = format("%s%s/", viewsPath, viewDirName); final List<String> dirList = listResources(viewPath); for (String fileName : dirList) { // view files final String def = readFile(format("/%s%s", viewPath, fileName)); if(MAP_JS.equals(fileName)) mr.setMap(def); else if(REDUCE_JS.equals(fileName)) mr.setReduce(def); } // /foreach view files views.put(viewDirName, mr); } // /foreach views sub-dirs } // /views dd.setId(DESIGN_PREFIX + id); dd.setLanguage(JAVASCRIPT); dd.setViews(views); dd.setFilters(populateMap(rootPath, elements, FILTERS)); dd.setShows(populateMap(rootPath, elements, SHOWS)); dd.setLists(populateMap(rootPath, elements, LISTS)); dd.setUpdates(populateMap(rootPath, elements, UPDATES)); dd.setValidateDocUpdate(readContent(elements, rootPath, VALIDATE_DOC)); dd.setRewrites(dbc.getGson().fromJson(readContent(elements, rootPath, REWRITES), JsonArray.class)); dd.setFulltext(dbc.getGson().fromJson(readContent(elements, rootPath, FULLTEXT), JsonObject.class)); dd.setIndexes(dbc.getGson().fromJson(readContent(elements, rootPath, INDEXES), JsonObject.class)); return dd; }
java
{ "resource": "" }
q177481
Replicator.save
test
public Response save() { assertNotEmpty(replicatorDoc.getSource(), "Source"); assertNotEmpty(replicatorDoc.getTarget(), "Target"); if(userCtxName != null) { UserCtx ctx = replicatorDoc.new UserCtx(); ctx.setName(userCtxName); ctx.setRoles(userCtxRoles); replicatorDoc.setUserCtx(ctx); } return dbc.put(dbURI, replicatorDoc, true); }
java
{ "resource": "" }
q177482
Replicator.find
test
public ReplicatorDocument find() { assertNotEmpty(replicatorDoc.getId(), "Doc id"); final URI uri = buildUri(dbURI).path(replicatorDoc.getId()).query("rev", replicatorDoc.getRevision()).build(); return dbc.get(uri, ReplicatorDocument.class); }
java
{ "resource": "" }
q177483
Replicator.findAll
test
public List<ReplicatorDocument> findAll() { InputStream instream = null; try { final URI uri = buildUri(dbURI).path("_all_docs").query("include_docs", "true").build(); final Reader reader = new InputStreamReader(instream = dbc.get(uri), Charsets.UTF_8); final JsonArray jsonArray = new JsonParser().parse(reader) .getAsJsonObject().getAsJsonArray("rows"); final List<ReplicatorDocument> list = new ArrayList<ReplicatorDocument>(); for (JsonElement jsonElem : jsonArray) { JsonElement elem = jsonElem.getAsJsonObject().get("doc"); if(!getAsString(elem.getAsJsonObject(), "_id").startsWith("_design")) { // skip design docs ReplicatorDocument rd = dbc.getGson().fromJson(elem, ReplicatorDocument.class); list.add(rd); } } return list; } finally { close(instream); } }
java
{ "resource": "" }
q177484
Replicator.remove
test
public Response remove() { assertNotEmpty(replicatorDoc.getId(), "Doc id"); assertNotEmpty(replicatorDoc.getRevision(), "Doc rev"); final URI uri = buildUri(dbURI).path(replicatorDoc.getId()).query("rev", replicatorDoc.getRevision()).build(); return dbc.delete(uri); }
java
{ "resource": "" }
q177485
CouchDbClientBase.find
test
public <T> T find(Class<T> classType, String id, Params params) { assertNotEmpty(classType, "Class"); assertNotEmpty(id, "id"); final URI uri = buildUri(getDBUri()).pathEncoded(id).query(params).build(); return get(uri, classType); }
java
{ "resource": "" }
q177486
CouchDbClientBase.findDocs
test
public <T> List<T> findDocs(String jsonQuery, Class<T> classOfT) { assertNotEmpty(jsonQuery, "jsonQuery"); HttpResponse response = null; try { response = post(buildUri(getDBUri()).path("_find").build(), jsonQuery); Reader reader = new InputStreamReader(getStream(response), Charsets.UTF_8); JsonArray jsonArray = new JsonParser().parse(reader) .getAsJsonObject().getAsJsonArray("docs"); List<T> list = new ArrayList<T>(); for (JsonElement jsonElem : jsonArray) { JsonElement elem = jsonElem.getAsJsonObject(); T t = this.gson.fromJson(elem, classOfT); list.add(t); } return list; } finally { close(response); } }
java
{ "resource": "" }
q177487
CouchDbClientBase.contains
test
public boolean contains(String id) { assertNotEmpty(id, "id"); HttpResponse response = null; try { response = head(buildUri(getDBUri()).pathEncoded(id).build()); } catch (NoDocumentException e) { return false; } finally { close(response); } return true; }
java
{ "resource": "" }
q177488
CouchDbClientBase.bulk
test
public List<Response> bulk(List<?> objects, boolean newEdits) { assertNotEmpty(objects, "objects"); HttpResponse response = null; try { final String newEditsVal = newEdits ? "\"new_edits\": true, " : "\"new_edits\": false, "; final String json = String.format("{%s%s%s}", newEditsVal, "\"docs\": ", getGson().toJson(objects)); final URI uri = buildUri(getDBUri()).path("_bulk_docs").build(); response = post(uri, json); return getResponseList(response); } finally { close(response); } }
java
{ "resource": "" }
q177489
CouchDbClientBase.put
test
Response put(URI uri, Object object, boolean newEntity) { assertNotEmpty(object, "object"); HttpResponse response = null; try { final JsonObject json = getGson().toJsonTree(object).getAsJsonObject(); String id = getAsString(json, "_id"); String rev = getAsString(json, "_rev"); if(newEntity) { // save assertNull(rev, "rev"); id = (id == null) ? generateUUID() : id; } else { // update assertNotEmpty(id, "id"); assertNotEmpty(rev, "rev"); } final HttpPut put = new HttpPut(buildUri(uri).pathEncoded(id).build()); setEntity(put, json.toString()); response = executeRequest(put); return getResponse(response); } finally { close(response); } }
java
{ "resource": "" }
q177490
CouchDbClientBase.put
test
Response put(URI uri, InputStream instream, String contentType) { HttpResponse response = null; try { final HttpPut httpPut = new HttpPut(uri); final InputStreamEntity entity = new InputStreamEntity(instream, -1); entity.setContentType(contentType); httpPut.setEntity(entity); response = executeRequest(httpPut); return getResponse(response); } finally { close(response); } }
java
{ "resource": "" }
q177491
CouchDbClientBase.post
test
HttpResponse post(URI uri, String json) { HttpPost post = new HttpPost(uri); setEntity(post, json); return executeRequest(post); }
java
{ "resource": "" }
q177492
CouchDbClientBase.delete
test
Response delete(URI uri) { HttpResponse response = null; try { HttpDelete delete = new HttpDelete(uri); response = executeRequest(delete); return getResponse(response); } finally { close(response); } }
java
{ "resource": "" }
q177493
CouchDbClientBase.validate
test
void validate(HttpResponse response) throws IOException { final int code = response.getStatusLine().getStatusCode(); if(code == 200 || code == 201 || code == 202) { // success (ok | created | accepted) return; } String reason = response.getStatusLine().getReasonPhrase(); switch (code) { case HttpStatus.SC_NOT_FOUND: { throw new NoDocumentException(reason); } case HttpStatus.SC_CONFLICT: { throw new DocumentConflictException(reason); } default: { // other errors: 400 | 401 | 500 etc. throw new CouchDbException(reason += EntityUtils.toString(response.getEntity())); } } }
java
{ "resource": "" }
q177494
CouchDbClientBase.setEntity
test
private void setEntity(HttpEntityEnclosingRequestBase httpRequest, String json) { StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); httpRequest.setEntity(entity); }
java
{ "resource": "" }
q177495
Document.addAttachment
test
public void addAttachment(String name, Attachment attachment) { if(attachments == null) attachments = new HashMap<String, Attachment>(); attachments.put(name, attachment); }
java
{ "resource": "" }
q177496
Changes.getChanges
test
public ChangesResult getChanges() { final URI uri = uriBuilder.query("feed", "normal").build(); return dbc.get(uri, ChangesResult.class); }
java
{ "resource": "" }
q177497
Changes.readNextRow
test
private boolean readNextRow() { boolean hasNext = false; try { if(!stop) { String row = ""; do { row = getReader().readLine(); } while(row.length() == 0); if(!row.startsWith("{\"last_seq\":")) { setNextRow(gson.fromJson(row, Row.class)); hasNext = true; } } } catch (Exception e) { terminate(); throw new CouchDbException("Error reading continuous stream.", e); } if(!hasNext) terminate(); return hasNext; }
java
{ "resource": "" }
q177498
MoneyToStr.convert
test
public String convert(Double theMoney) { if (theMoney == null) { throw new IllegalArgumentException("theMoney is null"); } Long intPart = theMoney.longValue(); Long fractPart = Math.round((theMoney - intPart) * NUM100); if (currency == Currency.PER1000) { fractPart = Math.round((theMoney - intPart) * NUM1000); } return convert(intPart, fractPart); }
java
{ "resource": "" }
q177499
LockManager.shutdown
test
public void shutdown() { try { locksExecutor.shutdown(); locksExecutor.awaitTermination(5, TimeUnit.SECONDS); CountDownLatch latch = new CountDownLatch(1); activeLocksLock.writeLock().lock(); Observable.from(activeLocks.entrySet()) .map(Map.Entry::getValue) .flatMap(lock -> releaseLock(lock.getName(), lock.getValue()) .map(released -> new Lock(lock.getName(), lock.getValue(), lock.getExpiration(), lock .getRenewalRate(), !released))) .subscribe( lock -> { if (lock.isLocked()) { logger.infof("Failed to release lock %s", lock.getName()); } }, t -> { logger.info("There was an error while releasing locks", t); latch.countDown(); }, latch::countDown ); latch.await(); logger.info("Shutdown complete"); } catch (InterruptedException e) { logger.debug("Shutdown was interrupted. Some locks may not have been released but they will still expire."); } }
java
{ "resource": "" }