idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
28,700 | public Map < String , Set < Object > > getMultipleLocationsForResources ( ) { return new TreeMap < String , Set < Object > > ( multipleLocationsForResource ) ; } | A resource such as class or properties file may be found in different locations . If this is the case only the first location is used to resolve the resource . This may lead to problems if different versions of resources exist . |
28,701 | public Class < ? > findClass ( String className ) throws ClassNotFoundException { Object location = classResourceLocations . get ( className ) ; if ( location == null && this . propertiesResourceLocations . containsKey ( className ) ) { String fileName = ( String ) propertiesResourceLocations . get ( className ) ; if ( fileName . endsWith ( ".properties" ) ) { return ResourceBundle . class ; } else { throw new ClassNotFoundException ( "resource '" + fileName + "' for class '" + className + "' has incompatible format" ) ; } } if ( className . startsWith ( "java." ) ) { return super . findClass ( className ) ; } if ( location == null ) { throw new ClassNotFoundException ( "class '" + className + "' not found in " + classpath ) ; } String fileName = className . replace ( '.' , '/' ) + ".class" ; byte [ ] data ; try { data = getData ( fileName , location ) ; } catch ( IOException ioe ) { throw new NoClassDefFoundError ( "class '" + className + "' could not be loaded from '" + location + "' with message: " + ioe ) ; } return defineClass ( className , data , 0 , data . length ) ; } | Tries to locate a class in the specific class path . |
28,702 | private static byte [ ] getData ( String fileName , Object location ) throws IOException { byte [ ] data ; if ( location instanceof String ) { data = FileSupport . getBinaryFromJar ( fileName , ( String ) location ) ; } else if ( location instanceof File ) { InputStream in = new FileInputStream ( ( File ) location ) ; data = StreamSupport . absorbInputStream ( in ) ; in . close ( ) ; } else { throw new NoClassDefFoundError ( "file '" + fileName + "' could not be loaded from '" + location + '\'' ) ; } return data ; } | Retrieves resource as byte array from a directory or jar in the file system . |
28,703 | public synchronized boolean checkResources ( ) { nrofResourcesDeleted = 0 ; nrofResourcesUpdated = 0 ; for ( File file : fileCreationTimes . keySet ( ) ) { if ( ! file . exists ( ) ) { nrofResourcesDeleted ++ ; } else if ( file . lastModified ( ) != ( ( Long ) fileCreationTimes . get ( file ) ) . longValue ( ) ) { nrofResourcesUpdated ++ ; } } return nrofResourcesDeleted > 0 || nrofResourcesUpdated > 0 ; } | Updates statistics on available resources in the classpath . These statistics can be used to determine if an application must be reset due to changed sources in a development environment . Processing may consume a considerable amount of CPU - time . |
28,704 | public static boolean clearDirectory ( File directory ) { if ( directory . isDirectory ( ) ) { for ( File file : directory . listFiles ( ) ) { if ( ! deleteRecursive ( file ) ) { return false ; } } } return true ; } | Recursively removes all entries from a directory . |
28,705 | public static void writeObjectToFile ( File file , Object object ) throws IOException { FileOutputStream fs = new FileOutputStream ( file ) ; ObjectOutputStream os = new ObjectOutputStream ( fs ) ; os . writeObject ( object ) ; os . close ( ) ; } | Writes a single object to a file . |
28,706 | public static Object readObjectFromFile ( File file ) throws IOException , ClassNotFoundException { FileInputStream fs = new FileInputStream ( file ) ; ObjectInputStream os = new ObjectInputStream ( fs ) ; Object object = os . readObject ( ) ; os . close ( ) ; return object ; } | Reads a single object from a file . |
28,707 | public static boolean isAncestor ( File file , File ancestor ) throws IOException { file = file . getCanonicalFile ( ) ; ancestor = ancestor . getCanonicalFile ( ) ; do { if ( file . equals ( ancestor ) ) { return true ; } file = file . getParentFile ( ) ; } while ( file != null ) ; return false ; } | Determines if the specified directory is an ancestor of the specified file or directory . |
28,708 | public static void prune ( File file , File root ) { while ( ! file . equals ( root ) && file . delete ( ) ) { file = file . getParentFile ( ) ; } } | Removes a file or directory and its ancestors up to but not including the specified directory until a non - empty directory is reached . |
28,709 | public static boolean postOrderTraversal ( File root , FileVisitor visitor ) throws Exception { if ( root . isDirectory ( ) ) { for ( File child : root . listFiles ( ) ) { if ( ! postOrderTraversal ( child , visitor ) ) { return false ; } } } return visitor . visit ( root ) ; } | Walks a directory tree using post - order traversal . The contents of a directory are visited before the directory itself is visited . |
28,710 | public static boolean preOrderTraversal ( File root , FileVisitor visitor ) throws Exception { if ( ! visitor . visit ( root ) ) { return false ; } if ( root . isDirectory ( ) ) { for ( File child : root . listFiles ( ) ) { if ( ! preOrderTraversal ( child , visitor ) ) { return false ; } } } return true ; } | Walks a directory tree using pre - order traversal . The contents of a directory are visited after the directory itself is visited . |
28,711 | public static void zip ( File zipFile , final File contents ) throws IOException { OutputStream os = new FileOutputStream ( zipFile ) ; final ZipOutputStream zs = new ZipOutputStream ( os ) ; try { preOrderTraversal ( contents , new FileVisitor ( ) { public boolean visit ( File file ) throws IOException { if ( file . isFile ( ) ) { String name = getRelativePath ( file , contents ) ; zs . putNextEntry ( new ZipEntry ( name ) ) ; FileInputStream fs = new FileInputStream ( file ) ; StreamUtil . writeStream ( fs , zs ) ; fs . close ( ) ; zs . closeEntry ( ) ; } return true ; } } ) ; } catch ( IOException e ) { throw e ; } catch ( Exception e ) { throw new UnexpectedException ( e ) ; } zs . close ( ) ; } | Zips the contents of a directory . |
28,712 | public static String getExtension ( String fileName ) { int pos = fileName . lastIndexOf ( '.' ) ; if ( pos < 0 ) { return "" ; } return fileName . substring ( pos + 1 ) ; } | Gets the extension part of the specified file name . |
28,713 | void _prepareResponseDataOnlyOnce ( HttpServletRequest req ) { if ( req . getAttribute ( KEY_FILE ) == null ) { String pathInfo = req . getPathInfo ( ) ; if ( pathInfo == null ) pathInfo = "" ; String fileSeparator = System . getProperty ( "file.separator" ) ; String filePath = pathInfo . replaceAll ( Pattern . quote ( "/" ) , fileSeparator ) ; String mappedDirPath = getMappedDirPath ( ) ; File file = new File ( mappedDirPath , filePath ) ; boolean isDirectory = file . isDirectory ( ) ; req . setAttribute ( KEY_IS_DIR , isDirectory ) ; if ( isDirectory ) file = new File ( mappedDirPath , getIndexFilename ( ) ) ; req . setAttribute ( KEY_FILE , file ) ; req . setAttribute ( KEY_MIME , __getMimeType ( file ) ) ; req . setAttribute ( KEY_LAST_MODIFIED , file . exists ( ) ? file . lastModified ( ) : 0 ) ; } } | prepares the response data associated with given request . |
28,714 | public Object getFragment ( String address , String jsonPath , Object jsonFragment ) { Object jsonFragment2 = null ; if ( ! fragmentCache . containsKey ( address ) ) { jsonFragment2 = read ( jsonPath , jsonFragment ) ; fragmentCache . put ( address , jsonFragment2 ) ; } else { jsonFragment2 = fragmentCache . get ( address ) ; } return jsonFragment2 ; } | Get a JSON fragment from cache . |
28,715 | private void position ( long newPosition ) throws IOException { check ( ) ; checkPosition ( newPosition ) ; this . getRandomAccessFile ( ) . seek ( newPosition + getHeaderLength ( ) ) ; } | Setzt Bereich der Nutzdaten auf die angegebenen Position . Evtl . HeaderBrereiche werden ignoriert |
28,716 | public void reset ( ) throws IOException { check ( ) ; this . position ( 0 ) ; this . commit ( ) ; this . getRandomAccessFile ( ) . getChannel ( ) . truncate ( TAEnabledRandomAccessFile . HEADER_LENGTH ) ; } | updates the committed size with 0 . All data is truncated |
28,717 | public static InetAddress getLocalHost ( ) { if ( localHost == null ) { try { localHost = java . net . InetAddress . getLocalHost ( ) ; } catch ( UnknownHostException e ) { LOGGER . error ( "Cannot get local host address. exception is: " + e ) ; localHost = null ; hostName = "UNKNOWN" ; ipAddress = "UNKNOWN" ; } } return localHost ; } | get the local host ip address . |
28,718 | public boolean wasKeyTyped ( int keyCode ) { if ( this . isKeyDown ( keyCode ) && ! this . checked . contains ( keyCode ) ) { this . checked . add ( keyCode ) ; return true ; } return false ; } | True if the key was pressed but hadn t been previously checked . Subsequent calls to this method will therefore return always false as long as the key hasn t been released and pressed again . |
28,719 | public void mouseClicked ( MouseEvent e ) { mouseEvents . add ( MouseInputEvent . fromMouseEvent ( MouseAction . CLICKED , e ) ) ; } | region ... Mouse listener methods ... |
28,720 | public static int countDifferences ( IntTuple t0 , IntTuple t1 ) { if ( t0 . getSize ( ) != t1 . getSize ( ) ) { throw new IllegalArgumentException ( "Sizes do not match: " + t0 . getSize ( ) + " and " + t1 . getSize ( ) ) ; } int n = t0 . getSize ( ) ; int differences = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( t0 . get ( i ) != t1 . get ( i ) ) { differences ++ ; } } return differences ; } | Returns the number of entries of the given tuples that are different |
28,721 | public void close ( ) throws Exception { MimeBodyPart part = new MimeBodyPart ( ) ; StringBuilder sb = new StringBuilder ( ) ; int len = buffer . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { ILoggingEvent event = buffer . get ( ) ; sb . append ( layout . doLayout ( event ) ) ; } part . setText ( sb . toString ( ) , "UTF-8" , "plain" ) ; Multipart mp = new MimeMultipart ( ) ; mp . addBodyPart ( part ) ; mimeMsg . setContent ( mp ) ; mimeMsg . setSentDate ( new Date ( ) ) ; Transport . send ( mimeMsg ) ; } | Close the trace and send the email |
28,722 | public InjectorConfiguration withDefined ( Class classDefinition ) { return new InjectorConfiguration ( scopes , definedClasses . withModified ( value -> value . withPut ( classDefinition , new ImmutableArrayList < > ( Arrays . asList ( classDefinition . getConstructors ( ) ) ) ) ) , factories , factoryClasses , sharedClasses , sharedInstances , aliases , collectedAliases , namedParameterValues ) ; } | Marks a class as injectable on a global scope with all possible constructors . |
28,723 | public InjectorConfiguration withDefined ( Constructor constructorDefinition ) { return new InjectorConfiguration ( scopes , definedClasses . withModified ( scopeValue -> scopeValue . withCompute ( constructorDefinition . getDeclaringClass ( ) , ( key , currentValue ) -> ( currentValue == null ? new ImmutableArrayList < Constructor > ( ) : currentValue ) . withAdd ( constructorDefinition ) ) ) , factories , factoryClasses , sharedClasses , sharedInstances , aliases , collectedAliases , namedParameterValues ) ; } | Marks a class as injectable on a global scope with one specific constructor . |
28,724 | public < T > InjectorConfiguration withFactory ( Class < T > classDefinition , Provider < T > factory ) { if ( classDefinition . equals ( Injector . class ) ) { throw new DependencyInjectionFailedException ( "Cowardly refusing to define a global factory for Injector since that would lead to a Service Locator pattern. If you need the injector, please define it on a per-class or per-method basis." ) ; } return new InjectorConfiguration ( scopes , definedClasses , factories . withModified ( ( value ) -> value . with ( classDefinition , factory ) ) , factoryClasses , sharedClasses , sharedInstances , aliases , collectedAliases , namedParameterValues ) ; } | Specify that the given class should be created using the factory instance specified . |
28,725 | public < T > InjectorConfiguration withShared ( T instance ) { return new InjectorConfiguration ( scopes , definedClasses , factories , factoryClasses , sharedClasses , sharedInstances . withPut ( instance . getClass ( ) , instance ) , aliases , collectedAliases , namedParameterValues ) ; } | Mark a class instance as shared . The type of the class will be marked as injectable and in all cases this class instance will be passed when requested . This holds true even with multiple injectors as long as they are created from the same configuration . |
28,726 | public < ABS , IMPL extends ABS > InjectorConfiguration withAlias ( Class scope , Executable forExecutable , Class < ABS > abstractDefinition , Class < IMPL > implementationDefinition ) { return new InjectorConfiguration ( scopes , definedClasses , factories , factoryClasses , sharedClasses , sharedInstances , aliases . withModified ( scope , ( value ) -> value . with ( forExecutable , abstractDefinition , implementationDefinition ) ) , collectedAliases , namedParameterValues ) ; } | Defines on a per - method or per - constructor basis that instead of the class defined in abstractDefinition the class defined in implementationDefinition should be used . |
28,727 | public MailMessage defaultFrom ( String email , String name ) { if ( StringUtils . isNullOrEmptyTrimmed ( fromEmail ) ) { from ( email , name ) ; } if ( ! StringUtils . isNullOrEmptyTrimmed ( email ) && StringUtils . equals ( fromEmail , email . trim ( ) , true ) && StringUtils . isNullOrEmptyTrimmed ( fromName ) ) { from ( email , name ) ; } return this ; } | Sets from email address only if not already set |
28,728 | private Map < String , String > getEmails ( Map < String , String > emails ) { if ( emails == null || emails . size ( ) == 0 ) { return null ; } Map < String , String > out = new HashMap < > ( ) ; for ( String email : emails . keySet ( ) ) { if ( excluded ( email ) ) { continue ; } out . put ( email , emails . get ( email ) ) ; } return out ; } | Filters out excluded emails if any |
28,729 | protected void update ( ) { _updated = true ; if ( System . currentTimeMillis ( ) > _lastDumpTime + _interval ) { try { dump ( ) ; } catch ( InvocationException ex ) { } } } | Makes counter measurements as updated and dumps them when timeout expires . |
28,730 | public Counter get ( String name , int type ) { if ( name == null || name . length ( ) == 0 ) throw new NullPointerException ( "Counter name was not set" ) ; synchronized ( _lock ) { resetIfNeeded ( ) ; Counter counter = _cache . get ( name ) ; if ( counter == null || counter . getType ( ) != type ) { counter = new Counter ( name , type ) ; _cache . put ( name , counter ) ; } return counter ; } } | Gets a counter specified by its name . It counter does not exist or its type doesn t match the specified type it creates a new one . |
28,731 | public void last ( String name , float value ) { Counter counter = get ( name , CounterType . LastValue ) ; counter . setLast ( value ) ; update ( ) ; } | Records the last calculated measurement value . |
28,732 | public void timestamp ( String name , ZonedDateTime value ) { Counter counter = get ( name , CounterType . Timestamp ) ; counter . setTime ( value != null ? value : ZonedDateTime . now ( ZoneId . of ( "Z" ) ) ) ; update ( ) ; } | Records the given timestamp . |
28,733 | public void increment ( String name , int value ) { Counter counter = get ( name , CounterType . Increment ) ; counter . setCount ( counter . getCount ( ) != null ? counter . getCount ( ) + value : value ) ; update ( ) ; } | Increments counter by given value . |
28,734 | public void unregister ( FileSubscriber fileSubscriber ) { for ( IdentificationSet < FileSubscriber > subList : fileSubscribers . values ( ) ) { subList . remove ( fileSubscriber ) ; } defaultFileSubscribers . remove ( fileSubscriber ) ; } | Unregisters all instances of fileSubscriber found . |
28,735 | public synchronized void notifyAllFileSubcribers ( ) { for ( IdentificationSet < FileSubscriber > subList : fileSubscribers . values ( ) ) { for ( FileSubscriber sub : subList ) { CompletableFuture . runAsync ( sub :: update , main . getThreadPoolManager ( ) . getAddOnsThreadPool ( ) ) ; } } notifyDefaultFileSubscribers ( ) ; } | Notifies all file subscribers . |
28,736 | public synchronized void notifyDefaultFileSubscribers ( ) { for ( FileSubscriber sub : defaultFileSubscribers ) { CompletableFuture . runAsync ( sub :: update , main . getThreadPoolManager ( ) . getAddOnsThreadPool ( ) ) ; } } | Notifies all default file subscribers that is those that will all be notified no matter what . |
28,737 | public static ListeningExecutorService executor ( ) { final ExecutorService svc = Executors . newCachedThreadPool ( MoreExecutors . platformThreadFactory ( ) ) ; return MoreExecutors . listeningDecorator ( svc ) ; } | Returns a ListeningExecutorService based off of the global ThreadFactory |
28,738 | public static < T > ListenableFuture < T > future ( final Async < T > async ) { return executor ( ) . submit ( async ) ; } | Returns a ListenableFuture for the given Async object |
28,739 | public static < T , X extends Exception > CheckedFuture < T , X > checkedFuture ( final CheckedAsync < T , X > async ) { return Futures . makeChecked ( future ( async ) , async ) ; } | Returns a CheckedFuture for the given CheckedAsync object |
28,740 | public < T , K extends T > void alias ( Class < T > abstraction , Class < K > implementation ) { injectorConfiguration = injectorConfiguration . withAlias ( abstraction , implementation ) ; } | Create an alias definition for an abstraction . This can be used to specify implementations for abstractions . |
28,741 | public < T > void define ( Class < T > classDefinition , ObjectFactory < T > factory ) { injectorConfiguration = injectorConfiguration . withFactory ( classDefinition , factory ) ; } | Define a class using a custom object factory . |
28,742 | private Type getParametrizedTypeOfJobListener ( Class < ? > listenerClass ) { Type [ ] interfaces = listenerClass . getGenericInterfaces ( ) ; Type [ ] typeParameters = null ; for ( Type anInterface : interfaces ) { if ( ! ( anInterface instanceof ParameterizedType ) ) { continue ; } Class interfaceClass = ( Class ) ( ( ParameterizedType ) anInterface ) . getRawType ( ) ; if ( TaskListener . class . isAssignableFrom ( interfaceClass ) ) { typeParameters = ( ( ParameterizedType ) anInterface ) . getActualTypeArguments ( ) ; break ; } } if ( typeParameters == null || typeParameters . length == 0 ) { throw SeedException . createNew ( SchedulerErrorCode . MISSING_TYPE_PARAMETER ) . put ( "class" , listenerClass ) ; } return typeParameters [ 0 ] ; } | Returns the type parameter of the TaskListener interface . |
28,743 | public HttpClient setURI ( final String uri ) throws HibiscusException { try { setURI ( new URI ( uri ) ) ; } catch ( URISyntaxException e ) { throw new HibiscusException ( e ) ; } return this ; } | Expects the Absolute URL for the Request |
28,744 | public HttpClient setURI ( final URI uri ) { final URIBuilder builder = new URIBuilder ( uri ) ; this . scheme = builder . getScheme ( ) ; this . host = builder . getHost ( ) ; this . port = builder . getPort ( ) ; this . path = builder . getPath ( ) ; this . fragment = builder . getFragment ( ) ; this . resetQueryParameters ( ) ; for ( NameValuePair nvp : builder . getQueryParams ( ) ) { this . queryParameters . add ( new BasicNameValuePair ( nvp . getName ( ) , nvp . getValue ( ) ) ) ; } return this ; } | A URI representing the Absolute URL for the Request |
28,745 | public HttpClient execute ( ) throws HibiscusException { HttpWorkerAbstract httpWorker = HttpWorkerAbstract . getWorkerStrategy ( requestMethod , this ) ; httpWorker . execute ( ) ; lastResponse = httpWorker . getResponse ( ) ; lastResponse . setElapsedTime ( httpWorker . getResponseTime ( ) ) ; return this ; } | Retrieves the HTTP worker and makes the request to the server |
28,746 | public HttpClient setRequestMethod ( final String rMethod ) throws HibiscusException { if ( null == rMethod || false == validHttpRequestMethods . contains ( rMethod ) ) { throw new HibiscusException ( rMethod + " is not a valid HTTP Request Method" ) ; } requestMethod = rMethod ; return this ; } | Must be One of HEAD GET POST PUT or DELETE |
28,747 | public Settings load ( String file , CommandBuilder builder ) throws CommandLineException { Scanner scanner = null ; try { File config = new File ( file ) ; Assert . isTrue ( config . exists ( ) , "File '" + file + "' does not exist" ) ; Assert . isFalse ( config . isDirectory ( ) , "File '" + file + "' is a directory" ) ; Assert . isTrue ( config . canRead ( ) , "File '" + file + "' cannot be read" ) ; scanner = new Scanner ( config ) ; ArrayList < String > list = new ArrayList < > ( ) ; while ( scanner . hasNextLine ( ) ) { list . add ( scanner . nextLine ( ) ) ; } return parse ( list , builder ) ; } catch ( FileNotFoundException e ) { log . error ( "File not found: " + e . getMessage ( ) ) ; throw new CommandLineException ( "File: '" + file + "', not found!" ) ; } finally { if ( scanner != null ) { scanner . close ( ) ; } } } | Loads name value pairs directly from given file ... adding them as settings |
28,748 | static public < T > Class < ? extends T > getClass ( T obj ) { return ( Class < ? extends T > ) obj . getClass ( ) ; } | Fudge the return from getClass to include the generic . |
28,749 | static public < K , V > Map < K , V > map ( Map < ? , ? > map ) { return ( Map < K , V > ) map ; } | Force a non generic map to be one . |
28,750 | protected void wrappedWrite ( int b ) throws IOException { checkState ( ) ; try { out . write ( b ) ; } catch ( IOException e ) { error = true ; throw e ; } } | Write one byte setting error flag on exception . |
28,751 | protected void uncheckedWriteBits ( int numAddBits , int addBits ) throws IOException { int chunks ; if ( numAddBits < numBitsLeft ) { addBits &= ( 0xFF >>> ( 8 - numAddBits ) ) ; addBits <<= numBitsLeft - numAddBits ; currentBits |= addBits ; numBitsLeft -= numAddBits ; return ; } addBits <<= Integer . SIZE - numAddBits ; currentBits |= addBits >>> ( Integer . SIZE - numBitsLeft ) ; numAddBits -= numBitsLeft ; addBits <<= numBitsLeft ; writeCurrent ( ) ; chunks = numAddBits >> 3 ; for ( int i = 0 ; i < chunks ; i ++ ) { int tmpBits = addBits >>> ( Integer . SIZE - Byte . SIZE ) ; wrappedWrite ( tmpBits ) ; addBits <<= Byte . SIZE ; } if ( ( numAddBits &= 0x7 ) == 0 ) return ; currentBits = addBits >>> ( Integer . SIZE - Byte . SIZE ) ; numBitsLeft = Byte . SIZE - numAddBits ; } | Writes bits to the output without checking arguments . Any currently incomplete byte is first completed and written . Bits left after last full byte is writeen are buffered until the next write . |
28,752 | public static < T extends Serializable > T deserializeFromStream ( InputStream in , Class < T > type ) throws ClassNotFoundException , IOException { ObjectInputStream objIn ; T obj ; if ( in instanceof ObjectInputStream ) objIn = ( ObjectInputStream ) in ; else objIn = new ObjectInputStream ( in ) ; obj = type . cast ( objIn . readObject ( ) ) ; objIn . close ( ) ; return obj ; } | Read one serialized object from a input stream . |
28,753 | public static < T extends Serializable > void serializeToStream ( T obj , OutputStream out ) throws IOException { ObjectOutputStream objOut ; if ( out instanceof ObjectOutputStream ) objOut = ( ObjectOutputStream ) out ; else objOut = new ObjectOutputStream ( out ) ; objOut . writeObject ( obj ) ; objOut . close ( ) ; } | Write one object serilized to a output stream . |
28,754 | public static < T extends Serializable > File serializeToTempFile ( T obj ) throws IOException { File file = File . createTempFile ( Serializer . class . getName ( ) . replace ( ".*\\." , "" ) , null ) ; file . deleteOnExit ( ) ; serializeToFile ( obj , file ) ; return file ; } | Serializes an object to a temporary file . |
28,755 | @ SuppressWarnings ( "unchecked" ) public < T extends Message > Map < String , Object > writeMessage ( final T message , final MessageDescriptor < T > descriptor ) { try { return ( Map < String , Object > ) objectFormat . write ( message , descriptor ) ; } catch ( Exception e ) { throw propagate ( e ) ; } } | Converts a message into a JSON - compatible map . |
28,756 | public < T > Object writeObject ( final T object , final DataTypeDescriptor < T > descriptor ) { try { return objectFormat . write ( object , descriptor ) ; } catch ( Exception e ) { throw propagate ( e ) ; } } | Converts an object into a JSON - compatible object . |
28,757 | public < T > T readObject ( final Object object , final DataTypeDescriptor < T > descriptor ) { try { return objectFormat . read ( object , descriptor ) ; } catch ( Exception e ) { throw propagate ( e ) ; } } | Parses an object from a JSON - compatible object . |
28,758 | public < T extends RESTDataProvider > void registerProvider ( Class < T > providerClass , Class < ? > providerInterface ) { try { final Constructor < T > constructor = providerClass . getConstructor ( RESTProviderFactory . class ) ; final T instance = constructor . newInstance ( this ) ; providerMap . put ( providerClass , instance ) ; if ( providerInterface != null ) { providerMap . put ( providerInterface , instance ) ; } } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } | Register an external provider with the provider factory . |
28,759 | public static SystemMail createSystemMail ( ) throws IllegalAccessException { if ( ! exists ) { SystemMail permissionManager = new SystemMail ( ) ; exists = true ; return permissionManager ; } throw new IllegalAccessException ( "Cannot create more than one instance of Mail" ) ; } | Creates a SystemMail . There can only be one single SystemMail so calling this method twice will cause an illegal access exception . |
28,760 | public void unregister ( final Object listener ) { for ( Class clazz = listener . getClass ( ) ; clazz != null ; clazz = clazz . getSuperclass ( ) ) { this . handlersByEventType . removeAll ( clazz ) ; } } | Unregisters the object from the event - handlers . |
28,761 | private static String stripEnvironmentPrefix ( final String key ) { if ( key . indexOf ( '.' ) < 0 ) return key ; final String prefix = key . substring ( 0 , key . indexOf ( '.' ) ) ; if ( ! prefix . toUpperCase ( ) . equals ( prefix ) ) return key ; final String newKey = key . substring ( prefix . length ( ) + 1 ) ; final String value = PropertyManager . getProperty ( newKey ) ; if ( value == null ) return key ; return newKey ; } | Looks at the prefix of the key up to the first period . If it is UPPERCASE strips it off then checks to see the PM has a value for that key in the current environment . If null returns the original key if there s a value returns the key with the prefix removed . If there is not an uppercase prefix returns the original key . |
28,762 | private String stringReplace ( final String source , final String find , final String replace ) { if ( source == null || find == null || replace == null ) return source ; final int index = source . indexOf ( find ) ; if ( index == - 1 ) return source ; if ( index == 0 ) return replace + source . substring ( find . length ( ) ) ; return source . substring ( 0 , index ) + replace + source . substring ( index + find . length ( ) ) ; } | Replaces a first occurence of a String with another string |
28,763 | private void setOverride ( final String key , final String value ) { final boolean doSecurely = key . startsWith ( "_" ) ; final String fullKey = defaultEnvironment + "." + key ; if ( value != null ) { final String oldValue = _getProperty ( "" , key , null ) ; if ( value . equals ( oldValue ) ) { if ( doSecurely ) { logger . warning ( "*** IGNORED *** Ignoring redundant override " + fullKey + "=***PROTECTED***" ) ; } else { logger . warning ( "*** IGNORED *** Ignoring redundant override " + fullKey + "='" + value + "'" ) ; } } else { logger . warning ( "*** OVERRIDE *** Setting override " + fullKey ) ; if ( doSecurely ) { logger . warning ( " New value=***PROTECTED***" ) ; logger . warning ( " Old value='" + oldValue + "'" ) ; } else { logger . warning ( " New value='" + value + "'" ) ; logger . warning ( " Old value='" + oldValue + "'" ) ; } allProperties . setProperty ( fullKey , value ) ; } } } | Replaces whatever was in the allProperties object and clears the cache . |
28,764 | public String getCountStatement ( ) { StringBuilder stmt = new StringBuilder ( ) ; stmt . append ( _SELECT_COUNT_ ) . append ( _fromClause ) . append ( _whereClause ) ; return stmt . toString ( ) ; } | Returns the OQL statement to count the objects . |
28,765 | public Object [ ] getParameterValues ( ) { Object [ ] empty = new Object [ 0 ] ; if ( _paramVlaues == null || _paramVlaues . size ( ) == 0 ) { return empty ; } return _paramVlaues . toArray ( empty ) ; } | Returns the parameter values to be bound to the OQL statement . |
28,766 | private void _buildLimit ( final Limit limit , final StringBuilder stmt ) { if ( limit == null ) { return ; } stmt . append ( _LIMIT_ ) ; stmt . append ( limit . getCount ( ) ) ; stmt . append ( _OFFSET_ ) ; stmt . append ( limit . getOffset ( ) ) ; } | Limit LIMIT c OFFSET 0 LIMIT c OFFSET o |
28,767 | private void _buildOrderClause ( final List < Order > orders , final StringBuilder stmt ) { int n_orders = ( orders == null ? 0 : orders . size ( ) ) ; if ( n_orders == 0 ) { return ; } stmt . append ( _ORDER_BY_ ) ; for ( int i = 0 ; i < n_orders ; i ++ ) { if ( i > 0 ) { stmt . append ( "," ) ; } final Order order = orders . get ( i ) ; _buildProperty ( order . getProperty ( ) , stmt ) ; if ( order . isDescending ( ) ) { stmt . append ( _DESC_ ) ; } } } | Order ORDER BY T . a ORDER BY T . a DESC ORDER BY T . a DESC T . b |
28,768 | private void _buildRelationalBinding ( final RelationalBinding binding , final StringBuilder stmt , final List < Object > params ) { String property = binding . getProperty ( ) ; Object value = binding . getValue ( ) ; Relation rel = binding . getRelation ( ) ; if ( value == null ) { NullBinding nullBinding = new NullBinding ( ) ; nullBinding . setProperty ( property ) ; if ( Relation . EQUAL == rel ) { nullBinding . setNotNull ( false ) ; } else if ( Relation . NOT_EQUAL == rel ) { nullBinding . setNotNull ( true ) ; } else { throw new IllegalArgumentException ( "invalid null-valued RelationalBinding: " + String . valueOf ( binding ) ) ; } _buildNullBinding ( nullBinding , stmt ) ; } else { _buildProperty ( property , stmt ) ; stmt . append ( _SPACE_ ) ; stmt . append ( rel . operator ( ) ) ; stmt . append ( _SPACE_ ) ; _buildParameter ( value , stmt , params ) ; } } | RelationalBinding p EQ 2001 p GE 2001 |
28,769 | private void _buildLikeBinding ( final LikeBinding binding , final StringBuilder stmt , final List < Object > params ) { _buildProperty ( binding . getProperty ( ) , stmt ) ; stmt . append ( _LIKE_ ) ; _buildParameter ( binding . getPattern ( ) , stmt , params ) ; } | LikeBinding T . p LIKE foo% |
28,770 | private void _buildFrom ( final String alias , final StringBuilder stmt ) { stmt . append ( _FROM_ ) . append ( getType ( ) . getName ( ) ) ; stmt . append ( _SPACE_ ) . append ( alias ) ; } | FROM FROM foo . bar . Type Type |
28,771 | private void _buildProperty ( final String property , final StringBuilder stmt ) { if ( property == null || property . length ( ) == 0 ) { throw new IllegalArgumentException ( "no property specified" ) ; } stmt . append ( _alias ) . append ( "." ) . append ( property ) ; } | T . p |
28,772 | public static String numericOffset ( String initial , String offset ) { BigDecimal number ; BigDecimal dOffset ; try { number = new BigDecimal ( initial ) ; dOffset = new BigDecimal ( offset ) ; } catch ( Exception ex ) { return null ; } return number . add ( dOffset ) . toString ( ) ; } | Offset a numeric string by another numeric string . |
28,773 | public static String multiply ( String f1 , String f2 ) { BigDecimal factor1 ; BigDecimal factor2 ; try { factor1 = new BigDecimal ( f1 ) ; factor2 = new BigDecimal ( f2 ) ; } catch ( Exception ex ) { return null ; } return factor1 . multiply ( factor2 ) . toString ( ) ; } | Multiply two numbers together |
28,774 | public static String sum ( String ... addends ) { if ( addends == null || addends . length == 0 ) { return null ; } BigDecimal sum ; try { sum = new BigDecimal ( addends [ 0 ] ) ; for ( int i = 1 ; i < addends . length ; i ++ ) { sum = sum . add ( new BigDecimal ( addends [ i ] ) ) ; } return sum . toString ( ) ; } catch ( Exception e ) { return null ; } } | Get the sum of all input numbers |
28,775 | public static String substract ( String minuend , String ... subtrahends ) { if ( subtrahends == null ) { return minuend ; } BigDecimal difference ; try { difference = new BigDecimal ( minuend ) ; for ( int i = 0 ; i < subtrahends . length ; i ++ ) { difference = difference . subtract ( new BigDecimal ( subtrahends [ i ] ) ) ; } return difference . toString ( ) ; } catch ( Exception e ) { return null ; } } | Get the difference of minuend and all subtrahends |
28,776 | public static String product ( String ... factors ) { if ( factors == null || factors . length == 0 ) { return null ; } BigDecimal prodcut ; try { prodcut = new BigDecimal ( factors [ 0 ] ) ; for ( int i = 1 ; i < factors . length ; i ++ ) { prodcut = prodcut . multiply ( new BigDecimal ( factors [ i ] ) ) ; } return prodcut . toString ( ) ; } catch ( Exception e ) { return null ; } } | Get the product of all input numbers |
28,777 | public static String divide ( String dividend , String divisor ) { try { BigDecimal bdDividend = new BigDecimal ( dividend ) ; BigDecimal bdDivisor = new BigDecimal ( divisor ) ; try { return bdDividend . divide ( bdDivisor ) . toString ( ) ; } catch ( ArithmeticException ae ) { int scale = Math . max ( bdDividend . scale ( ) , bdDivisor . scale ( ) ) + 1 ; return divide ( dividend , divisor , scale ) ; } } catch ( Exception ex ) { return null ; } } | Get the result of dividend divided by divisor . When the result is indivisible the scale will depends on the scale of dividend and divisor . |
28,778 | public static String divide ( String dividend , String divisor , int scale ) { BigDecimal bdDividend ; BigDecimal bdDivisor ; try { bdDividend = new BigDecimal ( dividend ) ; bdDivisor = new BigDecimal ( divisor ) ; return bdDividend . divide ( bdDivisor , scale , RoundingMode . HALF_UP ) . toString ( ) ; } catch ( Exception e ) { return null ; } } | Get the result of dividend divided by divisor with given scale . |
28,779 | public static String average ( String ... values ) { if ( values != null ) { return divide ( sum ( values ) , values . length + "" ) ; } return null ; } | Get the average of all input numbers . When the result is indivisible the scale will depends on the scale of all input numbers |
28,780 | public static String min ( String ... values ) { BigDecimal bd ; BigDecimal bd2 ; try { int start = 0 ; while ( values [ start ] == null ) { start ++ ; } bd = new BigDecimal ( values [ start ] ) ; for ( int i = start + 1 ; i < values . length ; i ++ ) { if ( values [ i ] == null ) { continue ; } bd2 = new BigDecimal ( values [ i ] ) ; if ( bd . compareTo ( bd2 ) > 0 ) { bd = bd2 ; } } return bd . toString ( ) ; } catch ( Exception e ) { return null ; } } | Returns the minimum number from a group of input value . |
28,781 | public static String pow ( String base , String exponent ) { try { BigDecimal bdBase = new BigDecimal ( base ) ; BigDecimal bdExp = new BigDecimal ( exponent ) ; return Math . pow ( bdBase . doubleValue ( ) , bdExp . doubleValue ( ) ) + "" ; } catch ( Exception ex ) { return null ; } } | Returns the value of the first argument raised to the power of the second argument . |
28,782 | public static boolean compare ( String v1 , String v2 , CompareMode mode ) { BigDecimal bd1 ; BigDecimal bd2 ; try { bd1 = new BigDecimal ( v1 ) ; bd2 = new BigDecimal ( v2 ) ; int ret = bd1 . compareTo ( bd2 ) ; switch ( mode ) { case LESS : return ret < 0 ; case NOTLESS : return ret >= 0 ; case GREATER : return ret > 0 ; case NOTGREATER : return ret <= 0 ; case EQUAL : return ret == 0 ; default : return false ; } } catch ( Exception e ) { return false ; } } | Compare the input number by given mode The scale will depends on the scale of input number when the result is indivisible |
28,783 | public static String [ ] removeNull ( String [ ] in ) { if ( in == null ) { return new String [ 0 ] ; } ArrayList < String > arr = new ArrayList ( ) ; for ( int i = 0 ; i < in . length ; i ++ ) { if ( in [ i ] != null ) { arr . add ( in [ i ] ) ; } } if ( in . length == arr . size ( ) ) { return in ; } else { return arr . toArray ( new String [ 0 ] ) ; } } | Remove the null value in the input String array |
28,784 | public static String revisePath ( String path ) { if ( ! path . trim ( ) . equals ( "" ) ) { File f = new File ( path ) ; if ( f != null && ! f . exists ( ) ) { f . mkdirs ( ) ; } if ( ! f . isDirectory ( ) ) { f = f . getParentFile ( ) ; path = f . getPath ( ) ; } if ( ! path . endsWith ( File . separator ) ) { path += File . separator ; } } return path ; } | Revise output path |
28,785 | public static List < Field > getAllFields ( List < Field > fields , Class < ? > clazz ) { for ( Field field : clazz . getDeclaredFields ( ) ) { fields . add ( field ) ; } if ( clazz . getSuperclass ( ) != null ) { fields = getAllFields ( fields , clazz . getSuperclass ( ) ) ; } return fields ; } | This static method will get ALL fields for this class including any inherited ones . |
28,786 | public static List < Method > getAllMethods ( List < Method > methods , Class < ? > clazz ) { for ( Method method : clazz . getDeclaredMethods ( ) ) { methods . add ( method ) ; } if ( clazz . getSuperclass ( ) != null ) { methods = getAllMethods ( methods , clazz . getSuperclass ( ) ) ; } return methods ; } | This static method will get ALL methods for this class including any inherited ones . |
28,787 | @ RequestMapping ( value = "/video/{conversionFormat}/**" , method = RequestMethod . GET ) public ResponseEntity < InputStreamResource > getVideo ( WebRequest request , HttpServletRequest servletRequest , @ PathVariable ( value = "conversionFormat" ) String conversionFormat ) throws IOException { String path = extractPathFromPattern ( servletRequest ) ; LOG . debug ( "getVideo(path={}, conversionFormat={})" , path , conversionFormat ) ; try { GalleryFile galleryFile = galleryService . getVideo ( path , conversionFormat ) ; if ( ! GalleryFileType . VIDEO . equals ( galleryFile . getType ( ) ) ) { LOG . warn ( "File {} was not a video but {}. Throwing ResourceNotFoundException." , path , galleryFile . getType ( ) ) ; throw new ResourceNotFoundException ( ) ; } return returnResource ( request , galleryFile ) ; } catch ( FileNotFoundException fnfe ) { LOG . warn ( "Could not find resource {}" , path ) ; throw new ResourceNotFoundException ( ) ; } catch ( NotAllowedException nae ) { LOG . warn ( "User was not allowed to access resource {}" , path ) ; throw new ResourceNotFoundException ( ) ; } catch ( IOException ioe ) { LOG . error ( "Error when calling getVideo" , ioe ) ; throw ioe ; } } | Requests a video of a certain format . |
28,788 | private long [ ] getRangesFromHeader ( String rangeHeader ) { LOG . debug ( "Range header: {}" , rangeHeader ) ; long [ ] result = new long [ 2 ] ; final String headerPrefix = "bytes=" ; if ( StringUtils . startsWith ( rangeHeader , headerPrefix ) ) { String [ ] splitRange = rangeHeader . substring ( headerPrefix . length ( ) ) . split ( "-" ) ; try { result [ 0 ] = Long . parseLong ( splitRange [ 0 ] ) ; if ( splitRange . length > 1 ) { result [ 1 ] = Long . parseLong ( splitRange [ 1 ] ) ; } if ( result [ 0 ] < 0 || ( result [ 1 ] != 0 && result [ 0 ] > result [ 1 ] ) ) { throw new RangeException ( ) ; } } catch ( NumberFormatException nfe ) { throw new RangeException ( ) ; } } return result ; } | Extracts the request range header if present . |
28,789 | private ImageFormat getImageFormatForCode ( String code ) { if ( code == null || imageFormats == null ) { return null ; } for ( ImageFormat oneImageFormat : imageFormats ) { if ( code . equalsIgnoreCase ( oneImageFormat . getCode ( ) ) ) { return oneImageFormat ; } } return null ; } | Retrieves the image format for the image format code . |
28,790 | public static String compressNumber ( String value , CompressionLevel compressionLevel ) { value = value . replaceAll ( "([0-9])0+$" , "$1" ) ; if ( compressionLevel . equals ( CompressionLevel . NORMAL ) ) { value = value . replaceAll ( "\\.0+$" , ".0" ) ; } else if ( compressionLevel . equals ( CompressionLevel . WITHOUT_TRAILING_ZEROS ) ) { value = value . replaceAll ( "\\.0+$" , "" ) ; } return value ; } | Removes the unnecessary 0 - s from the end of a number . For example 0 . 7000 becomes 0 . 7 0 . 00000 becomes 0 . 0 . |
28,791 | public static synchronized void deployment ( Class < ? > deployment ) { Preconditions . checkArgument ( deployment != null , "Parameter 'deployment' must not be [" + deployment + "]" ) ; Preconditions . checkArgument ( deployment . getAnnotation ( Deployment . class ) != null , "'deployment' [" + deployment + "] must be annotated with @Deployment" ) ; Jaguar . deployment = deployment ; logger . info ( "Deployment has been set to [" + deployment . getSimpleName ( ) + "]" ) ; } | Sets the deployment qualifier . The deployment qualifier must be specified before Jaguar starts . |
28,792 | public static synchronized void bootstrap ( ) { if ( container != null ) { logger . debug ( "Jaguar has already started" ) ; return ; } logger . info ( "Starting Jaguar on Java Runtime Environment [" + Environment . getProperty ( "java.version" ) + "]" ) ; try { container = new Container ( ) ; container . initialize ( ) ; } catch ( Exception e ) { container = null ; throw new UncheckedException ( e ) ; } } | Bootstraps Jaguar . |
28,793 | public static synchronized void shutdown ( ) { if ( container == null ) { logger . debug ( "Jaguar has already stopped" ) ; return ; } try { container . dispose ( ) ; } finally { container = null ; deployment = null ; logger . info ( "Jaguar stopped" ) ; } } | Shuts down Jaguar . |
28,794 | public static synchronized void install ( Class < ? > component ) { Preconditions . checkState ( container != null , "Cannot install component until Jaguar starts" ) ; if ( ! installed ( component ) ) { container . install ( component ) ; } } | Installs the specified component into Jaguar . The component must be installed after Jaguar started . |
28,795 | public static boolean installed ( Class < ? > component ) { Preconditions . checkState ( container != null , "Cannot indicate if the specified component has been installed " + "until Jaguar starts" ) ; return container . installed ( component ) ; } | Indicates the specified component installed or not . |
28,796 | public static < T > T component ( Class < T > component ) { Preconditions . checkState ( container != null , "Cannot assemble component until Jaguar starts" ) ; return container . component ( component ) ; } | Returns assembled component instance of the specified component type . This method must be invoked after Jaguar started . |
28,797 | public static < T > T assemble ( T component ) { Preconditions . checkState ( container != null , "Cannot assemble dependent component until Jaguar starts" ) ; return container . assemble ( component ) ; } | Assembles the specified component instance by injecting the dependent components into it . This method must be invoked after Jaguar started . |
28,798 | public ParallelEngine setWaitMode ( WaitMode mode , long timeout , TimeUnit unit ) { this . mode = mode ; this . timeout = timeout ; this . unit = unit ; return this ; } | Sets the wait mode the number of units and their scale before the wait for the background activities times out . |
28,799 | public Vector execute ( TypedVector < ActivityInfo > infos ) throws ActivityException { if ( infos != null && ! infos . isEmpty ( ) ) { logger . trace ( "executing {} activities..." , infos . size ( ) ) ; int i = 0 ; TypedVector < Future < ActivityData > > futures = new TypedVector < Future < ActivityData > > ( ) ; for ( ActivityInfo info : infos ) { ActivityCallable callable = new ActivityCallable ( i ++ , queue , info ) ; futures . add ( submit ( callable ) ) ; } return wait ( futures ) ; } else { logger . warn ( "no activities to execute" ) ; } return null ; } | Submits a set of activities to the underlying asynchornous execution mechanism . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.