idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
21,400 | public Optional < List < FormItem > > parseRequestMultiPartItems ( String encoding ) { DiskFileItemFactory factory = new DiskFileItemFactory ( ) ; factory . setSizeThreshold ( properties . getInt ( Constants . PROPERTY_UPLOADS_MAX_SIZE ) ) ; factory . setRepository ( new File ( System . getProperty ( "java.io.tmpdir" ) ) ) ; ServletFileUpload upload = new ServletFileUpload ( factory ) ; if ( encoding != null ) upload . setHeaderEncoding ( encoding ) ; upload . setFileSizeMax ( properties . getInt ( Constants . PROPERTY_UPLOADS_MAX_SIZE ) ) ; try { List < FormItem > items = upload . parseRequest ( request ) . stream ( ) . map ( item -> new ApacheFileItemFormItem ( item ) ) . collect ( Collectors . toList ( ) ) ; return Optional . of ( items ) ; } catch ( FileUploadException e ) { } return Optional . empty ( ) ; } | Gets the FileItemIterator of the input . |
21,401 | public void printRuleSet ( RuleSet ruleSet ) throws RuleException { RuleSelection ruleSelection = RuleSelection . builder ( ) . conceptIds ( ruleSet . getConceptBucket ( ) . getIds ( ) ) . constraintIds ( ruleSet . getConstraintBucket ( ) . getIds ( ) ) . groupIds ( ruleSet . getGroupsBucket ( ) . getIds ( ) ) . build ( ) ; printRuleSet ( ruleSet , ruleSelection ) ; } | Logs the given rule set on level info . |
21,402 | private void printValidRules ( CollectRulesVisitor visitor ) { logger . info ( "Groups [" + visitor . getGroups ( ) . size ( ) + "]" ) ; for ( Group group : visitor . getGroups ( ) ) { logger . info ( LOG_LINE_PREFIX + group . getId ( ) + "\"" ) ; } logger . info ( "Constraints [" + visitor . getConstraints ( ) . size ( ) + "]" ) ; for ( Constraint constraint : visitor . getConstraints ( ) . keySet ( ) ) { logger . info ( LOG_LINE_PREFIX + constraint . getId ( ) + "\" - " + constraint . getDescription ( ) ) ; } logger . info ( "Concepts [" + visitor . getConcepts ( ) . size ( ) + "]" ) ; for ( Concept concept : visitor . getConcepts ( ) . keySet ( ) ) { logger . info ( LOG_LINE_PREFIX + concept . getId ( ) + "\" - " + concept . getDescription ( ) ) ; } } | Prints all valid rules . |
21,403 | private CollectRulesVisitor getAllRules ( RuleSet ruleSet , RuleSelection ruleSelection ) throws RuleException { CollectRulesVisitor visitor = new CollectRulesVisitor ( ) ; RuleSetExecutor executor = new RuleSetExecutor ( visitor , new RuleSetExecutorConfiguration ( ) ) ; executor . execute ( ruleSet , ruleSelection ) ; return visitor ; } | Determines all rules . |
21,404 | private boolean printMissingRules ( CollectRulesVisitor visitor ) { Set < String > missingConcepts = visitor . getMissingConcepts ( ) ; if ( ! missingConcepts . isEmpty ( ) ) { logger . info ( "Missing concepts [" + missingConcepts . size ( ) + "]" ) ; for ( String missingConcept : missingConcepts ) { logger . warn ( LOG_LINE_PREFIX + missingConcept ) ; } } Set < String > missingConstraints = visitor . getMissingConstraints ( ) ; if ( ! missingConstraints . isEmpty ( ) ) { logger . info ( "Missing constraints [" + missingConstraints . size ( ) + "]" ) ; for ( String missingConstraint : missingConstraints ) { logger . warn ( LOG_LINE_PREFIX + missingConstraint ) ; } } Set < String > missingGroups = visitor . getMissingGroups ( ) ; if ( ! missingGroups . isEmpty ( ) ) { logger . info ( "Missing groups [" + missingGroups . size ( ) + "]" ) ; for ( String missingGroup : missingGroups ) { logger . warn ( LOG_LINE_PREFIX + missingGroup ) ; } } return missingConcepts . isEmpty ( ) && missingConstraints . isEmpty ( ) && missingGroups . isEmpty ( ) ; } | Prints all missing rule ids . |
21,405 | public String getTemplateNameForResult ( Route route , Result response ) { String template = response . template ( ) ; if ( template == null ) { if ( route != null ) { String controllerPath = RouterHelper . getReverseRouteFast ( route . getController ( ) ) ; if ( new File ( realPath + controllerPath + templateSuffix ) . exists ( ) ) { return controllerPath ; } return controllerPath + "/" + route . getActionName ( ) ; } else { return null ; } } else { if ( template . endsWith ( templateSuffix ) ) { return template . substring ( 0 , template . length ( ) - templateSuffixLengthToRemove ) ; } return template ; } } | If the template is specified by the user with a suffix corresponding to the template engine suffix then this is removed before returning the template . Suffixes such as . st or . ftl . html |
21,406 | public T locateLayoutTemplate ( String controller , final String layout , final boolean useCache ) throws ViewException { final String controllerLayoutCombined = controller + '/' + layout ; if ( useCache && cachedTemplates . containsKey ( controllerLayoutCombined ) ) return engine . clone ( cachedTemplates . get ( controllerLayoutCombined ) ) ; T template ; if ( ( template = lookupLayoutWithNonDefaultName ( controllerLayoutCombined ) ) != null ) return cacheTemplate ( controllerLayoutCombined , template , useCache ) ; if ( ( template = lookupDefaultLayoutInControllerPathChain ( controller ) ) != null ) return cacheTemplate ( controllerLayoutCombined , template , useCache ) ; if ( ( template = lookupDefaultLayout ( ) ) != null ) return cacheTemplate ( controllerLayoutCombined , template , useCache ) ; throw new ViewException ( TemplateEngine . LAYOUT_DEFAULT + engine . getSuffixOfTemplatingEngine ( ) + " is not to be found anywhere" ) ; } | If found uses the provided layout within the controller folder . If not found it looks for the default template within the controller folder then use this to override the root default template |
21,407 | protected void flash ( Map < String , String > values ) { for ( Object key : values . keySet ( ) ) { flash ( key . toString ( ) , values . get ( key ) ) ; } } | Convenience method takes in a map of values to flash . |
21,408 | protected void flash ( String name , String value ) { context . getFlash ( ) . put ( name , value ) ; } | Sends value to flash . Flash survives one more request . Using flash is typical for POST - > REDIRECT - > GET pattern |
21,409 | protected void redirectToReferrer ( ) { String referrer = context . requestHeader ( "Referer" ) ; referrer = referrer == null ? context . contextPath ( ) : referrer ; redirect ( referrer ) ; } | Redirects to referrer if one exists . If a referrer does not exist it will be redirected to the root of the application . |
21,410 | protected String cookieValue ( String name ) { Cookie cookie = cookie ( name ) ; return cookie != null ? cookie . getValue ( ) : null ; } | Convenience method returns cookie value . |
21,411 | public < T > Class < T > getType ( String typeName ) { try { return ( Class < T > ) classLoader . loadClass ( typeName ) ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( "Cannot find class " + typeName , e ) ; } } | Create and return an instance of the given type name . |
21,412 | private Map < String , ReportPlugin > selectReportPlugins ( ExecutableRule rule ) throws ReportException { Set < String > selection = rule . getReport ( ) . getSelectedTypes ( ) ; Map < String , ReportPlugin > reportPlugins = new HashMap < > ( ) ; if ( selection != null ) { for ( String type : selection ) { ReportPlugin candidate = this . selectableReportPlugins . get ( type ) ; if ( candidate == null ) { throw new ReportException ( "Unknown report selection '" + type + "' selected for '" + rule + "'" ) ; } reportPlugins . put ( type , candidate ) ; } } return reportPlugins ; } | Select the report writers for the given rule . |
21,413 | static Set < String > labels ( final ResultSet results ) throws SQLException { final ResultSetMetaData metadata = results . getMetaData ( ) ; final int count = metadata . getColumnCount ( ) ; final Set < String > labels = new HashSet < > ( count ) ; for ( int i = 1 ; i <= count ; i ++ ) { labels . add ( metadata . getColumnLabel ( i ) . toUpperCase ( ) ) ; } return labels ; } | Returns a set of column labels of given result set . |
21,414 | private void writeStatus ( Result . Status status ) throws XMLStreamException { xmlStreamWriter . writeStartElement ( "status" ) ; xmlStreamWriter . writeCharacters ( status . name ( ) . toLowerCase ( ) ) ; xmlStreamWriter . writeEndElement ( ) ; } | Write the status of the current result . |
21,415 | private void writeColumn ( String columnName , Object value ) throws XMLStreamException { xmlStreamWriter . writeStartElement ( "column" ) ; xmlStreamWriter . writeAttribute ( "name" , columnName ) ; String stringValue = null ; if ( value instanceof CompositeObject ) { CompositeObject descriptor = ( CompositeObject ) value ; LanguageElement elementValue = LanguageHelper . getLanguageElement ( descriptor ) ; if ( elementValue != null ) { xmlStreamWriter . writeStartElement ( "element" ) ; xmlStreamWriter . writeAttribute ( "language" , elementValue . getLanguage ( ) ) ; xmlStreamWriter . writeCharacters ( elementValue . name ( ) ) ; xmlStreamWriter . writeEndElement ( ) ; SourceProvider sourceProvider = elementValue . getSourceProvider ( ) ; stringValue = sourceProvider . getName ( descriptor ) ; String sourceFile = sourceProvider . getSourceFile ( descriptor ) ; Integer lineNumber = sourceProvider . getLineNumber ( descriptor ) ; if ( sourceFile != null ) { xmlStreamWriter . writeStartElement ( "source" ) ; xmlStreamWriter . writeAttribute ( "name" , sourceFile ) ; if ( lineNumber != null ) { xmlStreamWriter . writeAttribute ( "line" , lineNumber . toString ( ) ) ; } xmlStreamWriter . writeEndElement ( ) ; } } } else if ( value != null ) { stringValue = ReportHelper . getLabel ( value ) ; } xmlStreamWriter . writeStartElement ( "value" ) ; xmlStreamWriter . writeCharacters ( stringValue ) ; xmlStreamWriter . writeEndElement ( ) ; xmlStreamWriter . writeEndElement ( ) ; } | Determines the language and language element of a descriptor from a result column . |
21,416 | private void writeDuration ( long beginTime ) throws XMLStreamException { xmlStreamWriter . writeStartElement ( "duration" ) ; xmlStreamWriter . writeCharacters ( Long . toString ( System . currentTimeMillis ( ) - beginTime ) ) ; xmlStreamWriter . writeEndElement ( ) ; } | Writes the duration . |
21,417 | private void writeSeverity ( Severity severity ) throws XMLStreamException { xmlStreamWriter . writeStartElement ( "severity" ) ; xmlStreamWriter . writeAttribute ( "level" , severity . getLevel ( ) . toString ( ) ) ; xmlStreamWriter . writeCharacters ( severity . getValue ( ) ) ; xmlStreamWriter . writeEndElement ( ) ; } | Writes the severity of the rule . |
21,418 | private void run ( XmlOperation operation ) throws ReportException { try { operation . run ( ) ; } catch ( XMLStreamException | IOException e ) { throw new ReportException ( "Cannot write to XML report." , e ) ; } } | Defines an operation to write XML elements . |
21,419 | private final CompiledST loadTemplateResource ( String prefix , String unqualifiedFileName ) { if ( resourceRoots . isEmpty ( ) ) return null ; CompiledST template = null ; for ( URL resourceRoot : resourceRoots ) { if ( ( template = loadTemplate ( resourceRoot , prefix , unqualifiedFileName ) ) != null ) return template ; } return null ; } | Loads from a jar or similar resource if the template could not be found directly on the filesystem . |
21,420 | private final void renderContentTemplate ( final ST contentTemplate , final Writer writer , final Map < String , Object > values , final ErrorBuffer error ) { injectTemplateValues ( contentTemplate , values ) ; contentTemplate . write ( createSTWriter ( writer ) , error ) ; } | Renders template directly to writer |
21,421 | private final String renderContentTemplate ( final ST contentTemplate , final Map < String , Object > values , final ErrorBuffer error , boolean inErrorState ) { if ( contentTemplate != null ) { try ( Writer sw = new StringBuilderWriter ( ) ) { final ErrorBuffer templateErrors = new ErrorBuffer ( ) ; renderContentTemplate ( contentTemplate , sw , values , templateErrors ) ; if ( ! templateErrors . errors . isEmpty ( ) && ! inErrorState ) { for ( STMessage err : templateErrors . errors ) { if ( err . error == ErrorType . INTERNAL_ERROR ) { log . warn ( "Reloading GroupDir as we have found a problem during rendering of template \"{}\"\n{}" , contentTemplate . getName ( ) , templateErrors . errors . toString ( ) ) ; reloadGroup ( ) ; ST reloadedContentTemplate = readTemplate ( contentTemplate . getName ( ) ) ; return renderContentTemplate ( reloadedContentTemplate , values , error , true ) ; } } } return sw . toString ( ) ; } catch ( IOException noMethodsThrowsIOE ) { } } return "" ; } | Renders template into string |
21,422 | public static Integer toInteger ( Object value ) throws ConversionException { if ( value == null ) { return null ; } else if ( value instanceof Number ) { return ( ( Number ) value ) . intValue ( ) ; } else { NumberFormat nf = new DecimalFormat ( ) ; try { return nf . parse ( value . toString ( ) ) . intValue ( ) ; } catch ( ParseException e ) { throw new ConversionException ( "failed to convert: '" + value + "' to Integer" , e ) ; } } } | Converts value to Integer if it can . If value is an Integer it is returned if it is a Number it is promoted to Integer and then returned in all other cases it converts the value to String then tries to parse Integer from it . |
21,423 | public static Boolean toBoolean ( Object value ) { if ( value == null ) { return false ; } else if ( value instanceof Boolean ) { return ( Boolean ) value ; } else if ( value instanceof BigDecimal ) { return value . equals ( BigDecimal . ONE ) ; } else if ( value instanceof Long ) { return value . equals ( 1L ) ; } else if ( value instanceof Integer ) { return value . equals ( 1 ) ; } else if ( value instanceof Character ) { return value . equals ( 'y' ) || value . equals ( 'Y' ) || value . equals ( 't' ) || value . equals ( 'T' ) ; } else return value . toString ( ) . equalsIgnoreCase ( "yes" ) || value . toString ( ) . equalsIgnoreCase ( "true" ) || value . toString ( ) . equalsIgnoreCase ( "y" ) || value . toString ( ) . equalsIgnoreCase ( "t" ) || Boolean . parseBoolean ( value . toString ( ) ) ; } | Returns true if the value is any numeric type and has a value of 1 or if string type has a value of y t true or yes . Otherwise return false . |
21,424 | public static Long toLong ( Object value ) throws ConversionException { if ( value == null ) { return null ; } else if ( value instanceof Number ) { return ( ( Number ) value ) . longValue ( ) ; } else { NumberFormat nf = new DecimalFormat ( ) ; try { return nf . parse ( value . toString ( ) ) . longValue ( ) ; } catch ( ParseException e ) { throw new ConversionException ( "failed to convert: '" + value + "' to Long" , e ) ; } } } | Converts value to Long if c it can . If value is a Long it is returned if it is a Number it is promoted to Long and then returned in all other cases it converts the value to String then tries to parse Long from it . |
21,425 | protected < T > Class < T > getType ( String typeName ) throws PluginRepositoryException { try { return ( Class < T > ) classLoader . loadClass ( typeName . trim ( ) ) ; } catch ( ClassNotFoundException | LinkageError e ) { throw new PluginRepositoryException ( "Cannot find or load class " + typeName , e ) ; } } | Get the class for the given type name . |
21,426 | protected < T > T createInstance ( String typeName ) throws PluginRepositoryException { Class < T > type = getType ( typeName . trim ( ) ) ; try { return type . newInstance ( ) ; } catch ( InstantiationException e ) { throw new PluginRepositoryException ( "Cannot create instance of class " + type . getName ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new PluginRepositoryException ( "Cannot access class " + typeName , e ) ; } catch ( LinkageError e ) { throw new PluginRepositoryException ( "Cannot load plugin class " + typeName , e ) ; } } | Create an instance of the given scanner plugin class . |
21,427 | private final Route calculateRoute ( HttpMethod httpMethod , String requestUri ) throws RouteException { if ( routes == null ) throw new IllegalStateException ( "Routes have not been compiled. Call #compileRoutes() first" ) ; final Route route = matchCustom ( httpMethod , requestUri ) ; if ( route != null ) return route ; try { return matchStandard ( httpMethod , requestUri , invoker ) ; } catch ( ClassLoadException e ) { } throw new RouteException ( "Failed to map resource to URI: " + requestUri ) ; } | It is not consistent that this particular injector handles implementations from both core and server |
21,428 | private Route matchStandard ( HttpMethod httpMethod , String requestUri , ActionInvoker invoker ) throws ClassLoadException { for ( InternalRoute internalRoute : internalRoutes ) { if ( internalRoute . matches ( requestUri ) ) { Route deferred = deduceRoute ( internalRoute , httpMethod , requestUri , invoker ) ; if ( deferred != null ) return deferred ; } } throw new ClassLoadException ( "A route for request " + requestUri + " could not be deduced" ) ; } | Only to be used in DEV mode |
21,429 | @ SuppressWarnings ( "NullableProblems" ) public Iterator < T > iterator ( ) { return new Iterator < T > ( ) { private int index = 0 ; public boolean hasNext ( ) { return this . index < size ( ) ; } public T next ( ) { if ( this . index >= size ( ) ) { throw new NoSuchElementException ( this . index + ">=" + size ( ) ) ; } return getElementAt ( this . index ++ ) ; } public void remove ( ) { throw new UnsupportedOperationException ( "Removing is unsupported here" ) ; } } ; } | Generates an iterator to allow the array processing in loops . |
21,430 | private static void assertArrayLength ( final int length , final JBBPNamedFieldInfo name ) { if ( length < 0 ) { throw new JBBPParsingException ( "Detected negative calculated array length for field '" + ( name == null ? "<NO NAME>" : name . getFieldPath ( ) ) + "\' [" + JBBPUtils . int2msg ( length ) + ']' ) ; } } | Ensure that an array length is not a negative one . |
21,431 | public static JBBPParser prepare ( final String script , final JBBPBitOrder bitOrder ) { return new JBBPParser ( script , bitOrder , null , 0 ) ; } | Prepare a parser for a script and a bit order . |
21,432 | public static JBBPParser prepare ( final String script , final JBBPBitOrder bitOrder , final JBBPCustomFieldTypeProcessor customFieldTypeProcessor , final int flags ) { return new JBBPParser ( script , bitOrder , customFieldTypeProcessor , flags ) ; } | Prepare a parser for a script with defined bit order and special flags . |
21,433 | public JBBPFieldStruct parse ( final InputStream in , final JBBPVarFieldProcessor varFieldProcessor , final JBBPExternalValueProvider externalValueProvider ) throws IOException { final JBBPBitInputStream bitInStream = in instanceof JBBPBitInputStream ? ( JBBPBitInputStream ) in : new JBBPBitInputStream ( in , bitOrder ) ; this . finalStreamByteCounter = bitInStream . getCounter ( ) ; final JBBPNamedNumericFieldMap fieldMap ; if ( this . compiledBlock . hasEvaluatedSizeArrays ( ) || this . compiledBlock . hasVarFields ( ) ) { fieldMap = new JBBPNamedNumericFieldMap ( externalValueProvider ) ; } else { fieldMap = null ; } if ( this . compiledBlock . hasVarFields ( ) ) { JBBPUtils . assertNotNull ( varFieldProcessor , "The Script contains VAR fields, a var field processor must be provided" ) ; } try { return new JBBPFieldStruct ( new JBBPNamedFieldInfo ( "" , "" , - 1 ) , parseStruct ( bitInStream , new JBBPIntCounter ( ) , varFieldProcessor , fieldMap , new JBBPIntCounter ( ) , new JBBPIntCounter ( ) , false ) ) ; } finally { this . finalStreamByteCounter = bitInStream . getCounter ( ) ; } } | Parse am input stream with defined external value provider . |
21,434 | public List < ResultSrcItem > convertToSrc ( final TargetSources target , final String name ) { JBBPUtils . assertNotNull ( name , "Name must not be null" ) ; if ( target == TargetSources . JAVA_1_6 ) { final Properties metadata = new Properties ( ) ; metadata . setProperty ( "script" , this . compiledBlock . getSource ( ) ) ; metadata . setProperty ( "name" , name ) ; metadata . setProperty ( "target" , target . name ( ) ) ; metadata . setProperty ( "converter" , JBBPToJava6Converter . class . getCanonicalName ( ) ) ; final int nameStart = name . lastIndexOf ( '.' ) ; final String packageName ; final String className ; if ( nameStart < 0 ) { packageName = "" ; className = name ; } else { packageName = name . substring ( 0 , nameStart ) ; className = name . substring ( nameStart + 1 ) ; } final String resultSources = JBBPToJava6Converter . makeBuilder ( this ) . setMainClassPackage ( packageName ) . setMainClassName ( className ) . build ( ) . convert ( ) ; final Map < String , String > resultMap = Collections . singletonMap ( name . replace ( '.' , '/' ) + ".java" , resultSources ) ; return Collections . singletonList ( new ResultSrcItem ( ) { public Properties getMetadata ( ) { return metadata ; } public Map < String , String > getResult ( ) { return resultMap ; } } ) ; } throw new IllegalArgumentException ( "Unsupported target : " + target ) ; } | Convert the prepared parser into sources . It doesn t provide way to define different flag for conversion it uses default flags for converters and provided for short fast way . |
21,435 | public static String ensureEncodingName ( final String charsetName ) { final Charset defaultCharset = Charset . defaultCharset ( ) ; try { return ( charsetName == null ) ? defaultCharset . name ( ) : Charset . forName ( charsetName . trim ( ) ) . name ( ) ; } catch ( IllegalCharsetNameException ex ) { throw new IllegalArgumentException ( "Can't recognize charset for name '" + charsetName + '\'' ) ; } } | Get charset name . If name is null then default charset name provided . |
21,436 | public static String extractClassName ( final String canonicalJavaClassName ) { final int lastDot = canonicalJavaClassName . lastIndexOf ( '.' ) ; if ( lastDot < 0 ) { return canonicalJavaClassName . trim ( ) ; } return canonicalJavaClassName . substring ( lastDot + 1 ) . trim ( ) ; } | Extract class name from canonical Java class name |
21,437 | public static String extractPackageName ( final String fileNameWithoutExtension ) { final int lastDot = fileNameWithoutExtension . lastIndexOf ( '.' ) ; if ( lastDot < 0 ) { return "" ; } return fileNameWithoutExtension . substring ( 0 , lastDot ) . trim ( ) ; } | Extract package name from canonical Java class name |
21,438 | public static File scriptFileToJavaFile ( final File targetDir , final String classPackage , final File scriptFile ) { final String rawFileName = FilenameUtils . getBaseName ( scriptFile . getName ( ) ) ; final String className = CommonUtils . extractClassName ( rawFileName ) ; final String packageName = classPackage == null ? CommonUtils . extractPackageName ( rawFileName ) : classPackage ; String fullClassName = packageName . isEmpty ( ) ? className : packageName + '.' + className ; fullClassName = fullClassName . replace ( '.' , File . separatorChar ) + ".java" ; return new File ( targetDir , fullClassName ) ; } | Convert script file into path to Java class file . |
21,439 | public static byte [ ] strToUtf8 ( final String str ) { final ByteBuffer buffer = CHARSET_UTF8 . encode ( str ) ; final byte [ ] bytesArray = new byte [ buffer . remaining ( ) ] ; buffer . get ( bytesArray , 0 , bytesArray . length ) ; return bytesArray ; } | Convert a string into its UTF8 representation . |
21,440 | public static boolean isNumber ( final String num ) { if ( num == null || num . length ( ) == 0 ) { return false ; } final boolean firstIsDigit = Character . isDigit ( num . charAt ( 0 ) ) ; if ( ! firstIsDigit && num . charAt ( 0 ) != '-' ) { return false ; } boolean dig = firstIsDigit ; for ( int i = 1 ; i < num . length ( ) ; i ++ ) { if ( ! Character . isDigit ( num . charAt ( i ) ) ) { return false ; } dig = true ; } return dig ; } | Check that a string is a number . |
21,441 | public static byte [ ] packInt ( final int value ) { if ( ( value & 0xFFFFFF80 ) == 0 ) { return new byte [ ] { ( byte ) value } ; } else if ( ( value & 0xFFFF0000 ) == 0 ) { return new byte [ ] { ( byte ) 0x80 , ( byte ) ( value >>> 8 ) , ( byte ) value } ; } else { return new byte [ ] { ( byte ) 0x81 , ( byte ) ( value >>> 24 ) , ( byte ) ( value >>> 16 ) , ( byte ) ( value >>> 8 ) , ( byte ) value } ; } } | Pack an integer value as a byte array . |
21,442 | public static int packInt ( final byte [ ] array , final JBBPIntCounter position , final int value ) { if ( ( value & 0xFFFFFF80 ) == 0 ) { array [ position . getAndIncrement ( ) ] = ( byte ) value ; return 1 ; } else if ( ( value & 0xFFFF0000 ) == 0 ) { array [ position . getAndIncrement ( ) ] = ( byte ) 0x80 ; array [ position . getAndIncrement ( ) ] = ( byte ) ( value >>> 8 ) ; array [ position . getAndIncrement ( ) ] = ( byte ) value ; return 3 ; } array [ position . getAndIncrement ( ) ] = ( byte ) 0x81 ; array [ position . getAndIncrement ( ) ] = ( byte ) ( value >>> 24 ) ; array [ position . getAndIncrement ( ) ] = ( byte ) ( value >>> 16 ) ; array [ position . getAndIncrement ( ) ] = ( byte ) ( value >>> 8 ) ; array [ position . getAndIncrement ( ) ] = ( byte ) value ; return 5 ; } | Pack an integer value and save that into a byte array since defined position . |
21,443 | public static int unpackInt ( final byte [ ] array , final JBBPIntCounter position ) { final int code = array [ position . getAndIncrement ( ) ] & 0xFF ; if ( code < 0x80 ) { return code ; } final int result ; switch ( code ) { case 0x80 : { result = ( ( array [ position . getAndIncrement ( ) ] & 0xFF ) << 8 ) | ( array [ position . getAndIncrement ( ) ] & 0xFF ) ; } break ; case 0x81 : { result = ( ( array [ position . getAndIncrement ( ) ] & 0xFF ) << 24 ) | ( ( array [ position . getAndIncrement ( ) ] & 0xFF ) << 16 ) | ( ( array [ position . getAndIncrement ( ) ] & 0xFF ) << 8 ) | ( array [ position . getAndIncrement ( ) ] & 0xFF ) ; } break ; default : throw new IllegalArgumentException ( "Unsupported packed integer prefix [0x" + Integer . toHexString ( code ) . toUpperCase ( Locale . ENGLISH ) + ']' ) ; } return result ; } | Unpack an integer value from defined position in a byte array . |
21,444 | public static String byteArray2String ( final byte [ ] array , final String prefix , final String delimiter , final boolean brackets , final int radix ) { if ( array == null ) { return null ; } final int maxlen = Integer . toString ( 0xFF , radix ) . length ( ) ; final String zero = "00000000" ; final String normDelim = delimiter == null ? " " : delimiter ; final String normPrefix = prefix == null ? "" : prefix ; final StringBuilder result = new StringBuilder ( array . length * 4 ) ; if ( brackets ) { result . append ( '[' ) ; } boolean nofirst = false ; for ( final byte b : array ) { if ( nofirst ) { result . append ( normDelim ) ; } else { nofirst = true ; } result . append ( normPrefix ) ; final String v = Integer . toString ( b & 0xFF , radix ) ; if ( v . length ( ) < maxlen ) { result . append ( zero , 0 , maxlen - v . length ( ) ) ; } result . append ( v . toUpperCase ( Locale . ENGLISH ) ) ; } if ( brackets ) { result . append ( ']' ) ; } return result . toString ( ) ; } | Convert a byte array into string representation |
21,445 | public static byte reverseBitsInByte ( final JBBPBitNumber bitNumber , final byte value ) { final byte reversed = reverseBitsInByte ( value ) ; return ( byte ) ( ( reversed >>> ( 8 - bitNumber . getBitNumber ( ) ) ) & bitNumber . getMask ( ) ) ; } | Reverse lower part of a byte defined by bits number constant . |
21,446 | public static String bin2str ( final byte [ ] values , final JBBPBitOrder bitOrder , final boolean separateBytes ) { if ( values == null ) { return null ; } final StringBuilder result = new StringBuilder ( values . length * ( separateBytes ? 9 : 8 ) ) ; boolean nofirst = false ; for ( final byte b : values ) { if ( separateBytes ) { if ( nofirst ) { result . append ( ' ' ) ; } else { nofirst = true ; } } int a = b ; if ( bitOrder == JBBPBitOrder . MSB0 ) { for ( int i = 0 ; i < 8 ; i ++ ) { result . append ( ( a & 0x1 ) == 0 ? '0' : '1' ) ; a >>= 1 ; } } else { for ( int i = 0 ; i < 8 ; i ++ ) { result . append ( ( a & 0x80 ) == 0 ? '0' : '1' ) ; a <<= 1 ; } } } return result . toString ( ) ; } | Convert a byte array into string binary representation with defined bit order and possibility to separate bytes . |
21,447 | public static List < JBBPAbstractField > fieldsAsList ( final JBBPAbstractField ... fields ) { final List < JBBPAbstractField > result = new ArrayList < > ( ) ; Collections . addAll ( result , fields ) ; return result ; } | Convert array of JBBP fields into a list . |
21,448 | public static String [ ] splitString ( final String str , final char splitChar ) { final int length = str . length ( ) ; final StringBuilder bulder = new StringBuilder ( Math . max ( 8 , length ) ) ; int counter = 1 ; for ( int i = 0 ; i < length ; i ++ ) { if ( str . charAt ( i ) == splitChar ) { counter ++ ; } } final String [ ] result = new String [ counter ] ; int position = 0 ; for ( int i = 0 ; i < length ; i ++ ) { final char chr = str . charAt ( i ) ; if ( chr == splitChar ) { result [ position ++ ] = bulder . toString ( ) ; bulder . setLength ( 0 ) ; } else { bulder . append ( chr ) ; } } if ( position < result . length ) { result [ position ] = bulder . toString ( ) ; } return result ; } | Split a string for a char used as the delimeter . |
21,449 | public static void assertNotNull ( final Object object , final String message ) { if ( object == null ) { throw new NullPointerException ( message == null ? "Object is null" : message ) ; } } | Check that an object is null and throw NullPointerException in the case . |
21,450 | public static String int2msg ( final int number ) { return number + " (0x" + Long . toHexString ( ( long ) number & 0xFFFFFFFFL ) . toUpperCase ( Locale . ENGLISH ) + ')' ; } | Convert an integer number into human readable hexadecimal format . |
21,451 | public static String normalizeFieldNameOrPath ( final String nameOrPath ) { assertNotNull ( nameOrPath , "Name of path must not be null" ) ; return nameOrPath . trim ( ) . toLowerCase ( Locale . ENGLISH ) ; } | Normalize field name or path . |
21,452 | public static byte [ ] str2UnicodeByteArray ( final JBBPByteOrder byteOrder , final String str ) { final byte [ ] result = new byte [ str . length ( ) << 1 ] ; int index = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { final int val = str . charAt ( i ) ; switch ( byteOrder ) { case BIG_ENDIAN : { result [ index ++ ] = ( byte ) ( val >> 8 ) ; result [ index ++ ] = ( byte ) val ; } break ; case LITTLE_ENDIAN : { result [ index ++ ] = ( byte ) val ; result [ index ++ ] = ( byte ) ( val >> 8 ) ; } break ; default : throw new Error ( "Unexpected byte order [" + byteOrder + ']' ) ; } } return result ; } | Convert chars of a string into a byte array contains the unicode codes . |
21,453 | public static byte [ ] reverseArray ( final byte [ ] nullableArrayToBeInverted ) { if ( nullableArrayToBeInverted != null && nullableArrayToBeInverted . length > 0 ) { int indexStart = 0 ; int indexEnd = nullableArrayToBeInverted . length - 1 ; while ( indexStart < indexEnd ) { final byte a = nullableArrayToBeInverted [ indexStart ] ; nullableArrayToBeInverted [ indexStart ] = nullableArrayToBeInverted [ indexEnd ] ; nullableArrayToBeInverted [ indexEnd ] = a ; indexStart ++ ; indexEnd -- ; } } return nullableArrayToBeInverted ; } | Reverse order of bytes in a byte array . |
21,454 | public static byte [ ] splitInteger ( final int value , final boolean valueInLittleEndian , final byte [ ] buffer ) { final byte [ ] result ; if ( buffer == null || buffer . length < 4 ) { result = new byte [ 4 ] ; } else { result = buffer ; } int tmpvalue = value ; if ( valueInLittleEndian ) { for ( int i = 0 ; i < 4 ; i ++ ) { result [ i ] = ( byte ) tmpvalue ; tmpvalue >>>= 8 ; } } else { for ( int i = 3 ; i >= 0 ; i -- ) { result [ i ] = ( byte ) tmpvalue ; tmpvalue >>>= 8 ; } } return result ; } | Split an integer value to bytes and returns as a byte array . |
21,455 | public static byte [ ] concat ( final byte [ ] ... arrays ) { int len = 0 ; for ( final byte [ ] arr : arrays ) { len += arr . length ; } final byte [ ] result = new byte [ len ] ; int pos = 0 ; for ( final byte [ ] arr : arrays ) { System . arraycopy ( arr , 0 , result , pos , arr . length ) ; pos += arr . length ; } return result ; } | Concatenate byte arrays into one byte array sequentially . |
21,456 | public static long reverseByteOrder ( long value , int numOfLowerBytesToInvert ) { if ( numOfLowerBytesToInvert < 1 || numOfLowerBytesToInvert > 8 ) { throw new IllegalArgumentException ( "Wrong number of bytes [" + numOfLowerBytesToInvert + ']' ) ; } long result = 0 ; int offsetInResult = ( numOfLowerBytesToInvert - 1 ) * 8 ; while ( numOfLowerBytesToInvert -- > 0 ) { final long thebyte = value & 0xFF ; value >>>= 8 ; result |= ( thebyte << offsetInResult ) ; offsetInResult -= 8 ; } return result ; } | Revert order for defined number of bytes in a value . |
21,457 | public static String double2str ( final double doubleValue , final int radix ) { if ( radix != 10 && radix != 16 ) { throw new IllegalArgumentException ( "Illegal radix [" + radix + ']' ) ; } final String result ; if ( radix == 16 ) { String converted = Double . toHexString ( doubleValue ) ; boolean minus = converted . startsWith ( "-" ) ; if ( minus ) { converted = converted . substring ( 1 ) ; } if ( converted . startsWith ( "0x" ) ) { converted = converted . substring ( 2 ) ; } result = ( minus ? '-' + converted : converted ) . toUpperCase ( Locale . ENGLISH ) ; } else { result = Double . toString ( doubleValue ) ; } return result ; } | Convert double value into string representation with defined radix base . |
21,458 | public static String float2str ( final float floatValue , final int radix ) { if ( radix != 10 && radix != 16 ) { throw new IllegalArgumentException ( "Illegal radix [" + radix + ']' ) ; } final String result ; if ( radix == 16 ) { String converted = Double . toHexString ( floatValue ) ; boolean minus = converted . startsWith ( "-" ) ; if ( minus ) { converted = converted . substring ( 1 ) ; } if ( converted . startsWith ( "0x" ) ) { converted = converted . substring ( 2 ) ; } result = ( minus ? '-' + converted : converted ) . toUpperCase ( Locale . ENGLISH ) ; } else { result = Double . toString ( floatValue ) ; } return result ; } | Convert float value into string representation with defined radix base . |
21,459 | public static String ulong2str ( final long ulongValue , final int radix , final char [ ] charBuffer ) { if ( radix < 2 || radix > 36 ) { throw new IllegalArgumentException ( "Illegal radix [" + radix + ']' ) ; } if ( ulongValue == 0 ) { return "0" ; } else { final String result ; if ( ulongValue > 0 ) { result = Long . toString ( ulongValue , radix ) . toUpperCase ( Locale . ENGLISH ) ; } else { final char [ ] buffer = charBuffer == null || charBuffer . length < 64 ? new char [ 64 ] : charBuffer ; int pos = buffer . length ; long topPart = ulongValue >>> 32 ; long bottomPart = ( ulongValue & 0xFFFFFFFFL ) + ( ( topPart % radix ) << 32 ) ; topPart /= radix ; while ( ( bottomPart | topPart ) > 0 ) { final int val = ( int ) ( bottomPart % radix ) ; buffer [ -- pos ] = ( char ) ( val < 10 ? '0' + val : 'A' + val - 10 ) ; bottomPart = ( bottomPart / radix ) + ( ( topPart % radix ) << 32 ) ; topPart /= radix ; } result = new String ( buffer , pos , buffer . length - pos ) ; } return result ; } } | Convert unsigned long value into string representation with defined radix base . |
21,460 | public static String ensureMinTextLength ( final String text , final int neededLen , final char ch , final int mode ) { final int number = neededLen - text . length ( ) ; if ( number <= 0 ) { return text ; } final StringBuilder result = new StringBuilder ( neededLen ) ; switch ( mode ) { case 0 : { for ( int i = 0 ; i < number ; i ++ ) { result . append ( ch ) ; } result . append ( text ) ; } break ; case 1 : { result . append ( text ) ; for ( int i = 0 ; i < number ; i ++ ) { result . append ( ch ) ; } } break ; default : { int leftField = number / 2 ; int rightField = number - leftField ; while ( leftField -- > 0 ) { result . append ( ch ) ; } result . append ( text ) ; while ( rightField -- > 0 ) { result . append ( ch ) ; } } break ; } return result . toString ( ) ; } | Extend text by chars to needed length . |
21,461 | public static String removeLeadingZeros ( final String str ) { String result = str ; if ( str != null && str . length ( ) != 0 ) { int startIndex = 0 ; while ( startIndex < str . length ( ) - 1 ) { final char ch = str . charAt ( startIndex ) ; if ( ch != '0' ) { break ; } startIndex ++ ; } if ( startIndex > 0 ) { result = str . substring ( startIndex ) ; } } return result ; } | Remove leading zeros from string . |
21,462 | public static String removeTrailingZeros ( final String str ) { String result = str ; if ( str != null && str . length ( ) != 0 ) { int endIndex = str . length ( ) ; while ( endIndex > 1 ) { final char ch = str . charAt ( endIndex - 1 ) ; if ( ch != '0' ) { break ; } endIndex -- ; } if ( endIndex < str . length ( ) ) { result = str . substring ( 0 , endIndex ) ; } } return result ; } | Remove trailing zeros from string . |
21,463 | public static boolean arrayStartsWith ( final byte [ ] array , final byte [ ] str ) { boolean result = false ; if ( array . length >= str . length ) { result = true ; int index = str . length ; while ( -- index >= 0 ) { if ( array [ index ] != str [ index ] ) { result = false ; break ; } } } return result ; } | Check that a byte array starts with some byte values . |
21,464 | public static boolean arrayEndsWith ( final byte [ ] array , final byte [ ] str ) { boolean result = false ; if ( array . length >= str . length ) { result = true ; int index = str . length ; int arrindex = array . length ; while ( -- index >= 0 ) { if ( array [ -- arrindex ] != str [ index ] ) { result = false ; break ; } } } return result ; } | Check that a byte array ends with some byte values . |
21,465 | private JBBPTokenizerException checkFieldName ( final String name , final int position ) { if ( name != null ) { final String normalized = JBBPUtils . normalizeFieldNameOrPath ( name ) ; if ( normalized . indexOf ( '.' ) >= 0 ) { return new JBBPTokenizerException ( "Field name must not contain '.' char" , position ) ; } if ( normalized . length ( ) > 0 ) { if ( normalized . equals ( "_" ) || normalized . equals ( "$$" ) || normalized . startsWith ( "$" ) || Character . isDigit ( normalized . charAt ( 0 ) ) ) { return new JBBPTokenizerException ( "'" + name + "' can't be field name" , position ) ; } for ( int i = 1 ; i < normalized . length ( ) ; i ++ ) { final char chr = normalized . charAt ( i ) ; if ( chr != '_' && ! Character . isLetterOrDigit ( chr ) ) { return new JBBPTokenizerException ( "Char '" + chr + "' not allowed in name" , position ) ; } } } } return null ; } | Check a field name |
21,466 | public static int findIndexForFieldPath ( final String fieldPath , final List < JBBPNamedFieldInfo > namedFields ) { final String normalized = JBBPUtils . normalizeFieldNameOrPath ( fieldPath ) ; int result = - 1 ; for ( int i = namedFields . size ( ) - 1 ; i >= 0 ; i -- ) { final JBBPNamedFieldInfo f = namedFields . get ( i ) ; if ( normalized . equals ( f . getFieldPath ( ) ) ) { result = i ; break ; } } return result ; } | Find a named field info index in a list for its path . |
21,467 | public static void assertFieldIsNotArrayOrInArray ( final JBBPNamedFieldInfo fieldToCheck , final List < JBBPNamedFieldInfo > namedFieldList , final byte [ ] compiledScript ) { if ( ( compiledScript [ fieldToCheck . getFieldOffsetInCompiledBlock ( ) ] & FLAG_ARRAY ) != 0 ) { throw new JBBPCompilationException ( "An Array field can't be used as array size [" + fieldToCheck . getFieldPath ( ) + ']' ) ; } if ( fieldToCheck . getFieldPath ( ) . indexOf ( '.' ) >= 0 ) { final String [ ] splittedFieldPath = JBBPUtils . splitString ( fieldToCheck . getFieldPath ( ) , '.' ) ; final StringBuilder fieldPath = new StringBuilder ( ) ; for ( int i = 0 ; i < splittedFieldPath . length - 1 ; i ++ ) { if ( fieldPath . length ( ) != 0 ) { fieldPath . append ( '.' ) ; } fieldPath . append ( splittedFieldPath [ i ] ) ; final JBBPNamedFieldInfo structureEnd = JBBPCompilerUtils . findForFieldPath ( fieldPath . toString ( ) , namedFieldList ) ; if ( ( compiledScript [ structureEnd . getFieldOffsetInCompiledBlock ( ) ] & FLAG_ARRAY ) != 0 ) { throw new JBBPCompilationException ( "Field from structure array can't be use as array size [" + fieldToCheck . getFieldPath ( ) + ';' + structureEnd . getFieldPath ( ) + ']' ) ; } } } } | Check a field in a compiled list defined by its named field info that the field is not an array and it is not inside a structure array . |
21,468 | private static int codeToUnary ( final int code ) { final int result ; switch ( code ) { case CODE_MINUS : result = CODE_UNARYMINUS ; break ; case CODE_ADD : result = CODE_UNARYPLUS ; break ; default : result = code ; break ; } return result ; } | Encode code of an operator to code of similar unary operator . |
21,469 | public static boolean hasExpressionOperators ( final String str ) { boolean result = false ; for ( final char chr : OPERATOR_FIRST_CHARS ) { if ( str . indexOf ( chr ) >= 0 ) { result = true ; break ; } } return result ; } | Check that a string has a char of operators . |
21,470 | private void assertUnaryOperator ( final String operator ) { if ( ! ( "+" . equals ( operator ) || "-" . equals ( operator ) || "~" . equals ( operator ) ) ) { throw new JBBPCompilationException ( "Wrong unary operator '" + operator + "' [" + this . expressionSource + ']' ) ; } } | Check that a string represents a unary operator . |
21,471 | public JavaSrcTextBuffer printf ( final String text , final Object ... args ) { this . buffer . append ( String . format ( text , args ) ) ; return this ; } | Formatted print . |
21,472 | public JavaSrcTextBuffer printLinesWithIndent ( final String text ) { final String [ ] splitted = text . split ( "\n" , - 1 ) ; for ( final String aSplitted : splitted ) { this . indent ( ) . println ( aSplitted ) ; } return this ; } | Parse string to lines and print each line with current indent |
21,473 | public Integer getArraySizeAsInt ( ) { if ( this . arraySize == null ) { throw new NullPointerException ( "Array size is not defined" ) ; } try { return Integer . valueOf ( this . arraySize . trim ( ) ) ; } catch ( NumberFormatException ex ) { return null ; } } | Get numeric representation of the array size . |
21,474 | public Object extractFieldValue ( final Object instance , final Field field ) { JBBPUtils . assertNotNull ( field , "Field must not be null" ) ; try { return ReflectUtils . makeAccessible ( field ) . get ( instance ) ; } catch ( Exception ex ) { throw new JBBPException ( "Can't extract value from field for exception" , ex ) ; } } | Auxiliary method to extract field value . |
21,475 | public JBBPClassInstantiator make ( final JBBPClassInstantiatorType type ) { JBBPUtils . assertNotNull ( type , "Type must not be null" ) ; String className = "com.igormaznitsa.jbbp.mapper.instantiators.JBBPSafeInstantiator" ; switch ( type ) { case AUTO : { final String customClassName = JBBPSystemProperty . PROPERTY_INSTANTIATOR_CLASS . getAsString ( null ) ; if ( customClassName == null ) { try { final Class < ? > unsafeclazz = Class . forName ( "sun.misc.Unsafe" ) ; unsafeclazz . getDeclaredField ( "theUnsafe" ) ; className = "com.igormaznitsa.jbbp.mapper.instantiators.JBBPUnsafeInstantiator" ; } catch ( ClassNotFoundException | NoSuchFieldException | SecurityException ex ) { } } else { className = customClassName ; } } break ; case SAFE : { className = "com.igormaznitsa.jbbp.mapper.instantiators.JBBPSafeInstantiator" ; } break ; case UNSAFE : { className = "com.igormaznitsa.jbbp.mapper.instantiators.JBBPUnsafeInstantiator" ; } break ; default : throw new Error ( "Unexpected type, contact developer! [" + type + ']' ) ; } return ( JBBPClassInstantiator ) ReflectUtils . newInstanceForClassName ( className ) ; } | Make an instantiator for defined type . |
21,476 | public void writeShort ( final int value , final JBBPByteOrder byteOrder ) throws IOException { if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { this . write ( value >>> 8 ) ; this . write ( value ) ; } else { this . write ( value ) ; this . write ( value >>> 8 ) ; } } | Write a signed short value into the output stream . |
21,477 | public void writeInt ( final int value , final JBBPByteOrder byteOrder ) throws IOException { if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { this . writeShort ( value >>> 16 , byteOrder ) ; this . writeShort ( value , byteOrder ) ; } else { this . writeShort ( value , byteOrder ) ; this . writeShort ( value >>> 16 , byteOrder ) ; } } | Write an integer value into the output stream . |
21,478 | public void writeFloat ( final float value , final JBBPByteOrder byteOrder ) throws IOException { final int intValue = Float . floatToIntBits ( value ) ; if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { this . writeShort ( intValue >>> 16 , byteOrder ) ; this . writeShort ( intValue , byteOrder ) ; } else { this . writeShort ( intValue , byteOrder ) ; this . writeShort ( intValue >>> 16 , byteOrder ) ; } } | Write an float value into the output stream . |
21,479 | public void writeLong ( final long value , final JBBPByteOrder byteOrder ) throws IOException { if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { this . writeInt ( ( int ) ( value >>> 32 ) , byteOrder ) ; this . writeInt ( ( int ) value , byteOrder ) ; } else { this . writeInt ( ( int ) value , byteOrder ) ; this . writeInt ( ( int ) ( value >>> 32 ) , byteOrder ) ; } } | Write a long value into the output stream . |
21,480 | public void writeDouble ( final double value , final JBBPByteOrder byteOrder ) throws IOException { final long longValue = Double . doubleToLongBits ( value ) ; if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { this . writeInt ( ( int ) ( longValue >>> 32 ) , byteOrder ) ; this . writeInt ( ( int ) longValue , byteOrder ) ; } else { this . writeInt ( ( int ) longValue , byteOrder ) ; this . writeInt ( ( int ) ( longValue >>> 32 ) , byteOrder ) ; } } | Write a double value into the output stream . |
21,481 | public void writeBits ( final int value , final JBBPBitNumber bitNumber ) throws IOException { if ( this . bitBufferCount == 0 && bitNumber == JBBPBitNumber . BITS_8 ) { write ( value ) ; } else { final int initialMask ; int mask ; initialMask = 1 ; mask = initialMask << this . bitBufferCount ; int accum = value ; int i = bitNumber . getBitNumber ( ) ; while ( i > 0 ) { this . bitBuffer = this . bitBuffer | ( ( accum & 1 ) == 0 ? 0 : mask ) ; accum >>= 1 ; mask = mask << 1 ; i -- ; this . bitBufferCount ++ ; if ( this . bitBufferCount == 8 ) { this . bitBufferCount = 0 ; writeByte ( this . bitBuffer ) ; mask = initialMask ; this . bitBuffer = 0 ; } } } } | Write bits into the output stream . |
21,482 | public void align ( final long alignByteNumber ) throws IOException { if ( this . bitBufferCount > 0 ) { this . writeBits ( 0 , JBBPBitNumber . decode ( 8 - this . bitBufferCount ) ) ; } if ( alignByteNumber > 0 ) { long padding = ( alignByteNumber - ( this . byteCounter % alignByteNumber ) ) % alignByteNumber ; while ( padding > 0 ) { this . out . write ( 0 ) ; this . byteCounter ++ ; padding -- ; } } } | Write padding bytes to align the stream counter for the border . |
21,483 | private void writeByte ( int value ) throws IOException { if ( this . msb0 ) { value = JBBPUtils . reverseBitsInByte ( ( byte ) value ) & 0xFF ; } this . out . write ( value ) ; this . byteCounter ++ ; } | Inside method to write a byte into wrapped stream . |
21,484 | public void writeBytes ( final byte [ ] array , final int length , final JBBPByteOrder byteOrder ) throws IOException { if ( byteOrder == JBBPByteOrder . LITTLE_ENDIAN ) { int i = length < 0 ? array . length - 1 : length - 1 ; while ( i >= 0 ) { this . write ( array [ i -- ] ) ; } } else { this . write ( array , 0 , length < 0 ? array . length : length ) ; } } | Write number of items from byte array into stream |
21,485 | public Object mapTo ( final Object objectToMap , final JBBPMapperCustomFieldProcessor customFieldProcessor ) { return JBBPMapper . map ( this , objectToMap , customFieldProcessor ) ; } | Map the structure fields to object fields . |
21,486 | public String getExtraDataExpression ( ) { String result = null ; if ( hasExpressionAsExtraData ( ) ) { result = this . extraData . substring ( 1 , this . extraData . length ( ) - 1 ) ; } return result ; } | Extract expression for extra data . |
21,487 | public void putField ( final JBBPNumericField field ) { JBBPUtils . assertNotNull ( field , "Field must not be null" ) ; final JBBPNamedFieldInfo fieldName = field . getNameInfo ( ) ; JBBPUtils . assertNotNull ( fieldName , "Field name info must not be null" ) ; this . fieldMap . put ( fieldName , field ) ; } | Put a numeric field into map . |
21,488 | public JBBPNumericField remove ( final JBBPNamedFieldInfo nameInfo ) { JBBPUtils . assertNotNull ( nameInfo , "Name info must not be null" ) ; return this . fieldMap . remove ( nameInfo ) ; } | Remove a field for its field name info descriptor . |
21,489 | public JBBPNumericField findForFieldOffset ( final int offset ) { JBBPNumericField result = null ; for ( final Map . Entry < JBBPNamedFieldInfo , JBBPNumericField > f : fieldMap . entrySet ( ) ) { if ( f . getKey ( ) . getFieldOffsetInCompiledBlock ( ) == offset ) { result = f . getValue ( ) ; break ; } } return result ; } | Find a registered field for its field offset in compiled script . |
21,490 | public int getExternalFieldValue ( final String externalFieldName , final JBBPCompiledBlock compiledBlock , final JBBPIntegerValueEvaluator evaluator ) { final String normalizedName = JBBPUtils . normalizeFieldNameOrPath ( externalFieldName ) ; if ( this . externalValueProvider == null ) { throw new JBBPEvalException ( "Request for '" + externalFieldName + "' but there is not any value provider" , evaluator ) ; } else { return this . externalValueProvider . provideArraySize ( normalizedName , this , compiledBlock ) ; } } | Ask the registered external value provider for a field value . |
21,491 | private static Object readFieldValue ( final Object obj , final Field field ) { try { return field . get ( obj ) ; } catch ( Exception ex ) { throw new JBBPException ( "Can't get value from field [" + field + ']' , ex ) ; } } | Inside auxiliary method to read object field value . |
21,492 | protected void onFieldCustom ( final Object obj , final Field field , final Bin annotation , final Object customFieldProcessor , final Object value ) { } | Notification about custom field . |
21,493 | protected void onFieldBits ( final Object obj , final Field field , final Bin annotation , final JBBPBitNumber bitNumber , final int value ) { } | Notification about bit field . |
21,494 | public void resetInsideClassCache ( ) { final Map < Class < ? > , Field [ ] > fieldz = cachedClasses ; if ( fieldz != null ) { synchronized ( fieldz ) { fieldz . clear ( ) ; } } } | Inside JBBPOut . Bin command creates cached list of fields of a saved class the method allows to reset the inside cache . |
21,495 | public static JBBPTextWriter makeStrWriter ( ) { final String lineSeparator = System . setProperty ( "line.separator" , "\n" ) ; return new JBBPTextWriter ( new StringWriter ( ) , JBBPByteOrder . BIG_ENDIAN , lineSeparator , 16 , "0x" , "." , ";" , "~" , "," ) ; } | Auxiliary method allows to build writer over StringWriter with system - depended next line and hex radix . The Method allows fast instance create . |
21,496 | private void ensureValueMode ( ) throws IOException { switch ( this . mode ) { case MODE_START_LINE : { changeMode ( MODE_VALUES ) ; for ( final Extra e : extras ) { e . onBeforeFirstValue ( this ) ; } writeIndent ( ) ; this . write ( this . prefixFirtValueAtLine ) ; } break ; case MODE_COMMENTS : { this . BR ( ) ; writeIndent ( ) ; changeMode ( MODE_VALUES ) ; for ( final Extra e : extras ) { e . onBeforeFirstValue ( this ) ; } this . write ( this . prefixFirtValueAtLine ) ; } break ; case MODE_VALUES : break ; default : throw new Error ( "Unexpected state" ) ; } } | Ensure the value mode . |
21,497 | private void ensureCommentMode ( ) throws IOException { switch ( this . mode ) { case MODE_START_LINE : writeIndent ( ) ; this . prevLineCommentsStartPosition = this . linePosition ; this . write ( this . prefixComment ) ; changeMode ( MODE_COMMENTS ) ; break ; case MODE_VALUES : { this . prevLineCommentsStartPosition = this . linePosition ; this . write ( this . prefixComment ) ; changeMode ( MODE_COMMENTS ) ; } break ; case MODE_COMMENTS : { BR ( ) ; writeIndent ( ) ; while ( this . linePosition < this . prevLineCommentsStartPosition ) { this . write ( ' ' ) ; } this . write ( this . prefixComment ) ; } break ; default : throw new Error ( "Unexpected state" ) ; } } | Ensure the comment mode . |
21,498 | private void printValueString ( final String value ) throws IOException { if ( this . valuesLineCounter > 0 && this . valueSeparator . length ( ) > 0 ) { this . write ( this . valueSeparator ) ; } if ( this . prefixValue . length ( ) > 0 ) { this . write ( this . prefixValue ) ; } this . write ( value ) ; if ( this . postfixValue . length ( ) > 0 ) { this . write ( this . postfixValue ) ; } this . valuesLineCounter ++ ; if ( this . maxValuesPerLine > 0 && this . valuesLineCounter >= this . maxValuesPerLine ) { for ( final Extra e : this . extras ) { e . onReachedMaxValueNumberForLine ( this ) ; } ensureNewLineMode ( ) ; } } | Print a value represented by its string . |
21,499 | public JBBPTextWriter Str ( final String ... str ) throws IOException { JBBPUtils . assertNotNull ( str , "String must not be null" ) ; final String oldPrefix = this . prefixValue ; final String oldPostfix = this . postfixValue ; this . prefixValue = "" ; this . postfixValue = "" ; for ( final String s : str ) { ensureValueMode ( ) ; printValueString ( s == null ? "<NULL>" : s ) ; } this . prefixValue = oldPrefix ; this . postfixValue = oldPostfix ; return this ; } | Print string values . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.