idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
22,600
public static List < HistoryEntry > getHistory ( String siteUri , int limit , boolean filter , String token ) throws URISyntaxException , IOException , ClientProtocolException , Exception { if ( ! siteUri . endsWith ( "/system/history" ) ) { siteUri += "/system/history" ; } List < HistoryEntry > history = null ; HttpClient httpClient = httpClient ( ) ; HttpGet get = null ; try { URIBuilder uriBuilder = new URIBuilder ( siteUri ) ; if ( limit > 0 ) { uriBuilder . addParameter ( "limit" , limit + "" ) ; } if ( filter ) { uriBuilder . addParameter ( "filter" , filter + "" ) ; } URI uri = uriBuilder . build ( ) ; get = new HttpGet ( uri ) ; addAuthHeader ( token , get ) ; HttpResponse resp = httpClient . execute ( get ) ; if ( resp . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { HttpEntity entity = resp . getEntity ( ) ; if ( entity . getContentType ( ) . getValue ( ) . equals ( "application/json" ) ) { String responseContent = EntityUtils . toString ( entity ) ; Gson gson = new GsonBuilder ( ) . registerTypeAdapter ( Date . class , new JsonDeserializer < Date > ( ) { @ Override public Date deserialize ( JsonElement json , Type typeOfT , JsonDeserializationContext ctx ) throws JsonParseException { return new Date ( json . getAsLong ( ) ) ; } } ) . create ( ) ; history = gson . fromJson ( responseContent , new TypeToken < List < HistoryEntry > > ( ) { } . getType ( ) ) ; } else { System . err . println ( "Invalid response content type [" + entity . getContentType ( ) . getValue ( ) + "]" ) ; System . exit ( 1 ) ; } } else { System . err . println ( "Request failed due to a [" + resp . getStatusLine ( ) . getStatusCode ( ) + ":" + resp . getStatusLine ( ) . getReasonPhrase ( ) + "] response from the remote server." ) ; System . exit ( 1 ) ; } } finally { if ( get != null ) { get . releaseConnection ( ) ; } } return history ; }
Retrieves the history of a Cadmium site .
533
12
22,601
private static void printComments ( String comment ) { int index = 0 ; int nextIndex = 154 ; while ( index < comment . length ( ) ) { nextIndex = nextIndex <= comment . length ( ) ? nextIndex : comment . length ( ) ; String commentSegment = comment . substring ( index , nextIndex ) ; int lastSpace = commentSegment . lastIndexOf ( ' ' ) ; int lastNewLine = commentSegment . indexOf ( ' ' ) ; char lastChar = ' ' ; if ( nextIndex < comment . length ( ) ) { lastChar = comment . charAt ( nextIndex ) ; } if ( lastNewLine > 0 ) { nextIndex = index + lastNewLine ; commentSegment = comment . substring ( index , nextIndex ) ; } else if ( Character . isWhitespace ( lastChar ) ) { } else if ( lastSpace > 0 ) { nextIndex = index + lastSpace ; commentSegment = comment . substring ( index , nextIndex ) ; } System . out . println ( " " + commentSegment ) ; index = nextIndex ; if ( lastNewLine > 0 || lastSpace > 0 ) { index ++ ; } nextIndex = index + 154 ; } }
Helper method to format comments to standard out .
262
9
22,602
private static String formatTimeLive ( long timeLive ) { String timeString = "ms" ; timeString = ( timeLive % 1000 ) + timeString ; timeLive = timeLive / 1000 ; if ( timeLive > 0 ) { timeString = ( timeLive % 60 ) + "s" + timeString ; timeLive = timeLive / 60 ; if ( timeLive > 0 ) { timeString = ( timeLive % 60 ) + "m" + timeString ; timeLive = timeLive / 60 ; if ( timeLive > 0 ) { timeString = ( timeLive % 24 ) + "h" + timeString ; timeLive = timeLive / 24 ; if ( timeLive > 0 ) { timeString = ( timeLive ) + "d" + timeString ; } } } } return timeString ; }
Helper method to format a timestamp .
172
7
22,603
@ Override public boolean isSecure ( HttpServletRequest request ) { String proto = request . getHeader ( X_FORWARED_PROTO ) ; if ( proto != null ) return proto . equalsIgnoreCase ( HTTPS_PROTOCOL ) ; return super . isSecure ( request ) ; }
When the X - Forwarded - Proto header is present this method returns true if the header equals https false otherwise . When the header is not present it delegates this call to the super class .
66
38
22,604
@ Override public String getProtocol ( HttpServletRequest request ) { String proto = request . getHeader ( X_FORWARED_PROTO ) ; if ( proto != null ) return proto ; return super . getProtocol ( request ) ; }
When the X - Forwarded - Proto header is present this method returns the value of that header . When the header is not present it delegates this call to the super class .
55
35
22,605
@ Override public int getPort ( HttpServletRequest request ) { String portValue = request . getHeader ( X_FORWARED_PORT ) ; if ( portValue != null ) return Integer . parseInt ( portValue ) ; return super . getPort ( request ) ; }
When the X - Forwarded - Port header is present this method returns the value of that header . When the header is not present it delegates this call to the super class .
61
35
22,606
public String contentTypeOf ( String path ) throws IOException { File file = findFile ( path ) ; return lookupMimeType ( file . getName ( ) ) ; }
Returns the content type for the specified path .
37
9
22,607
public File findFile ( String path ) throws IOException { File base = new File ( getBasePath ( ) ) ; File pathFile = new File ( base , "." + path ) ; if ( ! pathFile . exists ( ) ) throw new FileNotFoundException ( "No file or directory at " + pathFile . getCanonicalPath ( ) ) ; if ( pathFile . isFile ( ) ) return pathFile ; pathFile = new File ( pathFile , "index.html" ) ; if ( ! pathFile . exists ( ) ) throw new FileNotFoundException ( "No welcome file at " + pathFile . getCanonicalPath ( ) ) ; return pathFile ; }
Returns the file object for the given path including welcome file lookup . If the file cannot be found a FileNotFoundException is returned .
148
27
22,608
public void setGitService ( GitService git ) { if ( git != null ) { logger . debug ( "Setting git service" ) ; this . git = git ; latch . countDown ( ) ; } }
Sets the common reference an releases any threads waiting for the reference to be set .
45
17
22,609
@ Override public void close ( ) throws IOException { if ( git != null ) { IOUtils . closeQuietly ( git ) ; git = null ; } latch . countDown ( ) ; try { latch . notifyAll ( ) ; } catch ( Exception e ) { logger . trace ( "Failed to notifyAll" ) ; } try { locker . notifyAll ( ) ; } catch ( Exception e ) { logger . trace ( "Failed to notifyAll" ) ; } }
Releases any used resources and waiting threads .
105
9
22,610
public int read ( byte [ ] b , int off , int len ) throws IOException { ensureOpen ( ) ; if ( ( off | len | ( off + len ) | ( b . length - ( off + len ) ) ) < 0 ) { throw new IndexOutOfBoundsException ( ) ; } else if ( len == 0 ) { return 0 ; } try { int n ; while ( ( n = inf . inflate ( b , off , len ) ) == 0 ) { if ( inf . finished ( ) || inf . needsDictionary ( ) ) { reachEOF = true ; return - 1 ; } if ( inf . needsInput ( ) ) { fill ( ) ; } } return n ; } catch ( DataFormatException e ) { String s = e . getMessage ( ) ; throw new ZipException ( s != null ? s : "Invalid ZLIB data format" ) ; } }
Reads uncompressed data into an array of bytes . This method will block until some input can be decompressed .
191
23
22,611
public static void writeTXT ( String string , File file ) throws IOException { BufferedWriter out = new BufferedWriter ( new FileWriter ( file ) ) ; out . write ( string ) ; out . close ( ) ; }
Writes the string into the file .
49
8
22,612
public void setOption ( String key ) throws UnsupportedOption { if ( key . equals ( IGNORE_SCHEMA_ID ) ) { options . add ( key ) ; } else { throw new UnsupportedOption ( "DecodingOption '" + key + "' is unknown!" ) ; } }
Enables given option .
63
5
22,613
public void encodeNBitUnsignedInteger ( int b , int n ) throws IOException { if ( b < 0 || n < 0 ) { throw new IllegalArgumentException ( "Negative value as unsigned integer!" ) ; } assert ( b >= 0 ) ; assert ( n >= 0 ) ; if ( n == 0 ) { // 0 bytes } else if ( n < 9 ) { // 1 byte encode ( b & 0xff ) ; } else if ( n < 17 ) { // 2 bytes encode ( b & 0x00ff ) ; encode ( ( b & 0xff00 ) >> 8 ) ; } else if ( n < 25 ) { // 3 bytes encode ( b & 0x0000ff ) ; encode ( ( b & 0x00ff00 ) >> 8 ) ; encode ( ( b & 0xff0000 ) >> 16 ) ; } else if ( n < 33 ) { // 4 bytes encode ( b & 0x000000ff ) ; encode ( ( b & 0x0000ff00 ) >> 8 ) ; encode ( ( b & 0x00ff0000 ) >> 16 ) ; encode ( ( b & 0xff000000 ) >> 24 ) ; } else { throw new RuntimeException ( "Currently not more than 4 Bytes allowed for NBitUnsignedInteger!" ) ; } }
Encode n - bit unsigned integer using the minimum number of bytes required to store n bits . The n least significant bits of parameter b starting with the most significant i . e . from left to right .
270
41
22,614
@ SuppressWarnings ( "rawtypes" ) public void addClass ( String name , Class mainClass , String description ) throws Throwable { programs . put ( name , new ProgramDescription ( mainClass , description ) ) ; }
This is the method that adds the classed to the repository
49
12
22,615
public void driver ( String [ ] args ) throws Throwable { // Make sure they gave us a program name. if ( args . length == 0 ) { System . out . println ( "An example program must be given as the" + " first argument." ) ; printUsage ( programs ) ; throw new IllegalArgumentException ( "An example program must be given " + "as the first argument." ) ; } // And that it is good. ProgramDescription pgm = programs . get ( args [ 0 ] ) ; if ( pgm == null ) { System . out . println ( "Unknown program '" + args [ 0 ] + "' chosen." ) ; printUsage ( programs ) ; throw new IllegalArgumentException ( "Unknown program '" + args [ 0 ] + "' chosen." ) ; } // Remove the leading argument and call main String [ ] new_args = new String [ args . length - 1 ] ; for ( int i = 1 ; i < args . length ; ++ i ) { new_args [ i - 1 ] = args [ i ] ; } pgm . invoke ( new_args ) ; }
This is a driver for the example programs . It looks at the first command line argument and tries to find an example program with that name . If it is found it calls the main method in that class with the rest of the command line arguments .
236
49
22,616
public void ser ( Object datum , OutputStream output ) throws IOException { Map < Class , Serializer > serializers = cachedSerializers . get ( ) ; Serializer ser = serializers . get ( datum . getClass ( ) ) ; if ( ser == null ) { ser = serialization . getSerializer ( datum . getClass ( ) ) ; if ( ser == null ) { throw new IOException ( "Serializer for class " + datum . getClass ( ) + " not found" ) ; } serializers . put ( datum . getClass ( ) , ser ) ; } ser . open ( output ) ; ser . serialize ( datum ) ; ser . close ( ) ; }
Serializes the given object using the Hadoop serialization system .
151
14
22,617
public < T > T deser ( Object obj , InputStream in ) throws IOException { Map < Class , Deserializer > deserializers = cachedDeserializers . get ( ) ; Deserializer deSer = deserializers . get ( obj . getClass ( ) ) ; if ( deSer == null ) { deSer = serialization . getDeserializer ( obj . getClass ( ) ) ; deserializers . put ( obj . getClass ( ) , deSer ) ; } deSer . open ( in ) ; obj = deSer . deserialize ( obj ) ; deSer . close ( ) ; return ( T ) obj ; }
Deseerializes into the given object using the Hadoop serialization system . Object cannot be null .
139
22
22,618
public < T > T deser ( Object obj , byte [ ] array , int offset , int length ) throws IOException { Map < Class , Deserializer > deserializers = cachedDeserializers . get ( ) ; Deserializer deSer = deserializers . get ( obj . getClass ( ) ) ; if ( deSer == null ) { deSer = serialization . getDeserializer ( obj . getClass ( ) ) ; deserializers . put ( obj . getClass ( ) , deSer ) ; } DataInputBuffer baIs = cachedInputStream . get ( ) ; baIs . reset ( array , offset , length ) ; deSer . open ( baIs ) ; obj = deSer . deserialize ( obj ) ; deSer . close ( ) ; baIs . close ( ) ; return ( T ) obj ; }
Deserialize an object using Hadoop serialization from a byte array . The object cannot be null .
180
22
22,619
public static void copyPartialContent ( InputStream in , OutputStream out , Range r ) throws IOException { IOUtils . copyLarge ( in , out , r . start , r . length ) ; }
Copies the given range of bytes from the input stream to the output stream .
45
16
22,620
public static Long calculateRangeLength ( FileRequestContext context , Range range ) { if ( range . start == - 1 ) range . start = 0 ; if ( range . end == - 1 ) range . end = context . file . length ( ) - 1 ; range . length = range . end - range . start + 1 ; return range . length ; }
Calculates the length of a given range .
74
10
22,621
protected boolean checkAccepts ( FileRequestContext context ) throws IOException { if ( ! canAccept ( context . request . getHeader ( ACCEPT_HEADER ) , false , context . contentType ) ) { notAcceptable ( context ) ; return true ; } if ( ! ( canAccept ( context . request . getHeader ( ACCEPT_ENCODING_HEADER ) , false , "identity" ) || canAccept ( context . request . getHeader ( ACCEPT_ENCODING_HEADER ) , false , "gzip" ) ) ) { notAcceptable ( context ) ; return true ; } if ( context . request . getHeader ( ACCEPT_ENCODING_HEADER ) != null && canAccept ( context . request . getHeader ( ACCEPT_ENCODING_HEADER ) , true , "gzip" ) && shouldGzip ( context . contentType ) ) { context . compress = true ; } return false ; }
Checks the accepts headers and makes sure that we can fulfill the request .
208
15
22,622
public boolean locateFileToServe ( FileRequestContext context ) throws IOException { context . file = new File ( contentDir , context . path ) ; // if the path is not on the file system, send a 404. if ( ! context . file . exists ( ) ) { context . response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return true ; } // redirect welcome files if needed. if ( handleWelcomeRedirect ( context ) ) return true ; // if the requested file is a directory, try to find the welcome file. if ( context . file . isDirectory ( ) ) { context . file = new File ( context . file , "index.html" ) ; } // if the file does not exist, then terminate with a 404. if ( ! context . file . exists ( ) ) { context . response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return true ; } return false ; }
Locates the file to serve . Returns true if locating the file caused the request to be handled .
206
20
22,623
public static void invalidRanges ( FileRequestContext context ) throws IOException { context . response . setHeader ( CONTENT_RANGE_HEADER , "*/" + context . file . length ( ) ) ; context . response . sendError ( HttpServletResponse . SC_REQUESTED_RANGE_NOT_SATISFIABLE ) ; }
Sets the appropriate response headers and error status for bad ranges
78
12
22,624
public static boolean canAccept ( String headerValue , boolean strict , String type ) { if ( headerValue != null && type != null ) { String availableTypes [ ] = headerValue . split ( "," ) ; for ( String availableType : availableTypes ) { String typeParams [ ] = availableType . split ( ";" ) ; double qValue = 1.0d ; if ( typeParams . length > 0 ) { for ( int i = 1 ; i < typeParams . length ; i ++ ) { if ( typeParams [ i ] . trim ( ) . startsWith ( "q=" ) ) { String qString = typeParams [ i ] . substring ( 2 ) . trim ( ) ; if ( qString . matches ( "\\A\\d+(\\.\\d*){0,1}\\Z" ) ) { qValue = Double . parseDouble ( qString ) ; break ; } } } } boolean matches = false ; if ( typeParams [ 0 ] . equals ( "*" ) || typeParams [ 0 ] . equals ( "*/*" ) ) { matches = true ; } else { matches = hasMatch ( typeParams , type ) ; } if ( qValue == 0 && matches ) { return false ; } else if ( matches ) { return true ; } } } return ! strict ; }
Parses an Accept header value and checks to see if the type is acceptable .
287
17
22,625
private static boolean hasMatch ( String [ ] typeParams , String ... type ) { boolean matches = false ; for ( String t : type ) { for ( String typeParam : typeParams ) { if ( typeParam . contains ( "/" ) ) { String typePart = typeParam . replace ( "*" , "" ) ; if ( t . startsWith ( typePart ) || t . endsWith ( typePart ) ) { matches = true ; break ; } } else if ( t . equals ( typeParam ) ) { matches = true ; break ; } } if ( matches ) { break ; } } return matches ; }
Check to see if a Accept header accept part matches any of the given types .
132
16
22,626
public boolean handleWelcomeRedirect ( FileRequestContext context ) throws IOException { if ( context . file . isFile ( ) && context . file . getName ( ) . equals ( "index.html" ) ) { resolveContentType ( context ) ; String location = context . path . replaceFirst ( "/index.html\\Z" , "" ) ; if ( location . isEmpty ( ) ) location = "/" ; if ( context . request . getQueryString ( ) != null ) location = location + "?" + context . request . getQueryString ( ) ; sendPermanentRedirect ( context , location ) ; return true ; } return false ; }
Forces requests for index files to not use the file name .
138
13
22,627
public void resolveContentType ( FileRequestContext context ) { String contentType = lookupMimeType ( context . file . getName ( ) ) ; if ( contentType != null ) { context . contentType = contentType ; if ( contentType . equals ( "text/html" ) ) { context . contentType += ";charset=UTF-8" ; } } }
Looks up the mime type based on file extension and if found sets it on the FileRequestContext .
81
21
22,628
protected void flushBuffer ( ) throws IOException { if ( capacity == 0 ) { ostream . write ( buffer ) ; capacity = BITS_IN_BYTE ; buffer = 0 ; len ++ ; } }
If buffer is full write it out and reset internal state .
44
12
22,629
public void align ( ) throws IOException { if ( capacity < BITS_IN_BYTE ) { ostream . write ( buffer << capacity ) ; capacity = BITS_IN_BYTE ; buffer = 0 ; len ++ ; } }
If there are some unwritten bits pad them if necessary and write them out .
51
16
22,630
public void writeBits ( int b , int n ) throws IOException { if ( n <= capacity ) { // all bits fit into the current buffer buffer = ( buffer << n ) | ( b & ( 0xff >> ( BITS_IN_BYTE - n ) ) ) ; capacity -= n ; if ( capacity == 0 ) { ostream . write ( buffer ) ; capacity = BITS_IN_BYTE ; len ++ ; } } else { // fill as many bits into buffer as possible buffer = ( buffer << capacity ) | ( ( b >>> ( n - capacity ) ) & ( 0xff >> ( BITS_IN_BYTE - capacity ) ) ) ; n -= capacity ; ostream . write ( buffer ) ; len ++ ; // possibly write whole bytes while ( n >= 8 ) { n -= 8 ; ostream . write ( b >>> n ) ; len ++ ; } // put the rest of bits into the buffer buffer = b ; // Note: the high bits will be shifted out during // further filling capacity = BITS_IN_BYTE - n ; } }
Write the n least significant bits of parameter b starting with the most significant i . e . from left to right .
228
23
22,631
protected void writeDirectBytes ( byte [ ] b , int off , int len ) throws IOException { ostream . write ( b , off , len ) ; len += len ; }
Ignore current buffer and write a sequence of bytes directly to the underlying stream .
38
16
22,632
private static String adaptNumber ( String number ) { String n = number . trim ( ) ; if ( n . startsWith ( "+" ) ) { return n . substring ( 1 ) ; } else { return n ; } }
Adapt a number for being able to be parsed by Integer and Long
48
13
22,633
private void persistRealmChanges ( ) { configManager . persistProperties ( realm . getProperties ( ) , new File ( applicationContentDir , PersistablePropertiesRealm . REALM_FILE_NAME ) , null ) ; }
Persists the user accounts to a properties file that is only available to this site only .
51
18
22,634
public static void stringToFile ( FileSystem fs , Path path , String string ) throws IOException { OutputStream os = fs . create ( path , true ) ; PrintWriter pw = new PrintWriter ( os ) ; pw . append ( string ) ; pw . close ( ) ; }
Creates a file with the given string overwritting if needed .
62
14
22,635
public static String fileToString ( FileSystem fs , Path path ) throws IOException { if ( ! fs . exists ( path ) ) { return null ; } InputStream is = fs . open ( path ) ; InputStreamReader isr = new InputStreamReader ( is ) ; BufferedReader br = new BufferedReader ( isr ) ; char [ ] buff = new char [ 256 ] ; StringBuilder sb = new StringBuilder ( ) ; int read ; while ( ( read = br . read ( buff ) ) != - 1 ) { sb . append ( buff , 0 , read ) ; } br . close ( ) ; return sb . toString ( ) ; }
Reads the content of a file into a String . Return null if the file does not exist .
143
20
22,636
public static HashMap < Integer , Integer > readIntIntMap ( Path path , FileSystem fs ) throws IOException { SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , fs . getConf ( ) ) ; IntWritable topic = new IntWritable ( ) ; IntWritable value = new IntWritable ( ) ; HashMap < Integer , Integer > ret = new HashMap < Integer , Integer > ( ) ; while ( reader . next ( topic ) ) { reader . getCurrentValue ( value ) ; ret . put ( topic . get ( ) , value . get ( ) ) ; } reader . close ( ) ; return ret ; }
Reads maps of integer - > integer
140
8
22,637
static Scenario scenario ( String text ) { reset ( ) ; final Scenario scenario = new Scenario ( text ) ; sRoot = scenario ; return scenario ; }
Describes the scenario of the use case .
34
9
22,638
static Given given ( String text ) { reset ( ) ; final Given given = new Given ( text ) ; sRoot = given ; return given ; }
Describes the entry point of the use case .
31
10
22,639
public static void insertMessage ( Throwable onObject , String msg ) { try { Field field = Throwable . class . getDeclaredField ( "detailMessage" ) ; //Method("initCause", new Class[]{Throwable.class}); field . setAccessible ( true ) ; if ( onObject . getMessage ( ) != null ) { field . set ( onObject , "\n[\n" + msg + "\n]\n[\nMessage: " + onObject . getMessage ( ) + "\n]" ) ; } else { field . set ( onObject , "\n[\n" + msg + "]\n" ) ; } } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { } }
Addes a message at the beginning of the stacktrace .
161
12
22,640
public Stylesheet parse ( ) throws ParseException { while ( tokenizer . more ( ) ) { if ( tokenizer . current ( ) . isKeyword ( KEYWORD_IMPORT ) ) { // Handle @import parseImport ( ) ; } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_MIXIN ) ) { // Handle @mixin Mixin mixin = parseMixin ( ) ; if ( mixin . getName ( ) != null ) { result . addMixin ( mixin ) ; } } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_MEDIA ) ) { // Handle @media result . addSection ( parseSection ( true ) ) ; } else if ( tokenizer . current ( ) . isSpecialIdentifier ( "$" ) && tokenizer . next ( ) . isSymbol ( ":" ) ) { // Handle variable definition parseVariableDeclaration ( ) ; } else { // Everything else is a "normal" section with selectors and attributes result . addSection ( parseSection ( false ) ) ; } } // Something went wrong? Throw an exception if ( ! tokenizer . getProblemCollector ( ) . isEmpty ( ) ) { throw ParseException . create ( tokenizer . getProblemCollector ( ) ) ; } return result ; }
Parses the given input returning the parsed stylesheet .
285
12
22,641
private Section parseSection ( boolean mediaQuery ) { Section section = new Section ( ) ; parseSectionSelector ( mediaQuery , section ) ; tokenizer . consumeExpectedSymbol ( "{" ) ; while ( tokenizer . more ( ) ) { if ( tokenizer . current ( ) . isSymbol ( "}" ) ) { tokenizer . consumeExpectedSymbol ( "}" ) ; return section ; } // Parse "normal" attributes like "font-weight: bold;" if ( isAtAttribute ( ) ) { Attribute attr = parseAttribute ( ) ; section . addAttribute ( attr ) ; } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_MEDIA ) ) { // Take care of @media sub sections section . addSubSection ( parseSection ( true ) ) ; } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_INCLUDE ) ) { parseInclude ( section ) ; } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_EXTEND ) ) { parseExtend ( section ) ; } else { // If it is neither an attribute, nor a media query or instruction - it is probably a sub section... section . addSubSection ( parseSection ( false ) ) ; } } tokenizer . consumeExpectedSymbol ( "}" ) ; return section ; }
Parses a section which is either a media query or a css selector along with a set of attributes .
296
23
22,642
private Object [ ] getValues ( Map < String , Object > annotationAtts ) { if ( null == annotationAtts ) { throw new DuraCloudRuntimeException ( "Arg annotationAtts is null." ) ; } List < Object > values = new ArrayList < Object > ( ) ; for ( String key : annotationAtts . keySet ( ) ) { Object [ ] objects = ( Object [ ] ) annotationAtts . get ( key ) ; for ( Object obj : objects ) { values . add ( obj ) ; } } return values . toArray ( ) ; }
This method extracts the annotation argument info from the annotation metadata . Since the implementation of access for annotation arguments varies this method may need to be overwritten by additional AnnotationParsers .
121
37
22,643
private Set < Role > getOtherRolesArg ( Object [ ] arguments ) { if ( arguments . length <= NEW_ROLES_INDEX ) { log . error ( "Illegal number of args: " + arguments . length ) ; } Set < Role > roles = new HashSet < Role > ( ) ; Object [ ] rolesArray = ( Object [ ] ) arguments [ NEW_ROLES_INDEX ] ; if ( null != rolesArray && rolesArray . length > 0 ) { for ( Object role : rolesArray ) { roles . add ( ( Role ) role ) ; } } return roles ; }
This method returns roles argument of in the target method invocation .
130
12
22,644
private Long getOtherUserIdArg ( Object [ ] arguments ) { if ( arguments . length <= OTHER_USER_ID_INDEX ) { log . error ( "Illegal number of args: " + arguments . length ) ; } return ( Long ) arguments [ OTHER_USER_ID_INDEX ] ; }
This method returns peer userId argument of the target method invocation .
66
13
22,645
private Long getUserIdArg ( Object [ ] arguments ) { if ( arguments . length <= USER_ID_INDEX ) { log . error ( "Illegal number of args: " + arguments . length ) ; } return ( Long ) arguments [ USER_ID_INDEX ] ; }
This method returns userId argument of the target method invocation .
63
12
22,646
private Long getAccountIdArg ( Object [ ] arguments ) { if ( arguments . length <= ACCT_ID_INDEX ) { log . error ( "Illegal number of args: " + arguments . length ) ; } return ( Long ) arguments [ ACCT_ID_INDEX ] ; }
This method returns acctId argument of the target method invocation .
63
13
22,647
public static Expression rgb ( Generator generator , FunctionCall input ) { return new Color ( input . getExpectedIntParam ( 0 ) , input . getExpectedIntParam ( 1 ) , input . getExpectedIntParam ( 2 ) ) ; }
Creates a color from given RGB values .
52
9
22,648
public static Expression rgba ( Generator generator , FunctionCall input ) { if ( input . getParameters ( ) . size ( ) == 4 ) { return new Color ( input . getExpectedIntParam ( 0 ) , input . getExpectedIntParam ( 1 ) , input . getExpectedIntParam ( 2 ) , input . getExpectedFloatParam ( 3 ) ) ; } if ( input . getParameters ( ) . size ( ) == 2 ) { Color color = input . getExpectedColorParam ( 0 ) ; float newA = input . getExpectedFloatParam ( 1 ) ; return new Color ( color . getR ( ) , color . getG ( ) , color . getB ( ) , newA ) ; } throw new IllegalArgumentException ( "rgba must be called with either 2 or 4 parameters. Function call: " + input ) ; }
Creates a color from given RGB and alpha values .
184
11
22,649
public static Expression adjusthue ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int changeInDegrees = input . getExpectedIntParam ( 1 ) ; Color . HSL hsl = color . getHSL ( ) ; hsl . setH ( hsl . getH ( ) + changeInDegrees ) ; return hsl . getColor ( ) ; }
Adjusts the hue of the given color by the given number of degrees .
93
15
22,650
public static Expression lighten ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int increase = input . getExpectedIntParam ( 1 ) ; return changeLighteness ( color , increase ) ; }
Increases the lightness of the given color by N percent .
53
12
22,651
public static Expression alpha ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; return new Number ( color . getA ( ) , String . valueOf ( color . getA ( ) ) , "" ) ; }
Returns the alpha value of the given color
55
8
22,652
public static Expression darken ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int decrease = input . getExpectedIntParam ( 1 ) ; return changeLighteness ( color , - decrease ) ; }
Decreases the lightness of the given color by N percent .
54
13
22,653
public static Expression saturate ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int increase = input . getExpectedIntParam ( 1 ) ; return changeSaturation ( color , increase ) ; }
Increases the saturation of the given color by N percent .
53
11
22,654
public static Expression desaturate ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int decrease = input . getExpectedIntParam ( 1 ) ; return changeSaturation ( color , - decrease ) ; }
Decreases the saturation of the given color by N percent .
55
12
22,655
@ SuppressWarnings ( "squid:S00100" ) public static Expression fade_out ( Generator generator , FunctionCall input ) { return opacify ( generator , input ) ; }
Decreases the opacity of the given color by the given amount .
42
13
22,656
public static Expression mix ( Generator generator , FunctionCall input ) { Color color1 = input . getExpectedColorParam ( 0 ) ; Color color2 = input . getExpectedColorParam ( 1 ) ; float weight = input . getParameters ( ) . size ( ) > 2 ? input . getExpectedFloatParam ( 2 ) : 0.5f ; return new Color ( ( int ) Math . round ( color1 . getR ( ) * weight + color2 . getR ( ) * ( 1.0 - weight ) ) , ( int ) Math . round ( color1 . getG ( ) * weight + color2 . getG ( ) * ( 1.0 - weight ) ) , ( int ) Math . round ( color1 . getB ( ) * weight + color2 . getB ( ) * ( 1.0 - weight ) ) , ( float ) ( color1 . getA ( ) * weight + color2 . getA ( ) * ( 1.0 - weight ) ) ) ; }
Calculates the weighted arithmetic mean of two colors .
214
11
22,657
public Output lineBreak ( ) throws IOException { writer . write ( "\n" ) ; if ( ! skipOptionalOutput ) { for ( int i = 0 ; i < indentLevel ; i ++ ) { writer . write ( indentDepth ) ; } } return this ; }
Outputs an indented line break in any case .
57
11
22,658
@ SuppressWarnings ( "squid:S1244" ) public HSL getHSL ( ) { // Convert the RGB values to the range 0-1 double red = r / 255.0 ; double green = g / 255.0 ; double blue = b / 255.0 ; // Find the minimum and maximum values of R, G and B. double min = Math . min ( red , Math . min ( green , blue ) ) ; double max = Math . max ( red , Math . max ( green , blue ) ) ; double delta = max - min ; // Now calculate the luminace value by adding the max and min values and divide by 2. double l = ( min + max ) / 2 ; // The next step is to find the Saturation. double s = 0 ; // If the min and max value are the same, it means that there is no saturation. // If all RGB values are equal you have a shade of grey. if ( Math . abs ( delta ) > EPSILON ) { // Now we know that there is Saturation we need to do check the level of the Luminance // in order to select the correct formula. if ( l < 0.5 ) { s = delta / ( max + min ) ; } else { s = delta / ( 2.0 - max - min ) ; } } // The Hue formula is depending on what RGB color channel is the max value. double h = 0 ; if ( delta > 0 ) { if ( red == max ) { h = ( green - blue ) / delta ; } else if ( green == max ) { h = ( ( blue - red ) / delta ) + 2.0 ; } else { h = ( ( red - green ) / delta ) + 4.0 ; } } // The Hue value you get needs to be multiplied by 60 to convert it to degrees on the color circle // If Hue becomes negative you need to add 360 to, because a circle has 360 degrees. h = h * 60 ; return new HSL ( ( int ) Math . round ( h ) , s , l ) ; }
Computes the HSL value form the stored RGB values .
440
12
22,659
public String getMediaQuery ( Scope scope , Generator gen ) { StringBuilder sb = new StringBuilder ( ) ; for ( Expression expr : mediaQueries ) { if ( sb . length ( ) > 0 ) { sb . append ( " and " ) ; } sb . append ( expr . eval ( scope , gen ) ) ; } return sb . toString ( ) ; }
Compiles the effective media query of this section into a string
83
12
22,660
public String getSelectorString ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( List < String > selector : selectors ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } for ( String s : selector ) { if ( sb . length ( ) > 0 ) { sb . append ( " " ) ; } sb . append ( s ) ; } } return sb . toString ( ) ; }
Compiles the effective selector string .
104
7
22,661
public void importStylesheet ( Stylesheet sheet ) { if ( sheet == null ) { return ; } if ( importedSheets . contains ( sheet . getName ( ) ) ) { return ; } importedSheets . add ( sheet . getName ( ) ) ; for ( String imp : sheet . getImports ( ) ) { importStylesheet ( imp ) ; } for ( Mixin mix : sheet . getMixins ( ) ) { mixins . put ( mix . getName ( ) , mix ) ; } for ( Variable var : sheet . getVariables ( ) ) { if ( ! scope . has ( var . getName ( ) ) || ! var . isDefaultValue ( ) ) { scope . set ( var . getName ( ) , var . getValue ( ) ) ; } else { debug ( "Skipping redundant variable definition: '" + var + "'" ) ; } } for ( Section section : sheet . getSections ( ) ) { List < Section > stack = new ArrayList <> ( ) ; expand ( null , section , stack ) ; } }
Imports an already parsed stylesheet .
232
8
22,662
protected final boolean isGroupNameValid ( String name ) { if ( name == null ) { return false ; } if ( ! name . startsWith ( DuracloudGroup . PREFIX ) ) { return false ; } if ( DuracloudGroup . PUBLIC_GROUP_NAME . equalsIgnoreCase ( name ) ) { return false ; } return name . substring ( DuracloudGroup . PREFIX . length ( ) ) . matches ( "\\A(?![_.@\\-])[a-z0-9_.@\\-]+(?<![_.@\\-])\\Z" ) ; }
This method is protected for testing purposes only .
131
9
22,663
public List < DuplicationInfo > getDupIssues ( ) { List < DuplicationInfo > dupIssues = new LinkedList <> ( ) ; for ( DuplicationInfo dupInfo : dupInfos . values ( ) ) { if ( dupInfo . hasIssues ( ) ) { dupIssues . add ( dupInfo ) ; } } return dupIssues ; }
This method gets all issues discovered for all checked accounts
81
10
22,664
protected static void appendNameAndParameters ( StringBuilder sb , String name , List < Expression > parameters ) { sb . append ( name ) ; sb . append ( "(" ) ; boolean first = true ; for ( Expression expr : parameters ) { if ( ! first ) { sb . append ( ", " ) ; } first = false ; sb . append ( expr ) ; } sb . append ( ")" ) ; }
Appends the name and parameters to the given string builder .
92
12
22,665
public Expression getExpectedParam ( int index ) { if ( parameters . size ( ) <= index ) { throw new IllegalArgumentException ( "Parameter index out of bounds: " + index + ". Function call: " + this ) ; } return parameters . get ( index ) ; }
Returns the parameter at the expected index .
59
8
22,666
public Expression get ( String name ) { if ( variables . containsKey ( name ) ) { return variables . get ( name ) ; } if ( parent == null ) { return new Value ( "" ) ; } return parent . get ( name ) ; }
Returns the value previously set for the given variable .
52
10
22,667
public DuplicationReport monitorDuplication ( ) { log . info ( "starting duplication monitor" ) ; DuplicationReport report = new DuplicationReport ( ) ; for ( String host : dupHosts . keySet ( ) ) { DuplicationInfo info = new DuplicationInfo ( host ) ; try { // Connect to storage providers ContentStoreManager storeManager = getStoreManager ( host ) ; ContentStore primary = storeManager . getPrimaryContentStore ( ) ; String primaryStoreId = primary . getStoreId ( ) ; List < ContentStore > secondaryList = getSecondaryStores ( storeManager , primaryStoreId ) ; // Get primary space listing and count List < String > primarySpaces = getSpaces ( host , primary ) ; countSpaces ( host , info , primary , primarySpaces , true ) ; // Get space listing and space counts for secondary providers for ( ContentStore secondary : secondaryList ) { List < String > secondarySpaces = getSpaces ( host , secondary ) ; if ( primarySpaces . size ( ) != secondarySpaces . size ( ) ) { info . addIssue ( "The spaces listings do not match " + "between primary and secondary " + "provider: " + secondary . getStorageProviderType ( ) ) ; } // Determine item count for secondary provider spaces countSpaces ( host , info , secondary , secondarySpaces , false ) ; } // Compare the space counts between providers compareSpaces ( primaryStoreId , info ) ; } catch ( Exception e ) { String error = e . getClass ( ) + " exception encountered while " + "running dup monitor for host " + host + ". Exception message: " + e . getMessage ( ) ; log . error ( error ) ; info . addIssue ( error ) ; } finally { report . addDupInfo ( host , info ) ; } } return report ; }
This method performs the duplication checks . These checks compare the number of content items in identically named spaces .
393
21
22,668
public static int calculateThreads ( final int executorThreads , final String name ) { // For current standard 8 core machines this is 10 regardless. // On Java 10, you might get less than 8 core reported, but it will still size as if it's 8 // Beyond 8 core you MIGHT undersize if running on Docker, but otherwise should be fine. final int optimalThreads = Math . max ( BASE_OPTIMAL_THREADS , ( Runtime . getRuntime ( ) . availableProcessors ( ) + THREAD_OVERHEAD ) ) ; int threadsChosen = optimalThreads ; if ( executorThreads > optimalThreads ) { // They requested more, sure we can do that! threadsChosen = executorThreads ; LOG . warn ( "Requested more than optimal threads. This is not necessarily an error, but you may be overallocating." ) ; } else { // They weren't auto tuning (<0)) if ( executorThreads > 0 ) { LOG . warn ( "You requested less than optimal threads. We've ignored that." ) ; } } LOG . debug ( "For factory {}, Optimal Threads {}, Configured Threads {}" , name , optimalThreads , threadsChosen ) ; return threadsChosen ; }
Calculate optimal threads . If they exceed the specified executorThreads use optimal threads instead . Emit appropriate logging
269
24
22,669
@ SafeVarargs public final synchronized JaxRsClientFactory addFeatureToAllClients ( Class < ? extends Feature > ... features ) { return addFeatureToGroup ( PrivateFeatureGroup . WILDCARD , features ) ; }
Register a list of features for all created clients .
48
10
22,670
public < T > T createClientProxy ( Class < T > proxyClass , WebTarget baseTarget ) { return factory ( ctx ) . createClientProxy ( proxyClass , baseTarget ) ; }
Create a Client proxy for the given interface type . Note that different JAX - RS providers behave slightly differently for this feature .
41
25
22,671
public static boolean seemsToHaveSignature ( Nanopub nanopub ) { for ( Statement st : nanopub . getPubinfo ( ) ) { if ( st . getPredicate ( ) . equals ( NanopubSignatureElement . HAS_SIGNATURE_ELEMENT ) ) return true ; if ( st . getPredicate ( ) . equals ( NanopubSignatureElement . HAS_SIGNATURE_TARGET ) ) return true ; if ( st . getPredicate ( ) . equals ( NanopubSignatureElement . HAS_SIGNATURE ) ) return true ; if ( st . getPredicate ( ) . equals ( CryptoElement . HAS_PUBLIC_KEY ) ) return true ; } return false ; }
This includes legacy signatures . Might include false positives .
153
10
22,672
private void workflowCuration ( JsonSimple response , JsonSimple message ) { String oid = message . getString ( null , "oid" ) ; if ( ! workflowCompleted ( oid ) ) { return ; } // Resolve relationships before we continue try { JSONArray relations = mapRelations ( oid ) ; // Unless there was an error, we should be good to go if ( relations != null ) { JsonObject request = createTask ( response , oid , "curation-request" ) ; if ( ! relations . isEmpty ( ) ) { request . put ( "relationships" , relations ) ; } } } catch ( Exception ex ) { log . error ( "Error processing relations: " , ex ) ; return ; } }
Assess a workflow event to see how it effects curation
158
12
22,673
private JSONArray mapRelations ( String oid ) { // We want our parsed data for reading JsonSimple formData = parsedFormData ( oid ) ; if ( formData == null ) { log . error ( "Error parsing form data" ) ; return null ; } // And raw data to see existing relations and write new ones JsonSimple rawData = getDataFromStorage ( oid ) ; if ( rawData == null ) { log . error ( "Error reading data from storage" ) ; return null ; } // Existing relationship data JSONArray relations = rawData . writeArray ( "relationships" ) ; boolean changed = false ; // For all configured relationships for ( String baseField : relationFields . keySet ( ) ) { JsonSimple relationConfig = relationFields . get ( baseField ) ; // Find the path we need to look under for our related object List < String > basePath = relationConfig . getStringList ( "path" ) ; if ( basePath == null || basePath . isEmpty ( ) ) { log . error ( "Ignoring invalid relationship '{}'. No 'path'" + " provided in configuration" , baseField ) ; continue ; } // Get our base object Object object = formData . getPath ( basePath . toArray ( ) ) ; if ( object instanceof JsonObject ) { // And process it JsonObject newRelation = lookForRelation ( oid , baseField , relationConfig , new JsonSimple ( ( JsonObject ) object ) ) ; if ( newRelation != null && ! isKnownRelation ( relations , newRelation ) ) { log . info ( "Adding relation: '{}' => '{}'" , baseField , newRelation . get ( "identifier" ) ) ; relations . add ( newRelation ) ; changed = true ; } } // If base path points at an array if ( object instanceof JSONArray ) { // Try every entry for ( Object loopObject : ( JSONArray ) object ) { if ( loopObject instanceof JsonObject ) { JsonObject newRelation = lookForRelation ( oid , baseField , relationConfig , new JsonSimple ( ( JsonObject ) loopObject ) ) ; if ( newRelation != null && ! isKnownRelation ( relations , newRelation ) ) { log . info ( "Adding relation: '{}' => '{}'" , baseField , newRelation . get ( "identifier" ) ) ; relations . add ( newRelation ) ; changed = true ; } } } } } // Do we need to store our object again? if ( changed ) { try { saveObjectData ( rawData , oid ) ; } catch ( TransactionException ex ) { log . error ( "Error updating object '{}' in storage: " , oid , ex ) ; return null ; } } return relations ; }
Map all the relationships buried in this record s data
617
10
22,674
private boolean isKnownRelation ( JSONArray relations , JsonObject newRelation ) { // Does it have an OID? Highest priority. Avoids infinite loops // between ReDBox collections pointing at each other, so strict if ( newRelation . containsKey ( "oid" ) ) { for ( Object relation : relations ) { JsonObject json = ( JsonObject ) relation ; String knownOid = ( String ) json . get ( "oid" ) ; String newOid = ( String ) newRelation . get ( "oid" ) ; // Do they match? if ( knownOid . equals ( newOid ) ) { log . debug ( "Known ReDBox linkage '{}'" , knownOid ) ; return true ; } } return false ; } // Mint records we are less strict about and happy // to allow multiple links in differing fields. for ( Object relation : relations ) { JsonObject json = ( JsonObject ) relation ; if ( json . containsKey ( "identifier" ) ) { String knownId = ( String ) json . get ( "identifier" ) ; String knownField = ( String ) json . get ( "field" ) ; String newId = ( String ) newRelation . get ( "identifier" ) ; String newField = ( String ) newRelation . get ( "field" ) ; // And does the ID match? if ( knownId . equals ( newId ) && knownField . equals ( newField ) ) { return true ; } } } // No match found return false ; }
Test whether the field provided is already a known relationship
331
10
22,675
private JsonSimple publish ( JsonSimple message , String oid ) throws TransactionException { log . debug ( "Publishing '{}'" , oid ) ; JsonSimple response = new JsonSimple ( ) ; try { DigitalObject object = storage . getObject ( oid ) ; Properties metadata = object . getMetadata ( ) ; // Already published? if ( ! metadata . containsKey ( PUBLISH_PROPERTY ) ) { metadata . setProperty ( PUBLISH_PROPERTY , "true" ) ; storeProperties ( object , metadata ) ; log . info ( "Publication flag set '{}'" , oid ) ; audit ( response , oid , "Publication flag set" ) ; } else { log . info ( "Publication flag is already set '{}'" , oid ) ; } } catch ( StorageException ex ) { throw new TransactionException ( "Error setting publish property: " , ex ) ; } // Make a final pass through the curation tool(s), // allows for external publication. eg. VITAL JsonSimple itemConfig = getConfigFromStorage ( oid ) ; if ( itemConfig == null ) { log . error ( "Error accessing item configuration!" ) ; } else { List < String > list = itemConfig . getStringList ( "transformer" , "curation" ) ; if ( list != null && ! list . isEmpty ( ) ) { for ( String id : list ) { JsonObject order = newTransform ( response , id , oid ) ; JsonObject config = ( JsonObject ) order . get ( "config" ) ; JsonObject overrides = itemConfig . getObject ( "transformerOverrides" , id ) ; if ( overrides != null ) { config . putAll ( overrides ) ; } } } } // Don't forget to publish children publishRelations ( response , oid ) ; return response ; }
Get the requested object ready for publication . This would typically just involve setting a flag
411
16
22,676
private void publishRelations ( JsonSimple response , String oid ) throws TransactionException { log . debug ( "Publishing Children of '{}'" , oid ) ; JsonSimple data = getDataFromStorage ( oid ) ; if ( data == null ) { log . error ( "Error accessing item data! '{}'" , oid ) ; emailObjectLink ( response , oid , "An error occured publishing the related objects for this" + " record. Please check the system logs." ) ; return ; } JSONArray relations = data . writeArray ( "relationships" ) ; for ( Object relation : relations ) { JsonSimple json = new JsonSimple ( ( JsonObject ) relation ) ; String broker = json . getString ( null , "broker" ) ; boolean localRecord = broker . equals ( brokerUrl ) ; String relatedId = json . getString ( null , "identifier" ) ; // We need to find OIDs to match IDs (only for local records) String relatedOid = json . getString ( null , "oid" ) ; if ( relatedOid == null && localRecord ) { String identifier = json . getString ( null , "identifier" ) ; if ( identifier == null ) { log . error ( "NULL identifer provided!" ) ; } relatedOid = idToOid ( identifier ) ; if ( relatedOid == null ) { log . error ( "Cannot resolve identifer: '{}'" , identifier ) ; } } // We only publish downstream relations (ie. we are their authority) boolean authority = json . getBoolean ( false , "authority" ) ; boolean relationPublishRequested = json . getBoolean ( false , "relationPublishedRequested" ) ; if ( authority && ! relationPublishRequested ) { // Is this relationship using a curated ID? boolean isCurated = json . getBoolean ( false , "isCurated" ) ; if ( isCurated ) { log . debug ( " * Publishing '{}'" , relatedId ) ; // It is a local object if ( localRecord ) { createTask ( response , relatedOid , "publish" ) ; // Or remote } else { JsonObject task = createTask ( response , broker , relatedOid , "publish" ) ; // We won't know OIDs for remote systems task . remove ( "oid" ) ; task . put ( "identifier" , relatedId ) ; } log . debug ( " * Writing relationPublishedRequested for '{}'" , relatedId ) ; json . getJsonObject ( ) . put ( "relationPublishedRequested" , true ) ; saveObjectData ( data , oid ) ; } else { log . debug ( " * Ignoring non-curated relationship '{}'" , relatedId ) ; } } } }
Send out requests to all relations to publish
608
8
22,677
private void reharvest ( JsonSimple response , JsonSimple message ) { String oid = message . getString ( null , "oid" ) ; try { if ( oid != null ) { setRenderFlag ( oid ) ; // Transformer config JsonSimple itemConfig = getConfigFromStorage ( oid ) ; if ( itemConfig == null ) { log . error ( "Error accessing item configuration!" ) ; return ; } itemConfig . getJsonObject ( ) . put ( "oid" , oid ) ; // Tool chain scheduleTransformers ( itemConfig , response ) ; JsonObject order = newIndex ( response , oid ) ; order . put ( "forceCommit" , true ) ; createTask ( response , oid , "clear-render-flag" ) ; } else { log . error ( "Cannot reharvest without an OID!" ) ; } } catch ( Exception ex ) { log . error ( "Error during reharvest setup: " , ex ) ; } }
Generate a fairly common list of orders to transform and index an object . This mirrors the traditional tool chain .
217
22
22,678
private void emailObjectLink ( JsonSimple response , String oid , String message ) { String link = urlBase + "default/detail/" + oid ; String text = "This is an automated message from the " ; text += "ReDBox Curation Manager.\n\n" + message ; text += "\n\nYou can find this object here:\n" + link ; email ( response , oid , text ) ; }
Generate an order to send an email to the intended recipient with a link to an object
94
18
22,679
private void email ( JsonSimple response , String oid , String text ) { JsonObject object = newMessage ( response , EmailNotificationConsumer . LISTENER_ID ) ; JsonObject message = ( JsonObject ) object . get ( "message" ) ; message . put ( "to" , emailAddress ) ; message . put ( "body" , text ) ; message . put ( "oid" , oid ) ; }
Generate an order to send an email to the intended recipient
94
12
22,680
private void audit ( JsonSimple response , String oid , String message ) { JsonObject order = newSubscription ( response , oid ) ; JsonObject messageObject = ( JsonObject ) order . get ( "message" ) ; messageObject . put ( "eventType" , message ) ; }
Generate an order to add a message to the System s audit log
66
14
22,681
private void scheduleTransformers ( JsonSimple message , JsonSimple response ) { String oid = message . getString ( null , "oid" ) ; List < String > list = message . getStringList ( "transformer" , "metadata" ) ; if ( list != null && ! list . isEmpty ( ) ) { for ( String id : list ) { JsonObject order = newTransform ( response , id , oid ) ; // Add item config to message... if it exists JsonObject itemConfig = message . getObject ( "transformerOverrides" , id ) ; if ( itemConfig != null ) { JsonObject config = ( JsonObject ) order . get ( "config" ) ; config . putAll ( itemConfig ) ; } } } }
Generate orders for the list of normal transformers scheduled to execute on the tool chain
166
17
22,682
private void setRenderFlag ( String oid ) { try { DigitalObject object = storage . getObject ( oid ) ; Properties props = object . getMetadata ( ) ; props . setProperty ( "render-pending" , "true" ) ; storeProperties ( object , props ) ; } catch ( StorageException ex ) { log . error ( "Error accessing storage for '{}'" , oid , ex ) ; } }
Set the render flag for objects that are starting in the tool chain
93
13
22,683
private JsonObject createTask ( JsonSimple response , String oid , String task ) { return createTask ( response , null , oid , task ) ; }
Create a task . Tasks are basically just trivial messages that will come back to this manager for later action .
35
22
22,684
private JsonObject createTask ( JsonSimple response , String broker , String oid , String task ) { JsonObject object = newMessage ( response , TransactionManagerQueueConsumer . LISTENER_ID ) ; if ( broker != null ) { object . put ( "broker" , broker ) ; } JsonObject message = ( JsonObject ) object . get ( "message" ) ; message . put ( "task" , task ) ; message . put ( "oid" , oid ) ; return message ; }
Create a task . This is a more detailed option allowing for tasks being sent to remote brokers .
111
19
22,685
private JsonObject newIndex ( JsonSimple response , String oid ) { JsonObject order = createNewOrder ( response , TransactionManagerQueueConsumer . OrderType . INDEXER . toString ( ) ) ; order . put ( "oid" , oid ) ; return order ; }
Creation of new Orders with appropriate default nodes
62
9
22,686
private JsonSimple getConfigFromStorage ( String oid ) { String configOid = null ; String configPid = null ; // Get our object and look for its config info try { DigitalObject object = storage . getObject ( oid ) ; Properties metadata = object . getMetadata ( ) ; configOid = metadata . getProperty ( "jsonConfigOid" ) ; configPid = metadata . getProperty ( "jsonConfigPid" ) ; } catch ( StorageException ex ) { log . error ( "Error accessing object '{}' in storage: " , oid , ex ) ; return null ; } // Validate if ( configOid == null || configPid == null ) { log . error ( "Unable to find configuration for OID '{}'" , oid ) ; return null ; } // Grab the config from storage try { DigitalObject object = storage . getObject ( configOid ) ; Payload payload = object . getPayload ( configPid ) ; try { return new JsonSimple ( payload . open ( ) ) ; } catch ( IOException ex ) { log . error ( "Error accessing config '{}' in storage: " , configOid , ex ) ; } finally { payload . close ( ) ; } } catch ( StorageException ex ) { log . error ( "Error accessing object in storage: " , ex ) ; } // Something screwed the pooch return null ; }
Get the stored harvest configuration from storage for the indicated object .
306
12
22,687
private JsonSimple parsedFormData ( String oid ) { // Get our data from Storage Payload payload = null ; try { DigitalObject object = storage . getObject ( oid ) ; payload = getDataPayload ( object ) ; } catch ( StorageException ex ) { log . error ( "Error accessing object '{}' in storage: " , oid , ex ) ; return null ; } // Parse the JSON try { try { return FormDataParser . parse ( payload . open ( ) ) ; } catch ( IOException ex ) { log . error ( "Error parsing data '{}': " , oid , ex ) ; return null ; } finally { payload . close ( ) ; } } catch ( StorageException ex ) { log . error ( "Error accessing data '{}' in storage: " , oid , ex ) ; return null ; } }
Get the form data from storage for the indicated object and parse it into a JSON structure .
185
18
22,688
private Properties getObjectMetadata ( String oid ) { try { DigitalObject object = storage . getObject ( oid ) ; return object . getMetadata ( ) ; } catch ( StorageException ex ) { log . error ( "Error accessing object '{}' in storage: " , oid , ex ) ; return null ; } }
Get the metadata properties for the indicated object .
72
9
22,689
private void saveObjectData ( JsonSimple data , String oid ) throws TransactionException { // Get from storage DigitalObject object = null ; try { object = storage . getObject ( oid ) ; getDataPayload ( object ) ; } catch ( StorageException ex ) { log . error ( "Error accessing object '{}' in storage: " , oid , ex ) ; throw new TransactionException ( ex ) ; } // Store modifications String jsonString = data . toString ( true ) ; try { updateDataPayload ( object , jsonString ) ; } catch ( Exception ex ) { log . error ( "Unable to store data '{}': " , oid , ex ) ; throw new TransactionException ( ex ) ; } }
Save the provided object data back into storage
157
8
22,690
public static JsonSimple parse ( String input ) throws IOException { ByteArrayInputStream bytes = new ByteArrayInputStream ( input . getBytes ( "UTF-8" ) ) ; return parse ( bytes ) ; }
A wrapper for Stream based parsing . This method accepts a String and will internally create a Stream for it .
46
21
22,691
public static JsonSimple parse ( InputStream input ) throws IOException { JsonSimple inputData = new JsonSimple ( input ) ; JsonSimple responseData = new JsonSimple ( ) ; // Go through every top level node JsonObject object = inputData . getJsonObject ( ) ; for ( Object key : object . keySet ( ) ) { // Ignoring some non-form related nodes String strKey = validString ( key ) ; if ( ! EXCLUDED_FIELDS . contains ( strKey ) ) { // And parse them into the repsonse String data = validString ( object . get ( key ) ) ; parseField ( responseData , strKey , data ) ; } } return responseData ; }
Accept and parse raw JSON data from an InputStream . Field name String literals will be broken down into meaningful JSON data structures .
155
26
22,692
private static String validString ( Object data ) throws IOException { // Null is ok if ( data == null ) { return "" ; } if ( ! ( data instanceof String ) ) { throw new IOException ( "Invalid non-String value found!" ) ; } return ( String ) data ; }
Ensures one of the generic objects coming from the JSON library is in fact a String .
62
19
22,693
private static void parseField ( JsonSimple response , String field , String data ) throws IOException { // Break it into pieces String [ ] fieldParts = field . split ( "\\." ) ; // These are used as replacable pointers // to the last object used on the path JsonObject lastObject = null ; JSONArray lastArray = null ; for ( int i = 0 ; i < fieldParts . length ; i ++ ) { // What is this segment? String segment = fieldParts [ i ] ; int number = parseInt ( segment ) ; //************************** // 1 (of 3) The first segment adds our // new empty object to the repsonse if ( i == 0 ) { JsonObject topObject = response . getJsonObject ( ) ; // Numbers aren't allowed here if ( number != - 1 ) { throw new IOException ( "Field '" + field + "' starts with" + " an array... this is illegal form data!" ) ; } // Really simple fields... just one segment if ( i + 1 == fieldParts . length ) { topObject . put ( segment , data ) ; // Longer field, but what to add? } else { String nextSegment = fieldParts [ i + 1 ] ; int nextNumber = parseInt ( nextSegment ) ; // Objects... nextSegment is a String key if ( nextNumber == - 1 ) { lastObject = getObject ( topObject , segment ) ; lastArray = null ; // Arrays... nextSegment is an integer index } else { lastObject = null ; lastArray = getArray ( topObject , segment ) ; } } } else { //************************** // 2 (of 3) The last segment is pretty simple if ( i == ( fieldParts . length - 1 ) ) { lastObject . put ( segment , data ) ; //************************** // 3 (of 3) Anything in between } else { // Check what comes next String nextSegment = fieldParts [ i + 1 ] ; int nextNumber = parseInt ( nextSegment ) ; // We are populating an object if ( lastArray == null ) { // So we shouldn't be looking at a number if ( number != - 1 ) { // In theory you'd need a logic bug to reach here; // illegal syntax should have been caught already. throw new IOException ( "Field '" + field + "' has an" + " illegal syntax!" ) ; } // Objects... nextSegment is a String key if ( nextNumber == - 1 ) { lastObject = getObject ( lastObject , segment ) ; lastArray = null ; // Arrays... nextSegment is an integer index } else { lastArray = getArray ( lastObject , segment ) ; lastObject = null ; } // Populating an array } else { // We should be looking at number if ( number == - 1 ) { // In theory you'd need a logic bug to reach here; // illegal syntax should have been caught already. throw new IOException ( "Field '" + field + "' has an" + " illegal syntax!" ) ; } // This is actually quite simple, because we can only // store objects. lastObject = getObject ( lastArray , number ) ; lastArray = null ; } } } } }
Parse an individual field into the response object .
684
10
22,694
private static JSONArray getArray ( JsonObject object , String key ) throws IOException { // Get the existing one if ( object . containsKey ( key ) ) { Object existing = object . get ( key ) ; if ( ! ( existing instanceof JSONArray ) ) { throw new IOException ( "Invalid field structure, '" + key + "' expected to be an array, but incompatible " + "data type already present." ) ; } return ( JSONArray ) existing ; // Or add a new one } else { JSONArray newObject = new JSONArray ( ) ; object . put ( key , newObject ) ; return newObject ; } }
Get a child JSON Array from an incoming JSON object . If the child does not exist it will be created .
135
22
22,695
private static JsonObject getObject ( JsonObject object , String key ) throws IOException { // Get the existing one if ( object . containsKey ( key ) ) { Object existing = object . get ( key ) ; if ( ! ( existing instanceof JsonObject ) ) { throw new IOException ( "Invalid field structure, '" + key + "' expected to be an object, but incompatible " + "data type already present." ) ; } return ( JsonObject ) existing ; // Or add a new one } else { JsonObject newObject = new JsonObject ( ) ; object . put ( key , newObject ) ; return newObject ; } }
Get a child JSON Object from an incoming JSON object . If the child does not exist it will be created .
140
22
22,696
private static int parseInt ( String integer ) throws IOException { try { int value = Integer . parseInt ( integer ) ; if ( value < 0 ) { throw new IOException ( "Invalid number in field name: '" + integer + "'" ) ; } return value ; } catch ( NumberFormatException ex ) { // It's not an integer return - 1 ; } }
Parse a String to an integer . This wrapper is simply to avoid the try catch statement repeatedly . Tests for - 1 are sufficient since it is illegal in form data . Valid integers below 1 throw exceptions because of this illegality .
79
46
22,697
@ Override public void init ( String jsonString ) throws TransformerException { try { setConfig ( new JsonSimpleConfig ( jsonString ) ) ; } catch ( IOException e ) { throw new TransformerException ( e ) ; } }
Initializes the plugin using the specified JSON String
51
9
22,698
private DigitalObject process ( DigitalObject in , String jsonConfig ) throws TransformerException { String oid = in . getId ( ) ; // Workflow payload JsonSimple workflow = null ; try { Payload workflowPayload = in . getPayload ( "workflow.metadata" ) ; workflow = new JsonSimple ( workflowPayload . open ( ) ) ; workflowPayload . close ( ) ; } catch ( StorageException ex ) { error ( "Error accessing workflow data from Object!\nOID: '" + oid + "'" , ex ) ; } catch ( IOException ex ) { error ( "Error parsing workflow data from Object!\nOID: '" + oid + "'" , ex ) ; } // Make sure it is live String step = workflow . getString ( null , "step" ) ; if ( step == null || ! step . equals ( "live" ) ) { log . warn ( "Object is not live! '{}'" , oid ) ; return in ; } // Make sure we have a title String title = workflow . getString ( null , Strings . NODE_FORMDATA , "title" ) ; if ( title == null ) { error ( "No title provided in Object form data!\nOID: '" + oid + "'" ) ; } // Object metadata Properties metadata = null ; try { metadata = in . getMetadata ( ) ; } catch ( StorageException ex ) { error ( "Error reading Object metadata!\nOID: '" + oid + "'" , ex ) ; } // Now that we have all the data we need, go do the real work return processObject ( in , workflow , metadata ) ; }
Top level wrapping method for a processing an object .
366
10
22,699
private DigitalObject processObject ( DigitalObject object , JsonSimple workflow , Properties metadata ) throws TransformerException { String oid = object . getId ( ) ; String title = workflow . getString ( null , Strings . NODE_FORMDATA , "title" ) ; FedoraClient fedora = null ; try { fedora = fedoraConnect ( ) ; } catch ( TransformerException ex ) { error ( "Error connecting to VITAL" , ex , oid , title ) ; } // Find out if we've sent it to VITAL before String vitalPid = metadata . getProperty ( Strings . PROP_VITAL_KEY ) ; if ( vitalPid != null ) { log . debug ( "Existing VITAL object: '{}'" , vitalPid ) ; // Make sure it exists, we'll test the DC datastream if ( ! datastreamExists ( fedora , vitalPid , "DC" ) ) { // How did this happen? Better let someone know String message = " !!! WARNING !!! The expected VITAL object '" + vitalPid + "' was not found. A new object will be created instead!" ; error ( message , null , oid , title ) ; vitalPid = null ; } } // A new VITAL object if ( vitalPid == null ) { try { vitalPid = createNewObject ( fedora , object . getId ( ) ) ; log . debug ( "New VITAL object created: '{}'" , vitalPid ) ; metadata . setProperty ( Strings . PROP_VITAL_KEY , vitalPid ) ; // Trigger a save on the object's metadata object . close ( ) ; } catch ( Exception ex ) { error ( "Failed to create object in VITAL" , ex , oid , title ) ; } } // Do we have any wait conditions to test? if ( ! waitProperties . isEmpty ( ) ) { boolean process = false ; for ( String test : waitProperties ) { String value = metadata . getProperty ( test ) ; if ( value != null ) { // We found a property we've been told to wait for log . info ( "Wait condition '{}' found." , test ) ; process = true ; } } // Are we continuing? if ( ! process ) { log . info ( "No wait conditions have been met, processing halted" ) ; return object ; } } // Need to make sure the object is active try { String isActive = metadata . getProperty ( Strings . PROP_VITAL_ACTIVE ) ; if ( isActive == null ) { log . info ( "Activating object in fedora: '{}'" , oid ) ; String cutTitle = title ; if ( cutTitle . length ( ) > 250 ) { cutTitle = cutTitle . substring ( 0 , 250 ) + "..." ; } fedora . getAPIM ( ) . modifyObject ( vitalPid , "A" , cutTitle , null , "ReDBox activating object: '" + oid + "'" ) ; // Record this so we don't do it again metadata . setProperty ( Strings . PROP_VITAL_ACTIVE , "true" ) ; object . close ( ) ; } } catch ( Exception ex ) { error ( "Failed to activate object in VITAL" , ex , oid , title ) ; } // Submit all the payloads to VITAL now try { processDatastreams ( fedora , object , vitalPid ) ; } catch ( Exception ex ) { error ( "Failed to send object to VITAL" , ex , oid , title ) ; } return object ; }
Middle level wrapping method for processing objects . Now we are looking at what actually needs to be done . Has the object already been put in VITAL or is it new .
786
34