idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
300
public static byte [ ] toByteArray ( final ZipFile zipFile , final String path ) throws IOException { final InputStream in = findInputStreamForResource ( zipFile , path ) ; byte [ ] result = null ; if ( in != null ) { try { result = IOUtils . toByteArray ( in ) ; } finally { IOUtils . closeQuietly ( in ) ; } } return result ; }
Read who ; e zip item into byte array .
301
public static Document loadXmlDocument ( final InputStream inStream , final String charset , final boolean autoClose ) throws SAXException , IOException , ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; try { factory . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; } catch ( final ParserConfigurationException ex ) { LOGGER . error ( "Can't set feature for XML parser : " + ex . getMessage ( ) , ex ) ; throw new SAXException ( "Can't set flag to use security processing of XML file" ) ; } try { factory . setFeature ( "http://apache.org/xml/features/nonvalidating/load-external-dtd" , false ) ; factory . setFeature ( "http://apache.org/xml/features/validation/schema" , false ) ; } catch ( final ParserConfigurationException ex ) { LOGGER . warn ( "Can't set some features for XML parser : " + ex . getMessage ( ) ) ; } factory . setIgnoringComments ( true ) ; factory . setValidating ( false ) ; final DocumentBuilder builder = factory . newDocumentBuilder ( ) ; final Document document ; try { final InputStream stream ; if ( charset == null ) { stream = inStream ; } else { stream = new ByteArrayInputStream ( IOUtils . toString ( inStream , charset ) . getBytes ( "UTF-8" ) ) ; } document = builder . parse ( stream ) ; } finally { if ( autoClose ) { IOUtils . closeQuietly ( inStream ) ; } } return document ; }
Load and parse XML document from input stream .
302
public static Element findFirstElement ( final Element node , final String elementName ) { Element result = null ; for ( final Element l : Utils . findDirectChildrenForName ( node , elementName ) ) { result = l ; break ; } return result ; }
Get first direct child for name .
303
public static List < Element > findDirectChildrenForName ( final Element element , final String childElementname ) { final List < Element > resultList = new ArrayList < Element > ( ) ; final NodeList list = element . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { final Node node = list . item ( i ) ; if ( element . equals ( node . getParentNode ( ) ) && node instanceof Element && childElementname . equals ( node . getNodeName ( ) ) ) { resultList . add ( ( Element ) node ) ; } } return resultList ; }
Find all direct children with defined name .
304
public static int getMaxImageSize ( ) { int result = MAX_IMAGE_SIDE_SIZE_IN_PIXELS ; try { final String defined = System . getProperty ( PROPERTY_MAX_EMBEDDED_IMAGE_SIDE_SIZE ) ; if ( defined != null ) { LOGGER . info ( "Detected redefined max size for embedded image side : " + defined ) ; result = Math . max ( 8 , Integer . parseInt ( defined . trim ( ) ) ) ; } } catch ( NumberFormatException ex ) { LOGGER . error ( "Error during image size decoding : " , ex ) ; } return result ; }
Get max image size .
305
public static String rescaleImageAndEncodeAsBase64 ( final InputStream in , final int maxSize ) throws IOException { final Image image = ImageIO . read ( in ) ; String result = null ; if ( image != null ) { result = rescaleImageAndEncodeAsBase64 ( image , maxSize ) ; } return result ; }
Load and encode image into Base64 .
306
public static String rescaleImageAndEncodeAsBase64 ( final File file , final int maxSize ) throws IOException { final Image image = ImageIO . read ( file ) ; if ( image == null ) { throw new IllegalArgumentException ( "Can't load image file : " + file ) ; } return rescaleImageAndEncodeAsBase64 ( image , maxSize ) ; }
Load and encode image into Base64 from file .
307
public static RenderQuality getDefaultRenderQialityForOs ( ) { RenderQuality result = RenderQuality . DEFAULT ; if ( SystemUtils . IS_OS_MAC || SystemUtils . IS_OS_WINDOWS ) { result = RenderQuality . QUALITY ; } return result ; }
Get default render quality for host OS .
308
public MMDPrintOptions setScaleType ( final ScaleType scaleOption ) { this . scaleOption = Assertions . assertNotNull ( scaleOption ) ; return this ; }
Set the selected scale option .
309
public < T > T getSessionObject ( final String key , final Class < T > klazz , final T def ) { this . lock ( ) ; try { T result = klazz . cast ( this . sessionObjects . get ( key ) ) ; return result == null ? def : result ; } finally { this . unlock ( ) ; } }
Get saved session object . Object is presented and saved only for the current panel and only in memory .
310
public void putSessionObject ( final String key , final Object obj ) { this . lock ( ) ; try { if ( obj == null ) { this . sessionObjects . remove ( key ) ; } else { this . sessionObjects . put ( key , obj ) ; } } finally { this . unlock ( ) ; } }
Put session object for key .
311
public void executeModelJobs ( final ModelJob ... jobs ) { Utils . safeSwingCall ( new Runnable ( ) { public void run ( ) { for ( final ModelJob j : jobs ) { try { if ( ! j . doChangeModel ( model ) ) { break ; } } catch ( Exception ex ) { LOGGER . error ( "Errot during job execution" , ex ) ; } } fireNotificationMindMapChanged ( true ) ; } } ) ; }
Safe Swing thread execution sequence of some jobs over model with model changed notification in the end
312
public void setModel ( final MindMap model , final boolean notifyModelChangeListeners ) { this . lock ( ) ; try { if ( this . elementUnderEdit != null ) { Utils . safeSwingBlockingCall ( new Runnable ( ) { public void run ( ) { endEdit ( false ) ; } } ) ; } final List < int [ ] > selectedPaths = new ArrayList < int [ ] > ( ) ; for ( final Topic t : this . selectedTopics ) { selectedPaths . add ( t . getPositionPath ( ) ) ; } this . selectedTopics . clear ( ) ; final MindMap oldModel = this . model ; this . model = assertNotNull ( "Model must not be null" , model ) ; for ( final PanelAwarePlugin p : MindMapPluginRegistry . getInstance ( ) . findFor ( PanelAwarePlugin . class ) ) { p . onPanelModelChange ( this , oldModel , this . model ) ; } doLayout ( ) ; revalidate ( ) ; boolean selectionChanged = false ; for ( final int [ ] posPath : selectedPaths ) { final Topic topic = this . model . findForPositionPath ( posPath ) ; if ( topic == null ) { selectionChanged = true ; } else if ( ! MindMapUtils . isHidden ( topic ) ) { this . selectedTopics . add ( topic ) ; } } if ( selectionChanged ) { fireNotificationSelectionChanged ( ) ; } repaint ( ) ; } finally { this . unlock ( ) ; if ( notifyModelChangeListeners ) { fireNotificationMindMapChanged ( true ) ; } } }
Set model for the panel allows to notify listeners optionally .
313
public boolean lockIfNotDisposed ( ) { boolean result = false ; if ( this . panelLocker != null ) { this . panelLocker . lock ( ) ; if ( this . disposed . get ( ) ) { this . panelLocker . unlock ( ) ; } else { result = true ; } } return result ; }
Try lock the panel if it is not disposed .
314
public MindMapPanel lock ( ) { if ( this . panelLocker != null ) { this . panelLocker . lock ( ) ; if ( this . isDisposed ( ) ) { this . panelLocker . unlock ( ) ; throw new IllegalStateException ( "Mind map has been already disposed!" ) ; } } return this ; }
Lock the panel .
315
public boolean copyTopicsToClipboard ( final boolean cut , final Topic ... topics ) { boolean result = false ; if ( this . lockIfNotDisposed ( ) ) { try { if ( topics . length > 0 ) { final Clipboard clipboard = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) ; clipboard . setContents ( new MMDTopicsTransferable ( topics ) , this ) ; if ( cut ) { deleteTopics ( true , ensureNoRootInArray ( topics ) ) ; } result = true ; } } finally { this . unlock ( ) ; } } return result ; }
Create transferable topic list in system clipboard .
316
public boolean pasteTopicsFromClipboard ( ) { boolean result = false ; if ( this . lockIfNotDisposed ( ) ) { try { final Clipboard clipboard = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) ; if ( Utils . isDataFlavorAvailable ( clipboard , MMDTopicsTransferable . MMD_DATA_FLAVOR ) ) { try { final NBMindMapTopicsContainer container = ( NBMindMapTopicsContainer ) clipboard . getData ( MMDTopicsTransferable . MMD_DATA_FLAVOR ) ; if ( container != null && ! container . isEmpty ( ) ) { final Topic [ ] selected = this . getSelectedTopics ( ) ; if ( selected . length > 0 ) { for ( final Topic s : selected ) { for ( final Topic t : container . getTopics ( ) ) { final Topic newTopic = new Topic ( this . model , t , true ) ; newTopic . removeExtra ( Extra . ExtraType . TOPIC ) ; newTopic . moveToNewParent ( s ) ; MindMapUtils . ensureVisibility ( newTopic ) ; } } } doLayout ( ) ; revalidate ( ) ; repaint ( ) ; fireNotificationMindMapChanged ( true ) ; result = true ; } } catch ( final Exception ex ) { LOGGER . error ( "Can't get clipboard data" , ex ) ; } } else if ( Utils . isDataFlavorAvailable ( clipboard , DataFlavor . stringFlavor ) ) { try { final int MAX_TEXT_LEN = 96 ; String clipboardText = ( String ) clipboard . getContents ( null ) . getTransferData ( DataFlavor . stringFlavor ) ; if ( clipboardText != null ) { clipboardText = clipboardText . trim ( ) ; final String topicText ; final String extraNoteText ; if ( clipboardText . length ( ) > MAX_TEXT_LEN ) { topicText = clipboardText . substring ( 0 , MAX_TEXT_LEN ) + "..." ; extraNoteText = clipboardText ; } else { topicText = clipboardText ; extraNoteText = null ; } final Topic [ ] selectedTopics = this . getSelectedTopics ( ) ; if ( selectedTopics . length > 0 ) { for ( final Topic s : selectedTopics ) { final Topic newTopic ; if ( extraNoteText == null ) { newTopic = new Topic ( this . model , s , topicText ) ; } else { newTopic = new Topic ( this . model , s , topicText , new ExtraNote ( extraNoteText ) ) ; } MindMapUtils . ensureVisibility ( newTopic ) ; } doLayout ( ) ; revalidate ( ) ; repaint ( ) ; fireNotificationMindMapChanged ( true ) ; result = true ; } } } catch ( Exception ex ) { LOGGER . error ( "Can't get clipboard text" , ex ) ; } } } finally { this . unlock ( ) ; } } return result ; }
Paste topics from clipboard to currently selected ones .
317
public static Topic [ ] removeSuccessorsAndDuplications ( final Topic ... topics ) { final List < Topic > result = new ArrayList < Topic > ( ) ; for ( final Topic t : topics ) { final Iterator < Topic > iterator = result . iterator ( ) ; while ( iterator . hasNext ( ) ) { final Topic listed = iterator . next ( ) ; if ( listed == t || listed . hasAncestor ( t ) ) { iterator . remove ( ) ; } } result . add ( t ) ; } return result . toArray ( new Topic [ result . size ( ) ] ) ; }
Remove duplications and successors for presented topics in array .
318
public static Pattern string2pattern ( final String text , final int patternFlags ) { final StringBuilder result = new StringBuilder ( ) ; for ( final char c : text . toCharArray ( ) ) { result . append ( "\\u" ) ; final String code = Integer . toHexString ( c ) . toUpperCase ( Locale . ENGLISH ) ; result . append ( "0000" , 0 , 4 - code . length ( ) ) . append ( code ) ; } return Pattern . compile ( result . toString ( ) , patternFlags ) ; }
Create pattern from string .
319
private static String lookupApiKey ( Properties props ) { String apiKey = null ; if ( props . containsKey ( Config . TD_LOGGER_API_KEY ) ) { apiKey = props . getProperty ( Config . TD_LOGGER_API_KEY ) ; props . setProperty ( Config . TD_API_KEY , apiKey ) ; } return apiKey ; }
Define order for API key lookup . 1 . lookup props s td . logger . api . key
320
private static String lookupHost ( Properties props ) { String host = null ; if ( props . containsKey ( Config . TD_LOGGER_API_SERVER_HOST ) ) { host = props . getProperty ( Config . TD_LOGGER_API_SERVER_HOST ) ; } if ( host == null ) { host = Config . TD_LOGGER_API_SERVER_HOST_DEFAULT ; } props . setProperty ( Config . TD_API_SERVER_HOST , host ) ; return host ; }
Define order for hostname lookup . 1 . lookup props s td . logger . api . server . host
321
private static String lookupPort ( Properties props ) { String port = null ; if ( props . containsKey ( Config . TD_LOGGER_API_SERVER_PORT ) ) { port = props . getProperty ( Config . TD_LOGGER_API_SERVER_PORT ) ; } if ( port == null ) { port = Config . TD_LOGGER_API_SERVER_PORT_DEFAULT ; } props . setProperty ( Config . TD_API_SERVER_PORT , port ) ; return port ; }
Define order for port num lookup . 1 . lookup props s td . logger . api . server . port
322
private static String lookupScheme ( Properties props ) { String scheme = null ; if ( props . containsKey ( Config . TD_LOGGER_API_SERVER_SCHEME ) ) { scheme = props . getProperty ( Config . TD_LOGGER_API_SERVER_SCHEME ) ; } if ( scheme == null ) { scheme = Config . TD_LOGGER_API_SERVER_SCHEME_DEFAULT ; } props . setProperty ( Config . TD_CK_API_SERVER_SCHEME , scheme ) ; return scheme ; }
Define order for scheme lookup . 1 . lookup props s td . logger . api . server . scheme
323
public static OptionalHeader newInstance ( byte [ ] headerbytes , long offset ) throws IOException { OptionalHeader header = new OptionalHeader ( headerbytes , offset ) ; header . read ( ) ; return header ; }
Creates and returns a new instance of the optional header .
324
public Optional < DataDirEntry > maybeGetDataDirEntry ( DataDirectoryKey key ) { return Optional . fromNullable ( dataDirectory . get ( key ) ) ; }
Returns the optional data directory entry for the given key or absent if entry doesn t exist .
325
public Optional < StandardField > maybeGetStandardFieldEntry ( StandardFieldEntryKey key ) { return Optional . fromNullable ( standardFields . get ( key ) ) ; }
Returns maybe the standard field entry for the given key .
326
public StandardField getStandardFieldEntry ( StandardFieldEntryKey key ) { if ( ! standardFields . containsKey ( key ) ) { throw new IllegalArgumentException ( "standard field " + key + " does not exist!" ) ; } return standardFields . get ( key ) ; }
Returns the standard field entry for the given key .
327
public String getDataDirInfo ( ) { StringBuilder b = new StringBuilder ( ) ; for ( DataDirEntry entry : dataDirectory . values ( ) ) { b . append ( entry . getKey ( ) + ": " + entry . getVirtualAddress ( ) + "(0x" + Long . toHexString ( entry . getVirtualAddress ( ) ) + ")/" + entry . getDirectorySize ( ) + "(0x" + Long . toHexString ( entry . getDirectorySize ( ) ) + ")" + NL ) ; } return b . toString ( ) ; }
Returns a description of all data directories .
328
public String getWindowsSpecificInfo ( ) { StringBuilder b = new StringBuilder ( ) ; for ( StandardField entry : windowsFields . values ( ) ) { long value = entry . getValue ( ) ; HeaderKey key = entry . getKey ( ) ; String description = entry . getDescription ( ) ; if ( key . equals ( IMAGE_BASE ) ) { b . append ( description + ": " + value + " (0x" + Long . toHexString ( value ) + "), " + getImageBaseDescription ( value ) + NL ) ; } else if ( key . equals ( SUBSYSTEM ) ) { b . append ( description + ": " + getSubsystem ( ) . getDescription ( ) + NL ) ; } else if ( key . equals ( DLL_CHARACTERISTICS ) ) { b . append ( NL + description + ": " + NL ) ; b . append ( getCharacteristicsInfo ( value ) + NL ) ; } else { b . append ( description + ": " + value + " (0x" + Long . toHexString ( value ) + ")" + NL ) ; if ( key . equals ( NUMBER_OF_RVA_AND_SIZES ) ) { directoryNr = value ; } } } return b . toString ( ) ; }
Returns a string with description of the windows specific header fields . Magic number must be set .
329
public long getRelocatedImageBase ( ) { long imageBase = get ( WindowsEntryKey . IMAGE_BASE ) ; long sizeOfImage = get ( WindowsEntryKey . SIZE_OF_IMAGE ) ; if ( imageBase + sizeOfImage >= 0x80000000L || imageBase == 0L ) { return 0x10000L ; } return imageBase ; }
Checks if image base is too large or zero and relocates it accordingly . Otherwise the usual image base is returned .
330
public List < DllCharacteristic > getDllCharacteristics ( ) { long value = get ( DLL_CHARACTERISTICS ) ; List < DllCharacteristic > dllChs = DllCharacteristic . getAllFor ( value ) ; return dllChs ; }
Returns a list of the DllCharacteristics that are set in the file .
331
public long getAdjustedFileAlignment ( ) { long fileAlign = get ( FILE_ALIGNMENT ) ; if ( isLowAlignmentMode ( ) ) { return 1 ; } if ( fileAlign < 512 ) { fileAlign = 512 ; } if ( fileAlign % 512 != 0 ) { long rest = fileAlign % 512 ; fileAlign += ( 512 - rest ) ; } return fileAlign ; }
Adjusts the file alignment to low alignment mode if necessary .
332
public boolean isLowAlignmentMode ( ) { long fileAlign = get ( FILE_ALIGNMENT ) ; long sectionAlign = get ( SECTION_ALIGNMENT ) ; return 1 <= fileAlign && fileAlign == sectionAlign && fileAlign <= 0x800 ; }
Determines if the file is in low alignment mode .
333
public boolean isStandardAlignmentMode ( ) { long fileAlign = get ( FILE_ALIGNMENT ) ; long sectionAlign = get ( SECTION_ALIGNMENT ) ; return 0x200 <= fileAlign && fileAlign <= sectionAlign && 0x1000 <= sectionAlign ; }
Determines if the file is in standard alignment mode .
334
private void read ( ) { final int key = 0 ; final int description = 1 ; final int offset = 2 ; final int length = 3 ; SpecificationFormat format = new SpecificationFormat ( key , description , offset , length ) ; try { data = IOUtil . readHeaderEntries ( COFFHeaderKey . class , format , COFF_SPEC_FILE , headerbytes , getOffset ( ) ) ; } catch ( IOException e ) { logger . error ( "unable to read coff specification: " + e . getMessage ( ) ) ; } }
Reads the header s fields .
335
public MachineType getMachineType ( ) { long value = get ( MACHINE ) ; try { return MachineType . getForValue ( value ) ; } catch ( IllegalArgumentException e ) { logger . error ( "Unable to resolve machine type for value: " + value ) ; return MachineType . UNKNOWN ; } }
Returns the enum that denotes the machine type .
336
public static COFFFileHeader newInstance ( byte [ ] headerbytes , long offset ) { COFFFileHeader header = new COFFFileHeader ( headerbytes , offset ) ; header . read ( ) ; return header ; }
Creates an instance of the COFF File Header based on headerbytes and offset .
337
public byte [ ] getBytes ( ) throws IOException { if ( sectionbytes . isPresent ( ) ) { return sectionbytes . get ( ) . clone ( ) ; } loadSectionBytes ( ) ; byte [ ] result = sectionbytes . get ( ) ; assert result != null ; return result ; }
Returns the section bytes . The file is read if the bytes aren t already loaded .
338
private void loadSectionBytes ( ) throws IOException { Preconditions . checkState ( size == ( int ) size , "section is too large to dump into byte array" ) ; try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { raf . seek ( offset ) ; byte [ ] bytes = new byte [ ( int ) size ] ; raf . read ( bytes ) ; sectionbytes = Optional . of ( bytes ) ; } }
Loads the section bytes from the file using offset and size .
339
public VisualizerBuilder setColor ( ColorableItem key , Color color ) { settings . colorMap . put ( key , color ) ; return this ; }
Sets the color for a colorable item .
340
public static void dumpLocationToFile ( PhysicalLocation loc , File inFile , File outFile ) throws IOException { Preconditions . checkArgument ( ! outFile . exists ( ) ) ; Preconditions . checkArgument ( inFile . exists ( ) , inFile . isFile ( ) ) ; final int BUFFER_SIZE = 2048 ; try ( RandomAccessFile raf = new RandomAccessFile ( inFile , "r" ) ; FileOutputStream out = new FileOutputStream ( outFile ) ) { byte [ ] buffer ; long remainingBytes = loc . size ( ) ; long offset = loc . from ( ) ; while ( remainingBytes >= BUFFER_SIZE ) { buffer = loadBytesSafely ( offset , BUFFER_SIZE , raf ) ; out . write ( buffer ) ; remainingBytes -= BUFFER_SIZE ; offset += BUFFER_SIZE ; } if ( remainingBytes > 0 ) { buffer = loadBytesSafely ( offset , ( int ) remainingBytes , raf ) ; out . write ( buffer ) ; } } }
Dumps the given part of the inFile to outFile . The part to dump is represented by loc . This will read safely from inFile which means locations outside of inFile are written as zero bytes to outFile .
341
public static byte [ ] loadBytesSafely ( long offset , int length , RandomAccessFile raf ) throws IOException { Preconditions . checkArgument ( length >= 0 ) ; if ( offset < 0 ) return new byte [ 0 ] ; raf . seek ( offset ) ; int readsize = length ; if ( readsize + offset > raf . length ( ) ) { readsize = ( int ) ( raf . length ( ) - offset ) ; } if ( readsize < 0 ) { readsize = 0 ; } byte [ ] bytes = new byte [ readsize ] ; raf . readFully ( bytes ) ; bytes = padBytes ( bytes , length ) ; assert bytes . length == length ; return bytes ; }
Loads the bytes at the offset into a byte array with the given length using the raf . If EOF the byte array is zero padded . If offset < 0 it will return a zero sized array .
342
private static byte [ ] padBytes ( byte [ ] bytes , int length ) { byte [ ] padded = new byte [ length ] ; for ( int i = 0 ; i < bytes . length ; i ++ ) { padded [ i ] = bytes [ i ] ; } return padded ; }
Return array with length size if length is greater than the previous size the array is zero - padded at the end .
343
public static byte [ ] loadBytes ( long offset , int length , RandomAccessFile raf ) throws IOException { if ( length < 0 ) { length = 0 ; logger . error ( "Negative length: " + length ) ; } if ( offset < 0 ) { offset = 0 ; logger . error ( "Negative offset: " + offset ) ; } offset = Math . min ( offset , raf . length ( ) ) ; long endOffset = Math . min ( offset + length , raf . length ( ) ) ; length = ( int ) ( endOffset - offset ) ; raf . seek ( offset ) ; byte [ ] bytes = new byte [ length ] ; raf . readFully ( bytes ) ; return bytes ; }
Loads the bytes at the offset into a byte array with the given length using the raf .
344
public static List < SymbolDescription > readSymbolDescriptions ( ) throws IOException { String filename = "importcategories.txt" ; List < SymbolDescription > list = new ArrayList < > ( ) ; List < String [ ] > lines = readArray ( filename ) ; String category = "" ; String subCategory = null ; for ( String [ ] array : lines ) { if ( array . length > 0 ) { String mainItem = array [ 0 ] ; if ( mainItem . startsWith ( "[" ) ) { category = mainItem ; subCategory = null ; } else if ( mainItem . startsWith ( "<" ) ) { subCategory = mainItem ; } else { String description = null ; if ( array . length > 1 ) { description = array [ 1 ] ; } list . add ( new SymbolDescription ( mainItem , Optional . fromNullable ( description ) , category , Optional . fromNullable ( subCategory ) ) ) ; } } } return list ; }
Reads a list of symbol descriptions
345
public static MSDOSHeader newInstance ( byte [ ] headerbytes , long peSigOffset ) throws IOException { MSDOSHeader header = new MSDOSHeader ( headerbytes , peSigOffset ) ; header . read ( ) ; return header ; }
Creates and returns an instance of the MSDOSHeader with the given bytes and the file offset of the PE signature .
346
public void read ( ) throws IOException { try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { throwIf ( file . length ( ) < PE_OFFSET_LOCATION ) ; byte [ ] offsetBytes = loadBytesSafely ( PE_OFFSET_LOCATION , PE_OFFSET_LOCATION_SIZE , raf ) ; peOffset = Optional . of ( ( long ) bytesToInt ( offsetBytes ) ) ; throwIf ( file . length ( ) < peOffset . get ( ) || peOffset . get ( ) < 0 ) ; byte [ ] peSigVal = loadBytesSafely ( peOffset . get ( ) , PE_SIG . length , raf ) ; for ( int i = 0 ; i < PE_SIG . length ; i ++ ) { throwIf ( peSigVal [ i ] != PE_SIG [ i ] ) ; } } }
Reads the PE signature and sets the peOffset .
347
public boolean exists ( ) { try { read ( ) ; return true ; } catch ( FileFormatException e ) { return false ; } catch ( IOException e ) { logger . error ( e ) ; return false ; } }
Tries to read the PE signature of the current file and returns true iff it was successfull .
348
public String getInfo ( ) { if ( ! peOffset . isPresent ( ) ) { return "No PE signature found" ; } return "-------------" + NL + "PE Signature" + NL + "-------------" + NL + "pe offset: " + peOffset . get ( ) + NL ; }
Returns a description string .
349
public long getOffset ( ) throws IOException { if ( offset == null ) { read ( ) ; SectionTable table = data . getSectionTable ( ) ; SectionLoader loader = new SectionLoader ( data ) ; offset = 0L ; List < SectionHeader > headers = table . getSectionHeaders ( ) ; for ( SectionHeader section : headers ) { long alignedPointerToRaw = section . getAlignedPointerToRaw ( ) ; long readSize = loader . getReadSize ( section ) ; if ( readSize == 0 || section . get ( SectionHeaderKey . POINTER_TO_RAW_DATA ) == 0 ) { continue ; } long endPoint = readSize + alignedPointerToRaw ; if ( offset < endPoint ) { offset = endPoint ; } } } if ( offset > file . length ( ) || offset == 0 ) { offset = file . length ( ) ; } return offset ; }
Returns the file offset of the overlay .
350
public boolean dumpTo ( File outFile ) throws IOException { if ( exists ( ) ) { dump ( getOffset ( ) , outFile ) ; return true ; } else { return false ; } }
Writes a dump of the overlay to the specified output location .
351
private void dump ( long offset , File outFile ) throws IOException { try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ; FileOutputStream out = new FileOutputStream ( outFile ) ) { raf . seek ( offset ) ; byte [ ] buffer = new byte [ 2048 ] ; int bytesRead ; while ( ( bytesRead = raf . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , bytesRead ) ; } } }
Dumps the last part of the file beginning at the specified offset .
352
public byte [ ] getDump ( ) throws IOException { byte [ ] dump = new byte [ ( int ) getSize ( ) ] ; try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { raf . seek ( offset ) ; raf . readFully ( dump ) ; } return dump ; }
Loads all bytes of the overlay into an array and returns them .
353
public static < T extends Characteristic > List < T > getAllMatching ( long value , T [ ] flags ) { List < T > list = new ArrayList < > ( ) ; for ( T ch : flags ) { long mask = ch . getValue ( ) ; if ( ( value & mask ) != 0 ) { list . add ( ch ) ; } } return list ; }
Returns a list of all flags which are set in the value
354
private long fileAligned ( long value ) { long fileAlign = optHeader . getAdjustedFileAlignment ( ) ; long rest = value % fileAlign ; long result = value ; if ( rest != 0 ) { result = value - rest + fileAlign ; } if ( ! ( optHeader . isLowAlignmentMode ( ) || result % 512 == 0 ) ) { logger . error ( "file aligning went wrong" ) ; logger . error ( "rest: " + rest ) ; logger . error ( "value: " + value ) ; logger . error ( "filealign: " + fileAlign ) ; logger . error ( "filealign % 512: " + ( fileAlign % 512 ) ) ; logger . error ( "result % 512: " + ( result % 512 ) ) ; logger . error ( "result: " + result ) ; } assert optHeader . isLowAlignmentMode ( ) || result % 512 == 0 ; assert result >= value ; return result ; }
Rounds up the value to the file alignment of the optional header .
355
private long fileSizeAdjusted ( long alignedPointerToRaw , long readSize ) { if ( readSize + alignedPointerToRaw > file . length ( ) ) { readSize = file . length ( ) - alignedPointerToRaw ; } if ( alignedPointerToRaw > file . length ( ) ) { logger . info ( "invalid section: starts outside the file, readsize set to 0" ) ; readSize = 0 ; } return readSize ; }
Adjusts the readsize of a section to the size of the file .
356
public Optional < Long > maybeGetFileOffset ( long rva ) { Optional < SectionHeader > section = maybeGetSectionHeaderByRVA ( rva ) ; long fileOffset = rva ; if ( section . isPresent ( ) ) { long virtualAddress = section . get ( ) . get ( VIRTUAL_ADDRESS ) ; long pointerToRawData = section . get ( ) . get ( POINTER_TO_RAW_DATA ) ; fileOffset = rva - ( virtualAddress - pointerToRawData ) ; } if ( fileOffset > file . length ( ) || fileOffset < 0 ) { logger . warn ( "invalid file offset: 0x" + Long . toHexString ( fileOffset ) + " for file: " + file . getName ( ) + " with length 0x" + Long . toHexString ( file . length ( ) ) ) ; return Optional . absent ( ) ; } return Optional . of ( fileOffset ) ; }
Returns the file offset for the given RVA . Returns absent if file offset is not within file .
357
public Optional < SectionHeader > maybeGetSectionHeaderByRVA ( long rva ) { List < SectionHeader > headers = table . getSectionHeaders ( ) ; for ( SectionHeader header : headers ) { VirtualLocation vLoc = getVirtualSectionLocation ( header ) ; if ( addressIsWithin ( vLoc , rva ) ) { return Optional . of ( header ) ; } } return Optional . absent ( ) ; }
Returns the section entry of the section table the rva is pointing into .
358
public Optional < SectionHeader > maybeGetSectionHeaderByOffset ( long fileOffset ) { List < SectionHeader > headers = table . getSectionHeaders ( ) ; for ( SectionHeader header : headers ) { PhysicalLocation loc = getPhysicalSectionLocation ( header ) ; if ( addressIsWithin ( loc , fileOffset ) ) { return Optional . of ( header ) ; } } return Optional . absent ( ) ; }
Returns the section entry of the section table the offset is pointing into .
359
private static boolean addressIsWithin ( Location location , long address ) { long endpoint = location . from ( ) + location . size ( ) ; return address >= location . from ( ) && address < endpoint ; }
Returns true if the address is within the given location
360
private MemoryMappedPE getMemoryMappedPE ( ) { if ( ! memoryMapped . isPresent ( ) ) { memoryMapped = Optional . of ( MemoryMappedPE . newInstance ( data , this ) ) ; } return memoryMapped . get ( ) ; }
Creates new instance of MemoryMappedPE or just returns it if it is already there .
361
private Optional < LoadInfo > maybeGetLoadInfo ( DataDirectoryKey dataDirKey ) { Optional < DataDirEntry > dirEntry = optHeader . maybeGetDataDirEntry ( dataDirKey ) ; if ( dirEntry . isPresent ( ) ) { long virtualAddress = dirEntry . get ( ) . getVirtualAddress ( ) ; Optional < Long > maybeOffset = maybeGetFileOffsetFor ( dataDirKey ) ; if ( ! maybeOffset . isPresent ( ) ) { logger . info ( "unable to get file offset for " + dataDirKey ) ; } long offset = maybeOffset . or ( - 1L ) ; return Optional . of ( new LoadInfo ( offset , virtualAddress , getMemoryMappedPE ( ) , data , this ) ) ; } return Optional . absent ( ) ; }
Assembles the loadInfo object for the dataDirKey .
362
public boolean containsEntryPoint ( SectionHeader header ) { long ep = data . getOptionalHeader ( ) . get ( StandardFieldEntryKey . ADDR_OF_ENTRY_POINT ) ; long vStart = header . getAlignedVirtualAddress ( ) ; long vSize = header . getAlignedVirtualSize ( ) ; if ( vSize == 0 ) { vSize = header . getAlignedSizeOfRaw ( ) ; } long vEnd = vSize + vStart ; return ep >= vStart && ep < vEnd ; }
Returns whether the section contains the entry point of the file .
363
public static byte [ ] fileHash ( File file , MessageDigest messageDigest ) throws IOException { return computeHash ( file , messageDigest , 0L , file . length ( ) ) ; }
Returns the hash value of the file for the specified messageDigest .
364
public BufferedImage createEntropyImage ( File file ) throws IOException { resetAvailabilityFlags ( ) ; this . data = new PEData ( null , null , null , null , null , file ) ; image = new BufferedImage ( fileWidth , height , IMAGE_TYPE ) ; final int MIN_WINDOW_SIZE = 100 ; final int windowSize = Math . max ( MIN_WINDOW_SIZE , pixelSize ) ; final int windowHalfSize = ( int ) Math . round ( windowSize / ( double ) 2 ) ; final long minLength = withMinLength ( 0 ) ; try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { for ( long address = 0 ; address <= file . length ( ) ; address += minLength ) { long start = ( address - windowHalfSize < 0 ) ? 0 : address - windowHalfSize ; raf . seek ( start ) ; int bytesToRead = ( int ) Math . min ( file . length ( ) - start , windowSize ) ; byte [ ] bytes = new byte [ bytesToRead ] ; raf . readFully ( bytes ) ; double entropy = ShannonEntropy . entropy ( bytes ) ; Color color = getColorForEntropy ( entropy ) ; drawPixels ( color , address , minLength ) ; } } drawVisOverlay ( true ) ; return image ; }
Creates an image of the local entropies of this file .
365
private Color getColorForEntropy ( double entropy ) { assert entropy <= 1 ; assert entropy >= 0 ; Color entropyColor = colorMap . get ( ENTROPY ) ; float [ ] hsbvals = new float [ 3 ] ; Color . RGBtoHSB ( entropyColor . getRed ( ) , entropyColor . getGreen ( ) , entropyColor . getBlue ( ) , hsbvals ) ; float entropyHue = hsbvals [ 0 ] ; float saturation = hsbvals [ 1 ] ; float brightness = ( float ) entropy ; return Color . getHSBColor ( entropyHue , saturation , brightness ) ; }
Creates a color instance based on a given entropy .
366
public void writeImage ( File input , File output , String formatName ) throws IOException { BufferedImage image = createImage ( input ) ; ImageIO . write ( image , formatName , output ) ; }
Writes an image to the output file that displays the structure of the PE file .
367
public BufferedImage createDiffImage ( BufferedImage firstImage , BufferedImage secondImage ) throws IOException { BufferedImage diffImage = new BufferedImage ( firstImage . getWidth ( ) , firstImage . getHeight ( ) , IMAGE_TYPE ) ; for ( int x = 0 ; x < firstImage . getWidth ( ) && x < secondImage . getWidth ( ) ; x ++ ) { for ( int y = 0 ; y < firstImage . getHeight ( ) && y < secondImage . getHeight ( ) ; y ++ ) { int pixelA = firstImage . getRGB ( x , y ) ; int pixelB = secondImage . getRGB ( x , y ) ; int diffRGB = Math . abs ( pixelA - pixelB ) ; diffImage . setRGB ( x , y , diffRGB ) ; } } return diffImage ; }
Creates a buffered image containing the diff of both files .
368
public BufferedImage createImage ( File file ) throws IOException { resetAvailabilityFlags ( ) ; this . data = PELoader . loadPE ( file ) ; image = new BufferedImage ( fileWidth , height , IMAGE_TYPE ) ; drawSections ( ) ; Overlay overlay = new Overlay ( data ) ; if ( overlay . exists ( ) ) { long overlayOffset = overlay . getOffset ( ) ; drawPixels ( colorMap . get ( OVERLAY ) , overlayOffset , withMinLength ( overlay . getSize ( ) ) ) ; overlayAvailable = true ; } drawPEHeaders ( ) ; drawSpecials ( ) ; drawResourceTypes ( ) ; assert image != null ; assert image . getWidth ( ) == fileWidth ; assert image . getHeight ( ) == height ; return image ; }
Creates a buffered image that displays the structure of the PE file .
369
public BufferedImage createLegendImage ( boolean withBytePlot , boolean withEntropy , boolean withPEStructure ) { image = new BufferedImage ( legendWidth , height , IMAGE_TYPE ) ; drawLegend ( withBytePlot , withEntropy , withPEStructure ) ; assert image != null ; assert image . getWidth ( ) == legendWidth ; assert image . getHeight ( ) == height ; return image ; }
Creates a buffered image with a basic Legend
370
private void drawPEHeaders ( ) { long msdosOffset = 0 ; long msdosSize = withMinLength ( data . getMSDOSHeader ( ) . getHeaderSize ( ) ) ; drawPixels ( colorMap . get ( MSDOS_HEADER ) , msdosOffset , msdosSize ) ; long optOffset = data . getOptionalHeader ( ) . getOffset ( ) ; long optSize = withMinLength ( data . getOptionalHeader ( ) . getSize ( ) ) ; drawPixels ( colorMap . get ( OPTIONAL_HEADER ) , optOffset , optSize ) ; long coffOffset = data . getCOFFFileHeader ( ) . getOffset ( ) ; long coffSize = withMinLength ( COFFFileHeader . HEADER_SIZE ) ; drawPixels ( colorMap . get ( COFF_FILE_HEADER ) , coffOffset , coffSize ) ; long tableOffset = data . getSectionTable ( ) . getOffset ( ) ; long tableSize = data . getSectionTable ( ) . getSize ( ) ; if ( tableSize != 0 ) { tableSize = withMinLength ( tableSize ) ; drawPixels ( colorMap . get ( SECTION_TABLE ) , tableOffset , tableSize ) ; } }
Draws the PE Header to the structure image
371
private Optional < Long > getEntryPoint ( ) { long rva = data . getOptionalHeader ( ) . get ( StandardFieldEntryKey . ADDR_OF_ENTRY_POINT ) ; Optional < SectionHeader > section = new SectionLoader ( data ) . maybeGetSectionHeaderByRVA ( rva ) ; if ( section . isPresent ( ) ) { long phystovirt = section . get ( ) . get ( SectionHeaderKey . VIRTUAL_ADDRESS ) - section . get ( ) . get ( SectionHeaderKey . POINTER_TO_RAW_DATA ) ; return Optional . of ( rva - phystovirt ) ; } return Optional . absent ( ) ; }
Returns the entry point of the PE if present and valid otherwise absent .
372
private void drawSections ( ) { SectionTable table = data . getSectionTable ( ) ; long sectionTableOffset = table . getOffset ( ) ; long sectionTableSize = table . getSize ( ) ; drawPixels ( colorMap . get ( SECTION_TABLE ) , sectionTableOffset , sectionTableSize ) ; logger . info ( "x pixels: " + getXPixels ( ) ) ; logger . info ( "y pixels: " + getYPixels ( ) ) ; logger . info ( "bytesPerPixel: " + bytesPerPixel ( ) ) ; for ( SectionHeader header : table . getSectionHeaders ( ) ) { long sectionOffset = header . getAlignedPointerToRaw ( ) ; logger . info ( "drawing section to: " + sectionOffset ) ; long sectionSize = new SectionLoader ( data ) . getReadSize ( header ) ; logger . info ( "drawing section size: " + sectionSize ) ; long pixelStart = getPixelNumber ( sectionOffset ) ; logger . info ( "pixelStart: " + pixelStart ) ; drawPixels ( getSectionColor ( header ) , sectionOffset , sectionSize ) ; } }
Draw the sections to the structure image .
373
private Color getSectionColor ( SectionHeader header ) { int nr = header . getNumber ( ) ; Color sectionColor = colorMap . get ( SECTION_START ) ; for ( int i = 1 ; i < nr ; i ++ ) { sectionColor = variate ( sectionColor ) ; } return sectionColor ; }
Generate the color of the given section .
374
private Color variate ( Color color ) { assert color != null ; final int diff = 30 ; int newRed = shiftColorPart ( color . getRed ( ) - diff ) ; int newGreen = shiftColorPart ( color . getGreen ( ) - diff ) ; int newBlue = shiftColorPart ( color . getBlue ( ) - diff ) ; Color newColor = new Color ( newRed , newGreen , newBlue ) ; if ( newColor . equals ( Color . black ) ) { newColor = colorMap . get ( SECTION_START ) ; } return newColor ; }
Shift the given section color one step .
375
private void drawRect ( Color color , int startX , int startY , int width , int height ) { assert color != null ; for ( int x = startX ; x < startX + width ; x ++ ) { for ( int y = startY ; y < startY + height ; y ++ ) { try { image . setRGB ( x , y , color . getRGB ( ) ) ; } catch ( ArrayIndexOutOfBoundsException e ) { logger . warn ( "tried to set x/y = " + x + "/" + y ) ; } } } }
Draws a rectangle .
376
private void drawCross ( Color color , int startX , int startY , int width , int height ) { assert color != null ; final int thickness = 2 ; for ( int x = startX ; x < startX + width ; x ++ ) { for ( int y = startY ; y < startY + height ; y ++ ) { try { if ( Math . abs ( ( x - startX ) - ( y - startY ) ) < thickness || Math . abs ( ( width - ( x - startX ) ) - ( y - startY ) ) < thickness ) { image . setRGB ( x , y , color . getRGB ( ) ) ; } } catch ( ArrayIndexOutOfBoundsException e ) { logger . warn ( "tried to set x/y = " + x + "/" + y ) ; } } } }
Draws a cross .
377
private void drawPixel ( Color color , long fileOffset ) { long size = withMinLength ( 0 ) ; drawPixels ( color , fileOffset , size ) ; }
Draws a square pixel at fileOffset with color .
378
private long getPixelNumber ( long fileOffset ) { assert fileOffset >= 0 ; long result = Math . round ( fileOffset / bytesPerPixel ( ) ) ; assert result >= 0 ; return result ; }
convert fileOffset to square pixels
379
private int bytesPerPixel ( ) { long fileSize = data . getFile ( ) . length ( ) ; long pixelMax = getXPixels ( ) * ( long ) getYPixels ( ) ; return ( int ) Math . ceil ( fileSize / ( double ) pixelMax ) ; }
Calculates how many bytes are covered by one square pixel .
380
private PEData loadData ( ) throws IOException { PESignature pesig = new PESignature ( file ) ; pesig . read ( ) ; checkState ( pesig . exists ( ) , "no valid pe file, signature not found" ) ; try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { MSDOSHeader msdos = loadMSDOSHeader ( raf , pesig . getOffset ( ) ) ; COFFFileHeader coff = loadCOFFFileHeader ( pesig , raf ) ; OptionalHeader opt = loadOptionalHeader ( pesig , coff , raf ) ; SectionTable table = loadSectionTable ( pesig , coff , raf ) ; table . read ( ) ; PEData data = new PEData ( msdos , pesig , coff , opt , table , file ) ; return data ; } }
Loads the PE file header data into a PEData instance .
381
private MSDOSHeader loadMSDOSHeader ( RandomAccessFile raf , long peSigOffset ) throws IOException { byte [ ] headerbytes = loadBytesSafely ( 0 , MSDOSHeader . FORMATTED_HEADER_SIZE , raf ) ; return MSDOSHeader . newInstance ( headerbytes , peSigOffset ) ; }
Loads the MSDOS header .
382
private SectionTable loadSectionTable ( PESignature pesig , COFFFileHeader coff , RandomAccessFile raf ) throws IOException { long offset = pesig . getOffset ( ) + PESignature . PE_SIG . length + COFFFileHeader . HEADER_SIZE + coff . getSizeOfOptionalHeader ( ) ; logger . info ( "SectionTable offset: " + offset ) ; int numberOfEntries = ( int ) coff . getNumberOfSections ( ) ; int size = SectionTable . ENTRY_SIZE * numberOfEntries ; if ( size + offset > file . length ( ) ) { size = ( int ) ( file . length ( ) - offset ) ; } if ( size <= 0 ) { logger . warn ( "Unable to parse Section table, offset outside the file" ) ; return new SectionTable ( new byte [ 0 ] , 0 , offset ) ; } byte [ ] tableBytes = loadBytes ( offset , size , raf ) ; return new SectionTable ( tableBytes , numberOfEntries , offset ) ; }
Loads the section table . Presumes a valid PE file .
383
private COFFFileHeader loadCOFFFileHeader ( PESignature pesig , RandomAccessFile raf ) throws IOException { long offset = pesig . getOffset ( ) + PESignature . PE_SIG . length ; logger . info ( "COFF Header offset: " + offset ) ; byte [ ] headerbytes = loadBytesSafely ( offset , COFFFileHeader . HEADER_SIZE , raf ) ; return COFFFileHeader . newInstance ( headerbytes , offset ) ; }
Loads the COFF File header . Presumes a valid PE file .
384
private OptionalHeader loadOptionalHeader ( PESignature pesig , COFFFileHeader coff , RandomAccessFile raf ) throws IOException { long offset = pesig . getOffset ( ) + PESignature . PE_SIG . length + COFFFileHeader . HEADER_SIZE ; logger . info ( "Optional Header offset: " + offset ) ; int size = getOptHeaderSize ( offset ) ; byte [ ] headerbytes = loadBytesSafely ( offset , size , raf ) ; return OptionalHeader . newInstance ( headerbytes , offset ) ; }
Loads the optional header . Presumes a valid PE file .
385
public long getFileOffset ( SectionTable table ) { checkArgument ( table != null , "section table must not be null" ) ; Optional < SectionHeader > section = maybeGetSectionTableEntry ( table ) ; if ( section . isPresent ( ) ) { long sectionRVA = section . get ( ) . getAlignedVirtualAddress ( ) ; long sectionOffset = section . get ( ) . getAlignedPointerToRaw ( ) ; return ( virtualAddress - sectionRVA ) + sectionOffset ; } return virtualAddress ; }
Calculates the file offset of the data directory based on the virtual address and the entries in the section table . This method is subject to change .
386
public SectionHeader getSectionTableEntry ( SectionTable table ) { Optional < SectionHeader > entry = maybeGetSectionTableEntry ( table ) ; if ( entry . isPresent ( ) ) { return entry . get ( ) ; } throw new IllegalStateException ( "there is no section for this data directory entry" ) ; }
Returns the section table entry of the section that the data directory entry is pointing to .
387
public Optional < SectionHeader > maybeGetSectionTableEntry ( SectionTable table ) { checkArgument ( table != null , "table must not be null" ) ; List < SectionHeader > sections = table . getSectionHeaders ( ) ; for ( SectionHeader header : sections ) { long vSize = header . getAlignedVirtualSize ( ) ; if ( vSize == 0 ) { vSize = header . getAlignedSizeOfRaw ( ) ; } long vAddress = header . getAlignedVirtualAddress ( ) ; logger . debug ( "check if rva is within " + vAddress + " and " + ( vAddress + vSize ) ) ; if ( rvaIsWithin ( new VirtualLocation ( vAddress , vSize ) ) ) { return Optional . of ( header ) ; } } logger . warn ( "there is no entry that matches data dir entry RVA " + virtualAddress ) ; return Optional . absent ( ) ; }
more convenient use of the API
388
public long getAlignedSizeOfRaw ( ) { long sizeOfRaw = get ( SIZE_OF_RAW_DATA ) ; if ( sizeOfRaw == ( sizeOfRaw & ~ 0xfff ) ) { return sizeOfRaw ; } long result = ( sizeOfRaw + 0xfff ) & ~ 0xfff ; assert result % 4096 == 0 ; return result ; }
Returns the SizeOfRawData rounded up to a multiple of 4kb .
389
public long getAlignedVirtualSize ( ) { long virtSize = get ( VIRTUAL_SIZE ) ; if ( virtSize == ( virtSize & ~ 0xfff ) ) { return virtSize ; } long result = ( virtSize + 0xfff ) & ~ 0xfff ; assert result % 4096 == 0 ; return result ; }
Returns the VirtualSize rounded up to a multiple of 4kb .
390
public long getAlignedVirtualAddress ( ) { long virtAddr = get ( VIRTUAL_ADDRESS ) ; if ( virtAddr == ( virtAddr & ~ 0xfff ) ) { return virtAddr ; } long result = ( virtAddr + 0xfff ) & ~ 0xfff ; assert result % 4096 == 0 ; return result ; }
Returns the VirtualAddress rounded up to a multiple of 4kb .
391
public List < SectionCharacteristic > getCharacteristics ( ) { long value = get ( SectionHeaderKey . CHARACTERISTICS ) ; List < SectionCharacteristic > list = SectionCharacteristic . getAllFor ( value ) ; assert list != null ; return list ; }
Returns a list of all characteristics of that section .
392
public SectionHeader getSectionHeader ( int number ) { for ( SectionHeader header : headers ) { if ( header . getNumber ( ) == number ) { return header ; } } throw new IllegalArgumentException ( "invalid section number, no section header found" ) ; }
Returns the section entry that has the given number or null if there is no section with that number .
393
public SectionHeader getSectionHeader ( String sectionName ) { for ( SectionHeader entry : headers ) { if ( entry . getName ( ) . equals ( sectionName ) ) { return entry ; } } throw new IllegalArgumentException ( "invalid section name, no section header found" ) ; }
Returns the section entry that has the given name . If there are several sections with the same name the first one will be returned .
394
public Optional < SectionHeader > getSectionHeaderByName ( String name ) { for ( SectionHeader header : headers ) { if ( header . getName ( ) . equals ( name ) ) { return Optional . of ( header ) ; } } return Optional . absent ( ) ; }
Returns an optional of the first section that has the given name .
395
public static String renderLinks ( CharSequence input , Iterable < LinkSpan > links , LinkRenderer linkRenderer ) { if ( input == null ) { throw new NullPointerException ( "input must not be null" ) ; } if ( links == null ) { throw new NullPointerException ( "links must not be null" ) ; } if ( linkRenderer == null ) { throw new NullPointerException ( "linkRenderer must not be null" ) ; } StringBuilder sb = new StringBuilder ( input . length ( ) + 16 ) ; int lastIndex = 0 ; for ( LinkSpan link : links ) { sb . append ( input , lastIndex , link . getBeginIndex ( ) ) ; linkRenderer . render ( link , input , sb ) ; lastIndex = link . getEndIndex ( ) ; } if ( lastIndex < input . length ( ) ) { sb . append ( input , lastIndex , input . length ( ) ) ; } return sb . toString ( ) ; }
Render the supplied links from the supplied input text using a renderer . The parts of the text outside of links are added to the result without processing .
396
private int findFirst ( CharSequence input , int beginIndex , int rewindIndex ) { int first = - 1 ; boolean atomBoundary = true ; for ( int i = beginIndex ; i >= rewindIndex ; i -- ) { char c = input . charAt ( i ) ; if ( localAtomAllowed ( c ) ) { first = i ; atomBoundary = false ; } else if ( c == '.' ) { if ( atomBoundary ) { break ; } atomBoundary = true ; } else { break ; } } return first ; }
See Local - part in RFC 5321 plus extensions in RFC 6531
397
private int findLast ( CharSequence input , int beginIndex ) { boolean firstInSubDomain = true ; boolean canEndSubDomain = false ; int firstDot = - 1 ; int last = - 1 ; for ( int i = beginIndex ; i < input . length ( ) ; i ++ ) { char c = input . charAt ( i ) ; if ( firstInSubDomain ) { if ( subDomainAllowed ( c ) ) { last = i ; firstInSubDomain = false ; canEndSubDomain = true ; } else { break ; } } else { if ( c == '.' ) { if ( ! canEndSubDomain ) { break ; } firstInSubDomain = true ; if ( firstDot == - 1 ) { firstDot = i ; } } else if ( c == '-' ) { canEndSubDomain = false ; } else if ( subDomainAllowed ( c ) ) { last = i ; canEndSubDomain = true ; } else { break ; } } } if ( domainMustHaveDot && ( firstDot == - 1 || firstDot > last ) ) { return - 1 ; } else { return last ; } }
See Domain in RFC 5321 plus extension of sub - domain in RFC 6531
398
private boolean localAtomAllowed ( char c ) { if ( Scanners . isAlnum ( c ) || Scanners . isNonAscii ( c ) ) { return true ; } switch ( c ) { case '!' : case '#' : case '$' : case '%' : case '&' : case '\'' : case '*' : case '+' : case '-' : case '/' : case '=' : case '?' : case '^' : case '_' : case '`' : case '{' : case '|' : case '}' : case '~' : return true ; } return false ; }
See Atom in RFC 5321 atext in RFC 5322
399
private int findFirst ( CharSequence input , int beginIndex , int rewindIndex ) { int first = - 1 ; int digit = - 1 ; for ( int i = beginIndex ; i >= rewindIndex ; i -- ) { char c = input . charAt ( i ) ; if ( Scanners . isAlpha ( c ) ) { first = i ; } else if ( Scanners . isDigit ( c ) ) { digit = i ; } else if ( ! schemeSpecial ( c ) ) { break ; } } if ( first > 0 && first - 1 == digit ) { first = - 1 ; } return first ; }
See scheme in RFC 3986