idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
800
|
public void run ( ) { try { Message response = res . send ( query ) ; listener . receiveMessage ( id , response ) ; } catch ( Exception e ) { listener . handleException ( id , e ) ; } }
|
Performs the query and executes the callback .
|
801
|
String rrToString ( ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( byteArrayToString ( cpu , true ) ) ; sb . append ( " " ) ; sb . append ( byteArrayToString ( os , true ) ) ; return sb . toString ( ) ; }
|
Converts to a string
|
802
|
public RRset [ ] answers ( ) { if ( type != SUCCESSFUL ) return null ; List l = ( List ) data ; return ( RRset [ ] ) l . toArray ( new RRset [ l . size ( ) ] ) ; }
|
If the query was successful return the answers
|
803
|
public static Record newRecord ( Name name , int type , int dclass , long ttl ) { if ( ! name . isAbsolute ( ) ) throw new RelativeNameException ( name ) ; Type . check ( type ) ; DClass . check ( dclass ) ; TTL . check ( ttl ) ; return getEmptyRecord ( name , type , dclass , ttl , false ) ; }
|
Creates a new empty record with the given parameters .
|
804
|
public static Record newRecord ( Name name , int type , int dclass ) { return newRecord ( name , type , dclass , 0 ) ; }
|
Creates a new empty record with the given parameters . This method is designed to create records that will be added to the QUERY section of a message .
|
805
|
public static Record fromWire ( byte [ ] b , int section ) throws IOException { return fromWire ( new DNSInput ( b ) , section , false ) ; }
|
Builds a Record from DNS uncompressed wire format .
|
806
|
public byte [ ] toWire ( int section ) { DNSOutput out = new DNSOutput ( ) ; toWire ( out , section , null ) ; return out . toByteArray ( ) ; }
|
Converts a Record into DNS uncompressed wire format .
|
807
|
protected static byte [ ] byteArrayFromString ( String s ) throws TextParseException { byte [ ] array = s . getBytes ( ) ; boolean escaped = false ; boolean hasEscapes = false ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] == '\\' ) { hasEscapes = true ; break ; } } if ( ! hasEscapes ) { if ( array . length > 255 ) { throw new TextParseException ( "text string too long" ) ; } return array ; } ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; int digits = 0 ; int intval = 0 ; for ( int i = 0 ; i < array . length ; i ++ ) { byte b = array [ i ] ; if ( escaped ) { if ( b >= '0' && b <= '9' && digits < 3 ) { digits ++ ; intval *= 10 ; intval += ( b - '0' ) ; if ( intval > 255 ) throw new TextParseException ( "bad escape" ) ; if ( digits < 3 ) continue ; b = ( byte ) intval ; } else if ( digits > 0 && digits < 3 ) throw new TextParseException ( "bad escape" ) ; os . write ( b ) ; escaped = false ; } else if ( array [ i ] == '\\' ) { escaped = true ; digits = 0 ; intval = 0 ; } else os . write ( array [ i ] ) ; } if ( digits > 0 && digits < 3 ) throw new TextParseException ( "bad escape" ) ; array = os . toByteArray ( ) ; if ( array . length > 255 ) { throw new TextParseException ( "text string too long" ) ; } return os . toByteArray ( ) ; }
|
Converts a String into a byte array .
|
808
|
protected static String byteArrayToString ( byte [ ] array , boolean quote ) { StringBuffer sb = new StringBuffer ( ) ; if ( quote ) sb . append ( '"' ) ; for ( int i = 0 ; i < array . length ; i ++ ) { int b = array [ i ] & 0xFF ; if ( b < 0x20 || b >= 0x7f ) { sb . append ( '\\' ) ; sb . append ( byteFormat . format ( b ) ) ; } else if ( b == '"' || b == '\\' ) { sb . append ( '\\' ) ; sb . append ( ( char ) b ) ; } else sb . append ( ( char ) b ) ; } if ( quote ) sb . append ( '"' ) ; return sb . toString ( ) ; }
|
Converts a byte array into a String .
|
809
|
protected static String unknownToString ( byte [ ] data ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( "\\# " ) ; sb . append ( data . length ) ; sb . append ( " " ) ; sb . append ( base16 . toString ( data ) ) ; return sb . toString ( ) ; }
|
Converts a byte array into the unknown RR format .
|
810
|
public boolean sameRRset ( Record rec ) { return ( getRRsetType ( ) == rec . getRRsetType ( ) && dclass == rec . dclass && name . equals ( rec . name ) ) ; }
|
Determines if two Records could be part of the same RRset . This compares the name type and class of the Records ; the ttl and rdata are not compared .
|
811
|
public String printFlags ( ) { StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < 16 ; i ++ ) if ( validFlag ( i ) && getFlag ( i ) ) { sb . append ( Flags . string ( i ) ) ; sb . append ( " " ) ; } return sb . toString ( ) ; }
|
Converts the header s flags into a String
|
812
|
public static synchronized Cache getDefaultCache ( int dclass ) { DClass . check ( dclass ) ; Cache c = ( Cache ) defaultCaches . get ( Mnemonic . toInteger ( dclass ) ) ; if ( c == null ) { c = new Cache ( dclass ) ; defaultCaches . put ( Mnemonic . toInteger ( dclass ) , c ) ; } return c ; }
|
Gets the Cache that will be used as the default for the specified class by future Lookups .
|
813
|
public static synchronized void setDefaultCache ( Cache cache , int dclass ) { DClass . check ( dclass ) ; defaultCaches . put ( Mnemonic . toInteger ( dclass ) , cache ) ; }
|
Sets the Cache to be used as the default for the specified class by future Lookups .
|
814
|
public static synchronized void setDefaultSearchPath ( String [ ] domains ) throws TextParseException { if ( domains == null ) { defaultSearchPath = null ; return ; } Name [ ] newdomains = new Name [ domains . length ] ; for ( int i = 0 ; i < domains . length ; i ++ ) newdomains [ i ] = Name . fromString ( domains [ i ] , Name . root ) ; defaultSearchPath = newdomains ; }
|
Sets the search path that will be used as the default by future Lookups .
|
815
|
public void setSearchPath ( String [ ] domains ) throws TextParseException { if ( domains == null ) { this . searchPath = null ; return ; } Name [ ] newdomains = new Name [ domains . length ] ; for ( int i = 0 ; i < domains . length ; i ++ ) newdomains [ i ] = Name . fromString ( domains [ i ] , Name . root ) ; this . searchPath = newdomains ; }
|
Sets the search path to use when performing this lookup . This overrides the default value .
|
816
|
public void setCache ( Cache cache ) { if ( cache == null ) { this . cache = new Cache ( dclass ) ; this . temporary_cache = true ; } else { this . cache = cache ; this . temporary_cache = false ; } }
|
Sets the cache to use when performing this lookup . This overrides the default value . If the results of this lookup should not be permanently cached null can be provided here .
|
817
|
public Record [ ] run ( ) { if ( done ) reset ( ) ; if ( name . isAbsolute ( ) ) resolve ( name , null ) ; else if ( searchPath == null ) resolve ( name , Name . root ) ; else { if ( name . labels ( ) > defaultNdots ) resolve ( name , Name . root ) ; if ( done ) return answers ; for ( int i = 0 ; i < searchPath . length ; i ++ ) { resolve ( name , searchPath [ i ] ) ; if ( done ) return answers ; else if ( foundAlias ) break ; } } if ( ! done ) { if ( badresponse ) { result = TRY_AGAIN ; error = badresponse_error ; done = true ; } else if ( timedout ) { result = TRY_AGAIN ; error = "timed out" ; done = true ; } else if ( networkerror ) { result = TRY_AGAIN ; error = "network error" ; done = true ; } else if ( nxdomain ) { result = HOST_NOT_FOUND ; done = true ; } else if ( referral ) { result = UNRECOVERABLE ; error = "referral" ; done = true ; } else if ( nametoolong ) { result = UNRECOVERABLE ; error = "name too long" ; done = true ; } } return answers ; }
|
Performs the lookup using the specified Cache Resolver and search path .
|
818
|
public String getErrorString ( ) { checkDone ( ) ; if ( error != null ) return error ; switch ( result ) { case SUCCESSFUL : return "successful" ; case UNRECOVERABLE : return "unrecoverable error" ; case TRY_AGAIN : return "try again" ; case HOST_NOT_FOUND : return "host not found" ; case TYPE_NOT_FOUND : return "type not found" ; } throw new IllegalStateException ( "unknown result" ) ; }
|
Returns an error string describing the result code of this lookup .
|
819
|
public static int value ( String s , boolean numberok ) { int val = types . getValue ( s ) ; if ( val == - 1 && numberok ) { val = types . getValue ( "TYPE" + s ) ; } return val ; }
|
Converts a String representation of an Type into its numeric value .
|
820
|
public InetAddress getAddress ( ) { try { if ( name == null ) return InetAddress . getByAddress ( address ) ; else return InetAddress . getByAddress ( name . toString ( ) , address ) ; } catch ( UnknownHostException e ) { return null ; } }
|
Returns the address
|
821
|
public synchronized void addRR ( Record r ) { if ( rrs . size ( ) == 0 ) { safeAddRR ( r ) ; return ; } Record first = first ( ) ; if ( ! r . sameRRset ( first ) ) throw new IllegalArgumentException ( "record does not match " + "rrset" ) ; if ( r . getTTL ( ) != first . getTTL ( ) ) { if ( r . getTTL ( ) > first . getTTL ( ) ) { r = r . cloneRecord ( ) ; r . setTTL ( first . getTTL ( ) ) ; } else { for ( int i = 0 ; i < rrs . size ( ) ; i ++ ) { Record tmp = ( Record ) rrs . get ( i ) ; tmp = tmp . cloneRecord ( ) ; tmp . setTTL ( r . getTTL ( ) ) ; rrs . set ( i , tmp ) ; } } } if ( ! rrs . contains ( r ) ) safeAddRR ( r ) ; }
|
Adds a Record to an RRset
|
822
|
private boolean findProperty ( ) { String prop ; List lserver = new ArrayList ( 0 ) ; List lsearch = new ArrayList ( 0 ) ; StringTokenizer st ; prop = System . getProperty ( "dns.server" ) ; if ( prop != null ) { st = new StringTokenizer ( prop , "," ) ; while ( st . hasMoreTokens ( ) ) addServer ( st . nextToken ( ) , lserver ) ; } prop = System . getProperty ( "dns.search" ) ; if ( prop != null ) { st = new StringTokenizer ( prop , "," ) ; while ( st . hasMoreTokens ( ) ) addSearch ( st . nextToken ( ) , lsearch ) ; } configureFromLists ( lserver , lsearch ) ; return ( servers != null && searchlist != null ) ; }
|
Looks in the system properties to find servers and a search path . Servers are defined by dns . server = server1 server2 ... The search path is defined by dns . search = domain1 domain2 ...
|
823
|
private void find95 ( ) { String s = "winipcfg.out" ; try { Process p ; p = Runtime . getRuntime ( ) . exec ( "winipcfg /all /batch " + s ) ; p . waitFor ( ) ; File f = new File ( s ) ; findWin ( new FileInputStream ( f ) ) ; new File ( s ) . delete ( ) ; } catch ( Exception e ) { return ; } }
|
Calls winipcfg and parses the result to find servers and a search path .
|
824
|
private void findNT ( ) { try { Process p ; p = Runtime . getRuntime ( ) . exec ( "ipconfig /all" ) ; findWin ( p . getInputStream ( ) ) ; p . destroy ( ) ; } catch ( Exception e ) { return ; } }
|
Calls ipconfig and parses the result to find servers and a search path .
|
825
|
public void writeU16 ( int val ) { check ( val , 16 ) ; need ( 2 ) ; array [ pos ++ ] = ( byte ) ( ( val >>> 8 ) & 0xFF ) ; array [ pos ++ ] = ( byte ) ( val & 0xFF ) ; }
|
Writes an unsigned 16 bit value to the stream .
|
826
|
public void writeU16At ( int val , int where ) { check ( val , 16 ) ; if ( where > pos - 2 ) throw new IllegalArgumentException ( "cannot write past " + "end of data" ) ; array [ where ++ ] = ( byte ) ( ( val >>> 8 ) & 0xFF ) ; array [ where ++ ] = ( byte ) ( val & 0xFF ) ; }
|
Writes an unsigned 16 bit value to the specified position in the stream .
|
827
|
public void writeU32 ( long val ) { check ( val , 32 ) ; need ( 4 ) ; array [ pos ++ ] = ( byte ) ( ( val >>> 24 ) & 0xFF ) ; array [ pos ++ ] = ( byte ) ( ( val >>> 16 ) & 0xFF ) ; array [ pos ++ ] = ( byte ) ( ( val >>> 8 ) & 0xFF ) ; array [ pos ++ ] = ( byte ) ( val & 0xFF ) ; }
|
Writes an unsigned 32 bit value to the stream .
|
828
|
public void writeByteArray ( byte [ ] b , int off , int len ) { need ( len ) ; System . arraycopy ( b , off , array , pos , len ) ; pos += len ; }
|
Writes a byte array to the stream .
|
829
|
public void writeCountedString ( byte [ ] s ) { if ( s . length > 0xFF ) { throw new IllegalArgumentException ( "Invalid counted string" ) ; } need ( 1 + s . length ) ; array [ pos ++ ] = ( byte ) ( s . length & 0xFF ) ; writeByteArray ( s , 0 , s . length ) ; }
|
Writes a counted string from the stream . A counted string is a one byte value indicating string length followed by bytes of data .
|
830
|
public byte [ ] hashName ( Name name ) throws NoSuchAlgorithmException { return NSEC3Record . hashName ( name , hashAlg , iterations , salt ) ; }
|
Hashes a name with the parameters of this NSEC3PARAM record .
|
831
|
public static boolean supportedType ( int type ) { Type . check ( type ) ; return ( type == Type . PTR || type == Type . CNAME || type == Type . DNAME || type == Type . A || type == Type . AAAA || type == Type . NS ) ; }
|
Indicates whether generation is supported for this type .
|
832
|
public Record nextRecord ( ) throws IOException { if ( current > end ) return null ; String namestr = substitute ( namePattern , current ) ; Name name = Name . fromString ( namestr , origin ) ; String rdata = substitute ( rdataPattern , current ) ; current += step ; return Record . fromString ( name , type , dclass , ttl , rdata , origin ) ; }
|
Constructs and returns the next record in the expansion .
|
833
|
public Record [ ] expand ( ) throws IOException { List list = new ArrayList ( ) ; for ( long i = start ; i < end ; i += step ) { String namestr = substitute ( namePattern , current ) ; Name name = Name . fromString ( namestr , origin ) ; String rdata = substitute ( rdataPattern , current ) ; list . add ( Record . fromString ( name , type , dclass , ttl , rdata , origin ) ) ; } return ( Record [ ] ) list . toArray ( new Record [ list . size ( ) ] ) ; }
|
Constructs and returns all records in the expansion .
|
834
|
String rrToString ( ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( mailbox ) ; sb . append ( " " ) ; sb . append ( textDomain ) ; return sb . toString ( ) ; }
|
Converts the RP Record to a String
|
835
|
public static String format ( Date date ) { Calendar c = new GregorianCalendar ( TimeZone . getTimeZone ( "UTC" ) ) ; StringBuffer sb = new StringBuffer ( ) ; c . setTime ( date ) ; sb . append ( w4 . format ( c . get ( Calendar . YEAR ) ) ) ; sb . append ( w2 . format ( c . get ( Calendar . MONTH ) + 1 ) ) ; sb . append ( w2 . format ( c . get ( Calendar . DAY_OF_MONTH ) ) ) ; sb . append ( w2 . format ( c . get ( Calendar . HOUR_OF_DAY ) ) ) ; sb . append ( w2 . format ( c . get ( Calendar . MINUTE ) ) ) ; sb . append ( w2 . format ( c . get ( Calendar . SECOND ) ) ) ; return sb . toString ( ) ; }
|
Converts a Date into a formatted string .
|
836
|
public static Date parse ( String s ) throws TextParseException { if ( s . length ( ) != 14 ) { throw new TextParseException ( "Invalid time encoding: " + s ) ; } Calendar c = new GregorianCalendar ( TimeZone . getTimeZone ( "UTC" ) ) ; c . clear ( ) ; try { int year = Integer . parseInt ( s . substring ( 0 , 4 ) ) ; int month = Integer . parseInt ( s . substring ( 4 , 6 ) ) - 1 ; int date = Integer . parseInt ( s . substring ( 6 , 8 ) ) ; int hour = Integer . parseInt ( s . substring ( 8 , 10 ) ) ; int minute = Integer . parseInt ( s . substring ( 10 , 12 ) ) ; int second = Integer . parseInt ( s . substring ( 12 , 14 ) ) ; c . set ( year , month , date , hour , minute , second ) ; } catch ( NumberFormatException e ) { throw new TextParseException ( "Invalid time encoding: " + s ) ; } return c . getTime ( ) ; }
|
Parses a formatted time string into a Date .
|
837
|
public InetAddress getAddress ( ) { try { if ( name == null ) return InetAddress . getByAddress ( toArray ( addr ) ) ; else return InetAddress . getByAddress ( name . toString ( ) , toArray ( addr ) ) ; } catch ( UnknownHostException e ) { return null ; } }
|
Returns the Internet address
|
838
|
String rrToString ( ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( responsibleAddress ) ; sb . append ( " " ) ; sb . append ( errorAddress ) ; return sb . toString ( ) ; }
|
Converts the MINFO Record to a String
|
839
|
public static void verify ( RRset rrset , RRSIGRecord rrsig , DNSKEYRecord key ) throws DNSSECException { if ( ! matches ( rrsig , key ) ) throw new KeyMismatchException ( key , rrsig ) ; Date now = new Date ( ) ; if ( now . compareTo ( rrsig . getExpire ( ) ) > 0 ) throw new SignatureExpiredException ( rrsig . getExpire ( ) , now ) ; if ( now . compareTo ( rrsig . getTimeSigned ( ) ) < 0 ) throw new SignatureNotYetValidException ( rrsig . getTimeSigned ( ) , now ) ; verify ( key . getPublicKey ( ) , rrsig . getAlgorithm ( ) , digestRRset ( rrsig , rrset ) , rrsig . getSignature ( ) ) ; }
|
Verify a DNSSEC signature .
|
840
|
static byte [ ] generateDSDigest ( DNSKEYRecord key , int digestid ) { MessageDigest digest ; try { switch ( digestid ) { case DSRecord . Digest . SHA1 : digest = MessageDigest . getInstance ( "sha-1" ) ; break ; case DSRecord . Digest . SHA256 : digest = MessageDigest . getInstance ( "sha-256" ) ; break ; case DSRecord . Digest . GOST3411 : digest = MessageDigest . getInstance ( "GOST3411" ) ; break ; case DSRecord . Digest . SHA384 : digest = MessageDigest . getInstance ( "sha-384" ) ; break ; default : throw new IllegalArgumentException ( "unknown DS digest type " + digestid ) ; } } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( "no message digest support" ) ; } digest . update ( key . getName ( ) . toWireCanonical ( ) ) ; digest . update ( key . rdataToWireCanonical ( ) ) ; return digest . digest ( ) ; }
|
Generate the digest value for a DS key
|
841
|
private static Map < String , String > parseKeyValueMap ( String kvString , Function < String , String > valueMapper ) { return Stream . of ( Optional . ofNullable ( kvString ) . map ( StringUtils :: trimAllWhitespace ) . filter ( StringUtils :: hasText ) . map ( s -> s . split ( PAIR_SEPARATOR ) ) . orElse ( new String [ 0 ] ) ) . map ( StringUtils :: trimAllWhitespace ) . map ( pair -> pair . split ( KEY_VALUE_SEPARATOR , 2 ) ) . collect ( toMap ( FIRST . andThen ( StringUtils :: trimAllWhitespace ) , SECOND . andThen ( StringUtils :: trimAllWhitespace ) . andThen ( valueMapper ) ) ) ; }
|
Parses a key - value pair string such as param1 = WdfaA param2 = AZrr param3 into a map .
|
842
|
public boolean setNonnull ( HttpResponse response ) { Preconditions . checkNotNull ( response ) ; if ( set ( response ) ) { callback . completed ( response ) ; return true ; } else { return false ; } }
|
superclass method has
|
843
|
public static void registerAccessor ( Class < ? > documentType , DocumentAccessor accessor ) { Assert . notNull ( documentType , "documentType may not be null" ) ; Assert . notNull ( accessor , "accessor may not be null" ) ; if ( accessors . containsKey ( documentType ) ) { DocumentAccessor existing = getAccessor ( documentType ) ; LOG . warn ( String . format ( "DocumentAccessor for class %s already exists: %s will be overridden by %s" , documentType , existing . getClass ( ) , accessor . getClass ( ) ) ) ; } putAccessor ( documentType , accessor ) ; LOG . debug ( "Registered document accessor: {} for class: {}" , accessor . getClass ( ) , documentType ) ; }
|
Used to register a custom DocumentAccessor for a particular class . Any existing accessor for the class will be overridden .
|
844
|
public static void setId ( Object document , String id ) { DocumentAccessor d = getAccessor ( document ) ; if ( d . hasIdMutator ( ) ) { d . setId ( document , id ) ; } }
|
Will set the id property on the document IF a mutator exists . Otherwise nothing happens .
|
845
|
public static List < String > parseAttachmentNames ( JsonParser documentJsonParser ) throws IOException { documentJsonParser . nextToken ( ) ; JsonToken jsonToken ; while ( ( jsonToken = documentJsonParser . nextToken ( ) ) != JsonToken . END_OBJECT ) { if ( CouchDbDocument . ATTACHMENTS_NAME . equals ( documentJsonParser . getCurrentName ( ) ) ) { return readAttachments ( documentJsonParser ) ; } else if ( jsonToken == JsonToken . START_OBJECT ) { readIgnoreObject ( documentJsonParser ) ; } } return null ; }
|
Parses a CouchDB document in the form of a JsonParser to get the attachments order . It is important that the JsonParser come straight from the source document and not from an object or the order will be incorrect .
|
846
|
public void setAnonymous ( String key , Object value ) { anonymous ( ) . put ( key , value ) ; }
|
Exists in order to future proof this class .
|
847
|
protected SettableBeanProperty constructSettableProperty ( DeserializationConfig config , BeanDescription beanDesc , String name , AnnotatedMethod setter , JavaType type ) { if ( config . isEnabled ( MapperFeature . CAN_OVERRIDE_ACCESS_MODIFIERS ) ) { Method member = setter . getAnnotated ( ) ; if ( ! Modifier . isPublic ( member . getModifiers ( ) ) || ! Modifier . isPublic ( member . getDeclaringClass ( ) . getModifiers ( ) ) ) { member . setAccessible ( true ) ; } } TypeDeserializer typeDeser = type . getTypeHandler ( ) ; SettableBeanProperty prop = new MethodProperty ( SimpleBeanPropertyDefinition . construct ( config , setter ) , type , typeDeser , beanDesc . getClassAnnotations ( ) , setter ) ; AnnotationIntrospector . ReferenceProperty ref = config . getAnnotationIntrospector ( ) . findReferenceType ( setter ) ; if ( ref != null && ref . isManagedReference ( ) ) { prop . setManagedReferenceName ( ref . getName ( ) ) ; } return prop ; }
|
Method copied from org . codehaus . jackson . map . deser . BeanDeserializerFactory
|
848
|
private List < String > parseRows ( JsonParser jp , List < String > result ) throws IOException { while ( jp . nextToken ( ) == JsonToken . START_OBJECT ) { while ( jp . nextToken ( ) == JsonToken . FIELD_NAME ) { String fieldName = jp . getCurrentName ( ) ; jp . nextToken ( ) ; if ( "id" . equals ( fieldName ) ) { result . add ( jp . getText ( ) ) ; } else { jp . skipChildren ( ) ; } } } return result ; }
|
The token is required to be on the START_ARRAY value for rows .
|
849
|
public static BulkDeleteDocument of ( Object o ) { return new BulkDeleteDocument ( Documents . getId ( o ) , Documents . getRevision ( o ) ) ; }
|
Will create a bulk delete document based on the specified object .
|
850
|
public Options param ( String name , String value ) { options . put ( name , value ) ; return this ; }
|
Adds a parameter to the GET request sent to the database .
|
851
|
protected ViewQuery createQuery ( String viewName ) { return new ViewQuery ( ) . dbPath ( db . path ( ) ) . designDocId ( stdDesignDocumentId ) . viewName ( viewName ) ; }
|
Creates a ViewQuery pre - configured with correct dbPath design document id and view name .
|
852
|
protected List < T > queryView ( String viewName , ComplexKey key ) { return db . queryView ( createQuery ( viewName ) . includeDocs ( true ) . key ( key ) , type ) ; }
|
Allows subclasses to query views with simple String value keys and load the result as the repository s handled type .
|
853
|
private void backOff ( ) { try { Thread . sleep ( new Random ( ) . nextInt ( 400 ) ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; } }
|
Wait a short while in order to prevent racing initializations from other repositories .
|
854
|
public void load ( Reader in ) { try { doLoad ( in ) ; } catch ( Exception e ) { throw Exceptions . propagate ( e ) ; } }
|
Reads documents from the reader and stores them in the database .
|
855
|
public void write ( Collection < ? > objects , boolean allOrNothing , OutputStream out ) { try { JsonGenerator jg = objectMapper . getFactory ( ) . createGenerator ( out , JsonEncoding . UTF8 ) ; jg . writeStartObject ( ) ; if ( allOrNothing ) { jg . writeBooleanField ( "all_or_nothing" , true ) ; } jg . writeArrayFieldStart ( "docs" ) ; for ( Object o : objects ) { jg . writeObject ( o ) ; } jg . writeEndArray ( ) ; jg . writeEndObject ( ) ; jg . flush ( ) ; jg . close ( ) ; } catch ( Exception e ) { throw Exceptions . propagate ( e ) ; } finally { IOUtils . closeQuietly ( out ) ; } }
|
Writes the objects collection as a bulk operation document . The output stream is flushed and closed by this method .
|
856
|
protected void applyDefaultConfiguration ( ObjectMapper om ) { om . configure ( SerializationFeature . WRITE_DATES_AS_TIMESTAMPS , this . writeDatesAsTimestamps ) ; om . setSerializationInclusion ( JsonInclude . Include . NON_NULL ) ; }
|
This protected method can be overridden in order to change the configuration .
|
857
|
public Socket connectSocket ( final Socket sock , final String host , final int port , final InetAddress localAddress , int localPort , final HttpParams params ) throws IOException { if ( host == null ) { throw new IllegalArgumentException ( "Target host may not be null." ) ; } if ( params == null ) { throw new IllegalArgumentException ( "Parameters may not be null." ) ; } SSLSocket sslsock = ( SSLSocket ) ( ( sock != null ) ? sock : createSocket ( ) ) ; if ( ( localAddress != null ) || ( localPort > 0 ) ) { if ( localPort < 0 ) localPort = 0 ; InetSocketAddress isa = new InetSocketAddress ( localAddress , localPort ) ; sslsock . bind ( isa ) ; } int connTimeout = HttpConnectionParams . getConnectionTimeout ( params ) ; int soTimeout = HttpConnectionParams . getSoTimeout ( params ) ; InetSocketAddress remoteAddress ; if ( this . nameResolver != null ) { remoteAddress = new InetSocketAddress ( this . nameResolver . resolve ( host ) , port ) ; } else { remoteAddress = new InetSocketAddress ( host , port ) ; } sslsock . connect ( remoteAddress , connTimeout ) ; sslsock . setSoTimeout ( soTimeout ) ; try { hostnameVerifier . verify ( host , sslsock ) ; } catch ( IOException iox ) { try { sslsock . close ( ) ; } catch ( Exception x ) { } throw iox ; } return sslsock ; }
|
non - javadoc see interface org . apache . http . conn . SocketFactory
|
858
|
public Socket createSocket ( final Socket socket , final String host , final int port , final boolean autoClose ) throws IOException , UnknownHostException { SSLSocket sslSocket = ( SSLSocket ) this . socketfactory . createSocket ( socket , host , port , autoClose ) ; hostnameVerifier . verify ( host , sslSocket ) ; return sslSocket ; }
|
non - javadoc see interface LayeredSocketFactory
|
859
|
public static Method findMethod ( Class < ? > clazz , String name ) { for ( Method me : clazz . getDeclaredMethods ( ) ) { if ( me . getName ( ) . equalsIgnoreCase ( name ) ) { return me ; } } if ( clazz . getSuperclass ( ) != null ) { return findMethod ( clazz . getSuperclass ( ) , name ) ; } return null ; }
|
Ignores case when comparing method names
|
860
|
public static DbAccessException createDbAccessException ( HttpResponse hr ) { JsonNode responseBody ; try { InputStream content = hr . getContent ( ) ; if ( content != null ) { responseBody = responseBodyAsNode ( IOUtils . toString ( content ) ) ; } else { responseBody = NullNode . getInstance ( ) ; } } catch ( Exception e ) { responseBody = NullNode . getInstance ( ) ; } switch ( hr . getCode ( ) ) { case HttpStatus . NOT_FOUND : return new DocumentNotFoundException ( hr . getRequestURI ( ) , responseBody ) ; case HttpStatus . CONFLICT : return new UpdateConflictException ( ) ; default : String body ; try { body = toPrettyString ( responseBody ) ; } catch ( IOException e ) { body = "unavailable" ; } return new DbAccessException ( hr . toString ( ) + "\nURI: " + hr . getRequestURI ( ) + "\nResponse Body: \n" + body ) ; } }
|
Creates an DbAccessException which specific type is determined by the response code in the http response .
|
861
|
public void afterPropertiesSet ( ) throws Exception { if ( couchDBProperties != null ) { new DirectFieldAccessor ( this ) . setPropertyValues ( couchDBProperties ) ; } LOG . info ( "Starting couchDb connector on {}:{}..." , new Object [ ] { host , port } ) ; LOG . debug ( "host: {}" , host ) ; LOG . debug ( "port: {}" , port ) ; LOG . debug ( "url: {}" , url ) ; LOG . debug ( "maxConnections: {}" , maxConnections ) ; LOG . debug ( "connectionTimeout: {}" , connectionTimeout ) ; LOG . debug ( "socketTimeout: {}" , socketTimeout ) ; LOG . debug ( "autoUpdateViewOnChange: {}" , autoUpdateViewOnChange ) ; LOG . debug ( "testConnectionAtStartup: {}" , testConnectionAtStartup ) ; LOG . debug ( "cleanupIdleConnections: {}" , cleanupIdleConnections ) ; LOG . debug ( "enableSSL: {}" , enableSSL ) ; LOG . debug ( "relaxedSSLSettings: {}" , relaxedSSLSettings ) ; LOG . debug ( "useExpectContinue: {}" , useExpectContinue ) ; client = new StdHttpClient . Builder ( ) . host ( host ) . port ( port ) . maxConnections ( maxConnections ) . connectionTimeout ( connectionTimeout ) . socketTimeout ( socketTimeout ) . username ( username ) . password ( password ) . cleanupIdleConnections ( cleanupIdleConnections ) . useExpectContinue ( useExpectContinue ) . enableSSL ( enableSSL ) . relaxedSSLSettings ( relaxedSSLSettings ) . sslSocketFactory ( sslSocketFactory ) . caching ( caching ) . maxCacheEntries ( maxCacheEntries ) . maxObjectSizeBytes ( maxObjectSizeBytes ) . url ( url ) . build ( ) ; if ( testConnectionAtStartup ) { testConnect ( client ) ; } configureAutoUpdateViewOnChange ( ) ; }
|
Create the couchDB connection when starting the bean factory
|
862
|
public Map < String , DesignDocument . View > generateViews ( final Object repository ) { final Map < String , DesignDocument . View > views = new HashMap < String , DesignDocument . View > ( ) ; final Class < ? > repositoryClass = repository . getClass ( ) ; final Class < ? > handledType = repository instanceof CouchDbRepositorySupport < ? > ? ( ( CouchDbRepositorySupport < ? > ) repository ) . getHandledType ( ) : null ; createDeclaredViews ( views , repositoryClass ) ; eachMethod ( repositoryClass , new Predicate < Method > ( ) { public boolean apply ( Method input ) { if ( hasAnnotation ( input , GenerateView . class ) ) { generateView ( views , input , handledType ) ; } return false ; } } ) ; if ( handledType != null ) { views . putAll ( generateViewsFromPersistentType ( handledType ) ) ; } return views ; }
|
Generates views based on annotations found in a repository class . If the repository class extends org . ektorp . support . CouchDbRepositorySupport its handled type will also examined for annotations eligible for view generation .
|
863
|
public boolean mergeWith ( DesignDocument dd , boolean updateOnDiff ) { boolean changed = mergeViews ( dd . views ( ) , updateOnDiff ) ; changed = mergeFunctions ( lists ( ) , dd . lists ( ) , updateOnDiff ) || changed ; changed = mergeFunctions ( shows ( ) , dd . shows ( ) , updateOnDiff ) || changed ; changed = mergeFunctions ( filters ( ) , dd . filters ( ) , updateOnDiff ) || changed ; changed = mergeFunctions ( updates ( ) , dd . updates ( ) , updateOnDiff ) || changed ; return changed ; }
|
Merge this design document with the specified document the result being stored in this design document .
|
864
|
public boolean isSubType ( String typeName ) throws AtlasException { HierarchicalType cType = typeSystem . getDataType ( HierarchicalType . class , typeName ) ; return ( cType == this || cType . superTypePaths . containsKey ( getName ( ) ) ) ; }
|
Given type must be a SubType of this type .
|
865
|
public List < EntityAuditEvent > listEvents ( String entityId , String startKey , short n ) throws AtlasException { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Listing events for entity id {}, starting timestamp {}, #records {}" , entityId , startKey , n ) ; } Table table = null ; ResultScanner scanner = null ; try { table = connection . getTable ( tableName ) ; Scan scan = new Scan ( ) . setReversed ( true ) . setFilter ( new PageFilter ( n ) ) . setStopRow ( Bytes . toBytes ( entityId ) ) . setCaching ( n ) . setSmall ( true ) ; if ( StringUtils . isEmpty ( startKey ) ) { byte [ ] entityBytes = getKey ( entityId , Long . MAX_VALUE ) ; scan = scan . setStartRow ( entityBytes ) ; } else { scan = scan . setStartRow ( Bytes . toBytes ( startKey ) ) ; } scanner = table . getScanner ( scan ) ; Result result ; List < EntityAuditEvent > events = new ArrayList < > ( ) ; while ( ( result = scanner . next ( ) ) != null && events . size ( ) < n ) { EntityAuditEvent event = fromKey ( result . getRow ( ) ) ; if ( ! event . getEntityId ( ) . equals ( entityId ) ) { continue ; } event . setUser ( getResultString ( result , COLUMN_USER ) ) ; event . setAction ( EntityAuditEvent . EntityAuditAction . valueOf ( getResultString ( result , COLUMN_ACTION ) ) ) ; event . setDetails ( getResultString ( result , COLUMN_DETAIL ) ) ; if ( persistEntityDefinition ) { String colDef = getResultString ( result , COLUMN_DEFINITION ) ; if ( colDef != null ) { event . setEntityDefinition ( colDef ) ; } } events . add ( event ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Got events for entity id {}, starting timestamp {}, #records {}" , entityId , startKey , events . size ( ) ) ; } return events ; } catch ( IOException e ) { throw new AtlasException ( e ) ; } finally { close ( scanner ) ; close ( table ) ; } }
|
List events for the given entity id in decreasing order of timestamp from the given startKey . Returns n results
|
866
|
public static org . apache . hadoop . conf . Configuration getHBaseConfiguration ( Configuration atlasConf ) throws AtlasException { Configuration subsetAtlasConf = ApplicationProperties . getSubsetConfiguration ( atlasConf , CONFIG_PREFIX ) ; org . apache . hadoop . conf . Configuration hbaseConf = HBaseConfiguration . create ( ) ; Iterator < String > keys = subsetAtlasConf . getKeys ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; hbaseConf . set ( key , subsetAtlasConf . getString ( key ) ) ; } return hbaseConf ; }
|
Converts atlas application properties to hadoop conf
|
867
|
public static Titan0Edge createEdge ( Titan0Graph graph , Edge source ) { if ( source == null ) { return null ; } return new Titan0Edge ( graph , source ) ; }
|
Creates a Titan0Edge that corresponds to the given Gremlin Edge .
|
868
|
public static Titan0Vertex createVertex ( Titan0Graph graph , Vertex source ) { if ( source == null ) { return null ; } return new Titan0Vertex ( graph , source ) ; }
|
Creates a Titan0Vertex that corresponds to the given Gremlin Vertex .
|
869
|
protected String errorMessage ( String input , Exception e ) { return String . format ( "Invalid parameter: %s (%s)" , input , e . getMessage ( ) ) ; }
|
Given a string representation which was unable to be parsed and the exception thrown produce an entity to be sent to the client .
|
870
|
private void notifyOfEntityEvent ( Collection < ITypedReferenceableInstance > entityDefinitions , EntityNotification . OperationType operationType ) throws AtlasException { List < EntityNotification > messages = new LinkedList < > ( ) ; for ( IReferenceableInstance entityDefinition : entityDefinitions ) { Referenceable entity = new Referenceable ( entityDefinition ) ; Map < String , Object > attributesMap = entity . getValuesMap ( ) ; List < String > entityNotificationAttrs = getNotificationAttributes ( entity . getTypeName ( ) ) ; if ( MapUtils . isNotEmpty ( attributesMap ) && CollectionUtils . isNotEmpty ( entityNotificationAttrs ) ) { for ( String entityAttr : attributesMap . keySet ( ) ) { if ( ! entityNotificationAttrs . contains ( entityAttr ) ) { entity . setNull ( entityAttr ) ; } } } EntityNotificationImpl notification = new EntityNotificationImpl ( entity , operationType , getAllTraits ( entity , typeSystem ) ) ; messages . add ( notification ) ; } notificationInterface . send ( NotificationInterface . NotificationType . ENTITIES , messages ) ; }
|
send notification of entity change
|
871
|
private GroovyExpression optimize ( GroovyExpression source , GremlinOptimization optimization , OptimizationContext context ) { GroovyExpression result = source ; if ( optimization . appliesTo ( source , context ) ) { result = optimization . apply ( source , context ) ; } if ( optimization . isApplyRecursively ( ) ) { List < GroovyExpression > updatedChildren = new ArrayList < > ( ) ; boolean changed = false ; for ( GroovyExpression child : result . getChildren ( ) ) { GroovyExpression updatedChild = optimize ( child , optimization , context ) ; changed |= updatedChild != child ; updatedChildren . add ( updatedChild ) ; } if ( changed ) { result = result . copy ( updatedChildren ) ; } } return result ; }
|
Optimizes the expression using the given optimization
|
872
|
public static GroovyExpression copyWithNewLeafNode ( AbstractFunctionExpression expr , GroovyExpression newLeaf ) { AbstractFunctionExpression result = ( AbstractFunctionExpression ) expr . copy ( ) ; if ( FACTORY . isLeafAnonymousTraversalExpression ( expr ) ) { result = ( AbstractFunctionExpression ) newLeaf ; } else { GroovyExpression newCaller = null ; if ( expr . getCaller ( ) == null ) { newCaller = newLeaf ; } else { newCaller = copyWithNewLeafNode ( ( AbstractFunctionExpression ) result . getCaller ( ) , newLeaf ) ; } result . setCaller ( newCaller ) ; } return result ; }
|
Recursively copies and follows the caller hierarchy of the expression until we come to a function call with a null caller . The caller of that expression is set to newLeaf .
|
873
|
public void doFilter ( ServletRequest servletRequest , ServletResponse servletResponse , FilterChain filterChain ) throws IOException , ServletException { if ( isFilteredURI ( servletRequest ) ) { LOG . debug ( "Is a filtered URI: {}. Passing request downstream." , ( ( HttpServletRequest ) servletRequest ) . getRequestURI ( ) ) ; filterChain . doFilter ( servletRequest , servletResponse ) ; } else if ( isInstanceActive ( ) ) { LOG . debug ( "Active. Passing request downstream" ) ; filterChain . doFilter ( servletRequest , servletResponse ) ; } else if ( serviceState . isInstanceInTransition ( ) ) { HttpServletResponse httpServletResponse = ( HttpServletResponse ) servletResponse ; LOG . error ( "Instance in transition. Service may not be ready to return a result" ) ; httpServletResponse . sendError ( HttpServletResponse . SC_SERVICE_UNAVAILABLE ) ; } else { HttpServletResponse httpServletResponse = ( HttpServletResponse ) servletResponse ; String activeServerAddress = activeInstanceState . getActiveServerAddress ( ) ; if ( activeServerAddress == null ) { LOG . error ( "Could not retrieve active server address as it is null. Cannot redirect request {}" , ( ( HttpServletRequest ) servletRequest ) . getRequestURI ( ) ) ; httpServletResponse . sendError ( HttpServletResponse . SC_SERVICE_UNAVAILABLE ) ; } else { handleRedirect ( ( HttpServletRequest ) servletRequest , httpServletResponse , activeServerAddress ) ; } } }
|
Determines if this Atlas server instance is passive and redirects to active if so .
|
874
|
public < T > Collection < T > getPropertyValues ( String propertyName , Class < T > type ) { return Collections . singleton ( getProperty ( propertyName , type ) ) ; }
|
Gets all of the values of the given property .
|
875
|
private boolean isAuthenticated ( ) { Authentication existingAuth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; return ! ( ! ( existingAuth != null && existingAuth . isAuthenticated ( ) ) || existingAuth instanceof SSOAuthentication ) ; }
|
Do not try to validate JWT if user already authenticated via other provider
|
876
|
protected String getJWTFromCookie ( HttpServletRequest req ) { String serializedJWT = null ; Cookie [ ] cookies = req . getCookies ( ) ; if ( cookieName != null && cookies != null ) { for ( Cookie cookie : cookies ) { if ( cookieName . equals ( cookie . getName ( ) ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "{} cookie has been found and is being processed" , cookieName ) ; } serializedJWT = cookie . getValue ( ) ; break ; } } } return serializedJWT ; }
|
Encapsulate the acquisition of the JWT token from HTTP cookies within the request .
|
877
|
protected String constructLoginURL ( HttpServletRequest request , boolean isXMLRequest ) { String delimiter = "?" ; if ( authenticationProviderUrl . contains ( "?" ) ) { delimiter = "&" ; } StringBuilder loginURL = new StringBuilder ( ) ; if ( isXMLRequest ) { String atlasApplicationURL = "" ; String referalURL = request . getHeader ( "referer" ) ; if ( referalURL == null ) { atlasApplicationURL = request . getScheme ( ) + "://" + request . getServerName ( ) + ":" + request . getServerPort ( ) + request . getContextPath ( ) ; } else { atlasApplicationURL = referalURL ; } loginURL . append ( authenticationProviderUrl ) . append ( delimiter ) . append ( originalUrlQueryParam ) . append ( "=" ) . append ( atlasApplicationURL ) ; } else { loginURL . append ( authenticationProviderUrl ) . append ( delimiter ) . append ( originalUrlQueryParam ) . append ( "=" ) . append ( request . getRequestURL ( ) . append ( getOriginalQueryString ( request ) ) ) ; } return loginURL . toString ( ) ; }
|
Create the URL to be used for authentication of the user in the absence of a JWT token within the incoming request .
|
878
|
protected boolean validateToken ( SignedJWT jwtToken ) { boolean isValid = validateSignature ( jwtToken ) ; if ( isValid ) { isValid = validateExpiration ( jwtToken ) ; if ( ! isValid ) { LOG . warn ( "Expiration time validation of JWT token failed." ) ; } } else { LOG . warn ( "Signature of JWT token could not be verified. Please check the public key" ) ; } return isValid ; }
|
This method provides a single method for validating the JWT for use in request processing . It provides for the override of specific aspects of this implementation through submethods used within but also allows for the override of the entire token validation algorithm .
|
879
|
protected boolean validateSignature ( SignedJWT jwtToken ) { boolean valid = false ; if ( JWSObject . State . SIGNED == jwtToken . getState ( ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "SSO token is in a SIGNED state" ) ; } if ( jwtToken . getSignature ( ) != null ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "SSO token signature is not null" ) ; } try { if ( verifier != null && jwtToken . verify ( verifier ) ) { valid = true ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "SSO token has been successfully verified" ) ; } } else { LOG . warn ( "SSO signature verification failed.Please check the public key" ) ; } } catch ( JOSEException je ) { LOG . warn ( "Error while validating signature" , je ) ; } catch ( Exception e ) { LOG . warn ( "Error while validating signature" , e ) ; } } } return valid ; }
|
Verify the signature of the JWT token in this method . This method depends on the public key that was established during init based upon the provisioned public key . Override this method in subclasses in order to customize the signature verification behavior .
|
880
|
protected boolean validateExpiration ( SignedJWT jwtToken ) { boolean valid = false ; try { Date expires = jwtToken . getJWTClaimsSet ( ) . getExpirationTime ( ) ; if ( expires == null || new Date ( ) . before ( expires ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "SSO token expiration date has been successfully validated" ) ; } valid = true ; } else { LOG . warn ( "SSO expiration date validation failed." ) ; } } catch ( ParseException pe ) { LOG . warn ( "SSO expiration date validation failed." , pe ) ; } return valid ; }
|
Validate that the expiration time of the JWT token has not been violated . If it has then throw an AuthenticationException . Override this method in subclasses in order to customize the expiration validation behavior .
|
881
|
boolean hasIncomingEdgesWithLabel ( AtlasVertex vertex , String label ) throws AtlasBaseException { boolean foundEdges = false ; Iterator < AtlasEdge > inEdges = vertex . getEdges ( AtlasEdgeDirection . IN ) . iterator ( ) ; while ( inEdges . hasNext ( ) ) { AtlasEdge edge = inEdges . next ( ) ; if ( label . equals ( edge . getLabel ( ) ) ) { foundEdges = true ; break ; } } return foundEdges ; }
|
Look to see if there are any IN edges with the supplied label
|
882
|
private boolean validateAtlasRelationshipType ( AtlasRelationshipType type ) { boolean isValid = false ; try { validateAtlasRelationshipDef ( type . getRelationshipDef ( ) ) ; isValid = true ; } catch ( AtlasBaseException abe ) { LOG . error ( "Validation error for AtlasRelationshipType" , abe ) ; } return isValid ; }
|
Validate the fields in the the RelationshipType are consistent with respect to themselves .
|
883
|
public static void validateAtlasRelationshipDef ( AtlasRelationshipDef relationshipDef ) throws AtlasBaseException { AtlasRelationshipEndDef endDef1 = relationshipDef . getEndDef1 ( ) ; AtlasRelationshipEndDef endDef2 = relationshipDef . getEndDef2 ( ) ; RelationshipCategory relationshipCategory = relationshipDef . getRelationshipCategory ( ) ; String name = relationshipDef . getName ( ) ; boolean isContainer1 = endDef1 . getIsContainer ( ) ; boolean isContainer2 = endDef2 . getIsContainer ( ) ; if ( ( endDef1 . getCardinality ( ) == AtlasAttributeDef . Cardinality . LIST ) || ( endDef2 . getCardinality ( ) == AtlasAttributeDef . Cardinality . LIST ) ) { throw new AtlasBaseException ( AtlasErrorCode . RELATIONSHIPDEF_LIST_ON_END , name ) ; } if ( isContainer1 && isContainer2 ) { throw new AtlasBaseException ( AtlasErrorCode . RELATIONSHIPDEF_DOUBLE_CONTAINERS , name ) ; } if ( ( isContainer1 || isContainer2 ) ) { if ( relationshipCategory == RelationshipCategory . ASSOCIATION ) { throw new AtlasBaseException ( AtlasErrorCode . RELATIONSHIPDEF_ASSOCIATION_AND_CONTAINER , name ) ; } } else { if ( relationshipCategory == RelationshipCategory . COMPOSITION ) { throw new AtlasBaseException ( AtlasErrorCode . RELATIONSHIPDEF_COMPOSITION_NO_CONTAINER , name ) ; } else if ( relationshipCategory == RelationshipCategory . AGGREGATION ) { throw new AtlasBaseException ( AtlasErrorCode . RELATIONSHIPDEF_AGGREGATION_NO_CONTAINER , name ) ; } } if ( relationshipCategory == RelationshipCategory . COMPOSITION ) { if ( endDef1 . getCardinality ( ) == AtlasAttributeDef . Cardinality . SET && ! endDef1 . getIsContainer ( ) ) { throw new AtlasBaseException ( AtlasErrorCode . RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS , name ) ; } if ( ( endDef2 . getCardinality ( ) == AtlasAttributeDef . Cardinality . SET ) && ! endDef2 . getIsContainer ( ) ) { throw new AtlasBaseException ( AtlasErrorCode . RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS , name ) ; } } }
|
Throw an exception so we can junit easily .
|
884
|
public static int getCompiledQueryCacheCapacity ( ) { try { return ApplicationProperties . get ( ) . getInt ( COMPILED_QUERY_CACHE_CAPACITY , DEFAULT_COMPILED_QUERY_CACHE_CAPACITY ) ; } catch ( AtlasException e ) { throw new RuntimeException ( e ) ; } }
|
Get the configuration property that specifies the size of the compiled query cache . This is an optional property . A default is used if it is not present .
|
885
|
public static int getCompiledQueryCacheEvictionWarningThrottle ( ) { try { return ApplicationProperties . get ( ) . getInt ( COMPILED_QUERY_CACHE_EVICTION_WARNING_THROTTLE , DEFAULT_COMPILED_QUERY_CACHE_EVICTION_WARNING_THROTTLE ) ; } catch ( AtlasException e ) { throw new RuntimeException ( e ) ; } }
|
Get the configuration property that specifies the number evictions that pass before a warning is logged . This is an optional property . A default is used if it is not present .
|
886
|
public static FieldMapping getFieldMapping ( IDataType type ) { switch ( type . getTypeCategory ( ) ) { case CLASS : case TRAIT : return ( ( HierarchicalType ) type ) . fieldMapping ( ) ; case STRUCT : return ( ( StructType ) type ) . fieldMapping ( ) ; default : throw new IllegalArgumentException ( "Type " + type + " doesn't have any fields!" ) ; } }
|
Get the field mappings for the specified data type . Field mappings are only relevant for CLASS TRAIT and STRUCT types .
|
887
|
public String getTypeDefinition ( String typeName ) throws AtlasException { final IDataType dataType = typeSystem . getDataType ( IDataType . class , typeName ) ; return TypesSerialization . toJson ( typeSystem , dataType . getName ( ) ) ; }
|
Return the definition for the given type .
|
888
|
public CreateUpdateEntitiesResult createEntities ( String entityInstanceDefinition ) throws AtlasException { entityInstanceDefinition = ParamChecker . notEmpty ( entityInstanceDefinition , "Entity instance definition" ) ; ITypedReferenceableInstance [ ] typedInstances = deserializeClassInstances ( entityInstanceDefinition ) ; return createEntities ( typedInstances ) ; }
|
Creates an entity instance of the type .
|
889
|
private void validateUniqueAttribute ( String entityType , String attributeName ) throws AtlasException { ClassType type = typeSystem . getDataType ( ClassType . class , entityType ) ; AttributeInfo attribute = type . fieldMapping ( ) . fields . get ( attributeName ) ; if ( attribute == null ) { throw new IllegalArgumentException ( String . format ( "%s is not an attribute in %s" , attributeName , entityType ) ) ; } if ( ! attribute . isUnique ) { throw new IllegalArgumentException ( String . format ( "%s.%s is not a unique attribute" , entityType , attributeName ) ) ; } }
|
Validate that attribute is unique attribute
|
890
|
public List < String > getEntityList ( String entityType ) throws AtlasException { validateTypeExists ( entityType ) ; return repository . getEntityList ( entityType ) ; }
|
Return the list of entity guids for the given type in the repository .
|
891
|
public void addTrait ( List < String > entityGuids , ITypedStruct traitInstance ) throws AtlasException { Preconditions . checkNotNull ( entityGuids , "entityGuids list cannot be null" ) ; Preconditions . checkNotNull ( traitInstance , "Trait instance cannot be null" ) ; final String traitName = traitInstance . getTypeName ( ) ; if ( ! typeSystem . isRegistered ( traitName ) ) { String msg = String . format ( "trait=%s should be defined in type system before it can be added" , traitName ) ; LOG . error ( msg ) ; throw new TypeNotFoundException ( msg ) ; } for ( String entityGuid : entityGuids ) { Preconditions . checkArgument ( ! getTraitNames ( entityGuid ) . contains ( traitName ) , "trait=%s is already defined for entity=%s" , traitName , entityGuid ) ; } repository . addTrait ( entityGuids , traitInstance ) ; for ( String entityGuid : entityGuids ) { onTraitAddedToEntity ( repository . getEntityDefinition ( entityGuid ) , traitInstance ) ; } }
|
Adds a new trait to the list of existing entities represented by their respective guids
|
892
|
public Iterator < AtlasEdge > getAdjacentEdgesByLabel ( AtlasVertex instanceVertex , AtlasEdgeDirection direction , final String edgeLabel ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Finding edges for {} with label {}" , string ( instanceVertex ) , edgeLabel ) ; } if ( instanceVertex != null && edgeLabel != null ) { final Iterator < AtlasEdge > iterator = instanceVertex . getEdges ( direction ) . iterator ( ) ; return new Iterator < AtlasEdge > ( ) { private AtlasEdge edge = null ; public boolean hasNext ( ) { while ( edge == null && iterator . hasNext ( ) ) { AtlasEdge localEdge = iterator . next ( ) ; if ( localEdge . getLabel ( ) . equals ( edgeLabel ) ) { edge = localEdge ; } } return edge != null ; } public AtlasEdge next ( ) { if ( hasNext ( ) ) { AtlasEdge localEdge = edge ; edge = null ; return localEdge ; } return null ; } public void remove ( ) { throw new IllegalStateException ( "Not handled" ) ; } } ; } return null ; }
|
So traversing all the edges
|
893
|
public AtlasEdge getEdgeForLabel ( AtlasVertex vertex , String edgeLabel ) { return getEdgeForLabel ( vertex , edgeLabel , AtlasEdgeDirection . OUT ) ; }
|
Returns the active edge for the given edge label . If the vertex is deleted and there is no active edge it returns the latest deleted edge
|
894
|
public void removeEdge ( AtlasEdge edge ) { String edgeString = null ; if ( LOG . isDebugEnabled ( ) ) { edgeString = string ( edge ) ; LOG . debug ( "Removing {}" , edgeString ) ; } graph . removeEdge ( edge ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . info ( "Removed {}" , edgeString ) ; } }
|
Remove the specified edge from the graph .
|
895
|
public void removeVertex ( AtlasVertex vertex ) { String vertexString = null ; if ( LOG . isDebugEnabled ( ) ) { vertexString = string ( vertex ) ; LOG . debug ( "Removing {}" , vertexString ) ; } graph . removeVertex ( vertex ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . info ( "Removed {}" , vertexString ) ; } }
|
Remove the specified AtlasVertex from the graph .
|
896
|
public Map < String , AtlasVertex > getVerticesForPropertyValues ( String property , List < String > values ) { if ( values . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } Collection < String > nonNullValues = new HashSet < > ( values . size ( ) ) ; for ( String value : values ) { if ( value != null ) { nonNullValues . add ( value ) ; } } AtlasGraphQuery query = graph . query ( ) ; query . in ( property , nonNullValues ) ; Iterable < AtlasVertex > results = query . vertices ( ) ; Map < String , AtlasVertex > result = new HashMap < > ( values . size ( ) ) ; for ( AtlasVertex vertex : results ) { if ( vertex . exists ( ) ) { String propertyValue = vertex . getProperty ( property , String . class ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Found a vertex {} with {} = {}" , string ( vertex ) , property , propertyValue ) ; } result . put ( propertyValue , vertex ) ; } } return result ; }
|
Finds the Vertices that correspond to the given property values . Property values that are not found in the graph will not be in the map .
|
897
|
public Map < String , AtlasVertex > getVerticesForGUIDs ( List < String > guids ) { return getVerticesForPropertyValues ( Constants . GUID_PROPERTY_KEY , guids ) ; }
|
Finds the Vertices that correspond to the given GUIDs . GUIDs that are not found in the graph will not be in the map .
|
898
|
public AtlasVertex getVertexForInstanceByUniqueAttribute ( ClassType classType , IReferenceableInstance instance ) throws AtlasException { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Checking if there is an instance with the same unique attributes for instance {}" , instance . toShortString ( ) ) ; } AtlasVertex result = null ; for ( AttributeInfo attributeInfo : classType . fieldMapping ( ) . fields . values ( ) ) { if ( attributeInfo . isUnique ) { String propertyKey = getQualifiedFieldName ( classType , attributeInfo . name ) ; try { result = findVertex ( propertyKey , instance . get ( attributeInfo . name ) , Constants . ENTITY_TYPE_PROPERTY_KEY , classType . getName ( ) , Constants . STATE_PROPERTY_KEY , Id . EntityState . ACTIVE . name ( ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Found vertex by unique attribute : {}={}" , propertyKey , instance . get ( attributeInfo . name ) ) ; } } catch ( EntityNotFoundException e ) { } } } return result ; }
|
For the given type finds an unique attribute and checks if there is an existing instance with the same unique value
|
899
|
public List < AtlasVertex > getVerticesForInstancesByUniqueAttribute ( ClassType classType , List < ? extends IReferenceableInstance > instancesForClass ) throws AtlasException { Map < String , AttributeValueMap > map = new HashMap < String , AttributeValueMap > ( ) ; for ( AttributeInfo attributeInfo : classType . fieldMapping ( ) . fields . values ( ) ) { if ( attributeInfo . isUnique ) { String propertyKey = getQualifiedFieldName ( classType , attributeInfo . name ) ; AttributeValueMap mapForAttribute = new AttributeValueMap ( ) ; for ( int idx = 0 ; idx < instancesForClass . size ( ) ; idx ++ ) { IReferenceableInstance instance = instancesForClass . get ( idx ) ; Object value = instance . get ( attributeInfo . name ) ; mapForAttribute . put ( value , instance , idx ) ; } map . put ( propertyKey , mapForAttribute ) ; } } AtlasVertex [ ] result = new AtlasVertex [ instancesForClass . size ( ) ] ; if ( map . isEmpty ( ) ) { return Arrays . asList ( result ) ; } AtlasGraphQuery query = graph . query ( ) ; query . has ( Constants . ENTITY_TYPE_PROPERTY_KEY , classType . getName ( ) ) ; query . has ( Constants . STATE_PROPERTY_KEY , Id . EntityState . ACTIVE . name ( ) ) ; List < AtlasGraphQuery > orChildren = new ArrayList < AtlasGraphQuery > ( ) ; for ( Map . Entry < String , AttributeValueMap > entry : map . entrySet ( ) ) { AtlasGraphQuery orChild = query . createChildQuery ( ) ; String propertyName = entry . getKey ( ) ; AttributeValueMap valueMap = entry . getValue ( ) ; Set < Object > values = valueMap . getAttributeValues ( ) ; if ( values . size ( ) == 1 ) { orChild . has ( propertyName , values . iterator ( ) . next ( ) ) ; } else if ( values . size ( ) > 1 ) { orChild . in ( propertyName , values ) ; } orChildren . add ( orChild ) ; } if ( orChildren . size ( ) == 1 ) { AtlasGraphQuery child = orChildren . get ( 0 ) ; query . addConditionsFrom ( child ) ; } else if ( orChildren . size ( ) > 1 ) { query . or ( orChildren ) ; } Iterable < AtlasVertex > queryResult = query . vertices ( ) ; for ( AtlasVertex matchingVertex : queryResult ) { Collection < IndexedInstance > matches = getInstancesForVertex ( map , matchingVertex ) ; for ( IndexedInstance wrapper : matches ) { result [ wrapper . getIndex ( ) ] = matchingVertex ; } } return Arrays . asList ( result ) ; }
|
Finds vertices that match at least one unique attribute of the instances specified . The AtlasVertex at a given index in the result corresponds to the IReferencableInstance at that same index that was passed in . The number of elements in the resultant list is guaranteed to match the number of instances that were passed in . If no vertex is found for a given instance that entry will be null in the resultant list .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.