idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
12,600
private static Element getCobolXsdAnnotations ( XmlSchemaElement xsdElement ) { XmlSchemaAnnotation annotation = xsdElement . getAnnotation ( ) ; if ( annotation == null || annotation . getItems ( ) . size ( ) == 0 ) { throw new IllegalArgumentException ( "Xsd element of type " + xsdElement . getSchemaType ( ) . getQName ( ) + " at line " + xsdElement . getLineNumber ( ) + " does not have COBOL annotations" ) ; } XmlSchemaAppInfo appinfo = ( XmlSchemaAppInfo ) annotation . getItems ( ) . get ( 0 ) ; if ( appinfo . getMarkup ( ) == null ) { throw new IllegalArgumentException ( "Xsd element of type " + xsdElement . getSchemaType ( ) . getQName ( ) + " does not have any markup in its annotations" ) ; } Node node = null ; boolean found = false ; for ( int i = 0 ; i < appinfo . getMarkup ( ) . getLength ( ) ; i ++ ) { node = appinfo . getMarkup ( ) . item ( i ) ; if ( node instanceof Element && node . getLocalName ( ) . equals ( CobolMarkup . ELEMENT ) && node . getNamespaceURI ( ) . equals ( CobolMarkup . NS ) ) { found = true ; break ; } } if ( ! found ) { throw new IllegalArgumentException ( "Xsd element of type " + xsdElement . getSchemaType ( ) . getQName ( ) + " at line " + xsdElement . getLineNumber ( ) + " does not have any COBOL annotations" ) ; } return ( Element ) node ; }
XSD elements are annotated with COBOL markup that we extract here .
12,601
public void reinitValue ( DataReader in , EntryValueShort value ) throws IOException { value . reinit ( in . readInt ( ) , in . readShort ( ) , in . readLong ( ) ) ; }
Read data from stream to populate an EntryValueShort .
12,602
private static String intPart ( String str ) { return str . indexOf ( JAVA_DECIMAL_POINT ) > 0 ? str . substring ( 0 , str . indexOf ( JAVA_DECIMAL_POINT ) ) : str ; }
Removes the fractional part from a numeric s string representation .
12,603
public void addReportingUser ( String userId ) { addActiveParticipant ( userId , null , null , true , null , null ) ; }
Add an active participant for the user reporting the security alert
12,604
public void addActiveParticipant ( String userId ) { addActiveParticipant ( userId , null , null , false , null , null ) ; }
Add an active participant for any participant involved in the alert
12,605
public void addURIParticipantObject ( String failedUri , String failureDescription ) { List < TypeValuePairType > failureDescriptionValue = new LinkedList < > ( ) ; if ( ! EventUtils . isEmptyOrNull ( failureDescription ) ) { failureDescriptionValue . add ( getTypeValuePair ( "Alert Description" , failureDescription . getBytes ( ) ) ) ; } this . addParticipantObjectIdentification ( new RFC3881ParticipantObjectCodes . RFC3881ParticipantObjectIDTypeCodes . PatientNumber ( ) , null , null , failureDescriptionValue , failedUri , RFC3881ParticipantObjectTypeCodes . SYSTEM , RFC3881ParticipantObjectTypeRoleCodes . MASTER_FILE , null , null ) ; }
Adds a Participant Object representing the URI resource that was accessed and generated the Security Alert
12,606
protected void initCheck ( ) throws IOException { if ( _version != STORAGE_VERSION ) { throw new IOException ( "Invalid version in " + _file . getName ( ) + ": " + _version + ", " + STORAGE_VERSION + " expected" ) ; } if ( ! checkHeader ( ) ) { throw new IOException ( "Invalid header in " + _file . getName ( ) + ": " + getHeader ( ) ) ; } }
Checks the header of this ArrayFile upon initial loading .
12,607
public void load ( MemoryIntArray intArray ) throws IOException { if ( ! _file . exists ( ) || _file . length ( ) == 0 ) { return ; } Chronos c = new Chronos ( ) ; DataReader r = IOFactory . createDataReader ( _file , _type ) ; try { r . open ( ) ; r . position ( DATA_START_POSITION ) ; for ( int i = 0 ; i < _arrayLength ; i ++ ) { intArray . set ( i , r . readInt ( ) ) ; } _log . info ( _file . getName ( ) + " loaded in " + c . getElapsedTime ( ) ) ; } finally { r . close ( ) ; } }
Loads this ArrayFile into a memory - based int array .
12,608
public void load ( MemoryLongArray longArray ) throws IOException { if ( ! _file . exists ( ) || _file . length ( ) == 0 ) { return ; } Chronos c = new Chronos ( ) ; DataReader r = IOFactory . createDataReader ( _file , _type ) ; try { r . open ( ) ; r . position ( DATA_START_POSITION ) ; for ( int i = 0 ; i < _arrayLength ; i ++ ) { longArray . set ( i , r . readLong ( ) ) ; } _log . info ( _file . getName ( ) + " loaded in " + c . getElapsedTime ( ) ) ; } finally { r . close ( ) ; } }
Loads this ArrayFile into a memory - based long array .
12,609
public void load ( MemoryShortArray shortArray ) throws IOException { if ( ! _file . exists ( ) || _file . length ( ) == 0 ) { return ; } Chronos c = new Chronos ( ) ; DataReader r = IOFactory . createDataReader ( _file , _type ) ; try { r . open ( ) ; r . position ( DATA_START_POSITION ) ; for ( int i = 0 ; i < _arrayLength ; i ++ ) { shortArray . set ( i , r . readShort ( ) ) ; } _log . info ( _file . getName ( ) + " loaded in " + c . getElapsedTime ( ) ) ; } finally { r . close ( ) ; } }
Loads this ArrayFile into a memory - based short array .
12,610
public short [ ] loadShortArray ( ) throws IOException { if ( ! _file . exists ( ) || _file . length ( ) == 0 ) { return null ; } Chronos c = new Chronos ( ) ; DataReader r = IOFactory . createDataReader ( _file , _type ) ; try { r . open ( ) ; r . position ( DATA_START_POSITION ) ; short [ ] array = new short [ _arrayLength ] ; for ( int i = 0 ; i < _arrayLength ; i ++ ) { array [ i ] = r . readShort ( ) ; } _log . info ( _file . getName ( ) + " loaded in " + c . getElapsedTime ( ) ) ; return array ; } finally { r . close ( ) ; } }
Loads the main array .
12,611
public synchronized < T extends EntryValue > void update ( List < Entry < T > > entryList ) throws IOException { Chronos c = new Chronos ( ) ; T [ ] values = EntryUtility . sortEntriesToValues ( entryList ) ; if ( values == null || values . length == 0 ) return ; long maxScn = _arrayHwmScn ; for ( Entry < ? > e : entryList ) { maxScn = Math . max ( e . getMaxScn ( ) , maxScn ) ; } _log . info ( "write hwmScn:" + maxScn ) ; _writer . writeLong ( HWM_SCN_POSITION , maxScn ) ; _writer . flush ( ) ; for ( T v : values ) { v . updateArrayFile ( _writer , getPosition ( v . pos ) ) ; } _writer . flush ( ) ; _log . info ( "write lwmScn:" + maxScn ) ; _writer . writeLong ( LWM_SCN_POSITION , maxScn ) ; _writer . flush ( ) ; _arrayLwmScn = maxScn ; _arrayHwmScn = maxScn ; _log . info ( entryList . size ( ) + " entries flushed to " + _file . getAbsolutePath ( ) + " in " + c . getElapsedTime ( ) ) ; }
Apply entries to the array file .
12,612
public void setWaterMarks ( long lwmScn , long hwmScn ) throws IOException { if ( lwmScn <= hwmScn ) { writeHwmScn ( hwmScn ) ; _writer . flush ( ) ; writeLwmScn ( lwmScn ) ; _writer . flush ( ) ; } else { throw new IOException ( "Invalid water marks: lwmScn=" + lwmScn + " hwmScn=" + hwmScn ) ; } }
Sets the water marks of this ArrayFile .
12,613
public synchronized void resetAll ( long value ) throws IOException { if ( _elementSize != 8 ) { throw new IOException ( "Operation aborted: elementSize=" + _elementSize ) ; } _writer . flush ( ) ; _writer . position ( DATA_START_POSITION ) ; for ( int i = 0 ; i < this . _arrayLength ; i ++ ) { _writer . writeLong ( value ) ; } _writer . flush ( ) ; }
Resets all element values to the specified long value .
12,614
public synchronized void setArrayLength ( int arrayLength , File renameToFile ) throws IOException { if ( arrayLength < 0 ) { throw new IOException ( "Invalid array length: " + arrayLength ) ; } if ( this . _arrayLength == arrayLength ) return ; this . flush ( ) ; long fileLength = DATA_START_POSITION + ( ( long ) arrayLength * _elementSize ) ; RandomAccessFile raf = new RandomAccessFile ( _file , "rw" ) ; try { raf . setLength ( fileLength ) ; } catch ( IOException e ) { _log . error ( "failed to setArrayLength " + arrayLength ) ; throw e ; } finally { raf . close ( ) ; } writeArrayLength ( arrayLength ) ; this . flush ( ) ; if ( renameToFile != null ) { if ( _file . renameTo ( renameToFile ) ) { _writer . close ( ) ; _file = renameToFile ; _writer = IOFactory . createDataWriter ( _file , _type ) ; _writer . open ( ) ; return ; } else { _log . warn ( "Failed to rename " + _file . getAbsolutePath ( ) + " to " + renameToFile . getAbsolutePath ( ) ) ; } } if ( MultiMappedWriter . class . isInstance ( _writer ) ) { ( ( MultiMappedWriter ) _writer ) . remap ( ) ; _log . info ( "remap " + _file . getPath ( ) + " " + _file . length ( ) ) ; } else { _writer . close ( ) ; _writer = IOFactory . createDataWriter ( _file , _type ) ; _writer . open ( ) ; } }
Updates the length of this ArrayFile to the specified value .
12,615
public static Usage getUsage ( String cobolUsage ) { if ( cobolUsage == null ) { return null ; } if ( cobolUsage . equals ( BINARY ) ) { return Usage . BINARY ; } else if ( cobolUsage . equals ( "COMP" ) ) { return Usage . BINARY ; } else if ( cobolUsage . equals ( "COMPUTATIONAL" ) ) { return Usage . BINARY ; } else if ( cobolUsage . equals ( "COMP-4" ) ) { return Usage . BINARY ; } else if ( cobolUsage . equals ( "COMPUTATIONAL-4" ) ) { return Usage . BINARY ; } else if ( cobolUsage . equals ( COMP_1 ) ) { return Usage . SINGLEFLOAT ; } else if ( cobolUsage . equals ( COMP_2 ) ) { return Usage . DOUBLEFLOAT ; } else if ( cobolUsage . equals ( PACKED_DECIMAL ) ) { return Usage . PACKEDDECIMAL ; } else if ( cobolUsage . equals ( "PACKED-DECIMAL" ) ) { return Usage . PACKEDDECIMAL ; } else if ( cobolUsage . equals ( "COMPUTATIONAL-3" ) ) { return Usage . PACKEDDECIMAL ; } else if ( cobolUsage . equals ( COMP_5 ) ) { return Usage . NATIVEBINARY ; } else if ( cobolUsage . equals ( "COMPUTATIONAL-5" ) ) { return Usage . NATIVEBINARY ; } else if ( cobolUsage . equals ( DISPLAY ) ) { return Usage . DISPLAY ; } else if ( cobolUsage . equals ( DISPLAY_1 ) ) { return Usage . DISPLAY1 ; } else if ( cobolUsage . equals ( INDEX ) ) { return Usage . INDEX ; } else if ( cobolUsage . equals ( NATIONAL ) ) { return Usage . NATIONAL ; } else if ( cobolUsage . equals ( POINTER ) ) { return Usage . POINTER ; } else if ( cobolUsage . equals ( PROCEDURE_POINTER ) ) { return Usage . PROCEDUREPOINTER ; } else if ( cobolUsage . equals ( FUNCTION_POINTER ) ) { return Usage . FUNCTIONPOINTER ; } else { throw new IllegalArgumentException ( "Unknown COBOL usage: " + cobolUsage ) ; } }
Get the java enumeration corresponding to a COBOL usage string .
12,616
public static XDMAuditor getAuditor ( ) { AuditorModuleContext ctx = AuditorModuleContext . getContext ( ) ; return ( XDMAuditor ) ctx . getAuditor ( XDMAuditor . class ) ; }
Get an instance of the XDM auditor from the global context
12,617
public void auditPortableMediaImport ( RFC3881EventOutcomeCodes eventOutcome , String submissionSetUniqueId , String patientId , List < CodedValueType > purposesOfUse ) { if ( ! isAuditorEnabled ( ) ) { return ; } ImportEvent importEvent = new ImportEvent ( false , eventOutcome , new IHETransactionEventTypeCodes . DistributeDocumentSetOnMedia ( ) , purposesOfUse ) ; importEvent . setAuditSourceId ( getAuditSourceId ( ) , getAuditEnterpriseSiteId ( ) ) ; importEvent . addDestinationActiveParticipant ( getSystemUserId ( ) , getSystemAltUserId ( ) , getSystemUserName ( ) , getSystemNetworkId ( ) , false ) ; if ( ! EventUtils . isEmptyOrNull ( patientId ) ) { importEvent . addPatientParticipantObject ( patientId ) ; } importEvent . addSubmissionSetParticipantObject ( submissionSetUniqueId ) ; audit ( importEvent ) ; }
Audits a PHI Import event for the IHE XDM Portable Media Importer actor and ITI - 32 Distribute Document Set on Media Transaction .
12,618
public void auditPortableMediaCreate ( RFC3881EventOutcomeCodes eventOutcome , String submissionSetUniqueId , String patientId , List < CodedValueType > purposesOfUse ) { if ( ! isAuditorEnabled ( ) ) { return ; } ExportEvent exportEvent = new ExportEvent ( true , eventOutcome , new IHETransactionEventTypeCodes . DistributeDocumentSetOnMedia ( ) , purposesOfUse ) ; exportEvent . setAuditSourceId ( getAuditSourceId ( ) , getAuditEnterpriseSiteId ( ) ) ; exportEvent . addSourceActiveParticipant ( getSystemUserId ( ) , getSystemAltUserId ( ) , getSystemUserName ( ) , getSystemNetworkId ( ) , true ) ; if ( ! EventUtils . isEmptyOrNull ( patientId ) ) { exportEvent . addPatientParticipantObject ( patientId ) ; } exportEvent . addSubmissionSetParticipantObject ( submissionSetUniqueId ) ; audit ( exportEvent ) ; }
Audits a PHI Export event for the IHE XDM Portable Media Creator actor ITI - 32 Distribute Document Set on Media transaction .
12,619
public long tick ( ) { long tick = System . currentTimeMillis ( ) ; long diff = tick - _lastTick ; _lastTick = tick ; return diff ; }
Returns the number of milliseconds elapsed since the last call to this function .
12,620
public String translate ( final Reader cobolReader , final String targetNamespace , final String xsltFileName ) throws XsdGenerationException { try { if ( _log . isDebugEnabled ( ) ) { _log . debug ( "Translating with options: {}" , getConfig ( ) . toString ( ) ) ; _log . debug ( "Target namespace: {}" , targetNamespace ) ; } return xsdToString ( emitXsd ( toModel ( cobolReader ) , targetNamespace ) , xsltFileName ) ; } catch ( RecognizerException e ) { throw new XsdGenerationException ( e ) ; } }
Execute the translation from COBOL to XML Schema .
12,621
public List < CobolDataItem > toModel ( final Reader cobolReader ) throws RecognizerException { return emitModel ( parse ( lex ( clean ( cobolReader ) ) ) ) ; }
Parses a COBOL source into an in - memory model .
12,622
public String clean ( final Reader cobolReader ) throws CleanerException { if ( _log . isDebugEnabled ( ) ) { _log . debug ( "1. Cleaning COBOL source code" ) ; } switch ( getConfig ( ) . getCodeFormat ( ) ) { case FIXED_FORMAT : CobolFixedFormatSourceCleaner fixedCleaner = new CobolFixedFormatSourceCleaner ( getErrorHandler ( ) , getConfig ( ) . getStartColumn ( ) , getConfig ( ) . getEndColumn ( ) ) ; return fixedCleaner . clean ( cobolReader ) ; case FREE_FORMAT : CobolFreeFormatSourceCleaner freeCleaner = new CobolFreeFormatSourceCleaner ( getErrorHandler ( ) ) ; return freeCleaner . clean ( cobolReader ) ; default : throw new CleanerException ( "Unkown COBOL source format " + getConfig ( ) . getCodeFormat ( ) ) ; } }
Remove any non COBOL Structure characters from the source .
12,623
public CommonTokenStream lex ( final String cleanedCobolSource ) throws RecognizerException { if ( _log . isDebugEnabled ( ) ) { _log . debug ( "2. Lexing COBOL source code: {}" , cleanedCobolSource ) ; } try { CobolStructureLexer lex = new CobolStructureLexerImpl ( new ANTLRReaderStream ( new StringReader ( cleanedCobolSource ) ) , getErrorHandler ( ) ) ; CommonTokenStream tokens = new CommonTokenStream ( lex ) ; if ( lex . getNumberOfSyntaxErrors ( ) != 0 || tokens == null ) { throw ( new RecognizerException ( "Lexing failed. " + lex . getNumberOfSyntaxErrors ( ) + " syntax errors." + " Last error was " + getErrorHistory ( ) . get ( getErrorHistory ( ) . size ( ) - 1 ) ) ) ; } return tokens ; } catch ( IOException e ) { throw ( new RecognizerException ( e ) ) ; } }
Apply the lexer to produce a token stream from source .
12,624
public CommonTree parse ( final CommonTokenStream tokens ) throws RecognizerException { if ( _log . isDebugEnabled ( ) ) { _log . debug ( "3. Parsing tokens: {}" , tokens . toString ( ) ) ; } try { CobolStructureParser parser = new CobolStructureParserImpl ( tokens , getErrorHandler ( ) ) ; cobdata_return parserResult = parser . cobdata ( ) ; if ( parser . getNumberOfSyntaxErrors ( ) != 0 || parserResult == null ) { throw ( new RecognizerException ( "Parsing failed. " + parser . getNumberOfSyntaxErrors ( ) + " syntax errors." + " Last error was " + getErrorHistory ( ) . get ( getErrorHistory ( ) . size ( ) - 1 ) ) ) ; } return ( CommonTree ) parserResult . getTree ( ) ; } catch ( RecognitionException e ) { throw ( new RecognizerException ( e ) ) ; } }
Apply Parser to produce an abstract syntax tree from a token stream .
12,625
public List < CobolDataItem > emitModel ( final CommonTree ast ) throws RecognizerException { List < CobolDataItem > cobolDataItems = new ArrayList < CobolDataItem > ( ) ; if ( _log . isDebugEnabled ( ) ) { _log . debug ( "4. Emitting Model from AST: {}" , ( ( ast == null ) ? "null" : ast . toStringTree ( ) ) ) ; } if ( ast == null ) { return cobolDataItems ; } try { TreeNodeStream nodes = new CommonTreeNodeStream ( ast ) ; CobolStructureEmitter emitter = new CobolStructureEmitterImpl ( nodes , getErrorHandler ( ) ) ; emitter . cobdata ( cobolDataItems ) ; return cobolDataItems ; } catch ( RecognitionException e ) { throw new RecognizerException ( e ) ; } }
Generates a model from an Abstract Syntax Tree .
12,626
public static List < String > getNonUniqueCobolNames ( final List < CobolDataItem > cobolDataItems ) { List < String > cobolNames = new ArrayList < String > ( ) ; List < String > nonUniqueCobolNames = new ArrayList < String > ( ) ; for ( CobolDataItem cobolDataItem : cobolDataItems ) { getNonUniqueCobolNames ( cobolDataItem , cobolNames , nonUniqueCobolNames ) ; } return nonUniqueCobolNames ; }
Create a list of COBOL names which are not unique . This is useful when we build complex type names from the COBOL names . Complex type names need to be unique within a target namespace .
12,627
private Socket getTLSSocket ( InetAddress destination , int port ) throws Exception { String key = destination . getHostAddress ( ) + ":" + port ; synchronized ( socketMap ) { Socket socket = socketMap . get ( key ) ; if ( socket == null ) { NodeAuthModuleContext nodeAuthContext = NodeAuthModuleContext . getContext ( ) ; socket = nodeAuthContext . getSocketHandler ( ) . getSocket ( destination . getHostName ( ) , port , true ) ; socketMap . put ( key , socket ) ; } return socket ; } }
Gets the socket tied to the address and port for this transport
12,628
public synchronized void clear ( ) { File [ ] files = mRootDirectory . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { file . delete ( ) ; } } mEntries . clear ( ) ; mTotalSize = 0 ; }
Clears the cache . Deletes all cached files from disk .
12,629
public synchronized Entry get ( String key ) { CacheHeader entry = mEntries . get ( key ) ; if ( entry == null ) { return null ; } File file = getFileForKey ( key ) ; CountingInputStream cis = null ; try { cis = new CountingInputStream ( new BufferedInputStream ( new FileInputStream ( file ) ) ) ; CacheHeader . readHeader ( cis ) ; byte [ ] data = streamToBytes ( cis , ( int ) ( file . length ( ) - cis . bytesRead ) ) ; return entry . toCacheEntry ( data ) ; } catch ( IOException e ) { JusLog . log ( file . getAbsolutePath ( ) + ": " + e . toString ( ) ) ; remove ( key ) ; return null ; } catch ( NegativeArraySizeException e ) { JusLog . log ( file . getAbsolutePath ( ) + ": " + e . toString ( ) ) ; remove ( key ) ; return null ; } finally { if ( cis != null ) { try { cis . close ( ) ; } catch ( IOException ioe ) { return null ; } } } }
Returns the cache entry with the specified key if it exists null otherwise .
12,630
public synchronized void initialize ( ) { if ( ! mRootDirectory . exists ( ) ) { if ( ! mRootDirectory . mkdirs ( ) ) { throw new IllegalStateException ( "Unable to create cache dir: " + mRootDirectory . getAbsolutePath ( ) ) ; } return ; } File [ ] files = mRootDirectory . listFiles ( ) ; if ( files == null ) { return ; } for ( File file : files ) { BufferedInputStream fis = null ; try { fis = new BufferedInputStream ( new FileInputStream ( file ) ) ; CacheHeader entry = CacheHeader . readHeader ( fis ) ; entry . size = file . length ( ) ; putEntry ( entry . key , entry ) ; } catch ( IOException e ) { if ( file != null ) { file . delete ( ) ; } } finally { try { if ( fis != null ) { fis . close ( ) ; } } catch ( IOException ignored ) { } } } }
Initializes the DiskBasedCache by scanning for all files currently in the specified root directory . Creates the root directory if necessary .
12,631
public MultipartBuilder addPart ( NetworkRequest part ) { if ( part == null ) { throw new NullPointerException ( "part == null" ) ; } parts . add ( part ) ; return this ; }
Add a part to the body .
12,632
public NetworkRequest build ( ) { if ( parts . isEmpty ( ) ) { throw new IllegalStateException ( "Multipart body must have at least one part." ) ; } MultipartRequest mrb = new MultipartRequest ( type , boundary , parts ) ; Buffer bb = new Buffer ( ) ; try { mrb . writeOrCountBytes ( bb , false ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return new NetworkRequest . Builder ( ) . setContentType ( mrb . contentType ( ) ) . setBody ( bb . readByteArray ( ) ) . build ( ) ; }
Assemble the specified parts into a request body .
12,633
protected void addNamespaceContext ( ) { NamespaceMap prefixmap = new NamespaceMap ( ) ; NamespacePrefixList npl = getXsd ( ) . getNamespaceContext ( ) ; if ( npl == null ) { prefixmap . add ( "" , XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; } else { for ( int i = 0 ; i < npl . getDeclaredPrefixes ( ) . length ; i ++ ) { prefixmap . add ( npl . getDeclaredPrefixes ( ) [ i ] , npl . getNamespaceURI ( npl . getDeclaredPrefixes ( ) [ i ] ) ) ; } } prefixmap . add ( getCOXBNamespacePrefix ( ) , getCOXBNamespace ( ) ) ; getXsd ( ) . setNamespaceContext ( prefixmap ) ; }
Adds the COXB namespace and associated prefixes to the XML schema .
12,634
public static String getErrorMessage ( final Logger log , final BaseRecognizer recognizer , final RecognitionException e , final String superMessage , final String [ ] tokenNames ) { if ( log . isDebugEnabled ( ) ) { List < ? > stack = BaseRecognizer . getRuleInvocationStack ( e , recognizer . getClass ( ) . getSuperclass ( ) . getName ( ) ) ; String debugMsg = recognizer . getErrorHeader ( e ) + " " + e . getClass ( ) . getSimpleName ( ) + ": " + superMessage + ":" ; if ( e instanceof NoViableAltException ) { NoViableAltException nvae = ( NoViableAltException ) e ; debugMsg += " (decision=" + nvae . decisionNumber + " state=" + nvae . stateNumber + ")" + " decision=<<" + nvae . grammarDecisionDescription + ">>" ; } else if ( e instanceof UnwantedTokenException ) { UnwantedTokenException ute = ( UnwantedTokenException ) e ; debugMsg += " (unexpected token=" + toString ( ute . getUnexpectedToken ( ) , tokenNames ) + ")" ; } else if ( e instanceof EarlyExitException ) { EarlyExitException eea = ( EarlyExitException ) e ; debugMsg += " (decision=" + eea . decisionNumber + ")" ; } debugMsg += " ruleStack=" + stack . toString ( ) ; log . debug ( debugMsg ) ; } return makeUserMsg ( e , superMessage ) ; }
Format an error message as expected by ANTLR . It is basically the same error message that ANTL BaseRecognizer generates with some additional data . Also used to log debugging information .
12,635
public static String makeUserMsg ( final RecognitionException e , final String msg ) { if ( e instanceof NoViableAltException ) { return msg . replace ( "no viable alternative at" , "unrecognized" ) ; } else if ( e instanceof UnwantedTokenException ) { return msg . replace ( "extraneous input" , "unexpected token" ) ; } else if ( e instanceof MismatchedTokenException ) { if ( msg . contains ( "mismatched input '<EOF>'" ) ) { return msg . replace ( "mismatched input '<EOF>' expecting" , "reached end of file looking for" ) ; } else { return msg . replace ( "mismatched input" , "unexpected token" ) ; } } else if ( e instanceof EarlyExitException ) { return msg . replace ( "required (...)+ loop did not match anything" , "required tokens not found" ) ; } else if ( e instanceof FailedPredicateException ) { if ( msg . contains ( "picture_string failed predicate: {Unbalanced parentheses}" ) ) { return "Unbalanced parentheses in picture string" ; } if ( msg . contains ( "PICTURE_PART failed predicate: {Contains invalid picture symbols}" ) ) { return "Picture string contains invalid symbols" ; } if ( msg . contains ( "PICTURE_PART failed predicate: {Syntax error in last picture clause}" ) ) { return "Syntax error in last picture clause" ; } if ( msg . contains ( "DATA_NAME failed predicate: {Syntax error in last clause}" ) ) { return "Syntax error in last COBOL clause" ; } } return msg ; }
Simplify error message text for end users .
12,636
protected void initIndexPersistableListener ( ) { _index . setPersistableListener ( new PersistableListener ( ) { public void beforePersist ( ) { try { PersistableListener l = _listener ; if ( l != null ) l . beforePersist ( ) ; } catch ( Exception e ) { _logger . error ( "failed on calling beforePersist" , e ) ; } try { _bytesDB . persist ( ) ; } catch ( Exception e ) { _logger . error ( "failed on calling beforePersist" , e ) ; } } public void afterPersist ( ) { try { PersistableListener l = _listener ; if ( l != null ) l . afterPersist ( ) ; } catch ( Exception e ) { _logger . error ( "failed on calling afterPersist" , e ) ; } } } ) ; }
Initialize the Index persistable listener .
12,637
public void populate ( ) throws Exception { for ( int i = 0 , cnt = _partition . getIdCount ( ) ; i < cnt ; i ++ ) { int memberId = _partition . getIdStart ( ) + i ; _partition . set ( memberId , createDataForMember ( memberId ) , System . nanoTime ( ) ) ; } _partition . sync ( ) ; }
Populates the underlying data partition .
12,638
public void doRandomReads ( int readCnt ) { Random rand = new Random ( ) ; int idStart = _partition . getIdStart ( ) ; int idCount = _partition . getIdCount ( ) ; for ( int i = 0 ; i < readCnt ; i ++ ) { int memberId = idStart + rand . nextInt ( idCount ) ; System . out . printf ( "MemberId=%-10d MemberData=%s%n" , memberId , new String ( _partition . get ( memberId ) ) ) ; } }
Perform a number of random reads from the underlying data partition .
12,639
public static void main ( String [ ] args ) { try { File homeDir = new File ( args [ 0 ] ) ; int idStart = Integer . parseInt ( args [ 1 ] ) ; int idCount = Integer . parseInt ( args [ 2 ] ) ; KratiDataPartition p = new KratiDataPartition ( homeDir , idStart , idCount ) ; p . populate ( ) ; p . doRandomReads ( 10 ) ; p . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
java - Xmx4G krati . examples . KratiDataPartition homeDir idStart idCount
12,640
public synchronized Clock updateHWMark ( String source , long hwm ) { _sourceWaterMarks . saveHWMark ( source , hwm ) ; return current ( ) ; }
Save the high water mark of a given source .
12,641
public static PDQConsumerAuditor getAuditor ( ) { AuditorModuleContext ctx = AuditorModuleContext . getContext ( ) ; return ( PDQConsumerAuditor ) ctx . getAuditor ( PDQConsumerAuditor . class ) ; }
Get an instance of the PDQ Consumer Auditor from the global context
12,642
public void auditPDQQueryEvent ( RFC3881EventOutcomeCodes eventOutcome , String pixManagerUri , String receivingFacility , String receivingApp , String sendingFacility , String sendingApp , String hl7MessageControlId , String hl7QueryParameters , String [ ] patientIds ) { if ( ! isAuditorEnabled ( ) ) { return ; } auditQueryEvent ( true , new IHETransactionEventTypeCodes . PatientDemographicsQuery ( ) , eventOutcome , sendingFacility , sendingApp , getSystemAltUserId ( ) , getSystemNetworkId ( ) , receivingFacility , receivingApp , null , EventUtils . getAddressForUrl ( pixManagerUri , false ) , getHumanRequestor ( ) , hl7MessageControlId , hl7QueryParameters , patientIds , null , null ) ; }
Audits an ITI - 21 Patient Demographics Query event for Patient Demographics Consumer actors .
12,643
public String formatKey ( URI uri ) throws URISyntaxException { if ( uri == null ) { throw new URISyntaxException ( "" , "URI specified is null" ) ; } return formatKey ( uri . getHost ( ) , uri . getPort ( ) ) ; }
Converts a well - formed URI containing a hostname and port into string which allows for lookups in the Security Domain table
12,644
protected void submitSegmentIndexBuffer ( ) { if ( _sibEnabled && ! _sib . isDirty ( ) ) { _sib . setSegmentId ( _segment . getSegmentId ( ) ) ; _sib . setSegmentLastForcedTime ( _segment . getLastForcedTime ( ) ) ; _segmentManager . submit ( _sib ) ; } else { _segmentManager . remove ( _sib ) ; } }
Submit current segment index buffer for asynchronous handling .
12,645
protected void init ( ) { try { _segment = _segmentManager . nextSegment ( ) ; _sib = _segmentManager . openSegmentIndexBuffer ( _segment . getSegmentId ( ) ) ; if ( ! _sibEnabled ) _sib . markAsDirty ( ) ; _log . info ( "Segment " + _segment . getSegmentId ( ) + " online: " + _segment . getStatus ( ) ) ; } catch ( IOException ioe ) { _log . error ( ioe . getMessage ( ) , ioe ) ; throw new SegmentException ( "Instantiation failed due to " + ioe . getMessage ( ) ) ; } }
Initialize this SimpleDataArray after it is instantiated .
12,646
protected void decrOriginalSegmentLoad ( int index ) { try { long address = getAddress ( index ) ; int segPos = _addressFormat . getOffset ( address ) ; int segInd = _addressFormat . getSegment ( address ) ; int length = _addressFormat . getDataSize ( address ) ; if ( segPos >= Segment . dataStartPosition ) { Segment seg = _segmentManager . getSegment ( segInd ) ; if ( seg != null ) seg . decrLoadSize ( 4 + ( ( length == 0 ) ? seg . readInt ( segPos ) : length ) ) ; } } catch ( IOException e1 ) { } catch ( IndexOutOfBoundsException e2 ) { } }
Decrease the load factor of a Segment based on the specified array index .
12,647
public byte [ ] get ( int index ) { rangeCheck ( index ) ; try { long address = getAddress ( index ) ; int segPos = _addressFormat . getOffset ( address ) ; int segInd = _addressFormat . getSegment ( address ) ; if ( segPos < Segment . dataStartPosition ) return null ; Segment seg = _segmentManager . getSegment ( segInd ) ; if ( seg == null ) return null ; int size = _addressFormat . getDataSize ( address ) ; int len = ( size == 0 ) ? seg . readInt ( segPos ) : size ; byte [ ] data = new byte [ len ] ; if ( len > 0 ) { seg . read ( segPos + 4 , data ) ; } return data ; } catch ( Exception e ) { _log . warn ( e . getMessage ( ) ) ; return null ; } }
Gets data at a given index .
12,648
public int read ( int index , byte [ ] dst ) { rangeCheck ( index ) ; try { long address = getAddress ( index ) ; int segPos = _addressFormat . getOffset ( address ) ; int segInd = _addressFormat . getSegment ( address ) ; if ( segPos < Segment . dataStartPosition ) return - 1 ; Segment seg = _segmentManager . getSegment ( segInd ) ; if ( seg == null ) return - 1 ; int size = _addressFormat . getDataSize ( address ) ; int len = ( size == 0 ) ? seg . readInt ( segPos ) : size ; if ( len > 0 ) { len = Math . min ( len , dst . length ) ; seg . read ( segPos + 4 , dst , 0 , len ) ; } return len ; } catch ( Exception e ) { _log . warn ( e . getMessage ( ) ) ; return - 1 ; } }
Reads data bytes at an index into a byte array .
12,649
public int transferTo ( int index , WritableByteChannel channel ) { rangeCheck ( index ) ; try { long address = getAddress ( index ) ; int segPos = _addressFormat . getOffset ( address ) ; int segInd = _addressFormat . getSegment ( address ) ; if ( segPos < Segment . dataStartPosition ) return - 1 ; Segment seg = _segmentManager . getSegment ( segInd ) ; if ( seg == null ) return - 1 ; int size = _addressFormat . getDataSize ( address ) ; int len = ( size == 0 ) ? seg . readInt ( segPos ) : size ; if ( len > 0 ) { seg . transferTo ( segPos + 4 , len , channel ) ; } return len ; } catch ( Exception e ) { return - 1 ; } }
Transfers data at a given index to a writable channel .
12,650
public synchronized void clear ( ) { if ( isOpen ( ) ) { _compactor . clear ( ) ; _addressArray . clear ( ) ; _segmentManager . clear ( ) ; this . init ( ) ; } }
Clears all data stored in this SimpleDataArray . This method is not effective if this SimpleDataArray is not open .
12,651
public synchronized void close ( ) throws IOException { if ( _mode == Mode . CLOSED ) { return ; } _mode = Mode . CLOSED ; try { _compactor . shutdown ( ) ; syncInternal ( ) ; submitSegmentIndexBuffer ( ) ; _compactor . clear ( ) ; _addressArray . close ( ) ; _segmentManager . close ( ) ; } catch ( Exception e ) { _log . error ( "Failed to close" , e ) ; throw ( e instanceof IOException ) ? ( IOException ) e : new IOException ( e ) ; } finally { _mode = Mode . CLOSED ; _log . info ( "mode=" + _mode ) ; } }
Close to quit from serving requests .
12,652
public synchronized void open ( ) throws IOException { if ( _mode == Mode . OPEN ) { return ; } try { _addressArray . open ( ) ; _segmentManager . open ( ) ; _compactor . start ( ) ; init ( ) ; _mode = Mode . OPEN ; } catch ( Exception e ) { _mode = Mode . CLOSED ; _log . error ( "Failed to open" , e ) ; _compactor . shutdown ( ) ; _compactor . clear ( ) ; if ( _addressArray . isOpen ( ) ) { _addressArray . close ( ) ; } if ( _segmentManager . isOpen ( ) ) { _segmentManager . close ( ) ; } throw ( e instanceof IOException ) ? ( IOException ) e : new IOException ( e ) ; } finally { _log . info ( "mode=" + _mode ) ; } }
Open to start serving requests .
12,653
protected void fireBeforePersist ( ) { PersistableListener l = _listener ; if ( l != null ) { try { l . beforePersist ( ) ; } catch ( Exception e ) { _log . error ( "failure on calling beforePersist" , e ) ; } } }
Fire beforePersist events to the PersistableListener .
12,654
protected void fireAfterPersist ( ) { PersistableListener l = _listener ; if ( l != null ) { try { l . afterPersist ( ) ; } catch ( Exception e ) { _log . error ( "failure on calling afterPersist" , e ) ; } } }
Fire afterPersist events to the PersistableListener .
12,655
public String cleanFixedLine ( final String line ) { StringBuilder cleanedLine = new StringBuilder ( ) ; int length = line . length ( ) ; for ( int i = 0 ; i < _startColumn - 1 ; i ++ ) { cleanedLine . append ( " " ) ; } if ( length > _startColumn - 1 ) { String areaA = line . substring ( _startColumn - 1 , ( length > _endColumn ) ? _endColumn : length ) ; cleanedLine . append ( areaA ) ; } return cleanedLine . toString ( ) ; }
Clear sequence numbers in column 1 - 6 and anything beyond column 72 .
12,656
private void freeCompactedSegments ( ) { SegmentManager segManager = _dataArray . getSegmentManager ( ) ; if ( segManager == null ) return ; while ( ! _freeQueue . isEmpty ( ) ) { Segment seg = _freeQueue . remove ( ) ; try { segManager . freeSegment ( seg ) ; } catch ( Exception e ) { _log . error ( "failed to free Segment " + seg . getSegmentId ( ) + ": " + seg . getStatus ( ) , e ) ; } } }
Frees segments that were compacted successfully .
12,657
private boolean compact ( ) throws IOException { try { final boolean sibEnabled = _dataArray . isSibEnabled ( ) ; _segTarget = _dataArray . getSegmentManager ( ) . nextSegment ( ) ; for ( Segment seg : _segSourceList ) { if ( ! _enabled ) { try { _updateManager . endUpdate ( _segTarget ) ; } catch ( Exception e ) { _log . warn ( "compact abort" , e ) ; } _log . info ( "ignored Segment " + seg . getSegmentId ( ) ) ; continue ; } try { if ( compact ( seg , _segTarget , sibEnabled ) ) { _compactedQueue . add ( seg ) ; } } catch ( Exception e ) { if ( _dataArray . isOpen ( ) ) { _ignoredSegs . add ( seg ) ; _log . error ( "failed to compact Segment " + seg . getSegmentId ( ) , e ) ; } } } if ( sibEnabled && ! _dataArray . isSibEnabled ( ) ) { _dataArray . getSegmentManager ( ) . openSegmentIndexBuffer ( _segTarget . getSegmentId ( ) ) . markAsDirty ( ) ; } _targetQueue . add ( _segTarget ) ; _log . info ( "bytes transferred to " + _segTarget . getSegmentId ( ) + ": " + ( _segTarget . getAppendPosition ( ) - Segment . dataStartPosition ) ) ; } catch ( ConcurrentModificationException e1 ) { _segSourceList . clear ( ) ; return false ; } catch ( Exception e2 ) { _log . warn ( e2 . getMessage ( ) , e2 ) ; return false ; } _log . info ( "compact done" ) ; return true ; }
Compacts a number of source fragmented Segments by moving data into a new target Segment .
12,658
private boolean compact ( Segment segment , SegmentIndexBuffer sibSource , Segment segTarget ) throws IOException { Segment segSource = segment ; int segSourceId = segSource . getSegmentId ( ) ; int segTargetId = segTarget . getSegmentId ( ) ; Chronos c = new Chronos ( ) ; if ( ! segment . canReadFromBuffer ( ) && segment . getLoadFactor ( ) > 0.1 ) { segSource = new BufferedSegment ( segment , getByteBuffer ( ( int ) segment . getInitialSize ( ) ) ) ; _log . info ( "buffering: " + c . tick ( ) + " ms" ) ; } SegmentIndexBuffer sibTarget = _dataArray . getSegmentManager ( ) . openSegmentIndexBuffer ( segTargetId ) ; long sizeLimit = segTarget . getInitialSize ( ) ; long bytesTransferred = 0 ; boolean succ = true ; try { AddressFormat addrFormat = _dataArray . _addressFormat ; SegmentIndexBuffer . IndexOffset reuse = new SegmentIndexBuffer . IndexOffset ( ) ; for ( int i = 0 , cnt = sibSource . size ( ) ; i < cnt ; i ++ ) { sibSource . get ( i , reuse ) ; int index = reuse . getIndex ( ) ; int sibSegPos = reuse . getOffset ( ) ; long oldAddress = _dataArray . getAddress ( index ) ; int oldSegPos = addrFormat . getOffset ( oldAddress ) ; if ( sibSegPos != oldSegPos ) continue ; int oldSegInd = addrFormat . getSegment ( oldAddress ) ; int length = addrFormat . getDataSize ( oldAddress ) ; if ( oldSegInd == segSourceId && oldSegPos >= Segment . dataStartPosition ) { if ( length == 0 ) length = segSource . readInt ( oldSegPos ) ; int byteCnt = 4 + length ; long newSegPos = segTarget . getAppendPosition ( ) ; long newAddress = addrFormat . composeAddress ( ( int ) newSegPos , segTargetId , length ) ; if ( segTarget . getAppendPosition ( ) + byteCnt >= sizeLimit ) { succ = false ; break ; } segSource . transferTo ( oldSegPos , byteCnt , segTarget ) ; bytesTransferred += byteCnt ; sibTarget . add ( index , ( int ) newSegPos ) ; _updateManager . addUpdate ( index , byteCnt , newAddress , oldAddress , segTarget ) ; } } _updateManager . endUpdate ( segTarget ) ; _log . info ( "bytes fastscanned from " + segSource . getSegmentId ( ) + ": " + bytesTransferred + " time: " + c . tick ( ) + " ms" ) ; return succ ; } finally { if ( segSource . getClass ( ) == BufferedSegment . class ) { segSource . close ( false ) ; segSource = null ; } } }
Compacts data from the specified source Segment into the specified target Segment .
12,659
public void run ( ) { while ( _enabled ) { if ( _newCycle . compareAndSet ( true , false ) ) { _lock . lock ( ) ; try { reset ( ) ; _state = State . INIT ; _log . info ( "cycle init" ) ; flushSegmentIndexBuffers ( ) ; freeCompactedSegments ( ) ; if ( ! inspect ( ) ) continue ; if ( ! compact ( ) ) continue ; } catch ( Exception e ) { _log . error ( "compaction failure" , e ) ; } finally { reset ( ) ; _state = State . DONE ; _log . info ( "cycle done" ) ; _lock . unlock ( ) ; } } else { try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { _log . warn ( e . getMessage ( ) ) ; } } } }
Compacting Segments .
12,660
protected ByteBuffer getByteBuffer ( int bufferLength ) { if ( _buffer == null ) { _buffer = ByteBuffer . wrap ( new byte [ bufferLength ] ) ; _log . info ( "ByteBuffer allocated for buffering" ) ; } return _buffer ; }
Gets the buffer for speeding up compaction .
12,661
private void toStringRenames ( final StringBuilder sb ) { if ( getRenamesSubject ( ) != null ) { sb . append ( ',' ) ; sb . append ( "renamesSubject:" + getRenamesSubject ( ) ) ; } if ( getRenamesSubjectRange ( ) != null ) { sb . append ( ',' ) ; sb . append ( "renamesSubjectRange:" + getRenamesSubjectRange ( ) ) ; } }
Pretty printing for a renames entry .
12,662
private void toStringCondition ( final StringBuilder sb ) { if ( getConditionLiterals ( ) . size ( ) > 0 ) { toStringList ( sb , getConditionLiterals ( ) , "conditionLiterals" ) ; } if ( getConditionRanges ( ) . size ( ) > 0 ) { toStringList ( sb , getConditionRanges ( ) , "conditionRanges" ) ; } }
Pretty printing for a condition entry .
12,663
private void toStringList ( final StringBuilder sb , final List < ? > list , final String title ) { sb . append ( ',' ) ; sb . append ( title + ":[" ) ; boolean first = true ; for ( Object child : list ) { if ( ! first ) { sb . append ( "," ) ; } else { first = false ; } sb . append ( child . toString ( ) ) ; } sb . append ( "]" ) ; }
Adds list elements to a string builder .
12,664
public void reinitValue ( DataReader in , EntryValueInt value ) throws IOException { value . reinit ( in . readInt ( ) , in . readInt ( ) , in . readLong ( ) ) ; }
Read data from stream to populate an EntryValueInt .
12,665
private static void initializeDefaultModules ( SecurityContext context ) { if ( context . isInitialized ( ) ) { return ; } if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "SecurityContext default module initializer starting" ) ; } String moduleName ; for ( int i = 0 ; i < DEFAULT_MODULES . length ; i ++ ) { moduleName = DEFAULT_MODULES [ i ] ; try { LOGGER . debug ( moduleName + MODULE_INITIALIZER_CLASS ) ; Class < ? > clazz = Class . forName ( moduleName + MODULE_INITIALIZER_CLASS ) ; Method method = clazz . getMethod ( MODULE_INITIALIZER_METHOD , ( Class [ ] ) null ) ; Object invokeResult = method . invoke ( clazz . newInstance ( ) , ( Object [ ] ) null ) ; if ( invokeResult instanceof AbstractModuleContext ) { context . registerModuleContext ( moduleName , ( AbstractModuleContext ) invokeResult ) ; } else { throw new IllegalArgumentException ( "Initializer method did not return correct type" ) ; } if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "SecurityContext module " + moduleName + " initialized" ) ; } } catch ( ClassNotFoundException cnfe ) { LOGGER . warn ( "SecurityContext module " + moduleName + " not found, skipping." ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Stack trace: " , cnfe ) ; } } catch ( NoSuchMethodException nsme ) { LOGGER . warn ( "SecurityContext module " + moduleName + " does not support default initialization, skipping." , nsme ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Stack trace: " , nsme ) ; } } catch ( Throwable t ) { LOGGER . error ( "Error initializing SecurityContext module " + moduleName , t ) ; } finally { } } if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "SecurityContext default module initializer ending" ) ; } }
Initialize and register the contexts for modules that by default are initialized with the security context
12,666
public void setAuditSourceId ( String sourceId , String enterpriseSiteId ) { setAuditSourceId ( sourceId , enterpriseSiteId , ( RFC3881AuditSourceTypes [ ] ) null ) ; }
Sets a Audit Source Identification block for a given Audit Source ID and Audit Source Enterprise Site ID
12,667
public void setAuditSourceId ( String sourceId , String enterpriseSiteId , RFC3881AuditSourceTypes [ ] typeCodes ) { addAuditSourceIdentification ( sourceId , enterpriseSiteId , typeCodes ) ; }
Sets a Audit Source Identification block for a given Audit Source ID Audit Source Enterprise Site ID and a list of audit source type codes
12,668
public void setRetention ( long duration , TimeUnit timeUnit ) { this . _duration = Math . max ( 1 , duration ) ; this . _timeUnit = timeUnit ; long millis = TimeUnit . MILLISECONDS == timeUnit ? _duration : TimeUnit . MILLISECONDS . convert ( _duration , timeUnit ) ; _timeMillis = Math . max ( millis , MIN_DURATION_MILLIS ) ; }
Sets the retention duration period of this policy .
12,669
private void expand ( int i ) { if ( count + i <= buf . length ) { return ; } byte [ ] newbuf = mPool . getBuf ( ( count + i ) * 2 ) ; System . arraycopy ( buf , 0 , newbuf , 0 , count ) ; mPool . returnBuf ( buf ) ; buf = newbuf ; }
Ensures there is enough space in the buffer for the given number of additional bytes .
12,670
protected void checkCobolSourceFile ( final File cobolSourceFile ) throws IOException { if ( cobolSourceFile == null ) { throw new IOException ( "You must provide a COBOL source file" ) ; } if ( ! cobolSourceFile . exists ( ) ) { throw new IOException ( "COBOL source file " + cobolSourceFile + " not found" ) ; } }
make sure the COBOL file is valid .
12,671
protected void checkTarget ( final File target ) throws IOException { if ( target == null ) { throw new IOException ( "You must provide a target directory or file" ) ; } if ( ! target . exists ( ) ) { String extension = FilenameUtils . getExtension ( target . getName ( ) ) ; if ( extension . length ( ) == 0 ) { throw new IOException ( "Target folder " + target + " not found" ) ; } } }
make sure the target folder or file is valid . We consider that target files will have extensions . Its ok for a target file not to exist but target folders must exist .
12,672
protected String getUniqueTargetNamespace ( String targetNamespacePrefix , final String baseName ) throws IOException { if ( targetNamespacePrefix == null || targetNamespacePrefix . length ( ) == 0 ) { return null ; } if ( baseName == null || baseName . length ( ) == 0 ) { throw new IOException ( "No target basename was provided" ) ; } if ( targetNamespacePrefix . charAt ( targetNamespacePrefix . length ( ) - 1 ) == '/' ) { return targetNamespacePrefix + baseName ; } else { return targetNamespacePrefix + '/' + baseName ; } }
TargetNamespace if it is not null is completed with the baseName .
12,673
protected void auditQueryEvent ( boolean systemIsSource , IHETransactionEventTypeCodes transaction , RFC3881EventOutcomeCodes eventOutcome , String sourceFacility , String sourceApp , String sourceAltUserId , String sourceNetworkId , String destinationFacility , String destinationApp , String destinationAltUserId , String destinationNetworkId , String humanRequestor , String hl7MessageId , String hl7QueryParameters , String [ ] patientIds , List < CodedValueType > purposesOfUse , List < CodedValueType > userRoles ) { QueryEvent queryEvent = new QueryEvent ( systemIsSource , eventOutcome , transaction , purposesOfUse ) ; queryEvent . setAuditSourceId ( getAuditSourceId ( ) , getAuditEnterpriseSiteId ( ) ) ; queryEvent . addSourceActiveParticipant ( EventUtils . concatHL7FacilityApplication ( sourceFacility , sourceApp ) , sourceAltUserId , null , sourceNetworkId , true ) ; if ( ! EventUtils . isEmptyOrNull ( humanRequestor ) ) { queryEvent . addHumanRequestorActiveParticipant ( humanRequestor , null , null , userRoles ) ; } queryEvent . addDestinationActiveParticipant ( EventUtils . concatHL7FacilityApplication ( destinationFacility , destinationApp ) , destinationAltUserId , null , destinationNetworkId , false ) ; if ( ! EventUtils . isEmptyOrNull ( patientIds ) ) { for ( int i = 0 ; i < patientIds . length ; i ++ ) { queryEvent . addPatientParticipantObject ( patientIds [ i ] ) ; } } byte [ ] queryParamsBytes = null , msgControlBytes = null ; if ( hl7QueryParameters != null ) { queryParamsBytes = hl7QueryParameters . getBytes ( ) ; } if ( hl7MessageId != null ) { msgControlBytes = hl7MessageId . getBytes ( ) ; } queryEvent . addQueryParticipantObject ( null , null , queryParamsBytes , msgControlBytes , transaction ) ; audit ( queryEvent ) ; }
Audit a QUERY event for PIX and PDQ transactions . Useful for PIX Query PDQ Query and PDVQ Query in the PIX Manager as well as the PIX and PDQ Consumer
12,674
public static AuditorModuleContext getContext ( ) { SecurityContext securityContext = SecurityContextFactory . getSecurityContext ( ) ; if ( ! securityContext . isInitialized ( ) ) { securityContext . initialize ( ) ; } AbstractModuleContext moduleContext = securityContext . getModuleContext ( CONTEXT_ID ) ; if ( null == moduleContext || ! ( moduleContext instanceof AuditorModuleContext ) ) { moduleContext = ContextInitializer . defaultInitialize ( ) ; securityContext . registerModuleContext ( CONTEXT_ID , moduleContext ) ; } return ( AuditorModuleContext ) moduleContext ; }
Returns the current singleton instance of the Auditor Module Context from the ThreadLocal cache . If the ThreadLocal cache has not been initialized or does not contain this context then create and initialize module context register in the ThreadLocal and return the new instance .
12,675
public AuditMessageSender getSender ( ) { if ( customSender == null ) { String transport = AuditorModuleContext . getContext ( ) . getConfig ( ) . getAuditRepositoryTransport ( ) ; if ( transport . equalsIgnoreCase ( "TLS" ) ) { return new TLSSyslogSenderImpl ( ) ; } else if ( transport . equalsIgnoreCase ( "UDP" ) ) { return new UDPSyslogSenderImpl ( ) ; } else { return new BSDSyslogSenderImpl ( ) ; } } else return customSender ; }
Gets the transport - specific sending instance used to deliver audit messages to their destination
12,676
public IHEAuditor getAuditor ( String className , boolean useContextAuditorRegistry ) { return getAuditor ( AuditorFactory . getAuditorClassForClassName ( className ) , useContextAuditorRegistry ) ; }
Get an IHE Auditor instance from a fully - qualified class name
12,677
public static XDSRegistryAuditor getAuditor ( ) { AuditorModuleContext ctx = AuditorModuleContext . getContext ( ) ; return ( XDSRegistryAuditor ) ctx . getAuditor ( XDSRegistryAuditor . class ) ; }
Get an instance of the XDS Document Registry Auditor from the global context
12,678
public void auditRegistryQueryEvent ( RFC3881EventOutcomeCodes eventOutcome , String consumerUserId , String consumerUserName , String consumerIpAddress , String registryEndpointUri , String adhocQueryRequestPayload , String patientId ) { if ( ! isAuditorEnabled ( ) ) { return ; } auditQueryEvent ( false , new IHETransactionEventTypeCodes . RegistrySQLQuery ( ) , eventOutcome , getAuditSourceId ( ) , getAuditEnterpriseSiteId ( ) , consumerUserId , null , consumerUserName , consumerIpAddress , consumerUserName , consumerUserName , true , registryEndpointUri , getSystemAltUserId ( ) , "" , adhocQueryRequestPayload , "" , patientId , null , null ) ; }
Audits an ITI - 16 Registry SQL Query event for XDS . a Document Registry actors .
12,679
public void auditRegistryStoredQueryEvent ( RFC3881EventOutcomeCodes eventOutcome , String consumerUserId , String consumerUserName , String consumerIpAddress , String registryEndpointUri , String storedQueryUUID , String adhocQueryRequestPayload , String homeCommunityId , String patientId , List < CodedValueType > purposesOfUse , List < CodedValueType > userRoles ) { if ( ! isAuditorEnabled ( ) ) { return ; } auditQueryEvent ( false , new IHETransactionEventTypeCodes . RegistryStoredQuery ( ) , eventOutcome , getAuditSourceId ( ) , getAuditEnterpriseSiteId ( ) , consumerUserId , null , consumerUserName , consumerIpAddress , consumerUserName , consumerUserName , false , registryEndpointUri , getSystemAltUserId ( ) , storedQueryUUID , adhocQueryRequestPayload , homeCommunityId , patientId , purposesOfUse , userRoles ) ; }
Audits an ITI - 18 Registry Stored Query event for XDS . a and XDS . b Document Registry actors .
12,680
protected void auditRegisterEvent ( IHETransactionEventTypeCodes transaction , RFC3881EventOutcomeCodes eventOutcome , String repositoryUserId , String repositoryIpAddress , String userName , String registryEndpointUri , String submissionSetUniqueId , String patientId , List < CodedValueType > purposesOfUse , List < CodedValueType > userRoles ) { ImportEvent importEvent = new ImportEvent ( false , eventOutcome , transaction , purposesOfUse ) ; importEvent . setAuditSourceId ( getAuditSourceId ( ) , getAuditEnterpriseSiteId ( ) ) ; importEvent . addSourceActiveParticipant ( repositoryUserId , null , null , repositoryIpAddress , true ) ; if ( ! EventUtils . isEmptyOrNull ( userName ) ) { importEvent . addHumanRequestorActiveParticipant ( userName , null , userName , userRoles ) ; } importEvent . addDestinationActiveParticipant ( registryEndpointUri , getSystemAltUserId ( ) , null , EventUtils . getAddressForUrl ( registryEndpointUri , false ) , false ) ; if ( ! EventUtils . isEmptyOrNull ( patientId ) ) { importEvent . addPatientParticipantObject ( patientId ) ; } importEvent . addSubmissionSetParticipantObject ( submissionSetUniqueId ) ; audit ( importEvent ) ; }
Generically sends audit messages for XDS Document Registry Register Document Set events
12,681
private void fixKeyManagers ( ) { if ( null == keyManagerFactory || null == keyManagerFactory . getKeyManagers ( ) ) { return ; } KeyManager [ ] defaultKeyManagers = keyManagerFactory . getKeyManagers ( ) ; KeyManager [ ] newKeyManagers = new KeyManager [ defaultKeyManagers . length ] ; KeyManager mgr = null ; for ( int i = 0 ; i < defaultKeyManagers . length ; i ++ ) { mgr = defaultKeyManagers [ i ] ; if ( mgr instanceof X509KeyManager ) { mgr = new AliasSensitiveX509KeyManager ( this , ( X509KeyManager ) mgr ) ; } newKeyManagers [ i ] = mgr ; } keyManagers = newKeyManagers ; }
If a keystore alias is defined then override the key manager assigned to with an alias - sensitive wrapper that selects the proper key from your assigned key alias .
12,682
public void init ( FilterConfig filterConfig ) throws ServletException { super . init ( filterConfig ) ; int reloadTime = readInt ( filterConfig . getInitParameter ( INIT_PARAM_RELOAD_TIME ) , 0 ) ; this . resetTime = readInt ( filterConfig . getInitParameter ( INIT_PARAM_RESET_TIME ) , resetTime ) ; this . cacheKeyFormat = readString ( filterConfig . getInitParameter ( INIT_PARAM_CAHE_KEY_FORMAT ) , DEFAULT_CACHE_KEY_FORMAT ) ; lastResetTime = new Date ( ) . getTime ( ) ; CacheConfig < String , CachedResponse > cacheConfig = new CacheConfig < > ( ) ; String providerValue = readString ( filterConfig . getInitParameter ( INIT_PARAM_CACHE_PROVIDER ) , null ) ; if ( providerValue != null ) cacheConfig . setProvider ( CacheConfig . CacheProvider . valueOf ( providerValue . toUpperCase ( ) ) ) ; String cacheHost = filterConfig . getInitParameter ( INIT_PARAM_CACHE_HOST ) ; cacheConfig . setHostname ( cacheHost ) ; int cachePort = readInt ( filterConfig . getInitParameter ( INIT_PARAM_CACHE_PORT ) , 0 ) ; cacheConfig . setPortNumber ( cachePort ) ; if ( ! CacheFactory . isCacheProvider ( cache , cacheConfig . getProvider ( ) ) ) { try { cache = CacheFactory . getCache ( cacheConfig ) ; } catch ( Exception ex ) { LOGGER . debug ( "Failed to initialize Cache Config: {}. Falling back to default Cache Service." , cacheConfig ) ; cache = CacheFactory . < String , CachedResponse > getDefaultCache ( ) ; } } LOGGER . debug ( "Cache Filter initialized with: " + "{}:{},\n" + "{}:{},\n" + "{}:{},\n" + "{}:{},\n" + "{}:{}" , INIT_PARAM_CACHE_PROVIDER , providerValue , INIT_PARAM_CACHE_HOST , cacheHost , INIT_PARAM_CACHE_PORT , String . valueOf ( cachePort ) , INIT_PARAM_RELOAD_TIME , String . valueOf ( reloadTime ) , INIT_PARAM_RESET_TIME , String . valueOf ( resetTime ) ) ; }
eg . queryString header = X - Requested - By parameter = username . URI is always part of key
12,683
protected String generateCacheKeyForTheRequest ( HttpServletRequest request ) { StringBuilder cacheKey = new StringBuilder ( ) ; cacheKey . append ( request . getRequestURI ( ) ) ; String [ ] keyAttributes = this . cacheKeyFormat . split ( "," ) ; for ( String attr : keyAttributes ) { String keyAttr = attr . trim ( ) . toLowerCase ( ) ; if ( keyAttr . equalsIgnoreCase ( "queryString" ) && request . getQueryString ( ) != null ) { cacheKey . append ( "+" ) . append ( request . getQueryString ( ) ) ; } else if ( keyAttr . startsWith ( "header=" ) ) { cacheKey . append ( "+" ) . append ( request . getHeader ( keyAttr . substring ( 7 ) . trim ( ) ) ) ; } else if ( keyAttr . startsWith ( "parameter=" ) ) { cacheKey . append ( "+" ) . append ( request . getHeader ( keyAttr . substring ( 9 ) . trim ( ) ) ) ; } } return cacheKey . toString ( ) ; }
Generate the cache key for the specific request by using the cacheKeyFormat init param You can specify comma separated list of attributes that you want to use to build the cache key . URI is by default part of the cache key . Using cacheKeyFormat params you can optionally include following details . - queryString - specific header value - specific request parameter value
12,684
protected void init ( ) throws IOException { try { long lwmScn = _arrayFile . getLwmScn ( ) ; long hwmScn = _arrayFile . getHwmScn ( ) ; if ( hwmScn < lwmScn ) { throw new IOException ( _arrayFile . getAbsolutePath ( ) + " is corrupted: lwmScn=" + lwmScn + " hwmScn=" + hwmScn ) ; } _entryManager . init ( lwmScn , hwmScn ) ; loadArrayFileData ( ) ; } catch ( IOException e ) { _entryManager . clear ( ) ; getLogger ( ) . error ( e . getMessage ( ) , e ) ; throw e ; } }
Loads data from the array file .
12,685
private String chooseClientAliasForKey ( String preferredAlias , String keyType , Principal [ ] issuers , Socket socket ) { String [ ] aliases = getClientAliases ( keyType , issuers ) ; if ( aliases != null && aliases . length > 0 ) { for ( int i = 0 ; i < aliases . length ; i ++ ) { if ( preferredAlias . equals ( aliases [ i ] ) ) { return aliases [ i ] ; } } } return null ; }
Attempts to find a keystore
12,686
private static String simpleHashOf ( String resourceRealPath ) { if ( resourceRealPath == null ) return null ; File resource = new File ( resourceRealPath ) ; if ( ! resource . exists ( ) ) return null ; long lastModified = resource . lastModified ( ) ; long size = resource . length ( ) ; return String . format ( "%s#%s" , lastModified , size ) ; }
Calculates simple hash using file size and last modified time .
12,687
public static String getParentPath ( String path ) { if ( path == null ) return null ; path = path . trim ( ) ; if ( path . endsWith ( PATH_ROOT ) && path . length ( ) > 1 ) { path = path . substring ( 0 , path . length ( ) - 1 ) ; } int lastIndex = path . lastIndexOf ( PATH_ROOT ) ; if ( path . length ( ) > 1 && lastIndex > 0 ) { return path . substring ( 0 , lastIndex ) ; } return PATH_ROOT ; }
Fast get parent directory using substring
12,688
protected Socket createSocket ( String host , int port ) throws SocketException , UnknownHostException { Socket socket = null ; int retries = 0 ; Throwable cause = null ; while ( retries < CONTEXT . getConfig ( ) . getSocketRetries ( ) ) { try { socket = createSocketFromFactory ( SocketFactory . getDefault ( ) , host , port ) ; break ; } catch ( UnknownHostException e ) { logger . error ( "Unknown host. Unable to establish connection to " + host + " on port " + port + ". Reason: " + e . getLocalizedMessage ( ) , e ) ; throw e ; } catch ( SocketException e ) { logger . error ( "Error connecting to " + host + " on port " + port + ". Will retry in " + CONTEXT . getConfig ( ) . getSocketRetryWait ( ) / 1000 + " seconds. " + ( CONTEXT . getConfig ( ) . getSocketRetries ( ) - retries ) + " retries left. Cause: " + e . getLocalizedMessage ( ) , e ) ; cause = e ; retries ++ ; try { Thread . sleep ( CONTEXT . getConfig ( ) . getSocketRetryWait ( ) ) ; continue ; } catch ( InterruptedException ie ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Sleep awoken early" ) ; } continue ; } } catch ( IOException e ) { logger . error ( "Error connecting to " + host + " on port " + port + ". Will retry in " + CONTEXT . getConfig ( ) . getSocketRetryWait ( ) / 1000 + " seconds. " + ( CONTEXT . getConfig ( ) . getSocketRetries ( ) - retries ) + " retries left. Cause: " + e . getLocalizedMessage ( ) , e ) ; retries ++ ; cause = e ; continue ; } } if ( retries >= CONTEXT . getConfig ( ) . getSocketRetries ( ) ) { logger . error ( "Socket Connect Retries Exhausted." , cause ) ; throw new ConnectException ( "Socket Connect Retries Exhausted. " + ( cause != null ? "Cause was: " + cause . getLocalizedMessage ( ) : "" ) ) ; } return socket ; }
Create non - secure socket for a given URI .
12,689
protected Socket createSocketFromFactory ( SocketFactory factory , String host , int port ) throws IOException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Connecting to " + host + " on port " + port + " (timeout: " + CONTEXT . getConfig ( ) . getConnectTimeout ( ) + " ms) using factory " + factory . getClass ( ) . getName ( ) ) ; } SocketAddress address = new InetSocketAddress ( host , port ) ; Socket socket = factory . createSocket ( ) ; socket . connect ( address , CONTEXT . getConfig ( ) . getConnectTimeout ( ) ) ; socket . setSoTimeout ( CONTEXT . getConfig ( ) . getSocketTimeout ( ) ) ; socket . setKeepAlive ( true ) ; return socket ; }
Creates a new connected socket to a given host and port from a provided Socket Factory .
12,690
public boolean isLineOfCode ( final String line ) { if ( line . length ( ) < getIndicatorAreaPos ( ) + 1 ) { return false ; } if ( line . trim ( ) . length ( ) == 0 ) { return false ; } if ( isComment ( line ) ) { return false ; } String [ ] tokens = line . trim ( ) . split ( "[\\s\\.]+" ) ; if ( tokens . length == 1 && COMPILER_DIRECTIVES . contains ( tokens [ 0 ] . toUpperCase ( Locale . getDefault ( ) ) ) ) { return false ; } return true ; }
Make sure this is a line worth parsing . Ignore empty lines comments and compiler directives .
12,691
public String cleanLine ( final String line ) { String cleanedLine = extendedCleanLine ( line ) ; cleanedLine = ( "a" + cleanedLine ) . trim ( ) . substring ( 1 ) ; return cleanedLine ; }
Remove characters that should not be passed to the lexer .
12,692
protected boolean isArgument ( final String fragment ) { String s = fragment . trim ( ) ; if ( s . length ( ) > 0 ) { return s . charAt ( s . length ( ) - 1 ) != COBOL_DELIMITER ; } return false ; }
Examine characters before an assumed level . If these characters are not terminated by a COBOL delimiter then the level is actually an argument to a previous keyword not an actual level .
12,693
public static ImageListener getImageListener ( final ImageView view , final int defaultImageResId , final int errorImageResId ) { return new ImageListener ( ) { public void onError ( JusError error ) { if ( errorImageResId != 0 ) { view . setImageResource ( errorImageResId ) ; } } public void onResponse ( ImageContainer response , boolean isImmediate ) { if ( response . getBitmap ( ) != null ) { view . setImageBitmap ( response . getBitmap ( ) ) ; } else if ( defaultImageResId != 0 ) { view . setImageResource ( defaultImageResId ) ; } } } ; }
The default implementation of ImageListener which handles basic functionality of showing a default image until the network response is received at which point it will switch to either the actual image or the error image .
12,694
public ImageContainer get ( String requestUrl , final ImageListener listener , final Object tag ) { return get ( requestUrl , listener , 0 , 0 , tag ) ; }
Returns an ImageContainer for the requested URL .
12,695
protected void onGetImageSuccess ( String cacheKey , Bitmap response ) { imageCache . putBitmap ( cacheKey , response ) ; BatchedImageRequest request = inFlightRequests . remove ( cacheKey ) ; if ( request != null ) { request . mResponseBitmap = response ; batchResponse ( cacheKey , request ) ; } }
Handler for when an image was successfully loaded .
12,696
protected void onGetImageError ( String cacheKey , JusError error ) { BatchedImageRequest request = inFlightRequests . remove ( cacheKey ) ; if ( request != null ) { request . setError ( error ) ; batchResponse ( cacheKey , request ) ; } }
Handler for when an image failed to load .
12,697
private void batchResponse ( String cacheKey , BatchedImageRequest request ) { batchedResponses . put ( cacheKey , request ) ; if ( runnable == null ) { runnable = new Runnable ( ) { public void run ( ) { for ( BatchedImageRequest bir : batchedResponses . values ( ) ) { for ( ImageContainer container : bir . mContainers ) { if ( container . mListener == null ) { continue ; } if ( bir . getError ( ) == null ) { container . mBitmap = bir . mResponseBitmap ; container . mListener . onResponse ( container , false ) ; } else { container . mListener . onError ( bir . getError ( ) ) ; } } } batchedResponses . clear ( ) ; runnable = null ; } } ; handler . postDelayed ( runnable , batchResponseDelayMs ) ; } }
Starts the runnable for batched delivery of responses if it is not already started .
12,698
private static String getCacheKey ( String url , int maxWidth , int maxHeight , ScaleType scaleType ) { return "#W" + maxWidth + "#H" + maxHeight + "#S" + scaleType . ordinal ( ) + url ; }
Creates a cache key for use with the L1 cache .
12,699
public static XDSSourceAuditor getAuditor ( ) { AuditorModuleContext ctx = AuditorModuleContext . getContext ( ) ; return ( XDSSourceAuditor ) ctx . getAuditor ( XDSSourceAuditor . class ) ; }
Get an instance of the XDS Document Source Auditor from the global context