idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
7,700
private void updateCursorObserver ( ) { Cursor newObservedCursor = getDataObserverCount ( ) > 0 ? mCursor : null ; if ( newObservedCursor != mObservedCursor ) { if ( mObservedCursor != null ) { mObservedCursor . unregisterContentObserver ( mCursorContentObserver ) ; } mObservedCursor = newObservedCursor ; if ( mObservedCursor != null ) { mObservedCursor . registerContentObserver ( mCursorContentObserver ) ; } } }
Registers or unregisters with the cursor . Idempotent .
7,701
private void closeCursor ( ) { if ( mCursor != null ) { int count = mCursor . getCount ( ) ; mCursor . close ( ) ; mCursor = null ; notifyItemRangeRemoved ( 0 , count ) ; } updateCursorObserver ( ) ; }
Closes the cursor notifying observers of data changes as necessary .
7,702
public void printElement ( String elementName , Object value ) { println ( "<" + elementName + ">" + ( value == null ? "" : escape ( value . toString ( ) ) ) + "</" + elementName + ">" ) ; }
Output a complete element with the given content .
7,703
public void printElement ( String elementName , String value , Map < String , String > attributes ) { print ( "<" + elementName ) ; for ( Entry < String , String > entry : attributes . entrySet ( ) ) { print ( " " + entry . getKey ( ) + "=\"" + escape ( entry . getValue ( ) ) + "\"" ) ; } if ( value != null ) { println ( ">" + escape ( value ) + "</" + elementName + ">" ) ; } else { println ( "/>" ) ; } }
Output a complete element with the given content and attributes .
7,704
public String escape ( String in ) { StringBuffer out = new StringBuffer ( ) ; for ( char c : in . toCharArray ( ) ) { switch ( c ) { case '<' : out . append ( "&lt;" ) ; break ; case '>' : out . append ( "&gt;" ) ; break ; case '&' : out . append ( "&amp;" ) ; break ; case '"' : out . append ( "&quot;" ) ; break ; default : out . append ( c ) ; } } return out . toString ( ) ; }
Translate reserved XML characters to XML entities .
7,705
public static String removeNewLines ( String textContent ) { if ( textContent == null ) { return "" ; } StringBuilder s = new StringBuilder ( ) ; boolean inNl = false ; for ( char c : textContent . toCharArray ( ) ) { if ( c == '\n' ) { if ( ! inNl ) { s . append ( ' ' ) ; inNl = true ; } } else { inNl = false ; s . append ( c ) ; } } return s . toString ( ) ; }
Replace multiple newline characters with a single space .
7,706
public void buildAll ( MessageMLParser context , org . w3c . dom . Element element ) throws InvalidInputException , ProcessingException { NamedNodeMap attr = element . getAttributes ( ) ; for ( int i = 0 ; i < attr . getLength ( ) ; i ++ ) { buildAttribute ( attr . item ( i ) ) ; } NodeList children = element . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { buildNode ( context , children . item ( i ) ) ; } }
Process a DOM element descending into its children and construct the output MessageML tree .
7,707
void buildAttribute ( org . w3c . dom . Node item ) throws InvalidInputException { switch ( item . getNodeName ( ) ) { case CLASS_ATTR : attributes . put ( CLASS_ATTR , getStringAttribute ( item ) ) ; break ; case STYLE_ATTR : final String styleAttribute = getStringAttribute ( item ) ; Styles . validate ( styleAttribute ) ; attributes . put ( STYLE_ATTR , styleAttribute ) ; break ; default : throw new InvalidInputException ( "Attribute \"" + item . getNodeName ( ) + "\" is not allowed in \"" + getMessageMLTag ( ) + "\"" ) ; } }
Parse a DOM attribute into MessageML element properties .
7,708
private void buildNode ( MessageMLParser context , org . w3c . dom . Node node ) throws InvalidInputException , ProcessingException { switch ( node . getNodeType ( ) ) { case org . w3c . dom . Node . TEXT_NODE : buildText ( ( Text ) node ) ; break ; case org . w3c . dom . Node . ELEMENT_NODE : buildElement ( context , ( org . w3c . dom . Element ) node ) ; break ; default : throw new InvalidInputException ( "Invalid element \"" + node . getNodeName ( ) + "\"" ) ; } }
Build a text node or a MessageML element based on the provided DOM node .
7,709
private void buildElement ( MessageMLParser context , org . w3c . dom . Element element ) throws InvalidInputException , ProcessingException { Element child = context . createElement ( element , this ) ; child . buildAll ( context , element ) ; child . validate ( ) ; addChild ( child ) ; }
Build a MessageML element based on the provided DOM element and descend into its children .
7,710
void buildMarkdown ( Node parent ) throws InvalidInputException { for ( Element child : this . children ) { Node node = child . asMarkdown ( ) ; if ( node != null ) { parent . appendChild ( node ) ; } else { node = parent ; } child . buildMarkdown ( node ) ; } }
Traverse the element and its children to construct its representation as a Markdown tree .
7,711
void buildEntityJson ( ObjectNode parent ) { for ( Element child : this . children ) { ObjectNode node = child . asEntityJson ( parent ) ; if ( node != null ) { child . buildEntityJson ( node ) ; } else { child . buildEntityJson ( parent ) ; } } }
Traverse the element and its children to construct its representation as EntityJSON nodes .
7,712
void asPresentationML ( XmlPrintStream out ) { out . openElement ( getMessageMLTag ( ) , getAttributes ( ) ) ; for ( Element child : getChildren ( ) ) { child . asPresentationML ( out ) ; } out . closeElement ( ) ; }
Print a PresentationML representation of the element and its children to the provided PrintStream .
7,713
public String asText ( ) { StringBuilder b = new StringBuilder ( ) ; for ( Element child : children ) { b . append ( child . asText ( ) ) ; } return b . toString ( ) ; }
Return a text representation of the element descending into its children .
7,714
Long getLongAttribute ( org . w3c . dom . Node attribute ) throws InvalidInputException { String s = getStringAttribute ( attribute ) ; if ( s == null ) { return null ; } try { return Long . parseLong ( s ) ; } catch ( NumberFormatException e ) { throw new InvalidInputException ( "Invalid input: " + attribute . getNodeName ( ) + " must be a int64 value not \"" + s + "\"" ) ; } }
Get a DOM attribute as a Long value .
7,715
Boolean getBooleanAttribute ( org . w3c . dom . Node attribute ) { String s = getStringAttribute ( attribute ) ; if ( s == null ) { return null ; } return Boolean . parseBoolean ( s ) ; }
Get a DOM attribute as a Boolean value .
7,716
URI getUrlAttribute ( org . w3c . dom . Node attribute ) throws InvalidInputException { String s = getStringAttribute ( attribute ) ; if ( s == null ) { return null ; } try { return new URI ( s ) ; } catch ( URISyntaxException e ) { throw new InvalidInputException ( "Invalid input: " + attribute . getLocalName ( ) + " must be a URI value not \"" + s + "\"" ) ; } }
Get a DOM attribute as a URI .
7,717
void assertNoText ( ) throws InvalidInputException { for ( Element child : this . getChildren ( ) ) if ( child instanceof TextNode && StringUtils . isNotBlank ( ( ( TextNode ) child ) . getText ( ) ) ) { throw new InvalidInputException ( "Element \"" + this . getMessageMLTag ( ) + "\" may not have text content" ) ; } }
Check that the element has no text content .
7,718
void assertPhrasingContent ( ) throws InvalidInputException { assertContentModel ( Arrays . asList ( TextNode . class , Link . class , Chime . class , Bold . class , Italic . class , Image . class , LineBreak . class , Span . class , Emoji . class , HashTag . class , CashTag . class , Mention . class ) ) ; }
Check that the element s children are limited to phrasing content .
7,719
void assertContentModel ( Collection < Class < ? extends Element > > permittedChildren ) throws InvalidInputException { for ( Element child : this . getChildren ( ) ) { if ( ! permittedChildren . contains ( child . getClass ( ) ) ) { if ( child instanceof TextNode && StringUtils . isBlank ( ( ( TextNode ) child ) . getText ( ) ) ) { continue ; } throw new InvalidInputException ( "Element \"" + child . getMessageMLTag ( ) + "\" is not allowed in \"" + this . getMessageMLTag ( ) + "\"" ) ; } } }
Check that the element s children are limited to allowed element types .
7,720
void assertParent ( Collection < Class < ? extends Element > > permittedParents ) throws InvalidInputException { if ( ! permittedParents . contains ( this . getParent ( ) . getClass ( ) ) ) { throw new InvalidInputException ( "Element \"" + this . getMessageMLTag ( ) + "\" is not allowed as a child of \"" + this . getParent ( ) . getMessageMLTag ( ) + "\"" ) ; } }
Check that the element s allowed parents are limited to the specified element types .
7,721
private void visitChildren ( Node parent , Collection < Class < ? extends Node > > includeNodes ) { Node child = parent . getFirstChild ( ) ; while ( child != null ) { Node next = child . getNext ( ) ; if ( includeNodes . contains ( child . getClass ( ) ) ) { child . accept ( this ) ; } else { visitChildren ( child , includeNodes ) ; } child = next ; } }
Recursively visit the children of the node processing only those specified by the parameter includeNodes .
7,722
public IEntityJsonSchemaContext validate ( EntityJsonParser parser ) throws SchemaValidationException , NoSchemaException , InvalidSchemaException { StringBuffer ubuf = new StringBuffer ( "https://symphonyosf.github.io/symphony-object/proposed" ) ; for ( String part : type_ . split ( "\\." ) ) { ubuf . append ( "/" ) ; ubuf . append ( part ) ; } ubuf . append ( "-v" ) ; ubuf . append ( majorVersion_ ) ; ubuf . append ( "_" ) ; ubuf . append ( minorVersion_ ) ; ubuf . append ( ".json" ) ; try { return parser . validate ( new URL ( ubuf . toString ( ) ) , instanceSource_ , jsonNode_ ) ; } catch ( MalformedURLException e ) { throw new InvalidSchemaException ( null , e ) ; } }
Validate this object against the specific schema for this type from the official repo .
7,723
private String enrichMarkdown ( String message , JsonNode entitiesNode , JsonNode mediaNode ) throws InvalidInputException { TreeMap < Integer , JsonNode > entities = new TreeMap < > ( ) ; TreeMap < Integer , JsonNode > media = new TreeMap < > ( ) ; if ( entitiesNode != null ) { validateEntities ( entitiesNode ) ; for ( JsonNode node : entitiesNode . findParents ( INDEX_START ) ) { entities . put ( node . get ( INDEX_START ) . intValue ( ) , node ) ; } } if ( mediaNode != null ) { validateMedia ( mediaNode ) ; for ( JsonNode node : mediaNode . findParents ( INDEX ) ) { media . put ( node . get ( INDEX ) . intValue ( ) , node . get ( TEXT ) ) ; } } int lastIndex = Math . max ( ( ! entities . isEmpty ( ) ) ? entities . lastKey ( ) : 0 , ( ! media . isEmpty ( ) ) ? media . lastKey ( ) : 0 ) ; if ( message . length ( ) <= lastIndex ) { message = StringUtils . rightPad ( message , lastIndex + 1 ) ; } StringBuilder output = new StringBuilder ( ) ; for ( int i = 0 ; i < message . length ( ) ; i ++ ) { char c = message . charAt ( i ) ; if ( entities . containsKey ( i ) ) { JsonNode entity = entities . get ( i ) ; String entityType = entity . get ( TYPE ) . asText ( ) . toUpperCase ( ) ; String id = entity . get ( ID ) . asText ( ) ; output . append ( ENTITY_DELIMITER ) ; output . append ( entityType ) . append ( FIELD_DELIMITER ) ; output . append ( id ) ; output . append ( ENTITY_DELIMITER ) ; int endIndex = entity . get ( INDEX_END ) . intValue ( ) - 1 ; i = Math . max ( endIndex , i ) ; } else if ( media . containsKey ( i ) ) { JsonNode table = media . get ( i ) ; output . append ( ENTITY_DELIMITER ) ; output . append ( TABLE ) . append ( FIELD_DELIMITER ) ; for ( JsonNode row : table ) { for ( JsonNode cell : row ) { String text = cell . asText ( ) ; output . append ( text ) . append ( RECORD_DELIMITER ) ; } output . append ( GROUP_DELIMITER ) ; } output . append ( ENTITY_DELIMITER ) ; output . append ( c ) ; } else { output . append ( c ) ; } } return output . toString ( ) ; }
Generate intermediate markup to delimit custom nodes representing entities for further processing by the Markdown parser .
7,724
private void validateEntities ( JsonNode data ) throws InvalidInputException { for ( JsonNode node : data . findParents ( INDEX_START ) ) { for ( String key : new String [ ] { INDEX_START , INDEX_END , ID , TYPE } ) { if ( node . path ( key ) . isMissingNode ( ) ) { throw new InvalidInputException ( "Required field \"" + key + "\" missing from the entity payload" ) ; } } int startIndex = node . get ( INDEX_START ) . intValue ( ) ; int endIndex = node . get ( INDEX_END ) . intValue ( ) ; if ( endIndex <= startIndex ) { throw new InvalidInputException ( String . format ( "Invalid entity payload: %s (start index: %s, end index: %s)" , node . get ( ID ) . textValue ( ) , startIndex , endIndex ) ) ; } } }
Verify that JSON entities contain the required fields and that entity indices are correct .
7,725
private void validateMedia ( JsonNode data ) throws InvalidInputException { for ( JsonNode node : data . findParents ( INDEX ) ) { JsonNode text = node . path ( TEXT ) ; if ( ! text . isMissingNode ( ) && ( ! text . isArray ( ) || ! text . get ( 0 ) . isArray ( ) ) ) { throw new InvalidInputException ( String . format ( "Invalid table payload: %s (index: %s)" , text . asText ( ) , node . get ( INDEX ) ) ) ; } } }
Verify that JSON media node contains valid table payload .
7,726
public MessageML parse ( String message , JsonNode entities , JsonNode media ) throws InvalidInputException { this . index = 0 ; message = message . replace ( ( char ) 160 , ( char ) 32 ) ; String enriched = enrichMarkdown ( message , entities , media ) ; Node markdown = MARKDOWN_PARSER . parse ( enriched ) ; markdown . accept ( this ) ; return messageML ; }
Parse the Markdown message and entity JSON into a MessageML document .
7,727
public void align ( Object ... o ) { int i = 0 ; String s [ ] = new String [ o . length ] ; for ( int ii = 0 ; ii < o . length ; ii ++ ) { if ( o [ ii ] != null ) { s [ ii ] = o [ ii ] . toString ( ) ; } } while ( i < s . length && i < maxColumnLength . size ( ) ) { int l = ( s [ i ] == null ? 0 : s [ i ] . length ( ) ) ; if ( maxColumnLength . get ( i ) < l ) { maxColumnLength . set ( i , l ) ; } i ++ ; } while ( i < s . length ) { maxColumnLength . add ( ( s [ i ] == null ? 0 : s [ i ] . length ( ) ) ) ; i ++ ; } rows . add ( s ) ; }
Add a row to the block each String represents a piece of text which should be aligned .
7,728
public void print ( String separator , String terminator ) { for ( int i = 0 ; i < maxColumnLength . size ( ) ; i ++ ) { maxColumnLength . set ( i , ( ( ( maxColumnLength . get ( i ) / TAB_SIZE ) + 1 ) * TAB_SIZE ) ) ; } for ( int r = 0 ; r < rows . size ( ) ; r ++ ) { String [ ] s = rows . get ( r ) ; for ( int i = 0 ; i < s . length ; i ++ ) { out . print ( s [ i ] ) ; if ( i < s . length - 1 ) { for ( int l = ( s [ i ] == null ? 0 : s [ i ] . length ( ) ) ; l < maxColumnLength . get ( i ) ; l ++ ) { out . print ( ' ' ) ; } } } if ( separator != null && r < rows . size ( ) - 1 ) { out . println ( separator ) ; } else if ( terminator != null && r == rows . size ( ) - 1 ) { out . println ( terminator ) ; } else { out . println ( ) ; } } }
Outputs the block with the given separator appended to each line except the last and the given terminator appended to the last line .
7,729
public String getPresentationML ( ) throws IllegalStateException { if ( messageML == null ) { throw new IllegalStateException ( "The message hasn't been parsed yet. " + "Please call MessageMLContext.parse() first." ) ; } ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; XmlPrintStream out = new XmlPrintStream ( bout ) ; out . setNoIndent ( true ) ; out . setNoNl ( true ) ; messageML . asPresentationML ( out ) ; out . close ( ) ; return bout . toString ( ) ; }
Retrieve a string representation of the message in PresentationML .
7,730
public static void validate ( String styleAttribute ) throws InvalidInputException { try { final Map < String , String > styleMap = Splitter . on ( ";" ) . omitEmptyStrings ( ) . withKeyValueSeparator ( ":" ) . split ( styleAttribute ) ; final HashSet < String > inputStyleProperties = new HashSet < > ( styleMap . keySet ( ) ) ; inputStyleProperties . removeAll ( ALLOWED_PROPERTIES ) ; if ( ! inputStyleProperties . isEmpty ( ) ) { throw new InvalidInputException ( "Invalid property(s): [" + Joiner . on ( "," ) . join ( inputStyleProperties ) + "] in the \"style\" attribute" ) ; } } catch ( IllegalArgumentException ex ) { throw new InvalidInputException ( "Unparseable \"style\" attribute: " + styleAttribute , ex ) ; } }
Validate that the input style attribute is allowed
7,731
MessageML parse ( String message , String entityJson , String version ) throws InvalidInputException , ProcessingException , IOException { this . index = 0 ; String expandedMessage ; if ( StringUtils . isBlank ( message ) ) { throw new InvalidInputException ( "Error parsing message: the message cannot be null or empty" ) ; } if ( StringUtils . isNotBlank ( entityJson ) ) { try { this . entityJson = ( ObjectNode ) MAPPER . readTree ( entityJson ) ; } catch ( JsonProcessingException e ) { throw new InvalidInputException ( "Error parsing EntityJSON: " + e . getMessage ( ) ) ; } } else { this . entityJson = new ObjectNode ( JsonNodeFactory . instance ) ; } try { expandedMessage = expandTemplates ( message , this . entityJson ) ; } catch ( IOException e ) { throw new InvalidInputException ( "Error parsing EntityJSON: " + e . getMessage ( ) ) ; } catch ( TemplateException e ) { throw new InvalidInputException ( String . format ( "Error parsing Freemarker template: invalid input at line %s, " + "column %s" , e . getLineNumber ( ) , e . getColumnNumber ( ) ) ) ; } this . messageML = parseMessageML ( expandedMessage , version ) ; if ( this . messageML != null ) { this . entityJson = this . messageML . asEntityJson ( this . entityJson ) ; return this . messageML ; } throw new ProcessingException ( "Internal error. Generated null MessageML from valid input" ) ; }
Parse the text contents of the message and optionally EntityJSON into a MessageMLV2 message . Expands Freemarker templates and generates a MessageML document tree .
7,732
private static void validateMessageText ( String messageML ) throws InvalidInputException { if ( messageML == null ) { throw new InvalidInputException ( "Message input is NULL" ) ; } for ( char ch : messageML . toCharArray ( ) ) { if ( ch != '\n' && ch != '\r' && ch != '\t' && ( ch < ' ' ) ) { throw new InvalidInputException ( "Invalid control characters in message" ) ; } } }
Check the input message text for null value and restricted characters .
7,733
private String expandTemplates ( String message , JsonNode entityJson ) throws IOException , TemplateException { Map < String , Object > data = new HashMap < > ( ) ; data . put ( "data" , MAPPER . convertValue ( entityJson , Map . class ) ) ; data . put ( "entity" , MAPPER . convertValue ( entityJson , Map . class ) ) ; StringWriter sw = new StringWriter ( ) ; Template template = new Template ( "messageML" , message , FREEMARKER ) ; template . process ( data , sw ) ; return sw . toString ( ) ; }
Expand Freemarker templates .
7,734
private MessageML parseMessageML ( String messageML , String version ) throws InvalidInputException , ProcessingException { validateMessageText ( messageML ) ; org . w3c . dom . Element docElement = parseDocument ( messageML ) ; validateEntities ( docElement , entityJson ) ; switch ( docElement . getTagName ( ) ) { case MessageML . MESSAGEML_TAG : this . messageFormat = FormatEnum . MESSAGEML ; if ( StringUtils . isBlank ( version ) ) { version = MessageML . MESSAGEML_VERSION ; } break ; case MessageML . PRESENTATIONML_TAG : this . messageFormat = FormatEnum . PRESENTATIONML ; break ; default : throw new InvalidInputException ( "Root tag must be <" + MessageML . MESSAGEML_TAG + ">" + " or <" + MessageML . PRESENTATIONML_TAG + ">" ) ; } MessageML result = new MessageML ( messageFormat , version ) ; result . buildAll ( this , docElement ) ; result . validate ( ) ; return result ; }
Parse the message string into its MessageML representation .
7,735
org . w3c . dom . Element parseDocument ( String messageML ) throws InvalidInputException , ProcessingException { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory . newInstance ( ) ; dbFactory . setXIncludeAware ( false ) ; dbFactory . setExpandEntityReferences ( false ) ; dbFactory . setIgnoringElementContentWhitespace ( true ) ; dbFactory . setFeature ( "http://apache.org/xml/features/nonvalidating/load-external-dtd" , false ) ; dbFactory . setFeature ( "http://apache.org/xml/features/disallow-doctype-decl" , true ) ; DocumentBuilder dBuilder = dbFactory . newDocumentBuilder ( ) ; dBuilder . setErrorHandler ( new NullErrorHandler ( ) ) ; dBuilder . setEntityResolver ( new NoOpEntityResolver ( ) ) ; StringReader sr = new StringReader ( messageML ) ; ReaderInputStream ris = new ReaderInputStream ( sr ) ; Document doc = dBuilder . parse ( ris ) ; doc . getDocumentElement ( ) . normalize ( ) ; return doc . getDocumentElement ( ) ; } catch ( SAXException e ) { throw new InvalidInputException ( "Invalid messageML: " + e . getMessage ( ) , e ) ; } catch ( ParserConfigurationException | IOException e ) { throw new ProcessingException ( "Failed to parse messageML" , e ) ; } }
Parse the message string into a DOM element tree .
7,736
public void align ( Object ... s ) { if ( alignedBlock == null ) { alignedBlock = new AlignedBlock ( this ) ; } alignedBlock . align ( s ) ; }
Takes an array of strings to be aligned in separate columns and adds them to the alignedblock
7,737
private void printAlignedBlock ( String separator , String terminator ) { if ( alignedBlock != null ) { alignedBlock . print ( separator , terminator ) ; alignedBlock = null ; } }
Prints the alignedblock with all strings aligned in columns dependent on the order in which they were declared in Align
7,738
public void println ( int tempIndent , char x ) { if ( startOfLine ) { doIndent ( tempIndent ) ; } super . println ( x ) ; startOfLine = true ; }
Indent the current line and print a character on the same line then print a line break
7,739
public void println ( int tempIndent , String x ) { if ( startOfLine ) { doIndent ( tempIndent ) ; } if ( noNl ) { super . print ( x ) ; } else { super . println ( x ) ; if ( oNlCr ) { super . write ( '\r' ) ; } } startOfLine = true ; }
Indent the current line and print a string on the same line then print a line break
7,740
public void print ( String pattern , Object ... arguments ) { print ( String . format ( pattern , arguments ) ) ; }
Convenience method for calling string . format and printing
7,741
public void println ( String pattern , Object ... arguments ) { println ( String . format ( pattern , arguments ) ) ; }
Convenience method for calling string . format and printing with line breaks
7,742
public String peek ( int count ) { return str . substring ( cursor , cursor + Math . min ( count , str . length ( ) - cursor ) ) ; }
What are the next characters that will be read?
7,743
public String read ( int count ) { if ( count < 0 ) throw new ParseException ( "use Rewind to seek back" ) ; int safecount = Math . min ( count , str . length ( ) - cursor ) ; if ( safecount == 0 && count > 0 ) throw new ParseException ( "no more data" ) ; String result = str . substring ( cursor , cursor + safecount ) ; cursor += safecount ; return result ; }
Read a number of characters .
7,744
public String readUntil ( char sentinel ) { int i = str . indexOf ( sentinel , cursor ) ; if ( i >= 0 ) { int from = cursor ; cursor = i + 1 ; return str . substring ( from , i ) ; } throw new ParseException ( "terminator not found" ) ; }
Read everything until one the sentinel which must exist in the string . Sentinel char is read but not returned in the result .
7,745
public String readWhile ( String accepted ) { int start = cursor ; while ( cursor < str . length ( ) ) { if ( accepted . indexOf ( str . charAt ( cursor ) ) >= 0 ) ++ cursor ; else break ; } return str . substring ( start , cursor ) ; }
Read everything as long as the char occurs in the accepted characters .
7,746
public String rest ( ) { if ( cursor >= str . length ( ) ) throw new ParseException ( "no more data" ) ; String result = str . substring ( cursor ) ; cursor = str . length ( ) ; return result ; }
Returns the rest of the data until the end .
7,747
public Object getData ( IDictToInstance dictConverter ) { ObjectifyVisitor v = new ObjectifyVisitor ( dictConverter ) ; this . accept ( v ) ; return v . getObject ( ) ; }
get the actual data as Java objects .
7,748
public Ast parse ( String expression ) { Ast ast = new Ast ( ) ; if ( expression == null || expression . length ( ) == 0 ) return ast ; SeekableStringReader sr = new SeekableStringReader ( expression ) ; if ( sr . peek ( ) == '#' ) sr . readUntil ( '\n' ) ; try { ast . root = parseExpr ( sr ) ; sr . skipWhitespace ( ) ; if ( sr . hasMore ( ) ) throw new ParseException ( "garbage at end of expression" ) ; return ast ; } catch ( ParseException x ) { String faultLocation = extractFaultLocation ( sr ) ; throw new ParseException ( x . getMessage ( ) + " (at position " + sr . bookmark ( ) + "; '" + faultLocation + "')" , x ) ; } }
Parse from a string with the Python literal expression
7,749
public FDSObject getObject ( String bucketName , String objectName , long pos ) throws GalaxyFDSClientException { return this . getObject ( bucketName , objectName , null , pos ) ; }
range mode for getobject while not be autoReConnection
7,750
public void putClientMetrics ( ClientMetrics clientMetrics ) throws GalaxyFDSClientException { URI uri = formatUri ( fdsConfig . getBaseUri ( ) , "" , ( SubResource [ ] ) null ) ; ContentType contentType = ContentType . APPLICATION_JSON ; HashMap < String , String > params = new HashMap < String , String > ( ) ; params . put ( "clientMetrics" , "" ) ; HttpEntity requestEntity = getJsonStringEntity ( clientMetrics , contentType ) ; HttpUriRequest httpRequest = prepareRequestMethod ( uri , HttpMethod . PUT , contentType , null , params , null , requestEntity ) ; HttpResponse response = executeHttpRequest ( httpRequest , Action . PutClientMetrics ) ; processResponse ( response , null , "put client metrics" ) ; }
Put client metrics to server . This method should only be used internally .
7,751
public void setInputStream ( InputStream inputStream , long inputStreamLength ) { if ( this . isUploadFile ) { try { this . inputStream . close ( ) ; } catch ( Exception e ) { } } if ( inputStream instanceof FDSProgressInputStream ) { this . inputStream = ( FDSProgressInputStream ) inputStream ; } else { this . inputStream = new FDSProgressInputStream ( inputStream , this . progressListener ) ; } if ( this . progressListener != null ) { this . progressListener . setTransferred ( 0 ) ; this . progressListener . setTotal ( inputStreamLength ) ; } this . isUploadFile = false ; this . inputStreamLength = inputStreamLength ; }
Auto convert inputStream to FDSProgressInputStream in order to invoke progress listener
7,752
public void setFile ( File file ) throws FileNotFoundException { this . setInputStream ( new BufferedInputStream ( new FileInputStream ( file ) ) , file . length ( ) ) ; this . isUploadFile = true ; }
Upload file as inputStream
7,753
protected void service ( HttpServletRequest req , HttpServletResponse resp ) throws IOException , ServletException { SessionConfiguration config = Server . createSessionConfiguration ( ) ; if ( oAuth2Credentials == null ) { oAuth2Credentials = Server . createOAuth2Credentials ( config ) ; } HttpSession httpSession = req . getSession ( true ) ; if ( httpSession . getAttribute ( Server . USER_SESSION_ID ) == null ) { httpSession . setAttribute ( Server . USER_SESSION_ID , new Random ( ) . nextLong ( ) ) ; } credential = oAuth2Credentials . loadCredential ( httpSession . getAttribute ( Server . USER_SESSION_ID ) . toString ( ) ) ; if ( credential != null && credential . getAccessToken ( ) != null ) { if ( uberRidesService == null ) { CredentialsSession session = new CredentialsSession ( config , credential ) ; UberRidesApi api = UberRidesApi . with ( session ) . build ( ) ; uberRidesService = api . createService ( ) ; } super . service ( req , resp ) ; } else { resp . sendRedirect ( oAuth2Credentials . getAuthorizationUrl ( ) ) ; } }
Before each request fetch an OAuth2 credential for the user or redirect them to the OAuth2 login page instead .
7,754
private static Credential authenticate ( String userId , SessionConfiguration config ) throws Exception { OAuth2Credentials oAuth2Credentials = createOAuth2Credentials ( config ) ; Credential credential = oAuth2Credentials . loadCredential ( userId ) ; if ( credential == null || credential . getAccessToken ( ) == null ) { System . out . printf ( "Add the following redirect URI to your developer.uber.com application: %s%n" , oAuth2Credentials . getRedirectUri ( ) ) ; System . out . println ( "Press Enter when done." ) ; System . in . read ( ) ; String authorizationUrl = oAuth2Credentials . getAuthorizationUrl ( ) ; System . out . printf ( "In your browser, navigate to: %s%n" , authorizationUrl ) ; System . out . println ( "Waiting for authentication..." ) ; String authorizationCode = localServerReceiver . waitForCode ( ) ; System . out . println ( "Authentication received." ) ; credential = oAuth2Credentials . authenticate ( authorizationCode , userId ) ; } localServerReceiver . stop ( ) ; return credential ; }
Authenticate the given user . If you are distributing an installed application this method should exist on your server so that the client ID and secret are not shared with the end user .
7,755
public String getAuthorizationUrl ( ) throws UnsupportedEncodingException { String authorizationCodeRequestUrl = authorizationCodeFlow . newAuthorizationUrl ( ) . setScopes ( scopes ) . build ( ) ; if ( redirectUri != null ) { authorizationCodeRequestUrl += "&redirect_uri=" + URLEncoder . encode ( redirectUri , "UTF-8" ) ; } return authorizationCodeRequestUrl ; }
Gets the authorization URL to retrieve the authorization code .
7,756
public void clearCredential ( String userId ) throws AuthException { try { authorizationCodeFlow . getCredentialDataStore ( ) . delete ( userId ) ; } catch ( IOException e ) { throw new AuthException ( "Unable to clear credential." , e ) ; } }
Clears the credential for the user in the underlying (
7,757
protected final < U extends GenericEvent > void bind ( EventBus eventBus , List < HandlerRegistration > registrations , Class < U > type , GenericEventHandler handler ) { registrations . add ( eventBus . addHandler ( GenericEventType . getTypeOf ( type ) , handler ) ) ; }
Registers the given handler for the given event class on the given event bus . Factored out into a method here instead of generated directly in order to simplify the generated code and save a little space .
7,758
private static Set < ClassTemplateSpec > findTopLevelTypes ( ClassTemplateSpec spec ) { Set < ClassTemplateSpec > specs = new HashSet < ClassTemplateSpec > ( ClassTemplateSpecs . allReferencedTypes ( spec ) ) ; specs . add ( spec ) ; Iterator < ClassTemplateSpec > iterator = specs . iterator ( ) ; while ( iterator . hasNext ( ) ) { ClassTemplateSpec entry = iterator . next ( ) ; if ( entry . getEnclosingClass ( ) != null ) { iterator . remove ( ) ; } } return specs ; }
Currently one ClassDefinition is provided per . pdsc file . But some of those . pdsc contain inline schema definitions that should be generated into top level classes .
7,759
private static String escapeKeyword ( String symbol , EscapeStrategy strategy ) { if ( tsKeywords . contains ( symbol ) ) { if ( strategy . equals ( EscapeStrategy . MANGLE ) ) { return symbol + "$" ; } else { return "\"" + symbol + "\"" ; } } else { return symbol ; } }
Returns the escaped Pegasus symbol for use in Typescript source code .
7,760
private static String docComment ( String doc , Object deprecation ) { StringBuilder docStr = new StringBuilder ( ) ; if ( doc != null ) { docStr . append ( doc . trim ( ) ) ; } if ( deprecation != null ) { docStr . append ( "\n\n" ) . append ( "@deprecated" ) ; if ( deprecation instanceof String ) { docStr . append ( " " ) . append ( ( ( String ) deprecation ) . trim ( ) ) ; } } return DocEscaping . stringToDocComment ( docStr . toString ( ) , DocCommentStyle . ASTRISK_MARGIN ) ; }
Return a full tsdoc for a type .
7,761
String typeNameQualifiedByEnclosingClass ( TSTypeSyntax syntax ) { if ( syntax instanceof TSEnclosedTypeSyntax ) { return ( ( TSEnclosedTypeSyntax ) syntax ) . typeNameQualifiedByEnclosedType ( ) ; } else { return syntax . typeName ( ) ; } }
Returns the type name prefaced with the enclosing class name if there was one .
7,762
public TSTyperefSyntax TSTyperefSyntaxCreate ( TyperefTemplateSpec template ) { return new TSTyperefSyntax ( template , template . getSchema ( ) , new TSNamedTypeSyntax ( template . getSchema ( ) ) ) ; }
Create a new TyperefSyntax
7,763
private static boolean allowCustomClass ( DataSchema schema ) { boolean result = false ; final DataSchema . Type type = schema . getType ( ) ; if ( type == DataSchema . Type . TYPEREF || type == DataSchema . Type . RECORD ) { final DataSchema dereferencedSchema = schema . getDereferencedDataSchema ( ) ; if ( dereferencedSchema . getType ( ) == DataSchema . Type . RECORD || ( CodeUtil . isDirectType ( dereferencedSchema ) && dereferencedSchema . getType ( ) != DataSchema . Type . ENUM ) ) { result = true ; } } return result ; }
Allow custom class to to bound to record or typeref of primitive types that are not enums .
7,764
private ClassTemplateSpec createFromDataSchema ( DataSchema schema ) { if ( schema instanceof MapDataSchema ) { return new CourierMapTemplateSpec ( ( MapDataSchema ) schema ) ; } return ClassTemplateSpec . createFromDataSchema ( schema ) ; }
For Courier use CourierMapTemplateSpec for maps .
7,765
public BracePair [ ] getPairs ( ) { return new BracePair [ ] { new BracePair ( CourierTypes . OPEN_BRACE , CourierTypes . CLOSE_BRACE , true ) , new BracePair ( CourierTypes . OPEN_BRACKET , CourierTypes . CLOSE_BRACKET , false ) , new BracePair ( CourierTypes . OPEN_PAREN , CourierTypes . CLOSE_PAREN , false ) } ; }
Returns the array of definitions for brace pairs that need to be matched when editing code in the language .
7,766
private String parse ( DocumentContext document ) throws ParseException { if ( document . namespaceDeclaration ( ) != null ) { setCurrentNamespace ( document . namespaceDeclaration ( ) . qualifiedIdentifier ( ) . value ) ; } else { setCurrentNamespace ( "" ) ; } setCurrentImports ( document . importDeclarations ( ) ) ; NamedDataSchema schema = parseNamedType ( document . namedTypeDeclaration ( ) ) ; topLevelSchemas . add ( schema ) ; return schema . getFullName ( ) ; }
Parse list of Data objects .
7,767
private void addPropertiesAtPath ( Map < String , Object > existingProperties , PropDeclarationContext prop ) throws ParseException { addPropertiesAtPath ( prop , existingProperties , prop . path , parsePropValue ( prop ) ) ; }
Adds additional properties to an existing properties map at the location identified by the given PropDeclarationContexts path .
7,768
private void addPropertiesAtPath ( ParserRuleContext context , Map < String , Object > existingProperties , Iterable < String > path , Object value ) throws ParseException { Map < String , Object > current = existingProperties ; Iterator < String > iter = path . iterator ( ) ; while ( iter . hasNext ( ) ) { String pathPart = iter . next ( ) ; if ( iter . hasNext ( ) ) { if ( existingProperties . containsKey ( pathPart ) ) { Object val = existingProperties . get ( pathPart ) ; if ( ! ( val instanceof DataMap ) ) { throw new ParseException ( new ParseError ( new ParseErrorLocation ( context ) , "Conflicting property: " + path . toString ( ) ) ) ; } current = ( DataMap ) val ; } else { DataMap next = new DataMap ( ) ; current . put ( pathPart , next ) ; current = next ; } } else { if ( current . containsKey ( pathPart ) ) { throw new ParseException ( new ParseError ( new ParseErrorLocation ( context ) , "Property already defined: " + path . toString ( ) ) ) ; } else { current . put ( pathPart , value ) ; } } } }
Adds additional properties to an existing properties map at the location identified by the given path .
7,769
public String computeFullName ( String name ) { String fullname ; DataSchema schema = DataSchemaUtil . typeStringToPrimitiveDataSchema ( name ) ; if ( schema != null ) { fullname = name ; } else if ( Name . isFullName ( name ) || getCurrentNamespace ( ) . isEmpty ( ) ) { fullname = name ; } else if ( currentImports . containsKey ( name ) ) { fullname = currentImports . get ( name ) . getFullName ( ) ; } else { fullname = getCurrentNamespace ( ) + "." + name ; } return fullname ; }
Extended fullname computation to handle imports
7,770
public static Number toNumber ( String string ) { BigDecimal value = new BigDecimal ( string ) ; try { long l = value . longValueExact ( ) ; int i = ( int ) l ; if ( ( long ) i == l ) { return i ; } else { return l ; } } catch ( ArithmeticException e ) { double d = value . doubleValue ( ) ; if ( BigDecimal . valueOf ( d ) . equals ( value ) ) { float f = ( float ) d ; if ( ( double ) f == d ) { return ( float ) d ; } else { return d ; } } else { return null ; } } }
There must be a better way .
7,771
private void validateSchemaWithFilePath ( File schemaSourceFile , DataSchema schema ) { if ( schemaSourceFile != null && schemaSourceFile . isFile ( ) && schema instanceof NamedDataSchema ) { final NamedDataSchema namedDataSchema = ( NamedDataSchema ) schema ; final String namespace = namedDataSchema . getNamespace ( ) ; if ( ! FileUtil . removeFileExtension ( schemaSourceFile . getName ( ) ) . equalsIgnoreCase ( namedDataSchema . getName ( ) ) ) { throw new IllegalArgumentException ( namedDataSchema . getFullName ( ) + " has name that does not match filename '" + schemaSourceFile . getAbsolutePath ( ) + "'" ) ; } final String directory = schemaSourceFile . getParentFile ( ) . getAbsolutePath ( ) ; if ( ! directory . endsWith ( namespace . replace ( '.' , File . separatorChar ) ) ) { throw new IllegalArgumentException ( namedDataSchema . getFullName ( ) + " has namespace that does not match " + "file path '" + schemaSourceFile . getAbsolutePath ( ) + "'" ) ; } } }
Checks that the schema name and namespace match the file name and path . These must match for FileDataSchemaResolver to find a schema pdscs by fully qualified name .
7,772
private boolean wasResolved ( File schemaSourceFile ) { final FileDataSchemaLocation schemaLocation = new FileDataSchemaLocation ( schemaSourceFile ) ; return _schemaResolver . locationResolved ( schemaLocation ) ; }
Whether a source file has already been resolved to data schemas .
7,773
private List < DataSchema > parseSchema ( final File schemaSourceFile , CourierParseResult result ) throws IOException { SchemaParser parser = _schemaParserFactory . create ( _schemaResolver ) ; final FileInputStream schemaStream = new SchemaFileInputStream ( schemaSourceFile ) ; try { parser . setLocation ( new FileDataSchemaLocation ( schemaSourceFile ) ) ; parser . parse ( schemaStream ) ; if ( parser . hasError ( ) ) { return Collections . emptyList ( ) ; } return parser . topLevelDataSchemas ( ) ; } finally { schemaStream . close ( ) ; if ( parser . hasError ( ) ) { result . addMessage ( schemaSourceFile . getPath ( ) + "," ) ; result . addMessage ( parser . errorMessage ( ) ) ; } } }
Parse a source file to obtain the data schemas contained within .
7,774
public static String escapeKeyword ( String symbol ) { if ( swiftKeywords . contains ( symbol ) ) { return "`" + symbol + "`" ; } else if ( reservedSymbols . contains ( symbol ) ) { return symbol + "$" ; } else { return symbol ; } }
Returns the escaped Pegasus symbol for use in Swift source code .
7,775
private String toTypeString ( ClassTemplateSpec spec ) { if ( spec . getSchema ( ) == null ) { return escapedFullname ( spec ) ; } Type schemaType = spec . getSchema ( ) . getType ( ) ; if ( schemaType == Type . INT ) { return "Int" ; } else if ( schemaType == Type . LONG ) { return "Int" ; } else if ( schemaType == Type . FLOAT ) { return "Float" ; } else if ( schemaType == Type . DOUBLE ) { return "Double" ; } else if ( schemaType == Type . STRING ) { return "String" ; } else if ( schemaType == Type . BOOLEAN ) { return "Bool" ; } else if ( schemaType == Type . BYTES ) { return "String" ; } else if ( schemaType == Type . FIXED ) { return "String" ; } else if ( schemaType == Type . ENUM ) { return escapedFullname ( spec ) ; } else if ( schemaType == Type . RECORD ) { return escapedFullname ( spec ) ; } else if ( schemaType == Type . UNION ) { return escapedFullname ( spec ) ; } else if ( schemaType == Type . MAP ) { return "[String: " + toTypeString ( ( ( CourierMapTemplateSpec ) spec ) . getValueClass ( ) ) + "]" ; } else if ( schemaType == Type . ARRAY ) { return "[" + toTypeString ( ( ( ArrayTemplateSpec ) spec ) . getItemClass ( ) ) + "]" ; } else { throw new IllegalArgumentException ( "unrecognized type: " + schemaType ) ; } }
emit string representing type
7,776
public static String stringToDocComment ( String doc ) { boolean emptyDoc = ( doc == null || doc . trim ( ) . isEmpty ( ) ) ; if ( emptyDoc ) return "" ; return DocEscaping . stringToDocComment ( doc , DocCommentStyle . NO_MARGIN ) ; }
Returns a doc comment as a string of Swift source for the given documentation string .
7,777
private String getScalaClassName ( PsiClass c ) { String baseName = c . getName ( ) ; return baseName . replaceAll ( "\\$" , "" ) ; }
Given a Java class or a Scala class OR object gets the underlying class name .
7,778
private CourierImportDeclarations addFirstImport ( CourierImportDeclaration importDecl ) { TypeName first = importDecl . getFullname ( ) ; CourierTopLevel root = getRoot ( ) ; CourierImportDeclarations importDecls = root . getImportDeclarations ( ) ; if ( importDecls . getImportDeclarationList ( ) . size ( ) == 0 ) { importDecls . delete ( ) ; CourierImportDeclarations emptyImports = CourierElementFactory . createImports ( getProject ( ) , Collections . singleton ( first ) ) ; CourierNamespaceDeclaration namespaceDecl = root . getNamespaceDeclaration ( ) ; if ( namespaceDecl != null ) { root . addAfter ( emptyImports , namespaceDecl ) ; } else { PsiElement firstChild = root . getFirstChild ( ) ; if ( firstChild != null ) { root . addBefore ( emptyImports , firstChild ) ; } else { root . add ( emptyImports ) ; } } return emptyImports ; } else { return importDecls ; } }
Position imports correctly when adding the first import .
7,779
private CourierImportDeclarations addNthImport ( CourierImportDeclaration importDecl ) { CourierTopLevel root = getRoot ( ) ; CourierImportDeclarations importDecls = root . getImportDeclarations ( ) ; if ( importDecl . getFullname ( ) == null ) { return importDecls ; } boolean added = false ; for ( CourierImportDeclaration existing : importDecls . getImportDeclarationList ( ) ) { if ( existing . getFullname ( ) != null && importDecl . getFullname ( ) . toString ( ) . compareTo ( existing . getFullname ( ) . toString ( ) ) < 0 ) { importDecls . addBefore ( importDecl , existing ) ; added = true ; break ; } } if ( ! added ) { importDecls . add ( importDecl ) ; } return importDecls ; }
Add an import to an existing import list attempting to keep the list sorted .
7,780
public static String stringToDocComment ( String doc , DocCommentStyle style ) { if ( doc == null || doc . trim ( ) . isEmpty ( ) ) return "" ; String commentNewline = ( style == DocCommentStyle . ASTRISK_MARGIN ) ? "\n * " : "\n" ; String schemadoc = wrap ( escape ( doc ) ) . replaceAll ( "\\n" , commentNewline ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( "/**\n" ) ; if ( style == DocCommentStyle . ASTRISK_MARGIN ) builder . append ( " * " ) ; builder . append ( schemadoc ) . append ( "\n" ) ; if ( style == DocCommentStyle . ASTRISK_MARGIN ) builder . append ( " " ) ; builder . append ( "*/" ) ; return builder . toString ( ) ; }
Returns a doc comment as a string of source for the given documentation string and deprecated property .
7,781
public static String stringToJavadoc ( String doc , Object deprecatedProp ) { boolean emptyDoc = ( doc == null || doc . trim ( ) . isEmpty ( ) ) ; boolean emptyDeprecated = ( deprecatedProp == null || ! ( deprecatedProp instanceof String ) ) ; if ( emptyDoc && emptyDeprecated ) return "" ; String javadocBody = emptyDoc ? "" : ( doc + "\n" ) ; String deprecated = ( emptyDeprecated ) ? "" : ( "@deprecated " + deprecatedProp + "\n" ) ; String text = javadocBody + deprecated ; return DocEscaping . stringToDocComment ( text , DocCommentStyle . ASTRISK_MARGIN ) ; }
Returns a javadoc comment as a string of java source for the given documentation string and deprecated property .
7,782
public String hashCodeList ( List < RecordTemplateSpec . Field > fields ) { StringBuilder sb = new StringBuilder ( ) ; Iterator < RecordTemplateSpec . Field > iter = fields . iterator ( ) ; while ( iter . hasNext ( ) ) { RecordTemplateSpec . Field field = iter . next ( ) ; Type schemaType = field . getSchemaField ( ) . getType ( ) . getType ( ) ; sb . append ( escapeKeyword ( field . getSchemaField ( ) . getName ( ) ) ) ; if ( iter . hasNext ( ) ) sb . append ( ", " ) ; } return sb . toString ( ) ; }
Returns Java source code that computes the hashCodes of each of the fields as a list of parameters .
7,783
public static Set < ClassTemplateSpec > allReferencedTypes ( ClassTemplateSpec spec ) { return findAllReferencedTypes ( directReferencedTypes ( spec ) , Collections . < ClassTemplateSpec > emptySet ( ) , Collections . < ClassTemplateSpec > emptySet ( ) ) ; }
Return all types directly or transitively referenced by this type .
7,784
private static Set < ClassTemplateSpec > findAllReferencedTypes ( Set < ClassTemplateSpec > current , Set < ClassTemplateSpec > visited , Set < ClassTemplateSpec > acc ) { Set < ClassTemplateSpec > nextUnvisited = new HashSet < ClassTemplateSpec > ( ) ; for ( ClassTemplateSpec currentSpec : current ) { for ( ClassTemplateSpec maybeNext : directReferencedTypes ( currentSpec ) ) { if ( ! visited . contains ( maybeNext ) ) { nextUnvisited . add ( maybeNext ) ; } } } Set < ClassTemplateSpec > accAndCurrent = new HashSet < ClassTemplateSpec > ( acc ) ; accAndCurrent . addAll ( current ) ; if ( nextUnvisited . size ( ) > 0 ) { Set < ClassTemplateSpec > currentAndVisited = new HashSet < ClassTemplateSpec > ( current ) ; currentAndVisited . addAll ( visited ) ; return findAllReferencedTypes ( nextUnvisited , currentAndVisited , accAndCurrent ) ; } else { return accAndCurrent ; } }
traverses the directReferencedTypes graph keeping track of already visited ClassTemplateSpecs
7,785
public void add ( ImprintNode node ) { Util . notNull ( node , "Node" ) ; if ( node . getLevel ( ) != 0 ) { throw new IllegalArgumentException ( "ImprintNode with level greater than 0 is not supported by BlindingMaskLinkingHashTreeBuilder" ) ; } ImprintNode newNode = calculateNewNode ( node ) ; hashTreeBuilder . add ( newNode ) ; previousBlockHash = new DataHash ( newNode . getValue ( ) ) ; }
Adds a new node to the tree .
7,786
public long calculateHeight ( ImprintNode node ) { Util . notNull ( node , "Node" ) ; return hashTreeBuilder . calculateHeight ( calculateNewNode ( node ) ) ; }
Calculates the binary tree height if new leaf would be added .
7,787
public void add ( ImprintNode ... nodes ) { Util . notNull ( nodes , "Nodes" ) ; for ( ImprintNode node : nodes ) { add ( node ) ; } }
Adds a new list of leaves to the binary tree .
7,788
Future < AggregatorConfiguration > getAggregationConfiguration ( ) { return new HAConfFuture < > ( invokeSubServiceConfUpdates ( ) , new HAConfFuture . ConfResultSupplier < ConsolidatedResult < AggregatorConfiguration > > ( ) { public ConsolidatedResult < AggregatorConfiguration > get ( ) { return lastConsolidatedConfiguration ; } } ) ; }
Gets the aggregator s configuration . Invokes configuration updates for all the subclients .
7,789
public PublicationsFile create ( InputStream input ) throws KSIException { InMemoryPublicationsFile publicationsFile = new InMemoryPublicationsFile ( input ) ; CMSSignature signature = publicationsFile . getSignature ( ) ; CMSSignatureVerifier verifier = new CMSSignatureVerifier ( trustStore ) ; verifier . verify ( signature ) ; return publicationsFile ; }
This method is used to read publications file from input stream . Input stream must be present and must be signed by trusted PKI certificate .
7,790
private void calculateCalendarHashChainOutput ( ) throws KSIException { ChainResult lastRes = null ; for ( AggregationHashChain chain : aggregationChains ) { if ( lastRes == null ) { lastRes = chain . calculateOutputHash ( 0L ) ; } else { lastRes = chain . calculateOutputHash ( lastRes . getLevel ( ) ) ; } LOGGER . debug ( "Output hash of chain: {} is {}" , chain , lastRes . getOutputHash ( ) ) ; } }
This method is used to verify signature consistency .
7,791
private List < AggregationHashChain > sortAggregationHashChains ( List < AggregationHashChain > chains ) throws InvalidSignatureException { Collections . sort ( chains , new Comparator < AggregationHashChain > ( ) { public int compare ( AggregationHashChain chain1 , AggregationHashChain chain2 ) { return chain2 . getChainIndex ( ) . size ( ) - chain1 . getChainIndex ( ) . size ( ) ; } } ) ; return chains ; }
Orders aggregation chains .
7,792
private void validateMac ( byte [ ] key , HashAlgorithm hmacAlgorithm ) throws KSIException { try { HashAlgorithm receivedHmacAlgorithm = mac . getAlgorithm ( ) ; if ( receivedHmacAlgorithm != hmacAlgorithm ) { throw new KSIException ( "HMAC algorithm mismatch. Expected " + hmacAlgorithm . getName ( ) + ", received " + receivedHmacAlgorithm . getName ( ) ) ; } DataHash macValue = new DataHash ( hmacAlgorithm , Util . calculateHMAC ( getContent ( ) , key , hmacAlgorithm . getName ( ) ) ) ; if ( ! mac . equals ( macValue ) ) { throw new InvalidMessageAuthenticationCodeException ( "Invalid MAC code. Expected " + mac + ", calculated " + macValue ) ; } } catch ( IOException e ) { throw new InvalidMessageAuthenticationCodeException ( "IO Exception occurred turning MAC calculation" , e ) ; } catch ( InvalidKeyException e ) { throw new InvalidMessageAuthenticationCodeException ( "Problem with HMAC key." , e ) ; } catch ( NoSuchAlgorithmException e ) { throw new InvalidMessageAuthenticationCodeException ( "Unsupported HMAC algorithm." , e ) ; } catch ( HashException e ) { throw new KSIProtocolException ( "Hashing exception occurred when calculating KSI service response HMAC" , e ) ; } }
Checks the MAC code .
7,793
private void throwErrorPayloadException ( TLVElement child ) throws KSIException { TLVElement errorCodeElement = child . getFirstChildElement ( ELEMENT_TYPE_ERROR_CODE ) ; TLVElement messageElement = child . getFirstChildElement ( ELEMENT_TYPE_ERROR_MESSAGE ) ; throw new KSIProtocolException ( errorCodeElement . getDecodedLong ( ) , "Response error " + errorCodeElement . getDecodedLong ( ) + ": " + messageElement . getDecodedString ( ) ) ; }
Reads error code and error message elements from given TLV element and throws KSI protocol exception containing error information .
7,794
private Date calculateRegistrationTime ( CalendarHashChain calendarHashChain ) throws InvalidCalendarHashChainException { List < CalendarHashChainLink > chain = calendarHashChain . getChainLinks ( ) ; long r = calendarHashChain . getPublicationTime ( ) . getTime ( ) / 1000 ; long t = 0 ; ListIterator < CalendarHashChainLink > li = chain . listIterator ( chain . size ( ) ) ; while ( li . hasPrevious ( ) ) { if ( r <= 0 ) { LOGGER . warn ( "Calendar hash chain shape is inconsistent with publication time" ) ; r = 0 ; return new Date ( 0 ) ; } CalendarHashChainLink link = li . previous ( ) ; if ( ! link . isRightLink ( ) ) { r = highBit ( r ) - 1 ; } else { t = t + highBit ( r ) ; r = r - highBit ( r ) ; } } if ( r != 0 ) { LOGGER . warn ( "Calendar hash chain shape inconsistent with publication time" ) ; t = 0 ; } return new Date ( t * 1000 ) ; }
Calculates the time when the signature was registered in the KSI hash calendar .
7,795
public final ChainResult calculateOutputHash ( long level ) throws KSIException { DataHash lastHash = inputHash ; long currentLevel = level ; for ( AggregationChainLink aggregationChainLink : chain ) { ChainResult step = aggregationChainLink . calculateChainStep ( lastHash . getImprint ( ) , currentLevel , aggregationAlgorithm ) ; lastHash = step . getOutputHash ( ) ; currentLevel = step . getLevel ( ) ; } this . outputHash = lastHash ; return new InMemoryChainResult ( lastHash , currentLevel ) ; }
Calculate hash chain output hash .
7,796
Future < ExtenderConfiguration > getExtensionConfiguration ( ) { return new HAConfFuture < > ( invokeSubserviceConfUpdates ( ) , new HAConfFuture . ConfResultSupplier < ConsolidatedResult < ExtenderConfiguration > > ( ) { public ConsolidatedResult < ExtenderConfiguration > get ( ) { return lastConsolidatedConfiguration ; } } ) ; }
Gets the extender s configuration . Invokes configuration updates for all the subclients .
7,797
public Future < T > doConfigurationUpdate ( final ConfigurationRequest < T > configurationRequest ) { Util . notNull ( configurationRequest , "ConfigurationRequest passed to ConfigurationHandler" ) ; return executorService . submit ( new Callable < T > ( ) { public T call ( ) throws Exception { try { T conf = configurationRequest . invoke ( ) ; updateListenersWithNewConfiguration ( conf ) ; return conf ; } catch ( Exception e ) { updateListenersWithFailure ( e ) ; throw e ; } } } ) ; }
Invokes a configuration request and updates listeners asynchronously .
7,798
void updateListenersWithNewConfiguration ( T newConfiguration ) { for ( ConfigurationListener < T > listener : listeners ) { try { listener . updated ( newConfiguration ) ; } catch ( Exception e ) { logger . error ( "Updating a listener with new configuration failed." , e ) ; } } }
Updates listeners with provided configuration
7,799
void updateListenersWithFailure ( Throwable t ) { for ( ConfigurationListener < T > listener : listeners ) { try { listener . updateFailed ( t ) ; } catch ( Exception e ) { logger . error ( "Updating a listener with configuration request failure failed." , e ) ; } } }
Updates listeners with failure