idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
7,800
private CloseableHttpAsyncClient createClient ( HttpSettings settings , ApacheHttpClientConfiguration conf ) { IOReactorConfig ioReactor = IOReactorConfig . custom ( ) . setIoThreadCount ( conf . getMaxThreadCount ( ) ) . build ( ) ; HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients . custom ( ) . useSystemProperties ( ) . setRedirectStrategy ( new LaxRedirectStrategy ( ) ) . setMaxConnTotal ( conf . getMaxTotalConnectionCount ( ) ) . setMaxConnPerRoute ( conf . getMaxRouteConnectionCount ( ) ) . setDefaultIOReactorConfig ( ioReactor ) . setKeepAliveStrategy ( new DefaultConnectionKeepAliveStrategy ( ) ) . setDefaultRequestConfig ( createDefaultRequestConfig ( settings ) ) ; if ( settings . getProxyUrl ( ) != null ) { DefaultProxyRoutePlanner routePlanner = createProxyRoutePlanner ( settings , httpClientBuilder ) ; httpClientBuilder . setRoutePlanner ( routePlanner ) ; } CloseableHttpAsyncClient httpClient = httpClientBuilder . build ( ) ; httpClient . start ( ) ; return httpClient ; }
Creates asynchronous Apache HTTP client .
7,801
private DefaultProxyRoutePlanner createProxyRoutePlanner ( HttpSettings settings , HttpAsyncClientBuilder httpClientBuilder ) { HttpHost proxy = new HttpHost ( settings . getProxyUrl ( ) . getHost ( ) , settings . getProxyUrl ( ) . getPort ( ) ) ; if ( settings . getProxyUser ( ) != null ) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider ( ) ; String proxyUser = settings . getProxyUser ( ) ; String proxyPassword = settings . getProxyPassword ( ) ; UsernamePasswordCredentials credentials = new UsernamePasswordCredentials ( proxyUser , proxyPassword ) ; credentialsProvider . setCredentials ( new AuthScope ( proxy ) , credentials ) ; httpClientBuilder . setDefaultCredentialsProvider ( credentialsProvider ) ; } return new DefaultProxyRoutePlanner ( proxy ) ; }
Creates default proxy route planner .
7,802
private RequestConfig createDefaultRequestConfig ( HttpSettings settings ) { int connectionTimeout = settings . getConnectionTimeout ( ) ; int socketTimeout = settings . getReadTimeout ( ) ; return RequestConfig . custom ( ) . setConnectionRequestTimeout ( connectionTimeout ) . setSocketTimeout ( socketTimeout ) . build ( ) ; }
Creates default request config .
7,803
public Future < ExtensionResponse > extend ( Date aggregationTime , Date publicationTime ) throws KSIException { Util . notNull ( aggregationTime , "aggregationTime" ) ; Collection < KSIExtendingService > services = subservices ; Collection < Callable < ExtensionResponse > > tasks = new ArrayList < > ( services . size ( ) ) ; for ( KSIExtendingService service : services ) { tasks . add ( new ExtendingTask ( service , aggregationTime , publicationTime ) ) ; } return new ServiceCallFuture < > ( executorService . submit ( new ServiceCallsTask < > ( executorService , tasks ) ) ) ; }
Creates a non - blocking extending request . Sends the request to all the subservices in parallel . First successful response is used others are cancelled . Request fails only if all the subservices fail .
7,804
public synchronized TLVElement getResult ( ) throws KSITCPTransactionException { if ( finished ) { if ( response != null ) { return response ; } if ( exception != null ) { throw exception ; } } return blockUntilTransactionFinished ( ) ; }
Blocks until response timeout occurs or the response arrives .
7,805
static boolean isBigger ( Long a , Long b ) { return a == null || ( b != null && b > a ) ; }
Is value of b bigger than value of a .
7,806
static boolean isSmaller ( Long a , Long b ) { return a == null || ( b != null && b < a ) ; }
Is value of b smaller than value of a .
7,807
static boolean isAfter ( Date a , Date b ) { return a == null || ( b != null && b . after ( a ) ) ; }
Is value of b after value of a .
7,808
static boolean isBefore ( Date a , Date b ) { return a == null || ( b != null && b . before ( a ) ) ; }
Is value of b before value of a .
7,809
public List < KSISignature > sign ( ) throws KSIException { TreeNode rootNode = treeBuilder . build ( ) ; logger . debug ( "Root node calculated. {}(level={})" , new DataHash ( rootNode . getValue ( ) ) , rootNode . getLevel ( ) ) ; KSISignature rootNodeSignature = signRootNode ( rootNode ) ; if ( leafs . size ( ) == 1 && ! leafs . get ( 0 ) . hasMetadata ( ) ) { return Collections . singletonList ( rootNodeSignature ) ; } List < KSISignature > signatures = new LinkedList < > ( ) ; AggregationHashChainBuilder chainBuilder = new AggregationHashChainBuilder ( ) ; for ( ImprintNode leaf : leafs ) { signatures . add ( signatureFactory . createSignature ( rootNodeSignature , chainBuilder . build ( leaf ) , new DataHash ( leaf . getValue ( ) ) ) ) ; } return signatures ; }
Creates a block of multiple signatures .
7,810
public void add ( ImprintNode node , IdentityMetadata metadata ) throws HashException , KSIException { addToHeads ( heads , aggregate ( node , metadata ) ) ; }
Adds a new leaf with its metadata to the hash tree .
7,811
public long calculateHeight ( ImprintNode node ) throws HashException { LinkedList < ImprintNode > tmpHeads = new LinkedList < > ( ) ; for ( ImprintNode in : heads ) { tmpHeads . add ( new ImprintNode ( in ) ) ; } addToHeads ( tmpHeads , new ImprintNode ( node ) ) ; ImprintNode root = getRootNode ( tmpHeads ) ; logger . debug ( "Adding node with hash {} and height {}, the hash tree height would be {}" , node . getValue ( ) , node . getLevel ( ) , root . getLevel ( ) ) ; return root . getLevel ( ) ; }
Calculates the height of the hash tree in case a new node would be added .
7,812
public long calculateHeight ( ImprintNode node , IdentityMetadata metadata ) throws HashException , KSIException { return calculateHeight ( aggregate ( node , metadata ) ) ; }
Calculates the height of the hash tree in case a new node with metadata would be added .
7,813
public void add ( ImprintNode ... nodes ) throws HashException { notNull ( nodes , "Nodes" ) ; for ( ImprintNode node : nodes ) { add ( node ) ; } }
Adds a new array of child nodes to the hash tree .
7,814
public KSIBuilder setKsiProtocolSignerClient ( KSISigningClient signingClient ) { Util . notNull ( signingClient , "KSI Signing Client" ) ; return setKsiProtocolSigningService ( new KSISigningClientServiceAdapter ( signingClient ) ) ; }
Sets the signer client to be used in signing process .
7,815
public KSIBuilder setKsiProtocolExtenderClient ( KSIExtenderClient extenderClient ) { Util . notNull ( extenderClient , "KSI Extender Client" ) ; return setKsiProtocolExtendingService ( new KSIExtendingClientServiceAdapter ( extenderClient ) ) ; }
Sets the extender client to be used in verification and extending process .
7,816
public boolean isTrusted ( X509Certificate certificate , Store certStore ) throws CryptoException { try { if ( certificate == null ) { throw new CryptoException ( "Invalid input parameter. Certificate can not be null" ) ; } LOGGER . info ( "Checking if certificate with subjectDN={} is trusted" , certificate . getSubjectDN ( ) ) ; Store certificateStore = certStore ; if ( certificateStore == null ) { certificateStore = new JcaCertStore ( new ArrayList ( ) ) ; } checkConstraints ( certSelector , certificate ) ; X509CertSelector selector = new X509CertSelector ( ) ; selector . setCertificate ( certificate ) ; CertStore pkixParamsCertStore = new JcaCertStoreBuilder ( ) . addCertificates ( certificateStore ) . build ( ) ; PKIXBuilderParameters buildParams = new PKIXBuilderParameters ( keyStore , selector ) ; buildParams . addCertStore ( pkixParamsCertStore ) ; buildParams . setRevocationEnabled ( false ) ; CertPathBuilder builder = CertPathBuilder . getInstance ( ALGORITHM_PKIX ) ; PKIXCertPathBuilderResult result = ( PKIXCertPathBuilderResult ) builder . build ( buildParams ) ; CertPath certPath = result . getCertPath ( ) ; PKIXParameters params = new PKIXParameters ( keyStore ) ; params . setRevocationEnabled ( false ) ; CertPathValidator validator = CertPathValidator . getInstance ( ALGORITHM_PKIX ) ; validator . validate ( certPath , params ) ; return true ; } catch ( CertPathValidatorException e ) { LOGGER . debug ( "Cert path validation failed" , e ) ; return false ; } catch ( CertPathBuilderException e ) { LOGGER . debug ( "Cert path building failed" , e ) ; return false ; } catch ( GeneralSecurityException e ) { throw new CryptoException ( "General security error occurred. " + e . getMessage ( ) , e ) ; } }
This method is used to check if certificate is trusted or not .
7,817
@ SuppressWarnings ( "resource" ) private InputStream loadFile ( String trustStorePath ) throws FileNotFoundException { InputStream input ; try { input = new FileInputStream ( trustStorePath ) ; } catch ( FileNotFoundException e ) { LOGGER . warn ( "File {} not found. Fallback to classpath." , trustStorePath ) ; input = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( trustStorePath ) ; } if ( input == null ) { throw new FileNotFoundException ( "File " + trustStorePath + " does not exist" ) ; } return input ; }
This method is used to find file from disk or classpath .
7,818
public String getPublicationString ( ) { byte [ ] imprint = publicationHash . getImprint ( ) ; byte [ ] data = new byte [ imprint . length + 8 ] ; System . arraycopy ( Util . toByteArray ( publicationTime . getTime ( ) / 1000 ) , 0 , data , 0 , 8 ) ; System . arraycopy ( imprint , 0 , data , 8 , imprint . length ) ; return Base32 . encodeWithDashes ( Util . addCrc32 ( data ) ) ; }
Returns a publication string that is a base - 32 encoded value that is meant published to print media as human readable text
7,819
protected DataHash calculateMac ( ) throws KSIException { try { HashAlgorithm algorithm = HashAlgorithm . getByName ( "DEFAULT" ) ; algorithm . checkExpiration ( ) ; return new DataHash ( algorithm , Util . calculateHMAC ( getContent ( ) , this . loginKey , algorithm . getName ( ) ) ) ; } catch ( IOException e ) { throw new KSIProtocolException ( "Problem with HMAC" , e ) ; } catch ( InvalidKeyException e ) { throw new KSIProtocolException ( "Problem with HMAC key." , e ) ; } catch ( NoSuchAlgorithmException e ) { throw new KSIProtocolException ( "Unsupported HMAC algorithm." , e ) ; } catch ( HashException e ) { throw new KSIProtocolException ( e . getMessage ( ) , e ) ; } }
Calculates the MAC based on header and payload TLVs .
7,820
public VerificationContextBuilder setDocumentHash ( DataHash documentHash , Long level ) { this . documentHash = documentHash ; this . inputHashLevel = level ; return this ; }
Used to set the hash and local aggregation tree height . If present then this hash must equal to signature input hash .
7,821
public final VerificationContext createVerificationContext ( ) throws KSIException { if ( signature == null ) { throw new KSIException ( "Failed to createSignature verification context. Signature must be present." ) ; } if ( extendingService == null ) { throw new KSIException ( "Failed to createSignature verification context. KSI extending service must be present." ) ; } if ( publicationsFile == null ) { throw new KSIException ( "Failed to createSignature verification context. PublicationsFile must be present." ) ; } return new KSIVerificationContext ( publicationsFile , signature , userPublication , extendingAllowed , extendingService , documentHash , inputHashLevel ) ; }
Builds the verification context .
7,822
private String getIdentityFromLegacyId ( ) throws CharacterCodingException { byte [ ] data = legacyId ; int len = Util . toShort ( data , 1 ) ; return Util . decodeString ( data , 3 , len ) ; }
Decodes link identity from legacy id .
7,823
protected final DataHash hash ( byte [ ] hash1 , byte [ ] hash2 , long level , HashAlgorithm algorithm ) throws InvalidAggregationHashChainException { if ( ! algorithm . isImplemented ( ) ) { throw new InvalidAggregationHashChainException ( "Invalid aggregation hash chain. Hash algorithm " + algorithm . getName ( ) + " is not implemented" ) ; } DataHasher hasher = new DataHasher ( algorithm , false ) ; hasher . addData ( hash1 ) ; hasher . addData ( hash2 ) ; hasher . addData ( Util . encodeUnsignedLong ( level ) ) ; return hasher . getHash ( ) ; }
Hash two hashes together .
7,824
public TLVElement readElement ( ) throws IOException , TLVParserException { TlvHeader header = readHeader ( ) ; TLVElement element = new TLVElement ( header . tlv16 , header . nonCritical , header . forwarded , header . type ) ; int count = countNestedTlvElements ( header ) ; if ( count > 0 ) { readNestedElements ( element , count ) ; } else { element . setContent ( readTlvContent ( header ) ) ; } return element ; }
Reads the next TLV element from the stream .
7,825
private byte [ ] readTlvContent ( TlvHeader header ) throws IOException { byte [ ] data = new byte [ header . getDataLength ( ) ] ; in . readFully ( data ) ; return data ; }
Reads the TLV content bytes from the underlying stream .
7,826
public static ContextAwarePolicy createPolicy ( Policy policy , PublicationsHandler handler , KSIExtendingService extendingService ) { if ( policy instanceof UserProvidedPublicationBasedVerificationPolicy ) { throw new IllegalArgumentException ( "Unsupported verification policy." ) ; } Util . notNull ( handler , "Publications handler" ) ; Util . notNull ( extendingService , "Extending service" ) ; return new ContextAwarePolicyAdapter ( policy , new PolicyContext ( handler , extendingService ) ) ; }
Method creating context aware policy using user provided policy with needed components .
7,827
public void setFallbackPolicy ( Policy fallbackPolicy ) { Policy p = fallbackPolicy ; while ( p != null ) { if ( ! ( p instanceof ContextAwarePolicy ) ) { throw new IllegalArgumentException ( "Fallback policy must be instance of ContextAwarePolicy" ) ; } p = p . getFallbackPolicy ( ) ; } this . policy . setFallbackPolicy ( fallbackPolicy ) ; }
Sets a fallback policy to be used when signature does not verify with given policy .
7,828
public static String decodeString ( byte [ ] buf , int ofs , int len ) throws CharacterCodingException { if ( ofs < 0 || len < 0 || ofs + len < 0 || ofs + len > buf . length ) { throw new IndexOutOfBoundsException ( ) ; } CharsetDecoder decoder = Charset . forName ( "UTF-8" ) . newDecoder ( ) . onMalformedInput ( CodingErrorAction . REPORT ) . onUnmappableCharacter ( CodingErrorAction . REPORT ) ; return decoder . decode ( ByteBuffer . wrap ( buf , ofs , len ) ) . toString ( ) ; }
Decodes UTF - 8 string from the given buffer .
7,829
public static byte [ ] toByteArray ( String value ) { if ( value == null ) { return null ; } try { CharsetEncoder encoder = Charset . forName ( "UTF-8" ) . newEncoder ( ) . onMalformedInput ( CodingErrorAction . REPORT ) . onUnmappableCharacter ( CodingErrorAction . REPORT ) ; ByteBuffer buf = encoder . encode ( CharBuffer . wrap ( value ) ) ; byte [ ] res = new byte [ buf . remaining ( ) ] ; buf . get ( res ) ; return res ; } catch ( CharacterCodingException e ) { throw new RuntimeException ( "Unexpected exception" , e ) ; } }
Encodes the given string in UTF - 8 .
7,830
public static byte [ ] copyOf ( byte [ ] b , int off , int len ) throws NullPointerException , ArrayIndexOutOfBoundsException { if ( b == null ) { throw new NullPointerException ( ) ; } if ( off < 0 || len < 0 || off > b . length - len ) { throw new ArrayIndexOutOfBoundsException ( ) ; } byte [ ] copy = new byte [ len ] ; System . arraycopy ( b , off , copy , 0 , len ) ; return copy ; }
Creates a copy of a section of the given byte array .
7,831
public static byte [ ] join ( byte [ ] a , byte [ ] b ) { byte [ ] result = new byte [ a . length + b . length ] ; System . arraycopy ( a , 0 , result , 0 , a . length ) ; System . arraycopy ( b , 0 , result , a . length , b . length ) ; return result ; }
Joins two byte arrays into one .
7,832
public static long decodeUnsignedLong ( byte [ ] buf , int ofs , int len ) throws IllegalArgumentException { if ( ofs < 0 || len < 0 || ofs + len < 0 || ofs + len > buf . length ) { throw new IndexOutOfBoundsException ( ) ; } if ( len > 8 || len == 8 && buf [ ofs ] < 0 ) { throw new IllegalArgumentException ( "Integers of at most 63 unsigned bits supported by this implementation" ) ; } long t = 0 ; for ( int i = 0 ; i < len ; ++ i ) { t = ( t << 8 ) | ( ( long ) buf [ ofs + i ] & 0xff ) ; } return t ; }
Decodes an unsigned integer from the given buffer .
7,833
public static byte [ ] calculateHMAC ( byte [ ] message , byte [ ] keyBytes , String algorithm ) throws NoSuchAlgorithmException , InvalidKeyException { if ( keyBytes == null ) { throw new IllegalArgumentException ( "Invalid HMAC key: null" ) ; } String hmacAlgorithmName = "Hmac" + algorithm . toUpperCase ( ) . replaceAll ( "[^\\p{Alnum}]" , "" ) ; SecretKeySpec key = new SecretKeySpec ( keyBytes , hmacAlgorithmName ) ; Mac mac = Mac . getInstance ( hmacAlgorithmName ) ; mac . init ( key ) ; return mac . doFinal ( message ) ; }
Calculates the RFC 2104 compatible HMAC for the given message key and algorithm .
7,834
public static boolean equalsIgnoreOrder ( Collection < ? > c1 , Collection < ? > c2 ) { return ( c1 == null && c2 == null ) || ( c1 != null && c2 != null && c1 . size ( ) == c2 . size ( ) && c1 . containsAll ( c2 ) && c2 . containsAll ( c1 ) ) ; }
Checks if two collections are equal ignoring the order of components . It s safe to pass collections that might be null .
7,835
protected void verifyCriticalFlag ( TLVElement element ) throws TLVParserException { if ( ! element . isNonCritical ( ) ) { throw new TLVParserException ( "Unknown critical TLV element with tag=0x" + Integer . toHexString ( element . getType ( ) ) + " encountered" ) ; } }
Checks if the TLV element is critical or not .
7,836
public Future < AggregationResponse > sign ( DataHash dataHash , Long level ) throws KSIException { Util . notNull ( dataHash , "dataHash" ) ; Util . notNull ( level , "level" ) ; final Collection < Callable < AggregationResponse > > tasks = new ArrayList < > ( subservices . size ( ) ) ; for ( KSISigningService subservice : subservices ) { tasks . add ( new SigningTask ( subservice , dataHash , level ) ) ; } return new ServiceCallFuture < > ( executorService . submit ( new ServiceCallsTask < > ( executorService , tasks ) ) ) ; }
Creates a non - blocking signing request . Sends the request to all the subservices in parallel . First successful response is used others are cancelled . Request fails only if all the subservices fail .
7,837
public final DataHasher addData ( byte [ ] data ) { Util . notNull ( data , "Date" ) ; return addData ( data , 0 , data . length ) ; }
Adds data to the digest using the specified array of bytes starting at an offset of 0 .
7,838
public final DataHasher addData ( InputStream inStream , int bufferSize ) { Util . notNull ( inStream , "Input stream" ) ; try { byte [ ] buffer = new byte [ bufferSize ] ; while ( true ) { int bytesRead = inStream . read ( buffer ) ; if ( bytesRead == - 1 ) { return this ; } addData ( buffer , 0 , bytesRead ) ; } } catch ( IOException e ) { throw new HashException ( "Exception occurred when reading input stream while calculating hash" , e ) ; } }
Adds data to the digest using the specified input stream of bytes starting at an offset of 0 .
7,839
public final DataHasher addData ( File file , int bufferSize ) { Util . notNull ( file , "File" ) ; FileInputStream inStream = null ; try { inStream = new FileInputStream ( file ) ; return addData ( inStream , bufferSize ) ; } catch ( FileNotFoundException e ) { throw new IllegalArgumentException ( "File not found, when calculating data hash" , e ) ; } finally { Util . closeQuietly ( inStream ) ; } }
Adds data to the digest using the specified file starting at the offset 0 .
7,840
private void addChars ( String chars ) { for ( int i = 0 ; i < chars . length ( ) ; i ++ ) { int c = chars . codePointAt ( i ) - min ; if ( values [ c ] != - 1 && values [ c ] != i ) { throw new IllegalArgumentException ( "Duplicate characters in the encoding alphabet" ) ; } values [ c ] = i ; } }
Adds the values for the given characters to the value lookup table .
7,841
public final StringBuffer encode ( byte [ ] in , int off , int len , String sep , int freq ) { if ( in == null ) { throw new NullPointerException ( ) ; } if ( off < 0 || len < 0 || off + len < 0 || off + len > in . length ) { throw new ArrayIndexOutOfBoundsException ( ) ; } if ( sep == null ) { freq = 0 ; } else { for ( int i = 0 ; i < sep . length ( ) ; i ++ ) { int c = sep . codePointAt ( i ) ; if ( c >= min && c <= max && values [ c - min ] != - 1 ) { throw new IllegalArgumentException ( "The separator contains characters from the encoding alphabet" ) ; } } } int outLen = ( 8 * len + bits - 1 ) / bits ; outLen = ( outLen + block - 1 ) / block * block ; if ( freq > 0 ) { outLen += ( outLen - 1 ) / freq * sep . length ( ) ; } StringBuffer out = new StringBuffer ( outLen ) ; int outCount = 0 ; int inCount = 0 ; int buf = 0 ; int bufBits = 0 ; int bufMask = ( 1 << bits ) - 1 ; while ( bits * outCount < 8 * len ) { if ( freq > 0 && outCount > 0 && outCount % freq == 0 ) { out . append ( sep ) ; } while ( bufBits < bits ) { int next = ( inCount < len ? in [ off + inCount ] : 0 ) ; inCount ++ ; buf = ( buf << 8 ) | ( next & 0xff ) ; bufBits += 8 ; } out . append ( chars [ ( buf >>> ( bufBits - bits ) ) & bufMask ] ) ; bufBits -= bits ; outCount ++ ; } while ( outCount % block != 0 ) { if ( freq > 0 && outCount > 0 && outCount % freq == 0 ) { out . append ( sep ) ; } out . append ( pad ) ; outCount ++ ; } return out ; }
Encodes the given bytes into a base - X string optionally inserting a separator into the result with given frequency .
7,842
public final byte [ ] decode ( String in ) { if ( in == null ) { throw new NullPointerException ( ) ; } byte [ ] out = new byte [ in . length ( ) * bits / 8 ] ; int outCount = 0 ; int inCount = 0 ; int buf = 0 ; int bufBits = 0 ; while ( inCount < in . length ( ) ) { int next = in . codePointAt ( inCount ) ; inCount ++ ; if ( next < min || next > max ) { continue ; } next = values [ next - min ] ; if ( next == - 1 ) { continue ; } buf = ( buf << bits ) | next ; bufBits += bits ; while ( bufBits >= 8 ) { out [ outCount ] = ( byte ) ( ( buf >>> ( bufBits - 8 ) ) & 0xff ) ; bufBits -= 8 ; outCount ++ ; } } if ( outCount < out . length ) { byte [ ] tmp = out ; out = new byte [ outCount ] ; System . arraycopy ( tmp , 0 , out , 0 , outCount ) ; } return out ; }
Decodes the given base - X string into bytes silently ignoring any non - base - X characters .
7,843
private void decodePublicationsFile ( TLVInputStream input ) throws KSIException , IOException { while ( input . hasNextElement ( ) ) { TLVElement element = input . readElement ( ) ; switch ( element . getType ( ) ) { case PublicationsFileHeader . ELEMENT_TYPE : if ( header != null ) { throw new InvalidPublicationsFileException ( "Publications file contains multiple header components" ) ; } this . header = new PublicationsFileHeader ( element ) ; break ; case InMemoryCertificateRecord . ELEMENT_TYPE : certificateRecords . add ( new InMemoryCertificateRecord ( element ) ) ; break ; case PublicationsFilePublicationRecord . ELEMENT_TYPE : publicationRecords . add ( new PublicationsFilePublicationRecord ( element ) ) ; break ; case ELEMENT_TYPE_CMS_SIGNATURE : cmsSignature = element . getContent ( ) ; break ; default : throw new InvalidPublicationsFileException ( "Invalid publications file element type=0x" + Integer . toHexString ( element . getType ( ) ) ) ; } verifyElementOrder ( element ) ; elements . add ( element ) ; } }
Decodes publications file . Reads publications data from given input stream .
7,844
private void verifyMagicBytes ( TLVInputStream input ) throws InvalidPublicationsFileException { try { byte [ ] magicBytes = new byte [ PUBLICATIONS_FILE_MAGIC_BYTES_LENGTH ] ; input . read ( magicBytes ) ; if ( ! Arrays . equals ( magicBytes , FILE_BEGINNING_MAGIC_BYTES ) ) { throw new InvalidPublicationsFileException ( "Invalid publications file magic bytes" ) ; } } catch ( IOException e ) { throw new InvalidPublicationsFileException ( "Checking publications file magic bytes failed" , e ) ; } }
Verifies that input stream starts with publications file magic bytes .
7,845
public Certificate findCertificateById ( byte [ ] certificateId ) throws CertificateNotFoundException { if ( certificateId == null ) { throw new CertificateNotFoundException ( "Certificate with id null not found from pubFile='" + this . toString ( ) + "'" ) ; } for ( InMemoryCertificateRecord record : certificateRecords ) { if ( Arrays . equals ( certificateId , record . getCertificateId ( ) ) ) { return X509CertUtil . toCert ( record . getCertificate ( ) ) ; } } throw new CertificateNotFoundException ( "Certificate with id " + Base64 . encode ( certificateId ) + " not found from pubFile='" + this . toString ( ) + "'" ) ; }
Finds a certificate by certificate id .
7,846
public PublicationRecord getPublicationRecord ( Date time ) { PublicationRecord nearest = null ; for ( PublicationRecord publicationRecord : publicationRecords ) { Date publicationTime = publicationRecord . getPublicationData ( ) . getPublicationTime ( ) ; if ( publicationTime . equals ( time ) || publicationTime . after ( time ) ) { if ( nearest == null ) { nearest = publicationRecord ; } else if ( publicationTime . before ( nearest . getPublicationData ( ) . getPublicationTime ( ) ) ) { nearest = publicationRecord ; } } } return nearest ; }
Returns the closest publication record to given time .
7,847
protected byte [ ] getSignedData ( ) throws KSIException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( ) ; try { byteStream . write ( FILE_BEGINNING_MAGIC_BYTES ) ; for ( TLVElement element : elements ) { if ( ELEMENT_TYPE_CMS_SIGNATURE != element . getType ( ) ) { element . writeTo ( byteStream ) ; } } } catch ( IOException e ) { return new byte [ ] { } ; } return byteStream . toByteArray ( ) ; }
Get publications file bytes without signature .
7,848
public static long calculateIndex ( List < AggregationChainLink > links ) { notNull ( links , "Aggregation chain links" ) ; long chainIndex = 0 ; for ( int i = 0 ; i < links . size ( ) ; i ++ ) { if ( links . get ( i ) . isLeft ( ) ) { chainIndex |= 1L << i ; } } chainIndex |= 1L << links . size ( ) ; return chainIndex ; }
Calculates chain index
7,849
public static TLVElement create ( byte [ ] bytes ) throws TLVParserException { Util . notNull ( bytes , "Byte array" ) ; TLVInputStream input = null ; try { input = new TLVInputStream ( new ByteArrayInputStream ( bytes ) ) ; TLVElement element = input . readElement ( ) ; if ( input . hasNextElement ( ) ) { throw new MultipleTLVElementException ( ) ; } return element ; } catch ( IOException e ) { throw new TLVParserException ( "Reading TLV bytes failed" , e ) ; } finally { Util . closeQuietly ( input ) ; } }
Creates TLVElement form byte array .
7,850
public static TLVElement create ( int type , byte [ ] value ) throws TLVParserException { TLVElement element = create ( type ) ; element . setContent ( value ) ; return element ; }
Creates TLV element with byte array content . TLV element nonCritical and forwarded flags are set to false .
7,851
public final String getDecodedString ( ) throws TLVParserException { byte [ ] data = getContent ( ) ; if ( ! ( data . length > 0 && data [ data . length - 1 ] == '\0' ) ) { throw new TLVParserException ( "String must be null terminated" ) ; } try { return Util . decodeString ( data , 0 , data . length - 1 ) ; } catch ( CharacterCodingException e ) { throw new TLVParserException ( "Malformed UTF-8 data" , e ) ; } }
Converts the TLV element content data to UTF - 8 string .
7,852
public HashAlgorithm getDecodedHashAlgorithm ( ) throws TLVParserException { int algorithmId = getDecodedLong ( ) . intValue ( ) ; if ( HashAlgorithm . isHashAlgorithmId ( algorithmId ) ) { return HashAlgorithm . getById ( algorithmId ) ; } throw new TLVParserException ( "Unknown hash algorithm with id " + algorithmId ) ; }
Gets HashAlgorithm form TLV element .
7,853
public byte [ ] getContent ( ) throws TLVParserException { byte [ ] content = this . content ; if ( ! children . isEmpty ( ) ) { for ( TLVElement child : children ) { content = Util . join ( content , child . encodeHeader ( ) ) ; content = Util . join ( content , child . getContent ( ) ) ; } } return content ; }
Returns the TLV content . If TLV does not include content then empty array is returned .
7,854
public void setContent ( byte [ ] content ) throws TLVParserException { Util . notNull ( content , "Content" ) ; assertActualContentLengthIsInTLVLimits ( content . length ) ; this . content = content ; }
Sets the value to TLV element content .
7,855
public TLVElement getFirstChildElement ( int tag ) { for ( TLVElement element : children ) { if ( tag == element . getType ( ) ) { return element ; } } return null ; }
Returns the first child element with specified tag . If tag doesn t exist then null is returned .
7,856
public List < TLVElement > getChildElements ( int tag ) { List < TLVElement > elements = new LinkedList < > ( ) ; for ( TLVElement element : children ) { if ( tag == element . getType ( ) ) { elements . add ( element ) ; } } return elements ; }
Returns all the tags with the specified tag .
7,857
public byte [ ] encodeHeader ( ) throws TLVParserException { DataOutputStream out = null ; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; out = new DataOutputStream ( byteArrayOutputStream ) ; int dataLength = getContentLength ( ) ; boolean tlv16 = isOutputTlv16 ( ) ; int firstByte = ( tlv16 ? TLVInputStream . TLV16_FLAG : 0 ) + ( isNonCritical ( ) ? TLVInputStream . NON_CRITICAL_FLAG : 0 ) + ( isForwarded ( ) ? TLVInputStream . FORWARD_FLAG : 0 ) ; if ( tlv16 ) { firstByte = firstByte | ( getType ( ) >>> TLVInputStream . BYTE_BITS ) & TLVInputStream . TYPE_MASK ; out . writeByte ( firstByte ) ; out . writeByte ( getType ( ) ) ; if ( dataLength < 1 ) { out . writeShort ( 0 ) ; } else { out . writeShort ( dataLength ) ; } } else { firstByte = firstByte | getType ( ) & TLVInputStream . TYPE_MASK ; out . writeByte ( firstByte ) ; if ( dataLength < 1 ) { out . writeByte ( 0 ) ; } else { out . writeByte ( dataLength ) ; } } return byteArrayOutputStream . toByteArray ( ) ; } catch ( IOException e ) { throw new TLVParserException ( "TLV header encoding failed" , e ) ; } finally { Util . closeQuietly ( out ) ; } }
Encodes TLV header .
7,858
public void replace ( TLVElement childToBeReplaced , TLVElement newChild ) { for ( int i = 0 ; i < children . size ( ) ; i ++ ) { if ( children . get ( i ) . equals ( childToBeReplaced ) ) { children . set ( i , newChild ) ; return ; } } }
Replaces first element with given one .
7,859
public void writeTo ( OutputStream out ) throws TLVParserException { Util . notNull ( out , "Output stream" ) ; try { assertActualContentLengthIsInTLVLimits ( getContentLength ( ) ) ; out . write ( encodeHeader ( ) ) ; out . write ( getContent ( ) ) ; } catch ( IOException e ) { throw new TLVParserException ( "Writing TLV element (" + convertHeader ( ) + ") to output stream failed" , e ) ; } }
Writes the encoded TLV element to the specified output stream .
7,860
private int extractNextTlvElementLength ( IoBuffer in ) { if ( ! hasRemainingData ( in , 2 ) ) { return NOT_ENOUGH_DATA ; } try { in . mark ( ) ; int firstByte = in . getUnsigned ( ) ; boolean tlv8 = ( firstByte & TLV16_MASK ) == 0 ; if ( tlv8 ) { return in . getUnsigned ( ) + TLV8_HEADER_LENGTH ; } in . skip ( 1 ) ; if ( ! hasRemainingData ( in , 2 ) ) { return NOT_ENOUGH_DATA ; } return in . getUnsignedShort ( ) + TLV16_HEADER_LENGTH ; } finally { in . reset ( ) ; } }
Returns the length of the next TLV element . Returns - 1 when buffer doesn t contain enough data for next TLV element .
7,861
public Server create ( ServerCreateOptions serverCreateOptions ) throws IOException , MailosaurException { return client . request ( "POST" , "api/servers" , serverCreateOptions ) . parseAs ( Server . class ) ; }
Create a server . Creates a new virtual SMTP server and returns it .
7,862
public Server get ( String id ) throws IOException , MailosaurException { return client . request ( "GET" , "api/servers/" + id ) . parseAs ( Server . class ) ; }
Retrieve a server . Retrieves the detail for a single server . Simply supply the unique identifier for the required server .
7,863
public Server update ( String id , Server server ) throws IOException , MailosaurException { return client . request ( "PUT" , "api/servers/" + id , server ) . parseAs ( Server . class ) ; }
Update a server . Updats a single server and returns it .
7,864
public Message get ( String id ) throws IOException , MailosaurException { return client . request ( "GET" , "api/messages/" + id ) . parseAs ( Message . class ) ; }
Retrieve an message . Retrieves the detail for a single message . Simply supply the unique identifier for the required message .
7,865
public void deleteAll ( String server ) throws MailosaurException { HashMap < String , String > query = new HashMap < String , String > ( ) ; query . put ( "server" , server ) ; client . request ( "DELETE" , "api/messages" , query ) ; }
Delete all messages . Permanently deletes all messages held by the specified server . This operation cannot be undone . Also deletes any attachments related to each message .
7,866
public MessageListResult list ( String server ) throws IOException , MailosaurException { HashMap < String , String > query = new HashMap < String , String > ( ) ; query . put ( "server" , server ) ; return client . request ( "GET" , "api/messages" , query ) . parseAs ( MessageListResult . class ) ; }
List all messages . Returns a list of your messages . The messages are returned sorted by received date with the most recently - received messages appearing first .
7,867
public MessageListResult search ( String server , SearchCriteria criteria ) throws IOException , MailosaurException { HashMap < String , String > query = new HashMap < String , String > ( ) ; query . put ( "server" , server ) ; return client . request ( "POST" , "api/messages/search" , criteria , query ) . parseAs ( MessageListResult . class ) ; }
Search for messages . Returns a list of messages matching the specified search criteria . The messages are returned sorted by received date with the most recently - received messages appearing first .
7,868
public Message waitFor ( String server , SearchCriteria criteria ) throws IOException , MailosaurException { HashMap < String , String > query = new HashMap < String , String > ( ) ; query . put ( "server" , server ) ; return client . request ( "POST" , "api/messages/await" , criteria , query ) . parseAs ( Message . class ) ; }
Wait for a specific message . Returns as soon as an message matching the specified search criteria is found .
7,869
public SpamAnalysisResult spam ( String email ) throws IOException , MailosaurException { return client . request ( "GET" , "api/analysis/spam/" + email ) . parseAs ( SpamAnalysisResult . class ) ; }
Perform spam analysis on the specified email .
7,870
@ RequestMapping ( value = "/checkout/complete" , method = RequestMethod . POST ) public String completeCheckout ( ) throws PaymentException { paymentService . updatePayPalPaymentForFulfillment ( ) ; String paymentId = paymentService . getPayPalPaymentIdFromCurrentOrder ( ) ; String payerId = paymentService . getPayPalPayerIdFromCurrentOrder ( ) ; if ( StringUtils . isBlank ( paymentId ) ) { throw new PaymentException ( "Unable to complete checkout because no PayPal payment id was found on the current order" ) ; } if ( StringUtils . isBlank ( payerId ) ) { throw new PaymentException ( "Unable to complete checkout because no PayPal payer id was found on the current order" ) ; } return "redirect:/paypal-checkout/return?" + MessageConstants . HTTP_PAYMENTID + "=" + paymentId + "&" + MessageConstants . HTTP_PAYERID + "=" + payerId ; }
Completes checkout for a PayPal payment . If there s already a PayPal payment we go ahead and make sure the details of the payment are updated to all of the forms filled out by the customer since they could ve updated shipping information added a promotion or other various things to the order .
7,871
public Signature getSignatureFrom ( SignerIdentifier signer ) { return signatures . stream ( ) . filter ( signatureFrom ( signer ) ) . findFirst ( ) . orElseThrow ( ( ) -> new IllegalArgumentException ( "Unable to find signature from this signer" ) ) ; }
Gets the signature from a given signer .
7,872
public String getFor ( String personalIdentificationNumber ) { for ( RedirectUrl redirectUrl : urls ) { if ( redirectUrl . signer . equals ( personalIdentificationNumber ) ) { return redirectUrl . url ; } } throw new IllegalArgumentException ( "Unable to find redirect URL for this signer" ) ; }
Gets the redirect URL for a given signer .
7,873
public < T > IMetadataDictionary getMetadataFor ( T instance ) { if ( instance == null ) { throw new IllegalArgumentException ( "Instance cannot be null" ) ; } DocumentInfo documentInfo = getDocumentInfo ( instance ) ; if ( documentInfo . getMetadataInstance ( ) != null ) { return documentInfo . getMetadataInstance ( ) ; } ObjectNode metadataAsJson = documentInfo . getMetadata ( ) ; MetadataAsDictionary metadata = new MetadataAsDictionary ( metadataAsJson ) ; documentInfo . setMetadataInstance ( metadata ) ; return metadata ; }
Gets the metadata for the specified entity .
7,874
public < T > List < String > getCountersFor ( T instance ) { if ( instance == null ) { throw new IllegalArgumentException ( "Instance cannot be null" ) ; } DocumentInfo documentInfo = getDocumentInfo ( instance ) ; ArrayNode countersArray = ( ArrayNode ) documentInfo . getMetadata ( ) . get ( Constants . Documents . Metadata . COUNTERS ) ; if ( countersArray == null ) { return null ; } return IntStream . range ( 0 , countersArray . size ( ) ) . mapToObj ( i -> countersArray . get ( i ) . asText ( ) ) . collect ( Collectors . toList ( ) ) ; }
Gets all counter names for the specified entity .
7,875
public < T > String getChangeVectorFor ( T instance ) { if ( instance == null ) { throw new IllegalArgumentException ( "instance cannot be null" ) ; } DocumentInfo documentInfo = getDocumentInfo ( instance ) ; JsonNode changeVector = documentInfo . getMetadata ( ) . get ( Constants . Documents . Metadata . CHANGE_VECTOR ) ; if ( changeVector != null ) { return changeVector . asText ( ) ; } return null ; }
Gets the Change Vector for the specified entity . If the entity is transient it will load the change vector from the store and associate the current state of the entity with the change vector from the server .
7,876
public String getDocumentId ( Object instance ) { if ( instance == null ) { return null ; } DocumentInfo value = documentsByEntity . get ( instance ) ; return value != null ? value . getId ( ) : null ; }
Gets the document id .
7,877
@ SuppressWarnings ( "unchecked" ) public < T > T trackEntity ( Class < T > clazz , DocumentInfo documentFound ) { return ( T ) trackEntity ( clazz , documentFound . getId ( ) , documentFound . getDocument ( ) , documentFound . getMetadata ( ) , noTracking ) ; }
Tracks the entity inside the unit of work
7,878
public Object trackEntity ( Class entityType , String id , ObjectNode document , ObjectNode metadata , boolean noTracking ) { noTracking = this . noTracking || noTracking ; if ( StringUtils . isEmpty ( id ) ) { return deserializeFromTransformer ( entityType , null , document ) ; } DocumentInfo docInfo = documentsById . getValue ( id ) ; if ( docInfo != null ) { if ( docInfo . getEntity ( ) == null ) { docInfo . setEntity ( entityToJson . convertToEntity ( entityType , id , document ) ) ; } if ( ! noTracking ) { includedDocumentsById . remove ( id ) ; documentsByEntity . put ( docInfo . getEntity ( ) , docInfo ) ; } return docInfo . getEntity ( ) ; } docInfo = includedDocumentsById . get ( id ) ; if ( docInfo != null ) { if ( docInfo . getEntity ( ) == null ) { docInfo . setEntity ( entityToJson . convertToEntity ( entityType , id , document ) ) ; } if ( ! noTracking ) { includedDocumentsById . remove ( id ) ; documentsById . add ( docInfo ) ; documentsByEntity . put ( docInfo . getEntity ( ) , docInfo ) ; } return docInfo . getEntity ( ) ; } Object entity = entityToJson . convertToEntity ( entityType , id , document ) ; String changeVector = metadata . get ( Constants . Documents . Metadata . CHANGE_VECTOR ) . asText ( ) ; if ( changeVector == null ) { throw new IllegalStateException ( "Document " + id + " must have Change Vector" ) ; } if ( ! noTracking ) { DocumentInfo newDocumentInfo = new DocumentInfo ( ) ; newDocumentInfo . setId ( id ) ; newDocumentInfo . setDocument ( document ) ; newDocumentInfo . setMetadata ( metadata ) ; newDocumentInfo . setEntity ( entity ) ; newDocumentInfo . setChangeVector ( changeVector ) ; documentsById . add ( newDocumentInfo ) ; documentsByEntity . put ( entity , newDocumentInfo ) ; } return entity ; }
Tracks the entity .
7,879
public < T > void delete ( T entity ) { if ( entity == null ) { throw new IllegalArgumentException ( "Entity cannot be null" ) ; } DocumentInfo value = documentsByEntity . get ( entity ) ; if ( value == null ) { throw new IllegalStateException ( entity + " is not associated with the session, cannot delete unknown entity instance" ) ; } deletedEntities . add ( entity ) ; includedDocumentsById . remove ( value . getId ( ) ) ; if ( _countersByDocId != null ) { _countersByDocId . remove ( value . getId ( ) ) ; } _knownMissingIds . add ( value . getId ( ) ) ; }
Marks the specified entity for deletion . The entity will be deleted when SaveChanges is called .
7,880
public void store ( Object entity ) { Reference < String > stringReference = new Reference < > ( ) ; boolean hasId = generateEntityIdOnTheClient . tryGetIdFromInstance ( entity , stringReference ) ; storeInternal ( entity , null , null , ! hasId ? ConcurrencyCheckMode . FORCED : ConcurrencyCheckMode . AUTO ) ; }
Stores the specified entity in the session . The entity will be saved when SaveChanges is called .
7,881
public boolean hasChanges ( ) { for ( Map . Entry < Object , DocumentInfo > entity : documentsByEntity . entrySet ( ) ) { ObjectNode document = entityToJson . convertEntityToJson ( entity . getKey ( ) , entity . getValue ( ) ) ; if ( entityChanged ( document , entity . getValue ( ) , null ) ) { return true ; } } return ! deletedEntities . isEmpty ( ) ; }
Gets a value indicating whether any of the entities tracked by the session has changes .
7,882
public boolean hasChanged ( Object entity ) { DocumentInfo documentInfo = documentsByEntity . get ( entity ) ; if ( documentInfo == null ) { return false ; } ObjectNode document = entityToJson . convertEntityToJson ( entity , documentInfo ) ; return entityChanged ( document , documentInfo , null ) ; }
Determines whether the specified entity has changed .
7,883
public < T > void evict ( T entity ) { DocumentInfo documentInfo = documentsByEntity . get ( entity ) ; if ( documentInfo != null ) { documentsByEntity . remove ( entity ) ; documentsById . remove ( documentInfo . getId ( ) ) ; } deletedEntities . remove ( entity ) ; if ( _countersByDocId != null ) { _countersByDocId . remove ( documentInfo . getId ( ) ) ; } }
Evicts the specified entity from the session . Remove the entity from the delete queue and stops tracking changes for this entity .
7,884
public void clear ( ) { documentsByEntity . clear ( ) ; deletedEntities . clear ( ) ; documentsById . clear ( ) ; _knownMissingIds . clear ( ) ; if ( _countersByDocId != null ) { _countersByDocId . clear ( ) ; } }
Clears this instance . Remove all entities from the delete queue and stops tracking changes for all entities .
7,885
private Set < String > getPagePathsForTemplate ( String [ ] templates , String rootPath , SlingHttpServletRequest request ) { Set < String > pagePaths = new HashSet < > ( ) ; if ( templates != null && templates . length > 0 ) { try { NodeIterator nodes = searchNodesByTemplate ( templates , rootPath , request ) ; while ( nodes . hasNext ( ) ) { Node node = nodes . nextNode ( ) ; String path = StringUtils . removeEnd ( node . getPath ( ) , "/jcr:content" ) ; pagePaths . add ( path ) ; } } catch ( RepositoryException ex ) { log . warn ( "Seaching nodes by template failed." , ex ) ; } } return pagePaths ; }
Get paths for pages that use the given template
7,886
private Optional < Boolean > isParagraphValid ( Resource resource ) { Method getModelFromResourceMethod ; try { getModelFromResourceMethod = ModelFactory . class . getDeclaredMethod ( "getModelFromResource" , Resource . class ) ; } catch ( NoSuchMethodException | SecurityException ex ) { log . debug ( "ModelFactory does not support method 'getModelFromResource' - skip paragraph validation." ) ; return Optional . empty ( ) ; } try { Object model = getModelFromResourceMethod . invoke ( modelFactory , resource ) ; if ( model instanceof ParsysItem ) { return Optional . of ( ( ( ParsysItem ) model ) . isValid ( ) ) ; } } catch ( ModelClassException ex ) { } catch ( InvocationTargetException ex ) { if ( ex . getCause ( ) instanceof ModelClassException ) { } else { log . warn ( "Unable to invoke ModelFactory.getModelFromResource." , ex ) ; } } catch ( IllegalAccessException ex ) { log . warn ( "Unable to access ModelFactory.getModelFromResource." , ex ) ; } return Optional . empty ( ) ; }
Checks if the given paragraph is valid .
7,887
private Map < String , String > getComponentHtmlTagAttributes ( String resourceType ) { if ( StringUtils . isNotEmpty ( resourceType ) ) { Component component = componentManager ( ) . getComponent ( resourceType ) ; if ( component != null && component . getHtmlTagAttributes ( ) != null ) { return component . getHtmlTagAttributes ( ) ; } } return ImmutableMap . of ( ) ; }
Get HTML tag attributes from component .
7,888
private String getNewAreaResourceType ( String componentPath ) { Resource componentResource = resolver . getResource ( componentPath ) ; if ( componentResource != null ) { if ( componentResource . getChild ( NEWAREA_CHILD_NAME ) != null ) { return componentPath + "/" + NEWAREA_CHILD_NAME ; } String resourceSuperType = componentResource . getResourceSuperType ( ) ; if ( StringUtils . isNotEmpty ( resourceSuperType ) ) { return getNewAreaResourceType ( resourceSuperType ) ; } } return FALLBACK_NEWAREA_RESOURCE_TYPE ; }
Get resource type for new area - from current parsys component or from a supertype component .
7,889
private Page seek ( ) { Page prev = next ; next = null ; while ( resources . hasNext ( ) && next == null ) { Resource nextResource = resources . next ( ) ; next = nextResource . adaptTo ( Page . class ) ; if ( next == null ) { String primaryType = nextResource . getValueMap ( ) . get ( JcrConstants . JCR_PRIMARYTYPE , String . class ) ; if ( StringUtils . equals ( primaryType , "sling:Folder" ) || StringUtils . equals ( primaryType , "sling:OrderedFolder" ) ) { next = new SlingFolderVirtualPage ( nextResource ) ; } } if ( next != null && pageFilter != null && ! pageFilter . includes ( next ) ) { next = null ; } } return prev ; }
Seeks the next available page
7,890
public boolean tryGetIdFromInstance ( Object entity , Reference < String > idHolder ) { if ( entity == null ) { throw new IllegalArgumentException ( "Entity cannot be null" ) ; } try { Field identityProperty = getIdentityProperty ( entity . getClass ( ) ) ; if ( identityProperty != null ) { Object value = FieldUtils . readField ( identityProperty , entity , true ) ; if ( value instanceof String ) { idHolder . value = ( String ) value ; return true ; } } idHolder . value = null ; return false ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } }
Attempts to get the document key from an instance
7,891
public String getOrGenerateDocumentId ( Object entity ) { Reference < String > idHolder = new Reference < > ( ) ; tryGetIdFromInstance ( entity , idHolder ) ; String id = idHolder . value ; if ( id == null ) { id = _generateId . apply ( entity ) ; } if ( id != null && id . startsWith ( "/" ) ) { throw new IllegalStateException ( "Cannot use value '" + id + "' as a document id because it begins with a '/'" ) ; } return id ; }
Tries to get the identity .
7,892
public void trySetIdentity ( Object entity , String id ) { Class < ? > entityType = entity . getClass ( ) ; Field identityProperty = _conventions . getIdentityProperty ( entityType ) ; if ( identityProperty == null ) { return ; } setPropertyOrField ( identityProperty . getType ( ) , entity , identityProperty , id ) ; }
Tries to set the identity property
7,893
public static String defaultGetCollectionName ( Class clazz ) { String result = _cachedDefaultTypeCollectionNames . get ( clazz ) ; if ( result != null ) { return result ; } if ( clazz . isInterface ( ) ) { throw new IllegalStateException ( "Cannot find collection name for interface " + clazz . getName ( ) + ", only concrete classes are supported. Did you forget to customize conventions.findCollectionName?" ) ; } if ( Modifier . isAbstract ( clazz . getModifiers ( ) ) ) { throw new IllegalStateException ( "Cannot find collection name for abstract class " + clazz . getName ( ) + ", only concrete class are supported. Did you forget to customize conventions.findCollectionName?" ) ; } result = Inflector . pluralize ( clazz . getSimpleName ( ) ) ; _cachedDefaultTypeCollectionNames . put ( clazz , result ) ; return result ; }
Default method used when finding a collection name for a type
7,894
@ SuppressWarnings ( "unchecked" ) public String generateDocumentId ( String databaseName , Object entity ) { Class < ? > clazz = entity . getClass ( ) ; for ( Tuple < Class , BiFunction < String , Object , String > > listOfRegisteredIdConvention : _listOfRegisteredIdConventions ) { if ( listOfRegisteredIdConvention . first . isAssignableFrom ( clazz ) ) { return listOfRegisteredIdConvention . second . apply ( databaseName , entity ) ; } } return _documentIdGenerator . apply ( databaseName , entity ) ; }
Generates the document id .
7,895
@ SuppressWarnings ( "unchecked" ) public < TEntity > DocumentConventions registerIdConvention ( Class < TEntity > clazz , BiFunction < String , TEntity , String > function ) { assertNotFrozen ( ) ; _listOfRegisteredIdConventions . stream ( ) . filter ( x -> x . first . equals ( clazz ) ) . findFirst ( ) . ifPresent ( x -> _listOfRegisteredIdConventions . remove ( x ) ) ; int index ; for ( index = 0 ; index < _listOfRegisteredIdConventions . size ( ) ; index ++ ) { Tuple < Class , BiFunction < String , Object , String > > entry = _listOfRegisteredIdConventions . get ( index ) ; if ( entry . first . isAssignableFrom ( clazz ) ) { break ; } } _listOfRegisteredIdConventions . add ( index , Tuple . create ( clazz , ( BiFunction < String , Object , String > ) function ) ) ; return this ; }
Register an id convention for a single type ( and all of its derived types . Note that you can still fall back to the DocumentIdGenerator if you want .
7,896
public Field getIdentityProperty ( Class clazz ) { Field info = _idPropertyCache . get ( clazz ) ; if ( info != null ) { return info ; } try { Field idField = Arrays . stream ( Introspector . getBeanInfo ( clazz ) . getPropertyDescriptors ( ) ) . filter ( x -> _findIdentityProperty . apply ( x ) ) . findFirst ( ) . map ( x -> getField ( clazz , x . getName ( ) ) ) . orElse ( null ) ; _idPropertyCache . put ( clazz , idField ) ; return idField ; } catch ( IntrospectionException e ) { throw new RuntimeException ( e ) ; } }
Gets the identity property .
7,897
private DataSource getDataSource ( ComponentHelper cmp , Resource resource ) { try { ValueMap overwriteProperties = new ValueMapDecorator ( ImmutableMap . < String , Object > of ( "path" , resource . getPath ( ) ) ) ; Resource dataSourceResourceWrapper = GraniteUiSyntheticResource . wrapMerge ( request . getResource ( ) , overwriteProperties ) ; return cmp . getItemDataSource ( dataSourceResourceWrapper ) ; } catch ( ServletException | IOException ex ) { throw new RuntimeException ( "Unable to get data source." , ex ) ; } }
Get data source to list children of given resource .
7,898
private static Column getCurrentResourceColumn ( DataSource dataSource , Integer size , Resource currentResource , String itemResourceType ) { Iterator < Resource > items = dataSource . iterator ( ) ; boolean hasMore = false ; if ( size != null ) { List < Resource > list = new ArrayList < Resource > ( ) ; while ( items . hasNext ( ) && list . size ( ) < size ) { list . add ( items . next ( ) ) ; } hasMore = items . hasNext ( ) ; items = list . iterator ( ) ; } Column column = new Column ( ) . columnId ( currentResource . getPath ( ) ) . hasMore ( hasMore ) . metaElement ( true ) ; while ( items . hasNext ( ) ) { Resource item = items . next ( ) ; column . addItem ( new ColumnItem ( item ) . resourceType ( itemResourceType ) ) ; } return column ; }
Generate column for data source items for current resource .
7,899
private static Column getRootColumn ( Resource rootResource , String itemResourceType ) { String columnId = "parentof:" + rootResource . getPath ( ) ; Column column = new Column ( ) . columnId ( columnId ) . hasMore ( false ) ; column . addItem ( new ColumnItem ( rootResource ) . resourceType ( itemResourceType ) . active ( true ) ) ; return column ; }
Generate extra column representing the root resource .