idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
18,400
public static < T > List < T > getOrNullList ( Optional < T > ... optionals ) { return Arrays . stream ( optionals ) . map ( opt -> opt . orElse ( null ) ) . collect ( Collectors . toList ( ) ) ; }
Gets or null list .
18,401
static public Map < String , ColumnMetaData > createMapByLabelOrName ( ResultSetMetaData m ) throws SQLException { Map < String , ColumnMetaData > result = new HashMap < String , ColumnMetaData > ( ) ; for ( int i = 1 ; i <= m . getColumnCount ( ) ; i ++ ) { ColumnMetaData cm = new ColumnMetaData ( m , i ) ; result . put ( cm . getLabelOrName ( ) , cm ) ; } return result ; }
Get all the column meta data and put them into a map keyed by column label or name
18,402
static public List < ColumnMetaData > createList ( ResultSetMetaData m ) throws SQLException { List < ColumnMetaData > result = new ArrayList < ColumnMetaData > ( m . getColumnCount ( ) ) ; for ( int i = 1 ; i <= m . getColumnCount ( ) ; i ++ ) { ColumnMetaData cm = new ColumnMetaData ( m , i ) ; result . add ( cm ) ; } return result ; }
Get all the column meta data and put them into a list in their default order
18,403
private void expandToLimit ( AreaImpl sub , Rectangular gp , Rectangular limit , AreaImpl template , boolean hsep , boolean vsep , short prefDir , short required ) { System . out . println ( " Expand " + sub + " DIR=" + prefDir + " sep=" + hsep + ":" + vsep ) ; if ( getTopology ( ) . getTopologyWidth ( ) > 0 && getTopology ( ) . getTopologyHeight ( ) > 0 && ! sub . isBackgroundSeparated ( ) ) { int dir = prefDir ; int attempts = 0 ; while ( attempts < 4 && ! limitReached ( gp , limit , required ) ) { boolean change = false ; int newx , newy ; switch ( dir ) { case DIR_DOWN : if ( gp . getY2 ( ) < limit . getY2 ( ) && ( ! hsep || ! separatorDown ( sub . getGridPosition ( ) . replaceY ( gp ) ) ) ) { newy = expandVertically ( gp , limit , template , true , hsep ) ; if ( newy > gp . getY2 ( ) ) { gp . setY2 ( newy ) ; change = true ; } } break ; case DIR_RIGHT : if ( gp . getX2 ( ) < limit . getX2 ( ) && ( ! vsep || ! separatorRight ( sub . getGridPosition ( ) . replaceX ( gp ) ) ) ) { newx = expandHorizontally ( gp , limit , template , true , vsep ) ; if ( newx > gp . getX2 ( ) ) { gp . setX2 ( newx ) ; change = true ; } } break ; case DIR_UP : if ( gp . getY1 ( ) > limit . getY1 ( ) && ( ! hsep || ! separatorUp ( sub . getGridPosition ( ) . replaceY ( gp ) ) ) ) { newy = expandVertically ( gp , limit , template , false , hsep ) ; if ( newy < gp . getY1 ( ) ) { gp . setY1 ( newy ) ; change = true ; } } break ; case DIR_LEFT : if ( gp . getX1 ( ) > limit . getX1 ( ) && ( ! vsep || ! separatorLeft ( sub . getGridPosition ( ) . replaceX ( gp ) ) ) ) { newx = expandHorizontally ( gp , limit , template , false , vsep ) ; if ( newx < gp . getX1 ( ) ) { gp . setX1 ( newx ) ; change = true ; } } break ; } if ( ! change ) { dir ++ ; if ( dir >= 4 ) dir = 0 ; attempts ++ ; } else { attempts = 0 ; } } } }
Tries to expand the area in the grid to a greater rectangle in the given limits .
18,404
private boolean limitReached ( Rectangular gp , Rectangular limit , short required ) { switch ( required ) { case REQ_HORIZONTAL : return gp . getX1 ( ) <= limit . getX1 ( ) && gp . getX2 ( ) >= limit . getX2 ( ) ; case REQ_VERTICAL : return gp . getY1 ( ) <= limit . getY1 ( ) && gp . getY2 ( ) >= limit . getY2 ( ) ; case REQ_BOTH : return gp . getX1 ( ) <= limit . getX1 ( ) && gp . getX2 ( ) >= limit . getX2 ( ) && gp . getY1 ( ) <= limit . getY1 ( ) && gp . getY2 ( ) >= limit . getY2 ( ) ; } return false ; }
Checks if the grid bounds have reached a specified limit in the specified direction .
18,405
private int expandHorizontally ( Rectangular gp , Rectangular limit , AreaImpl template , boolean right , boolean sep ) { int na = right ? gp . getX2 ( ) : gp . getX1 ( ) ; int targetx = right ? ( gp . getX2 ( ) + 1 ) : ( gp . getX1 ( ) - 1 ) ; boolean found = false ; int y = gp . getY1 ( ) ; while ( y <= gp . getY2 ( ) ) { AreaImpl cand = ( AreaImpl ) getTopology ( ) . findAreaAt ( targetx , y ) ; if ( cand != null && ! cand . getGridPosition ( ) . intersects ( gp ) ) { found = true ; if ( sep && ( ( right && separatorLeft ( cand . getGridPosition ( ) ) ) || ( ! right && separatorRight ( cand . getGridPosition ( ) ) ) ) ) return na ; else if ( ( matchstyles && ! cand . hasSameStyle ( cand ) ) || cand . getLevel ( ) > maxlevel ) return na ; else { Rectangular cgp = new Rectangular ( cand . getGridPosition ( ) ) ; if ( cgp . getY1 ( ) == gp . getY1 ( ) && cgp . getY2 ( ) == gp . getY2 ( ) ) return targetx ; else if ( cgp . getY1 ( ) < gp . getY1 ( ) || cgp . getY2 ( ) > gp . getY2 ( ) ) return na ; else { if ( right ) { Rectangular newlimit = new Rectangular ( targetx , gp . getY1 ( ) , limit . getX2 ( ) , gp . getY2 ( ) ) ; expandToLimit ( cand , cgp , newlimit , template , false , true , DIR_DOWN , REQ_VERTICAL ) ; if ( cgp . getY1 ( ) == gp . getY1 ( ) && cgp . getY2 ( ) == gp . getY2 ( ) ) return cgp . getX2 ( ) ; } else { Rectangular newlimit = new Rectangular ( limit . getX1 ( ) , gp . getY1 ( ) , targetx , gp . getY2 ( ) ) ; expandToLimit ( cand , cgp , newlimit , template , false , true , DIR_DOWN , REQ_VERTICAL ) ; if ( cgp . getY1 ( ) == gp . getY1 ( ) && cgp . getY2 ( ) == gp . getY2 ( ) ) return cgp . getX1 ( ) ; } } } y += cand . getGridPosition ( ) . getY2 ( ) + 1 ; } else y ++ ; } if ( ! found ) return targetx ; else return na ; }
Try to expand the area horizontally by a smallest step possible
18,406
static protected String extractTemplateUrl ( String viewName ) { int i1 = - 1 ; int i2 = - 1 ; int i3 = - 1 ; int i4 = - 1 ; i1 = viewName . indexOf ( LEFT_BRACKET ) ; if ( i1 != - 1 ) { i2 = viewName . indexOf ( LEFT_BRACKET , i1 + 1 ) ; } i4 = viewName . lastIndexOf ( RIGHT_BRACKET ) ; if ( i4 != - 1 ) { i3 = viewName . lastIndexOf ( RIGHT_BRACKET , i4 - 1 ) ; } if ( ( i1 == - 1 || i4 == - 1 ) || ( i2 * i3 < 0 ) || ( i2 > i3 ) ) { return viewName ; } String url = null ; if ( i2 != - 1 ) { url = viewName . substring ( i1 + 1 , i2 ) ; } else { url = viewName . substring ( i1 + 1 , i4 ) ; } if ( i1 > 0 ) { String prefix = viewName . substring ( 0 , i1 ) ; url = prefix + url ; } if ( i4 < viewName . length ( ) - 1 ) { String postfix = viewName . substring ( i4 + 1 ) ; url = url + postfix ; } return url ; }
Parse the template descriptor to extract template URL
18,407
static protected Map < String , String > extractTemplateParameters ( String viewName ) { int i1 = - 1 ; int i2 = - 1 ; int i3 = - 1 ; int i4 = - 1 ; i1 = viewName . indexOf ( LEFT_BRACKET ) ; if ( i1 != - 1 ) { i2 = viewName . indexOf ( LEFT_BRACKET , i1 + 1 ) ; } i4 = viewName . lastIndexOf ( RIGHT_BRACKET ) ; if ( i4 != - 1 ) { i3 = viewName . lastIndexOf ( RIGHT_BRACKET , i4 - 1 ) ; } if ( ( i1 == - 1 || i4 == - 1 ) || ( i2 == - 1 || i3 == - 1 ) || ( i2 > i3 ) ) { return null ; } Map < String , String > parameters = new HashMap < String , String > ( ) ; if ( i1 > 0 ) { String prefix = viewName . substring ( 0 , i1 ) ; parameters . put ( StdrUtil . URL_PREFIX_PARAMETER , prefix ) ; } if ( i4 < viewName . length ( ) - 1 ) { String postfix = viewName . substring ( i4 + 1 ) ; parameters . put ( StdrUtil . URL_POSTFIX_PARAMETER , postfix ) ; } StrTokenizer tokenizer = new StrTokenizer ( viewName . substring ( i2 + 1 , i3 ) , StrMatcher . charSetMatcher ( ',' , '=' ) , StrMatcher . singleQuoteMatcher ( ) ) ; tokenizer . setEmptyTokenAsNull ( true ) ; while ( tokenizer . hasNext ( ) ) { String name = tokenizer . next ( ) ; String value = null ; try { value = tokenizer . next ( ) ; } catch ( NoSuchElementException e ) { } parameters . put ( name , value ) ; } return parameters ; }
Parse the template descriptor to extract template parameters
18,408
public static String join ( String [ ] strings , String separator ) { StringBuilder sb = new StringBuilder ( ) ; boolean first = true ; for ( String s : strings ) { if ( first ) { first = false ; } else { sb . append ( separator ) ; } sb . append ( s ) ; } return sb . toString ( ) ; }
Join an array of strings with the given separator .
18,409
public static String cap ( String str , int capSize ) { if ( str . length ( ) <= capSize ) { return str ; } if ( capSize <= 3 ) { return str . substring ( 0 , capSize ) ; } return str . substring ( 0 , capSize - 3 ) + "..." ; }
Return a string that is no longer than capSize and pad with ... if returning a substring .
18,410
public MethodVisitor visitMethod ( int access , final String name , String desc , String signature , String [ ] exceptions ) { MethodVisitor mv = cv . visitMethod ( access | Opcodes . ACC_SYNTHETIC , name , desc , signature , exceptions ) ; return new LineNumberingMethodAdapter ( mv , access | Opcodes . ACC_SYNTHETIC , name , desc ) { protected void onMethodEnter ( ) { this . lineNumbers = LineNumberingClassAdapter . this . lineNumbers ; super . onMethodEnter ( ) ; } } ; }
Visits the specified method adding line numbering .
18,411
@ Requires ( { "kind != null" , "pos >= 0" , "id >= 0" , "pos <= id" , "expr != null" , "annotation != null" , "kind.isOld()" , "lineNumber == null || lineNumber >= 1" } ) private void createOldMethods ( ContractKind kind , int pos , int id , String expr , ContractAnnotationModel annotation , Long lineNumber ) { MethodModel helper = ContractCreation . createBlankContractHelper ( kind , annotation , "$" + Integer . toString ( pos ) ) ; helper . setReturnType ( new ClassName ( "java/lang/Object" ) ) ; if ( helper . getKind ( ) == ElementKind . CONTRACT_METHOD ) { ContractMethodModel helperContract = ( ContractMethodModel ) helper ; if ( lineNumber != null ) { helperContract . setLineNumbers ( Collections . singletonList ( lineNumber ) ) ; } String code = expr ; if ( ! annotation . isVirtual ( ) ) { code = ContractCreation . rebaseLocalCalls ( expr , JavaUtils . THAT_VARIABLE , null ) ; } helperContract . addStatement ( "return " + code + ";" ) ; } ContractMethodModel contract = ContractCreation . createBlankContractMethod ( kind , annotation , "$" + id ) ; contract . setReturnType ( new ClassName ( "java/lang/Object" ) ) ; contract . setId ( id ) ; contract . addStatement ( "return " + ContractCreation . getHelperCallCode ( helper , annotation ) + ";" ) ; }
Creates contract and helper methods according to the parameters and adds it to the parent type .
18,412
public void handle ( Buffer buffer ) { if ( buff == null ) { buff = buffer ; } else { buff . appendBuffer ( buffer ) ; } if ( recordSize == - 1 ) { fixedSizeMode ( buff . getInt ( 0 ) + 4 ) ; } handleParsing ( ) ; }
This method is called to provide the parser with data .
18,413
private Type findType ( String typeString ) throws UnknownDashletTypeException { if ( "viewReport" . equalsIgnoreCase ( typeString ) ) { return Type . VIEW ; } else if ( "textContent" . equalsIgnoreCase ( typeString ) ) { return Type . TEXT ; } throw new UnknownDashletTypeException ( typeString ) ; }
Determines the dashlet type from the given type string .
18,414
private View getContentView ( BellaDatiServiceImpl service , JsonNode node ) throws UnsupportedDashletContentException { if ( ! node . hasNonNull ( "canAccessViewReport" ) || ! node . get ( "canAccessViewReport" ) . asBoolean ( ) ) { throw new UnsupportedDashletContentException ( "View not accessible" ) ; } if ( ! node . hasNonNull ( "viewReport" ) ) { throw new UnsupportedDashletContentException ( "Missing view element" ) ; } try { return ViewImpl . buildView ( service , node . get ( "viewReport" ) ) ; } catch ( UnknownViewTypeException e ) { throw new UnsupportedDashletContentException ( e ) ; } }
Reads view content from a dashlet node .
18,415
private String getContentText ( JsonNode node ) throws UnsupportedDashletContentException { if ( node . hasNonNull ( "textContent" ) ) { return node . get ( "textContent" ) . asText ( ) ; } else { throw new UnsupportedDashletContentException ( "Text content missing" ) ; } }
Reads text content from a dashlet node .
18,416
@ InternalFunction ( ) public Boolean unique ( final List < ProxyField > list ) { if ( list == null ) { return Boolean . TRUE ; } int size = list . size ( ) ; int index = 0 ; for ( ProxyField proxyField : list ) { for ( int i = index + 1 ; i < size ; i ++ ) { if ( list . get ( i ) . getValue ( ) . equals ( proxyField . getValue ( ) ) ) { return Boolean . FALSE ; } } } return Boolean . TRUE ; }
Every item in the list must be unique
18,417
@ InternalFunction ( ) public Boolean match ( final List < ProxyField > list , final List < ProxyField > list2 ) { if ( list == null ) { return Boolean . TRUE ; } for ( ProxyField proxyField : list ) { boolean found = false ; for ( ProxyField proxyField2 : list2 ) { if ( proxyField . getValue ( ) . equals ( proxyField2 . getValue ( ) ) ) { found = true ; break ; } } if ( ! found ) { return Boolean . FALSE ; } } return Boolean . TRUE ; }
Everything in the first list must be in the second list too But not necessarily the reverse .
18,418
public static String toHex ( byte b ) { StringBuilder sb = new StringBuilder ( ) ; appendByteAsHex ( sb , b ) ; return sb . toString ( ) ; }
Encodes a single byte to hex symbols .
18,419
public static byte [ ] toBytes ( String hexString ) { if ( hexString == null || hexString . length ( ) % 2 != 0 ) { throw new RuntimeException ( "Input string must contain an even number of characters" ) ; } char [ ] hex = hexString . toCharArray ( ) ; int length = hex . length / 2 ; byte [ ] raw = new byte [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { int high = Character . digit ( hex [ i * 2 ] , 16 ) ; int low = Character . digit ( hex [ i * 2 + 1 ] , 16 ) ; int value = ( high << 4 ) | low ; if ( value > 127 ) value -= 256 ; raw [ i ] = ( byte ) value ; } return raw ; }
Get the byte representation of an ASCII - HEX string .
18,420
public static < T , C extends Collection < T > > void ifNotNullOrEmptyConsume ( C collection , Consumer < C > consumer ) { JMOptional . getOptional ( collection ) . ifPresent ( consumer ) ; }
If not null or empty consume .
18,421
public static < E > List < E > buildMergedList ( Collection < E > collection1 , Collection < E > collection2 ) { List < E > mergedList = new ArrayList < > ( collection1 ) ; mergedList . addAll ( collection2 ) ; return mergedList ; }
Build merged list list .
18,422
public static List < String > buildListWithDelimiter ( String stringWithDelimiter , String delimiter ) { return buildTokenStream ( stringWithDelimiter , delimiter ) . collect ( toList ( ) ) ; }
Build list with delimiter list .
18,423
public static < E > List < List < E > > splitIntoSubList ( List < E > list , int targetSize ) { int listSize = list . size ( ) ; return JMStream . numberRange ( 0 , listSize , targetSize ) . mapToObj ( index -> list . subList ( index , Math . min ( index + targetSize , listSize ) ) ) . collect ( toList ( ) ) ; }
Split into sub list list .
18,424
public static < T > List < T > getReversed ( Collection < T > collection ) { List < T > reversedList = new ArrayList < > ( collection ) ; Collections . reverse ( reversedList ) ; return reversedList ; }
Gets reversed .
18,425
public static < T , R > List < R > transformList ( Collection < T > collection , Function < T , R > transformFunction ) { return collection . stream ( ) . map ( transformFunction ) . collect ( toList ( ) ) ; }
Transform list list .
18,426
public static < T > T addAndGet ( Collection < T > collection , T item ) { collection . add ( item ) ; return item ; }
Add and get t .
18,427
public static < T , R > List < R > buildNewList ( Collection < T > collection , Function < T , R > transformFunction ) { return collection . stream ( ) . map ( transformFunction ) . collect ( Collectors . toList ( ) ) ; }
Build new list list .
18,428
private void initCacheSyncTask ( ) { int delay = getServiceDirectoryConfig ( ) . getInt ( SD_API_CACHE_SYNC_DELAY_PROPERTY , SD_API_CACHE_SYNC_DELAY_DEFAULT ) ; int interval = getServiceDirectoryConfig ( ) . getInt ( SD_API_CACHE_SYNC_INTERVAL_PROPERTY , SD_API_CACHE_SYNC_INTERVAL_DEFAULT ) ; syncService . scheduleWithFixedDelay ( new CacheSyncTask ( ) , delay , interval , TimeUnit . SECONDS ) ; }
initialization of the CacheSyncTask
18,429
private List < ModelService > getAllServicesForSync ( ) { List < ModelService > allServices = new ArrayList < ModelService > ( ) ; allServices . addAll ( this . cache . values ( ) ) ; List < ModelService > syncServices = new ArrayList < ModelService > ( ) ; for ( ModelService service : allServices ) { ModelService syncService = new ModelService ( service . getName ( ) , service . getId ( ) , service . getCreateTime ( ) ) ; Date modifiedTime = service . getModifiedTime ( ) ; if ( modifiedTime != null ) { syncService . setModifiedTime ( modifiedTime ) ; } syncServices . add ( syncService ) ; } return syncServices ; }
Get the ModelService List for cache sync .
18,430
private List < ModelMetadataKey > getAllMetadataKeysForSync ( ) { List < ModelMetadataKey > allKeys = new ArrayList < ModelMetadataKey > ( ) ; allKeys . addAll ( this . metaKeyCache . values ( ) ) ; List < ModelMetadataKey > syncKeys = new ArrayList < ModelMetadataKey > ( ) ; for ( ModelMetadataKey service : allKeys ) { ModelMetadataKey syncKey = new ModelMetadataKey ( service . getName ( ) , service . getId ( ) , service . getModifiedTime ( ) , service . getCreateTime ( ) ) ; syncKeys . add ( syncKey ) ; } return syncKeys ; }
Get the ModelMetadataKey List for cache sync .
18,431
private Map < String , OperationResult < ModelMetadataKey > > getChangedMetadataKeys ( Map < String , ModelMetadataKey > keyMap ) { return this . getDirectoryServiceClient ( ) . getChangedMetadataKeys ( keyMap ) ; }
Get the changed list for the MetadataKey from the server .
18,432
private Map < String , OperationResult < ModelService > > getChangedServices ( Map < String , ModelService > serviceMap ) { return this . getDirectoryServiceClient ( ) . getChangedServices ( serviceMap ) ; }
Get the changed Services list from the server .
18,433
public boolean acceptTaggedScenario ( final Set < String > tags ) { if ( acceptAll || ( acceptedTags . isEmpty ( ) && excludedTags . isEmpty ( ) ) ) { return true ; } else if ( acceptedTags . size ( ) > 0 && ( tags == null || tags . isEmpty ( ) ) ) { return false ; } else if ( containsAny ( tags , excludedTags ) ) { return false ; } else { return tags == null || tags . containsAll ( acceptedTags ) ; } }
passed a set of tags works out if we should run this feature or not
18,434
public static ListBoxModel getParsersAsListModel ( ) { ListBoxModel items = new ListBoxModel ( ) ; for ( ParserDescription parser : getAvailableParsers ( ) ) { items . add ( parser . getName ( ) , parser . getGroup ( ) ) ; } return items ; }
Returns the available parsers as a list model .
18,435
public static List < ParserDescription > getAvailableParsers ( ) { Set < String > groups = Sets . newHashSet ( ) ; for ( AbstractWarningsParser parser : getAllParsers ( ) ) { groups . add ( parser . getGroup ( ) ) ; } List < ParserDescription > sorted = Lists . newArrayList ( ) ; for ( String group : groups ) { sorted . add ( new ParserDescription ( group , getParser ( group ) . getParserName ( ) ) ) ; } Collections . sort ( sorted ) ; return sorted ; }
Returns all available parsers groups sorted alphabetically .
18,436
public static AbstractWarningsParser getParser ( final String group ) { if ( StringUtils . isEmpty ( group ) ) { return new NullWarnigsParser ( "NULL" ) ; } List < AbstractWarningsParser > parsers = ParserRegistry . getParsers ( group ) ; if ( parsers . isEmpty ( ) ) { return new NullWarnigsParser ( group ) ; } else { return parsers . get ( 0 ) ; } }
Returns a parser for the specified group . If there is no such parser then a null object is returned .
18,437
public static int getUrl ( final String group ) { List < AbstractWarningsParser > allParsers = getAllParsers ( ) ; for ( int number = 0 ; number < allParsers . size ( ) ; number ++ ) { if ( allParsers . get ( number ) . isInGroup ( group ) ) { return number ; } } throw new NoSuchElementException ( "No parser found for group: " + group ) ; }
Returns the parser ID which could be used as a URL .
18,438
public static List < AbstractWarningsParser > getParsers ( final Collection < String > parserGroups ) { List < AbstractWarningsParser > actualParsers = new ArrayList < AbstractWarningsParser > ( ) ; for ( String name : parserGroups ) { for ( AbstractWarningsParser warningsParser : getAllParsers ( ) ) { if ( warningsParser . isInGroup ( name ) ) { actualParsers . add ( warningsParser ) ; } } } return actualParsers ; }
Returns a list of parsers that match the specified names . Note that the mapping of names to parsers is one to many .
18,439
private static List < AbstractWarningsParser > getAllParsers ( ) { List < AbstractWarningsParser > parsers = Lists . newArrayList ( ) ; parsers . add ( new MsBuildParser ( Messages . _Warnings_PCLint_ParserName ( ) , Messages . _Warnings_PCLint_LinkName ( ) , Messages . _Warnings_PCLint_TrendName ( ) ) ) ; if ( PluginDescriptor . isPluginInstalled ( "violations" ) ) { ViolationsRegistry . addParsers ( parsers ) ; } Iterable < GroovyParser > parserDescriptions = getDynamicParserDescriptions ( ) ; parsers . addAll ( getDynamicParsers ( parserDescriptions ) ) ; parsers . addAll ( all ( ) ) ; return ImmutableList . copyOf ( parsers ) ; }
Returns all available parsers . Parsers are automatically detected using the extension point mechanism .
18,440
private Set < FileAnnotation > applyExcludeFilter ( final Set < FileAnnotation > allAnnotations ) { Set < FileAnnotation > includedAnnotations ; if ( includePatterns . isEmpty ( ) ) { includedAnnotations = allAnnotations ; } else { includedAnnotations = Sets . newHashSet ( ) ; for ( FileAnnotation annotation : allAnnotations ) { for ( Pattern include : includePatterns ) { if ( include . matcher ( annotation . getFileName ( ) ) . matches ( ) ) { includedAnnotations . add ( annotation ) ; } } } } if ( excludePatterns . isEmpty ( ) ) { return includedAnnotations ; } else { Set < FileAnnotation > excludedAnnotations = Sets . newHashSet ( includedAnnotations ) ; for ( FileAnnotation annotation : includedAnnotations ) { for ( Pattern exclude : excludePatterns ) { if ( exclude . matcher ( annotation . getFileName ( ) ) . matches ( ) ) { excludedAnnotations . remove ( annotation ) ; } } } return excludedAnnotations ; } }
Applies the exclude filter to the found annotations .
18,441
@ edu . umd . cs . findbugs . annotations . SuppressWarnings ( "OBL" ) protected Reader createReader ( final File file ) throws FileNotFoundException { return createReader ( new FileInputStream ( file ) ) ; }
Creates a reader from the specified file . Uses the defined character set to read the content of the input stream .
18,442
public static com . simiacryptus . util . io . HtmlNotebookOutput create ( final File parentDirectory ) throws FileNotFoundException { final FileOutputStream out = new FileOutputStream ( new File ( parentDirectory , "index.html" ) ) ; return new com . simiacryptus . util . io . HtmlNotebookOutput ( parentDirectory , out ) { public void close ( ) throws IOException { out . close ( ) ; } } ; }
Create html notebook output .
18,443
public com . simiacryptus . util . io . HtmlNotebookOutput setSourceRoot ( final String sourceRoot ) { this . sourceRoot = sourceRoot ; return this ; }
Sets source root .
18,444
public static Configuration createConfiguration ( File configurationDirectory ) { Configuration hadoopConfiguration = new Configuration ( ) ; hadoopConfiguration . addResource ( new Path ( new File ( configurationDirectory , "etc/hadoop/core-site.xml" ) . toString ( ) ) ) ; hadoopConfiguration . addResource ( new Path ( new File ( configurationDirectory , "etc/hadoop/hdfs-site.xml" ) . toString ( ) ) ) ; hadoopConfiguration . addResource ( new Path ( new File ( configurationDirectory , "etc/hadoop/mapred-site.xml" ) . toString ( ) ) ) ; return hadoopConfiguration ; }
This method provides the default configuration for Hadoop client . The configuration for the client is looked up in the provided directory . The Hadoop etc directory is expected there .
18,445
public static FileSystem connect ( Properties configuration ) throws IOException { String host = configuration . getProperty ( "transformator.dfs.host" ) ; String port = configuration . getProperty ( "transformator.dfs.port" ) ; String hdfsUrl = "hdfs://" + host + ":" + port ; Configuration conf = new Configuration ( ) ; conf . set ( "fs.defaultFS" , hdfsUrl ) ; return FileSystem . get ( conf ) ; }
This method connects to Hadoop . The configuration for the client is looked up in the provided directory . The Hadoop etc directory is expected there .
18,446
private void generateHierarchyAttributeInterfaces ( Map < String , List < XsdAttribute > > createdAttributes , ElementHierarchyItem hierarchyInterface , String apiName ) { String interfaceName = hierarchyInterface . getInterfaceName ( ) ; List < String > extendedInterfaceList = hierarchyInterface . getInterfaces ( ) ; String [ ] extendedInterfaces = listToArray ( extendedInterfaceList , ELEMENT ) ; ClassWriter classWriter = generateClass ( interfaceName , JAVA_OBJECT , extendedInterfaces , getInterfaceSignature ( extendedInterfaces , apiName ) , ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE , apiName ) ; hierarchyInterface . getAttributes ( ) . forEach ( attribute -> generateMethodsAndCreateAttribute ( createdAttributes , classWriter , attribute , elementTypeDesc , interfaceName , apiName ) ) ; writeClassToFile ( interfaceName , classWriter , apiName ) ; }
Generates all the hierarchy interfaces .
18,447
private void generateAttributesGroupInterface ( Map < String , List < XsdAttribute > > createdAttributes , String attributeGroupName , AttributeHierarchyItem attributeHierarchyItem , String apiName ) { String baseClassNameCamelCase = firstToUpper ( attributeGroupName ) ; String [ ] interfaces = getAttributeGroupObjectInterfaces ( attributeHierarchyItem . getParentsName ( ) ) ; StringBuilder signature = getAttributeGroupSignature ( interfaces , apiName ) ; ClassWriter interfaceWriter = generateClass ( baseClassNameCamelCase , JAVA_OBJECT , interfaces , signature . toString ( ) , ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE , apiName ) ; attributeHierarchyItem . getOwnElements ( ) . forEach ( elementAttribute -> { if ( createdAttributes . keySet ( ) . stream ( ) . anyMatch ( createdAttributeName -> createdAttributeName . equalsIgnoreCase ( elementAttribute . getName ( ) ) ) ) { elementAttribute . setName ( elementAttribute . getName ( ) + ATTRIBUTE_CASE_SENSITIVE_DIFFERENCE ) ; } generateMethodsAndCreateAttribute ( createdAttributes , interfaceWriter , elementAttribute , elementTypeDesc , baseClassNameCamelCase , apiName ) ; } ) ; writeClassToFile ( baseClassNameCamelCase , interfaceWriter , apiName ) ; }
Generates an attribute group interface with all the required methods . It uses the information gathered about in attributeGroupInterfaces .
18,448
private Collection < String > getTypeAttributeGroups ( XsdComplexType complexType , Stream < XsdAttributeGroup > extensionAttributeGroups ) { Stream < XsdAttributeGroup > attributeGroups = complexType . getXsdAttributes ( ) . filter ( attribute -> attribute . getParent ( ) instanceof XsdAttributeGroup ) . map ( attribute -> ( XsdAttributeGroup ) attribute . getParent ( ) ) . distinct ( ) ; attributeGroups = Stream . concat ( attributeGroups , extensionAttributeGroups ) ; attributeGroups = Stream . concat ( attributeGroups , complexType . getXsdAttributeGroup ( ) ) ; List < XsdAttributeGroup > attributeGroupList = attributeGroups . distinct ( ) . collect ( Collectors . toList ( ) ) ; attributeGroupList . forEach ( this :: addAttributeGroup ) ; if ( ! attributeGroupList . isEmpty ( ) ) { return getBaseAttributeGroupInterface ( complexType . getXsdAttributeGroup ( ) . collect ( Collectors . toList ( ) ) ) ; } return Collections . emptyList ( ) ; }
Obtains the attribute groups of a given element that are present in its type attribute .
18,449
private List < String > getBaseAttributeGroupInterface ( List < XsdAttributeGroup > attributeGroups ) { List < XsdAttributeGroup > parents = new ArrayList < > ( ) ; attributeGroups . forEach ( attributeGroup -> { XsdAbstractElement parent = attributeGroup . getParent ( ) ; if ( parent instanceof XsdAttributeGroup && ! parents . contains ( parent ) ) { parents . add ( ( XsdAttributeGroup ) parent ) ; } } ) ; if ( attributeGroups . size ( ) == 1 || parents . isEmpty ( ) ) { return attributeGroups . stream ( ) . map ( attributeGroup -> firstToUpper ( attributeGroup . getName ( ) ) ) . collect ( Collectors . toList ( ) ) ; } return getBaseAttributeGroupInterface ( parents ) ; }
Recursively iterates order to define an hierarchy on the attribute group interfaces .
18,450
private void addAttributeGroup ( XsdAttributeGroup attributeGroup ) { String interfaceName = firstToUpper ( attributeGroup . getName ( ) ) ; if ( ! attributeGroupInterfaces . containsKey ( interfaceName ) ) { List < XsdAttribute > ownElements = attributeGroup . getXsdElements ( ) . filter ( attribute -> attribute . getParent ( ) . equals ( attributeGroup ) ) . map ( attribute -> ( XsdAttribute ) attribute ) . collect ( Collectors . toList ( ) ) ; List < String > parentNames = attributeGroup . getAttributeGroups ( ) . stream ( ) . map ( XsdNamedElements :: getName ) . collect ( Collectors . toList ( ) ) ; AttributeHierarchyItem attributeHierarchyItemItem = new AttributeHierarchyItem ( parentNames , ownElements ) ; attributeGroupInterfaces . put ( interfaceName , attributeHierarchyItemItem ) ; attributeGroup . getAttributeGroups ( ) . forEach ( this :: addAttributeGroup ) ; } }
Adds information about the attribute group interface to the attributeGroupInterfaces variable .
18,451
private StringBuilder getAttributeGroupSignature ( String [ ] interfaces , String apiName ) { StringBuilder signature = new StringBuilder ( "<T::L" + elementType + "<TT;TZ;>;Z::" + elementTypeDesc + ">" + JAVA_OBJECT_DESC ) ; if ( interfaces . length == 0 ) { signature . append ( "L" ) . append ( elementType ) . append ( "<TT;TZ;>;" ) ; } else { for ( String anInterface : interfaces ) { signature . append ( "L" ) . append ( getFullClassTypeName ( anInterface , apiName ) ) . append ( "<TT;TZ;>;" ) ; } } return signature ; }
Obtains the signature for the attribute group interfaces based on the implemented interfaces .
18,452
private String [ ] getAttributeGroupObjectInterfaces ( List < String > parentsName ) { return listToArray ( parentsName . stream ( ) . map ( XsdAsmUtils :: firstToUpper ) . collect ( Collectors . toList ( ) ) , CUSTOM_ATTRIBUTE_GROUP ) ; }
Obtains an array with the names of the interfaces implemented by a attribute group interface with the given parents as in interfaces that will be extended .
18,453
String [ ] getInterfaces ( XsdElement element , String apiName ) { String [ ] attributeGroupInterfacesArr = getAttributeGroupInterfaces ( element ) ; String [ ] elementGroupInterfacesArr = getElementInterfaces ( element , apiName ) ; String [ ] hierarchyInterfacesArr = getHierarchyInterfaces ( element , apiName ) ; return ArrayUtils . addAll ( ArrayUtils . addAll ( attributeGroupInterfacesArr , elementGroupInterfacesArr ) , hierarchyInterfacesArr ) ; }
Obtains all the interfaces that a given element will implement .
18,454
private void sequenceMethod ( Stream < XsdAbstractElement > xsdElements , String className , int interfaceIndex , String apiName , String groupName ) { pendingSequenceMethods . put ( className , classWriter -> createSequence ( classWriter , xsdElements , className , interfaceIndex , apiName , groupName ) ) ; }
Postpones the sequence method creation due to solution design .
18,455
private void createSequence ( ClassWriter classWriter , Stream < XsdAbstractElement > xsdElements , String className , int interfaceIndex , String apiName , String groupName ) { SequenceMethodInfo sequenceInfo = getSequenceInfo ( xsdElements , className , interfaceIndex , 0 , apiName , groupName ) ; List < XsdAbstractElement > sequenceList = new ArrayList < > ( ) ; List < String > sequenceNames = new ArrayList < > ( ) ; sequenceList . addAll ( sequenceInfo . getSequenceElements ( ) ) ; sequenceNames . add ( className ) ; sequenceNames . addAll ( sequenceInfo . getSequenceElementNames ( ) ) ; for ( int i = 0 ; i < sequenceNames . size ( ) ; i ++ ) { boolean isLast = i == sequenceNames . size ( ) - 1 ; boolean willPointToLast = i == sequenceNames . size ( ) - 2 ; String typeName = getNextTypeName ( className , groupName , firstToLower ( getCleanName ( sequenceNames . get ( i ) ) ) , isLast ) ; if ( isLast ) { if ( ! typeName . equals ( className ) ) { createdElements . put ( getCleanName ( typeName ) , null ) ; writeClassToFile ( typeName , generateInnerSequenceClass ( typeName , className , apiName ) , apiName ) ; } break ; } String nextTypeName = getNextTypeName ( className , groupName , firstToLower ( getCleanName ( sequenceNames . get ( i + 1 ) ) ) , willPointToLast ) ; createSequenceClasses ( sequenceList . get ( i ) , classWriter , className , typeName , nextTypeName , apiName , i == 0 ) ; ++ interfaceIndex ; } }
Obtains sequence information and creates all the required classes and methods .
18,456
private void createSequenceClasses ( XsdAbstractElement sequenceElement , ClassWriter classWriter , String className , String typeName , String nextTypeName , String apiName , boolean isFirst ) { List < XsdElement > elements = null ; if ( sequenceElement instanceof XsdElement ) { elements = Collections . singletonList ( ( XsdElement ) sequenceElement ) ; } if ( sequenceElement instanceof XsdGroup || sequenceElement instanceof XsdChoice || sequenceElement instanceof XsdAll ) { elements = getAllElementsRecursively ( sequenceElement ) ; } if ( elements != null ) { if ( isFirst ) { createFirstSequenceInterface ( classWriter , className , nextTypeName , apiName , elements ) ; } else { createElementsForSequence ( className , typeName , nextTypeName , apiName , elements ) ; } } }
Creates classes and methods required to implement the sequence .
18,457
private void createFirstSequenceInterface ( ClassWriter classWriter , String className , String nextTypeName , String apiName , List < XsdElement > elements ) { elements . forEach ( element -> generateSequenceMethod ( classWriter , className , getJavaType ( element . getType ( ) ) , getCleanName ( element . getName ( ) ) , className , nextTypeName , apiName ) ) ; elements . forEach ( element -> createElement ( element , apiName ) ) ; }
Adds a method to the element which contains the sequence .
18,458
private String getNextTypeName ( String className , String groupName , String sequenceName , boolean isLast ) { if ( isLast ) return groupName == null ? className + "Complete" : className ; else return className + firstToUpper ( sequenceName ) ; }
Obtains the name of the next type of the sequence .
18,459
private void createElementsForSequence ( String className , String typeName , String nextTypeName , String apiName , List < XsdElement > sequenceElements ) { ClassWriter classWriter = generateInnerSequenceClass ( typeName , className , apiName ) ; sequenceElements . forEach ( sequenceElement -> generateSequenceMethod ( classWriter , className , getJavaType ( sequenceElement . getType ( ) ) , getCleanName ( sequenceElement . getName ( ) ) , typeName , nextTypeName , apiName ) ) ; sequenceElements . forEach ( element -> createElement ( element , apiName ) ) ; addToCreateElements ( typeName ) ; writeClassToFile ( typeName , classWriter , apiName ) ; }
Creates the inner classes that are used to support the sequence behaviour and the respective sequence methods .
18,460
private ClassWriter generateInnerSequenceClass ( String typeName , String className , String apiName ) { ClassWriter classWriter = generateClass ( typeName , JAVA_OBJECT , new String [ ] { CUSTOM_ATTRIBUTE_GROUP } , getClassSignature ( new String [ ] { CUSTOM_ATTRIBUTE_GROUP } , typeName , apiName ) , ACC_PUBLIC + ACC_SUPER , apiName ) ; generateClassMethods ( classWriter , typeName , className , apiName , false ) ; return classWriter ; }
Creates the inner classes that are used to support the sequence behaviour .
18,461
private SequenceMethodInfo getSequenceInfo ( Stream < XsdAbstractElement > xsdElements , String className , int interfaceIndex , int unnamedIndex , String apiName , String groupName ) { List < XsdAbstractElement > xsdElementsList = xsdElements . collect ( Collectors . toList ( ) ) ; SequenceMethodInfo sequenceMethodInfo = new SequenceMethodInfo ( xsdElementsList . stream ( ) . filter ( element -> ! ( element instanceof XsdSequence ) ) . collect ( Collectors . toList ( ) ) , interfaceIndex , unnamedIndex ) ; for ( XsdAbstractElement element : xsdElementsList ) { if ( element instanceof XsdElement ) { String elementName = ( ( XsdElement ) element ) . getName ( ) ; if ( elementName != null ) { sequenceMethodInfo . addElementName ( elementName ) ; } else { sequenceMethodInfo . addElementName ( className + "SequenceUnnamed" + sequenceMethodInfo . getUnnamedIndex ( ) ) ; sequenceMethodInfo . incrementUnnamedIndex ( ) ; } } else { if ( element instanceof XsdSequence ) { sequenceMethodInfo . receiveChildSequence ( getSequenceInfo ( element . getXsdElements ( ) , className , interfaceIndex , unnamedIndex , apiName , groupName ) ) ; } else { InterfaceInfo interfaceInfo = iterativeCreation ( element , className , interfaceIndex + 1 , apiName , groupName ) . get ( 0 ) ; sequenceMethodInfo . setInterfaceIndex ( interfaceInfo . getInterfaceIndex ( ) ) ; sequenceMethodInfo . addElementName ( interfaceInfo . getInterfaceName ( ) ) ; } } } return sequenceMethodInfo ; }
Obtains information about all the members that make up the sequence .
18,462
@ SuppressWarnings ( "MismatchedQueryAndUpdateOfCollection" ) private List < InterfaceInfo > iterativeCreation ( XsdAbstractElement element , String className , int interfaceIndex , String apiName , String groupName ) { List < XsdChoice > choiceElements = new ArrayList < > ( ) ; List < XsdGroup > groupElements = new ArrayList < > ( ) ; List < XsdAll > allElements = new ArrayList < > ( ) ; List < XsdSequence > sequenceElements = new ArrayList < > ( ) ; List < XsdElement > directElements = new ArrayList < > ( ) ; Map < Class , List > mapper = new HashMap < > ( ) ; mapper . put ( XsdGroup . class , groupElements ) ; mapper . put ( XsdChoice . class , choiceElements ) ; mapper . put ( XsdAll . class , allElements ) ; mapper . put ( XsdSequence . class , sequenceElements ) ; mapper . put ( XsdElement . class , directElements ) ; element . getXsdElements ( ) . forEach ( elementChild -> mapper . get ( elementChild . getClass ( ) ) . add ( elementChild ) ) ; List < InterfaceInfo > interfaceInfoList = new ArrayList < > ( ) ; if ( element instanceof XsdGroup ) { XsdChoice choiceElement = choiceElements . size ( ) == 1 ? choiceElements . get ( 0 ) : null ; XsdSequence sequenceElement = sequenceElements . size ( ) == 1 ? sequenceElements . get ( 0 ) : null ; XsdAll allElement = allElements . size ( ) == 1 ? allElements . get ( 0 ) : null ; interfaceInfoList . add ( groupMethod ( ( ( XsdGroup ) element ) . getName ( ) , choiceElement , allElement , sequenceElement , className , interfaceIndex , apiName ) ) ; } if ( element instanceof XsdAll ) { interfaceInfoList . add ( allMethod ( directElements , className , interfaceIndex , apiName , groupName ) ) ; } if ( element instanceof XsdChoice ) { interfaceInfoList = choiceMethod ( groupElements , directElements , className , interfaceIndex , apiName , groupName ) ; } if ( element instanceof XsdSequence ) { sequenceMethod ( element . getXsdElements ( ) , className , interfaceIndex , apiName , groupName ) ; } interfaceInfoList . forEach ( interfaceInfo -> createdInterfaces . put ( interfaceInfo . getInterfaceName ( ) , interfaceInfo ) ) ; return interfaceInfoList ; }
This method functions as an iterative process for interface creation .
18,463
void checkForSequenceMethod ( ClassWriter classWriter , String className ) { Consumer < ClassWriter > sequenceMethodCreator = pendingSequenceMethods . get ( className ) ; if ( sequenceMethodCreator != null ) { sequenceMethodCreator . accept ( classWriter ) ; } }
Verifies if there is any postponed sequence method creation in pendingSequenceMethods and performs the method if it exists .
18,464
protected ClientHttpRequestInterceptor buildAddHeadersRequestInterceptor ( String header1 , String value1 , String header2 , String value2 , String header3 , String value3 , String header4 , String value4 ) { return new AddHeadersRequestInterceptor ( new String [ ] { header1 , header2 , header3 , header4 } , new String [ ] { value1 , value2 , value3 , value4 } ) ; }
Build a ClientHttpRequestInterceptor that adds three request headers
18,465
protected ClientHttpRequestInterceptor buildAddBasicAuthHeaderRequestInterceptor ( String user , String password ) { return new AddHeaderRequestInterceptor ( HEADER_AUTHORIZATION , buildBasicAuthValue ( user , password ) ) ; }
Build a ClientHttpRequestInterceptor that adds BasicAuth header
18,466
protected HttpHeaders copy ( HttpHeaders headers ) { HttpHeaders newHeaders = new HttpHeaders ( ) ; newHeaders . putAll ( headers ) ; return newHeaders ; }
Make a writable copy of an existing HttpHeaders
18,467
public void startElement ( String namespaceURI , String localeName , String tagName , Attributes attrs ) throws SAXException { Command . printAttrs ( tabCount , tagName , attrs ) ; Command cmd = tagName . equals ( "java" ) ? new Command ( decoder , tagName , Command . parseAttrs ( tagName , attrs ) ) : new Command ( tagName , Command . parseAttrs ( tagName , attrs ) ) ; stack . push ( cmd ) ; ++ tabCount ; }
create new command and put it on stack
18,468
public void characters ( char [ ] text , int start , int length ) throws SAXException { if ( length > 0 ) { String data = String . valueOf ( text , start , length ) . replace ( '\n' , ' ' ) . replace ( '\t' , ' ' ) . trim ( ) ; if ( data . length ( ) > 0 ) { Command . prn ( tabCount , tabCount + ">setting data=" + data + "<EOL>" ) ; Command cmd = stack . peek ( ) ; cmd . setData ( data ) ; } } }
add data to command
18,469
public void endElement ( String namespaceURI , String localeName , String tagName ) throws SAXException { Command cmd = stack . pop ( ) ; if ( ! stack . isEmpty ( ) ) { Command ctx = stack . peek ( ) ; ctx . addChild ( cmd ) ; } if ( stack . size ( ) == 1 && cmd . isExecutable ( ) ) { commands . add ( cmd ) ; } if ( cmd . hasAttr ( "id" ) ) { references . put ( cmd . getAttr ( "id" ) , cmd ) ; } try { cmd . exec ( references ) ; } catch ( Exception e ) { SAXException e2 = new SAXException ( e . getMessage ( ) ) ; e2 . initCause ( e ) ; throw e2 ; } if ( -- tabCount < 0 ) { tabCount = 0 ; } Command . prn ( tabCount , tabCount + ">...<" + tagName + "> end" ) ; }
pop command from stack and put it to one of collections
18,470
public void endDocument ( ) throws SAXException { for ( int i = 0 ; i < commands . size ( ) ; ++ i ) { Command cmd = commands . elementAt ( i ) ; try { cmd . backtrack ( references ) ; } catch ( Exception e ) { throw new SAXException ( Messages . getString ( "beans.0B" ) ) ; } } for ( int i = 0 ; i < commands . size ( ) ; ++ i ) { Command cmd = commands . elementAt ( i ) ; result . add ( cmd . getResultValue ( ) ) ; } }
iterate over deferred commands and execute them again
18,471
public static void join ( StringBuilder buf , Iterable < ? > values , String separator ) { for ( Iterator < ? > i = values . iterator ( ) ; i . hasNext ( ) ; ) { buf . append ( i . next ( ) ) ; if ( i . hasNext ( ) ) { buf . append ( separator ) ; } } }
append values to buf separated with the specified separator
18,472
public Object deserialize ( byte [ ] input , TypeReference < ? > typeRef ) throws JsonParseException , JsonMappingException , IOException { return mapper . readValue ( input , typeRef ) ; }
Deserialize from byte array it always used in the generic type object .
18,473
public static String escape ( String str ) { StringBuffer result = new StringBuffer ( ) ; StringTokenizer tokenizer = new StringTokenizer ( str , DELIMITER , true ) ; while ( tokenizer . hasMoreTokens ( ) ) { String currentToken = tokenizer . nextToken ( ) ; if ( ESCAPED_CHARS . containsKey ( currentToken ) ) { result . append ( ESCAPED_CHARS . get ( currentToken ) ) ; } else { result . append ( currentToken ) ; } } return result . toString ( ) ; }
Encoder special characters that may occur in a HTML so it can be displayed safely .
18,474
public com . simiacryptus . util . MonitoredObject addConst ( final String key , final Object item ) { items . put ( key , item ) ; return this ; }
Add const monitored object .
18,475
public com . simiacryptus . util . MonitoredObject addObj ( final String key , final MonitoredItem item ) { items . put ( key , item ) ; return this ; }
Add obj monitored object .
18,476
public com . simiacryptus . util . MonitoredObject clearConstants ( ) { final HashSet < String > keys = new HashSet < > ( items . keySet ( ) ) ; for ( final String k : keys ) { final Object v = items . get ( k ) ; if ( v instanceof com . simiacryptus . util . MonitoredObject ) { ( ( com . simiacryptus . util . MonitoredObject ) v ) . clearConstants ( ) ; } else if ( ! ( v instanceof Supplier ) && ! ( v instanceof MonitoredItem ) ) { items . remove ( k ) ; } } return this ; }
Clear constants monitored object .
18,477
private void addList ( StringBuffer buffer , BufferedReader reader ) throws IOException { char [ ] lastBullet = new char [ 0 ] ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . length ( ) == 0 ) { continue ; } int bulletEnd = line . indexOf ( ' ' ) ; if ( bulletEnd < 1 ) { continue ; } if ( line . charAt ( bulletEnd - 1 ) == '.' ) { bulletEnd -- ; } char [ ] bullet = line . substring ( 0 , bulletEnd ) . toCharArray ( ) ; int sharedPrefixEnd ; for ( sharedPrefixEnd = 0 ; ; sharedPrefixEnd ++ ) { if ( bullet . length <= sharedPrefixEnd || lastBullet . length <= sharedPrefixEnd || + bullet [ sharedPrefixEnd ] != lastBullet [ sharedPrefixEnd ] ) { break ; } } for ( int i = sharedPrefixEnd ; i < lastBullet . length ; i ++ ) { buffer . append ( closeList . get ( new Character ( lastBullet [ i ] ) ) ) . append ( "\n" ) ; } for ( int i = sharedPrefixEnd ; i < bullet . length ; i ++ ) { buffer . append ( openList . get ( new Character ( bullet [ i ] ) ) ) . append ( "\n" ) ; } buffer . append ( "<li>" ) ; buffer . append ( line . substring ( line . indexOf ( ' ' ) + 1 ) ) ; buffer . append ( "</li>\n" ) ; lastBullet = bullet ; } for ( int i = lastBullet . length - 1 ; i >= 0 ; i -- ) { buffer . append ( closeList . get ( new Character ( lastBullet [ i ] ) ) ) ; } }
Adds a list to a buffer
18,478
public String render ( Reader in , RenderContext context ) throws IOException { StringBuffer buffer = new StringBuffer ( ) ; BufferedReader inputReader = new BufferedReader ( in ) ; String line ; while ( ( line = inputReader . readLine ( ) ) != null ) { buffer . append ( line ) ; } return render ( buffer . toString ( ) , context ) ; }
Render an input with text markup from a Reader and write the result to a writer
18,479
private TransactionOutput createOutput ( Address sendTo , long value ) { ScriptOutput script ; if ( sendTo . isMultisig ( _network ) ) { script = new ScriptOutputMultisig ( sendTo . getTypeSpecificBytes ( ) ) ; } else { script = new ScriptOutputStandard ( sendTo . getTypeSpecificBytes ( ) ) ; } TransactionOutput output = new TransactionOutput ( value , script ) ; return output ; }
XXX Should we support pubkey outputs?
18,480
public UnsignedTransaction createUnsignedTransaction ( List < UnspentTransactionOutput > unspent , Address changeAddress , PublicKeyRing keyRing , NetworkParameters network ) throws InsufficientFundsException { long fee = MIN_MINER_FEE ; while ( true ) { UnsignedTransaction unsigned ; try { unsigned = createUnsignedTransaction ( unspent , changeAddress , fee , keyRing , network ) ; } catch ( InsufficientFundsException e ) { throw e ; } int txSize = estimateTransacrionSize ( unsigned ) ; long requiredFee = ( 1 + ( txSize / 1000 ) ) * MIN_MINER_FEE ; if ( fee >= requiredFee ) { return unsigned ; } fee += MIN_MINER_FEE ; } }
Create an unsigned transaction without specifying a fee . The fee is automatically calculated to pass minimum relay and mining requirements .
18,481
public UnsignedTransaction createUnsignedTransaction ( List < UnspentTransactionOutput > unspent , Address changeAddress , long fee , PublicKeyRing keyRing , NetworkParameters network ) throws InsufficientFundsException { unspent = new LinkedList < UnspentTransactionOutput > ( unspent ) ; List < UnspentTransactionOutput > funding = new LinkedList < UnspentTransactionOutput > ( ) ; long outputSum = outputSum ( ) ; long toSend = fee + outputSum ; long found = 0 ; while ( found < toSend ) { UnspentTransactionOutput output = extractOldest ( unspent ) ; if ( output == null ) { throw new InsufficientFundsException ( outputSum , fee ) ; } found += output . value ; funding . add ( output ) ; } long change = found - toSend ; List < TransactionOutput > outputs = new LinkedList < TransactionOutput > ( _outputs ) ; if ( change > 0 ) { outputs . add ( createOutput ( changeAddress , change ) ) ; } return new UnsignedTransaction ( outputs , funding , keyRing , network ) ; }
Create an unsigned transaction with a specific miner fee . Note that specifying a miner fee that is too low may result in hanging transactions that never confirm .
18,482
public void updateInstanceUri ( String serviceName , String instanceId , String uri , boolean isOwned ) { String serviceUri = toInstanceUri ( serviceName , instanceId ) + "/uri" ; String body = null ; try { body = "uri=" + URLEncoder . encode ( uri , "UTF-8" ) + "&isOwned=" + isOwned ; } catch ( UnsupportedEncodingException e ) { LOGGER . error ( "UTF-8 not supported. " , e ) ; } Map < String , String > headers = new HashMap < String , String > ( ) ; headers . put ( "Content-Type" , "application/x-www-form-urlencoded" ) ; HttpResponse result = invoker . invoke ( serviceUri , body , HttpMethod . PUT , headers ) ; if ( result . getHttpCode ( ) != HTTP_OK ) { throw new ServiceException ( ErrorCode . REMOTE_DIRECTORY_SERVER_ERROR , "HTTP Code is not OK, code=%s" , result . getHttpCode ( ) ) ; } }
Update the ServiceInstance attribute uri .
18,483
public void unregisterInstance ( String serviceName , String instanceId , boolean isOwned ) { String uri = toInstanceUri ( serviceName , instanceId ) + "/" + isOwned ; HttpResponse result = invoker . invoke ( uri , null , HttpMethod . DELETE ) ; if ( result . getHttpCode ( ) != HTTP_OK ) { throw new ServiceException ( ErrorCode . REMOTE_DIRECTORY_SERVER_ERROR , "HTTP Code is not OK, code=%s" , result . getHttpCode ( ) ) ; } }
Unregister a ServiceInstance .
18,484
public Map < String , OperationResult < String > > sendHeartBeat ( Map < String , ServiceInstanceHeartbeat > heartbeatMap ) { String body = _serialize ( heartbeatMap ) ; HttpResponse result = invoker . invoke ( "/service/heartbeat" , body , HttpMethod . PUT ) ; if ( result . getHttpCode ( ) != HTTP_OK ) { throw new ServiceException ( ErrorCode . REMOTE_DIRECTORY_SERVER_ERROR , "HTTP Code is not OK, code=%s" , result . getHttpCode ( ) ) ; } Map < String , OperationResult < String > > operateResult = _deserialize ( result . getRetBody ( ) , new TypeReference < Map < String , OperationResult < String > > > ( ) { } ) ; return operateResult ; }
Send ServiceInstance heartbeats .
18,485
public ModelService lookupService ( String serviceName ) { HttpResponse result = invoker . invoke ( "/service/" + serviceName , null , HttpMethod . GET ) ; if ( result . getHttpCode ( ) != HTTP_OK ) { throw new ServiceException ( ErrorCode . REMOTE_DIRECTORY_SERVER_ERROR , "HTTP Code is not OK, code=%s" , result . getHttpCode ( ) ) ; } ModelService service = _deserialize ( result . getRetBody ( ) , ModelService . class ) ; return service ; }
Lookup a Service by serviceName .
18,486
public List < ModelServiceInstance > getAllInstances ( ) { HttpResponse result = invoker . invoke ( "/service" , null , HttpMethod . GET ) ; if ( result . getHttpCode ( ) != HTTP_OK ) { throw new ServiceException ( ErrorCode . REMOTE_DIRECTORY_SERVER_ERROR , "HTTP Code is not OK, code=%s" , result . getHttpCode ( ) ) ; } List < ModelServiceInstance > allInstances = _deserialize ( result . getRetBody ( ) , new TypeReference < List < ModelServiceInstance > > ( ) { } ) ; return allInstances ; }
Get all service instances .
18,487
public Map < String , OperationResult < ModelService > > getChangedServices ( Map < String , ModelService > services ) { String body = _serialize ( services ) ; HttpResponse result = invoker . invoke ( "/service/changing" , body , HttpMethod . POST ) ; if ( result . getHttpCode ( ) != HTTP_OK ) { throw new ServiceException ( ErrorCode . REMOTE_DIRECTORY_SERVER_ERROR , "HTTP Code is not OK, code=%s" , result . getHttpCode ( ) ) ; } Map < String , OperationResult < ModelService > > changedServices = _deserialize ( result . getRetBody ( ) , new TypeReference < Map < String , OperationResult < ModelService > > > ( ) { } ) ; return changedServices ; }
Get the changed services list .
18,488
public Map < String , OperationResult < ModelMetadataKey > > getChangedMetadataKeys ( Map < String , ModelMetadataKey > keys ) { String body = _serialize ( keys ) ; HttpResponse result = invoker . invoke ( "/metadatakey/changing" , body , HttpMethod . POST ) ; if ( result . getHttpCode ( ) != HTTP_OK ) { throw new ServiceException ( ErrorCode . REMOTE_DIRECTORY_SERVER_ERROR , "HTTP Code is not OK, code=%s" , result . getHttpCode ( ) ) ; } Map < String , OperationResult < ModelMetadataKey > > changedKeys = _deserialize ( result . getRetBody ( ) , new TypeReference < Map < String , OperationResult < ModelMetadataKey > > > ( ) { } ) ; return changedKeys ; }
Get the changed MetadataKey list .
18,489
private static void loadRestrictionsToAttribute ( XsdAttribute attribute , MethodVisitor mVisitor , String javaType , boolean hasEnum ) { getAttributeRestrictions ( attribute ) . forEach ( restriction -> loadRestrictionToAttribute ( mVisitor , restriction , javaType , hasEnum ? 1 : 0 ) ) ; mVisitor . visitInsn ( RETURN ) ; mVisitor . visitMaxs ( 4 , hasEnum ? 2 : 1 ) ; mVisitor . visitEnd ( ) ; }
Loads all the existing restrictions to the attribute class .
18,490
private static void numericAdjustment ( MethodVisitor mVisitor , String javaType ) { adjustmentsMapper . getOrDefault ( javaType , XsdAsmAttributes :: doubleAdjustment ) . accept ( mVisitor ) ; }
Applies a cast to numeric types i . e . int short long to double .
18,491
public String prettyHtml ( ) { StringBuilder html = new StringBuilder ( ) ; for ( Change aDiff : getChangeList ( ) ) { String text = aDiff . text . replace ( "&" , "&amp;" ) . replace ( "<" , "&lt;" ) . replace ( ">" , "&gt;" ) . replace ( "\n" , "&para;<br>" ) ; switch ( aDiff . operation ) { case INSERT : html . append ( "<ins style=\"background:#e6ffe6;\">" ) . append ( text ) . append ( "</ins>" ) ; break ; case DELETE : html . append ( "<del style=\"background:#ffe6e6;\">" ) . append ( text ) . append ( "</del>" ) ; break ; case EQUAL : html . append ( "<span>" ) . append ( text ) . append ( "</span>" ) ; break ; } } return html . toString ( ) ; }
Convert a DiffBase list into a pretty HTML report .
18,492
public String toDelta ( ) { StringBuilder text = new StringBuilder ( ) ; for ( Change aDiff : getChangeList ( ) ) { switch ( aDiff . operation ) { case INSERT : try { text . append ( "+" ) . append ( URLEncoder . encode ( aDiff . text , "UTF-8" ) . replace ( '+' , ' ' ) ) . append ( "\t" ) ; } catch ( UnsupportedEncodingException e ) { throw new Error ( "This system does not support UTF-8." , e ) ; } break ; case DELETE : text . append ( "-" ) . append ( aDiff . text . length ( ) ) . append ( "\t" ) ; break ; case EQUAL : text . append ( "=" ) . append ( aDiff . text . length ( ) ) . append ( "\t" ) ; break ; } } String delta = text . toString ( ) ; if ( delta . length ( ) != 0 ) { delta = delta . substring ( 0 , delta . length ( ) - 1 ) ; delta = Strings . unescapeForEncodeUriCompatability ( delta ) ; } return delta ; }
Crush the diff into an encoded string which describes the operations required to transform text1 into text2 . E . g . = 3 \ t - 2 \ t + ing - &gt ; Keep 3 chars delete 2 chars insert ing . Operations are tab - separated . Inserted text is escaped using %xx notation .
18,493
private String linesToCharsMunge ( String text , List < String > lineArray , Map < String , Integer > lineHash ) { int lineStart = 0 ; int lineEnd = - 1 ; String line ; StringBuilder chars = new StringBuilder ( ) ; while ( lineEnd < text . length ( ) - 1 ) { lineEnd = text . indexOf ( '\n' , lineStart ) ; if ( lineEnd == - 1 ) { lineEnd = text . length ( ) - 1 ; } line = text . substring ( lineStart , lineEnd + 1 ) ; lineStart = lineEnd + 1 ; if ( lineHash . containsKey ( line ) ) { chars . append ( String . valueOf ( ( char ) ( int ) lineHash . get ( line ) ) ) ; } else { lineArray . add ( line ) ; lineHash . put ( line , lineArray . size ( ) - 1 ) ; chars . append ( String . valueOf ( ( char ) ( lineArray . size ( ) - 1 ) ) ) ; } } return chars . toString ( ) ; }
Split a text into a list of strings . Reduce the texts to a string of hashes where each Unicode character represents one line .
18,494
public TextSearch filter ( final SearchFilter filter ) { if ( filters == null ) { filters = new HashSet < SearchFilter > ( ) ; } filters . add ( filter ) ; return this ; }
Add a filter to the query using the Fluent API approach .
18,495
public void stop ( ) { if ( isStarted ) { synchronized ( this ) { if ( isStarted ) { if ( getLookupService ( ) instanceof Closable ) { ( ( Closable ) getLookupService ( ) ) . stop ( ) ; } isStarted = false ; } } } }
Stop the LookupManagerImpl
18,496
private DirectoryLookupService getLookupService ( ) { if ( lookupService == null ) { synchronized ( this ) { if ( lookupService == null ) { boolean cacheEnabled = Configurations . getBoolean ( SD_API_CACHE_ENABLED_PROPERTY , SD_API_CACHE_ENABLED_DEFAULT ) ; if ( cacheEnabled ) { CachedDirectoryLookupService service = new CachedDirectoryLookupService ( directoryServiceClientManager ) ; service . start ( ) ; lookupService = service ; LOGGER . info ( "Created the CachedDirectoryLookupService in LookupManager" ) ; } else { lookupService = new DirectoryLookupService ( directoryServiceClientManager ) ; LOGGER . info ( "Created the DirectoryLookupService in LookupManager" ) ; } } } } return lookupService ; }
Get the DirectoryLookupService to do the lookup .
18,497
public ResourceBundle getResourceBundle ( String baseName ) { ResourceBundle bundle = ( ResourceBundle ) resourceBundles . get ( baseName ) ; if ( null == bundle ) { resourceBundles . put ( baseName , bundle = findBundle ( baseName ) ) ; } return bundle ; }
Get the bundle that is active for this thread . This is done by loading either the specified locale based resource bundle and if that fails by looping through the fallback locales to locate a usable bundle .
18,498
private ResourceBundle findBundle ( String baseName ) { ResourceBundle resourceBundle = null ; ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( null != locale ) { try { resourceBundle = ResourceBundle . getBundle ( baseName , locale , cl ) ; } catch ( Exception e ) { log . fatal ( "unable to load a default bundle: " + baseName + "_" + locale ) ; } if ( ! resourceBundle . getLocale ( ) . equals ( locale ) ) { resourceBundle = null ; } } if ( null == resourceBundle ) { if ( null != fallback ) { while ( fallback . hasMoreElements ( ) ) { Locale testLocale = ( Locale ) fallback . nextElement ( ) ; log . debug ( "looking up locale " + testLocale ) ; ResourceBundle testBundle = ResourceBundle . getBundle ( baseName , testLocale , cl ) ; String language = testBundle . getLocale ( ) . getLanguage ( ) ; String country = testBundle . getLocale ( ) . getCountry ( ) ; if ( testBundle . getLocale ( ) . equals ( testLocale ) ) { resourceBundle = testBundle ; log . debug ( "found bundle for locale " + baseName + "_" + testBundle . getLocale ( ) ) ; break ; } else if ( testLocale . getLanguage ( ) . equals ( language ) ) { if ( testLocale . getCountry ( ) . equals ( country ) ) { resourceBundle = testBundle ; log . debug ( "potential bundle: " + baseName + "_" + testBundle . getLocale ( ) ) ; continue ; } else { if ( null == resourceBundle ) { resourceBundle = testBundle ; log . debug ( "potential bundle: " + baseName + "_" + testBundle . getLocale ( ) ) ; } continue ; } } } } if ( null == resourceBundle ) { resourceBundle = ResourceBundle . getBundle ( baseName ) ; if ( null != resourceBundle ) { log . debug ( "system locale bundle taken: " + baseName + "_" + resourceBundle . getLocale ( ) ) ; } } } return resourceBundle ; }
Find a resource bundle by looking up using the locales . This is done by loading either the specified locale based resource bundle and if that fails by looping through the fallback locales to locate a usable bundle .
18,499
public final CharSlice substring ( int start , int end ) { if ( start < 0 || end > len || end < - len ) { throw new IllegalArgumentException ( String . format ( "[%d,%d] of slice length %d is not valid." , start , end , len ) ) ; } int l = end < 0 ? ( len - start ) + end : end - start ; if ( l < 0 || l > ( len - start ) ) { throw new IllegalArgumentException ( String . format ( "[%d,%d] of slice length %d is not valid." , start , end , len ) ) ; } return new CharSlice ( fb , off + start , l ) ; }
Create a substring slice based on the current slice .