idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
14,700
protected synchronized Response netCall ( Request request , int timeout ) { Response response = null ; if ( serverCaps != null && serverCaps . isDebugMode ( ) ) { timeout = 0 ; } try { socket . setSoTimeout ( timeout ) ; DataOutputStream requestPacket = new DataOutputStream ( new BufferedOutputStream ( socket . getOutputStream ( ) ) ) ; request . write ( requestPacket , nextSequenceId ( ) ) ; requestPacket . flush ( ) ; DataInputStream responsePacket = new DataInputStream ( new BufferedInputStream ( socket . getInputStream ( ) ) ) ; response = new Response ( responsePacket ) ; if ( response . getSequenceId ( ) != request . getSequenceId ( ) ) { throw new IOException ( "Response is not for current request." ) ; } } catch ( Exception e ) { netFlush ( ) ; throw MiscUtil . toUnchecked ( e ) ; } if ( response . getResponseType ( ) == ResponseType . ERROR ) { throw new RPCException ( response . getData ( ) ) ; } return response ; }
Issues a request to the server returning the response .
14,701
public void addHostEventHandler ( IHostEventHandler hostEventHandler ) { synchronized ( hostEventHandlers ) { if ( ! hostEventHandlers . contains ( hostEventHandler ) ) { hostEventHandlers . add ( hostEventHandler ) ; } } }
Adds an event handler for background polling events .
14,702
protected void onRPCError ( int asyncHandle , int asyncError , String text ) { IAsyncRPCEvent callback = getCallback ( asyncHandle ) ; if ( callback != null ) { callback . onRPCError ( asyncHandle , asyncError , text ) ; } }
Invokes the callback for the specified handle when an error is encountered during an asynchronous RPC call .
14,703
protected void onRPCComplete ( int asyncHandle , String data ) { IAsyncRPCEvent callback = getCallback ( asyncHandle ) ; if ( callback != null ) { callback . onRPCComplete ( asyncHandle , data ) ; } }
Invokes the callback for the specified handle upon successful completion of an asynchronous RPC call .
14,704
public void setSerializationMethod ( SerializationMethod serializationMethod ) { if ( serializationMethod == SerializationMethod . NULL ) { throw new IllegalArgumentException ( "Invalid serialization method." ) ; } this . serializationMethod = serializationMethod == null ? SerializationMethod . JSON : serializationMethod ; }
Sets the serialization method to be used when sending objects .
14,705
public static Validator getExperimentalValidator ( ) { return CascadingValidator . create ( ParenthesesValidator . INSTANCE , ConfigurableValidator . create ( ValidatorConfiguration . createExperimental ( ) ) ) ; }
This validator includes support for the experimental gdl keyword and associated GDL variants .
14,706
public < T > void handleEvent ( final T event ) throws EventException { final Class < ? > type = event . getClass ( ) ; if ( ! this . cachedListeners . containsKey ( event . getClass ( ) ) ) { this . cachedListeners . put ( type , new LinkedList < ListenerInstancePair < ? > > ( ) ) ; for ( final ListenerInstancePair < ? > listener : this . listeners ) { final Type observableType = GenericsUtil . getEntityGenericType ( listener . listener . getClass ( ) , 0 , Listener . class ) ; final Class < ? > observable = GenericsUtil . guessClazz ( observableType ) ; if ( observable . isAssignableFrom ( type ) ) { this . cachedListeners . get ( type ) . add ( listener ) ; } } } @ SuppressWarnings ( "unchecked" ) final List < ListenerInstancePair < T > > resolvedListeners = List . class . cast ( this . cachedListeners . get ( event . getClass ( ) ) ) ; for ( final ListenerInstancePair < T > listener : resolvedListeners ) { listener . handleEvent ( event , null ) ; } }
Handle an event .
14,707
public Dimension getPreferredSize ( ) { if ( this . getParent ( ) != null ) return new Dimension ( this . getParent ( ) . getWidth ( ) / 3 , super . getPreferredSize ( ) . height ) ; return super . getPreferredSize ( ) ; }
Preferred panel size .
14,708
private String removeAbsoluteRootPathElement ( String xPath ) { String trimmedXpath = xPath ; if ( xPath . startsWith ( "/" ) && xPath . charAt ( 1 ) != '/' ) { trimmedXpath = xPath . substring ( 1 ) ; } return trimmedXpath ; }
we stop absolute queries on sub - roots from failing
14,709
private void injectInto ( final Object target , final boolean oneMatch ) throws AssertionError { boolean success = false ; for ( final Field field : this . collectFieldCandidates ( target ) ) { if ( this . isMatching ( field ) ) { Object val = getValue ( field ) ; try { field . setAccessible ( true ) ; this . inject ( target , field , val ) ; success = true ; } catch ( IllegalArgumentException | IllegalAccessException e ) { throw new AssertionError ( "Injection of " + val + " into " + target + " failed" , e ) ; } if ( oneMatch ) { return ; } } } assertTrue ( "No matching field for injection found" , success ) ; }
Injects the value of the Injection into the target .
14,710
private List < Field > collectFieldCandidates ( final Object target ) { final Class < ? > targetClass = target . getClass ( ) ; return this . collectFieldCandidates ( this . value , targetClass ) ; }
Determines all fields that are candidates for the injection as their type is compatible with the injected object . The method checks the target objects type and supertypes for declared fields .
14,711
private List < Field > collectFieldCandidates ( final Object injectedValue , final Class < ? > targetClass ) { final List < Field > fieldCandidates = new ArrayList < > ( ) ; Class < ? > current = targetClass ; while ( current != Object . class ) { fieldCandidates . addAll ( this . collectionDeclaredFieldCandidates ( injectedValue , current ) ) ; current = current . getSuperclass ( ) ; } return fieldCandidates ; }
Collects all matching declared fields of the target class and returns the result as a list .
14,712
private boolean isNullOrMatchingType ( final Object injectedValue , final Field field ) { if ( injectedValue == null ) { return true ; } final Class < ? > fieldType = field . getType ( ) ; final Class < ? > valueType = injectedValue . getClass ( ) ; if ( fieldType . isPrimitive ( ) ) { return fieldType == primitiveTypeFor ( valueType ) ; } return fieldType . isAssignableFrom ( valueType ) ; }
Checks if the specified value is either null or compatible with the field . Compatibility is verified based on inheritance or primitive - type compatibility .
14,713
private List < Field > collectionDeclaredFieldCandidates ( final Object injectedValue , final Class < ? > targetClass ) { final List < Field > fieldCandidates = new ArrayList < > ( ) ; for ( final Field field : targetClass . getDeclaredFields ( ) ) { if ( this . isFieldCandidate ( field , injectedValue ) ) { fieldCandidates . add ( field ) ; } } return fieldCandidates ; }
Collects all declared fields from the targetClass that are type - compatible with the class of the injected value into the fieldCandidates list .
14,714
public static Set < Field > getDeclaredFields ( Class < ? > clazz , FieldFilter filter ) { Set < Field > fields = new HashSet < Field > ( ) ; Field [ ] allFields = clazz . getDeclaredFields ( ) ; for ( Field field : allFields ) { if ( filter . passFilter ( field ) ) { fields . add ( field ) ; } } return fields ; }
Returns a set of all fields matching the supplied filter declared in the clazz class .
14,715
public Record moveRecordToBase ( Record record ) { SharedBaseRecordTable sharedTable = this . getSharedTable ( ) ; sharedTable . setCurrentRecord ( record ) ; boolean bCopyEditMode = false ; boolean bOnlyModifiedFields = false ; Record recBase = sharedTable . getBaseRecord ( ) ; sharedTable . copyRecordInfo ( recBase , record , bCopyEditMode , bOnlyModifiedFields ) ; return recBase ; }
Copy this record to the base table .
14,716
public static < T , R , V > Function < T , V > compose ( final Function < T , R > first , final Function < ? super R , ? extends V > second ) { return new Function < T , V > ( ) { public V apply ( T argument ) { return second . apply ( first . apply ( argument ) ) ; } } ; }
Create a function that uses the result of the first function as the input to the second .
14,717
public static < F , S , R , V > BiFunction < F , S , V > andThen ( final BiFunction < F , S , R > first , final Function < ? super R , ? extends V > second ) { return new BiFunction < F , S , V > ( ) { public V apply ( F f , S s ) { return second . apply ( first . apply ( f , s ) ) ; } } ; }
Compose a BiFunction which applies a Function to the result of another BiFunction .
14,718
public static < T > Consumer < T > andThen ( final Consumer < T > first , final Consumer < T > second ) { return new Consumer < T > ( ) { public void accept ( T consumable ) { first . accept ( consumable ) ; second . accept ( consumable ) ; } } ; }
Compose a new consumer from two existing ones . The consumable will be passed to the first then the second .
14,719
public static final void xmlConfig ( File configFile ) throws IOException { try { JAXBContext jaxbCtx = JAXBContext . newInstance ( "org.vesalainen.util.jaxb" ) ; Unmarshaller unmarshaller = jaxbCtx . createUnmarshaller ( ) ; JavaLoggingConfig javaLoggingConfig = ( JavaLoggingConfig ) unmarshaller . unmarshal ( configFile ) ; Map < String , String > expressionMap = new HashMap < > ( ) ; Properties properties = javaLoggingConfig . getProperties ( ) ; if ( properties != null ) { for ( Element element : properties . getAny ( ) ) { String property = element . getTagName ( ) ; String expression = element . getTextContent ( ) ; expressionMap . put ( property , expression ) ; } } ExpressionParser ep = new ExpressionParser ( expressionMap ) ; for ( LoggerType loggerType : javaLoggingConfig . getLogger ( ) ) { String name = ep . replace ( loggerType . getName ( ) ) ; JavaLogging javaLogging = getLogger ( name ) ; Logger logger = javaLogging . getLogger ( ) ; String lev = ep . replace ( loggerType . getLevel ( ) ) ; Level level = lev != null ? BaseLogging . parseLevel ( lev ) : null ; if ( level != null ) { logger . setLevel ( level ) ; } logger . setUseParentHandlers ( parseBoolean ( ep . replace ( loggerType . getUseParentHandlers ( ) ) ) ) ; String resourceBundleString = ep . replace ( loggerType . getResourceBundle ( ) ) ; if ( resourceBundleString != null ) { Locale locale ; String languageTag = ep . replace ( loggerType . getLocale ( ) ) ; if ( languageTag != null ) { locale = Locale . forLanguageTag ( languageTag ) ; } else { locale = Locale . getDefault ( ) ; } ResourceBundle resourceBundle = ResourceBundle . getBundle ( resourceBundleString , locale ) ; logger . setResourceBundle ( resourceBundle ) ; } logger . setFilter ( getInstance ( ep . replace ( loggerType . getFilter ( ) ) ) ) ; for ( ConsoleHandlerType consoleHandlerType : loggerType . getConsoleHandler ( ) ) { logger . addHandler ( createConsoleHandler ( ep , consoleHandlerType , level ) ) ; } for ( FileHandlerType fileHandlerType : loggerType . getFileHandler ( ) ) { logger . addHandler ( createFileHandler ( ep , fileHandlerType , level ) ) ; } for ( MemoryHandlerType memoryHandlerType : loggerType . getMemoryHandler ( ) ) { logger . addHandler ( createMemoryHandler ( ep , memoryHandlerType , level ) ) ; } for ( SocketHandlerType socketHandlerType : loggerType . getSocketHandler ( ) ) { logger . addHandler ( createSocketHandler ( ep , socketHandlerType , level ) ) ; } } } catch ( JAXBException ex ) { throw new RuntimeException ( ex ) ; } }
Configures logging from xml file .
14,720
public static final Set < String > impliedSet ( String ... views ) { Set < String > set = new HashSet < > ( ) ; for ( String view : views ) { set . addAll ( impliesMap . get ( view ) ) ; } return set ; }
Returns a set that contains given views as well as all implied views .
14,721
public void removeAll ( ) { if ( m_gridList != null ) m_gridList . removeAll ( ) ; if ( m_gridBuffer != null ) m_gridBuffer . removeAll ( ) ; if ( m_gridNew != null ) m_gridNew . removeAll ( ) ; m_iEndOfFileIndex = UNKNOWN_POSITION ; m_iPhysicalFilePosition = UNKNOWN_POSITION ; m_iLogicalFilePosition = UNKNOWN_POSITION ; }
Free the buffers in this grid table .
14,722
public void addRecordReference ( int iTargetPosition ) { DataRecord bookmark = this . getNextTable ( ) . getDataRecord ( m_bCacheRecordData , BaseBuffer . SELECTED_FIELDS ) ; m_gridBuffer . addElement ( iTargetPosition , bookmark , m_gridList ) ; }
Add this record s unique info to the end of the recordset . The current record is at this logical position cache it .
14,723
private int lowestNonNullIndex ( int iTargetPosition ) { Object bookmark = null ; int iBookmarkIndex = iTargetPosition ; while ( bookmark == null ) { int iArrayIndex = m_gridList . listToArrayIndex ( iBookmarkIndex ) ; iBookmarkIndex = m_gridList . arrayToListIndex ( iArrayIndex ) ; bookmark = m_gridList . elementAt ( iBookmarkIndex ) ; if ( bookmark == null ) { if ( iBookmarkIndex == 0 ) return - 1 ; iBookmarkIndex -- ; if ( m_gridBuffer != null ) bookmark = m_gridBuffer . elementAt ( iBookmarkIndex ) ; } } return iBookmarkIndex ; }
Search backwards from this position for the first non - null value .
14,724
public int findElement ( Object bookmark , int iHandleType ) { if ( bookmark == null ) return - 1 ; int iTargetPosition = m_gridBuffer . findElement ( bookmark , iHandleType ) ; if ( iTargetPosition == - 1 ) iTargetPosition = m_gridList . findElement ( bookmark , iHandleType ) ; return iTargetPosition ; }
Find this bookmark in one of the lists .
14,725
public boolean seek ( String strSeekSign ) throws DBException { boolean bAutonomousSeek = false ; if ( m_iEndOfFileIndex == UNKNOWN_POSITION ) if ( ( m_iPhysicalFilePosition == UNKNOWN_POSITION ) || ( m_iPhysicalFilePosition == ADD_NEW_POSITION ) ) if ( ( m_iLogicalFilePosition == UNKNOWN_POSITION ) || ( m_iLogicalFilePosition == ADD_NEW_POSITION ) ) bAutonomousSeek = true ; if ( bAutonomousSeek ) { Object bookmark = this . getRecord ( ) . getHandle ( DBConstants . BOOKMARK_HANDLE ) ; int iPosition = this . findElement ( bookmark , DBConstants . BOOKMARK_HANDLE ) ; if ( iPosition == 0 ) { DataRecord dataRecord = ( DataRecord ) this . elementAt ( iPosition ) ; return this . getNextTable ( ) . setDataRecord ( dataRecord ) ; } } boolean bSuccess = super . seek ( strSeekSign ) ; if ( bAutonomousSeek ) { if ( bSuccess ) this . addRecordReference ( 0 ) ; } return bSuccess ; }
Read the record that matches this record s current key . For a GridTable this method calls the inherited seek .
14,726
public int addNewBookmark ( Object bookmark , int iHandleType ) { if ( bookmark == null ) return - 1 ; if ( iHandleType != DBConstants . DATA_SOURCE_HANDLE ) { DataRecord dataRecord = new DataRecord ( null ) ; dataRecord . setHandle ( bookmark , iHandleType ) ; bookmark = dataRecord ; } int iIndexAdded = m_iEndOfFileIndex ; if ( m_iEndOfFileIndex == - 1 ) { } else { m_gridBuffer . addElement ( m_iEndOfFileIndex , bookmark , m_gridList ) ; m_iEndOfFileIndex ++ ; } return iIndexAdded ; }
Here is a bookmark for a brand new record add it to the end of the list .
14,727
public int updateGridToMessage ( BaseMessage message , boolean bReReadMessage , boolean bAddIfNotFound ) { Record record = this . getRecord ( ) ; int iHandleType = DBConstants . BOOKMARK_HANDLE ; if ( this . getNextTable ( ) instanceof org . jbundle . base . db . shared . MultiTable ) iHandleType = DBConstants . FULL_OBJECT_HANDLE ; Object bookmark = ( ( RecordMessageHeader ) message . getMessageHeader ( ) ) . getBookmark ( iHandleType ) ; int iRecordMessageType = ( ( RecordMessageHeader ) message . getMessageHeader ( ) ) . getRecordMessageType ( ) ; GridTable table = ( GridTable ) record . getTable ( ) ; int iIndex = - 1 ; if ( iRecordMessageType == - 1 ) { iIndex = table . bookmarkToIndex ( bookmark , iHandleType ) ; } else if ( iRecordMessageType == DBConstants . CACHE_UPDATE_TYPE ) { iIndex = table . bookmarkToIndex ( bookmark , iHandleType ) ; } else if ( iRecordMessageType == DBConstants . SELECT_TYPE ) { } else if ( iRecordMessageType == DBConstants . AFTER_ADD_TYPE ) { iIndex = table . refreshBookmark ( bookmark , iHandleType , false ) ; if ( iIndex == - 1 ) { if ( bAddIfNotFound ) { try { record = record . setHandle ( bookmark , iHandleType ) ; int iDBMasterSlave = record . getTable ( ) . getCurrentTable ( ) . getDatabase ( ) . getMasterSlave ( ) ; record . getTable ( ) . getCurrentTable ( ) . getDatabase ( ) . setMasterSlave ( RecordOwner . MASTER | RecordOwner . SLAVE ) ; boolean bMatch = record . handleRemoteCriteria ( null , false , null ) ; record . getTable ( ) . getCurrentTable ( ) . getDatabase ( ) . setMasterSlave ( iDBMasterSlave ) ; if ( bMatch ) { iHandleType = DBConstants . DATA_SOURCE_HANDLE ; bookmark = this . getDataRecord ( m_bCacheRecordData , BaseBuffer . SELECTED_FIELDS ) ; } else bookmark = null ; } catch ( DBException e ) { e . printStackTrace ( ) ; } if ( bookmark != null ) iIndex = table . addNewBookmark ( bookmark , iHandleType ) ; } } } else { iIndex = table . refreshBookmark ( bookmark , iHandleType , bReReadMessage ) ; } return iIndex ; }
Use this record update notification to update this gridtable .
14,728
public String getTitle ( ComponentParent screenMain ) { String strScreenTitle = DBConstants . BLANK ; if ( screenMain != null ) strScreenTitle = screenMain . getTitle ( ) ; return strScreenTitle ; }
Get the default title for this screen . Calls the getTitle method of this screen .
14,729
protected < T > T createProxy ( Class < T > interfaceClass , Session session ) throws Exception { return configBean . getConfig ( ) . getStoredProcedureProxyFactory ( ) . getProxy ( interfaceClass , session ) ; }
Creates data proxy of specified class for specified session .
14,730
protected < T > T createProxy ( Class < T > interfaceClass ) throws Exception { return createProxy ( interfaceClass , getSession ( ) ) ; }
Creates data proxy of specified class for current invocation SQL session .
14,731
protected Response ok ( Object entity ) { entity = mapResponseEntity ( entity ) ; return buildResponse ( Response . ok ( entity ) ) ; }
This is shorthand method for simple response 200 OK with entity .
14,732
protected Response ok ( List < Object > entityList ) { for ( int i = 0 ; i < entityList . size ( ) ; i ++ ) { entityList . set ( i , mapResponseEntity ( entityList . get ( i ) ) ) ; } return buildResponse ( Response . ok ( entityList ) ) ; }
This is shorthand method for simple response 200 OK with list of entities .
14,733
public int fieldChanged ( boolean bDisplayOption , int iMoveMode ) { boolean flag = this . getOwner ( ) . getState ( ) ; if ( flag ) m_mergeRecord . getTable ( ) . addTable ( m_subRecord . getTable ( ) ) ; else m_mergeRecord . getTable ( ) . removeTable ( m_subRecord . getTable ( ) ) ; m_mergeRecord . close ( ) ; if ( m_gridScreen == null ) return DBConstants . NORMAL_RETURN ; else return super . fieldChanged ( bDisplayOption , iMoveMode ) ; }
The Field has Changed . If this field is true add the table back to the grid query and requery the grid table .
14,734
private static Object toPrimitive ( final String value , final Class < ? > type ) { final Class < ? > objectType = objectTypeFor ( type ) ; final Object objectValue = valueOf ( value , objectType ) ; final Object primitiveValue ; final String toValueMethodName = type . getSimpleName ( ) + "Value" ; try { final Method toValueMethod = objectType . getMethod ( toValueMethodName ) ; primitiveValue = toValueMethod . invoke ( objectValue ) ; } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e ) { throw new RuntimeException ( "Can not convert to primitive type" , e ) ; } return primitiveValue ; }
Converts the given value to it s given primitive type .
14,735
private static Object valueOf ( final String value , final Class < ? > objectType ) { if ( objectType == Character . class ) { return value . charAt ( 0 ) ; } try { final Constructor < ? > constructor = objectType . getConstructor ( String . class ) ; return constructor . newInstance ( value ) ; } catch ( InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e ) { throw new RuntimeException ( "Could not create instance of type " + objectType . getName ( ) + " from value " + value , e ) ; } }
Converts the given String value to a object type . The method assumes the object type has a constructor accepting a single String representation of the content .
14,736
public static final String decode ( String str ) { Matcher m = ENT . matcher ( str ) ; StringBuffer sb = new StringBuffer ( ) ; while ( m . find ( ) ) { String entity = m . group ( 1 ) ; Matcher m2 = HENT . matcher ( entity ) ; Integer codePoint = null ; if ( m2 . matches ( ) ) { codePoint = Integer . parseInt ( m2 . group ( 1 ) ) ; } else { codePoint = codePointMap . get ( entity ) ; } if ( codePoint == null ) { m . appendReplacement ( sb , m . group ( ) ) ; } else { String s = new String ( new int [ ] { codePoint . intValue ( ) } , 0 , 1 ) ; m . appendReplacement ( sb , s ) ; } } m . appendTail ( sb ) ; return sb . toString ( ) ; }
Decodes String from HTML format . &amp ; - &gt ; &amp ;
14,737
public void log ( int iUserID , int iUserLogTypeID , String strMessage ) { try { this . addNew ( ) ; this . getField ( UserLog . USER_ID ) . setValue ( iUserID ) ; this . getField ( UserLog . USER_LOG_TYPE_ID ) . setValue ( iUserLogTypeID ) ; this . getField ( UserLog . MESSAGE ) . setString ( strMessage ) ; this . add ( ) ; } catch ( DBException ex ) { ex . printStackTrace ( ) ; } }
Add this log entry .
14,738
public static OWLValueObject buildFromObject ( OWLModel model , Object object ) throws NotYetImplementedException , OWLTranslationException { return buildFromClasAndObject ( model , OWLURIClass . from ( object ) , object ) ; }
Builds an instance from a given object
14,739
public static OWLValueObject buildFromCollection ( OWLModel model , Collection col ) throws NotYetImplementedException , OWLTranslationException { if ( col . isEmpty ( ) ) { return null ; } return buildFromClasAndCollection ( model , OWLURIClass . from ( col . iterator ( ) . next ( ) ) , col ) ; }
Builds an instance from a given collection
14,740
private Bitmap decodeFile ( File f ) { try { BitmapFactory . Options o = new BitmapFactory . Options ( ) ; o . inJustDecodeBounds = true ; BitmapFactory . decodeStream ( new FileInputStream ( f ) , null , o ) ; final int REQUIRED_SIZE = 70 ; int width_tmp = o . outWidth , height_tmp = o . outHeight ; int scale = 1 ; while ( true ) { if ( width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE ) break ; width_tmp /= 2 ; height_tmp /= 2 ; scale *= 2 ; } BitmapFactory . Options o2 = new BitmapFactory . Options ( ) ; o2 . inSampleSize = scale ; return BitmapFactory . decodeStream ( new FileInputStream ( f ) , null , o2 ) ; } catch ( FileNotFoundException e ) { } return null ; }
decodes image and scales it to reduce memory consumption
14,741
public GetIndividualProfilesRequest withIndividualId ( final int id ) { this . id = id ; this . password = new char [ 0 ] ; this . login = this . accountNumber = this . routingNumber = null ; return this ; }
Request the IndividualProfile for the given individual id .
14,742
public GetIndividualProfilesRequest withLoginPassword ( final String login , final char [ ] password ) { this . login = login ; this . password = password ; this . id = 0 ; this . accountNumber = this . routingNumber = null ; return this ; }
Request the IndividualProfile for the given login and password .
14,743
public GetIndividualProfilesRequest withMICR ( final String routingNumber , final String accountNumber ) { this . routingNumber = routingNumber ; this . accountNumber = accountNumber ; return this ; }
Request the IndividualProfile for the given bank account information .
14,744
public void traverse ( X x , Function < ? super X , ? extends Collection < X > > edges ) { traverseS ( x , ( y ) -> edges . apply ( y ) . stream ( ) ) ; }
This algorithm traverses all vertices and all edges once .
14,745
public Map < String , Object > getProperties ( ) { Map < String , Object > properties = ( ( PropertiesField ) this . getField ( CalendarEntry . PROPERTIES ) ) . getProperties ( ) ; if ( ! this . getField ( Anniversary . ANNIV_MASTER_ID ) . isNull ( ) ) if ( this . getField ( Anniversary . ANNIV_MASTER_ID ) instanceof ReferenceField ) { Record recAnnivMaster = ( ( ReferenceField ) this . getField ( Anniversary . ANNIV_MASTER_ID ) ) . getReference ( ) ; if ( ( recAnnivMaster != null ) && ( ( recAnnivMaster . getEditMode ( ) == DBConstants . EDIT_CURRENT ) || ( recAnnivMaster . getEditMode ( ) == DBConstants . EDIT_IN_PROGRESS ) ) ) { Map < String , Object > propMaster = ( ( PropertiesField ) recAnnivMaster . getField ( AnnivMaster . PROPERTIES ) ) . getProperties ( ) ; if ( propMaster != null ) { if ( properties != null ) propMaster . putAll ( properties ) ; properties = propMaster ; } } } return properties ; }
Get the properties from the Properties field and merge with the properties from the Master field if it exists .
14,746
public Object getStartIcon ( ) { Object iconStart = null ; Record recCalendarCategory = ( ( ReferenceField ) this . getField ( CalendarEntry . CALENDAR_CATEGORY_ID ) ) . getReference ( ) ; if ( ( recCalendarCategory == null ) || ( recCalendarCategory . getEditMode ( ) != DBConstants . EDIT_CURRENT ) ) if ( this . getField ( Anniversary . ANNIV_MASTER_ID ) instanceof ReferenceField ) { } if ( ( recCalendarCategory != null ) && ( recCalendarCategory . getEditMode ( ) == DBConstants . EDIT_CURRENT ) ) iconStart = ( ( ImageField ) recCalendarCategory . getField ( CalendarCategory . ICON ) ) . getImage ( ) . getImage ( ) ; if ( iconStart == null ) { if ( this . getTask ( ) instanceof BaseApplet ) iconStart = ( ( BaseApplet ) this . getTask ( ) ) . loadImageIcon ( "Calendar" ) ; } return iconStart ; }
Get the icon for the screen display .
14,747
@ SuppressWarnings ( "rawtypes" ) public static < S > ServiceLoader load ( final Class < S > service ) { return load ( service , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; }
Creates a new service loader for the given service type using the current thread s context class loader .
14,748
public boolean execute ( Properties properties ) { if ( this . getEditMode ( ) == DBConstants . EDIT_IN_PROGRESS ) { try { this . writeAndRefresh ( ) ; } catch ( DBException ex ) { ex . printStackTrace ( ) ; } } if ( this . getEditMode ( ) != DBConstants . EDIT_CURRENT ) return false ; RunScriptProcess process = new RunScriptProcess ( this . getTask ( ) , null , null ) ; boolean bSuccess = ( process . doCommand ( this , null ) == DBConstants . NORMAL_RETURN ) ; process . free ( ) ; return bSuccess ; }
Execute Method .
14,749
public Record getTargetRecord ( Map < String , Object > properties , String strParam ) { String strRecordName = ( String ) properties . get ( strParam ) ; Record record = null ; if ( ( strRecordName != null ) && ( strRecordName . length ( ) > 0 ) ) { String strTableName = strRecordName ; if ( strTableName . indexOf ( '.' ) != - 1 ) strTableName = strTableName . substring ( strTableName . lastIndexOf ( '.' ) + 1 ) ; if ( this . getRecordOwner ( ) != null ) record = ( Record ) this . getRecordOwner ( ) . getRecord ( strTableName ) ; if ( record != null ) return record ; if ( strRecordName . indexOf ( '.' ) == - 1 ) if ( properties . get ( "package" ) != null ) strRecordName = ( String ) properties . get ( "package" ) + '.' + strRecordName ; if ( strRecordName . indexOf ( '.' ) == - 1 ) { ClassInfo recClassInfo = new ClassInfo ( this . getRecordOwner ( ) ) ; try { recClassInfo . getField ( ClassInfo . CLASS_NAME ) . setString ( strRecordName ) ; recClassInfo . setKeyArea ( ClassInfo . CLASS_NAME_KEY ) ; if ( recClassInfo . seek ( null ) ) strRecordName = recClassInfo . getPackageName ( null ) + '.' + strRecordName ; } catch ( DBException ex ) { ex . printStackTrace ( ) ; } finally { recClassInfo . free ( ) ; } } if ( strRecordName . indexOf ( '.' ) != - 1 ) { record = ( Record ) ClassServiceUtility . getClassService ( ) . makeObjectFromClassName ( strRecordName ) ; if ( record != null ) record . init ( this . findRecordOwner ( ) ) ; } } return record ; }
GetTargetRecord Method .
14,750
public String getProperty ( String strKey ) { return ( ( PropertiesField ) this . getField ( Script . PROPERTIES ) ) . getProperty ( strKey ) ; }
GetProperty Method .
14,751
public Script getSubScript ( ) { if ( m_recSubScript == null ) { RecordOwner recordOwner = this . findRecordOwner ( ) ; m_recSubScript = new Script ( recordOwner ) ; recordOwner . removeRecord ( m_recSubScript ) ; m_recSubScript . addListener ( new SubFileFilter ( this ) ) ; } return m_recSubScript ; }
Create a record to read through this script s children .
14,752
public static < T > Maker < T > cycle ( T first , T ... rest ) { ImmutableList < T > values = ImmutableList . < T > builder ( ) . add ( first ) . add ( rest ) . build ( ) ; return new RangeValuesMaker < T > ( Iterables . cycle ( values ) . iterator ( ) ) ; }
Factory method . Given a list of values and the produced maker will cycle them infinitely .
14,753
public static < T > Maker < T > errorOnEnd ( T first , T ... rest ) { ImmutableList < T > values = ImmutableList . < T > builder ( ) . add ( first ) . add ( rest ) . build ( ) ; return new RangeValuesMaker < T > ( values . iterator ( ) ) ; }
Factory method . Given a list of values and the produced maker will exhaust them before throwing an exception .
14,754
@ SuppressWarnings ( "unchecked" ) public void init ( ) throws ServletException { ServletConfig config = getServletConfig ( ) ; try { final Grammar root = XmlGrammar . getMainGrammar ( ) ; final InputStream inpt = CernunnosServlet . class . getResourceAsStream ( "servlet.grammar" ) ; final Document doc = new SAXReader ( ) . read ( inpt ) ; final Task k = new ScriptRunner ( root ) . compileTask ( doc . getRootElement ( ) ) ; final RuntimeRequestResponse req = new RuntimeRequestResponse ( ) ; final ReturnValueImpl rslt = new ReturnValueImpl ( ) ; req . setAttribute ( Attributes . RETURN_VALUE , rslt ) ; k . perform ( req , new RuntimeRequestResponse ( ) ) ; Grammar g = ( Grammar ) rslt . getValue ( ) ; runner = new ScriptRunner ( g ) ; String defaultLoc = "/WEB-INF/" + config . getServletName ( ) + "-portlet.xml" ; URL defaultUrl = getServletConfig ( ) . getServletContext ( ) . getResource ( defaultLoc ) ; URL u = Settings . locateContextConfig ( getServletConfig ( ) . getServletContext ( ) . getResource ( "/" ) . toExternalForm ( ) , config . getInitParameter ( CONFIG_LOCATION_PARAM ) , defaultUrl ) ; if ( u != null ) { spring_context = new FileSystemXmlApplicationContext ( u . toExternalForm ( ) ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Location of spring context (null means none): " + u ) ; } Map < String , String > settingsMap = new HashMap < String , String > ( ) ; if ( spring_context != null && spring_context . containsBean ( "settings" ) ) { settingsMap = ( Map < String , String > ) spring_context . getBean ( "settings" ) ; } settings = Settings . load ( settingsMap ) ; } catch ( Throwable t ) { String msg = "Failure in CernunnosServlet.init()" ; throw new ServletException ( msg , t ) ; } }
Don t declare as static in general libraries
14,755
@ BeforeSuite ( alwaysRun = true ) @ Parameters ( value = { "parameters" } ) public static void startSelenium ( String parameters ) { parametersMap = parameterScanner ( parameters ) ; parametersInfo ( ) ; String browserName = parametersMap . get ( "browser" ) , profile = parametersMap . get ( "profile" ) , chromeDriverBin = parametersMap . get ( "chromeDriverBin" ) , ieDriverBin = parametersMap . get ( "ieDriverBin" ) , chromeBin = parametersMap . get ( "chromeBin" ) , languages = parametersMap . get ( "languages" ) ; if ( browserName == null ) { throw new IllegalArgumentException ( String . format ( ErrorMessages . ERROR_TEMPLATE_VARIABLE_NULL , "browser" ) ) ; } if ( driver == null ) { if ( BrowsersList . FIREFOX . equalsString ( browserName ) ) { FirefoxProfile fp = new FirefoxProfile ( ) ; fp . setPreference ( "dom.max_script_run_time" , 0 ) ; fp . setPreference ( "dom.max_chrome_script_run_time" , 0 ) ; if ( profile != null && ! profile . isEmpty ( ) ) { fp . setPreference ( "webdriver.firefox.profile" , profile ) ; } if ( languages != null && ! languages . isEmpty ( ) ) { fp . setPreference ( "intl.accept_languages" , languages ) ; } driver = new WebDriverAdapter ( new FirefoxDriver ( fp ) ) ; } else if ( BrowsersList . CHROME . equalsString ( browserName ) ) { if ( chromeBin == null ) { throw new IllegalArgumentException ( String . format ( ErrorMessages . ERROR_TEMPLATE_VARIABLE_NULL , "chromeBin" ) ) ; } if ( System . getProperty ( "webdriver.chrome.driver" ) == null || System . getProperty ( "webdriver.chrome.driver" ) . isEmpty ( ) ) { if ( chromeDriverBin == null ) { throw new IllegalArgumentException ( String . format ( ErrorMessages . ERROR_TEMPLATE_VARIABLE_NULL , "chromeDriverBin" ) ) ; } System . setProperty ( "webdriver.chrome.driver" , chromeDriverBin ) ; } ChromeOptions co = new ChromeOptions ( ) ; co . setBinary ( new File ( chromeBin ) ) ; driver = new WebDriverAdapter ( new ChromeDriver ( co ) ) ; } else if ( BrowsersList . IE . equalsString ( browserName ) ) { if ( ieDriverBin == null ) { throw new IllegalArgumentException ( String . format ( ErrorMessages . ERROR_TEMPLATE_VARIABLE_NULL , "ieDriverBin" ) ) ; } System . setProperty ( "webdriver.ie.driver" , ieDriverBin ) ; driver = new WebDriverAdapter ( new InternetExplorerDriver ( ) ) ; } else if ( BrowsersList . HTML_UNIT . equalsString ( browserName ) ) { driver = new HtmlUnitDriver ( true ) ; } else { throw new IllegalArgumentException ( ErrorMessages . ERROR_BROWSER_INVALID ) ; } } SeleniumController . driver . manage ( ) . timeouts ( ) . implicitlyWait ( 1 , TimeUnit . SECONDS ) ; SeleniumController . builder = new SeleniumBuilder ( driver ) ; SeleniumController . browser = new SeleniumBrowser ( ) ; ListenerGateway . setWebDriver ( driver ) ; ListenerGateway . setParameters ( parametersMap ) ; }
This method starts the selenium remote control using the parameters informed by testng . xml file
14,756
@ AfterSuite ( alwaysRun = true ) public static void closeSelenium ( ) { if ( driver != null ) { driver . quit ( ) ; driver = null ; } }
Close the driver . It ll close the browsers window and stop the selenium RC .
14,757
public static < T > T [ ] recoveredValueASArray ( Class < T > type , String properties ) throws ExecutionException { LOGGER . info ( String . format ( "Recovered propeties [%s] as [%s]" , properties , type ) ) ; String [ ] stringParseProperties = properties . replaceAll ( "\\s+" , "" ) . replaceAll ( "\\[" , "" ) . replaceAll ( "]" , "" ) . split ( "," ) ; T [ ] returnValue = null ; if ( isString ( type ) ) { returnValue = ( T [ ] ) stringParseProperties ; } else if ( isBoolean ( type ) ) { Boolean [ ] tempReturnValue = new Boolean [ stringParseProperties . length ] ; for ( int i = 0 ; i < stringParseProperties . length ; i ++ ) { tempReturnValue [ i ] = Boolean . parseBoolean ( stringParseProperties [ i ] ) ; } returnValue = ( T [ ] ) tempReturnValue ; } else { String message = String . format ( "The type %s is not supported for conversion." , type ) ; LOGGER . error ( message ) ; throw new ExecutionException ( String . format ( message ) ) ; } if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( String . format ( "The property as converted to %s" , Arrays . deepToString ( returnValue ) ) ) ; } return returnValue ; }
This method recovered the array of properties .
14,758
public static < T > T recoveredValue ( Class < T > type , String properties ) throws ExecutionException { return recoveredValueASArray ( type , properties ) [ 0 ] ; }
This method recovered the property .
14,759
public static final void init ( ) { String settingDir = System . getProperty ( SETTINGS_DIR ) ; if ( settingDir == null ) { settingDir = System . getenv ( SETTINGS_DIR ) ; } if ( settingDir == null ) { throw Fault . create ( SettingsFaultCodes . SettingsDirNotSpecified , SETTINGS_DIR ) ; } init ( settingDir ) ; }
load the files from - Dcom . pahakia . settings . dir = directory
14,760
public void updateGroupPermission ( int iGroupID ) { if ( m_recUserPermission == null ) m_recUserPermission = new UserPermission ( this . getOwner ( ) . findRecordOwner ( ) ) ; Record m_recUserGroup = ( ( ReferenceField ) m_recUserPermission . getField ( UserPermission . USER_GROUP_ID ) ) . getReferenceRecord ( ) ; m_recUserGroup . setOpenMode ( m_recUserGroup . getOpenMode ( ) & ~ DBConstants . OPEN_READ_ONLY ) ; if ( m_recUserPermission . getListener ( SubFileFilter . class ) == null ) m_recUserPermission . addListener ( new SubFileFilter ( m_recUserGroup ) ) ; try { m_recUserGroup . addNew ( ) ; m_recUserGroup . getCounterField ( ) . setValue ( iGroupID ) ; if ( m_recUserGroup . seek ( null ) ) { m_recUserGroup . edit ( ) ; StringBuffer sb = new StringBuffer ( ) ; m_recUserPermission . close ( ) ; while ( m_recUserPermission . hasNext ( ) ) { m_recUserPermission . next ( ) ; Record recUserResource = ( ( ReferenceField ) m_recUserPermission . getField ( UserPermission . USER_RESOURCE_ID ) ) . getReference ( ) ; String strResource = recUserResource . getField ( UserResource . RESOURCE_CLASS ) . toString ( ) ; StringTokenizer tokenizer = new StringTokenizer ( strResource , "\n\t ," ) ; while ( tokenizer . hasMoreTokens ( ) ) { String strClass = tokenizer . nextToken ( ) ; int startThin = strClass . indexOf ( Constants . THIN_SUBPACKAGE , 0 ) ; if ( startThin != - 1 ) strClass = strClass . substring ( 0 , startThin ) + strClass . substring ( startThin + Constants . THIN_SUBPACKAGE . length ( ) ) ; if ( strClass . length ( ) > 0 ) { sb . append ( strClass ) . append ( '\t' ) ; sb . append ( m_recUserPermission . getField ( UserPermission . ACCESS_LEVEL ) . toString ( ) ) . append ( '\t' ) ; sb . append ( m_recUserPermission . getField ( UserPermission . LOGIN_LEVEL ) . toString ( ) ) . append ( "\t\n" ) ; } } } m_recUserGroup . getField ( UserGroup . ACCESS_MAP ) . setString ( sb . toString ( ) ) ; m_recUserGroup . set ( ) ; } } catch ( DBException e ) { e . printStackTrace ( ) ; } }
UpdateGroupPermission Method .
14,761
public boolean inMap ( Location location ) { for ( String map : schedule . getMap ( ) ) { if ( station . inMap ( map , location ) ) { return true ; } } return false ; }
Returns true if location is inside map .
14,762
public void init ( Object env , Map < String , Object > properties , Object applet ) { super . init ( env , properties , applet ) ; }
Initializes the ServletApplication . Usually you pass the object that wants to use this session . For example the applet or ServletApplication .
14,763
public void valueUnbound ( HttpSessionBindingEvent event ) { Utility . getLogger ( ) . info ( "Session Unbound" ) ; if ( this . getMainTask ( ) == null ) this . free ( ) ; else Utility . getLogger ( ) . severe ( "Unbound error ServletApplication.valueUnbound" ) ; }
Notifies the object that is being unbound from a session and identifies the session .
14,764
public static boolean isSynchronized ( final AcraReport pReport , final Issue pIssue ) throws IssueParseException { final IssueDescriptionReader reader = new IssueDescriptionReader ( pIssue ) ; return CollectionUtils . exists ( reader . getOccurrences ( ) , new ReportPredicate ( pReport ) ) ; }
Gets wheter or not the given report has already been synchronized with the given issue .
14,765
public int getNumWarnings ( ) { int numWarnings = 0 ; if ( getBuildData ( ) . getErrorDatabase ( ) != null && getBuildData ( ) . getErrorDatabase ( ) . getErrors ( getBuildData ( ) . getBuildLocale ( ) ) != null ) { for ( final TopicErrorData errorData : getBuildData ( ) . getErrorDatabase ( ) . getErrors ( getBuildData ( ) . getBuildLocale ( ) ) ) { numWarnings += errorData . getItemsOfType ( ErrorLevel . WARNING ) . size ( ) ; } } return numWarnings ; }
Gets the number of warnings that occurred during the last build .
14,766
public int getNumErrors ( ) { int numErrors = 0 ; if ( getBuildData ( ) . getErrorDatabase ( ) != null && getBuildData ( ) . getErrorDatabase ( ) . getErrors ( getBuildData ( ) . getBuildLocale ( ) ) != null ) { for ( final TopicErrorData errorData : getBuildData ( ) . getErrorDatabase ( ) . getErrors ( getBuildData ( ) . getBuildLocale ( ) ) ) { numErrors += errorData . getItemsOfType ( ErrorLevel . ERROR ) . size ( ) ; } } return numErrors ; }
Gets the number of errors that occurred during the last build .
14,767
protected void pullTranslations ( final ContentSpec contentSpec , final String locale ) throws BuildProcessingException { final CollectionWrapper < TranslatedContentSpecWrapper > translatedContentSpecs = providerFactory . getProvider ( TranslatedContentSpecProvider . class ) . getTranslatedContentSpecsWithQuery ( "query;" + CommonFilterConstants . ZANATA_IDS_FILTER_VAR + "=CS" + contentSpec . getId ( ) + "-" + contentSpec . getRevision ( ) ) ; if ( translatedContentSpecs == null || translatedContentSpecs . isEmpty ( ) ) { throw new BuildProcessingException ( "Unable to find any translations for Content Spec " + contentSpec . getId ( ) + ( contentSpec . getRevision ( ) == null ? "" : ( ", Revision " + contentSpec . getRevision ( ) ) ) ) ; } final TranslatedContentSpecWrapper translatedContentSpec = translatedContentSpecs . getItems ( ) . get ( 0 ) ; if ( translatedContentSpec . getTranslatedNodes ( ) != null ) { final Map < String , String > translations = new HashMap < String , String > ( ) ; final List < TranslatedCSNodeWrapper > translatedCSNodes = translatedContentSpec . getTranslatedNodes ( ) . getItems ( ) ; for ( final TranslatedCSNodeWrapper translatedCSNode : translatedCSNodes ) { if ( ! isNullOrEmpty ( translatedCSNode . getOriginalString ( ) ) ) { if ( translatedCSNode . getTranslatedStrings ( ) != null ) { final List < TranslatedCSNodeStringWrapper > translatedCSNodeStrings = translatedCSNode . getTranslatedStrings ( ) . getItems ( ) ; for ( final TranslatedCSNodeStringWrapper translatedCSNodeString : translatedCSNodeStrings ) { if ( translatedCSNodeString . getLocale ( ) . getValue ( ) . equals ( locale ) ) { translations . put ( translatedCSNode . getOriginalString ( ) , translatedCSNodeString . getTranslatedString ( ) ) ; } } } } } final List < Entity > entities = XMLUtilities . parseEntitiesFromString ( contentSpec . getEntities ( ) ) ; TranslationUtilities . resolveCustomContentSpecEntities ( entities , translatedContentSpec . getContentSpec ( ) ) ; TranslationUtilities . replaceTranslatedStrings ( translatedContentSpec . getContentSpec ( ) , contentSpec , translations ) ; setTranslationUniqueIds ( contentSpec , translatedContentSpec ) ; } }
Get the translations from the REST API and replace the original strings with the values downloaded .
14,768
protected void setTranslationUniqueIds ( final ContentSpec contentSpec , final TranslatedContentSpecWrapper translatedContentSpec ) throws BuildProcessingException { final List < TranslatedCSNodeWrapper > translatedCSNodes = translatedContentSpec . getTranslatedNodes ( ) . getItems ( ) ; for ( final TranslatedCSNodeWrapper translatedCSNode : translatedCSNodes ) { final org . jboss . pressgang . ccms . contentspec . Node node = ContentSpecUtilities . findMatchingContentSpecNode ( contentSpec , translatedCSNode . getNodeId ( ) ) ; if ( node != null ) { node . setTranslationUniqueId ( translatedCSNode . getId ( ) . toString ( ) ) ; if ( node instanceof KeyValueNode && ( ( KeyValueNode ) node ) . getValue ( ) instanceof SpecTopic ) { ( ( SpecTopic ) ( ( KeyValueNode ) node ) . getValue ( ) ) . setTranslationUniqueId ( translatedCSNode . getId ( ) . toString ( ) ) ; } } else { throw new BuildProcessingException ( "Unable to find a matching Content Spec Node object for Translated Node " + translatedCSNode . getId ( ) ) ; } } }
Sets the Translation Unique Ids on all the content spec nodes that have a matching translated node .
14,769
@ SuppressWarnings ( "unchecked" ) protected void validateTopicLinks ( final BuildData buildData , final Set < String > bookIdAttributes ) throws BuildProcessingException { final List < SpecTopic > topics = buildData . getBuildDatabase ( ) . getAllSpecTopics ( ) ; final Set < Integer > processedTopics = new HashSet < Integer > ( ) ; for ( final SpecTopic specTopic : topics ) { final BaseTopicWrapper < ? > topic = specTopic . getTopic ( ) ; final Document doc = specTopic . getXMLDocument ( ) ; if ( ! processedTopics . contains ( topic . getId ( ) ) ) { processedTopics . add ( topic . getId ( ) ) ; final Set < String > linkIds = new HashSet < String > ( ) ; DocBookBuildUtilities . getTopicLinkIds ( doc , linkIds ) ; final List < String > invalidLinks = new ArrayList < String > ( ) ; for ( final String linkId : linkIds ) { if ( ! bookIdAttributes . contains ( linkId ) && ! linkId . startsWith ( CommonConstants . ERROR_XREF_ID_PREFIX ) ) { invalidLinks . add ( "\"" + linkId + "\"" ) ; } } if ( ! invalidLinks . isEmpty ( ) ) { final String xmlStringInCDATA = DocBookBuildUtilities . convertDocumentToCDATAFormattedString ( doc , getXMLFormatProperties ( ) ) ; buildData . getErrorDatabase ( ) . addError ( topic , ErrorType . INVALID_CONTENT , "The following link(s) " + CollectionUtilities . toSeperatedString ( invalidLinks , ", " ) + " don't exist. The processed XML is <programlisting>" + xmlStringInCDATA + "</programlisting>" ) ; final Integer topicId = topic . getTopicId ( ) ; final List < ITopicNode > buildTopics = buildData . getBuildDatabase ( ) . getTopicNodesForTopicID ( topicId ) ; for ( final ITopicNode topicNode : buildTopics ) { DocBookBuildUtilities . setTopicNodeXMLForError ( buildData , topicNode , getErrorInvalidValidationTopicTemplate ( ) . getValue ( ) ) ; } } } } }
Validate all the book links in the each topic to ensure that they exist somewhere in the book . If they don t then the topic XML is replaced with a generic error template .
14,770
@ SuppressWarnings ( "unchecked" ) private void doPopulateDatabasePass ( final BuildData buildData ) throws BuildProcessingException { log . info ( "Doing " + buildData . getBuildLocale ( ) + " Populate Database Pass" ) ; final ContentSpec contentSpec = buildData . getContentSpec ( ) ; final Map < String , BaseTopicWrapper < ? > > topics = new HashMap < String , BaseTopicWrapper < ? > > ( ) ; if ( buildData . isTranslationBuild ( ) ) { populateTranslatedTopicDatabase ( buildData , topics ) ; } else { populateDatabaseTopics ( buildData , topics ) ; } if ( isShuttingDown . get ( ) ) { return ; } DocBookBuildUtilities . addLevelsToDatabase ( buildData . getBuildDatabase ( ) , contentSpec . getBaseLevel ( ) ) ; if ( isShuttingDown . get ( ) ) { return ; } doTopicPass ( buildData , topics ) ; }
Populates the SpecTopicDatabase with the SpecTopics inside the content specification . It also adds the equivalent real topics to each SpecTopic .
14,771
private void populateTranslatedTopicDatabase ( final BuildData buildData , final Map < String , BaseTopicWrapper < ? > > translatedTopics ) throws BuildProcessingException { final List < ITopicNode > topicNodes = buildData . getContentSpec ( ) . getAllTopicNodes ( ) ; final int showPercent = 10 ; final float total = topicNodes . size ( ) ; float current = 0 ; int lastPercent = 0 ; for ( final ITopicNode topicNode : topicNodes ) { getTranslatedTopicForTopicNode ( buildData , topicNode , translatedTopics ) ; ++ current ; final int percent = Math . round ( current / total * 100 ) ; if ( percent - lastPercent >= showPercent ) { lastPercent = percent ; log . info ( "\tPopulate " + buildData . getBuildLocale ( ) + " Database Pass " + percent + "% Done" ) ; } } }
Gets the translated topics from the REST Interface and also creates any dummy translations for topics that have yet to be translated .
14,772
private TranslatedTopicWrapper createDummyTranslatedTopicFromExisting ( final TranslatedTopicWrapper translatedTopic , final LocaleWrapper locale ) { translatedTopic . getTags ( ) ; translatedTopic . getProperties ( ) ; final TranslatedTopicWrapper defaultLocaleTranslatedTopic = translatedTopic . clone ( false ) ; defaultLocaleTranslatedTopic . setId ( translatedTopic . getTopicId ( ) * - 1 ) ; defaultLocaleTranslatedTopic . setLocale ( locale ) ; return defaultLocaleTranslatedTopic ; }
Creates a dummy translated topic from an existing translated topic so that a book can be built using the same relationships as a normal build .
14,773
private Document mergeAdditionalTranslatedXML ( BuildData buildData , final Document topicDoc , final TranslatedTopicWrapper translatedTopic , final TopicType topicType ) throws BuildProcessingException { Document retValue = topicDoc ; if ( ! isNullOrEmpty ( translatedTopic . getTranslatedAdditionalXML ( ) ) ) { Document additionalXMLDoc = null ; try { additionalXMLDoc = XMLUtilities . convertStringToDocument ( translatedTopic . getTranslatedAdditionalXML ( ) ) ; } catch ( Exception ex ) { buildData . getErrorDatabase ( ) . addError ( translatedTopic , ErrorType . INVALID_CONTENT , BuilderConstants . ERROR_INVALID_TOPIC_XML + " " + StringUtilities . escapeForXML ( ex . getMessage ( ) ) ) ; retValue = DocBookBuildUtilities . setTopicXMLForError ( buildData , translatedTopic , getErrorInvalidValidationTopicTemplate ( ) . getValue ( ) ) ; } if ( additionalXMLDoc != null ) { try { if ( TopicType . AUTHOR_GROUP . equals ( topicType ) ) { DocBookBuildUtilities . mergeAuthorGroups ( topicDoc , additionalXMLDoc ) ; } else if ( TopicType . REVISION_HISTORY . equals ( topicType ) ) { DocBookBuildUtilities . mergeRevisionHistories ( topicDoc , additionalXMLDoc ) ; } } catch ( BuildProcessingException ex ) { final String xmlStringInCDATA = XMLUtilities . wrapStringInCDATA ( translatedTopic . getTranslatedAdditionalXML ( ) ) ; buildData . getErrorDatabase ( ) . addError ( translatedTopic , ErrorType . INVALID_CONTENT , BuilderConstants . ERROR_BAD_XML_STRUCTURE + " " + StringUtilities . escapeForXML ( ex . getMessage ( ) ) + " The processed XML is <programlisting>" + xmlStringInCDATA + "</programlisting>" ) ; retValue = DocBookBuildUtilities . setTopicXMLForError ( buildData , translatedTopic , getErrorInvalidValidationTopicTemplate ( ) . getValue ( ) ) ; } } else { final String xmlStringInCDATA = XMLUtilities . wrapStringInCDATA ( translatedTopic . getTranslatedAdditionalXML ( ) ) ; buildData . getErrorDatabase ( ) . addError ( translatedTopic , ErrorType . INVALID_CONTENT , BuilderConstants . ERROR_INVALID_XML_CONTENT + " The processed XML is <programlisting>" + xmlStringInCDATA + "</programlisting>" ) ; retValue = DocBookBuildUtilities . setTopicXMLForError ( buildData , translatedTopic , getErrorInvalidValidationTopicTemplate ( ) . getValue ( ) ) ; } } return retValue ; }
Merges the Additional Translated XML of a Translated Topic into the original Topic XML content .
14,774
protected void processConditions ( final BuildData buildData , final SpecTopic specTopic , final Document doc ) { final String condition = specTopic . getConditionStatement ( true ) ; DocBookUtilities . processConditions ( condition , doc , BuilderConstants . DEFAULT_CONDITION ) ; }
Checks if the conditional pass should be performed .
14,775
protected void doLinkSecondPass ( final BuildData buildData , final Map < SpecTopic , Set < String > > usedIdAttributes ) throws BuildProcessingException { final List < SpecTopic > topics = buildData . getBuildDatabase ( ) . getAllSpecTopics ( ) ; for ( final SpecTopic specTopic : topics ) { final Document doc = specTopic . getXMLDocument ( ) ; final Set < String > linkIds = new HashSet < String > ( ) ; DocBookBuildUtilities . getTopicLinkIds ( doc , linkIds ) ; final Map < String , SpecTopic > invalidLinks = new HashMap < String , SpecTopic > ( ) ; for ( final String linkId : linkIds ) { if ( linkId . startsWith ( CommonConstants . ERROR_XREF_ID_PREFIX ) ) continue ; SpecTopic linkedTopic = null ; for ( final Map . Entry < SpecTopic , Set < String > > usedIdEntry : usedIdAttributes . entrySet ( ) ) { if ( usedIdEntry . getValue ( ) . contains ( linkId ) ) { linkedTopic = usedIdEntry . getKey ( ) ; break ; } } if ( linkedTopic != null && buildData . getErrorDatabase ( ) . hasErrorData ( linkedTopic . getTopic ( ) ) ) { final TopicErrorData errorData = buildData . getErrorDatabase ( ) . getErrorData ( linkedTopic . getTopic ( ) ) ; if ( errorData . hasFatalErrors ( ) ) { invalidLinks . put ( linkId , linkedTopic ) ; } } } if ( ! invalidLinks . isEmpty ( ) ) { final List < Node > linkNodes = XMLUtilities . getChildNodes ( doc , "xref" , "link" ) ; for ( final Node linkNode : linkNodes ) { final String linkId = ( ( Element ) linkNode ) . getAttribute ( "linkend" ) ; if ( invalidLinks . containsKey ( linkId ) ) { final SpecTopic linkedTopic = invalidLinks . get ( linkId ) ; ( ( Element ) linkNode ) . setAttribute ( "linkend" , linkedTopic . getUniqueLinkId ( buildData . isUseFixedUrls ( ) ) ) ; } } } } }
Fixes any topics links that have been broken due to the linked topics XML being invalid .
14,776
protected boolean processSpecTopicInjectionErrors ( final BuildData buildData , final BaseTopicWrapper < ? > topic , final List < String > customInjectionErrors ) { boolean valid = true ; if ( ! customInjectionErrors . isEmpty ( ) ) { final String message = "Topic has referenced Topic/Level(s) " + CollectionUtilities . toSeperatedString ( customInjectionErrors ) + " in a custom injection point that was not included this book." ; if ( buildData . getBuildOptions ( ) . getIgnoreMissingCustomInjections ( ) ) { buildData . getErrorDatabase ( ) . addWarning ( topic , ErrorType . INVALID_INJECTION , message ) ; } else { buildData . getErrorDatabase ( ) . addError ( topic , ErrorType . INVALID_INJECTION , message ) ; valid = false ; } } return valid ; }
Process the Injection Errors and add them to the Error Database .
14,777
protected void addBookBaseFilesAndImages ( final BuildData buildData ) throws BuildProcessingException { final String pressgangWebsiteJS = buildPressGangWebsiteJS ( buildData ) ; addToZip ( buildData . getBookImagesFolder ( ) + "icon.svg" , ResourceUtilities . resourceFileToByteArray ( "/" , "icon.svg" ) , buildData ) ; addToZip ( buildData . getBookFilesFolder ( ) + "pressgang_website.js" , pressgangWebsiteJS , buildData ) ; }
Adds the basic Images and Files to the book that are the minimum requirements to build it .
14,778
protected void buildBookPreface ( final BuildData buildData ) throws BuildProcessingException { final ContentSpec contentSpec = buildData . getContentSpec ( ) ; if ( contentSpec . getUseDefaultPreface ( ) ) { final Map < String , String > overrides = buildData . getBuildOptions ( ) . getOverrides ( ) ; final Map < String , byte [ ] > overrideFiles = buildData . getOverrideFiles ( ) ; final Document prefaceDoc ; try { prefaceDoc = XMLUtilities . convertStringToDocument ( "<preface></preface>" ) ; } catch ( Exception e ) { throw new BuildProcessingException ( e ) ; } final String prefaceTitleTranslation = buildData . getConstants ( ) . getString ( "PREFACE" ) ; final Element titleEle = prefaceDoc . createElement ( "title" ) ; titleEle . setTextContent ( prefaceTitleTranslation ) ; prefaceDoc . getDocumentElement ( ) . appendChild ( titleEle ) ; final Element conventions = XMLUtilities . createXIInclude ( prefaceDoc , "Common_Content/Conventions.xml" ) ; prefaceDoc . getDocumentElement ( ) . appendChild ( conventions ) ; if ( overrides . containsKey ( CSConstants . FEEDBACK_OVERRIDE ) && overrideFiles . containsKey ( CSConstants . FEEDBACK_OVERRIDE ) || contentSpec . getFeedback ( ) != null ) { final Element xinclude = XMLUtilities . createXIInclude ( prefaceDoc , "Feedback.xml" ) ; prefaceDoc . getDocumentElement ( ) . appendChild ( xinclude ) ; } else { final Element xinclude = XMLUtilities . createXIInclude ( prefaceDoc , "Common_Content/Feedback.xml" ) ; prefaceDoc . getDocumentElement ( ) . appendChild ( xinclude ) ; } final String prefaceXml = DocBookBuildUtilities . convertDocumentToDocBookFormattedString ( buildData . getDocBookVersion ( ) , prefaceDoc , "preface" , buildData . getEntityFileName ( ) , getXMLFormatProperties ( ) ) ; addToZip ( buildData . getBookLocaleFolder ( ) + PREFACE_FILE_NAME , prefaceXml , buildData ) ; } }
Builds the Preface . xml file for the book .
14,779
protected String buildBookEntityFile ( final BuildData buildData ) throws BuildProcessingException { final ContentSpec contentSpec = buildData . getContentSpec ( ) ; final StringBuilder retValue = new StringBuilder ( ) ; if ( ! buildData . getBuildOptions ( ) . getUseOldBugLinks ( ) && buildData . getBuildOptions ( ) . getInsertBugLinks ( ) ) { retValue . append ( "<!-- BUG LINK ENTITIES ) ; try { final BaseBugLinkStrategy bugLinkStrategy = buildData . getBugLinkStrategy ( ) ; final BugLinkOptions bugLinkOptions = buildData . getBugLinkOptions ( ) ; retValue . append ( bugLinkStrategy . generateEntities ( bugLinkOptions , buildData . getBuildName ( ) , buildData . getBuildDate ( ) ) ) ; } catch ( UnsupportedEncodingException e ) { throw new BuildProcessingException ( e ) ; } catch ( BugLinkException e ) { throw new BuildProcessingException ( e ) ; } catch ( final Exception ex ) { throw new BuildProcessingException ( "Failed to insert Bug Links into the DOM Document" , ex ) ; } } retValue . append ( "<!-- CS ENTITIES ) ; final String entities = ContentSpecUtilities . generateEntitiesForContentSpec ( contentSpec , buildData . getDocBookVersion ( ) , buildData . getEscapedBookTitle ( ) , buildData . getOriginalBookTitle ( ) , buildData . getOriginalBookProduct ( ) ) ; retValue . append ( entities ) ; if ( buildData . getDocBookVersion ( ) == DocBookVersion . DOCBOOK_50 ) { retValue . append ( "<!-- START DOCBOOK ENTITIES ) ; retValue . append ( docbook45Entities ) ; } return retValue . toString ( ) ; }
Builds the book . ent file that is a basic requirement to build the book .
14,780
protected void setUpRootElement ( final BuildData buildData , final Level level , final Document doc , Element ele ) { final Element titleNode = doc . createElement ( "title" ) ; if ( buildData . isTranslationBuild ( ) && ! isNullOrEmpty ( level . getTranslatedTitle ( ) ) ) { titleNode . setTextContent ( DocBookUtilities . escapeForXML ( level . getTranslatedTitle ( ) ) ) ; } else { titleNode . setTextContent ( DocBookUtilities . escapeForXML ( level . getTitle ( ) ) ) ; } final Element infoElement ; if ( level . getInfoTopic ( ) != null ) { final InfoTopic infoTopic = level . getInfoTopic ( ) ; final Node info = doc . importNode ( infoTopic . getXMLDocument ( ) . getDocumentElement ( ) , true ) ; final String elementInfoName ; if ( buildData . getDocBookVersion ( ) == DocBookVersion . DOCBOOK_50 ) { elementInfoName = "info" ; } else { elementInfoName = ele . getNodeName ( ) + "info" ; } infoElement = doc . createElement ( elementInfoName ) ; final NodeList infoChildren = info . getChildNodes ( ) ; while ( infoChildren . getLength ( ) > 0 ) { infoElement . appendChild ( infoChildren . item ( 0 ) ) ; } } else { infoElement = null ; } if ( buildData . getDocBookVersion ( ) == DocBookVersion . DOCBOOK_50 ) { ele . appendChild ( titleNode ) ; if ( infoElement != null ) { ele . appendChild ( infoElement ) ; } } else { if ( infoElement != null ) { ele . appendChild ( infoElement ) ; } ele . appendChild ( titleNode ) ; } DocBookBuildUtilities . setDOMElementId ( buildData . getDocBookVersion ( ) , ele , level . getUniqueLinkId ( buildData . isUseFixedUrls ( ) ) ) ; }
Sets up an elements title info and id based on the passed level .
14,781
protected String createTopicXMLFile ( final BuildData buildData , final SpecTopic specTopic , final String parentFileLocation ) throws BuildProcessingException { String topicFileName ; final BaseTopicWrapper < ? > topic = specTopic . getTopic ( ) ; if ( topic != null ) { topicFileName = specTopic . getUniqueLinkId ( buildData . isUseFixedUrls ( ) ) + ".xml" ; final String fixedParentFileLocation = buildData . getBuildOptions ( ) . getFlattenTopics ( ) ? buildData . getBookTopicsFolder ( ) : parentFileLocation ; final String fixedEntityPath = fixedParentFileLocation . replace ( buildData . getBookLocaleFolder ( ) , "" ) . replaceAll ( ".*?" + File . separator + "" , "../" ) ; final String topicXML = DocBookBuildUtilities . convertDocumentToDocBookFormattedString ( buildData . getDocBookVersion ( ) , specTopic . getXMLDocument ( ) , DocBookUtilities . TOPIC_ROOT_NODE_NAME , fixedEntityPath + buildData . getEntityFileName ( ) , getXMLFormatProperties ( ) ) ; addToZip ( fixedParentFileLocation + topicFileName , topicXML , buildData ) ; return topicFileName ; } return null ; }
Creates the Topic component of a chapter . xml for a specific SpecTopic .
14,782
protected void buildRevisionHistoryFromTemplate ( final BuildData buildData , final String revisionHistoryXml ) throws BuildProcessingException { log . info ( "\tBuilding " + REVISION_HISTORY_FILE_NAME ) ; Document revHistoryDoc ; try { revHistoryDoc = XMLUtilities . convertStringToDocument ( revisionHistoryXml ) ; } catch ( Exception ex ) { log . debug ( "" , ex ) ; throw new BuildProcessingException ( String . format ( getMessages ( ) . getString ( "FAILED_CONVERTING_TEMPLATE" ) , REVISION_HISTORY_FILE_NAME ) ) ; } if ( revHistoryDoc == null ) { throw new BuildProcessingException ( String . format ( getMessages ( ) . getString ( "FAILED_CONVERTING_TEMPLATE" ) , REVISION_HISTORY_FILE_NAME ) ) ; } final String reportHistoryTitleTranslation = buildData . getConstants ( ) . getString ( "REVISION_HISTORY" ) ; if ( reportHistoryTitleTranslation != null ) { DocBookUtilities . setRootElementTitle ( reportHistoryTitleTranslation , revHistoryDoc ) ; } final Element revHistory ; final NodeList revHistories = revHistoryDoc . getElementsByTagName ( "revhistory" ) ; if ( revHistories . getLength ( ) > 0 ) { revHistory = ( Element ) revHistories . item ( 0 ) ; } else { revHistory = revHistoryDoc . createElement ( "revhistory" ) ; if ( buildData . getDocBookVersion ( ) == DocBookVersion . DOCBOOK_50 ) { revHistoryDoc . getDocumentElement ( ) . appendChild ( revHistory ) ; } else { final Element simpara = revHistoryDoc . createElement ( "simpara" ) ; simpara . appendChild ( revHistory ) ; revHistoryDoc . getDocumentElement ( ) . appendChild ( simpara ) ; } } final TagWrapper author = buildData . getRequester ( ) == null ? null : tagProvider . getTagByName ( buildData . getRequester ( ) ) ; if ( isShuttingDown . get ( ) ) { return ; } if ( author != null ) { AuthorInformation authorInfo = EntityUtilities . getAuthorInformation ( providerFactory , buildData . getServerEntities ( ) , author . getId ( ) , author . getRevision ( ) ) ; if ( authorInfo != null ) { final Element revision = generateRevision ( buildData , revHistoryDoc , authorInfo ) ; addRevisionToRevHistory ( revHistory , revision ) ; } else { authorInfo = new AuthorInformation ( - 1 , BuilderConstants . DEFAULT_AUTHOR_FIRSTNAME , BuilderConstants . DEFAULT_AUTHOR_LASTNAME , BuilderConstants . DEFAULT_EMAIL ) ; final Element revision = generateRevision ( buildData , revHistoryDoc , authorInfo ) ; addRevisionToRevHistory ( revHistory , revision ) ; } } else { final AuthorInformation authorInfo = new AuthorInformation ( - 1 , BuilderConstants . DEFAULT_AUTHOR_FIRSTNAME , BuilderConstants . DEFAULT_AUTHOR_LASTNAME , BuilderConstants . DEFAULT_EMAIL ) ; final Element revision = generateRevision ( buildData , revHistoryDoc , authorInfo ) ; addRevisionToRevHistory ( revHistory , revision ) ; } final String fixedRevisionHistoryXml = DocBookBuildUtilities . convertDocumentToDocBookFormattedString ( buildData . getDocBookVersion ( ) , revHistoryDoc , "appendix" , buildData . getEntityFileName ( ) , getXMLFormatProperties ( ) ) ; addToZip ( buildData . getBookLocaleFolder ( ) + REVISION_HISTORY_FILE_NAME , fixedRevisionHistoryXml , buildData ) ; }
Builds the revision history using the requester of the build .
14,783
private void addRevisionToRevHistory ( final Node revHistory , final Node revision ) { if ( revHistory . hasChildNodes ( ) ) { revHistory . insertBefore ( revision , revHistory . getFirstChild ( ) ) ; } else { revHistory . appendChild ( revision ) ; } }
Adds a revision element to the list of revisions in a revhistory element . This method ensures that the new revision is at the top of the revhistory list .
14,784
private String buildTranslateCSChapter ( final BuildData buildData ) { final ContentSpec contentSpec = buildData . getContentSpec ( ) ; final TranslatedContentSpecWrapper translatedContentSpec = EntityUtilities . getClosestTranslatedContentSpecById ( providerFactory , contentSpec . getId ( ) , contentSpec . getRevision ( ) ) ; final String para ; if ( translatedContentSpec != null ) { final String url = translatedContentSpec . getEditorURL ( buildData . getZanataDetails ( ) , buildData . getBuildLocale ( ) ) ; if ( url != null ) { para = DocBookUtilities . wrapInPara ( DocBookUtilities . buildULink ( url , "Translate this Content Spec" ) ) ; } else { para = DocBookUtilities . wrapInPara ( "No editor link available as this Content Specification hasn't been pushed for Translation." ) ; } } else { para = DocBookUtilities . wrapInPara ( "No editor link available as this Content Specification hasn't been pushed for Translation." ) ; } if ( contentSpec . getBookType ( ) == BookType . ARTICLE || contentSpec . getBookType ( ) == BookType . ARTICLE_DRAFT ) { return DocBookUtilities . buildSection ( para , "Content Specification" ) ; } else { return DocBookUtilities . buildChapter ( para , "Content Specification" ) ; } }
Builds a Chapter with a single paragraph that contains a link to translate the Content Specification .
14,785
private String buildErrorChapterGlossary ( final BuildData buildData , final String title ) { final StringBuilder glossary = new StringBuilder ( "<glossary>" ) ; glossary . append ( "<title>" ) ; if ( title != null ) { glossary . append ( title ) ; } glossary . append ( "</title>" ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . WARNING_EMPTY_TOPIC_XML + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . WARNING_NO_CONTENT_TOPIC_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . ERROR_INVALID_XML_CONTENT + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . ERROR_INVALID_XML_CONTENT_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . ERROR_BAD_XML_STRUCTURE + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . ERROR_BAD_XML_STRUCTURE_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . ERROR_INVALID_TOPIC_XML + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . ERROR_INVALID_TOPIC_XML_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . ERROR_INVALID_INJECTIONS + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . ERROR_INVALID_INJECTIONS_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"... " + BuilderConstants . WARNING_POSSIBLE_INVALID_INJECTIONS + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . WARNING_POSSIBLE_INVALID_INJECTIONS_DEFINITION ) ) ) ; if ( buildData . isTranslationBuild ( ) ) { glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . WARNING_INCOMPLETE_TRANSLATION + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . WARNING_INCOMPLETE_TRANSLATED_TOPIC_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . WARNING_FUZZY_TRANSLATION + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . WARNING_FUZZY_TRANSLATED_TOPIC_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . WARNING_UNTRANSLATED_TOPIC + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . WARNING_UNTRANSLATED_TOPIC_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . WARNING_NONPUSHED_TOPIC + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . WARNING_NONPUSHED_TOPIC_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . WARNING_OLD_TRANSLATED_TOPIC + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . WARNING_OLD_TRANSLATED_TOPIC_DEFINITION ) ) ) ; glossary . append ( DocBookUtilities . wrapInGlossEntry ( DocBookUtilities . wrapInGlossTerm ( "\"" + BuilderConstants . WARNING_OLD_UNTRANSLATED_TOPIC + "\"" ) , DocBookUtilities . wrapInItemizedGlossDef ( null , BuilderConstants . WARNING_OLD_UNTRANSLATED_TOPIC_DEFINITION ) ) ) ; } glossary . append ( "</glossary>" ) ; return glossary . toString ( ) ; }
Builds the Glossary used in the Error Chapter .
14,786
@ SuppressWarnings ( "unchecked" ) private void processImageLocations ( final BuildData buildData ) { final List < Integer > topicIds = buildData . getBuildDatabase ( ) . getTopicIds ( ) ; for ( final Integer topicId : topicIds ) { final ITopicNode topicNode = buildData . getBuildDatabase ( ) . getTopicNodesForTopicID ( topicId ) . get ( 0 ) ; final BaseTopicWrapper < ? > topic = topicNode . getTopic ( ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "\tProcessing SpecTopic " + topicNode . getId ( ) + ( topicNode . getRevision ( ) != null ? ( ", " + "Revision " + topicNode . getRevision ( ) ) : "" ) ) ; final List < Node > images = XMLUtilities . getChildNodes ( topicNode . getXMLDocument ( ) , "imagedata" , "inlinegraphic" ) ; for ( final Node imageNode : images ) { final NamedNodeMap attributes = imageNode . getAttributes ( ) ; if ( attributes != null ) { final Node fileRefAttribute = attributes . getNamedItem ( "fileref" ) ; if ( fileRefAttribute != null && ( fileRefAttribute . getNodeValue ( ) == null || fileRefAttribute . getNodeValue ( ) . isEmpty ( ) ) ) { fileRefAttribute . setNodeValue ( "images/" + BuilderConstants . FAILPENGUIN_PNG_NAME + ".jpg" ) ; buildData . getImageLocations ( ) . add ( new TopicImageData ( topic , fileRefAttribute . getNodeValue ( ) ) ) ; } else if ( fileRefAttribute != null && fileRefAttribute . getNodeValue ( ) != null ) { final String fileRefValue = fileRefAttribute . getNodeValue ( ) ; if ( BuilderConstants . IMAGE_FILE_REF_PATTERN . matcher ( fileRefValue ) . matches ( ) ) { if ( fileRefValue . startsWith ( "./images/" ) ) { fileRefAttribute . setNodeValue ( fileRefValue . substring ( 2 ) ) ; } else if ( ! fileRefValue . startsWith ( "images/" ) ) { fileRefAttribute . setNodeValue ( "images/" + fileRefValue ) ; } buildData . getImageLocations ( ) . add ( new TopicImageData ( topic , fileRefAttribute . getNodeValue ( ) ) ) ; } else if ( ! BuilderConstants . COMMON_CONTENT_FILE_REF_PATTERN . matcher ( fileRefValue ) . matches ( ) ) { fileRefAttribute . setNodeValue ( "images/" + BuilderConstants . FAILPENGUIN_PNG_NAME + ".jpg" ) ; buildData . getImageLocations ( ) . add ( new TopicImageData ( topic , fileRefAttribute . getNodeValue ( ) ) ) ; } } } } } }
Processes the Topics in the BuildDatabase and builds up the images found within the topics XML . If the image reference is blank or invalid it is replaced by the fail penguin image .
14,787
protected void processTopicSectionInfo ( final BuildData buildData , final BaseTopicWrapper < ? > topic , final Document doc ) { if ( doc == null || topic == null ) return ; final String infoName ; if ( buildData . getDocBookVersion ( ) == DocBookVersion . DOCBOOK_50 ) { infoName = "info" ; } else { infoName = DocBookUtilities . TOPIC_ROOT_SECTIONINFO_NODE_NAME ; } final CollectionWrapper < TagWrapper > tags = topic . getTags ( ) ; final List < Integer > seoCategoryIds = buildData . getServerSettings ( ) . getSEOCategoryIds ( ) ; if ( seoCategoryIds != null && ! seoCategoryIds . isEmpty ( ) && tags != null && tags . getItems ( ) != null && tags . getItems ( ) . size ( ) > 0 ) { final Element sectionInfo ; final List < Node > sectionInfoNodes = XMLUtilities . getDirectChildNodes ( doc . getDocumentElement ( ) , infoName ) ; if ( sectionInfoNodes . size ( ) == 1 ) { sectionInfo = ( Element ) sectionInfoNodes . get ( 0 ) ; } else { sectionInfo = doc . createElement ( infoName ) ; } final Element keywordSet = doc . createElement ( "keywordset" ) ; final List < TagWrapper > tagItems = tags . getItems ( ) ; for ( final TagWrapper tag : tagItems ) { if ( tag . getName ( ) == null || tag . getName ( ) . isEmpty ( ) ) continue ; if ( tag . containedInCategories ( seoCategoryIds ) ) { final Element keyword = doc . createElement ( "keyword" ) ; keyword . setTextContent ( tag . getName ( ) ) ; keywordSet . appendChild ( keyword ) ; } } if ( keywordSet . hasChildNodes ( ) ) { sectionInfo . appendChild ( keywordSet ) ; DocBookUtilities . setInfo ( buildData . getDocBookVersion ( ) , sectionInfo , doc . getDocumentElement ( ) ) ; } } }
Process a topic and add the section info information . This information consists of the keywordset information . The keywords are populated using the tags assigned to the topic .
14,788
protected boolean doFixedURLsPass ( final BuildData buildData ) throws BuildProcessingException { log . info ( "Doing Fixed URL Pass" ) ; final Set < String > processedFileNames = new HashSet < String > ( ) ; final Set < SpecNode > nodesWithoutFixedUrls = new HashSet < SpecNode > ( ) ; boolean success = true ; try { FixedURLGenerator . collectFixedUrlInformation ( buildData . getBuildDatabase ( ) . getAllSpecNodes ( ) , nodesWithoutFixedUrls , processedFileNames ) ; if ( ! nodesWithoutFixedUrls . isEmpty ( ) ) { log . info ( "\tUsing " + nodesWithoutFixedUrls . size ( ) + " temporary Fixed URLs" ) ; } FixedURLGenerator . generateFixedUrlForNodes ( nodesWithoutFixedUrls , processedFileNames , buildData . getServerEntities ( ) . getFixedUrlPropertyTagId ( ) ) ; } catch ( Exception e ) { success = false ; log . debug ( "" , e ) ; throw new BuildProcessingException ( "Failed to update the Fixed URLs. Please try again and if the issue persists please log a bug." ) ; } return success ; }
This method does a pass over all the spec nodes and attempts to create unique Fixed URL if one does not already exist .
14,789
protected void addAdditionalFilesToBook ( final BuildData buildData ) throws BuildProcessingException { final FileProvider fileProvider = providerFactory . getProvider ( FileProvider . class ) ; final ContentSpec contentSpec = buildData . getContentSpec ( ) ; if ( contentSpec . getFiles ( ) != null ) { log . info ( "\tDownloading Additional Files" ) ; for ( final org . jboss . pressgang . ccms . contentspec . File file : contentSpec . getFiles ( ) ) { try { final FileWrapper fileEntity = fileProvider . getFile ( file . getId ( ) , file . getRevision ( ) ) ; LanguageFileWrapper languageFileFile = null ; if ( fileEntity . getLanguageFiles ( ) != null && fileEntity . getLanguageFiles ( ) . getItems ( ) != null ) { final List < LanguageFileWrapper > languageFiles = fileEntity . getLanguageFiles ( ) . getItems ( ) ; for ( final LanguageFileWrapper languageFile : languageFiles ) { if ( languageFile . getLocale ( ) . getValue ( ) . equals ( buildData . getBuildLocale ( ) ) ) { languageFileFile = languageFile ; } else if ( languageFile . getLocale ( ) . getValue ( ) . equals ( buildData . getDefaultLocale ( ) ) && languageFileFile == null ) { languageFileFile = languageFile ; } } } if ( languageFileFile != null && languageFileFile . getFileData ( ) != null ) { final String filePath ; if ( ! isNullOrEmpty ( fileEntity . getFilePath ( ) ) ) { if ( fileEntity . getFilePath ( ) . endsWith ( "/" ) || fileEntity . getFilePath ( ) . endsWith ( "\\" ) ) { filePath = fileEntity . getFilePath ( ) ; } else { filePath = fileEntity . getFilePath ( ) + "/" ; } } else { filePath = "" ; } if ( fileEntity . isExplodeArchive ( ) ) { try { final Map < String , byte [ ] > files = ZipUtilities . unzipFile ( languageFileFile . getFileData ( ) , false ) ; for ( final Entry < String , byte [ ] > entry : files . entrySet ( ) ) { addToZip ( buildData . getBookFilesFolder ( ) + filePath + entry . getKey ( ) , entry . getValue ( ) , buildData ) ; } } catch ( IOException e ) { throw new BuildProcessingException ( e ) ; } } else { addToZip ( buildData . getBookFilesFolder ( ) + filePath + fileEntity . getFilename ( ) , languageFileFile . getFileData ( ) , buildData ) ; } } else { throw new BuildProcessingException ( "File ID " + fileEntity . getId ( ) + " has no language files!" ) ; } } catch ( NotFoundException e ) { throw new BuildProcessingException ( "File ID " + file . getId ( ) + " could not be found!" ) ; } } } }
Adds the additional files defined in a content spec to the book .
14,790
private void segmentPage ( ) { DefaultContentRect . resetId ( ) ; if ( segmentatorCombo . getSelectedIndex ( ) != - 1 ) { AreaTreeProvider provider = segmentatorCombo . getItemAt ( segmentatorCombo . getSelectedIndex ( ) ) ; proc . segmentPage ( provider , null ) ; setAreaTree ( proc . getAreaTree ( ) ) ; } }
Segments the page using the chosen provider and parametres .
14,791
private void buildLogicalTree ( ) { if ( logicalCombo . getSelectedIndex ( ) != - 1 ) { LogicalTreeProvider provider = logicalCombo . getItemAt ( logicalCombo . getSelectedIndex ( ) ) ; proc . buildLogicalTree ( provider , null ) ; setLogicalTree ( proc . getLogicalAreaTree ( ) ) ; } }
Builds the logical tree the chosen provider and parametres .
14,792
private JPanel createContentCanvas ( ) { if ( contentCanvas != null ) { contentCanvas = new BrowserPanel ( proc . getPage ( ) ) ; contentCanvas . setLayout ( null ) ; selection = new Selection ( ) ; contentCanvas . add ( selection ) ; selection . setVisible ( false ) ; selection . setLocation ( 0 , 0 ) ; } return contentCanvas ; }
Creates the appropriate canvas based on the file type
14,793
private void canvasClick ( int x , int y ) { for ( CanvasClickListener listener : canvasClickAlwaysListeners ) listener . canvasClicked ( x , y ) ; for ( JToggleButton button : canvasClickToggleListeners . keySet ( ) ) { if ( button . isSelected ( ) ) canvasClickToggleListeners . get ( button ) . canvasClicked ( x , y ) ; } }
This is called when the browser canvas is clicked
14,794
@ SuppressWarnings ( "PMD.EmptyCatchBlock" ) private synchronized void cleanup ( final WatchKey key ) { logger . trace ( "cleanUp {}" , key ) ; try { key . cancel ( ) ; } catch ( Exception ex ) { } Collection < SFMF4JWatchListener > listeners = listenersByWatchKey . remove ( key ) ; if ( listeners != null && ! listeners . isEmpty ( ) ) { logger . warn ( "Cleaning up key but listeners are still registered." ) ; } String path = pathsByWatchKey . remove ( key ) ; if ( path != null ) { watchKeysByPath . remove ( path ) ; } }
Properly unregisters and removes a watch key .
14,795
public static Map < String , String > getCapabilities ( HttpServletRequest request , String ddsUrl ) throws IOException { URL url ; try { url = new URL ( ddsUrl + "/get_capabilities?capability=resolution_width&capability=model_name&capability=xhtml_support_level&" + "headers=" + URLEncoder . encode ( jsonEncode ( getHeadersAsHashMap ( request ) ) , "UTF-8" ) ) ; } catch ( MalformedURLException e ) { throw new IOException ( e ) ; } String httpResponse = fetchHttpResponse ( url ) ; return jsonDecode ( httpResponse , new TypeReference < Map < String , String > > ( ) { } ) ; }
Get the capabilities as a map of capabilities . There are times that a strict data type is not desirable . Getting it as map provides some flexibility . This does not require any knowledge of what capabilities will be returned by the service .
14,796
private static String fetchHttpResponse ( URL url ) throws IOException { HttpURLConnection conn = null ; try { logger . info ( "fetching from url = " + url ) ; conn = ( HttpURLConnection ) url . openConnection ( ) ; int response = conn . getResponseCode ( ) ; if ( response != HttpURLConnection . HTTP_ACCEPTED ) { String responseContent = IOUtils . toString ( conn . getInputStream ( ) ) ; logger . info ( "responseContent = " + responseContent ) ; return responseContent ; } throw new IOException ( "response from service not valid" ) ; } catch ( IOException e ) { logger . severe ( "unable to do proper http request url = " + url . toString ( ) ) ; throw e ; } finally { conn . disconnect ( ) ; } }
convenience method to do a http request on url and return result as a string
14,797
private static < T > T jsonDecode ( String responseContent , TypeReference < T > valueTypeRef ) throws IOException { ObjectMapper mapper = new ObjectMapper ( ) ; try { return mapper . < T > readValue ( responseContent , valueTypeRef ) ; } catch ( JsonGenerationException e ) { logger . severe ( "unable decode" ) ; throw new IOException ( e ) ; } catch ( JsonMappingException e ) { logger . severe ( "unable decode" ) ; throw new IOException ( e . getMessage ( ) ) ; } }
Given a string and a type ref . Decode the string and return the values .
14,798
private static String jsonEncode ( Object object ) throws IOException { ObjectMapper mapper = new ObjectMapper ( ) ; ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; try { mapper . writeValue ( outputStream , object ) ; return new String ( outputStream . toByteArray ( ) ) ; } catch ( JsonGenerationException e ) { logger . severe ( "unable encode" ) ; throw new IOException ( e ) ; } catch ( JsonMappingException e ) { logger . severe ( "unable encode" ) ; throw new IOException ( e . getMessage ( ) ) ; } }
Encode a java object into a json which is returned as a string
14,799
private static Map < String , String > getHeadersAsHashMap ( HttpServletRequest request ) { Map < String , String > headers = new HashMap < String , String > ( ) ; for ( Enumeration < ? > h = request . getHeaderNames ( ) ; h . hasMoreElements ( ) ; ) { String headerName = ( String ) h . nextElement ( ) ; String headerValue = request . getHeader ( headerName ) ; headers . put ( headerName . toLowerCase ( ) , headerValue ) ; } return headers ; }
convenience method turn http headers into a hash map