idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
7,100 | static Class < ? > loadType ( String fullName ) throws ClassNotFoundException { try { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; return loader != null ? loader . loadClass ( fullName ) : Class . forName ( fullName ) ; } catch ( ClassNotFoundException ex ) { return loadPrimitiveType ( fullName , ex ) ; } } | loads a type avoiding nulls context class loader if available |
7,101 | private static Class < ? > loadPrimitiveType ( String fullName , ClassNotFoundException ex ) throws ClassNotFoundException { if ( fullName . equals ( "int" ) ) { return int . class ; } else if ( fullName . equals ( "long" ) ) { return long . class ; } else if ( fullName . equals ( "double" ) ) { return double . class ; } else if ( fullName . equals ( "boolean" ) ) { return boolean . class ; } else if ( fullName . equals ( "short" ) ) { return short . class ; } else if ( fullName . equals ( "byte" ) ) { return byte . class ; } else if ( fullName . equals ( "char" ) ) { return char . class ; } else if ( fullName . equals ( "float" ) ) { return float . class ; } else if ( fullName . equals ( "void" ) ) { return void . class ; } throw ex ; } | handle primitive types |
7,102 | private < T > StringConverter < T > findAnnotatedConverter ( final Class < T > cls ) { Method toString = findToStringMethod ( cls ) ; if ( toString == null ) { return null ; } MethodConstructorStringConverter < T > con = findFromStringConstructor ( cls , toString ) ; MethodsStringConverter < T > mth = findFromStringMethod ( cls , toString , con == null ) ; if ( con == null && mth == null ) { throw new IllegalStateException ( "Class annotated with @ToString but not with @FromString: " + cls . getName ( ) ) ; } if ( con != null && mth != null ) { throw new IllegalStateException ( "Both method and constructor are annotated with @FromString: " + cls . getName ( ) ) ; } return ( con != null ? con : mth ) ; } | Finds a converter searching annotated . |
7,103 | private Class < ? > eliminateEnumSubclass ( Class < ? > cls ) { Class < ? > sup = cls . getSuperclass ( ) ; if ( sup != null && sup . getSuperclass ( ) == Enum . class ) { return sup ; } return cls ; } | eliminates enum subclass as they are pesky |
7,104 | private static RenameHandler createInstance ( ) { RenameHandler instance = create ( false ) ; try { instance . loadFromClasspath ( ) ; } catch ( IllegalStateException ex ) { System . err . println ( "ERROR: " + ex . getMessage ( ) ) ; ex . printStackTrace ( ) ; } catch ( Throwable ex ) { System . err . println ( "ERROR: Failed to load Renamed.ini files: " + ex . getMessage ( ) ) ; ex . printStackTrace ( ) ; } return instance ; } | this is a method to aid IDE debugging of class initialization |
7,105 | public Class < ? > lookupType ( String name ) throws ClassNotFoundException { if ( name == null ) { throw new IllegalArgumentException ( "name must not be null" ) ; } Class < ? > type = typeRenames . get ( name ) ; if ( type == null ) { type = StringConvert . loadType ( name ) ; } return type ; } | Lookup a type from a name handling renames . |
7,106 | public < T extends Enum < T > > T lookupEnum ( Class < T > type , String name ) { if ( type == null ) { throw new IllegalArgumentException ( "type must not be null" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "name must not be null" ) ; } Map < String , Enum < ? > > map = getEnumRenames ( type ) ; Enum < ? > value = map . get ( name ) ; if ( value != null ) { return type . cast ( value ) ; } return Enum . valueOf ( type , name ) ; } | Lookup an enum from a name handling renames . |
7,107 | private byte [ ] getSerializedEntity ( ClientRequest request ) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; try { writeRequestEntity ( request , new RequestEntityWriterListener ( ) { public void onRequestEntitySize ( long size ) throws IOException { } public OutputStream onGetOutputStream ( ) throws IOException { return outputStream ; } } ) ; } catch ( IOException e ) { throw new ClientHandlerException ( "Unable to serialize request entity" , e ) ; } return outputStream . toByteArray ( ) ; } | Get the serialized representation of the request entity . This is used when generating the client signature because this is the representation that the server will receive and use when it generates the server - side signature to compare to the client - side signature . |
7,108 | protected void cachePrincipal ( String apiKey , Principal principal ) { cache . put ( apiKey , Optional . fromNullable ( principal ) ) ; } | Put this principal directly into cache . This can avoid lookup on user request and prepay the lookup cost . |
7,109 | private boolean validateTimestamp ( String timestamp ) { DateTime requestTime = TimeUtils . parse ( timestamp ) ; long difference = Math . abs ( new Duration ( requestTime , nowInUTC ( ) ) . getMillis ( ) ) ; return difference <= allowedTimestampRange ; } | To protect against replay attacks make sure the timestamp on the request is valid by ensuring that the difference between the request time and the current time on the server does not fall outside the acceptable time range . Note that the request time may have been generated on a different machine and so it may be ahead or behind the current server time . |
7,110 | private boolean validateSignature ( Credentials credentials , String secretKey ) { String clientSignature = credentials . getSignature ( ) ; String serverSignature = createSignature ( credentials , secretKey ) ; return MessageDigest . isEqual ( clientSignature . getBytes ( ) , serverSignature . getBytes ( ) ) ; } | Validate the signature on the request by generating a new signature here and making sure they match . The only way for them to match is if both signature are generated using the same secret key . If they match this means that the requester has a valid secret key and can be a trusted source . |
7,111 | private String createSignature ( Credentials credentials , String secretKey ) { return new SignatureGenerator ( ) . generate ( secretKey , credentials . getMethod ( ) , credentials . getTimestamp ( ) , credentials . getPath ( ) , credentials . getContent ( ) ) ; } | Create a signature given the set of request credentials and a secret key . |
7,112 | public void clear ( ) { for ( int i = 0 ; i < mNumberPinBoxes ; i ++ ) { getPinBox ( i ) . getText ( ) . clear ( ) ; } checkPinBoxesAvailableOrder ( ) ; } | Clear PinBoxes values |
7,113 | public void resetChildrenFocus ( ) { for ( int pinBoxesId : pinBoxesIds ) { EditText pin = ( EditText ) findViewById ( pinBoxesId ) ; pin . setOnFocusChangeListener ( this ) ; } } | Clear PinBoxes focus |
7,114 | public static float convertPixelToDp ( Context context , float px ) { Resources resources = context . getResources ( ) ; DisplayMetrics metrics = resources . getDisplayMetrics ( ) ; return px / ( metrics . densityDpi / 160f ) ; } | This method converts device specific pixels to density independent pixels . |
7,115 | public static void hideKeyboard ( Context context ) { try { InputMethodManager imm = ( InputMethodManager ) context . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; View currentFocus = ( ( Activity ) context ) . getCurrentFocus ( ) ; if ( imm != null && currentFocus != null ) { IBinder windowToken = currentFocus . getWindowToken ( ) ; if ( windowToken != null ) { imm . hideSoftInputFromWindow ( windowToken , 0 ) ; } } } catch ( Exception e ) { Log . e ( LOG_TAG , "Can't even hide keyboard " + e . getMessage ( ) ) ; } } | Hides the already popped up keyboard from the screen . |
7,116 | private void createEditModeView ( Context context ) { ( ( LayoutInflater ) context . getSystemService ( Context . LAYOUT_INFLATER_SERVICE ) ) . inflate ( R . layout . pin_view_edit_mode , this , true ) ; } | This method inflates the PinView to be visible from Preview Layout |
7,117 | private void createView ( Context context ) { ( ( LayoutInflater ) context . getSystemService ( Context . LAYOUT_INFLATER_SERVICE ) ) . inflate ( R . layout . pin_view , this , true ) ; inputMethodManager = ( InputMethodManager ) getContext ( ) . getSystemService ( Service . INPUT_METHOD_SERVICE ) ; mLinearLayoutPinTexts = ( LinearLayout ) findViewById ( R . id . ll_pin_texts ) ; mLinearLayoutPinBoxes = ( LinearLayout ) findViewById ( R . id . ll_pin_edit_texts ) ; } | This method inflates the PinView |
7,118 | private void getAttributes ( Context context , AttributeSet attrs ) { TypedArray typedArray = context . obtainStyledAttributes ( attrs , R . styleable . PinView ) ; if ( typedArray != null ) { try { mNumberPinBoxes = typedArray . getInteger ( R . styleable . PinView_numberPinBoxes , PinViewSettings . DEFAULT_NUMBER_PIN_BOXES ) ; mMaskPassword = typedArray . getBoolean ( R . styleable . PinView_password , PinViewSettings . DEFAULT_MASK_PASSWORD ) ; mNumberCharacters = typedArray . getInteger ( R . styleable . PinView_numberCharacters , PinViewSettings . DEFAULT_NUMBER_CHARACTERS ) ; mSplit = typedArray . getString ( R . styleable . PinView_split ) ; mKeyboardMandatory = typedArray . getBoolean ( R . styleable . PinView_keyboardMandatory , PinViewSettings . DEFAULT_KEYBOARD_MANDATORY ) ; mDeleteOnClick = typedArray . getBoolean ( R . styleable . PinView_deleteOnClick , PinViewSettings . DEFAULT_DELETE_ON_CLICK ) ; mNativePinBox = typedArray . getBoolean ( R . styleable . PinView_nativePinBox , PinViewSettings . DEFAULT_NATIVE_PIN_BOX ) ; mCustomDrawablePinBox = typedArray . getResourceId ( R . styleable . PinView_drawablePinBox , PinViewSettings . DEFAULT_CUSTOM_PIN_BOX ) ; mColorTextPinBoxes = typedArray . getColor ( R . styleable . PinView_colorTextPinBox , getResources ( ) . getColor ( PinViewSettings . DEFAULT_TEXT_COLOR_PIN_BOX ) ) ; mColorTextTitles = typedArray . getColor ( R . styleable . PinView_colorTextTitles , getResources ( ) . getColor ( PinViewSettings . DEFAULT_TEXT_COLOR_TITLES ) ) ; mColorSplit = typedArray . getColor ( R . styleable . PinView_colorSplit , getResources ( ) . getColor ( PinViewSettings . DEFAULT_COLOR_SPLIT ) ) ; mTextSizePinBoxes = typedArray . getDimension ( R . styleable . PinView_textSizePinBox , getResources ( ) . getDimension ( PinViewSettings . DEFAULT_TEXT_SIZE_PIN_BOX ) ) ; mTextSizeTitles = typedArray . getDimension ( R . styleable . PinView_textSizeTitles , getResources ( ) . getDimension ( PinViewSettings . DEFAULT_TEXT_SIZE_TITLES ) ) ; mSizeSplit = typedArray . getDimension ( R . styleable . PinView_sizeSplit , getResources ( ) . getDimension ( PinViewSettings . DEFAULT_SIZE_SPLIT ) ) ; int titles ; titles = typedArray . getResourceId ( R . styleable . PinView_titles , - 1 ) ; if ( titles != - 1 ) { setTitles ( getResources ( ) . getStringArray ( titles ) ) ; } if ( this . mNumberPinBoxes != 0 ) { setPin ( this . mNumberPinBoxes ) ; } } catch ( Exception e ) { Log . e ( LOG_TAG , "Error while creating the view PinView: " , e ) ; } finally { typedArray . recycle ( ) ; } } } | Retrieve styles attributes |
7,119 | private void setStylePinBox ( EditText editText ) { editText . setFilters ( new InputFilter [ ] { new InputFilter . LengthFilter ( mNumberCharacters ) } ) ; if ( mMaskPassword ) { editText . setTransformationMethod ( PasswordTransformationMethod . getInstance ( ) ) ; } else { editText . setTransformationMethod ( HideReturnsTransformationMethod . getInstance ( ) ) ; } if ( mNativePinBox ) { if ( android . os . Build . VERSION . SDK_INT < android . os . Build . VERSION_CODES . JELLY_BEAN ) { editText . setBackgroundDrawable ( new EditText ( getContext ( ) ) . getBackground ( ) ) ; } else { editText . setBackground ( new EditText ( getContext ( ) ) . getBackground ( ) ) ; } } else { editText . setBackgroundResource ( mCustomDrawablePinBox ) ; } if ( mColorTextPinBoxes != PinViewSettings . DEFAULT_TEXT_COLOR_PIN_BOX ) { editText . setTextColor ( mColorTextPinBoxes ) ; } editText . setTextSize ( PinViewUtils . convertPixelToDp ( getContext ( ) , mTextSizePinBoxes ) ) ; } | Set a PinBox with all attributes |
7,120 | private void setStylesPinTitle ( TextView pinTitle ) { if ( mColorTextTitles != PinViewSettings . DEFAULT_TEXT_COLOR_TITLES ) { pinTitle . setTextColor ( mColorTextTitles ) ; } pinTitle . setTextSize ( PinViewUtils . convertPixelToDp ( getContext ( ) , mTextSizeTitles ) ) ; } | Set a Title with all attributes |
7,121 | private void setStylesSplit ( TextView split ) { if ( split != null ) { split . setText ( mSplit ) ; split . setLayoutParams ( new LayoutParams ( ViewGroup . LayoutParams . WRAP_CONTENT , ViewGroup . LayoutParams . MATCH_PARENT ) ) ; split . setGravity ( Gravity . CENTER_VERTICAL ) ; if ( mColorSplit != PinViewSettings . DEFAULT_COLOR_SPLIT ) { split . setTextColor ( mColorSplit ) ; } split . setTextSize ( PinViewUtils . convertPixelToDp ( getContext ( ) , mSizeSplit ) ) ; } } | Set a Split with all attributes |
7,122 | public boolean dispatchKeyEventPreIme ( KeyEvent event ) { if ( mKeyboardMandatory ) { if ( getContext ( ) != null ) { InputMethodManager imm = ( InputMethodManager ) getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; if ( imm . isActive ( ) && event . getKeyCode ( ) == KeyEvent . KEYCODE_BACK ) { setImeVisibility ( true ) ; return true ; } } } return super . dispatchKeyEventPreIme ( event ) ; } | Keyboard back button |
7,123 | public static DataLinkType valueOf ( short value ) { for ( Map . Entry < DataLinkType , Short > entry : registry . entrySet ( ) ) { if ( entry . getValue ( ) == value ) { return entry . getKey ( ) ; } } return new DataLinkType ( ( short ) - 1 , "Unknown" ) ; } | Get datalink type from value . |
7,124 | @ ConditionalOnClass ( { Inet4Address . class , PcapIf . class } ) @ Bean ( NETMASK_BEAN_NAME ) public Inet4Address netmask ( @ Qualifier ( PCAP_IF_BEAN_NAME ) PcapIf pcapIf ) { Iterator < PcapAddr > iterator = pcapIf . getAddresses ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { PcapAddr pcapAddr = iterator . next ( ) ; if ( pcapAddr . getNetmask ( ) != null && pcapAddr . getNetmask ( ) . getSaFamily ( ) == SockAddr . Family . AF_INET && pcapAddr . getNetmask ( ) . getData ( ) != null ) { Inet4Address netmask = Inet4Address . valueOf ( pcapAddr . getNetmask ( ) . getData ( ) ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Default netmask: {}." , netmask ) ; } return netmask ; } } throw new UnknownNetmaskException ( ) ; } | Default netmask . |
7,125 | @ ConditionalOnClass ( { MacAddress . class , PcapIf . class , PcapAddr . class , SockAddr . class , DeviceNotFoundException . class , PlatformNotSupportedException . class } ) @ Bean ( MAC_ADDRESS_BEAN_NAME ) public MacAddress macAddress ( @ Qualifier ( PCAP_IF_BEAN_NAME ) PcapIf pcapIf ) throws PlatformNotSupportedException , DeviceNotFoundException , SocketException { MacAddress macAddress ; if ( pcapIf . isLoopback ( ) ) { macAddress = MacAddress . ZERO ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "No MAC address for loopback interface, use default address: {}." , macAddress ) ; } return macAddress ; } if ( Platforms . isWindows ( ) ) { byte [ ] hardwareAddress = Jxnet . FindHardwareAddress ( pcapIf . getName ( ) ) ; if ( hardwareAddress != null && hardwareAddress . length == MacAddress . MAC_ADDRESS_LENGTH ) { macAddress = MacAddress . valueOf ( hardwareAddress ) ; } else { throw new DeviceNotFoundException ( ) ; } } else { macAddress = MacAddress . fromNicName ( pcapIf . getName ( ) ) ; } if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Mac address: {}." , macAddress ) ; } return macAddress ; } | Default mac address specified by pcapIf . |
7,126 | @ ConditionalOnClass ( { Context . class , DataLinkType . class } ) @ Bean ( DATALINK_TYPE_BEAN_NAME ) public DataLinkType dataLinkType ( @ Qualifier ( CONTEXT_BEAN_NAME ) Context context ) { DataLinkType dataLinkType = context . pcapDataLink ( ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Datalink type: {}." , dataLinkType ) ; } return dataLinkType ; } | A handle link type . |
7,127 | @ Bean ( ERRBUF_BEAN_NAME ) public StringBuilder errbuf ( ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Create error buffer with size: {}." , PCAP_ERRBUF_SIZE ) ; } return new StringBuilder ( PCAP_ERRBUF_SIZE ) ; } | Error buffer . |
7,128 | @ Bean ( EXECUTOR_SERVICE_BEAN_NAME ) public ExecutorService executorService ( ) { if ( this . properties . getNumberOfThread ( ) == 0 ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Use cached thread pool." ) ; } return Executors . newCachedThreadPool ( ) ; } if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Use {} fixed thread pool." , this . properties . getNumberOfThread ( ) ) ; } return Executors . newFixedThreadPool ( this . properties . getNumberOfThread ( ) ) ; } | Thread pool . |
7,129 | @ ConditionalOnClass ( { PcapIf . class } ) @ Bean ( PCAP_BUILDER_BEAN_NAME ) public Pcap . Builder pcapBuilder ( @ Qualifier ( PCAP_IF_BEAN_NAME ) PcapIf pcapIf , @ Qualifier ( ERRBUF_BEAN_NAME ) StringBuilder errbuf ) { String source = pcapIf . getName ( ) ; Pcap . Builder builder = new Pcap . Builder ( ) . source ( source ) . snaplen ( properties . getSnapshot ( ) ) . promiscuousMode ( properties . getPromiscuous ( ) ) . timeout ( properties . getTimeout ( ) ) . immediateMode ( properties . getImmediate ( ) ) . timestampType ( properties . getTimestampType ( ) ) . direction ( properties . getDirection ( ) ) . timestampPrecision ( properties . getTimestampPrecision ( ) ) . rfmon ( properties . getRfmon ( ) ) . enableNonBlock ( ! properties . getBlocking ( ) ) . dataLinkType ( properties . getDatalink ( ) ) . fileName ( properties . getFile ( ) ) . errbuf ( errbuf ) ; return builder ; } | Pcap builder . |
7,130 | @ ConditionalOnClass ( { Pcap . class , Inet4Address . class , Context . class } ) @ Bean ( CONTEXT_BEAN_NAME ) public Context context ( @ Qualifier ( PCAP_BUILDER_BEAN_NAME ) Pcap . Builder builder , @ Qualifier ( NETMASK_BEAN_NAME ) Inet4Address netmask ) { switch ( properties . getPcapType ( ) ) { case DEAD : if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Opening pcap dead handler : {}" , builder ) ; } builder . pcapType ( Pcap . PcapType . DEAD ) ; break ; case OFFLINE : if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Opening pcap offline hadler : {}" , builder ) ; } builder . pcapType ( Pcap . PcapType . OFFLINE ) ; break ; default : if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Opening pcap live hadler : {}" , builder ) ; } builder . pcapType ( Pcap . PcapType . LIVE ) ; break ; } Application . run ( applicationName , applicationDisplayName , applicationVersion , builder ) ; Context context = Application . getApplicationContext ( ) ; if ( properties . getFilter ( ) != null ) { if ( context . pcapCompile ( properties . getFilter ( ) , properties . getBpfCompileMode ( ) , netmask . toInt ( ) ) == PcapCode . PCAP_OK ) { if ( context . pcapSetFilter ( ) != PcapCode . PCAP_OK ) { if ( LOGGER . isWarnEnabled ( ) ) { LOGGER . warn ( context . pcapGetErr ( ) ) ; } } else { LOGGER . debug ( "Filter \'{}\' has been applied." , this . properties . getFilter ( ) ) ; } } else { if ( LOGGER . isWarnEnabled ( ) ) { LOGGER . warn ( context . pcapGetErr ( ) ) ; } } } else { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "No filter has been applied." ) ; } } return context ; } | Jxnet application context . |
7,131 | public static Context getApplicationContext ( ) { com . ardikars . jxnet . context . Context context = com . ardikars . jxnet . context . Application . getApplicationContext ( ) ; return new ApplicationContext ( context ) ; } | Get application context . |
7,132 | public void load ( Callback < Void > callback , Class [ ] loadClasses ) { boolean doNotLoad = false ; for ( Class clazzes : loadClasses ) { try { Class . forName ( clazzes . getName ( ) ) ; } catch ( ClassNotFoundException e ) { callback . onFailure ( e ) ; doNotLoad = true ; } } if ( ! doNotLoad ) { doLoad ( callback ) ; } } | Load classes then perform load native library . |
7,133 | public static PcapIf pcapIf ( StringBuilder errbuf ) throws DeviceNotFoundException { String source = Application . source ; List < PcapIf > alldevsp = new ArrayList < PcapIf > ( ) ; if ( PcapFindAllDevs ( alldevsp , errbuf ) != OK && LOGGER . isLoggable ( Level . WARNING ) ) { LOGGER . warning ( "Error: {}" + errbuf . toString ( ) ) ; } if ( source == null || source . isEmpty ( ) ) { for ( PcapIf dev : alldevsp ) { for ( PcapAddr addr : dev . getAddresses ( ) ) { if ( addr . getAddr ( ) . getSaFamily ( ) == SockAddr . Family . AF_INET && addr . getAddr ( ) . getData ( ) != null ) { Inet4Address d = Inet4Address . valueOf ( addr . getAddr ( ) . getData ( ) ) ; if ( ! d . equals ( Inet4Address . LOCALHOST ) && ! d . equals ( Inet4Address . ZERO ) ) { return dev ; } } } } } else { for ( PcapIf dev : alldevsp ) { if ( dev . getName ( ) . equals ( source ) ) { return dev ; } } } throw new DeviceNotFoundException ( "No device connected to the network." ) ; } | Get default pcap interface . |
7,134 | public byte [ ] getData ( ) { if ( this . data == null ) { return new byte [ ] { } ; } if ( this . data . length == 0 ) { Family family = getSaFamily ( ) ; if ( family == Family . AF_INET6 ) { this . data = new byte [ Inet6Address . IPV6_ADDRESS_LENGTH ] ; } else { this . data = new byte [ Inet4Address . IPV4_ADDRESS_LENGTH ] ; } } byte [ ] data = new byte [ this . data . length ] ; System . arraycopy ( this . data , 0 , data , 0 , data . length ) ; return data ; } | Returns bytes address of SockAddr . |
7,135 | public SockAddr getAddr ( ) { SockAddr sockAddr = null ; if ( this . addr != null ) { sockAddr = new SockAddr ( this . addr . getSaFamily ( ) . getValue ( ) , this . addr . getData ( ) ) ; } return sockAddr ; } | Getting interface address . |
7,136 | public SockAddr getNetmask ( ) { SockAddr sockAddr = null ; if ( this . netmask != null ) { sockAddr = new SockAddr ( this . netmask . getSaFamily ( ) . getValue ( ) , this . netmask . getData ( ) ) ; } return sockAddr ; } | Getting interface netmask . |
7,137 | public SockAddr getBroadAddr ( ) { SockAddr sockAddr = null ; if ( this . broadaddr != null ) { sockAddr = new SockAddr ( this . broadaddr . getSaFamily ( ) . getValue ( ) , this . broadaddr . getData ( ) ) ; } return sockAddr ; } | Getting interface broadcast address . |
7,138 | public SockAddr getDstAddr ( ) { SockAddr sockAddr = null ; if ( this . dstaddr != null ) { sockAddr = new SockAddr ( this . dstaddr . getSaFamily ( ) . getValue ( ) , this . dstaddr . getData ( ) ) ; } return sockAddr ; } | Getting interface destination address . |
7,139 | public static PcapPktHdr newInstance ( final int caplen , final int len , final int tvSec , final long tvUsec ) { return new PcapPktHdr ( caplen , len , tvSec , tvUsec ) ; } | Create new PcapPktHdr instance . |
7,140 | public PcapPktHdr copy ( ) { PcapPktHdr pktHdr = new PcapPktHdr ( ) ; pktHdr . caplen = this . caplen ; pktHdr . len = this . len ; pktHdr . tv_sec = this . tv_sec ; pktHdr . tv_usec = this . tv_usec ; return pktHdr ; } | Copy this instance . |
7,141 | public void run ( String ... args ) { int maxIteration = 10 ; int totalMoreFast = 0 ; int totalMoreFastWithThreadPool = 0 ; int totalMoreFastPacketThreadPool = 0 ; for ( int i = 0 ; i < maxIteration ; i ++ ) { LOGGER . info ( "**********************************" ) ; long jxnetRunnerRes = jxnetRunner . run ( ) ; long jxnetWithThreadPoolRunnerRes = jxnetWithThreadPoolRunner . run ( ) ; long jxnetPacketThreadPoolRunnerRes = springJxnetWithThreadPoolRunner . run ( ) ; long pcap4jRunnerRes = pcap4jRunner . run ( ) ; long pcap4jWithThreadPoolRunnerRes = pcap4jWithThreadPoolRunner . run ( ) ; long pcap4jPacketThreadPoolRunnerRes = pcap4jPacketWithThreadPoolRunner . run ( ) ; LOGGER . info ( "Jxnet x Pcap4j" ) ; boolean moreFast = jxnetRunnerRes < pcap4jRunnerRes ; boolean moreFastWithThreadPool = jxnetWithThreadPoolRunnerRes < pcap4jWithThreadPoolRunnerRes ; boolean moreFastPacketThreadPool = jxnetPacketThreadPoolRunnerRes < pcap4jPacketThreadPoolRunnerRes ; if ( moreFast ) { totalMoreFast ++ ; } if ( moreFastWithThreadPool ) { totalMoreFastWithThreadPool ++ ; } if ( moreFastPacketThreadPool ) { totalMoreFastPacketThreadPool ++ ; } LOGGER . info ( "Is Jxnet runner more fast? {} : {}" , moreFast ? "YES" : "NO" , jxnetRunnerRes + " and " + pcap4jRunnerRes ) ; LOGGER . info ( "Is Jxnet with thread pool runner more fast? {} : {}" , moreFastWithThreadPool ? "YES" : "NO" , jxnetWithThreadPoolRunnerRes + " and " + pcap4jWithThreadPoolRunnerRes ) ; LOGGER . info ( "IS Jxnet packet with thread pool runner more fast? {} : {}" , moreFastPacketThreadPool ? "YES" : "NO" , jxnetPacketThreadPoolRunnerRes + " and " + pcap4jPacketThreadPoolRunnerRes ) ; LOGGER . info ( "**********************************\n" ) ; } LOGGER . info ( "Total jxnet more fast : {}/{}" , totalMoreFast , maxIteration ) ; LOGGER . info ( "Total jxnet more fast with thread pool : {}/{}" , totalMoreFastWithThreadPool , maxIteration ) ; LOGGER . info ( "Total jxnet more fast packet decoder with thread pool : {}/{}" , totalMoreFastPacketThreadPool , maxIteration ) ; executorService . shutdownNow ( ) ; } | Run bencmarking test . |
7,142 | protected Map < String , String > convertParameters ( WikiParameters params ) { Map < String , String > xwikiParams ; if ( params . getSize ( ) > 0 ) { xwikiParams = new LinkedHashMap < String , String > ( ) ; for ( WikiParameter wikiParameter : params . toList ( ) ) { xwikiParams . put ( wikiParameter . getKey ( ) , wikiParameter . getValue ( ) ) ; } } else { xwikiParams = Listener . EMPTY_PARAMETERS ; } return xwikiParams ; } | Convert Wikimodel parameters to XWiki parameters format . |
7,143 | protected Pair < Map < String , String > , Map < String , String > > convertAndSeparateParameters ( WikiParameters params ) { Map < String , String > resourceParameters ; Map < String , String > genericParameters ; if ( params . getSize ( ) > 0 ) { resourceParameters = new LinkedHashMap < String , String > ( ) ; genericParameters = new LinkedHashMap < String , String > ( ) ; for ( WikiParameter wikiParameter : params . toList ( ) ) { String key = wikiParameter . getKey ( ) ; if ( DocumentResourceReference . ANCHOR . equals ( key ) || DocumentResourceReference . QUERY_STRING . equals ( key ) ) { resourceParameters . put ( key , wikiParameter . getValue ( ) ) ; } else { genericParameters . put ( key , wikiParameter . getValue ( ) ) ; } } } else { resourceParameters = Listener . EMPTY_PARAMETERS ; genericParameters = Listener . EMPTY_PARAMETERS ; } return new ImmutablePair < Map < String , String > , Map < String , String > > ( resourceParameters , genericParameters ) ; } | Convert Wikimodel parameters to XWiki parameters format separating anchor and query string parameters which we consider ResourceReference parameters from the rest which we consider generic event parameters . |
7,144 | public void transferStart ( QueueListener eventsToTransfer ) { while ( ! eventsToTransfer . isEmpty ( ) ) { Event event = eventsToTransfer . removeLast ( ) ; this . previousEvents . offerFirst ( event ) ; } } | Transfer all passed events by removing the from the passed parameter and moving them to the beginning of the event stack . |
7,145 | public WikiFormat addStyle ( WikiStyle style ) { if ( fStyles . contains ( style ) ) { return this ; } WikiFormat clone = getClone ( ) ; clone . fStyles . add ( style ) ; return clone ; } | Creates a new style set and adds the given style to it . |
7,146 | public WikiFormat removeStyle ( WikiStyle style ) { if ( ! fStyles . contains ( style ) ) { return this ; } WikiFormat clone = getClone ( ) ; clone . fStyles . remove ( style ) ; return clone ; } | Creates a new style set which does not contain the specified style . |
7,147 | public static String escapeXmlString ( String str , boolean escapeQuots ) { if ( str == null ) { return "" ; } StringBuffer buf = new StringBuffer ( ) ; char [ ] array = str . toCharArray ( ) ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] == '>' || array [ i ] == '&' || array [ i ] == '<' || ( escapeQuots && ( array [ i ] == '\'' || array [ i ] == '"' ) ) ) { buf . append ( "&#x" + Integer . toHexString ( array [ i ] ) + ";" ) ; } else { buf . append ( array [ i ] ) ; } } return buf . toString ( ) ; } | Returns the escaped string . |
7,148 | private XDOM createXDOM ( String content , MacroTransformationContext macroContext , boolean transform , MetaData metadata , boolean inline , Syntax syntax ) throws MacroExecutionException { try { XDOM result = getSyntaxParser ( syntax ) . parse ( new StringReader ( content ) ) ; if ( metadata != null ) { result . getMetaData ( ) . addMetaData ( metadata ) ; } if ( transform && macroContext . getTransformation ( ) != null ) { TransformationContext txContext = new TransformationContext ( result , syntax ) ; txContext . setId ( macroContext . getId ( ) ) ; performTransformation ( ( MutableRenderingContext ) this . renderingContext , macroContext . getTransformation ( ) , txContext , result ) ; } if ( inline ) { result = convertToInline ( result ) ; } return result ; } catch ( Exception e ) { throw new MacroExecutionException ( "Failed to parse content [" + content + "]" , e ) ; } } | creates XDOM . |
7,149 | private void performTransformation ( MutableRenderingContext renderingContext , Transformation transformation , TransformationContext context , Block block ) throws MacroExecutionException { try { renderingContext . transformInContext ( transformation , context , block ) ; } catch ( Exception e ) { throw new MacroExecutionException ( "Failed to perform transformation" , e ) ; } } | Calls transformInContext on renderingContext . |
7,150 | private Parser getSyntaxParser ( Syntax syntax ) throws MacroExecutionException { try { return this . componentManager . getInstance ( Parser . class , syntax . toIdString ( ) ) ; } catch ( ComponentLookupException e ) { throw new MacroExecutionException ( "Failed to find source parser for syntax [" + syntax + "]" , e ) ; } } | Get the parser for the current syntax . |
7,151 | protected String computeLabel ( ResourceReference reference ) { String label ; try { URILabelGenerator uriLabelGenerator = this . componentManager . getInstance ( URILabelGenerator . class , reference . getType ( ) . getScheme ( ) ) ; label = uriLabelGenerator . generateLabel ( reference ) ; } catch ( ComponentLookupException e ) { label = reference . getReference ( ) ; } return label ; } | Default implementation for computing a link label when no label has been specified . Can be overwritten by implementations to provide a different algorithm . |
7,152 | private void handleTargetAttribute ( Map < String , String > anchorAttributes ) { String target = anchorAttributes . get ( "target" ) ; if ( StringUtils . isNotBlank ( target ) && ! "_self" . equals ( target ) && ! "_parent" . equals ( target ) && ! "_top" . equals ( target ) ) { List < String > relAttributes = new ArrayList < > ( ) ; String relAttribute = anchorAttributes . get ( REL ) ; if ( relAttribute != null ) { relAttributes . addAll ( Arrays . asList ( relAttribute . split ( " " ) ) ) ; } if ( ! relAttributes . contains ( NOOPENER ) ) { relAttributes . add ( NOOPENER ) ; } if ( ! relAttributes . contains ( NOREFERRER ) ) { relAttributes . add ( NOREFERRER ) ; } if ( ! relAttributes . isEmpty ( ) ) { anchorAttributes . put ( REL , String . join ( " " , relAttributes ) ) ; } } } | When a link is open in an other window or in an other frame the loaded page has some restricted access to the parent window . Among other things it has the ability to redirect it to an other page which can lead to dangerous phishing attacks . |
7,153 | private String addAttributeValue ( String currentValue , String valueToAdd ) { String newValue ; if ( currentValue == null || currentValue . length ( ) == 0 ) { newValue = "" ; } else { newValue = currentValue + " " ; } return newValue + valueToAdd ; } | Add an attribute value to an existing attribute . This is useful for example for adding a value to an HTML CLASS attribute . |
7,154 | public long indexOf ( Block child ) { CounterBlockMatcher counter = new CounterBlockMatcher ( child ) ; Block found = getFirstBlock ( counter , Axes . ANCESTOR_OR_SELF ) ; return found != null ? counter . getCount ( ) : - 1 ; } | Find the index of the block in the tree . |
7,155 | public final static String clearName ( String name ) { boolean stripDots = false ; boolean ascii = true ; return clearName ( name , stripDots , ascii ) ; } | Clears the name of files ; used while uploading attachments within XWiki |
7,156 | public static int getHtmlCodeByHtmlEntity ( String htmlEntity ) { Entity entity = fHtmlToWiki . get ( htmlEntity ) ; return entity != null ? entity . fHtmlCode : 0 ; } | Returns an HTML code corresponding to the specified HTML entity . |
7,157 | public static int getHtmlCodeByWikiSymbol ( String wikiEntity ) { Entity entity = fWikiToHtml . get ( wikiEntity ) ; return entity != null ? entity . fHtmlCode : 0 ; } | Returns an HTML code corresponding to the specified wiki entity . |
7,158 | public static boolean matchesSequence ( char [ ] array , int arrayPos , char [ ] sequence ) { int i ; int j ; for ( i = arrayPos , j = 0 ; i < array . length && j < sequence . length ; i ++ , j ++ ) { if ( array [ i ] != sequence [ j ] ) { break ; } } return j == sequence . length ; } | Indicate if the specified sequence starts from the given position in the character array . |
7,159 | private static int removeSpaces ( char [ ] array , int pos , StringBuffer buf ) { buf . delete ( 0 , buf . length ( ) ) ; for ( ; pos < array . length && ( array [ pos ] == '=' || Character . isSpaceChar ( array [ pos ] ) ) ; pos ++ ) { if ( array [ pos ] == '=' ) { buf . append ( array [ pos ] ) ; } } return pos ; } | Moves forward the current position in the array until the first not empty character is found . |
7,160 | public static int skipSequence ( char [ ] array , int arrayPos , char [ ] sequence ) { int i ; int j ; for ( i = arrayPos , j = 0 ; i < array . length && j < sequence . length ; i ++ , j ++ ) { if ( array [ i ] != sequence [ j ] ) { break ; } } return j == sequence . length ? i : arrayPos ; } | Skips the specified sequence if it starts from the given position in the character array . |
7,161 | public static int splitToPairs ( String str , List < WikiParameter > list , String delimiter , String end , char escapeChar ) { if ( str == null ) { return 0 ; } char [ ] array = str . toCharArray ( ) ; if ( delimiter == null ) { delimiter = " " ; } char [ ] delimiterArray = delimiter . toCharArray ( ) ; char [ ] endArray = end != null ? end . toCharArray ( ) : new char [ 0 ] ; StringBuffer buf = new StringBuffer ( ) ; int i = 0 ; boolean [ ] trim = { false } ; for ( ; i < array . length ; ) { String key = null ; String value = null ; i = removeSpaces ( array , i , buf ) ; if ( i >= array . length ) { break ; } int prev = i ; i = skipSequence ( array , i , delimiterArray ) ; if ( i >= array . length ) { break ; } if ( i > prev ) { i = removeSpaces ( array , i , buf ) ; if ( i >= array . length ) { break ; } } if ( end != null && matchesSequence ( array , i , endArray ) ) { break ; } i = getNextToken ( array , i , delimiterArray , buf , trim , escapeChar ) ; key = buf . toString ( ) . trim ( ) ; i = removeSpaces ( array , i , buf ) ; if ( buf . indexOf ( "=" ) >= 0 ) { i = getNextToken ( array , i , delimiterArray , buf , trim , escapeChar ) ; value = buf . toString ( ) ; if ( trim [ 0 ] ) { value = value . trim ( ) ; } } WikiParameter entry = new WikiParameter ( key , value ) ; list . add ( entry ) ; } return i ; } | Splits the given string into a set of key - value pairs ; all extracted values will be added to the given list |
7,162 | public static String unescape ( String str , char escape ) { if ( str == null ) { return "" ; } StringBuffer buf = new StringBuffer ( ) ; char [ ] array = str . toCharArray ( ) ; boolean escaped = false ; for ( int i = 0 ; i < array . length ; i ++ ) { char ch = array [ i ] ; if ( escaped ) { buf . append ( ch ) ; escaped = false ; } else { escaped = ( ch == escape ) ; if ( ! escaped ) { buf . append ( ch ) ; } } } return buf . toString ( ) ; } | Unescapes the given string and returns the result . |
7,163 | protected void processLinkQueue ( ) { long timeout = this . configuration . getCheckTimeout ( ) ; List < Pattern > excludedReferencePatterns = this . configuration . getExcludedReferencePatterns ( ) ; LinkQueueItem queueItem = null ; boolean shouldBeChecked = false ; while ( ! this . linkQueue . isEmpty ( ) && ! shouldBeChecked ) { queueItem = this . linkQueue . poll ( ) ; shouldBeChecked = isExcluded ( queueItem . getContentReference ( ) , excludedReferencePatterns ) ; if ( ! shouldBeChecked ) { break ; } Map < String , LinkState > contentReferences = this . linkStateManager . getLinkStates ( ) . get ( queueItem . getLinkReference ( ) ) ; if ( contentReferences != null ) { LinkState state = contentReferences . get ( queueItem . getContentReference ( ) ) ; if ( state != null && ( System . currentTimeMillis ( ) - state . getLastCheckedTime ( ) <= timeout ) ) { shouldBeChecked = false ; } } } if ( shouldBeChecked && queueItem != null ) { checkLink ( queueItem ) ; } } | Read the queue and find links to process removing links that have already been checked out recently . |
7,164 | private Block generateTree ( List < HeaderBlock > headers , int start , int depth , boolean numbered , String documentReference ) { Block tocBlock = null ; int currentLevel = start - 1 ; Block currentBlock = null ; for ( HeaderBlock headerBlock : headers ) { int headerLevel = headerBlock . getLevel ( ) . getAsInt ( ) ; if ( headerLevel >= start && headerLevel <= depth ) { if ( currentLevel < headerLevel ) { while ( currentLevel < headerLevel ) { if ( currentBlock instanceof ListBLock ) { currentBlock = addItemBlock ( currentBlock , null , documentReference ) ; } currentBlock = createChildListBlock ( numbered , currentBlock ) ; ++ currentLevel ; } } else { while ( currentLevel > headerLevel ) { currentBlock = currentBlock . getParent ( ) . getParent ( ) ; -- currentLevel ; } currentBlock = currentBlock . getParent ( ) ; } currentBlock = addItemBlock ( currentBlock , headerBlock , documentReference ) ; } } if ( currentBlock != null ) { tocBlock = currentBlock . getRoot ( ) ; } return tocBlock ; } | Convert headers into list block tree . |
7,165 | private ListItemBlock createTocEntry ( HeaderBlock headerBlock , String documentReference ) { DocumentResourceReference reference = new DocumentResourceReference ( documentReference ) ; reference . setAnchor ( headerBlock . getId ( ) ) ; LinkBlock linkBlock = new LinkBlock ( this . tocBlockFilter . generateLabel ( headerBlock ) , reference , false ) ; return new ListItemBlock ( Collections . singletonList ( linkBlock ) ) ; } | Create a new toc list item based on section title . |
7,166 | private ListBLock createChildListBlock ( boolean numbered , Block parentBlock ) { ListBLock childListBlock = numbered ? new NumberedListBlock ( Collections . emptyList ( ) ) : new BulletedListBlock ( Collections . emptyList ( ) ) ; if ( parentBlock != null ) { parentBlock . addChild ( childListBlock ) ; } return childListBlock ; } | Create a new ListBlock and add it in the provided parent block . |
7,167 | private void appendInlineEvent ( Event event ) throws SAXException { cleanContentLeadingSpaces ( ) ; cleanContentExtraWhiteSpaces ( ) ; if ( getContent ( ) . length ( ) > 0 ) { sendPreviousContent ( false ) ; fPreviousInlineText . append ( getContent ( ) ) ; if ( getContent ( ) . charAt ( getContent ( ) . length ( ) - 1 ) == ' ' ) { fPreviousContent = getContent ( ) . toString ( ) ; fPreviousElements . add ( event ) ; } else { sendCharacters ( getContent ( ) . toString ( ) . toCharArray ( ) ) ; sendInlineEvent ( event ) ; } getContent ( ) . setLength ( 0 ) ; } else { if ( fPreviousInlineText . length ( ) == 0 ) { sendInlineEvent ( event ) ; } else { fPreviousElements . add ( event ) ; } } } | Append an inline element . Inline elements ending with a space are stacked waiting for a non space character or the end of the inline content . |
7,168 | protected void startNonVisibleElement ( ) throws SAXException { if ( shouldRemoveWhiteSpaces ( ) ) { cleanContentLeadingSpaces ( ) ; cleanContentExtraWhiteSpaces ( ) ; if ( getContent ( ) . length ( ) > 0 ) { sendPreviousContent ( false ) ; fPreviousInlineText . append ( getContent ( ) ) ; if ( getContent ( ) . charAt ( getContent ( ) . length ( ) - 1 ) == ' ' ) { fPreviousContent = getContent ( ) . toString ( ) ; } else { sendCharacters ( getContent ( ) . toString ( ) . toCharArray ( ) ) ; } } if ( fPreviousContent != null ) { sendCharacters ( fPreviousContent . toCharArray ( ) , 0 , fPreviousContent . length ( ) - 1 ) ; fPreviousContent = " " ; } } else { sendCharacters ( getContent ( ) . toString ( ) . toCharArray ( ) ) ; } getContent ( ) . setLength ( 0 ) ; ++ fNoCleanUpLevel ; } | Append an non visible element . |
7,169 | protected void trimLeadingWhiteSpaces ( ) { if ( shouldRemoveWhiteSpaces ( ) && getContent ( ) . length ( ) > 0 ) { String result = trimLeadingWhiteSpaces ( getContent ( ) ) ; getContent ( ) . setLength ( 0 ) ; getContent ( ) . append ( result ) ; } } | when in CDATA or PRE elements ) . |
7,170 | private String cleanHTML ( String content , MacroTransformationContext context ) throws MacroExecutionException { String cleanedContent = content ; HTMLCleanerConfiguration cleanerConfiguration = getCleanerConfiguration ( context ) ; Document document = this . htmlCleaner . clean ( new StringReader ( cleanedContent ) , cleanerConfiguration ) ; HTMLUtils . stripHTMLEnvelope ( document ) ; if ( context . isInline ( ) ) { Element root = document . getDocumentElement ( ) ; if ( root . getChildNodes ( ) . getLength ( ) == 1 && root . getFirstChild ( ) . getNodeType ( ) == Node . ELEMENT_NODE && root . getFirstChild ( ) . getNodeName ( ) . equalsIgnoreCase ( "p" ) ) { HTMLUtils . stripFirstElementInside ( document , HTMLConstants . TAG_HTML , HTMLConstants . TAG_P ) ; } else { throw new MacroExecutionException ( "When using the HTML macro inline, you can only use inline HTML content." + " Block HTML content (such as tables) cannot be displayed." + " Try leaving an empty line before and after the HTML macro." ) ; } } cleanedContent = HTMLUtils . toString ( document , true , true ) ; cleanedContent = cleanedContent . substring ( 7 , cleanedContent . length ( ) - 8 ) ; return cleanedContent ; } | Clean the HTML entered by the user transforming it into valid XHTML . |
7,171 | private String renderWikiSyntax ( String content , Transformation transformation , MacroTransformationContext context ) throws MacroExecutionException { String xhtml ; try { XDOM xdom = this . contentParser . parse ( content , context , false , false ) ; List < MacroBlock > macros = xdom . getBlocks ( MACROBLOCKMATCHER , Axes . DESCENDANT ) ; for ( MacroBlock macro : macros ) { if ( "html" . equals ( macro . getId ( ) ) ) { macro . setParameter ( "clean" , "false" ) ; } } MacroBlock htmlMacroBlock = context . getCurrentMacroBlock ( ) ; MacroMarkerBlock htmlMacroMarker = new MacroMarkerBlock ( htmlMacroBlock . getId ( ) , htmlMacroBlock . getParameters ( ) , htmlMacroBlock . getContent ( ) , xdom . getChildren ( ) , htmlMacroBlock . isInline ( ) ) ; htmlMacroBlock . getParent ( ) . replaceChild ( htmlMacroMarker , htmlMacroBlock ) ; try { ( ( MutableRenderingContext ) this . renderingContext ) . transformInContext ( transformation , context . getTransformationContext ( ) , htmlMacroMarker ) ; } finally { htmlMacroMarker . getParent ( ) . replaceChild ( htmlMacroBlock , htmlMacroMarker ) ; } WikiPrinter printer = new DefaultWikiPrinter ( ) ; PrintRenderer renderer = this . xhtmlRendererFactory . createRenderer ( printer ) ; for ( Block block : htmlMacroMarker . getChildren ( ) ) { block . traverse ( renderer ) ; } xhtml = printer . toString ( ) ; } catch ( Exception e ) { throw new MacroExecutionException ( "Failed to parse content [" + content + "]." , e ) ; } return xhtml ; } | Parse the passed context using a wiki syntax parser and render the result as an XHTML string . |
7,172 | protected WikiParameters getParameters ( String [ ] chunks ) { return WikiParameters . newWikiParameters ( chunks . length > 2 ? chunks [ 2 ] . trim ( ) : null ) ; } | Extracts parameters part of the original reference and returns it as a WikiParameters . |
7,173 | protected String [ ] splitToChunks ( String str ) { String delimiter = "[|>]" ; String [ ] chunks = str . split ( delimiter ) ; return chunks ; } | Returns the given string split to individual segments |
7,174 | private void addFootnoteRef ( MacroMarkerBlock footnoteMacro , Block footnoteRef ) { footnoteMacro . getChildren ( ) . clear ( ) ; footnoteMacro . addChild ( footnoteRef ) ; } | Add a footnote to the list of document footnotes . If such a list doesn t exist yet create it and append it to the end of the document . |
7,175 | private ListItemBlock createFootnoteBlock ( String content , int counter , MacroTransformationContext context ) throws MacroExecutionException { List < Block > parsedContent ; try { parsedContent = this . contentParser . parse ( content , context , false , true ) . getChildren ( ) ; } catch ( MacroExecutionException e ) { parsedContent = Collections . < Block > singletonList ( new WordBlock ( content ) ) ; } Block result = new WordBlock ( "^" ) ; DocumentResourceReference reference = new DocumentResourceReference ( null ) ; reference . setAnchor ( FOOTNOTE_REFERENCE_ID_PREFIX + counter ) ; result = new LinkBlock ( Collections . singletonList ( result ) , reference , false ) ; result . setParameter ( ID_ATTRIBUTE_NAME , FOOTNOTE_ID_PREFIX + counter ) ; result . setParameter ( CLASS_ATTRIBUTE_NAME , "footnoteBackRef" ) ; result = new ListItemBlock ( Collections . singletonList ( result ) ) ; result . addChild ( new SpaceBlock ( ) ) ; result . addChildren ( parsedContent ) ; return ( ListItemBlock ) result ; } | Generate the footnote block a numbered list item containing a backlink to the footnote s reference and the actual footnote text parsed into XDOM . |
7,176 | public WikiParameter [ ] getParameters ( String key ) { Map < String , WikiParameter [ ] > map = getParameters ( ) ; WikiParameter [ ] list = map . get ( key ) ; return list ; } | Returns all parameters with this key |
7,177 | public List < WikiParameter > toList ( ) { List < WikiParameter > result = new ArrayList < WikiParameter > ( fList ) ; return result ; } | Returns a new list containing all parameters defined in this object . |
7,178 | private void beginInternalLink ( ResourceReference reference , boolean freestanding , Map < String , String > parameters ) { Map < String , String > spanAttributes = new LinkedHashMap < String , String > ( ) ; Map < String , String > anchorAttributes = new LinkedHashMap < String , String > ( ) ; anchorAttributes . putAll ( parameters ) ; if ( StringUtils . isEmpty ( reference . getReference ( ) ) ) { spanAttributes . put ( CLASS , WIKILINK ) ; renderAutoLink ( reference , spanAttributes , anchorAttributes ) ; } else if ( this . wikiModel . isDocumentAvailable ( reference ) ) { spanAttributes . put ( CLASS , WIKILINK ) ; anchorAttributes . put ( XHTMLLinkRenderer . HREF , this . wikiModel . getDocumentViewURL ( reference ) ) ; } else { spanAttributes . put ( CLASS , "wikicreatelink" ) ; anchorAttributes . put ( XHTMLLinkRenderer . HREF , this . wikiModel . getDocumentEditURL ( reference ) ) ; } getXHTMLWikiPrinter ( ) . printXMLStartElement ( SPAN , spanAttributes ) ; getXHTMLWikiPrinter ( ) . printXMLStartElement ( XHTMLLinkRenderer . ANCHOR , anchorAttributes ) ; } | Start of an internal link . |
7,179 | public void normalize ( Set < String > testNames , Map < String , Pair < Set < Test > , Set < Test > > > tests ) { for ( Pair < Set < Test > , Set < Test > > inOutTests : tests . values ( ) ) { addNotApplicableTests ( testNames , inOutTests . getLeft ( ) ) ; addNotApplicableTests ( testNames , inOutTests . getRight ( ) ) ; } } | Add not applicable tests for all syntaxes . |
7,180 | private static SyntaxType register ( String id , String name ) { SyntaxType syntaxType = new SyntaxType ( id , name ) ; KNOWN_SYNTAX_TYPES . put ( id , syntaxType ) ; return syntaxType ; } | Register a Syntax Type . |
7,181 | public void onMacro ( String name , WikiParameters params , String content ) { checkBlockContainer ( ) ; fMacroName = name ; fMacroParameters = params ; fMacroContent = content ; } | Waiting for following events to know if the macro is inline or not . |
7,182 | public void onVerbatim ( String str , WikiParameters params ) { checkBlockContainer ( ) ; fVerbatimContent = str ; fVerbatimParameters = params ; } | Waiting for following events to know if the verbatim is inline or not . |
7,183 | protected Parser getSyntaxParser ( Syntax syntax ) throws MacroExecutionException { if ( this . componentManager . hasComponent ( Parser . class , syntax . toIdString ( ) ) ) { try { return this . componentManager . getInstance ( Parser . class , syntax . toIdString ( ) ) ; } catch ( ComponentLookupException e ) { throw new MacroExecutionException ( String . format ( "Failed to lookup Parser for syntax [%s]" , syntax . toIdString ( ) ) , e ) ; } } else { throw new MacroExecutionException ( String . format ( "Cannot find Parser for syntax [%s]" , syntax . toIdString ( ) ) ) ; } } | Get the parser for the passed Syntax . |
7,184 | private void parseReference ( char [ ] array , int i , StringBuffer reference , StringBuffer parameters ) { int nb ; for ( boolean escaped = false ; i < array . length ; ++ i ) { char c = array [ i ] ; if ( ! escaped ) { if ( array [ i ] == '~' && ! escaped ) { escaped = true ; } else if ( ( nb = countFirstChar ( array , i , '|' ) ) >= 2 ) { for ( ; nb > 2 ; -- nb ) { reference . append ( array [ i ++ ] ) ; } i += 2 ; parameters . append ( array , i , array . length - i ) ; break ; } else { reference . append ( c ) ; } } else { reference . append ( c ) ; escaped = false ; } } } | Extract the link and the parameters . |
7,185 | public void printXMLComment ( String content , boolean escape ) { try { this . xmlWriter . write ( new DefaultComment ( escape ? XMLUtils . escapeXMLComment ( content ) : content ) ) ; } catch ( IOException e ) { } } | Print a XML comment . |
7,186 | public Event getEvent ( int depth ) { Event event = null ; if ( depth > 0 && size ( ) > depth - 1 ) { event = get ( depth - 1 ) ; } return event ; } | Returns the event at the specified position in this queue . |
7,187 | private Listener popListener ( ) { Listener listener = this . listenerStack . pop ( ) ; if ( ! this . listenerStack . isEmpty ( ) ) { setWrappedListener ( this . listenerStack . peek ( ) ) ; } return listener ; } | Removes the last listener from the stack . |
7,188 | public static char getChar ( String symbol ) { CharInfo info = ( CharInfo ) fSymbolMap . get ( symbol ) ; return ( info != null ) ? ( char ) info . fCode : '\0' ; } | A character corresponding to the given symbol . |
7,189 | public static String getDescription ( char ch ) { CharInfo info = ( CharInfo ) fCodeMap . get ( Integer . valueOf ( ch ) ) ; return ( info != null ) ? info . fDescription : null ; } | Returns description of the given character |
7,190 | public static String getDescription ( String symbol ) { CharInfo info = ( CharInfo ) fSymbolMap . get ( symbol ) ; return ( info != null ) ? info . fDescription : null ; } | Returns description of the given symbol . |
7,191 | public void generateError ( MacroBlock macroToReplace , String message , Throwable throwable ) { List < Block > errorBlocks = this . errorBlockGenerator . generateErrorBlocks ( message , throwable , macroToReplace . isInline ( ) ) ; macroToReplace . getParent ( ) . replaceChild ( wrapInMacroMarker ( macroToReplace , errorBlocks ) , macroToReplace ) ; } | Generates Blocks to signify that the passed Macro Block has failed to execute . |
7,192 | private void mergeTree ( Block targetTree , Block sourceTree ) { for ( Block block : sourceTree . getChildren ( ) ) { int pos = indexOf ( targetTree . getChildren ( ) , block ) ; if ( pos > - 1 ) { Block foundBlock = targetTree . getChildren ( ) . get ( pos ) ; mergeTree ( foundBlock , block ) ; } else { targetTree . addChild ( block ) ; } } } | Merged two XDOM trees . |
7,193 | private int indexOf ( List < Block > targetBlocks , Block block ) { int pos = 0 ; for ( Block targetBlock : targetBlocks ) { if ( blockEquals ( targetBlock , block ) ) { return pos ; } pos ++ ; } return - 1 ; } | Shallow indexOf implementation that only compares nodes based on their data and not their children data . |
7,194 | private void parseTree ( List < Block > sourceBlocks ) { Block matchStartBlock = null ; int count = 0 ; Block mappingCursor = this . mappingTree . getChildren ( ) . get ( 0 ) ; Block sourceBlock = sourceBlocks . get ( 0 ) ; while ( sourceBlock != null ) { while ( mappingCursor != null ) { if ( blockEquals ( sourceBlock , mappingCursor ) ) { if ( matchStartBlock == null ) { matchStartBlock = sourceBlock ; } count ++ ; mappingCursor = mappingCursor . getChildren ( ) . get ( 0 ) ; if ( mappingCursor instanceof ImageBlock ) { for ( int i = 0 ; i < count - 1 ; i ++ ) { matchStartBlock . getParent ( ) . removeBlock ( matchStartBlock . getNextSibling ( ) ) ; } sourceBlock = mappingCursor . clone ( ) ; matchStartBlock . getParent ( ) . replaceChild ( sourceBlock , matchStartBlock ) ; mappingCursor = null ; matchStartBlock = null ; count = 0 ; } else { break ; } } else { mappingCursor = mappingCursor . getNextSibling ( ) ; } } List < Block > filteredSourceBlocks = this . filter . filter ( sourceBlock . getChildren ( ) ) ; if ( ! filteredSourceBlocks . isEmpty ( ) ) { parseTree ( filteredSourceBlocks ) ; } else if ( mappingCursor == null ) { mappingCursor = this . mappingTree . getChildren ( ) . get ( 0 ) ; count = 0 ; matchStartBlock = null ; } sourceBlock = this . filter . getNextSibling ( sourceBlock ) ; } } | Parse a list of blocks and replace suite of Blocks matching the icon mapping definitions by image blocks . |
7,195 | private static BufferedImage createThumb ( BufferedImage image , int thumbWidth , int thumbHeight ) { int imageWidth = image . getWidth ( null ) ; int imageHeight = image . getHeight ( null ) ; int [ ] size = getNewSize ( imageWidth , imageHeight , thumbWidth , thumbHeight ) ; if ( size [ 0 ] == imageWidth && size [ 1 ] == imageHeight ) { return image ; } BufferedImage thumbImage = new BufferedImage ( size [ 0 ] , size [ 1 ] , BufferedImage . TYPE_INT_RGB ) ; Graphics2D graphics2D = thumbImage . createGraphics ( ) ; graphics2D . setRenderingHint ( RenderingHints . KEY_INTERPOLATION , RenderingHints . VALUE_INTERPOLATION_BILINEAR ) ; graphics2D . drawImage ( image , 0 , 0 , thumbWidth , thumbHeight , null ) ; return thumbImage ; } | Creates a smaller version of an image or returns the original image if it was in the specified boundaries . The returned image keeps the ratio of the original image . |
7,196 | public static int [ ] getImageSize ( InputStream input , int maxWidth , int maxHeight ) throws IOException { int [ ] size = getImageSize ( input ) ; return getNewSize ( size [ 0 ] , size [ 1 ] , maxWidth , maxHeight ) ; } | Returns the possible size of an image from the given input stream ; the returned size does not overcome the specified maximal borders but keeps the ratio of the image . This method closes the given stream . |
7,197 | public static int [ ] getNewSize ( int width , int height , int maxWidth , int maxHeight ) { if ( width <= maxWidth && height <= maxHeight ) { return new int [ ] { width , height } ; } double thumbRatio = ( double ) maxWidth / ( double ) maxHeight ; double imageRatio = ( double ) width / ( double ) height ; if ( thumbRatio < imageRatio ) { maxHeight = ( int ) ( maxWidth / imageRatio ) ; } else { maxWidth = ( int ) ( maxHeight * imageRatio ) ; } return new int [ ] { maxWidth , maxHeight } ; } | Calculates new size of an image with the specified max borders keeping the ratio between height and width of the image . |
7,198 | public void addBlock ( Block block ) { try { this . stack . getFirst ( ) . add ( block ) ; } catch ( NoSuchElementException e ) { throw new IllegalStateException ( "All container blocks are closed, too many calls to endBlockList()." ) ; } } | Add a block to the current block container . |
7,199 | private int readChar ( Reader source ) throws ParseException { int c ; try { c = source . read ( ) ; } catch ( IOException e ) { throw new ParseException ( "Failed to read input source" , e ) ; } return c ; } | Read a single char from an Reader source . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.