idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
5,800 | public static final String defaultToString ( Object object ) { if ( object == null ) return "null" ; else return object . getClass ( ) . getName ( ) + '@' + Integer . toHexString ( System . identityHashCode ( object ) ) ; } | The default toString implementation of an object |
5,801 | public static long parseTimePeriod ( String period ) { try { String s = period . toLowerCase ( ) ; long factor ; if ( s . endsWith ( "msec" ) ) { s = s . substring ( 0 , s . lastIndexOf ( "msec" ) ) ; factor = MSEC ; } else if ( s . endsWith ( "sec" ) ) { s = s . substring ( 0 , s . lastIndexOf ( "sec" ) ) ; factor = SECS ; } else if ( s . endsWith ( "min" ) ) { s = s . substring ( 0 , s . lastIndexOf ( "min" ) ) ; factor = MINS ; } else if ( s . endsWith ( "h" ) ) { s = s . substring ( 0 , s . lastIndexOf ( "h" ) ) ; factor = HOUR ; } else { factor = 1 ; } return Long . parseLong ( s ) * factor ; } catch ( RuntimeException e ) { throw new NumberFormatException ( "For input time period: '" + period + "'" ) ; } } | Parses a time period into a long . |
5,802 | public static String trimLeadingCharacter ( String str , final char leadingCharacter ) { return trimLeadingCharacter ( str , new CharacterFilter ( ) { public boolean isCharacterLegal ( char character ) { return character == leadingCharacter ; } } ) ; } | Trim all occurences of the supplied leading character from the given String . |
5,803 | public static String readOutput ( BufferedReader in ) throws IOException { StringBuffer output = new StringBuffer ( ) ; String line = "" ; while ( ( line = in . readLine ( ) ) != null ) { output . append ( line ) ; output . append ( "\n" ) ; } return output . toString ( ) ; } | Reads the output of the reader and delivers it at string . |
5,804 | public static TextClassifier getClassifier ( File resourceDirectoryFile ) throws Exception { if ( resourceDirectoryFile . toString ( ) . endsWith ( ".zip" ) && resourceDirectoryFile . isFile ( ) ) { resourceDirectoryFile = UnZip . unzip ( resourceDirectoryFile ) ; } if ( resourceDirectoryFile . exists ( ) == false ) throw new IOException ( "Directory " + resourceDirectoryFile . getAbsolutePath ( ) + " does not exist" ) ; File lexiconFile = new File ( resourceDirectoryFile , Parameters . lexiconName ) ; if ( lexiconFile . exists ( ) == false ) throw new IOException ( "Lexicon " + lexiconFile + " does not exist" ) ; File modelFile = new File ( resourceDirectoryFile , Parameters . modelName ) ; if ( modelFile . exists ( ) == false ) throw new IOException ( "Model " + modelFile + " does not exist" ) ; Lexicon lexicon = new Lexicon ( lexiconFile . toString ( ) ) ; String classifier = lexicon . getClassifierType ( ) ; TextClassifier instance = ( TextClassifier ) Class . forName ( classifier ) . newInstance ( ) ; instance . lastmodifiedLexicon = lexiconFile . lastModified ( ) ; instance . pathResourceDirectory = resourceDirectoryFile . getAbsolutePath ( ) ; instance . lexicon = lexicon ; instance . loadModel ( ) ; return instance ; } | Returns a specific instance of a Text Classifier given a resource Directory |
5,805 | public Map < Integer , Integer > compact ( ) { Map < Integer , Integer > equiv = new HashMap < Integer , Integer > ( ) ; TreeMap < Integer , int [ ] > newIndex2docfreq = new TreeMap < Integer , int [ ] > ( ) ; Iterator < Entry < String , int [ ] > > iter = tokenForm2index . entrySet ( ) . iterator ( ) ; nextAttributeID = 1 ; while ( iter . hasNext ( ) ) { Entry < String , int [ ] > entry = iter . next ( ) ; int oldIndex = entry . getValue ( ) [ 0 ] ; int newIndex = nextAttributeID ; entry . setValue ( new int [ ] { newIndex } ) ; equiv . put ( oldIndex , newIndex ) ; int [ ] docFreq = index2docfreq . get ( oldIndex ) ; newIndex2docfreq . put ( newIndex , docFreq ) ; nextAttributeID ++ ; } index2docfreq = newIndex2docfreq ; return equiv ; } | Adjust the indices of the attributes so that maxAttributeID == getAttributesNum . Returns a Map containing the mapping between the old indices and the new ones . |
5,806 | public WeightingMethod getMethod ( String fieldName ) { WeightingMethod method = this . customWeights . get ( fieldName ) ; if ( method != null ) return method ; return this . method_used ; } | Returns the weighting scheme used for a specific field or the default one if nothing has been specified for it |
5,807 | public int getIndex ( String tokenForm ) { int [ ] index = ( int [ ] ) tokenForm2index . get ( tokenForm ) ; if ( index == null ) return - 1 ; return index [ 0 ] ; } | returns the position of a given tokenform or - 1 if the tokenform is unknown or has been filtered out |
5,808 | public int createIndex ( String tokenForm ) { int [ ] index = ( int [ ] ) tokenForm2index . get ( tokenForm ) ; if ( index == null ) { index = new int [ ] { nextAttributeID } ; tokenForm2index . put ( tokenForm , index ) ; nextAttributeID ++ ; } Integer integ = Integer . valueOf ( index [ 0 ] ) ; int [ ] docfreq = ( int [ ] ) this . index2docfreq . get ( integ ) ; if ( docfreq == null ) { docfreq = new int [ ] { 0 } ; index2docfreq . put ( integ , docfreq ) ; } docfreq [ 0 ] ++ ; return index [ 0 ] ; } | called from Document |
5,809 | public void addDocument ( Document doc ) throws IOException { String serial = doc . getStringSerialization ( ) ; raw_file_buffer . write ( serial ) ; } | there is exactly one document per line |
5,810 | public static void getAttributeScores ( String modelPath , String lexiconF , int topAttributesNumber ) throws IOException { Lexicon lexicon = new Lexicon ( lexiconF ) ; Model liblinearModel = Model . load ( new File ( modelPath ) ) ; double [ ] weights = liblinearModel . getFeatureWeights ( ) ; int numClasses = liblinearModel . getNrClass ( ) ; int numFeatures = liblinearModel . getNrFeature ( ) ; Map < Integer , String > invertedAttributeIndex = lexicon . getInvertedIndex ( ) ; Map < String , WeightedAttributeQueue > topAttributesPerLabel = new HashMap < String , WeightedAttributeQueue > ( numClasses ) ; if ( topAttributesNumber != - 1 ) { for ( int classNum = 0 ; classNum < numClasses ; classNum ++ ) { String classLabel = lexicon . getLabel ( classNum ) ; WeightedAttributeQueue queue = new WeightedAttributeQueue ( topAttributesNumber ) ; topAttributesPerLabel . put ( classLabel , queue ) ; } } for ( int classNum = 0 ; classNum < numClasses ; classNum ++ ) { String classLabel = lexicon . getLabel ( classNum ) ; WeightedAttributeQueue queue = topAttributesPerLabel . get ( classLabel ) ; for ( int featNum = 0 ; featNum < numFeatures ; featNum ++ ) { int pos = featNum * numClasses + classNum ; double featWeight = weights [ pos ] ; String attLabel = invertedAttributeIndex . get ( featNum + 1 ) ; if ( featWeight < 0.001 && featWeight > - 0.001 ) featWeight = 0 ; if ( topAttributesNumber != - 1 ) { WeightedAttribute wa = new WeightedAttribute ( attLabel , featWeight ) ; queue . insertWithOverflow ( wa ) ; continue ; } System . out . println ( attLabel + "\t" + classLabel + "\t" + featWeight ) ; } } if ( topAttributesNumber < 1 ) return ; Iterator < String > labelIter = topAttributesPerLabel . keySet ( ) . iterator ( ) ; while ( labelIter . hasNext ( ) ) { String label = ( String ) labelIter . next ( ) ; System . out . println ( "LABEL : " + label ) ; WeightedAttributeQueue queue = topAttributesPerLabel . get ( label ) ; String [ ] sorted = new String [ queue . size ( ) ] ; for ( int i = queue . size ( ) - 1 ; i >= 0 ; i -- ) { WeightedAttribute wa = queue . pop ( ) ; sorted [ i ] = wa . label + " : " + wa . weight ; } for ( int j = 0 ; j < sorted . length ; j ++ ) { System . out . println ( j + 1 + "\t" + sorted [ j ] ) ; } } } | Prints out the attributes and their weights from the models generated by liblinear . This is different from CorpusUtils . dumpBestAttributes which computes a score for the attributes regardless of the model . |
5,811 | public int compareTo ( WeightedAttribute att ) { double absoltarget = att . weight ; double absolsource = this . weight ; double diff = absolsource - absoltarget ; if ( diff < 0 ) return - 1 ; if ( diff > 0 ) return + 1 ; return 0 ; } | rank the attributes based on weight |
5,812 | public static boolean isSnapshot ( Version version ) { Assert . notNull ( version , "Version must not be null." ) ; return version . toString ( ) . endsWith ( SNAPSHOT_SUFFIX ) ; } | Returns if the version specified is a SNAPSHOT |
5,813 | private boolean isCanonical ( final FileDescriptor file ) { final FileDescriptorProto proto = file . toProto ( ) ; if ( proto . hasOptions ( ) && proto . getOptions ( ) . getUninterpretedOptionCount ( ) > 0 ) { return false ; } for ( final FieldDescriptorProto field : proto . getExtensionList ( ) ) { if ( ! isFieldCanonical ( field ) ) { return false ; } } for ( final ServiceDescriptorProto serviceProto : proto . getServiceList ( ) ) { if ( ! isCanonical ( serviceProto ) ) { return false ; } } for ( final EnumDescriptorProto enumProto : proto . getEnumTypeList ( ) ) { if ( ! isCanonical ( enumProto ) ) { return false ; } } for ( final DescriptorProto message : proto . getMessageTypeList ( ) ) { if ( ! isMessageRefsCanonical ( message ) ) { return false ; } } return true ; } | very consuming and problematic! |
5,814 | private void ensureBuilders ( ) { if ( this . builders == null ) { this . builders = new ArrayList < SingleFieldBuilder < MType , BType , IType > > ( messages . size ( ) ) ; for ( int i = 0 ; i < messages . size ( ) ; i ++ ) { builders . add ( null ) ; } } } | Ensures that the list of builders is not null . If it s null the list is created and initialized to be the same size as the messages list with null entries . |
5,815 | public RepeatedFieldBuilder < MType , BType , IType > addAllMessages ( final Iterable < ? extends MType > values ) { for ( final MType value : values ) { if ( value == null ) { throw new NullPointerException ( ) ; } } if ( values instanceof Collection ) { @ SuppressWarnings ( "unchecked" ) final Collection < MType > collection = ( Collection < MType > ) values ; if ( collection . size ( ) == 0 ) { return this ; } ensureMutableMessageList ( ) ; for ( final MType value : values ) { addMessage ( value ) ; } } else { ensureMutableMessageList ( ) ; for ( final MType value : values ) { addMessage ( value ) ; } } onChanged ( ) ; incrementModCounts ( ) ; return this ; } | Appends all of the messages in the specified collection to the end of this list in the order that they are returned by the specified collection s iterator . |
5,816 | public BType addBuilder ( final MType message ) { ensureMutableMessageList ( ) ; ensureBuilders ( ) ; final SingleFieldBuilder < MType , BType , IType > builder = newSingleFieldBuilder ( message , this , isClean ) ; messages . add ( null ) ; builders . add ( builder ) ; onChanged ( ) ; incrementModCounts ( ) ; return builder . getBuilder ( ) ; } | Appends a new builder to the end of this list and returns the builder . |
5,817 | public List < MType > getMessageList ( ) { if ( externalMessageList == null ) { externalMessageList = new MessageExternalList < MType , BType , IType > ( this ) ; } return externalMessageList ; } | Gets a view of the builder as a list of messages . The returned list is live and will reflect any changes to the underlying builder . |
5,818 | public List < BType > getBuilderList ( ) { if ( externalBuilderList == null ) { externalBuilderList = new BuilderExternalList < MType , BType , IType > ( this ) ; } return externalBuilderList ; } | Gets a view of the builder as a list of builders . This returned list is live and will reflect any changes to the underlying builder . |
5,819 | public List < IType > getMessageOrBuilderList ( ) { if ( externalMessageOrBuilderList == null ) { externalMessageOrBuilderList = new MessageOrBuilderExternalList < MType , BType , IType > ( this ) ; } return externalMessageOrBuilderList ; } | Gets a view of the builder as a list of MessageOrBuilders . This returned list is live and will reflect any changes to the underlying builder . |
5,820 | private void incrementModCounts ( ) { if ( externalMessageList != null ) { externalMessageList . incrementModCount ( ) ; } if ( externalBuilderList != null ) { externalBuilderList . incrementModCount ( ) ; } if ( externalMessageOrBuilderList != null ) { externalMessageOrBuilderList . incrementModCount ( ) ; } } | Increments the mod counts so that an ConcurrentModificationException can be thrown if calling code tries to modify the builder while its iterating the list . |
5,821 | private void collectRequiredAddons ( AddonInfo addonInfo , List < AddonInfo > addons ) { addons . remove ( addonInfo ) ; addons . add ( 0 , addonInfo ) ; for ( AddonId addonId : addonInfo . getRequiredAddons ( ) ) { if ( ! addons . contains ( addonId ) && ( ! isDeployed ( addonId ) || ! isEnabled ( addonId ) ) ) { AddonInfo childInfo = info ( addonId ) ; collectRequiredAddons ( childInfo , addons ) ; } } } | Collect all required addons for a specific addon . |
5,822 | public void parse ( String str ) { if ( buffer . length ( ) > 0 ) { str = buffer . toString ( ) . concat ( str ) ; buffer = new StringBuilder ( ) ; } Reader reader = new StringReader ( str ) ; try { try { parse ( reader ) ; } finally { reader . close ( ) ; } } catch ( IOException ex ) { } } | Parses the specified string . |
5,823 | private void parse ( Reader reader ) throws IOException { StringBuilder text = new StringBuilder ( ) ; int character ; while ( ( character = reader . read ( ) ) != - 1 ) { boolean introducedControlSequence = false ; if ( character == SINGLE_CSI ) { introducedControlSequence = true ; } else if ( character == MULTI_CSI [ 0 ] ) { int nextCharacter = reader . read ( ) ; if ( nextCharacter == - 1 ) { buffer . append ( ( char ) character ) ; break ; } else if ( nextCharacter == MULTI_CSI [ 1 ] ) { introducedControlSequence = true ; } else { text . append ( ( char ) character ) ; text . append ( ( char ) nextCharacter ) ; } } else { text . append ( ( char ) character ) ; } if ( introducedControlSequence ) { if ( text . length ( ) > 0 ) { listener . parsedString ( text . toString ( ) ) ; text = new StringBuilder ( ) ; } parseControlSequence ( reader ) ; } } if ( text . length ( ) > 0 ) { listener . parsedString ( text . toString ( ) ) ; } } | Parses characters from the specified character reader . |
5,824 | private void parseControlSequence ( Reader reader ) throws IOException { boolean finishedSequence = false ; StringBuilder parameters = new StringBuilder ( ) ; int character ; while ( ( character = reader . read ( ) ) != - 1 ) { if ( ( character >= 'a' && character <= 'z' ) || ( character >= 'A' && character <= 'Z' ) ) { String [ ] array = parameters . toString ( ) . split ( ";" ) ; AnsiControlSequence seq = new AnsiControlSequence ( ( char ) character , array ) ; listener . parsedControlSequence ( seq ) ; finishedSequence = true ; break ; } else { parameters . append ( ( char ) character ) ; } } if ( ! finishedSequence ) { buffer . append ( ( char ) SINGLE_CSI ) ; buffer . append ( parameters ) ; } } | Parses a control sequence . |
5,825 | public static < T > ArgumentProcessor < T > newInstance ( Class < ? extends T > beanType , CommandLineParser parser ) { return ArgumentProcessorFactory . getInstance ( ) . newProcessor ( beanType , parser ) ; } | Create new instance with given bean type and command line parser that describes command line sytnax . |
5,826 | public T process ( String [ ] arguments , T bean ) { return process ( Arrays . asList ( arguments ) , bean ) ; } | Process argument array and pass values to given bean |
5,827 | public void onBindViewHolder ( EfficientViewHolder < T > viewHolder , int position , EfficientAdapter < T > adapter ) { T object = get ( position ) ; viewHolder . onBindView ( object , position ) ; viewHolder . setAdapter ( adapter ) ; setClickListenerOnView ( viewHolder ) ; setLongClickListenerOnView ( viewHolder ) ; } | Called by the view to display the data at the specified position . |
5,828 | int remove ( T object ) { int positionOfRemove = mObjects . indexOf ( object ) ; if ( positionOfRemove >= 0 ) { T objectRemoved = removeAt ( positionOfRemove ) ; if ( objectRemoved != null ) { return positionOfRemove ; } } return - 1 ; } | Remove the specified object of the array . |
5,829 | public void addPoint ( Point p ) { if ( p == null ) throw new NullPointerException ( ) ; points . add ( new Point ( p ) ) ; repaint ( ) ; } | Adds a point to the list of pixels marked by this overlay . |
5,830 | public void setPoint ( Point p ) { points . clear ( ) ; if ( p != null ) { points . add ( new Point ( p ) ) ; } repaint ( ) ; } | Sets the argument as the only point marked by this overlay . |
5,831 | public void setPoints ( Iterable < Point > points ) { if ( points == null ) throw new NullPointerException ( ) ; this . points . clear ( ) ; for ( Point p : points ) { this . points . add ( new Point ( p ) ) ; } repaint ( ) ; } | Sets the marked pixels . |
5,832 | public static void setVisibility ( EfficientCacheView cacheView , int viewId , int visibility ) { View view = cacheView . findViewByIdEfficient ( viewId ) ; if ( view != null ) { view . setVisibility ( visibility ) ; } } | Equivalent to calling View . setVisibility |
5,833 | public static void setBackground ( EfficientCacheView cacheView , int viewId , Drawable drawable ) { View view = cacheView . findViewByIdEfficient ( viewId ) ; if ( view != null ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . JELLY_BEAN ) { view . setBackgroundDrawable ( drawable ) ; } else { view . setBackground ( drawable ) ; } } } | Equivalent to calling View . setBackground |
5,834 | public static void setImageDrawable ( EfficientCacheView cacheView , int viewId , Drawable drawable ) { View view = cacheView . findViewByIdEfficient ( viewId ) ; if ( view instanceof ImageView ) { ( ( ImageView ) view ) . setImageDrawable ( drawable ) ; } } | Equivalent to calling ImageView . setImageDrawable |
5,835 | public static void setImageBitmap ( EfficientCacheView cacheView , int viewId , Bitmap bm ) { View view = cacheView . findViewByIdEfficient ( viewId ) ; if ( view instanceof ImageView ) { ( ( ImageView ) view ) . setImageBitmap ( bm ) ; } } | Equivalent to calling ImageView . setImageBitmap |
5,836 | private void init ( ) { setLayout ( new BorderLayout ( 0 , 0 ) ) ; int rows = model . getRows ( ) ; int bufferSize = model . getBufferSize ( ) ; if ( bufferSize > rows ) { scrollBar = new JScrollBar ( JScrollBar . VERTICAL , 0 , rows , 0 , bufferSize + 1 ) ; scrollBar . addAdjustmentListener ( new AdjustmentListener ( ) { public void adjustmentValueChanged ( AdjustmentEvent evt ) { repaint ( ) ; } } ) ; add ( BorderLayout . LINE_END , scrollBar ) ; } add ( BorderLayout . CENTER , new Terminal ( ) ) ; repaint ( ) ; } | Initializes the terminal . |
5,837 | public void clearViewCached ( int parentId , int viewId ) { SparseArray < View > sparseArrayViewsParent = mSparseSparseArrayView . get ( parentId ) ; if ( sparseArrayViewsParent != null ) { sparseArrayViewsParent . remove ( viewId ) ; } } | Clear the cache for the view specify |
5,838 | public CommandLineBuilder withLongOption ( String name , String value ) { cl . addOptionValue ( name , value , false ) ; return this ; } | Add an option with its long name |
5,839 | public CommandLineBuilder withShortOption ( String name , String value ) { cl . addOptionValue ( name , value , true ) ; return this ; } | Add an option with its short name |
5,840 | @ SuppressWarnings ( "unchecked" ) < P > void setValues ( T bean , List < String > values ) { Collection < P > col ; try { col = ( Collection < P > ) listType . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( "Can't instantiate " + listType , e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( "Can't access default constructor of " + listType ) ; } for ( String value : values ) { col . add ( ( P ) converter . fromCharacters ( value ) ) ; } ref . writeValue ( col , bean ) ; } | Write multi value to bean |
5,841 | private static < A extends Annotation > A getAnnotation ( PropertyDescriptor descriptor , Class < A > type ) { A a = null ; if ( descriptor . getWriteMethod ( ) != null ) { a = descriptor . getWriteMethod ( ) . getAnnotation ( type ) ; } if ( a == null && descriptor . getReadMethod ( ) != null ) { a = descriptor . getReadMethod ( ) . getAnnotation ( type ) ; } return a ; } | Get annotation from either writer or reader of a Java property |
5,842 | public final void setModel ( PixelModel newModel ) { if ( newModel == null ) throw new NullPointerException ( ) ; if ( model != newModel ) { if ( model != null ) model . removeChangeListener ( modelListener ) ; model = newModel ; model . addChangeListener ( modelListener ) ; update ( ) ; } } | Sets the model dictating the pixel shown by this status bar . |
5,843 | protected final void update ( ) { BufferedImage image = getImageViewer ( ) == null ? null : getImageViewer ( ) . getImage ( ) ; if ( image == null || model . isInvalid ( ) || model . getX ( ) >= image . getWidth ( ) || model . getY ( ) >= image . getHeight ( ) ) updateLabelNoData ( ) ; else updateLabel ( image , model . getX ( ) , model . getY ( ) , statusBar . getWidth ( ) - statusBarInsets . left - statusBarInsets . right ) ; } | Updates the info label . This function is called when either the selected pixel or the image shown in the viewer is changed . You can call this method to indicate that the message should be updated for some different reason . |
5,844 | public void setPosition ( int pos ) { if ( pos < 0 || pos >= number ) throw new IllegalArgumentException ( "Position " + pos + " out of range" ) ; position = pos ; updateLocationDefinition ( position ) ; forwardButton . setEnabled ( position < number - 1 ) ; backwardButton . setEnabled ( position > 0 ) ; if ( panel . getParent ( ) != null ) positionChanged ( ) ; } | Sets the position of the viewer . |
5,845 | public void setStatusBarVisible ( boolean statusBarVisible ) { if ( this . statusBarVisible == statusBarVisible ) return ; if ( statusBar != null ) { if ( statusBarVisible ) panel . add ( statusBar . getComponent ( ) , BorderLayout . SOUTH ) ; else panel . remove ( statusBar . getComponent ( ) ) ; panel . revalidate ( ) ; panel . repaint ( ) ; } boolean prev = this . statusBarVisible ; this . statusBarVisible = statusBarVisible ; synchronizer . statusBarVisibilityChanged ( this ) ; propertyChangeSupport . firePropertyChange ( "statusBarVisible" , prev , statusBarVisible ) ; } | Sets whether the status bar is visible . The status bar is hidden by default . |
5,846 | public View . OnClickListener getOnClickListener ( boolean adapterHasListener ) { if ( isClickable ( ) && adapterHasListener ) { if ( mViewHolderClickListener == null ) { mViewHolderClickListener = new ViewHolderClickListener < > ( this ) ; } } else { mViewHolderClickListener = null ; } return mViewHolderClickListener ; } | Get the OnClickListener to call when the user click on the item . |
5,847 | public View . OnLongClickListener getOnLongClickListener ( boolean adapterHasListener ) { if ( isLongClickable ( ) && adapterHasListener ) { if ( mViewHolderLongClickListener == null ) { mViewHolderLongClickListener = new ViewHolderLongClickListener < > ( this ) ; } } else { mViewHolderLongClickListener = null ; } return mViewHolderLongClickListener ; } | Get the OnLongClickListener to call when the user long - click on the item . |
5,848 | Reference < T > lookupReference ( String name , boolean isLongName ) { if ( isLongName ) { for ( Reference < T > r : referenceMap . values ( ) ) { if ( r . longName . equals ( name ) ) { return r ; } } return null ; } return referenceMap . get ( name ) ; } | Find reference with given name of option or argument |
5,849 | void end ( ) { switch ( state ) { case OPTION : currentOption = context . optionWithShortName ( currentValue . substring ( 1 ) ) ; case LONG_OPTION : if ( state == ArgumentsInspectorState . LONG_OPTION ) { currentOption = context . optionWithLongName ( currentValue . substring ( 2 ) ) ; } if ( currentOption != null && ! currentOption . isMultiValue ( ) ) { remainingOptions . remove ( currentOption ) ; } if ( currentOption == null || currentOption . isFlag ( ) ) { state = ArgumentsInspectorState . ARGUMENT ; } else { state = ArgumentsInspectorState . OPTION_VALUE ; } break ; default : state = ArgumentsInspectorState . READY ; } currentValue = null ; } | End the process |
5,850 | void setValue ( T bean , String value ) { ref . writeValue ( converter . fromCharacters ( value ) , bean ) ; } | Set a string value to bean based on known conversion rule and value reference |
5,851 | protected void fireChange ( ) { Object [ ] listeners = listenerList . getListenerList ( ) ; ChangeEvent event = new ChangeEvent ( this ) ; for ( int i = listeners . length - 2 ; i >= 0 ; i -= 2 ) { if ( listeners [ i ] == ChangeListener . class ) { ( ( ChangeListener ) listeners [ i + 1 ] ) . stateChanged ( event ) ; } } } | Notifies the registered listeners that the model has changed . |
5,852 | public void addOverlay ( Overlay overlay , int layer ) { if ( overlay == null ) throw new NullPointerException ( ) ; OverlayComponent c = new OverlayComponent ( overlay , theImage ) ; overlay . addOverlayComponent ( c ) ; layeredPane . add ( c , Integer . valueOf ( layer ) ) ; layeredPane . revalidate ( ) ; layeredPane . repaint ( ) ; } | Adds an overlay as the specified layer . |
5,853 | public void removeOverlay ( Overlay overlay ) { if ( overlay == null ) throw new NullPointerException ( ) ; for ( Component c : layeredPane . getComponents ( ) ) { if ( c instanceof OverlayComponent && ( ( OverlayComponent ) c ) . overlay == overlay ) { overlay . removeOverlayComponent ( ( OverlayComponent ) c ) ; layeredPane . remove ( c ) ; layeredPane . revalidate ( ) ; layeredPane . repaint ( ) ; return ; } } throw new IllegalArgumentException ( "Overlay not part of this viewer" ) ; } | Removes an overlay from the image viewer . |
5,854 | protected Map < String , Role > parseDefinedRoles ( Config config ) { Map < String , Role > roleMap = new HashMap < > ( ) ; if ( ! config . hasPath ( "roles" ) ) { log . trace ( "'{}' has no roles" , config ) ; } else if ( config . hasPath ( "roles" ) ) { log . trace ( "Parsing Role definitions" ) ; Config roleConfig = config . getConfig ( "roles" ) ; for ( Map . Entry < String , ConfigValue > entry : roleConfig . entrySet ( ) ) { String name = entry . getKey ( ) ; List < String > permissions = roleConfig . getStringList ( name ) ; Role role = new Role ( name , permissions . toArray ( new String [ permissions . size ( ) ] ) ) ; roleMap . put ( role . getName ( ) , role ) ; } } return Collections . unmodifiableMap ( roleMap ) ; } | Parse the Roles specified in the Config object . |
5,855 | public static Collection < Class < ? > > getClasses ( String ... packageNames ) { List < Class < ? > > classes = new ArrayList < > ( ) ; for ( String packageName : packageNames ) { final String packagePath = packageName . replace ( '.' , '/' ) ; final String packagePrefix = packageName + '.' ; List < URL > packageUrls = getResources ( packagePath ) ; for ( URL packageUrl : packageUrls ) { if ( packageUrl . getProtocol ( ) . equals ( "jar" ) ) { log . debug ( "Scanning jar {} for classes" , packageUrl ) ; try { String jar = packageUrl . toString ( ) . substring ( "jar:" . length ( ) ) . split ( "!" ) [ 0 ] ; File file = new File ( new URI ( jar ) ) ; try ( JarInputStream is = new JarInputStream ( new FileInputStream ( file ) ) ) { JarEntry entry = null ; while ( ( entry = is . getNextJarEntry ( ) ) != null ) { if ( ! entry . isDirectory ( ) && entry . getName ( ) . endsWith ( ".class" ) ) { String className = entry . getName ( ) . replace ( ".class" , "" ) . replace ( '/' , '.' ) ; if ( className . startsWith ( packagePrefix ) ) { Class < ? > aClass = getClass ( className ) ; classes . add ( aClass ) ; } } } } } catch ( URISyntaxException | IOException e ) { throw new FathomException ( e , "Failed to get classes for package '{}'" , packageName ) ; } } else { log . debug ( "Scanning filesystem {} for classes" , packageUrl ) ; log . debug ( packageUrl . getProtocol ( ) ) ; try ( InputStream is = packageUrl . openStream ( ) ) { Preconditions . checkNotNull ( is , "Package url %s stream is null!" , packageUrl ) ; try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( is , StandardCharsets . UTF_8 ) ) ) { classes . addAll ( reader . lines ( ) . filter ( line -> line != null && line . endsWith ( ".class" ) ) . map ( line -> { String className = line . replace ( ".class" , "" ) . replace ( '/' , '.' ) ; try { Class < ? > aClass = getClass ( packagePrefix + className ) ; return aClass ; } catch ( Exception e ) { log . error ( "Failed to find {}" , line , e ) ; } return null ; } ) . collect ( Collectors . toList ( ) ) ) ; } } catch ( IOException e ) { throw new FathomException ( e , "Failed to get classes for package '{}'" , packageName ) ; } } } } return Collections . unmodifiableCollection ( classes ) ; } | Returns the list of all classes within a package . |
5,856 | public static < T extends Annotation > T getAnnotation ( Method method , Class < T > annotationClass ) { T t = method . getAnnotation ( annotationClass ) ; if ( t == null ) { t = getAnnotation ( method . getDeclaringClass ( ) , annotationClass ) ; } return t ; } | Extract the annotation from the method or the declaring class . |
5,857 | protected void executeScript ( String scriptPath ) { URL scriptUrl = null ; try { if ( scriptPath . startsWith ( "classpath:" ) ) { String script = scriptPath . substring ( "classpath:" . length ( ) ) ; scriptUrl = ClassUtil . getResource ( script ) ; if ( scriptUrl == null ) { log . warn ( "Script '{}' not found!" , scriptPath ) ; } } else { File file = new File ( scriptPath ) ; if ( file . exists ( ) ) { scriptUrl = file . toURI ( ) . toURL ( ) ; } else { log . warn ( "Script '{}' not found!" , scriptPath ) ; } } if ( scriptUrl != null ) { executeScript ( scriptUrl ) ; } } catch ( Exception e ) { log . error ( "Failed to parse '{}' as a url" , scriptPath ) ; } } | Execute a script located either in the classpath or on the filesystem . |
5,858 | private byte [ ] berEncodedValue ( ) { final ByteBuffer buff = ByteBuffer . allocate ( 5 ) ; buff . put ( ( byte ) 0x30 ) ; buff . put ( ( byte ) 0x03 ) ; buff . put ( ( byte ) 0x02 ) ; buff . put ( ( byte ) 0x01 ) ; buff . put ( NumberFacility . leftTrim ( NumberFacility . getBytes ( flags ) ) ) ; return buff . array ( ) ; } | BER encode the flags . |
5,859 | public static String getEscaped ( byte ... bytes ) { final StringBuilder bld = new StringBuilder ( ) ; for ( byte b : bytes ) { bld . append ( "\\" ) . append ( Hex . get ( b ) ) ; } return bld . toString ( ) ; } | Gets escaped hex string corresponding to the given bytes . |
5,860 | public static byte [ ] reverse ( byte ... bytes ) { byte [ ] res = new byte [ bytes . length ] ; int j = 0 ; for ( int i = bytes . length - 1 ; i >= 0 ; i -- ) { res [ j ] = bytes [ i ] ; j ++ ; } return res ; } | Reverses bytes . |
5,861 | public static SID newInstance ( final byte [ ] identifier ) { final SID sid = new SID ( ) ; sid . setRevision ( ( byte ) 0x01 ) ; sid . setIdentifierAuthority ( identifier ) ; return sid ; } | Instances a new SID with the given identifier authority . |
5,862 | public static SID parse ( final byte [ ] src ) { final ByteBuffer sddlBuffer = ByteBuffer . wrap ( src ) ; final SID sid = new SID ( ) ; sid . parse ( sddlBuffer . asIntBuffer ( ) , 0 ) ; return sid ; } | Instances a SID instance of the given byte array . |
5,863 | int parse ( final IntBuffer buff , final int start ) { int pos = start ; final byte [ ] sidHeader = NumberFacility . getBytes ( buff . get ( pos ) ) ; revision = sidHeader [ 0 ] ; int subAuthorityCount = NumberFacility . getInt ( sidHeader [ 1 ] ) ; identifierAuthority = new byte [ 6 ] ; System . arraycopy ( sidHeader , 2 , identifierAuthority , 0 , 2 ) ; pos ++ ; System . arraycopy ( NumberFacility . getBytes ( buff . get ( pos ) ) , 0 , identifierAuthority , 2 , 4 ) ; for ( int j = 0 ; j < subAuthorityCount ; j ++ ) { pos ++ ; subAuthorities . add ( Hex . reverse ( NumberFacility . getBytes ( buff . get ( pos ) ) ) ) ; } return pos ; } | Load the SID from the buffer returning the last SID segment position into the buffer . |
5,864 | public static boolean isUserCannotChangePassword ( final SDDL sddl ) { boolean res = false ; final List < ACE > aces = sddl . getDacl ( ) . getAces ( ) ; for ( int i = 0 ; ! res && i < aces . size ( ) ; i ++ ) { final ACE ace = aces . get ( i ) ; if ( ace . getType ( ) == AceType . ACCESS_DENIED_OBJECT_ACE_TYPE && ace . getObjectFlags ( ) . getFlags ( ) . contains ( AceObjectFlags . Flag . ACE_OBJECT_TYPE_PRESENT ) ) { if ( GUID . getGuidAsString ( ace . getObjectType ( ) ) . equals ( UCP_OBJECT_GUID ) ) { final SID sid = ace . getSid ( ) ; if ( sid . getSubAuthorities ( ) . size ( ) == 1 ) { if ( ( Arrays . equals ( sid . getIdentifierAuthority ( ) , new byte [ ] { 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x01 } ) && Arrays . equals ( sid . getSubAuthorities ( ) . get ( 0 ) , new byte [ ] { 0x00 , 0x00 , 0x00 , 0x00 } ) ) || ( Arrays . equals ( sid . getIdentifierAuthority ( ) , new byte [ ] { 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x05 } ) && Arrays . equals ( sid . getSubAuthorities ( ) . get ( 0 ) , new byte [ ] { 0x00 , 0x00 , 0x00 , 0x0a } ) ) ) { res = true ; } } } } } return res ; } | Check if user canot change password . |
5,865 | protected final boolean isAuthenticated ( Context context ) { Account account = context . getSession ( AuthConstants . ACCOUNT_ATTRIBUTE ) ; if ( account == null ) { account = context . getLocal ( AuthConstants . ACCOUNT_ATTRIBUTE ) ; } return account != null && account . isAuthenticated ( ) ; } | Determines if the current Context has already been authenticated . |
5,866 | private byte [ ] berEncodedValue ( ) { final byte [ ] cookieSize = NumberFacility . leftTrim ( NumberFacility . getBytes ( cookie . length ) ) ; final byte [ ] size = NumberFacility . leftTrim ( NumberFacility . getBytes ( 14 + cookieSize . length + cookie . length ) ) ; final ByteBuffer buff = ByteBuffer . allocate ( 1 + 1 + size . length + 14 + cookieSize . length + cookie . length ) ; buff . put ( ( byte ) 0x30 ) ; buff . put ( ( byte ) ( size . length == 1 ? 0x81 : size . length == 2 ? 0x82 : 0x83 ) ) ; buff . put ( size ) ; buff . put ( ( byte ) 0x02 ) ; buff . put ( ( byte ) 0x04 ) ; buff . putInt ( flags ) ; buff . put ( ( byte ) 0x02 ) ; buff . put ( ( byte ) 0x04 ) ; buff . putInt ( Integer . MAX_VALUE ) ; buff . put ( ( byte ) 0x04 ) ; buff . put ( ( byte ) ( cookieSize . length == 1 ? 0x81 : cookieSize . length == 2 ? 0x82 : 0x83 ) ) ; buff . put ( cookieSize ) ; if ( cookie . length > 0 ) { buff . put ( cookie ) ; } return buff . array ( ) ; } | BER encode the cookie value . |
5,867 | private int parse ( final IntBuffer buff , final int start ) { int pos = start ; final byte [ ] header = NumberFacility . getBytes ( buff . get ( pos ) ) ; revision = header [ 0 ] ; controlFlags = new byte [ ] { header [ 3 ] , header [ 2 ] } ; final boolean [ ] controlFlag = NumberFacility . getBits ( controlFlags ) ; pos ++ ; if ( ! controlFlag [ 15 ] ) { offsetOwner = NumberFacility . getReverseUInt ( buff . get ( pos ) ) ; } else { offsetOwner = 0 ; } pos ++ ; if ( ! controlFlag [ 14 ] ) { offsetGroup = NumberFacility . getReverseUInt ( buff . get ( pos ) ) ; } else { offsetGroup = 0 ; } pos ++ ; if ( controlFlag [ 11 ] ) { offsetSACL = NumberFacility . getReverseUInt ( buff . get ( pos ) ) ; } else { offsetSACL = 0 ; } pos ++ ; if ( controlFlag [ 13 ] ) { offsetDACL = NumberFacility . getReverseUInt ( buff . get ( pos ) ) ; } else { offsetDACL = 0 ; } if ( offsetOwner > 0 ) { pos = ( int ) ( offsetOwner / 4 ) ; owner = new SID ( ) ; pos = owner . parse ( buff , pos ) ; } if ( offsetGroup > 0 ) { pos = ( int ) ( offsetGroup / 4 ) ; group = new SID ( ) ; pos = group . parse ( buff , pos ) ; } if ( offsetSACL > 0 ) { pos = ( int ) ( offsetSACL / 4 ) ; sacl = new ACL ( ) ; pos = sacl . parse ( buff , pos ) ; } if ( offsetDACL > 0 ) { pos = ( int ) ( offsetDACL / 4 ) ; dacl = new ACL ( ) ; pos = dacl . parse ( buff , pos ) ; } return pos ; } | Load the SDDL from the buffer returning the last SDDL segment position into the buffer . |
5,868 | public int getSize ( ) { return 20 + ( sacl == null ? 0 : sacl . getSize ( ) ) + ( dacl == null ? 0 : dacl . getSize ( ) ) + ( owner == null ? 0 : owner . getSize ( ) ) + ( group == null ? 0 : group . getSize ( ) ) ; } | Gets size in terms of number of bytes . |
5,869 | public byte [ ] toByteArray ( ) { final ByteBuffer buff = ByteBuffer . allocate ( getSize ( ) ) ; buff . put ( revision ) ; buff . put ( ( byte ) 0x00 ) ; buff . put ( controlFlags [ 1 ] ) ; buff . put ( controlFlags [ 0 ] ) ; buff . position ( 4 ) ; int nextAvailablePosition = 20 ; if ( owner == null ) { buff . putInt ( 0 ) ; } else { buff . put ( Hex . reverse ( NumberFacility . getBytes ( nextAvailablePosition ) ) ) ; buff . position ( nextAvailablePosition ) ; buff . put ( owner . toByteArray ( ) ) ; nextAvailablePosition += owner . getSize ( ) ; } buff . position ( 8 ) ; if ( group == null ) { buff . putInt ( 0 ) ; } else { buff . put ( Hex . reverse ( NumberFacility . getBytes ( nextAvailablePosition ) ) ) ; buff . position ( nextAvailablePosition ) ; buff . put ( group . toByteArray ( ) ) ; nextAvailablePosition += group . getSize ( ) ; } buff . position ( 12 ) ; if ( sacl == null ) { buff . putInt ( 0 ) ; } else { buff . put ( Hex . reverse ( NumberFacility . getBytes ( nextAvailablePosition ) ) ) ; buff . position ( nextAvailablePosition ) ; buff . put ( sacl . toByteArray ( ) ) ; nextAvailablePosition += sacl . getSize ( ) ; } buff . position ( 16 ) ; if ( dacl == null ) { buff . putInt ( 0 ) ; } else { buff . put ( Hex . reverse ( NumberFacility . getBytes ( nextAvailablePosition ) ) ) ; buff . position ( nextAvailablePosition ) ; buff . put ( dacl . toByteArray ( ) ) ; } return buff . array ( ) ; } | Serializes SDDL as byte array . |
5,870 | private void setAdminAttribute ( Account account ) { if ( adminGroups != null ) { for ( String adminGroup : adminGroups ) { if ( adminGroup . startsWith ( "@" ) && account . getUsername ( ) . equalsIgnoreCase ( adminGroup . substring ( 1 ) ) ) { account . getAuthorizations ( ) . addPermission ( "*" ) ; } else if ( account . hasRole ( adminGroup ) ) { account . getAuthorizations ( ) . addPermission ( "*" ) ; } } } } | Set the admin attribute from group memberships retrieved from LDAP . |
5,871 | public void setAllowOrigin ( String ... origin ) { allowOriginSet . clear ( ) ; allowOriginSet . addAll ( Arrays . asList ( origin ) ) ; allowOrigin = Joiner . on ( "," ) . join ( origin ) ; } | Set the list of request origins that are permitted to access the protected routes . |
5,872 | public void setAllowMethods ( String ... methods ) { allowMethodsSet . clear ( ) ; for ( String method : methods ) { allowMethodsSet . add ( method . toUpperCase ( ) ) ; } allowMethods = Joiner . on ( "," ) . join ( allowMethodsSet ) ; } | Set the list of request methods that may be sent by the browser for a CORS request . |
5,873 | public void setAllowHeaders ( String ... headers ) { allowHeadersSet . clear ( ) ; for ( String header : headers ) { allowHeadersSet . add ( header . toLowerCase ( ) ) ; } allowHeaders = Joiner . on ( "," ) . join ( headers ) ; } | Set the list of headers that may be sent by the browser for a CORS request . |
5,874 | protected Collection < Method > sortMethods ( Collection < Method > methods ) { List < Method > list = new ArrayList < > ( methods ) ; Collections . sort ( list , ( m1 , m2 ) -> { int o1 = Integer . MAX_VALUE ; Order order1 = ClassUtil . getAnnotation ( m1 , Order . class ) ; if ( order1 != null ) { o1 = order1 . value ( ) ; } int o2 = Integer . MAX_VALUE ; Order order2 = ClassUtil . getAnnotation ( m2 , Order . class ) ; if ( order2 != null ) { o2 = order2 . value ( ) ; } if ( o1 == o2 ) { String s1 = Util . toString ( m1 ) ; String s2 = Util . toString ( m2 ) ; return s1 . compareTo ( s2 ) ; } if ( o1 < o2 ) { return - 1 ; } else { return 1 ; } } ) ; return list ; } | Sort the methods by their preferred order if specified . |
5,875 | @ SuppressWarnings ( "empty-statement" ) public static byte [ ] leftTrim ( final byte ... bytes ) { int pos = 0 ; for ( ; pos < bytes . length && bytes [ pos ] == 0x00 ; pos ++ ) ; if ( pos < bytes . length ) { return Arrays . copyOfRange ( bytes , pos , bytes . length ) ; } else { return new byte [ ] { 0x00 } ; } } | Remove 0x00 bytes from left side . |
5,876 | public static boolean [ ] getBits ( final byte ... bytes ) { if ( bytes . length > 4 ) { throw new InvalidParameterException ( "Invalid number of bytes" ) ; } final boolean [ ] res = new boolean [ bytes . length * 8 ] ; int pos = 0 ; for ( byte b : bytes ) { for ( boolean bool : getBits ( b ) ) { res [ pos ] = bool ; pos ++ ; } } return res ; } | Gets bits as boolean array from a given byte array . |
5,877 | public static boolean [ ] getBits ( final byte b ) { final boolean [ ] res = new boolean [ 8 ] ; for ( int i = 0 ; i < 8 ; i ++ ) { res [ 7 - i ] = ( b & ( 1 << i ) ) != 0 ; } return res ; } | Gets bits as boolean array from a given byte . |
5,878 | public static long getUInt ( final byte ... bytes ) { if ( bytes . length > 4 ) { throw new InvalidParameterException ( "Invalid number of bytes" ) ; } long res = 0 ; for ( int i = 0 ; i < bytes . length ; i ++ ) { res |= bytes [ i ] & 0xFF ; if ( i < bytes . length - 1 ) { res <<= 8 ; } } return res ; } | Gets unsigned integer value corresponding to the given bytes . |
5,879 | private Set < String > toSet ( String value , String delimiter ) { if ( Strings . isNullOrEmpty ( value ) ) { return Collections . emptySet ( ) ; } else { Set < String > stringSet = new LinkedHashSet < > ( ) ; String [ ] values = value . split ( delimiter ) ; for ( String stringValue : values ) { if ( ! Strings . isNullOrEmpty ( stringValue ) ) { stringSet . add ( stringValue . trim ( ) ) ; } } return stringSet ; } } | Creates an ordered set from a comma or semi - colon delimited string . Empty values are discarded . |
5,880 | int parse ( final IntBuffer buff , final int start ) { int pos = start ; byte [ ] bytes = NumberFacility . getBytes ( buff . get ( pos ) ) ; revision = AclRevision . parseValue ( bytes [ 0 ] ) ; pos ++ ; bytes = NumberFacility . getBytes ( buff . get ( pos ) ) ; final int aceCount = NumberFacility . getInt ( bytes [ 1 ] , bytes [ 0 ] ) ; for ( int i = 0 ; i < aceCount ; i ++ ) { pos ++ ; final ACE ace = new ACE ( ) ; aces . add ( ace ) ; pos = ace . parse ( buff , pos ) ; } return pos ; } | Load the ACL from the buffer returning the last ACL segment position into the buffer . |
5,881 | public static boolean allowInstance ( Settings settings , Object object ) { Preconditions . checkNotNull ( object , "Can not check runtime permissions on a null instance!" ) ; if ( object instanceof Method ) { return allowMethod ( settings , ( Method ) object ) ; } return allowClass ( settings , object . getClass ( ) ) ; } | Determines if this object may be used in the current runtime environment . Fathom settings are considered as well as runtime modes . |
5,882 | public static boolean allowClass ( Settings settings , Class < ? > aClass ) { if ( aClass . isAnnotationPresent ( RequireSettings . class ) ) { RequireSetting [ ] requireSettings = aClass . getAnnotation ( RequireSettings . class ) . value ( ) ; StringJoiner joiner = new StringJoiner ( ", " ) ; Arrays . asList ( requireSettings ) . forEach ( ( require ) -> { if ( ! settings . hasSetting ( require . value ( ) ) ) { joiner . add ( require . value ( ) ) ; } } ) ; String requiredSettings = joiner . toString ( ) ; if ( ! requiredSettings . isEmpty ( ) ) { log . warn ( "skipping {}, it requires the following {} mode settings: {}" , aClass . getName ( ) , settings . getMode ( ) , requiredSettings ) ; return false ; } } } | Determines if this class may be used in the current runtime environment . Fathom settings are considered as well as runtime modes . |
5,883 | public static String getGuidAsString ( byte [ ] GUID ) { final StringBuilder res = new StringBuilder ( ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 3 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 2 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 1 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 0 ] & 0xFF ) ) ; res . append ( "-" ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 5 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 4 ] & 0xFF ) ) ; res . append ( "-" ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 7 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 6 ] & 0xFF ) ) ; res . append ( "-" ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 8 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 9 ] & 0xFF ) ) ; res . append ( "-" ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 10 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 11 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 12 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 13 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 14 ] & 0xFF ) ) ; res . append ( AddLeadingZero ( ( int ) GUID [ 15 ] & 0xFF ) ) ; return res . toString ( ) ; } | Gets GUID as string . |
5,884 | public static byte [ ] getGuidAsByteArray ( final String GUID ) { final UUID uuid = UUID . fromString ( GUID ) ; final ByteBuffer buff = ByteBuffer . wrap ( new byte [ 16 ] ) ; buff . putLong ( uuid . getMostSignificantBits ( ) ) ; buff . putLong ( uuid . getLeastSignificantBits ( ) ) ; byte [ ] res = new byte [ ] { buff . get ( 3 ) , buff . get ( 2 ) , buff . get ( 1 ) , buff . get ( 0 ) , buff . get ( 5 ) , buff . get ( 4 ) , buff . get ( 7 ) , buff . get ( 6 ) , buff . get ( 8 ) , buff . get ( 9 ) , buff . get ( 10 ) , buff . get ( 11 ) , buff . get ( 12 ) , buff . get ( 13 ) , buff . get ( 14 ) , buff . get ( 15 ) , } ; return res ; } | Gets GUID as byte array . |
5,885 | public Authorizations setRoles ( Set < Role > roles ) { this . roles . clear ( ) ; this . aggregatePermissions = null ; addRoles ( roles ) ; return this ; } | Sets the roles assigned to the Account . |
5,886 | public Authorizations addRoles ( String ... roles ) { for ( String role : roles ) { addRole ( new Role ( role ) ) ; } return this ; } | Adds roles to the Account Authorizations . |
5,887 | public Collection < Permission > getAggregatePermissions ( ) { if ( aggregatePermissions == null ) { Set < Permission > perms = new LinkedHashSet < > ( ) ; perms . addAll ( permissions ) ; for ( Role role : roles ) { perms . addAll ( role . getPermissions ( ) ) ; } if ( perms . isEmpty ( ) ) { aggregatePermissions = Collections . emptySet ( ) ; } else { aggregatePermissions = Collections . unmodifiableSet ( perms ) ; } } return aggregatePermissions ; } | Gets the collection of permissions including the role permissions and discrete permissions . |
5,888 | protected Method findMethod ( Class < ? > controllerClass , String name ) { Method controllerMethod = null ; for ( Method method : controllerClass . getMethods ( ) ) { if ( method . getName ( ) . equals ( name ) ) { if ( controllerMethod == null ) { controllerMethod = method ; } else { throw new FatalException ( "Found overloaded controller method '{}'. Method names must be unique!" , Util . toString ( method ) ) ; } } } return controllerMethod ; } | Finds the named controller method . |
5,889 | protected Set < String > configureContentTypeSuffixes ( ContentTypeEngines engines ) { if ( null == ClassUtil . getAnnotation ( method , ContentTypeBySuffix . class ) ) { return Collections . emptySet ( ) ; } Set < String > suffixes = new TreeSet < > ( ) ; for ( String suffix : engines . getContentTypeSuffixes ( ) ) { String contentType = engines . getContentTypeEngine ( suffix ) . getContentType ( ) ; if ( declaredProduces . contains ( contentType ) ) { suffixes . add ( suffix ) ; } } return suffixes ; } | Configures the content - type suffixes |
5,890 | protected void configureMethodArgs ( Injector injector ) { Class < ? > [ ] types = method . getParameterTypes ( ) ; extractors = new ArgumentExtractor [ types . length ] ; patterns = new String [ types . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { final Parameter parameter = method . getParameters ( ) [ i ] ; final Class < ? extends Collection > collectionType ; final Class < ? > objectType ; if ( Collection . class . isAssignableFrom ( types [ i ] ) ) { collectionType = ( Class < ? extends Collection > ) types [ i ] ; objectType = getParameterGenericType ( parameter ) ; } else { collectionType = null ; objectType = types [ i ] ; } Class < ? extends ArgumentExtractor > extractorType ; if ( FileItem . class == objectType ) { extractorType = FileItemExtractor . class ; } else { extractorType = ControllerUtil . getArgumentExtractor ( parameter ) ; } extractors [ i ] = injector . getInstance ( extractorType ) ; if ( extractors [ i ] instanceof ConfigurableExtractor < ? > ) { ConfigurableExtractor extractor = ( ConfigurableExtractor ) extractors [ i ] ; Annotation annotation = ClassUtil . getAnnotation ( parameter , extractor . getAnnotationClass ( ) ) ; if ( annotation != null ) { extractor . configure ( annotation ) ; } } if ( extractors [ i ] instanceof SuffixExtractor ) { SuffixExtractor extractor = ( SuffixExtractor ) extractors [ i ] ; extractor . setSuffixes ( contentTypeSuffixes ) ; } if ( collectionType != null ) { if ( extractors [ i ] instanceof CollectionExtractor ) { CollectionExtractor extractor = ( CollectionExtractor ) extractors [ i ] ; extractor . setCollectionType ( collectionType ) ; } else { throw new FatalException ( "Controller method '{}' parameter {} of type '{}' does not specify an argument extractor that supports collections!" , Util . toString ( method ) , i + 1 , Util . toString ( collectionType , objectType ) ) ; } } if ( extractors [ i ] instanceof TypedExtractor ) { TypedExtractor extractor = ( TypedExtractor ) extractors [ i ] ; extractor . setObjectType ( objectType ) ; } if ( extractors [ i ] instanceof NamedExtractor ) { NamedExtractor namedExtractor = ( NamedExtractor ) extractors [ i ] ; if ( Strings . isNullOrEmpty ( namedExtractor . getName ( ) ) ) { if ( parameter . isNamePresent ( ) ) { namedExtractor . setName ( parameter . getName ( ) ) ; } else { log . error ( "Properly annotate your controller methods OR specify the '-parameters' flag for your Java compiler!" ) ; throw new FatalException ( "Controller method '{}' parameter {} of type '{}' does not specify a name!" , Util . toString ( method ) , i + 1 , Util . toString ( collectionType , objectType ) ) ; } } } } } | Configures the controller method arguments . |
5,891 | public void validateMethodArgs ( String uriPattern ) { Set < String > namedParameters = new LinkedHashSet < > ( ) ; for ( ArgumentExtractor extractor : extractors ) { if ( extractor instanceof NamedExtractor ) { NamedExtractor namedExtractor = ( NamedExtractor ) extractor ; namedParameters . add ( namedExtractor . getName ( ) ) ; } } List < String > requiredParameters = getParameterNames ( uriPattern ) ; if ( ! namedParameters . containsAll ( requiredParameters ) ) { throw new FatalException ( "Controller method '{}' declares parameters {} but the URL specification requires {}" , Util . toString ( method ) , namedParameters , requiredParameters ) ; } } | Validate that the parameters specified in the uri pattern are declared in the method signature . |
5,892 | protected void validateConsumes ( Collection < String > fathomContentTypes ) { Set < String > ignoreConsumes = new TreeSet < > ( ) ; ignoreConsumes . add ( Consumes . ALL ) ; ignoreConsumes . add ( Consumes . HTML ) ; ignoreConsumes . add ( Consumes . XHTML ) ; ignoreConsumes . add ( Consumes . FORM ) ; ignoreConsumes . add ( Consumes . MULTIPART ) ; for ( String declaredConsume : declaredConsumes ) { if ( ignoreConsumes . contains ( declaredConsume ) ) { continue ; } String consume = declaredConsume ; int fuzz = consume . indexOf ( '*' ) ; if ( fuzz > - 1 ) { consume = consume . substring ( 0 , fuzz ) ; } if ( ! fathomContentTypes . contains ( consume ) ) { if ( consume . equals ( declaredConsume ) ) { throw new FatalException ( "{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for that type!" , Util . toString ( method ) , Consumes . class . getSimpleName ( ) , declaredConsume ) ; } else { throw new FatalException ( "{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for \"{}\"!" , Util . toString ( method ) , Consumes . class . getSimpleName ( ) , declaredConsume , consume ) ; } } } } | Validates that the declared consumes can actually be processed by Fathom . |
5,893 | protected void validateProduces ( Collection < String > fathomContentTypes ) { Set < String > ignoreProduces = new TreeSet < > ( ) ; ignoreProduces . add ( Produces . TEXT ) ; ignoreProduces . add ( Produces . HTML ) ; ignoreProduces . add ( Produces . XHTML ) ; for ( String produces : declaredProduces ) { if ( ignoreProduces . contains ( produces ) ) { continue ; } if ( ! fathomContentTypes . contains ( produces ) ) { throw new FatalException ( "{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for that type!" , Util . toString ( method ) , Produces . class . getSimpleName ( ) , produces ) ; } } } | Validates that the declared content - types can actually be generated by Fathom . |
5,894 | protected void validateDeclaredReturns ( ) { boolean returnsObject = void . class != method . getReturnType ( ) ; if ( returnsObject ) { for ( Return declaredReturn : declaredReturns ) { if ( declaredReturn . code ( ) >= 200 && declaredReturn . code ( ) < 300 ) { return ; } } throw new FatalException ( "{} returns an object but does not declare a successful @{}(code=200, onResult={}.class)" , Util . toString ( method ) , Return . class . getSimpleName ( ) , method . getReturnType ( ) . getSimpleName ( ) ) ; } } | Validates the declared Returns of the controller method . If the controller method returns an object then it must also declare a successful |
5,895 | public static String getVersion ( ) { String FATHOM_PROPERTIES = "fathom/version.properties" ; String version = null ; URL url = ClassUtil . getResource ( FATHOM_PROPERTIES ) ; Preconditions . checkNotNull ( url , "Failed to find " + FATHOM_PROPERTIES ) ; try ( InputStream stream = url . openStream ( ) ) { Properties prop = new Properties ( ) ; prop . load ( stream ) ; version = prop . getProperty ( "version" ) ; } catch ( IOException e ) { LoggerFactory . getLogger ( Constants . class ) . error ( "Failed to read '{}'" , FATHOM_PROPERTIES , e ) ; } Preconditions . checkNotNull ( version , "The Fathom version is null!" ) ; return version ; } | Returns the running Fathom version . |
5,896 | public void clearCache ( ) { if ( accountCache != null ) { accountCache . invalidateAll ( ) ; } for ( Realm realm : allRealms ) { if ( realm instanceof CachingRealm ) { CachingRealm cachingRealm = ( CachingRealm ) realm ; cachingRealm . clearCache ( ) ; } } } | Clears the SecurityManager account cache and any CachingRealm s cache . MemoryRealms are not affected by this call . |
5,897 | protected Collection < Realm > parseDefinedRealms ( Config config ) { List < Realm > realms = new ArrayList < > ( ) ; if ( config . hasPath ( "realms" ) ) { log . trace ( "Parsing Realm definitions" ) ; for ( Config realmConfig : config . getConfigList ( "realms" ) ) { String realmType = Strings . emptyToNull ( realmConfig . getString ( "type" ) ) ; Preconditions . checkNotNull ( realmType , "Realm 'type' is null!" ) ; if ( ClassUtil . doesClassExist ( realmType ) ) { Class < ? extends Realm > realmClass = ClassUtil . getClass ( realmType ) ; if ( RequireUtil . allowClass ( settings , realmClass ) ) { try { Realm realm = injector . getInstance ( realmClass ) ; realm . setup ( realmConfig ) ; realms . add ( realm ) ; log . debug ( "Created '{}' named '{}'" , realmType , realm . getRealmName ( ) ) ; } catch ( Exception e ) { log . error ( "Failed to create '{}' realm" , realmType , e ) ; } } } else { throw new FathomException ( "Unknown realm type '{}'!" , realmType ) ; } } } return Collections . unmodifiableList ( realms ) ; } | Parse the Realms from the Config object . |
5,898 | public String generateJSON ( Collection < Route > routes ) { Swagger swagger = build ( routes ) ; String json = Json . pretty ( swagger ) ; return json ; } | Generates a Swagger 2 . 0 JSON specification from the collection of routes . |
5,899 | protected boolean canRegister ( Route route , ControllerHandler handler ) { if ( ! METHODS . contains ( route . getRequestMethod ( ) . toUpperCase ( ) ) ) { log . debug ( "Skip {} {}, {} Swagger does not support specified HTTP method" , route . getRequestMethod ( ) , route . getUriPattern ( ) , Util . toString ( handler . getControllerMethod ( ) ) ) ; return false ; } List < String > produces = handler . getDeclaredProduces ( ) ; if ( produces . isEmpty ( ) ) { log . debug ( "Skip {} {}, {} does not declare @Produces" , route . getRequestMethod ( ) , route . getUriPattern ( ) , Util . toString ( handler . getControllerMethod ( ) ) ) ; return false ; } if ( handler . getDeclaredReturns ( ) . isEmpty ( ) ) { log . debug ( "Skip {} {}, {} does not declare expected @Returns" , route . getRequestMethod ( ) , route . getUriPattern ( ) , Util . toString ( handler . getControllerMethod ( ) ) ) ; return false ; } if ( handler . getControllerMethod ( ) . isAnnotationPresent ( Undocumented . class ) || handler . getControllerMethod ( ) . getDeclaringClass ( ) . isAnnotationPresent ( Undocumented . class ) ) { log . debug ( "Skip {} {}, {} is annotated as @Undocumented" , route . getRequestMethod ( ) , route . getUriPattern ( ) , Util . toString ( handler . getControllerMethod ( ) ) ) ; return false ; } if ( ! route . getUriPattern ( ) . startsWith ( relativeSwaggerBasePath ) ) { log . debug ( "Skip {} {}, {} route is not within Swagger basePath '{}'" , route . getRequestMethod ( ) , route . getUriPattern ( ) , Util . toString ( handler . getControllerMethod ( ) ) , relativeSwaggerBasePath ) ; return false ; } return true ; } | Determines if this controller handler can be registered in the Swagger specification . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.