idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
32,400
public static LifecycleChaincodePackage fromStream ( InputStream inputStream ) throws IOException , InvalidArgumentException { if ( null == inputStream ) { throw new InvalidArgumentException ( "The parameter inputStream may not be null." ) ; } byte [ ] packageBytes = IOUtils . toByteArray ( inputStream ) ; return fromBytes ( packageBytes ) ; }
Construct a LifecycleChaincodePackage from a stream .
32,401
public byte [ ] getAsBytes ( ) { byte [ ] ret = new byte [ pBytes . length ] ; System . arraycopy ( pBytes , 0 , ret , 0 , pBytes . length ) ; return ret ; }
Lifecycle chaincode package as bytes
32,402
public void toFile ( Path path , OpenOption ... options ) throws IOException { Files . write ( path , pBytes , options ) ; }
Write Lifecycle chaincode package bytes to file .
32,403
public org . hyperledger . fabric . protos . common . Collection . CollectionConfigPackage getCollectionConfigPackage ( ) throws InvalidProtocolBufferException { if ( null == cp ) { cp = org . hyperledger . fabric . protos . common . Collection . CollectionConfigPackage . parseFrom ( collectionConfigBytes ) ; } return cp ; }
The raw collection information returned from the peer .
32,404
public Collection < CollectionConfig > getCollectionConfigs ( ) throws InvalidProtocolBufferException { List < CollectionConfig > ret = new LinkedList < > ( ) ; for ( org . hyperledger . fabric . protos . common . Collection . CollectionConfig collectionConfig : getCollectionConfigPackage ( ) . getConfigList ( ) ) { ret . add ( new CollectionConfig ( collectionConfig ) ) ; } return ret ; }
Collection of the chaincode collections .
32,405
public void setRevokedStart ( Date revokedStart ) throws InvalidArgumentException { if ( revokedStart == null ) { throw new InvalidArgumentException ( "Date can't be null" ) ; } queryParms . put ( "revoked_start" , Util . dateToString ( revokedStart ) ) ; }
Get certificates that have been revoked after this date
32,406
public void setRevokedEnd ( Date revokedEnd ) throws InvalidArgumentException { if ( revokedEnd == null ) { throw new InvalidArgumentException ( "Date can't be null" ) ; } queryParms . put ( "revoked_end" , Util . dateToString ( revokedEnd ) ) ; }
Get certificates that have been revoked before this date
32,407
public void setExpiredStart ( Date expiredStart ) throws InvalidArgumentException { if ( expiredStart == null ) { throw new InvalidArgumentException ( "Date can't be null" ) ; } queryParms . put ( "expired_start" , Util . dateToString ( expiredStart ) ) ; }
Get certificates that have expired after this date
32,408
public void setExpiredEnd ( Date expiredEnd ) throws InvalidArgumentException { if ( expiredEnd == null ) { throw new InvalidArgumentException ( "Date can't be null" ) ; } queryParms . put ( "expired_end" , Util . dateToString ( expiredEnd ) ) ; }
Get certificates that have expired before this date
32,409
public static byte [ ] calculateBlockHash ( HFClient client , long blockNumber , byte [ ] previousHash , byte [ ] dataHash ) throws IOException , InvalidArgumentException { if ( previousHash == null ) { throw new InvalidArgumentException ( "previousHash parameter is null." ) ; } if ( dataHash == null ) { throw new InvalidArgumentException ( "dataHash parameter is null." ) ; } if ( null == client ) { throw new InvalidArgumentException ( "client parameter is null." ) ; } CryptoSuite cryptoSuite = client . getCryptoSuite ( ) ; if ( null == cryptoSuite ) { throw new InvalidArgumentException ( "Client crypto suite has not been set." ) ; } ByteArrayOutputStream s = new ByteArrayOutputStream ( ) ; DERSequenceGenerator seq = new DERSequenceGenerator ( s ) ; seq . addObject ( new ASN1Integer ( blockNumber ) ) ; seq . addObject ( new DEROctetString ( previousHash ) ) ; seq . addObject ( new DEROctetString ( dataHash ) ) ; seq . close ( ) ; return cryptoSuite . hash ( s . toByteArray ( ) ) ; }
used asn1 and get hash
32,410
private JsonObject toJsonObject ( ) { JsonObjectBuilder factory = Json . createObjectBuilder ( ) ; if ( enrollmentID != null ) { factory . add ( "id" , enrollmentID ) ; } else { factory . add ( "serial" , serial ) ; factory . add ( "aki" , aki ) ; } if ( null != reason ) { factory . add ( "reason" , reason ) ; } if ( caName != null ) { factory . add ( HFCAClient . FABRIC_CA_REQPROP , caName ) ; } if ( genCRL != null ) { factory . add ( "gencrl" , genCRL ) ; } return factory . build ( ) ; }
Convert the revocation request to a JSON object
32,411
public static boolean computeUpdate ( String channelId , Configtx . Config original , Configtx . Config update , Configtx . ConfigUpdate . Builder configUpdateBuilder ) { Configtx . ConfigGroup . Builder readSetBuilder = Configtx . ConfigGroup . newBuilder ( ) ; Configtx . ConfigGroup . Builder writeSetBuilder = Configtx . ConfigGroup . newBuilder ( ) ; if ( computeGroupUpdate ( original . getChannelGroup ( ) , update . getChannelGroup ( ) , readSetBuilder , writeSetBuilder ) ) { configUpdateBuilder . setReadSet ( readSetBuilder . build ( ) ) . setWriteSet ( writeSetBuilder . build ( ) ) . setChannelId ( channelId ) ; return true ; } return false ; }
not an api
32,412
public ChaincodeID getChaincodeID ( ) throws InvalidArgumentException { try { if ( chaincodeID == null ) { Header header = Header . parseFrom ( proposal . getHeader ( ) ) ; Common . ChannelHeader channelHeader = Common . ChannelHeader . parseFrom ( header . getChannelHeader ( ) ) ; ChaincodeHeaderExtension chaincodeHeaderExtension = ChaincodeHeaderExtension . parseFrom ( channelHeader . getExtension ( ) ) ; chaincodeID = new ChaincodeID ( chaincodeHeaderExtension . getChaincodeId ( ) ) ; } return chaincodeID ; } catch ( Exception e ) { throw new InvalidArgumentException ( e ) ; } }
Chaincode ID that was executed .
32,413
public byte [ ] getChaincodeActionResponsePayload ( ) throws InvalidArgumentException { if ( isInvalid ( ) ) { throw new InvalidArgumentException ( "Proposal response is invalid." ) ; } try { final ProposalResponsePayloadDeserializer proposalResponsePayloadDeserializer = getProposalResponsePayloadDeserializer ( ) ; ByteString ret = proposalResponsePayloadDeserializer . getExtension ( ) . getChaincodeAction ( ) . getResponse ( ) . getPayload ( ) ; if ( null == ret ) { return null ; } return ret . toByteArray ( ) ; } catch ( InvalidArgumentException e ) { throw e ; } catch ( Exception e ) { throw new InvalidArgumentException ( e ) ; } }
ChaincodeActionResponsePayload is the result of the executing chaincode .
32,414
public int getChaincodeActionResponseStatus ( ) throws InvalidArgumentException { if ( statusReturnCode != - 1 ) { return statusReturnCode ; } try { final ProposalResponsePayloadDeserializer proposalResponsePayloadDeserializer = getProposalResponsePayloadDeserializer ( ) ; statusReturnCode = proposalResponsePayloadDeserializer . getExtension ( ) . getResponseStatus ( ) ; return statusReturnCode ; } catch ( InvalidArgumentException e ) { throw e ; } catch ( Exception e ) { throw new InvalidArgumentException ( e ) ; } }
getChaincodeActionResponseStatus returns the what chaincode executions set as the return status .
32,415
public TxReadWriteSetInfo getChaincodeActionResponseReadWriteSetInfo ( ) throws InvalidArgumentException { if ( isInvalid ( ) ) { throw new InvalidArgumentException ( "Proposal response is invalid." ) ; } try { final ProposalResponsePayloadDeserializer proposalResponsePayloadDeserializer = getProposalResponsePayloadDeserializer ( ) ; TxReadWriteSet txReadWriteSet = proposalResponsePayloadDeserializer . getExtension ( ) . getResults ( ) ; if ( txReadWriteSet == null ) { return null ; } return new TxReadWriteSetInfo ( txReadWriteSet ) ; } catch ( Exception e ) { throw new InvalidArgumentException ( e ) ; } }
getChaincodeActionResponseReadWriteSetInfo get this proposals read write set .
32,416
public PrivateKey bytesToPrivateKey ( byte [ ] pemKey ) throws CryptoException { PrivateKey pk = null ; CryptoException ce = null ; try { PemReader pr = new PemReader ( new StringReader ( new String ( pemKey ) ) ) ; PemObject po = pr . readPemObject ( ) ; PEMParser pem = new PEMParser ( new StringReader ( new String ( pemKey ) ) ) ; if ( po . getType ( ) . equals ( "PRIVATE KEY" ) ) { pk = new JcaPEMKeyConverter ( ) . getPrivateKey ( ( PrivateKeyInfo ) pem . readObject ( ) ) ; } else { logger . trace ( "Found private key with type " + po . getType ( ) ) ; PEMKeyPair kp = ( PEMKeyPair ) pem . readObject ( ) ; pk = new JcaPEMKeyConverter ( ) . getPrivateKey ( kp . getPrivateKeyInfo ( ) ) ; } } catch ( Exception e ) { throw new CryptoException ( "Failed to convert private key bytes" , e ) ; } return pk ; }
Return PrivateKey from pem bytes .
32,417
public void addCACertificatesToTrustStore ( BufferedInputStream bis ) throws CryptoException , InvalidArgumentException { if ( bis == null ) { throw new InvalidArgumentException ( "The certificate stream bis cannot be null" ) ; } try { final Collection < ? extends Certificate > certificates = cf . generateCertificates ( bis ) ; for ( Certificate certificate : certificates ) { addCACertificateToTrustStore ( certificate ) ; } } catch ( CertificateException e ) { throw new CryptoException ( "Unable to add CA certificate to trust store. Error: " + e . getMessage ( ) , e ) ; } }
addCACertificatesToTrustStore adds a CA certs in a stream to the trust store used for signature validation
32,418
boolean validateCertificate ( byte [ ] certPEM ) { if ( certPEM == null ) { return false ; } try { X509Certificate certificate = getX509Certificate ( certPEM ) ; if ( null == certificate ) { throw new Exception ( "Certificate transformation returned null" ) ; } return validateCertificate ( certificate ) ; } catch ( Exception e ) { logger . error ( "Cannot validate certificate. Error is: " + e . getMessage ( ) + "\r\nCertificate (PEM, hex): " + DatatypeConverter . printHexBinary ( certPEM ) ) ; return false ; } }
validateCertificate checks whether the given certificate is trusted . It checks if the certificate is signed by one of the trusted certs in the trust store .
32,419
void setSecurityLevel ( final int securityLevel ) throws InvalidArgumentException { logger . trace ( format ( "setSecurityLevel to %d" , securityLevel ) ) ; if ( securityCurveMapping . isEmpty ( ) ) { throw new InvalidArgumentException ( "Security curve mapping has no entries." ) ; } if ( ! securityCurveMapping . containsKey ( securityLevel ) ) { StringBuilder sb = new StringBuilder ( ) ; String sp = "" ; for ( int x : securityCurveMapping . keySet ( ) ) { sb . append ( sp ) . append ( x ) ; sp = ", " ; } throw new InvalidArgumentException ( format ( "Illegal security level: %d. Valid values are: %s" , securityLevel , sb . toString ( ) ) ) ; } String lcurveName = securityCurveMapping . get ( securityLevel ) ; logger . debug ( format ( "Mapped curve strength %d to %s" , securityLevel , lcurveName ) ) ; X9ECParameters params = ECNamedCurveTable . getByName ( lcurveName ) ; if ( params == null ) { InvalidArgumentException invalidArgumentException = new InvalidArgumentException ( format ( "Curve %s defined for security strength %d was not found." , curveName , securityLevel ) ) ; logger . error ( invalidArgumentException ) ; throw invalidArgumentException ; } curveName = lcurveName ; this . securityLevel = securityLevel ; }
Security Level determines the elliptic curve used in key generation
32,420
private static BigInteger [ ] decodeECDSASignature ( byte [ ] signature ) throws Exception { try ( ByteArrayInputStream inStream = new ByteArrayInputStream ( signature ) ) { ASN1InputStream asnInputStream = new ASN1InputStream ( inStream ) ; ASN1Primitive asn1 = asnInputStream . readObject ( ) ; BigInteger [ ] sigs = new BigInteger [ 2 ] ; int count = 0 ; if ( asn1 instanceof ASN1Sequence ) { ASN1Sequence asn1Sequence = ( ASN1Sequence ) asn1 ; ASN1Encodable [ ] asn1Encodables = asn1Sequence . toArray ( ) ; for ( ASN1Encodable asn1Encodable : asn1Encodables ) { ASN1Primitive asn1Primitive = asn1Encodable . toASN1Primitive ( ) ; if ( asn1Primitive instanceof ASN1Integer ) { ASN1Integer asn1Integer = ( ASN1Integer ) asn1Primitive ; BigInteger integer = asn1Integer . getValue ( ) ; if ( count < 2 ) { sigs [ count ] = integer ; } count ++ ; } } } if ( count != 2 ) { throw new CryptoException ( format ( "Invalid ECDSA signature. Expected count of 2 but got: %d. Signature is: %s" , count , DatatypeConverter . printHexBinary ( signature ) ) ) ; } return sigs ; } }
Decodes an ECDSA signature and returns a two element BigInteger array .
32,421
private byte [ ] ecdsaSignToBytes ( ECPrivateKey privateKey , byte [ ] data ) throws CryptoException { if ( data == null ) { throw new CryptoException ( "Data that to be signed is null." ) ; } if ( data . length == 0 ) { throw new CryptoException ( "Data to be signed was empty." ) ; } try { X9ECParameters params = ECNamedCurveTable . getByName ( curveName ) ; BigInteger curveN = params . getN ( ) ; Signature sig = SECURITY_PROVIDER == null ? Signature . getInstance ( DEFAULT_SIGNATURE_ALGORITHM ) : Signature . getInstance ( DEFAULT_SIGNATURE_ALGORITHM , SECURITY_PROVIDER ) ; sig . initSign ( privateKey ) ; sig . update ( data ) ; byte [ ] signature = sig . sign ( ) ; BigInteger [ ] sigs = decodeECDSASignature ( signature ) ; sigs = preventMalleability ( sigs , curveN ) ; try ( ByteArrayOutputStream s = new ByteArrayOutputStream ( ) ) { DERSequenceGenerator seq = new DERSequenceGenerator ( s ) ; seq . addObject ( new ASN1Integer ( sigs [ 0 ] ) ) ; seq . addObject ( new ASN1Integer ( sigs [ 1 ] ) ) ; seq . close ( ) ; return s . toByteArray ( ) ; } } catch ( Exception e ) { throw new CryptoException ( "Could not sign the message using private key" , e ) ; } }
Sign data with the specified elliptic curve private key .
32,422
private String certificationRequestToPEM ( PKCS10CertificationRequest csr ) throws IOException { PemObject pemCSR = new PemObject ( "CERTIFICATE REQUEST" , csr . getEncoded ( ) ) ; StringWriter str = new StringWriter ( ) ; JcaPEMWriter pemWriter = new JcaPEMWriter ( str ) ; pemWriter . writeObject ( pemCSR ) ; pemWriter . close ( ) ; str . close ( ) ; return str . toString ( ) ; }
certificationRequestToPEM - Convert a PKCS10CertificationRequest to PEM format .
32,423
private void resetConfiguration ( ) throws CryptoException , InvalidArgumentException { setSecurityLevel ( securityLevel ) ; setHashAlgorithm ( hashAlgorithm ) ; try { cf = CertificateFactory . getInstance ( CERTIFICATE_FORMAT ) ; } catch ( CertificateException e ) { CryptoException ex = new CryptoException ( "Cannot initialize " + CERTIFICATE_FORMAT + " certificate factory. Error = " + e . getMessage ( ) , e ) ; logger . error ( ex . getMessage ( ) , ex ) ; throw ex ; } }
Resets curve name hash algorithm and cert factory . Call this method when a config value changes
32,424
public String getPackageId ( ) throws ProposalException { Lifecycle . QueryInstalledChaincodeResult queryInstalledChaincodeResult = parsePayload ( ) ; if ( queryInstalledChaincodeResult == null ) { return null ; } return queryInstalledChaincodeResult . getPackageId ( ) ; }
The packageId for this chaincode .
32,425
public static HFCAClient createNewInstance ( NetworkConfig . CAInfo caInfo ) throws MalformedURLException , InvalidArgumentException { try { return createNewInstance ( caInfo , CryptoSuite . Factory . getCryptoSuite ( ) ) ; } catch ( MalformedURLException e ) { throw e ; } catch ( Exception e ) { throw new InvalidArgumentException ( e ) ; } }
Create HFCAClient from a NetworkConfig . CAInfo using default crypto suite .
32,426
public static HFCAClient createNewInstance ( NetworkConfig . CAInfo caInfo , CryptoSuite cryptoSuite ) throws MalformedURLException , InvalidArgumentException { if ( null == caInfo ) { throw new InvalidArgumentException ( "The caInfo parameter can not be null." ) ; } if ( null == cryptoSuite ) { throw new InvalidArgumentException ( "The cryptoSuite parameter can not be null." ) ; } HFCAClient ret = new HFCAClient ( caInfo . getCAName ( ) , caInfo . getUrl ( ) , caInfo . getProperties ( ) ) ; ret . setCryptoSuite ( cryptoSuite ) ; return ret ; }
Create HFCAClient from a NetworkConfig . CAInfo
32,427
public String register ( RegistrationRequest request , User registrar ) throws RegistrationException , InvalidArgumentException { if ( cryptoSuite == null ) { throw new InvalidArgumentException ( "Crypto primitives not set." ) ; } if ( Utils . isNullOrEmpty ( request . getEnrollmentID ( ) ) ) { throw new InvalidArgumentException ( "EntrollmentID cannot be null or empty" ) ; } if ( registrar == null ) { throw new InvalidArgumentException ( "Registrar should be a valid member" ) ; } logger . debug ( format ( "register url: %s, registrar: %s" , url , registrar . getName ( ) ) ) ; setUpSSL ( ) ; try { String body = request . toJson ( ) ; JsonObject resp = httpPost ( url + HFCA_REGISTER , body , registrar ) ; String secret = resp . getString ( "secret" ) ; if ( secret == null ) { throw new Exception ( "secret was not found in response" ) ; } logger . debug ( format ( "register url: %s, registrar: %s done." , url , registrar ) ) ; return secret ; } catch ( Exception e ) { RegistrationException registrationException = new RegistrationException ( format ( "Error while registering the user %s url: %s %s " , registrar , url , e . getMessage ( ) ) , e ) ; logger . error ( registrar ) ; throw registrationException ; } }
Register a user .
32,428
public HFCAInfo info ( ) throws InfoException , InvalidArgumentException { logger . debug ( format ( "info url:%s" , url ) ) ; if ( cryptoSuite == null ) { throw new InvalidArgumentException ( "Crypto primitives not set." ) ; } setUpSSL ( ) ; try { JsonObjectBuilder factory = Json . createObjectBuilder ( ) ; if ( caName != null ) { factory . add ( HFCAClient . FABRIC_CA_REQPROP , caName ) ; } JsonObject body = factory . build ( ) ; String responseBody = httpPost ( url + HFCA_INFO , body . toString ( ) , ( UsernamePasswordCredentials ) null ) ; logger . debug ( "response:" + responseBody ) ; JsonReader reader = Json . createReader ( new StringReader ( responseBody ) ) ; JsonObject jsonst = ( JsonObject ) reader . read ( ) ; boolean success = jsonst . getBoolean ( "success" ) ; logger . debug ( format ( "[HFCAClient] enroll success:[%s]" , success ) ) ; if ( ! success ) { throw new EnrollmentException ( format ( "FabricCA failed info %s" , url ) ) ; } JsonObject result = jsonst . getJsonObject ( "result" ) ; if ( result == null ) { throw new InfoException ( format ( "FabricCA info error - response did not contain a result url %s" , url ) ) ; } String caName = result . getString ( "CAName" ) ; String caChain = result . getString ( "CAChain" ) ; String version = null ; if ( result . containsKey ( "Version" ) ) { version = result . getString ( "Version" ) ; } String issuerPublicKey = null ; if ( result . containsKey ( "IssuerPublicKey" ) ) { issuerPublicKey = result . getString ( "IssuerPublicKey" ) ; } String issuerRevocationPublicKey = null ; if ( result . containsKey ( "IssuerRevocationPublicKey" ) ) { issuerRevocationPublicKey = result . getString ( "IssuerRevocationPublicKey" ) ; } logger . info ( format ( "CA Name: %s, Version: %s, issuerPublicKey: %s, issuerRevocationPublicKey: %s" , caName , caChain , issuerPublicKey , issuerRevocationPublicKey ) ) ; return new HFCAInfo ( caName , caChain , version , issuerPublicKey , issuerRevocationPublicKey ) ; } catch ( Exception e ) { InfoException ee = new InfoException ( format ( "Url:%s, Failed to get info" , url ) , e ) ; logger . error ( e . getMessage ( ) , e ) ; throw ee ; } }
Return information on the Fabric Certificate Authority . No credentials are needed for this API .
32,429
public Enrollment reenroll ( User user , EnrollmentRequest req ) throws EnrollmentException , InvalidArgumentException { if ( cryptoSuite == null ) { throw new InvalidArgumentException ( "Crypto primitives not set." ) ; } if ( user == null ) { throw new InvalidArgumentException ( "reenrollment user is missing" ) ; } if ( user . getEnrollment ( ) == null ) { throw new InvalidArgumentException ( "reenrollment user is not a valid user object" ) ; } logger . debug ( format ( "re-enroll user: %s, url: %s" , user . getName ( ) , url ) ) ; try { setUpSSL ( ) ; PublicKey publicKey = cryptoSuite . bytesToCertificate ( user . getEnrollment ( ) . getCert ( ) . getBytes ( StandardCharsets . UTF_8 ) ) . getPublicKey ( ) ; KeyPair keypair = new KeyPair ( publicKey , user . getEnrollment ( ) . getKey ( ) ) ; String pem = cryptoSuite . generateCertificationRequest ( user . getName ( ) , keypair ) ; req . setCSR ( pem ) ; if ( caName != null && ! caName . isEmpty ( ) ) { req . setCAName ( caName ) ; } String body = req . toJson ( ) ; JsonObject result = httpPost ( url + HFCA_REENROLL , body , user ) ; Base64 . Decoder b64dec = Base64 . getDecoder ( ) ; String signedPem = new String ( b64dec . decode ( result . getString ( "Cert" ) . getBytes ( UTF_8 ) ) ) ; logger . debug ( format ( "[HFCAClient] re-enroll returned pem:[%s]" , signedPem ) ) ; logger . debug ( format ( "reenroll user %s done." , user . getName ( ) ) ) ; return new X509Enrollment ( keypair , signedPem ) ; } catch ( EnrollmentException ee ) { logger . error ( ee . getMessage ( ) , ee ) ; throw ee ; } catch ( Exception e ) { EnrollmentException ee = new EnrollmentException ( format ( "Failed to re-enroll user %s" , user ) , e ) ; logger . error ( e . getMessage ( ) , e ) ; throw ee ; } }
Re - Enroll the user with member service
32,430
public void revoke ( User revoker , Enrollment enrollment , String reason ) throws RevocationException , InvalidArgumentException { revokeInternal ( revoker , enrollment , reason , false ) ; }
revoke one enrollment of user
32,431
public void revoke ( User revoker , String serial , String aki , String reason ) throws RevocationException , InvalidArgumentException { revokeInternal ( revoker , serial , aki , reason , false ) ; }
revoke one certificate
32,432
public String generateCRL ( User registrar , Date revokedBefore , Date revokedAfter , Date expireBefore , Date expireAfter ) throws InvalidArgumentException , GenerateCRLException { if ( cryptoSuite == null ) { throw new InvalidArgumentException ( "Crypto primitives not set." ) ; } if ( registrar == null ) { throw new InvalidArgumentException ( "registrar is not set" ) ; } try { setUpSSL ( ) ; JsonObjectBuilder factory = Json . createObjectBuilder ( ) ; if ( revokedBefore != null ) { factory . add ( "revokedBefore" , Util . dateToString ( revokedBefore ) ) ; } if ( revokedAfter != null ) { factory . add ( "revokedAfter" , Util . dateToString ( revokedAfter ) ) ; } if ( expireBefore != null ) { factory . add ( "expireBefore" , Util . dateToString ( expireBefore ) ) ; } if ( expireAfter != null ) { factory . add ( "expireAfter" , Util . dateToString ( expireAfter ) ) ; } if ( caName != null ) { factory . add ( HFCAClient . FABRIC_CA_REQPROP , caName ) ; } JsonObject jsonObject = factory . build ( ) ; StringWriter stringWriter = new StringWriter ( ) ; JsonWriter jsonWriter = Json . createWriter ( new PrintWriter ( stringWriter ) ) ; jsonWriter . writeObject ( jsonObject ) ; jsonWriter . close ( ) ; String body = stringWriter . toString ( ) ; JsonObject ret = httpPost ( url + HFCA_GENCRL , body , registrar ) ; return ret . getString ( "CRL" ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; throw new GenerateCRLException ( e . getMessage ( ) , e ) ; } }
Generate certificate revocation list .
32,433
public Collection < HFCAIdentity > getHFCAIdentities ( User registrar ) throws IdentityException , InvalidArgumentException { if ( registrar == null ) { throw new InvalidArgumentException ( "Registrar should be a valid member" ) ; } logger . debug ( format ( "identity url: %s, registrar: %s" , url , registrar . getName ( ) ) ) ; try { JsonObject result = httpGet ( HFCAIdentity . HFCA_IDENTITY , registrar ) ; Collection < HFCAIdentity > allIdentities = new ArrayList < > ( ) ; JsonArray identities = result . getJsonArray ( "identities" ) ; if ( identities != null && ! identities . isEmpty ( ) ) { for ( int i = 0 ; i < identities . size ( ) ; i ++ ) { JsonObject identity = identities . getJsonObject ( i ) ; HFCAIdentity idObj = new HFCAIdentity ( identity ) ; allIdentities . add ( idObj ) ; } } logger . debug ( format ( "identity url: %s, registrar: %s done." , url , registrar ) ) ; return allIdentities ; } catch ( HTTPException e ) { String msg = format ( "[HTTP Status Code: %d] - Error while getting all users from url '%s': %s" , e . getStatusCode ( ) , url , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } catch ( Exception e ) { String msg = format ( "Error while getting all users from url '%s': %s" , url , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } }
gets all identities that the registrar is allowed to see
32,434
public HFCAAffiliation getHFCAAffiliations ( User registrar ) throws AffiliationException , InvalidArgumentException { if ( cryptoSuite == null ) { throw new InvalidArgumentException ( "Crypto primitives not set." ) ; } if ( registrar == null ) { throw new InvalidArgumentException ( "Registrar should be a valid member" ) ; } logger . debug ( format ( "affiliations url: %s, registrar: %s" , url , registrar . getName ( ) ) ) ; try { JsonObject result = httpGet ( HFCAAffiliation . HFCA_AFFILIATION , registrar ) ; HFCAAffiliation affiliations = new HFCAAffiliation ( result ) ; logger . debug ( format ( "affiliations url: %s, registrar: %s done." , url , registrar ) ) ; return affiliations ; } catch ( HTTPException e ) { String msg = format ( "[HTTP Status Code: %d] - Error while getting all affiliations from url '%s': %s" , e . getStatusCode ( ) , url , e . getMessage ( ) ) ; AffiliationException affiliationException = new AffiliationException ( msg , e ) ; logger . error ( msg ) ; throw affiliationException ; } catch ( Exception e ) { String msg = format ( "Error while getting all affiliations from url '%s': %s" , url , e . getMessage ( ) ) ; AffiliationException affiliationException = new AffiliationException ( msg , e ) ; logger . error ( msg ) ; throw affiliationException ; } }
gets all affiliations that the registrar is allowed to see
32,435
public HFCACertificateResponse getHFCACertificates ( User registrar , HFCACertificateRequest req ) throws HFCACertificateException { try { logger . debug ( format ( "certificate url: %s, registrar: %s" , HFCA_CERTIFICATE , registrar . getName ( ) ) ) ; JsonObject result = httpGet ( HFCA_CERTIFICATE , registrar , req . getQueryParameters ( ) ) ; int statusCode = result . getInt ( "statusCode" ) ; Collection < HFCACredential > certs = new ArrayList < > ( ) ; if ( statusCode < 400 ) { JsonArray certificates = result . getJsonArray ( "certs" ) ; if ( certificates != null && ! certificates . isEmpty ( ) ) { for ( int i = 0 ; i < certificates . size ( ) ; i ++ ) { String certPEM = certificates . getJsonObject ( i ) . getString ( "PEM" ) ; certs . add ( new HFCAX509Certificate ( certPEM ) ) ; } } logger . debug ( format ( "certificate url: %s, registrar: %s done." , HFCA_CERTIFICATE , registrar ) ) ; } return new HFCACertificateResponse ( statusCode , certs ) ; } catch ( HTTPException e ) { String msg = format ( "[Code: %d] - Error while getting certificates from url '%s': %s" , e . getStatusCode ( ) , HFCA_CERTIFICATE , e . getMessage ( ) ) ; HFCACertificateException certificateException = new HFCACertificateException ( msg , e ) ; logger . error ( msg ) ; throw certificateException ; } catch ( Exception e ) { String msg = format ( "Error while getting certificates from url '%s': %s" , HFCA_CERTIFICATE , e . getMessage ( ) ) ; HFCACertificateException certificateException = new HFCACertificateException ( msg , e ) ; logger . error ( msg ) ; throw certificateException ; } }
Gets all certificates that the registrar is allowed to see and based on filter parameters that are part of the certificate request .
32,436
String httpPost ( String url , String body , UsernamePasswordCredentials credentials ) throws Exception { logger . debug ( format ( "httpPost %s, body:%s" , url , body ) ) ; final HttpClientBuilder httpClientBuilder = HttpClientBuilder . create ( ) ; CredentialsProvider provider = null ; if ( credentials != null ) { provider = new BasicCredentialsProvider ( ) ; provider . setCredentials ( AuthScope . ANY , credentials ) ; httpClientBuilder . setDefaultCredentialsProvider ( provider ) ; } if ( registry != null ) { httpClientBuilder . setConnectionManager ( new PoolingHttpClientConnectionManager ( registry ) ) ; } HttpClient client = httpClientBuilder . build ( ) ; HttpPost httpPost = new HttpPost ( url ) ; httpPost . setConfig ( getRequestConfig ( ) ) ; AuthCache authCache = new BasicAuthCache ( ) ; HttpHost targetHost = new HttpHost ( httpPost . getURI ( ) . getHost ( ) , httpPost . getURI ( ) . getPort ( ) ) ; if ( credentials != null ) { authCache . put ( targetHost , new BasicScheme ( ) ) ; } final HttpClientContext context = HttpClientContext . create ( ) ; if ( null != provider ) { context . setCredentialsProvider ( provider ) ; } if ( credentials != null ) { context . setAuthCache ( authCache ) ; } httpPost . setEntity ( new StringEntity ( body ) ) ; if ( credentials != null ) { httpPost . addHeader ( new BasicScheme ( ) . authenticate ( credentials , httpPost , context ) ) ; } HttpResponse response = client . execute ( httpPost , context ) ; int status = response . getStatusLine ( ) . getStatusCode ( ) ; HttpEntity entity = response . getEntity ( ) ; logger . trace ( format ( "httpPost %s sending..." , url ) ) ; String responseBody = entity != null ? EntityUtils . toString ( entity ) : null ; logger . trace ( format ( "httpPost %s responseBody %s" , url , responseBody ) ) ; if ( status >= 400 ) { Exception e = new Exception ( format ( "POST request to %s with request body: %s, " + "failed with status code: %d. Response: %s" , url , body , status , responseBody ) ) ; logger . error ( e . getMessage ( ) ) ; throw e ; } logger . debug ( format ( "httpPost Status: %d returning: %s " , status , responseBody ) ) ; return responseBody ; }
Http Post Request .
32,437
public int read ( User registrar ) throws IdentityException , InvalidArgumentException { if ( registrar == null ) { throw new InvalidArgumentException ( "Registrar should be a valid member" ) ; } String readIdURL = "" ; try { readIdURL = HFCA_IDENTITY + "/" + enrollmentID ; logger . debug ( format ( "identity url: %s, registrar: %s" , readIdURL , registrar . getName ( ) ) ) ; JsonObject result = client . httpGet ( readIdURL , registrar ) ; statusCode = result . getInt ( "statusCode" ) ; if ( statusCode < 400 ) { type = result . getString ( "type" ) ; maxEnrollments = result . getInt ( "max_enrollments" ) ; affiliation = result . getString ( "affiliation" ) ; JsonArray attributes = result . getJsonArray ( "attrs" ) ; Collection < Attribute > attrs = new ArrayList < Attribute > ( ) ; if ( attributes != null && ! attributes . isEmpty ( ) ) { for ( int i = 0 ; i < attributes . size ( ) ; i ++ ) { JsonObject attribute = attributes . getJsonObject ( i ) ; Attribute attr = new Attribute ( attribute . getString ( "name" ) , attribute . getString ( "value" ) , attribute . getBoolean ( "ecert" , false ) ) ; attrs . add ( attr ) ; } } this . attrs = attrs ; logger . debug ( format ( "identity url: %s, registrar: %s done." , readIdURL , registrar ) ) ; } this . deleted = false ; return statusCode ; } catch ( HTTPException e ) { String msg = format ( "[Code: %d] - Error while getting user '%s' from url '%s': %s" , e . getStatusCode ( ) , getEnrollmentId ( ) , readIdURL , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } catch ( Exception e ) { String msg = format ( "Error while getting user '%s' from url '%s': %s" , enrollmentID , readIdURL , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } }
read retrieves a specific identity
32,438
public int create ( User registrar ) throws IdentityException , InvalidArgumentException { if ( this . deleted ) { throw new IdentityException ( "Identity has been deleted" ) ; } if ( registrar == null ) { throw new InvalidArgumentException ( "Registrar should be a valid member" ) ; } String createURL = "" ; try { createURL = client . getURL ( HFCA_IDENTITY ) ; logger . debug ( format ( "identity url: %s, registrar: %s" , createURL , registrar . getName ( ) ) ) ; String body = client . toJson ( idToJsonObject ( ) ) ; JsonObject result = client . httpPost ( createURL , body , registrar ) ; statusCode = result . getInt ( "statusCode" ) ; if ( statusCode < 400 ) { getHFCAIdentity ( result ) ; logger . debug ( format ( "identity url: %s, registrar: %s done." , createURL , registrar ) ) ; } this . deleted = false ; return statusCode ; } catch ( HTTPException e ) { String msg = format ( "[Code: %d] - Error while creating user '%s' from url '%s': %s" , e . getStatusCode ( ) , getEnrollmentId ( ) , createURL , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } catch ( Exception e ) { String msg = format ( "Error while creating user '%s' from url '%s': %s" , getEnrollmentId ( ) , createURL , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } }
create an identity
32,439
public int update ( User registrar ) throws IdentityException , InvalidArgumentException { if ( this . deleted ) { throw new IdentityException ( "Identity has been deleted" ) ; } if ( registrar == null ) { throw new InvalidArgumentException ( "Registrar should be a valid member" ) ; } String updateURL = "" ; try { updateURL = client . getURL ( HFCA_IDENTITY + "/" + getEnrollmentId ( ) ) ; logger . debug ( format ( "identity url: %s, registrar: %s" , updateURL , registrar . getName ( ) ) ) ; String body = client . toJson ( idToJsonObject ( filtredUpdateAttrNames ) ) ; JsonObject result = client . httpPut ( updateURL , body , registrar ) ; statusCode = result . getInt ( "statusCode" ) ; if ( statusCode < 400 ) { getHFCAIdentity ( result ) ; logger . debug ( format ( "identity url: %s, registrar: %s done." , updateURL , registrar ) ) ; } return statusCode ; } catch ( HTTPException e ) { String msg = format ( "[Code: %d] - Error while updating user '%s' from url '%s': %s" , e . getStatusCode ( ) , getEnrollmentId ( ) , updateURL , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } catch ( Exception e ) { String msg = format ( "Error while updating user '%s' from url '%s': %s" , getEnrollmentId ( ) , updateURL , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } }
update an identity
32,440
public int delete ( User registrar ) throws IdentityException , InvalidArgumentException { if ( this . deleted ) { throw new IdentityException ( "Identity has been deleted" ) ; } if ( registrar == null ) { throw new InvalidArgumentException ( "Registrar should be a valid member" ) ; } String deleteURL = "" ; try { deleteURL = client . getURL ( HFCA_IDENTITY + "/" + getEnrollmentId ( ) ) ; logger . debug ( format ( "identity url: %s, registrar: %s" , deleteURL , registrar . getName ( ) ) ) ; JsonObject result = client . httpDelete ( deleteURL , registrar ) ; statusCode = result . getInt ( "statusCode" ) ; if ( statusCode < 400 ) { getHFCAIdentity ( result ) ; logger . debug ( format ( "identity url: %s, registrar: %s done." , deleteURL , registrar ) ) ; } this . deleted = true ; return statusCode ; } catch ( HTTPException e ) { String msg = format ( "[Code: %d] - Error while deleting user '%s' from url '%s': %s" , e . getStatusCode ( ) , getEnrollmentId ( ) , deleteURL , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } catch ( Exception e ) { String msg = format ( "Error while deleting user '%s' from url '%s': %s" , getEnrollmentId ( ) , deleteURL , e . getMessage ( ) ) ; IdentityException identityException = new IdentityException ( msg , e ) ; logger . error ( msg ) ; throw identityException ; } }
delete an identity
32,441
public static String generateDirectoryHash ( String rootDir , String chaincodeDir , String hash ) throws IOException { Path projectPath = null ; if ( rootDir == null ) { projectPath = Paths . get ( chaincodeDir ) ; } else { projectPath = Paths . get ( rootDir , chaincodeDir ) ; } File dir = projectPath . toFile ( ) ; if ( ! dir . exists ( ) || ! dir . isDirectory ( ) ) { throw new IOException ( format ( "The chaincode path \"%s\" is invalid" , projectPath ) ) ; } StringBuilder hashBuilder = new StringBuilder ( hash ) ; Files . walk ( projectPath ) . sorted ( Comparator . naturalOrder ( ) ) . filter ( Files :: isRegularFile ) . map ( Path :: toFile ) . forEach ( file -> { try { byte [ ] buf = readFile ( file ) ; byte [ ] toHash = Arrays . concatenate ( buf , hashBuilder . toString ( ) . getBytes ( UTF_8 ) ) ; hashBuilder . setLength ( 0 ) ; hashBuilder . append ( Hex . toHexString ( hash ( toHash , new SHA3Digest ( ) ) ) ) ; } catch ( IOException ex ) { throw new RuntimeException ( format ( "Error while reading file %s" , file . getAbsolutePath ( ) ) , ex ) ; } } ) ; if ( hashBuilder . toString ( ) . equals ( hash ) ) { throw new IOException ( format ( "The chaincode directory \"%s\" has no files" , projectPath ) ) ; } return hashBuilder . toString ( ) ; }
Generate hash of a chaincode directory
32,442
public static byte [ ] generateTarGz ( File sourceDirectory , String pathPrefix , File chaincodeMetaInf ) throws IOException { logger . trace ( format ( "generateTarGz: sourceDirectory: %s, pathPrefix: %s, chaincodeMetaInf: %s" , sourceDirectory == null ? "null" : sourceDirectory . getAbsolutePath ( ) , pathPrefix , chaincodeMetaInf == null ? "null" : chaincodeMetaInf . getAbsolutePath ( ) ) ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( 500000 ) ; String sourcePath = sourceDirectory . getAbsolutePath ( ) ; TarArchiveOutputStream archiveOutputStream = new TarArchiveOutputStream ( new GzipCompressorOutputStream ( bos ) ) ; archiveOutputStream . setLongFileMode ( TarArchiveOutputStream . LONGFILE_GNU ) ; try { Collection < File > childrenFiles = org . apache . commons . io . FileUtils . listFiles ( sourceDirectory , null , true ) ; ArchiveEntry archiveEntry ; FileInputStream fileInputStream ; for ( File childFile : childrenFiles ) { String childPath = childFile . getAbsolutePath ( ) ; String relativePath = childPath . substring ( ( sourcePath . length ( ) + 1 ) , childPath . length ( ) ) ; if ( pathPrefix != null ) { relativePath = Utils . combinePaths ( pathPrefix , relativePath ) ; } relativePath = FilenameUtils . separatorsToUnix ( relativePath ) ; if ( TRACE_ENABED ) { logger . trace ( format ( "generateTarGz: Adding '%s' entry from source '%s' to archive." , relativePath , childFile . getAbsolutePath ( ) ) ) ; } archiveEntry = new TarArchiveEntry ( childFile , relativePath ) ; fileInputStream = new FileInputStream ( childFile ) ; archiveOutputStream . putArchiveEntry ( archiveEntry ) ; try { IOUtils . copy ( fileInputStream , archiveOutputStream ) ; } finally { IOUtils . closeQuietly ( fileInputStream ) ; archiveOutputStream . closeArchiveEntry ( ) ; } } if ( null != chaincodeMetaInf ) { childrenFiles = org . apache . commons . io . FileUtils . listFiles ( chaincodeMetaInf , null , true ) ; final URI metabase = chaincodeMetaInf . toURI ( ) ; for ( File childFile : childrenFiles ) { final String relativePath = Paths . get ( "META-INF" , metabase . relativize ( childFile . toURI ( ) ) . getPath ( ) ) . toString ( ) ; if ( TRACE_ENABED ) { logger . trace ( format ( "generateTarGz: Adding '%s' entry from source '%s' to archive." , relativePath , childFile . getAbsolutePath ( ) ) ) ; } archiveEntry = new TarArchiveEntry ( childFile , relativePath ) ; fileInputStream = new FileInputStream ( childFile ) ; archiveOutputStream . putArchiveEntry ( archiveEntry ) ; try { IOUtils . copy ( fileInputStream , archiveOutputStream ) ; } finally { IOUtils . closeQuietly ( fileInputStream ) ; archiveOutputStream . closeArchiveEntry ( ) ; } } } } finally { IOUtils . closeQuietly ( archiveOutputStream ) ; } return bos . toByteArray ( ) ; }
Compress the contents of given directory using Tar and Gzip to an in - memory byte array .
32,443
public static byte [ ] readFile ( File input ) throws IOException { return Files . readAllBytes ( Paths . get ( input . getAbsolutePath ( ) ) ) ; }
Read the contents a file .
32,444
public static void deleteFileOrDirectory ( File file ) throws IOException { if ( file . exists ( ) ) { if ( file . isDirectory ( ) ) { Path rootPath = Paths . get ( file . getAbsolutePath ( ) ) ; Files . walk ( rootPath , FileVisitOption . FOLLOW_LINKS ) . sorted ( Comparator . reverseOrder ( ) ) . map ( Path :: toFile ) . forEach ( File :: delete ) ; } else { file . delete ( ) ; } } else { throw new RuntimeException ( "File or directory does not exist" ) ; } }
Delete a file or directory
32,445
public static String combinePaths ( String first , String ... other ) { return Paths . get ( first , other ) . toString ( ) ; }
Combine two or more paths
32,446
public static byte [ ] readFileFromClasspath ( String fileName ) throws IOException { InputStream is = Utils . class . getClassLoader ( ) . getResourceAsStream ( fileName ) ; byte [ ] data = ByteStreams . toByteArray ( is ) ; try { is . close ( ) ; } catch ( IOException ex ) { } return data ; }
Read a file from classpath
32,447
public static Exception checkGrpcUrl ( String url ) { try { parseGrpcUrl ( url ) ; return null ; } catch ( Exception e ) { return e ; } }
Check if the strings Grpc url is valid
32,448
public static String logString ( final String string ) { if ( string == null || string . length ( ) == 0 ) { return string ; } String ret = string . replaceAll ( "[^\\p{Print}]" , "?" ) ; ret = ret . substring ( 0 , Math . min ( ret . length ( ) , MAX_LOG_STRING_LENGTH ) ) + ( ret . length ( ) > MAX_LOG_STRING_LENGTH ? "..." : "" ) ; return ret ; }
Makes logging strings which can be long or with unprintable characters be logged and trimmed .
32,449
public Map < Integer , String > getSecurityCurveMapping ( ) { if ( curveMapping == null ) { curveMapping = parseSecurityCurveMappings ( getProperty ( SECURITY_CURVE_MAPPING ) ) ; } return Collections . unmodifiableMap ( curveMapping ) ; }
Get a mapping from strength to curve desired .
32,450
public DiagnosticFileDumper getDiagnosticFileDumper ( ) { if ( diagnosticFileDumper != null ) { return diagnosticFileDumper ; } String dd = sdkProperties . getProperty ( DIAGNOTISTIC_FILE_DIRECTORY ) ; if ( dd != null ) { diagnosticFileDumper = DiagnosticFileDumper . configInstance ( new File ( dd ) ) ; } return diagnosticFileDumper ; }
The directory where diagnostic dumps are to be place null if none should be done .
32,451
public Boolean getLifecycleInitRequiredDefault ( ) { String property = getProperty ( LIFECYCLE_INITREQUIREDDEFAULT ) ; if ( property != null ) { return Boolean . parseBoolean ( property ) ; } return null ; }
Whether require init method in chaincode to be run . The default will return null which will not set the Fabric protobuf value which then sets false . False is the Fabric default .
32,452
public void setChaincodeInputStream ( InputStream chaincodeInputStream ) throws InvalidArgumentException { if ( chaincodeInputStream == null ) { throw new InvalidArgumentException ( "Chaincode input stream may not be null." ) ; } if ( chaincodeSourceLocation != null ) { throw new InvalidArgumentException ( "Error setting chaincode input stream. Chaincode source location already set. Only one or the other maybe set." ) ; } if ( chaincodeMetaInfLocation != null ) { throw new InvalidArgumentException ( "Error setting chaincode input stream. Chaincode META-INF location already set. Only one or the other maybe set." ) ; } this . chaincodeInputStream = chaincodeInputStream ; }
Chaincode input stream containing the actual chaincode . Only format supported is a tar zip compressed input of the source . Only input stream or source location maybe used at the same time . The contents of the stream are not validated or inspected by the SDK .
32,453
public void setChaincodeSourceLocation ( File chaincodeSourceLocation ) throws InvalidArgumentException { if ( chaincodeSourceLocation == null ) { throw new InvalidArgumentException ( "Chaincode source location may not be null." ) ; } if ( chaincodeInputStream != null ) { throw new InvalidArgumentException ( "Error setting chaincode location. Chaincode input stream already set. Only one or the other maybe set." ) ; } this . chaincodeSourceLocation = chaincodeSourceLocation ; }
The location of the chaincode . Chaincode input stream and source location can not both be set .
32,454
public void setChaincodeCollectionConfiguration ( ChaincodeCollectionConfiguration collectionConfigPackage ) throws InvalidArgumentException { if ( null == collectionConfigPackage ) { throw new InvalidArgumentException ( "The parameter collectionConfigPackage may not be null." ) ; } this . collectionConfigPackage = collectionConfigPackage . getCollectionConfigPackage ( ) ; }
The collection configuration for the approval being queried for .
32,455
public Channel addPeer ( Peer peer , PeerOptions peerOptions ) throws InvalidArgumentException { if ( shutdown ) { throw new InvalidArgumentException ( format ( "Channel %s has been shutdown." , name ) ) ; } if ( null == peer ) { throw new InvalidArgumentException ( "Peer is invalid can not be null." ) ; } if ( peer . getChannel ( ) != null && peer . getChannel ( ) != this ) { throw new InvalidArgumentException ( format ( "Peer already connected to channel %s" , peer . getChannel ( ) . getName ( ) ) ) ; } if ( null == peerOptions ) { throw new InvalidArgumentException ( "peerOptions is invalid can not be null." ) ; } logger . debug ( format ( "%s adding peer: %s, peerOptions: %s" , toString ( ) , peer , "" + peerOptions ) ) ; peer . setChannel ( this ) ; peers . add ( peer ) ; peerOptionsMap . put ( peer , peerOptions . clone ( ) ) ; peerEndpointMap . put ( peer . getEndpoint ( ) , peer ) ; if ( peerOptions . getPeerRoles ( ) . contains ( PeerRole . SERVICE_DISCOVERY ) ) { final Properties properties = peer . getProperties ( ) ; if ( ( properties == null ) || properties . isEmpty ( ) || ( isNullOrEmpty ( properties . getProperty ( "clientCertFile" ) ) && ! properties . containsKey ( "clientCertBytes" ) ) ) { TLSCertificateBuilder tlsCertificateBuilder = new TLSCertificateBuilder ( ) ; TLSCertificateKeyPair tlsCertificateKeyPair = tlsCertificateBuilder . clientCert ( ) ; peer . setTLSCertificateKeyPair ( tlsCertificateKeyPair ) ; } discoveryEndpoints . add ( peer . getEndpoint ( ) ) ; } for ( Map . Entry < PeerRole , Set < Peer > > peerRole : peerRoleSetMap . entrySet ( ) ) { if ( peerOptions . getPeerRoles ( ) . contains ( peerRole . getKey ( ) ) ) { peerRole . getValue ( ) . add ( peer ) ; } } if ( isInitialized ( ) && peerOptions . getPeerRoles ( ) . contains ( PeerRole . EVENT_SOURCE ) ) { try { peer . initiateEventing ( getTransactionContext ( ) , getPeersOptions ( peer ) ) ; } catch ( TransactionException e ) { logger . error ( format ( "Error channel %s enabling eventing on peer %s" , toString ( ) , peer ) ) ; } } return this ; }
Add a peer to the channel
32,456
public Channel addOrderer ( Orderer orderer ) throws InvalidArgumentException { if ( shutdown ) { throw new InvalidArgumentException ( format ( "Channel %s has been shutdown." , name ) ) ; } if ( null == orderer ) { throw new InvalidArgumentException ( "Orderer is invalid can not be null." ) ; } logger . debug ( format ( "Channel %s adding %s" , toString ( ) , orderer . toString ( ) ) ) ; orderer . setChannel ( this ) ; ordererEndpointMap . put ( orderer . getEndpoint ( ) , orderer ) ; orderers . add ( orderer ) ; return this ; }
Add an Orderer to this channel .
32,457
public Collection < Peer > getPeers ( EnumSet < PeerRole > roles ) { Set < Peer > ret = new HashSet < > ( getPeers ( ) . size ( ) ) ; for ( PeerRole peerRole : roles ) { ret . addAll ( peerRoleSetMap . get ( peerRole ) ) ; } return Collections . unmodifiableCollection ( ret ) ; }
Get the peers for this channel .
32,458
PeerOptions setPeerOptions ( Peer peer , PeerOptions peerOptions ) throws InvalidArgumentException { if ( initialized ) { throw new InvalidArgumentException ( format ( "Channel %s already initialized." , name ) ) ; } checkPeer ( peer ) ; PeerOptions ret = getPeersOptions ( peer ) ; removePeerInternal ( peer ) ; addPeer ( peer , peerOptions ) ; return ret ; }
Set peerOptions in the channel that has not be initialized yet .
32,459
public Channel initialize ( ) throws InvalidArgumentException , TransactionException { logger . debug ( format ( "Channel %s initialize shutdown %b" , name , shutdown ) ) ; if ( isInitialized ( ) ) { return this ; } if ( shutdown ) { throw new InvalidArgumentException ( format ( "Channel %s has been shutdown." , name ) ) ; } if ( isNullOrEmpty ( name ) ) { throw new InvalidArgumentException ( "Can not initialize channel without a valid name." ) ; } if ( client == null ) { throw new InvalidArgumentException ( "Can not initialize channel without a client object." ) ; } userContextCheck ( client . getUserContext ( ) ) ; if ( null == sdOrdererAddition ) { setSDOrdererAddition ( new SDOrdererDefaultAddition ( getServiceDiscoveryProperties ( ) ) ) ; } if ( null == sdPeerAddition ) { setSDPeerAddition ( new SDOPeerDefaultAddition ( getServiceDiscoveryProperties ( ) ) ) ; } try { loadCACertificates ( false ) ; } catch ( Exception e ) { logger . warn ( format ( "Channel %s could not load peer CA certificates from any peers." , name ) ) ; } Collection < Peer > serviceDiscoveryPeers = getServiceDiscoveryPeers ( ) ; if ( ! serviceDiscoveryPeers . isEmpty ( ) ) { logger . trace ( "Starting service discovery." ) ; this . serviceDiscovery = new ServiceDiscovery ( this , serviceDiscoveryPeers , getTransactionContext ( ) ) ; serviceDiscovery . fullNetworkDiscovery ( true ) ; serviceDiscovery . run ( ) ; logger . trace ( "Completed. service discovery." ) ; } try { logger . debug ( format ( "Eventque started %s" , "" + eventQueueThread ) ) ; for ( Peer peer : getEventingPeers ( ) ) { peer . initiateEventing ( getTransactionContext ( ) , getPeersOptions ( peer ) ) ; } transactionListenerProcessorHandle = registerTransactionListenerProcessor ( ) ; logger . debug ( format ( "Channel %s registerTransactionListenerProcessor completed" , name ) ) ; if ( serviceDiscovery != null ) { chaincodeEventUpgradeListenerHandle = registerChaincodeEventListener ( Pattern . compile ( "^lscc$" ) , Pattern . compile ( "^upgrade$" ) , ( handle , blockEvent , chaincodeEvent ) -> { logger . debug ( format ( "Channel %s got upgrade chaincode event" , name ) ) ; if ( ! isShutdown ( ) && isChaincodeUpgradeEvent ( blockEvent . getBlockNumber ( ) ) ) { getExecutorService ( ) . execute ( ( ) -> serviceDiscovery . fullNetworkDiscovery ( true ) ) ; } } ) ; } startEventQue ( ) ; logger . info ( format ( "Channel %s eventThread started shutdown: %b thread: %s " , toString ( ) , shutdown , eventQueueThread == null ? "null" : eventQueueThread . getName ( ) ) ) ; this . initialized = true ; logger . debug ( format ( "Channel %s initialized" , name ) ) ; return this ; } catch ( Exception e ) { TransactionException exp = new TransactionException ( e ) ; logger . error ( exp . getMessage ( ) , exp ) ; throw exp ; } }
Initialize the Channel . Starts the channel . event hubs will connect .
32,460
protected synchronized void loadCACertificates ( boolean force ) throws InvalidArgumentException , CryptoException , TransactionException { if ( ! force && msps != null && ! msps . isEmpty ( ) ) { return ; } logger . debug ( format ( "Channel %s loadCACertificates" , name ) ) ; Map < String , MSP > lmsp = parseConfigBlock ( force ) ; if ( lmsp == null || lmsp . isEmpty ( ) ) { throw new InvalidArgumentException ( "Unable to load CA certificates. Channel " + name + " does not have any MSPs." ) ; } List < byte [ ] > certList ; for ( MSP msp : lmsp . values ( ) ) { logger . debug ( "loading certificates for MSP : " + msp . getID ( ) ) ; certList = Arrays . asList ( msp . getRootCerts ( ) ) ; if ( certList . size ( ) > 0 ) { client . getCryptoSuite ( ) . loadCACertificatesAsBytes ( certList ) ; } certList = Arrays . asList ( msp . getIntermediateCerts ( ) ) ; if ( certList . size ( ) > 0 ) { client . getCryptoSuite ( ) . loadCACertificatesAsBytes ( certList ) ; } } logger . debug ( format ( "Channel %s loadCACertificates completed " , name ) ) ; }
load the peer organizations CA certificates into the channel s trust store so that we can verify signatures from peer messages
32,461
public byte [ ] getUpdateChannelConfigurationSignature ( UpdateChannelConfiguration updateChannelConfiguration , User signer ) throws InvalidArgumentException { userContextCheck ( signer ) ; if ( null == updateChannelConfiguration ) { throw new InvalidArgumentException ( "channelConfiguration is null" ) ; } try { TransactionContext transactionContext = getTransactionContext ( signer ) ; final ByteString configUpdate = ByteString . copyFrom ( updateChannelConfiguration . getUpdateChannelConfigurationAsBytes ( ) ) ; ByteString sigHeaderByteString = getSignatureHeaderAsByteString ( signer , transactionContext ) ; ByteString signatureByteSting = transactionContext . signByteStrings ( new User [ ] { signer } , sigHeaderByteString , configUpdate ) [ 0 ] ; return ConfigSignature . newBuilder ( ) . setSignatureHeader ( sigHeaderByteString ) . setSignature ( signatureByteSting ) . build ( ) . toByteArray ( ) ; } catch ( Exception e ) { throw new InvalidArgumentException ( e ) ; } finally { logger . debug ( "finally done" ) ; } }
Get signed byes of the update channel .
32,462
private Block getConfigurationBlock ( ) throws TransactionException { logger . debug ( format ( "getConfigurationBlock for channel %s" , name ) ) ; try { Orderer orderer = getRandomOrderer ( ) ; long lastConfigIndex = getLastConfigIndex ( orderer ) ; logger . debug ( format ( "Last config index is %d" , lastConfigIndex ) ) ; Block configBlock = getBlockByNumber ( lastConfigIndex ) ; Envelope envelopeRet = Envelope . parseFrom ( configBlock . getData ( ) . getData ( 0 ) ) ; Payload payload = Payload . parseFrom ( envelopeRet . getPayload ( ) ) ; ChannelHeader channelHeader = ChannelHeader . parseFrom ( payload . getHeader ( ) . getChannelHeader ( ) ) ; if ( channelHeader . getType ( ) != HeaderType . CONFIG . getNumber ( ) ) { throw new TransactionException ( format ( "Bad last configuration block type %d, expected %d" , channelHeader . getType ( ) , HeaderType . CONFIG . getNumber ( ) ) ) ; } if ( ! name . equals ( channelHeader . getChannelId ( ) ) ) { throw new TransactionException ( format ( "Bad last configuration block channel id %s, expected %s" , channelHeader . getChannelId ( ) , name ) ) ; } if ( null != diagnosticFileDumper ) { logger . trace ( format ( "Channel %s getConfigurationBlock returned %s" , name , diagnosticFileDumper . createDiagnosticFile ( String . valueOf ( configBlock ) . getBytes ( ) ) ) ) ; } if ( ! logger . isTraceEnabled ( ) ) { logger . debug ( format ( "Channel %s getConfigurationBlock returned" , name ) ) ; } return configBlock ; } catch ( TransactionException e ) { logger . error ( e . getMessage ( ) , e ) ; throw e ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; throw new TransactionException ( e ) ; } }
Provide the Channel s latest raw Configuration Block .
32,463
Collection < ProposalResponse > sendInstallProposal ( InstallProposalRequest installProposalRequest ) throws ProposalException , InvalidArgumentException { return sendInstallProposal ( installProposalRequest , getChaincodePeers ( ) ) ; }
Send install chaincode request proposal to all the channels on the peer .
32,464
Collection < ProposalResponse > sendInstallProposal ( InstallProposalRequest installProposalRequest , Collection < Peer > peers ) throws ProposalException , InvalidArgumentException { checkChannelState ( ) ; checkPeers ( peers ) ; if ( null == installProposalRequest ) { throw new InvalidArgumentException ( "InstallProposalRequest is null" ) ; } try { TransactionContext transactionContext = getTransactionContext ( installProposalRequest . getUserContext ( ) ) ; transactionContext . verify ( false ) ; transactionContext . setProposalWaitTime ( installProposalRequest . getProposalWaitTime ( ) ) ; InstallProposalBuilder installProposalbuilder = InstallProposalBuilder . newBuilder ( ) ; installProposalbuilder . context ( transactionContext ) ; installProposalbuilder . setChaincodeLanguage ( installProposalRequest . getChaincodeLanguage ( ) ) ; installProposalbuilder . chaincodeName ( installProposalRequest . getChaincodeName ( ) ) ; installProposalbuilder . chaincodePath ( installProposalRequest . getChaincodePath ( ) ) ; installProposalbuilder . chaincodeVersion ( installProposalRequest . getChaincodeVersion ( ) ) ; installProposalbuilder . setChaincodeSource ( installProposalRequest . getChaincodeSourceLocation ( ) ) ; installProposalbuilder . setChaincodeInputStream ( installProposalRequest . getChaincodeInputStream ( ) ) ; installProposalbuilder . setChaincodeMetaInfLocation ( installProposalRequest . getChaincodeMetaInfLocation ( ) ) ; FabricProposal . Proposal deploymentProposal = installProposalbuilder . build ( ) ; SignedProposal signedProposal = getSignedProposal ( transactionContext , deploymentProposal ) ; return sendProposalToPeers ( peers , signedProposal , transactionContext ) ; } catch ( Exception e ) { throw new ProposalException ( e ) ; } }
Send install chaincode request proposal to the channel .
32,465
public BlockInfo queryBlockByHash ( byte [ ] blockHash ) throws InvalidArgumentException , ProposalException { return queryBlockByHash ( getShuffledPeers ( EnumSet . of ( PeerRole . LEDGER_QUERY ) ) , blockHash ) ; }
query this channel for a Block by the block hash . The request is retried on each peer on the channel till successful .
32,466
public BlockInfo queryBlockByHash ( Collection < Peer > peers , byte [ ] blockHash ) throws InvalidArgumentException , ProposalException { return queryBlockByHash ( peers , blockHash , client . getUserContext ( ) ) ; }
Query a peer in this channel for a Block by the block hash . Each peer is tried until successful response .
32,467
public BlockInfo queryBlockByNumber ( long blockNumber ) throws InvalidArgumentException , ProposalException { return queryBlockByNumber ( getShuffledPeers ( EnumSet . of ( PeerRole . LEDGER_QUERY ) ) , blockNumber ) ; }
query this channel for a Block by the blockNumber . The request is retried on all peers till successful
32,468
public BlockInfo queryBlockByNumber ( Peer peer , long blockNumber ) throws InvalidArgumentException , ProposalException { return queryBlockByNumber ( Collections . singleton ( peer ) , blockNumber ) ; }
Query a peer in this channel for a Block by the blockNumber
32,469
public BlockInfo queryBlockByTransactionID ( String txID ) throws InvalidArgumentException , ProposalException { return queryBlockByTransactionID ( getShuffledPeers ( EnumSet . of ( PeerRole . LEDGER_QUERY ) ) , txID ) ; }
query this channel for a Block by a TransactionID contained in the block The request is tried on on each peer till successful .
32,470
public Collection < LifecycleCommitChaincodeDefinitionProposalResponse > sendLifecycleCommitChaincodeDefinitionProposal ( LifecycleCommitChaincodeDefinitionRequest lifecycleCommitChaincodeDefinitionRequest , Collection < Peer > peers ) throws InvalidArgumentException , ProposalException { if ( null == lifecycleCommitChaincodeDefinitionRequest ) { throw new InvalidArgumentException ( "The lifecycleCommitChaincodeDefinitionRequest parameter can not be null." ) ; } checkChannelState ( ) ; checkPeers ( peers ) ; try { if ( IS_TRACE_LEVEL ) { String collectionData = "null" ; final ChaincodeCollectionConfiguration chaincodeCollectionConfiguration = lifecycleCommitChaincodeDefinitionRequest . getChaincodeCollectionConfiguration ( ) ; if ( null != chaincodeCollectionConfiguration ) { final byte [ ] asBytes = chaincodeCollectionConfiguration . getAsBytes ( ) ; if ( null != asBytes ) { collectionData = toHexString ( asBytes ) ; } } logger . trace ( format ( "LifecycleCommitChaincodeDefinition channel: %s, sequence: %d, chaincodeName: %s, chaincodeVersion: %s" + ", isInitRequired: %s, validationParameter: '%s', endorsementPolicyPlugin: %s, validationPlugin: %s" + ", collectionConfiguration: %s" , name , lifecycleCommitChaincodeDefinitionRequest . getSequence ( ) , lifecycleCommitChaincodeDefinitionRequest . getChaincodeName ( ) , lifecycleCommitChaincodeDefinitionRequest . getChaincodeVersion ( ) , lifecycleCommitChaincodeDefinitionRequest . isInitRequired ( ) + "" , toHexString ( lifecycleCommitChaincodeDefinitionRequest . getValidationParameter ( ) ) , lifecycleCommitChaincodeDefinitionRequest . getChaincodeEndorsementPlugin ( ) , lifecycleCommitChaincodeDefinitionRequest . getChaincodeValidationPlugin ( ) , collectionData ) ) ; } TransactionContext transactionContext = getTransactionContext ( lifecycleCommitChaincodeDefinitionRequest ) ; LifecycleCommitChaincodeDefinitionProposalBuilder commitChaincodeDefinitionProposalBuilder = LifecycleCommitChaincodeDefinitionProposalBuilder . newBuilder ( ) ; commitChaincodeDefinitionProposalBuilder . context ( transactionContext ) ; commitChaincodeDefinitionProposalBuilder . chaincodeName ( lifecycleCommitChaincodeDefinitionRequest . getChaincodeName ( ) ) ; commitChaincodeDefinitionProposalBuilder . version ( lifecycleCommitChaincodeDefinitionRequest . getChaincodeVersion ( ) ) ; commitChaincodeDefinitionProposalBuilder . sequence ( lifecycleCommitChaincodeDefinitionRequest . getSequence ( ) ) ; Boolean initRequired = lifecycleCommitChaincodeDefinitionRequest . isInitRequired ( ) ; if ( null != initRequired ) { commitChaincodeDefinitionProposalBuilder . initRequired ( initRequired ) ; } ByteString validationParameter = lifecycleCommitChaincodeDefinitionRequest . getValidationParameter ( ) ; if ( null != validationParameter ) { commitChaincodeDefinitionProposalBuilder . setValidationParamter ( validationParameter ) ; } String chaincodeCodeEndorsementPlugin = lifecycleCommitChaincodeDefinitionRequest . getChaincodeEndorsementPlugin ( ) ; if ( null != chaincodeCodeEndorsementPlugin ) { commitChaincodeDefinitionProposalBuilder . chaincodeCodeEndorsementPlugin ( chaincodeCodeEndorsementPlugin ) ; } String chaincodeCodeValidationPlugin = lifecycleCommitChaincodeDefinitionRequest . getChaincodeValidationPlugin ( ) ; if ( null != chaincodeCodeValidationPlugin ) { commitChaincodeDefinitionProposalBuilder . chaincodeCodeValidationPlugin ( chaincodeCodeValidationPlugin ) ; } ChaincodeCollectionConfiguration chaincodeCollectionConfiguration = lifecycleCommitChaincodeDefinitionRequest . getChaincodeCollectionConfiguration ( ) ; if ( null != chaincodeCollectionConfiguration ) { commitChaincodeDefinitionProposalBuilder . chaincodeCollectionConfiguration ( chaincodeCollectionConfiguration . getCollectionConfigPackage ( ) ) ; } FabricProposal . Proposal deploymentProposal = commitChaincodeDefinitionProposalBuilder . build ( ) ; SignedProposal signedProposal = getSignedProposal ( transactionContext , deploymentProposal ) ; return sendProposalToPeers ( peers , signedProposal , transactionContext , LifecycleCommitChaincodeDefinitionProposalResponse . class ) ; } catch ( Exception e ) { throw new ProposalException ( e ) ; } }
Commit chaincode final approval to run on all organizations that have approved .
32,471
public Collection < LifecycleQueryNamespaceDefinitionsProposalResponse > lifecycleQueryNamespaceDefinitions ( LifecycleQueryNamespaceDefinitionsRequest queryNamespaceDefinitionsRequest , Collection < Peer > peers ) throws InvalidArgumentException , ProposalException { if ( null == queryNamespaceDefinitionsRequest ) { throw new InvalidArgumentException ( "The queryNamespaceDefinitionsRequest parameter can not be null." ) ; } checkChannelState ( ) ; checkPeers ( peers ) ; try { logger . trace ( format ( "lifecycleQueryNamespaceDefinitions channel: %s" , name ) ) ; TransactionContext context = getTransactionContext ( queryNamespaceDefinitionsRequest ) ; LifecycleQueryNamespaceDefinitionsBuilder q = LifecycleQueryNamespaceDefinitionsBuilder . newBuilder ( ) ; q . context ( context ) ; SignedProposal qProposal = getSignedProposal ( context , q . build ( ) ) ; return sendProposalToPeers ( peers , qProposal , context , LifecycleQueryNamespaceDefinitionsProposalResponse . class ) ; } catch ( Exception e ) { throw new ProposalException ( format ( "QueryNamespaceDefinitions %s channel failed. " + e . getMessage ( ) , name ) , e ) ; } }
Query namespaces . Takes no specific arguments returns namespaces including chaincode names that have been committed .
32,472
public Collection < LifecycleQueryApprovalStatusProposalResponse > sendLifecycleQueryApprovalStatusRequest ( LifecycleQueryApprovalStatusRequest lifecycleQueryApprovalStatusRequest , Collection < Peer > peers ) throws InvalidArgumentException , ProposalException { if ( null == lifecycleQueryApprovalStatusRequest ) { throw new InvalidArgumentException ( "The lifecycleQueryApprovalStatusRequest parameter can not be null." ) ; } checkChannelState ( ) ; checkPeers ( peers ) ; try { if ( IS_TRACE_LEVEL ) { String collectionData = "null" ; final org . hyperledger . fabric . protos . common . Collection . CollectionConfigPackage chaincodeCollectionConfiguration = lifecycleQueryApprovalStatusRequest . getCollectionConfigPackage ( ) ; if ( null != chaincodeCollectionConfiguration ) { final byte [ ] asBytes = chaincodeCollectionConfiguration . toByteArray ( ) ; if ( null != asBytes ) { collectionData = toHexString ( asBytes ) ; } } logger . trace ( format ( "LifecycleQueryApprovalStatus channel: %s, sequence: %d, chaincodeName: %s, chaincodeVersion: %s" + ", isInitRequired: %s, validationParameter: '%s', endorsementPolicyPlugin: %s, validationPlugin: %s" + ", collectionConfiguration: %s" , name , lifecycleQueryApprovalStatusRequest . getSequence ( ) , lifecycleQueryApprovalStatusRequest . getChaincodeName ( ) , lifecycleQueryApprovalStatusRequest . getChaincodeVersion ( ) , lifecycleQueryApprovalStatusRequest . isInitRequired ( ) + "" , toHexString ( lifecycleQueryApprovalStatusRequest . getValidationParameter ( ) ) , lifecycleQueryApprovalStatusRequest . getChaincodeEndorsementPlugin ( ) , lifecycleQueryApprovalStatusRequest . getChaincodeValidationPlugin ( ) , collectionData ) ) ; } TransactionContext context = getTransactionContext ( lifecycleQueryApprovalStatusRequest ) ; LifecycleQueryApprovalStatusBuilder lifecycleQueryApprovalStatusBuilder = LifecycleQueryApprovalStatusBuilder . newBuilder ( ) ; lifecycleQueryApprovalStatusBuilder . setSequence ( lifecycleQueryApprovalStatusRequest . getSequence ( ) ) ; lifecycleQueryApprovalStatusBuilder . setName ( lifecycleQueryApprovalStatusRequest . getChaincodeName ( ) ) ; lifecycleQueryApprovalStatusBuilder . setVersion ( lifecycleQueryApprovalStatusRequest . getChaincodeVersion ( ) ) ; String endorsementPlugin = lifecycleQueryApprovalStatusRequest . getChaincodeEndorsementPlugin ( ) ; if ( ! isNullOrEmpty ( endorsementPlugin ) ) { lifecycleQueryApprovalStatusBuilder . setEndorsementPlugin ( endorsementPlugin ) ; } String validationPlugin = lifecycleQueryApprovalStatusRequest . getChaincodeValidationPlugin ( ) ; if ( ! isNullOrEmpty ( validationPlugin ) ) { lifecycleQueryApprovalStatusBuilder . setValidationPlugin ( validationPlugin ) ; } ByteString validationParameter = lifecycleQueryApprovalStatusRequest . getValidationParameter ( ) ; if ( null != validationParameter ) { lifecycleQueryApprovalStatusBuilder . setValidationParameter ( validationParameter ) ; } org . hyperledger . fabric . protos . common . Collection . CollectionConfigPackage collectionConfigPackage = lifecycleQueryApprovalStatusRequest . getCollectionConfigPackage ( ) ; if ( null != collectionConfigPackage ) { lifecycleQueryApprovalStatusBuilder . setCollections ( collectionConfigPackage ) ; } Boolean initRequired = lifecycleQueryApprovalStatusRequest . isInitRequired ( ) ; if ( null != initRequired ) { lifecycleQueryApprovalStatusBuilder . setInitRequired ( initRequired ) ; } lifecycleQueryApprovalStatusBuilder . context ( context ) ; SignedProposal qProposal = getSignedProposal ( context , lifecycleQueryApprovalStatusBuilder . build ( ) ) ; return sendProposalToPeers ( peers , qProposal , context , LifecycleQueryApprovalStatusProposalResponse . class ) ; } catch ( Exception e ) { throw new ProposalException ( format ( "QueryNamespaceDefinitions %s channel failed. " + e . getMessage ( ) , name ) , e ) ; } }
Query approval status for all organizations .
32,473
public Collection < LifecycleQueryChaincodeDefinitionProposalResponse > lifecycleQueryChaincodeDefinition ( QueryLifecycleQueryChaincodeDefinitionRequest queryLifecycleQueryChaincodeDefinitionRequest , Collection < Peer > peers ) throws InvalidArgumentException , ProposalException { if ( null == queryLifecycleQueryChaincodeDefinitionRequest ) { throw new InvalidArgumentException ( "The queryLifecycleQueryChaincodeDefinitionRequest parameter can not be null." ) ; } checkChannelState ( ) ; checkPeers ( peers ) ; try { logger . trace ( format ( "LifecycleQueryChaincodeDefinition channel: %s, chaincode name: %s" , name , queryLifecycleQueryChaincodeDefinitionRequest . getChaincodeName ( ) ) ) ; TransactionContext context = getTransactionContext ( queryLifecycleQueryChaincodeDefinitionRequest ) ; LifecycleQueryChaincodeDefinitionBuilder lifecycleQueryChaincodeDefinitionBuilder = LifecycleQueryChaincodeDefinitionBuilder . newBuilder ( ) ; lifecycleQueryChaincodeDefinitionBuilder . context ( context ) . setChaincodeName ( queryLifecycleQueryChaincodeDefinitionRequest . getChaincodeName ( ) ) ; SignedProposal qProposal = getSignedProposal ( context , lifecycleQueryChaincodeDefinitionBuilder . build ( ) ) ; return sendProposalToPeers ( peers , qProposal , context , LifecycleQueryChaincodeDefinitionProposalResponse . class ) ; } catch ( ProposalException e ) { throw e ; } catch ( Exception e ) { throw new ProposalException ( format ( "Query for peer %s channels failed. " + e . getMessage ( ) , name ) , e ) ; } }
lifecycleQueryChaincodeDefinition get definition of chaincode .
32,474
public List < ChaincodeInfo > queryInstantiatedChaincodes ( Peer peer ) throws InvalidArgumentException , ProposalException { return queryInstantiatedChaincodes ( peer , client . getUserContext ( ) ) ; }
Query peer for chaincode that has been instantiated
32,475
public CollectionConfigPackage queryCollectionsConfig ( String chaincodeName , Peer peer , User userContext ) throws InvalidArgumentException , ProposalException { if ( isNullOrEmpty ( chaincodeName ) ) { throw new InvalidArgumentException ( "Parameter chaincodeName expected to be non null or empty string." ) ; } checkChannelState ( ) ; checkPeer ( peer ) ; User . userContextCheck ( userContext ) ; try { TransactionContext context = getTransactionContext ( userContext ) ; QueryCollectionsConfigBuilder queryCollectionsConfigBuilder = QueryCollectionsConfigBuilder . newBuilder ( ) . context ( context ) . chaincodeName ( chaincodeName ) ; FabricProposal . Proposal q = queryCollectionsConfigBuilder . build ( ) ; SignedProposal qProposal = getSignedProposal ( context , q ) ; Collection < ProposalResponse > proposalResponses = sendProposalToPeers ( Collections . singletonList ( peer ) , qProposal , context ) ; if ( null == proposalResponses ) { throw new ProposalException ( format ( "Peer %s channel query return with null for responses" , peer . getName ( ) ) ) ; } if ( proposalResponses . size ( ) != 1 ) { throw new ProposalException ( format ( "Peer %s channel query expected one response but got back %d responses " , peer . getName ( ) , proposalResponses . size ( ) ) ) ; } ProposalResponse proposalResponse = proposalResponses . iterator ( ) . next ( ) ; FabricProposalResponse . ProposalResponse fabricResponse = proposalResponse . getProposalResponse ( ) ; if ( null == fabricResponse ) { throw new ProposalException ( format ( "Peer %s channel query return with empty fabric response" , peer . getName ( ) ) ) ; } final Response fabricResponseResponse = fabricResponse . getResponse ( ) ; if ( null == fabricResponseResponse ) { throw new ProposalException ( format ( "Peer %s channel query return with empty fabricResponseResponse" , peer . getName ( ) ) ) ; } if ( 200 != fabricResponseResponse . getStatus ( ) ) { throw new ProposalException ( format ( "Peer %s channel query expected 200, actual returned was: %d. " + fabricResponseResponse . getMessage ( ) , peer . getName ( ) , fabricResponseResponse . getStatus ( ) ) ) ; } return new CollectionConfigPackage ( fabricResponseResponse . getPayload ( ) ) ; } catch ( ProposalException e ) { throw e ; } catch ( Exception e ) { throw new ProposalException ( format ( "Query for peer %s channels failed. " + e . getMessage ( ) , name ) , e ) ; } }
Get information on the collections used by the chaincode .
32,476
public Collection < ProposalResponse > sendTransactionProposal ( TransactionProposalRequest transactionProposalRequest , Collection < Peer > peers ) throws ProposalException , InvalidArgumentException { return sendProposal ( transactionProposalRequest , peers ) ; }
Send a transaction proposal to specific peers .
32,477
public CompletableFuture < TransactionEvent > sendTransaction ( Collection < ProposalResponse > proposalResponses , User userContext ) { return sendTransaction ( proposalResponses , getOrderers ( ) , userContext ) ; }
Send transaction to one of the orderers on the channel using a specific user context .
32,478
public CompletableFuture < TransactionEvent > sendTransaction ( Collection < ? extends ProposalResponse > proposalResponses , Collection < Orderer > orderers ) { return sendTransaction ( proposalResponses , orderers , client . getUserContext ( ) ) ; }
Send transaction to one of the specified orderers using the usercontext set on the client ..
32,479
private String getRespData ( BroadcastResponse resp ) { StringBuilder respdata = new StringBuilder ( 400 ) ; if ( resp != null ) { Status status = resp . getStatus ( ) ; if ( null != status ) { respdata . append ( status . name ( ) ) ; respdata . append ( "-" ) ; respdata . append ( status . getNumber ( ) ) ; } String info = resp . getInfo ( ) ; if ( null != info && ! info . isEmpty ( ) ) { if ( respdata . length ( ) > 0 ) { respdata . append ( ", " ) ; } respdata . append ( "Additional information: " ) . append ( info ) ; } } return respdata . toString ( ) ; }
Build response details
32,480
public String registerBlockListener ( BlockListener listener ) throws InvalidArgumentException { if ( shutdown ) { throw new InvalidArgumentException ( format ( "Channel %s has been shutdown." , name ) ) ; } if ( null == listener ) { throw new InvalidArgumentException ( "Listener parameter is null." ) ; } String handle = new BL ( listener ) . getHandle ( ) ; logger . trace ( format ( "Register event BlockEvent listener %s" , handle ) ) ; return handle ; }
Register a block listener .
32,481
public boolean unregisterBlockListener ( String handle ) throws InvalidArgumentException { if ( shutdown ) { throw new InvalidArgumentException ( format ( "Channel %s has been shutdown." , name ) ) ; } checkHandle ( BLOCK_LISTENER_TAG , handle ) ; logger . trace ( format ( "Unregister BlockListener with handle %s." , handle ) ) ; LinkedHashMap < String , BL > lblockListeners = blockListeners ; if ( lblockListeners == null ) { return false ; } synchronized ( lblockListeners ) { return null != lblockListeners . remove ( handle ) ; } }
Unregister a block listener .
32,482
private String registerTransactionListenerProcessor ( ) throws InvalidArgumentException { logger . debug ( format ( "Channel %s registerTransactionListenerProcessor starting" , name ) ) ; return registerBlockListener ( blockEvent -> { HFClient lclient = client ; if ( null == lclient || shutdown ) { return ; } final String source = blockEvent . getPeer ( ) != null ? blockEvent . getPeer ( ) . toString ( ) : "not peer!" ; logger . debug ( format ( "is peer %b, is filtered: %b" , blockEvent . getPeer ( ) != null , blockEvent . isFiltered ( ) ) ) ; final Iterable < TransactionEvent > transactionEvents = blockEvent . getTransactionEvents ( ) ; if ( transactionEvents == null || ! transactionEvents . iterator ( ) . hasNext ( ) ) { if ( isLaterBlock ( blockEvent . getBlockNumber ( ) ) ) { ServiceDiscovery lserviceDiscovery = serviceDiscovery ; if ( null != lserviceDiscovery ) { client . getExecutorService ( ) . execute ( ( ) -> lserviceDiscovery . fullNetworkDiscovery ( true ) ) ; } } else { lclient . getExecutorService ( ) . execute ( ( ) -> { try { if ( ! shutdown ) { loadCACertificates ( true ) ; } } catch ( Exception e ) { logger . warn ( format ( "Channel %s failed to load certificates for an update" , name ) , e ) ; } } ) ; } return ; } if ( txListeners . isEmpty ( ) || shutdown ) { return ; } for ( TransactionEvent transactionEvent : blockEvent . getTransactionEvents ( ) ) { logger . debug ( format ( "Channel %s got event from %s for transaction %s in block number: %d" , name , source , transactionEvent . getTransactionID ( ) , blockEvent . getBlockNumber ( ) ) ) ; List < TL > txL = new ArrayList < > ( txListeners . size ( ) + 2 ) ; synchronized ( txListeners ) { LinkedList < TL > list = txListeners . get ( transactionEvent . getTransactionID ( ) ) ; if ( null != list ) { txL . addAll ( list ) ; } } for ( TL l : txL ) { try { if ( shutdown ) { break ; } if ( l . eventReceived ( transactionEvent ) ) { l . fire ( transactionEvent ) ; } } catch ( Throwable e ) { logger . error ( e ) ; } } } } ) ; }
Own block listener to manage transactions .
32,483
private CompletableFuture < TransactionEvent > registerTxListener ( String txid , NOfEvents nOfEvents , boolean failFast ) { CompletableFuture < TransactionEvent > future = new CompletableFuture < > ( ) ; new TL ( txid , future , nOfEvents , failFast ) ; return future ; }
Register a transactionId that to get notification on when the event is seen in the block chain .
32,484
public String registerChaincodeEventListener ( Pattern chaincodeId , Pattern eventName , ChaincodeEventListener chaincodeEventListener ) throws InvalidArgumentException { if ( shutdown ) { throw new InvalidArgumentException ( format ( "Channel %s has been shutdown." , name ) ) ; } if ( chaincodeId == null ) { throw new InvalidArgumentException ( "The chaincodeId argument may not be null." ) ; } if ( eventName == null ) { throw new InvalidArgumentException ( "The eventName argument may not be null." ) ; } if ( chaincodeEventListener == null ) { throw new InvalidArgumentException ( "The chaincodeEventListener argument may not be null." ) ; } ChaincodeEventListenerEntry chaincodeEventListenerEntry = new ChaincodeEventListenerEntry ( chaincodeId , eventName , chaincodeEventListener ) ; synchronized ( this ) { if ( null == blh ) { blh = registerChaincodeListenerProcessor ( ) ; } } return chaincodeEventListenerEntry . handle ; }
Register a chaincode event listener . Both chaincodeId pattern AND eventName pattern must match to invoke the chaincodeEventListener
32,485
public boolean unregisterChaincodeEventListener ( String handle ) throws InvalidArgumentException { boolean ret ; if ( shutdown ) { throw new InvalidArgumentException ( format ( "Channel %s has been shutdown." , name ) ) ; } checkHandle ( CHAINCODE_EVENTS_TAG , handle ) ; synchronized ( chainCodeListeners ) { ret = null != chainCodeListeners . remove ( handle ) ; } synchronized ( this ) { if ( null != blh && chainCodeListeners . isEmpty ( ) ) { unregisterBlockListener ( blh ) ; blh = null ; } } return ret ; }
Unregister an existing chaincode event listener .
32,486
public synchronized void shutdown ( boolean force ) { if ( shutdown ) { return ; } String ltransactionListenerProcessorHandle = transactionListenerProcessorHandle ; transactionListenerProcessorHandle = null ; if ( null != ltransactionListenerProcessorHandle ) { try { unregisterBlockListener ( ltransactionListenerProcessorHandle ) ; } catch ( Exception e ) { logger . error ( format ( "Shutting down channel %s transactionListenerProcessorHandle" , name ) , e ) ; } } String lchaincodeEventUpgradeListenerHandle = chaincodeEventUpgradeListenerHandle ; chaincodeEventUpgradeListenerHandle = null ; if ( null != lchaincodeEventUpgradeListenerHandle ) { try { unregisterChaincodeEventListener ( lchaincodeEventUpgradeListenerHandle ) ; } catch ( Exception e ) { logger . error ( format ( "Shutting down channel %s chaincodeEventUpgradeListenr" , name ) , e ) ; } } initialized = false ; shutdown = true ; final ServiceDiscovery lserviceDiscovery = serviceDiscovery ; serviceDiscovery = null ; if ( null != lserviceDiscovery ) { lserviceDiscovery . shutdown ( ) ; } if ( chainCodeListeners != null ) { chainCodeListeners . clear ( ) ; } if ( blockListeners != null ) { blockListeners . clear ( ) ; } if ( client != null ) { client . removeChannel ( this ) ; } client = null ; for ( Peer peer : new ArrayList < > ( getPeers ( ) ) ) { try { removePeerInternal ( peer ) ; peer . shutdown ( force ) ; } catch ( Exception e ) { } } peers . clear ( ) ; peerEndpointMap . clear ( ) ; ordererEndpointMap . clear ( ) ; for ( Set < Peer > peerRoleSet : peerRoleSetMap . values ( ) ) { peerRoleSet . clear ( ) ; } for ( Orderer orderer : getOrderers ( ) ) { orderer . shutdown ( force ) ; } orderers . clear ( ) ; if ( null != eventQueueThread ) { eventQueueThread . interrupt ( ) ; eventQueueThread = null ; } ScheduledFuture < ? > lsweeper = sweeper ; sweeper = null ; if ( null != lsweeper ) { lsweeper . cancel ( true ) ; } ScheduledExecutorService lse = sweeperExecutorService ; sweeperExecutorService = null ; if ( null != lse ) { lse . shutdownNow ( ) ; } }
Shutdown the channel with all resources released .
32,487
public void serializeChannel ( File file ) throws IOException , InvalidArgumentException { if ( null == file ) { throw new InvalidArgumentException ( "File parameter may not be null" ) ; } Files . write ( Paths . get ( file . getAbsolutePath ( ) ) , serializeChannel ( ) , StandardOpenOption . CREATE , StandardOpenOption . TRUNCATE_EXISTING , StandardOpenOption . WRITE ) ; }
Serialize channel to a file using Java serialization . Deserialized channel will NOT be in an initialized state .
32,488
public byte [ ] serializeChannel ( ) throws IOException , InvalidArgumentException { if ( isShutdown ( ) ) { throw new InvalidArgumentException ( format ( "Channel %s has been shutdown." , getName ( ) ) ) ; } ObjectOutputStream out = null ; try { ByteArrayOutputStream bai = new ByteArrayOutputStream ( ) ; out = new ObjectOutputStream ( bai ) ; out . writeObject ( this ) ; out . flush ( ) ; return bai . toByteArray ( ) ; } finally { if ( null != out ) { try { out . close ( ) ; } catch ( IOException e ) { logger . error ( e ) ; } } } }
Serialize channel to a byte array using Java serialization . Deserialized channel will NOT be in an initialized state .
32,489
public static int getProofBytes ( RevocationAlgorithm alg ) { if ( alg == null ) { throw new IllegalArgumentException ( "Revocation algorithm cannot be null" ) ; } switch ( alg ) { case ALG_NO_REVOCATION : return 0 ; default : throw new IllegalArgumentException ( "Unsupported RevocationAlgorithm: " + alg . name ( ) ) ; } }
Depending on the selected revocation algorithm the proof data length will be different . This method will give the proof length for any supported revocation algorithm .
32,490
public static java . security . KeyPair generateLongTermRevocationKey ( ) { try { KeyPairGenerator keyGen = KeyPairGenerator . getInstance ( "EC" ) ; SecureRandom random = new SecureRandom ( ) ; AlgorithmParameterSpec params = new ECGenParameterSpec ( "secp384r1" ) ; keyGen . initialize ( params , random ) ; return keyGen . generateKeyPair ( ) ; } catch ( NoSuchAlgorithmException | InvalidAlgorithmParameterException e ) { throw new RuntimeException ( "Error during the LTRevocation key. Invalid algorithm" ) ; } }
Generate a long term ECDSA key pair used for revocation
32,491
public static Idemix . CredentialRevocationInformation createCRI ( PrivateKey key , BIG [ ] unrevokedHandles , int epoch , RevocationAlgorithm alg ) throws CryptoException { Idemix . CredentialRevocationInformation . Builder builder = Idemix . CredentialRevocationInformation . newBuilder ( ) ; builder . setRevocationAlg ( alg . ordinal ( ) ) ; builder . setEpoch ( epoch ) ; WeakBB . KeyPair keyPair = WeakBB . weakBBKeyGen ( ) ; if ( alg == RevocationAlgorithm . ALG_NO_REVOCATION ) { builder . setEpochPk ( IdemixUtils . transformToProto ( IdemixUtils . genG2 ) ) ; } else { builder . setEpochPk ( IdemixUtils . transformToProto ( keyPair . getPk ( ) ) ) ; } byte [ ] signed ; try { Idemix . CredentialRevocationInformation cri = builder . build ( ) ; Signature ecdsa = Signature . getInstance ( "SHA256withECDSA" ) ; ecdsa . initSign ( key ) ; ecdsa . update ( cri . toByteArray ( ) ) ; signed = ecdsa . sign ( ) ; builder . setEpochPkSig ( ByteString . copyFrom ( signed ) ) ; } catch ( NoSuchAlgorithmException | SignatureException | InvalidKeyException e ) { throw new CryptoException ( "Error processing the signature" ) ; } if ( alg == RevocationAlgorithm . ALG_NO_REVOCATION ) { return builder . build ( ) ; } else { throw new IllegalArgumentException ( "Algorithm " + alg . name ( ) + " not supported" ) ; } }
Creates a Credential Revocation Information object
32,492
public static boolean verifyEpochPK ( PublicKey pk , Idemix . ECP2 epochPK , byte [ ] epochPkSig , long epoch , RevocationAlgorithm alg ) throws CryptoException { Idemix . CredentialRevocationInformation . Builder builder = Idemix . CredentialRevocationInformation . newBuilder ( ) ; builder . setRevocationAlg ( alg . ordinal ( ) ) ; builder . setEpochPk ( epochPK ) ; builder . setEpoch ( epoch ) ; Idemix . CredentialRevocationInformation cri = builder . build ( ) ; byte [ ] bytesTosign = cri . toByteArray ( ) ; try { Signature dsa = Signature . getInstance ( "SHA256withECDSA" ) ; dsa . initVerify ( pk ) ; dsa . update ( bytesTosign ) ; return dsa . verify ( epochPkSig ) ; } catch ( NoSuchAlgorithmException | SignatureException | InvalidKeyException e ) { throw new CryptoException ( "Error during the EpochPK verification" , e ) ; } }
Verifies that the revocation PK for a certain epoch is valid by checking that it was signed with the long term revocation key
32,493
public Identities . SerializedIdentity createSerializedIdentity ( ) { MspPrincipal . OrganizationUnit ou = MspPrincipal . OrganizationUnit . newBuilder ( ) . setCertifiersIdentifier ( ByteString . copyFrom ( this . ipkHash ) ) . setMspIdentifier ( this . mspId ) . setOrganizationalUnitIdentifier ( this . ou ) . build ( ) ; MspPrincipal . MSPRole role = MspPrincipal . MSPRole . newBuilder ( ) . setRole ( IdemixRoles . getMSPRoleFromIdemixRole ( this . roleMask ) ) . setMspIdentifier ( this . mspId ) . build ( ) ; Identities . SerializedIdemixIdentity serializedIdemixIdentity = Identities . SerializedIdemixIdentity . newBuilder ( ) . setProof ( ByteString . copyFrom ( this . associationProof . toProto ( ) . toByteArray ( ) ) ) . setOu ( ByteString . copyFrom ( ou . toByteArray ( ) ) ) . setRole ( ByteString . copyFrom ( role . toByteArray ( ) ) ) . setNymY ( ByteString . copyFrom ( IdemixUtils . bigToBytes ( this . pseudonym . getY ( ) ) ) ) . setNymX ( ByteString . copyFrom ( IdemixUtils . bigToBytes ( this . pseudonym . getX ( ) ) ) ) . build ( ) ; return Identities . SerializedIdentity . newBuilder ( ) . setIdBytes ( ByteString . copyFrom ( serializedIdemixIdentity . toByteArray ( ) ) ) . setMspid ( this . mspId ) . build ( ) ; }
Serialize Idemix Identity
32,494
JsonObject toJsonObject ( ) { JsonObjectBuilder ob = Json . createObjectBuilder ( ) ; ob . add ( "id" , enrollmentID ) ; ob . add ( "type" , type ) ; if ( this . secret != null ) { ob . add ( "secret" , secret ) ; } if ( null != maxEnrollments ) { ob . add ( "max_enrollments" , maxEnrollments ) ; } if ( affiliation != null ) { ob . add ( "affiliation" , affiliation ) ; } JsonArrayBuilder ab = Json . createArrayBuilder ( ) ; for ( Attribute attr : attrs ) { ab . add ( attr . toJsonObject ( ) ) ; } if ( caName != null ) { ob . add ( HFCAClient . FABRIC_CA_REQPROP , caName ) ; } ob . add ( "attrs" , ab . build ( ) ) ; return ob . build ( ) ; }
Convert the registration request to a JSON object
32,495
public Collection < String > getChaincodeNamespaceTypes ( ) throws ProposalException { final Lifecycle . QueryNamespaceDefinitionsResult queryNamespaceDefinitionsResult = parsePayload ( ) ; if ( queryNamespaceDefinitionsResult == null ) { return Collections . emptySet ( ) ; } final Map < String , Lifecycle . QueryNamespaceDefinitionsResult . Namespace > namespacesMap = queryNamespaceDefinitionsResult . getNamespacesMap ( ) ; if ( null == namespacesMap ) { return Collections . emptySet ( ) ; } final Set < String > ret = new HashSet < > ( ) ; namespacesMap . forEach ( ( s , namespace ) -> { if ( "Chaincode" . equalsIgnoreCase ( namespace . getType ( ) ) ) { ret . add ( s ) ; } } ) ; return Collections . unmodifiableSet ( ret ) ; }
The names of chaincode that have been committed .
32,496
public String encode ( ) throws IOException { FastStringWriter fsw = new FastStringWriter ( ) ; try { fsw . write ( "{" ) ; ChartUtils . writeDataValue ( fsw , "display" , this . display , false ) ; ChartUtils . writeDataValue ( fsw , "color" , this . color , true ) ; ChartUtils . writeDataValue ( fsw , "lineWidth" , this . lineWidth , true ) ; fsw . write ( "}" ) ; } finally { fsw . close ( ) ; } return fsw . toString ( ) ; }
Write the options of angled lines on radial linear type
32,497
private String guessImageFormat ( String contentType , String imagePath ) throws IOException { String format = "png" ; if ( contentType == null ) { contentType = URLConnection . guessContentTypeFromName ( imagePath ) ; } if ( contentType != null ) { format = contentType . replaceFirst ( "^image/([^;]+)[;]?.*$" , "$1" ) ; } else { int queryStringIndex = imagePath . indexOf ( '?' ) ; if ( queryStringIndex != - 1 ) { imagePath = imagePath . substring ( 0 , queryStringIndex ) ; } String [ ] pathTokens = imagePath . split ( "\\." ) ; if ( pathTokens . length > 1 ) { format = pathTokens [ pathTokens . length - 1 ] ; } } return format ; }
Attempt to obtain the image format used to write the image from the contentType or the image s file extension .
32,498
public static void writeDataValue ( Writer fsw , String optionName , Object value , boolean hasComma ) throws IOException { if ( value == null ) { return ; } boolean isList = value instanceof List ; if ( hasComma ) { fsw . write ( "," ) ; } fsw . write ( "\"" + optionName + "\":" ) ; if ( isList ) { fsw . write ( "[" ) ; for ( int i = 0 ; i < ( ( List < ? > ) value ) . size ( ) ; i ++ ) { Object item = ( ( List < ? > ) value ) . get ( i ) ; Object writeText ; if ( item instanceof BubblePoint ) { BubblePoint point = ( BubblePoint ) item ; writeText = ( i == 0 ) ? "" : "," ; writeText += "{\"x\":" + point . getX ( ) + ",\"y\":" + point . getY ( ) + ",\"r\":" + point . getR ( ) + "}" ; } else if ( item instanceof String ) { String escapedText = EscapeUtils . forJavaScript ( ( String ) item ) ; writeText = ( i == 0 ) ? "\"" + escapedText + "\"" : ",\"" + escapedText + "\"" ; } else { writeText = ( i == 0 ) ? item : "," + item ; } fsw . write ( "" + writeText ) ; } fsw . write ( "]" ) ; } else { if ( value instanceof String ) { fsw . write ( "\"" + EscapeUtils . forJavaScript ( ( String ) value ) + "\"" ) ; } else { fsw . write ( "" + value ) ; } } }
Write the value of chartJs options
32,499
public String encode ( ) throws IOException { FastStringWriter fsw = new FastStringWriter ( ) ; try { fsw . write ( "{" ) ; fsw . write ( super . encode ( ) ) ; ChartUtils . writeDataValue ( fsw , "beginAtZero" , this . beginAtZero , true ) ; ChartUtils . writeDataValue ( fsw , "backdropColor" , this . backdropColor , true ) ; ChartUtils . writeDataValue ( fsw , "backdropPaddingX" , this . backdropPaddingX , true ) ; ChartUtils . writeDataValue ( fsw , "backdropPaddingY" , this . backdropPaddingY , true ) ; ChartUtils . writeDataValue ( fsw , "min" , this . min , true ) ; ChartUtils . writeDataValue ( fsw , "max" , this . max , true ) ; ChartUtils . writeDataValue ( fsw , "maxTicksLimit" , this . maxTicksLimit , true ) ; ChartUtils . writeDataValue ( fsw , "stepSize" , this . stepSize , true ) ; ChartUtils . writeDataValue ( fsw , "suggestedMax" , this . suggestedMax , true ) ; ChartUtils . writeDataValue ( fsw , "suggestedMin" , this . suggestedMin , true ) ; ChartUtils . writeDataValue ( fsw , "showLabelBackdrop" , this . showLabelBackdrop , true ) ; fsw . write ( "}" ) ; } finally { fsw . close ( ) ; } return fsw . toString ( ) ; }
Write the radial linear ticks