idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
10,700 | public Map < String , String > loadDocStrings ( Set < ServiceConfig > serviceConfigs ) { return serviceConfigs . stream ( ) . flatMap ( c -> c . service ( ) . as ( THttpService . class ) . get ( ) . entries ( ) . values ( ) . stream ( ) ) . flatMap ( entry -> entry . interfaces ( ) . stream ( ) . map ( Class :: getClassLoader ) ) . flatMap ( loader -> docstringExtractor . getAllDocStrings ( loader ) . entrySet ( ) . stream ( ) ) . collect ( toImmutableMap ( Map . Entry :: getKey , Map . Entry :: getValue , ( a , b ) -> a ) ) ; } | Methods related with extracting documentation strings . |
10,701 | public static CorsServiceBuilder forOrigins ( String ... origins ) { requireNonNull ( origins , "origins" ) ; if ( Arrays . asList ( origins ) . contains ( ANY_ORIGIN ) ) { if ( origins . length > 1 ) { logger . warn ( "Any origin (*) has been already included. Other origins ({}) will be ignored." , Arrays . stream ( origins ) . filter ( c -> ! ANY_ORIGIN . equals ( c ) ) . collect ( Collectors . joining ( "," ) ) ) ; } return forAnyOrigin ( ) ; } return new CorsServiceBuilder ( origins ) ; } | Creates a new builder with the specified origins . |
10,702 | public ZooKeeperUpdatingListenerBuilder connectTimeout ( Duration connectTimeout ) { requireNonNull ( connectTimeout , "connectTimeout" ) ; checkArgument ( ! connectTimeout . isZero ( ) && ! connectTimeout . isNegative ( ) , "connectTimeout: %s (expected: > 0)" , connectTimeout ) ; return connectTimeoutMillis ( connectTimeout . toMillis ( ) ) ; } | Sets the connect timeout . |
10,703 | public ZooKeeperUpdatingListenerBuilder sessionTimeout ( Duration sessionTimeout ) { requireNonNull ( sessionTimeout , "sessionTimeout" ) ; checkArgument ( ! sessionTimeout . isZero ( ) && ! sessionTimeout . isNegative ( ) , "sessionTimeout: %s (expected: > 0)" , sessionTimeout ) ; return sessionTimeoutMillis ( sessionTimeout . toMillis ( ) ) ; } | Sets the session timeout . |
10,704 | public static ZooKeeperUpdatingListener of ( String zkConnectionStr , String zNodePath ) { return new ZooKeeperUpdatingListenerBuilder ( zkConnectionStr , zNodePath ) . build ( ) ; } | Creates a ZooKeeper server listener which registers server into ZooKeeper . |
10,705 | private static void setContentLength ( HttpRequest req , HttpHeaders headers , int contentLength ) { if ( req . method ( ) == HttpMethod . HEAD || ArmeriaHttpUtil . isContentAlwaysEmpty ( headers . status ( ) ) ) { return ; } headers . setInt ( HttpHeaderNames . CONTENT_LENGTH , contentLength ) ; } | Sets the content - length header to the response . |
10,706 | public void deframe ( HttpData data , boolean endOfStream ) { requireNonNull ( data , "data" ) ; checkNotClosed ( ) ; checkState ( ! this . endOfStream , "Past end of stream" ) ; startedDeframing = true ; final int dataLength = data . length ( ) ; if ( dataLength != 0 ) { final ByteBuf buf ; if ( data instanceof ByteBufHolder ) { buf = ( ( ByteBufHolder ) data ) . content ( ) ; } else { buf = Unpooled . wrappedBuffer ( data . array ( ) , data . offset ( ) , dataLength ) ; } assert unprocessed != null ; unprocessed . add ( buf ) ; unprocessedBytes += dataLength ; } this . endOfStream = endOfStream ; deliver ( ) ; } | Adds the given data to this deframer and attempts delivery to the listener . |
10,707 | public void close ( ) { if ( unprocessed != null ) { try { unprocessed . forEach ( ByteBuf :: release ) ; } finally { unprocessed = null ; } if ( endOfStream ) { listener . endOfStream ( ) ; } } } | Closes this deframer and frees any resources . After this method is called additional calls will have no effect . |
10,708 | private void readHeader ( ) { final int type = readUnsignedByte ( ) ; if ( ( type & RESERVED_MASK ) != 0 ) { throw new ArmeriaStatusException ( StatusCodes . INTERNAL , DEBUG_STRING + ": Frame header malformed: reserved bits not zero" ) ; } compressedFlag = ( type & COMPRESSED_FLAG_MASK ) != 0 ; requiredLength = readInt ( ) ; if ( requiredLength < 0 || requiredLength > maxMessageSizeBytes ) { throw new ArmeriaStatusException ( StatusCodes . RESOURCE_EXHAUSTED , String . format ( "%s: Frame size %d exceeds maximum: %d. " , DEBUG_STRING , requiredLength , maxMessageSizeBytes ) ) ; } state = State . BODY ; } | Processes the gRPC compression header which is composed of the compression flag and the outer frame length . |
10,709 | private void readBody ( ) { final ByteBuf buf = readBytes ( requiredLength ) ; final ByteBufOrStream msg = compressedFlag ? getCompressedBody ( buf ) : getUncompressedBody ( buf ) ; listener . messageRead ( msg ) ; state = State . HEADER ; requiredLength = HEADER_LENGTH ; } | Processes the body of the gRPC compression frame . A single compression frame may contain several gRPC messages within it . |
10,710 | @ Get ( "/hello/{name}" ) public String hello ( @ Size ( min = 3 , max = 10 , message = "name should have between 3 and 10 characters" ) String name ) { return String . format ( "Hello, %s! This message is from Armeria annotated service!" , name ) ; } | An example in order to show how to use validation framework in an annotated HTTP service . |
10,711 | public ArmeriaRetrofitBuilder baseUrl ( String baseUrl ) { requireNonNull ( baseUrl , "baseUrl" ) ; final URI uri = URI . create ( baseUrl ) ; checkArgument ( SessionProtocol . find ( uri . getScheme ( ) ) . isPresent ( ) , "baseUrl must have an HTTP scheme: %s" , baseUrl ) ; final String path = uri . getPath ( ) ; if ( ! path . isEmpty ( ) && ! SLASH . equals ( path . substring ( path . length ( ) - 1 ) ) ) { throw new IllegalArgumentException ( "baseUrl must end with /: " + baseUrl ) ; } this . baseUrl = baseUrl ; return this ; } | Sets the API base URL . |
10,712 | final void doRequest ( SubscriptionImpl subscription , long unused ) { if ( requested ( ) != 0 ) { return ; } setRequested ( 1 ) ; notifySubscriberOfCloseEvent ( subscription , SUCCESSFUL_CLOSE ) ; } | No objects so just notify of close as soon as there is demand . |
10,713 | public ServerBuilder idleTimeout ( Duration idleTimeout ) { requireNonNull ( idleTimeout , "idleTimeout" ) ; idleTimeoutMillis = ServerConfig . validateIdleTimeoutMillis ( idleTimeout . toMillis ( ) ) ; return this ; } | Sets the idle timeout of a connection for keep - alive . |
10,714 | public static String decodePath ( String path ) { if ( path . indexOf ( '%' ) < 0 ) { return path ; } final int len = path . length ( ) ; final byte [ ] buf = new byte [ len ] ; int dstLen = 0 ; for ( int i = 0 ; i < len ; i ++ ) { final char ch = path . charAt ( i ) ; if ( ch != '%' ) { buf [ dstLen ++ ] = ( byte ) ( ( ch & 0xFF80 ) == 0 ? ch : 0xFF ) ; continue ; } final int hexEnd = i + 3 ; if ( hexEnd > len ) { buf [ dstLen ++ ] = ( byte ) 0xFF ; break ; } final int digit1 = decodeHexNibble ( path . charAt ( ++ i ) ) ; final int digit2 = decodeHexNibble ( path . charAt ( ++ i ) ) ; if ( digit1 < 0 || digit2 < 0 ) { buf [ dstLen ++ ] = ( byte ) 0xFF ; } else { buf [ dstLen ++ ] = ( byte ) ( ( digit1 << 4 ) | digit2 ) ; } } return new String ( buf , 0 , dstLen , StandardCharsets . UTF_8 ) ; } | Decodes a percent - encoded path string . |
10,715 | public int doRead ( ByteChunk chunk ) { if ( ! isNeedToRead ( ) ) { return - 1 ; } read = true ; final int readableBytes = content . length ( ) ; chunk . setBytes ( content . array ( ) , content . offset ( ) , readableBytes ) ; return readableBytes ; } | Required for 8 . 5 . |
10,716 | private List < ServerConnection > updateServerList ( ) { final Map < Endpoint , ServerConnection > allServersByEndpoint = allServers . stream ( ) . collect ( toImmutableMap ( ServerConnection :: endpoint , Function . identity ( ) , ( l , r ) -> l ) ) ; return allServers = delegate . endpoints ( ) . stream ( ) . map ( endpoint -> { ServerConnection connection = allServersByEndpoint . get ( endpoint ) ; if ( connection != null ) { return connection ; } return new ServerConnection ( endpoint , createEndpointHealthChecker ( endpoint ) ) ; } ) . collect ( toImmutableList ( ) ) ; } | Update the servers this health checker client talks to . |
10,717 | private HttpResponse handleCorsPreflight ( ServiceRequestContext ctx , HttpRequest req ) { final HttpHeaders headers = HttpHeaders . of ( HttpStatus . OK ) ; final CorsPolicy policy = setCorsOrigin ( ctx , req , headers ) ; if ( policy != null ) { policy . setCorsAllowMethods ( headers ) ; policy . setCorsAllowHeaders ( headers ) ; policy . setCorsAllowCredentials ( headers ) ; policy . setCorsMaxAge ( headers ) ; policy . setCorsPreflightResponseHeaders ( headers ) ; } return HttpResponse . of ( headers ) ; } | Handles CORS preflight by setting the appropriate headers . |
10,718 | private void setCorsResponseHeaders ( ServiceRequestContext ctx , HttpRequest req , HttpHeaders headers ) { final CorsPolicy policy = setCorsOrigin ( ctx , req , headers ) ; if ( policy != null ) { policy . setCorsAllowCredentials ( headers ) ; policy . setCorsAllowHeaders ( headers ) ; policy . setCorsExposeHeaders ( headers ) ; } } | Emit CORS headers if origin was found . |
10,719 | private CorsPolicy setCorsOrigin ( ServiceRequestContext ctx , HttpRequest request , HttpHeaders headers ) { if ( ! config . isEnabled ( ) ) { return null ; } final String origin = request . headers ( ) . get ( HttpHeaderNames . ORIGIN ) ; if ( origin != null ) { final CorsPolicy policy = config . getPolicy ( origin , ctx . pathMappingContext ( ) ) ; if ( policy == null ) { logger . debug ( "{} There is no CORS policy configured for the request origin '{}' and the path '{}'." , ctx , origin , ctx . path ( ) ) ; return null ; } if ( NULL_ORIGIN . equals ( origin ) ) { setCorsNullOrigin ( headers ) ; return policy ; } if ( config . isAnyOriginSupported ( ) ) { if ( policy . isCredentialsAllowed ( ) ) { echoCorsRequestOrigin ( request , headers ) ; setCorsVaryHeader ( headers ) ; } else { setCorsAnyOrigin ( headers ) ; } return policy ; } setCorsOrigin ( headers , origin ) ; setCorsVaryHeader ( headers ) ; return policy ; } return null ; } | Sets origin header according to the given CORS configuration and HTTP request . |
10,720 | public PathMappingResultBuilder decodedParam ( String name , String value ) { params . put ( requireNonNull ( name , "name" ) , requireNonNull ( value , "value" ) ) ; return this ; } | Adds a decoded path parameter . |
10,721 | public PathMappingResultBuilder rawParam ( String name , String value ) { params . put ( requireNonNull ( name , "name" ) , ArmeriaHttpUtil . decodePath ( requireNonNull ( value , "value" ) ) ) ; return this ; } | Adds an encoded path parameter which will be decoded in UTF - 8 automatically . |
10,722 | static void ensureHostnamePatternMatchesDefaultHostname ( String hostnamePattern , String defaultHostname ) { if ( "*" . equals ( hostnamePattern ) ) { return ; } final DomainNameMapping < Boolean > mapping = new DomainNameMappingBuilder < > ( Boolean . FALSE ) . add ( hostnamePattern , Boolean . TRUE ) . build ( ) ; if ( ! mapping . map ( defaultHostname ) ) { throw new IllegalArgumentException ( "defaultHostname: " + defaultHostname + " (must be matched by hostnamePattern: " + hostnamePattern + ')' ) ; } } | Ensure that hostnamePattern matches defaultHostname . |
10,723 | public TBase < ? , ? > newArgs ( List < Object > args ) { requireNonNull ( args , "args" ) ; final TBase < ? , ? > newArgs = newArgs ( ) ; final int size = args . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { ThriftFieldAccess . set ( newArgs , argFields [ i ] , args . get ( i ) ) ; } return newArgs ; } | Returns a new arguments instance . |
10,724 | public void writeMessageBegin ( TMessage message ) throws TException { try { getCurrentWriter ( ) . writeStartObject ( ) ; getCurrentWriter ( ) . writeFieldName ( "method" ) ; getCurrentWriter ( ) . writeString ( message . name ) ; getCurrentWriter ( ) . writeFieldName ( "type" ) ; TypedParser . TMESSAGE_TYPE . writeValue ( getCurrentWriter ( ) , message . type ) ; getCurrentWriter ( ) . writeFieldName ( "seqid" ) ; getCurrentWriter ( ) . writeNumber ( message . seqid ) ; getCurrentWriter ( ) . writeFieldName ( "args" ) ; } catch ( IOException e ) { throw new TTransportException ( e ) ; } } | I believe these two messages are called for a thrift service interface . We don t plan on storing any text objects of that type on disk . |
10,725 | private void readRoot ( ) throws IOException { if ( root != null ) { return ; } final ByteArrayOutputStream content = new ByteArrayOutputStream ( ) ; final byte [ ] buffer = new byte [ READ_BUFFER_SIZE ] ; try { while ( trans_ . read ( buffer , 0 , READ_BUFFER_SIZE ) > 0 ) { content . write ( buffer ) ; } } catch ( TTransportException e ) { if ( TTransportException . END_OF_FILE != e . getType ( ) ) { throw new IOException ( e ) ; } } root = OBJECT_MAPPER . readTree ( content . toByteArray ( ) ) ; } | Read in the root node if it has not yet been read . |
10,726 | public Function < Service < HttpRequest , HttpResponse > , Service < HttpRequest , HttpResponse > > newSamlDecorator ( ) { return delegate -> new SamlDecorator ( this , delegate ) ; } | Creates a decorator which initiates a SAML authentication if a request is not authenticated . |
10,727 | public static void copy ( RequestContext src , RequestContext dst ) { dst . attr ( TRACE_CONTEXT_KEY ) . set ( src . attr ( TRACE_CONTEXT_KEY ) . get ( ) ) ; } | Use this to ensure the trace context propagates to children . |
10,728 | private static Attribute < TraceContext > getTraceContextAttributeOrWarnOnce ( ) { final RequestContext ctx = getRequestContextOrWarnOnce ( ) ; if ( ctx == null ) { return null ; } return ctx . attr ( TRACE_CONTEXT_KEY ) ; } | Armeria code should always have a request context available and this won t work without it . |
10,729 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public Map < String , List < String > > parameters ( ) { return ( Map < String , List < String > > ) ( Map ) parameters . asMap ( ) ; } | Returns a multimap containing the parameters of this media type . |
10,730 | public static void addTags ( Span span , RequestLog log ) { final String host = log . requestHeaders ( ) . authority ( ) ; assert host != null ; span . tag ( "http.host" , host ) ; final StringBuilder uriBuilder = new StringBuilder ( ) . append ( log . scheme ( ) . uriText ( ) ) . append ( "://" ) . append ( host ) . append ( log . path ( ) ) ; if ( log . query ( ) != null ) { uriBuilder . append ( '?' ) . append ( log . query ( ) ) ; } span . tag ( "http.method" , log . method ( ) . name ( ) ) . tag ( "http.path" , log . path ( ) ) . tag ( "http.url" , uriBuilder . toString ( ) ) . tag ( "http.status_code" , log . status ( ) . codeAsText ( ) ) ; final Throwable responseCause = log . responseCause ( ) ; if ( responseCause != null ) { span . tag ( "error" , responseCause . toString ( ) ) ; } final SocketAddress raddr = log . context ( ) . remoteAddress ( ) ; if ( raddr != null ) { span . tag ( "address.remote" , raddr . toString ( ) ) ; } final SocketAddress laddr = log . context ( ) . localAddress ( ) ; if ( laddr != null ) { span . tag ( "address.local" , laddr . toString ( ) ) ; } final Object requestContent = log . requestContent ( ) ; if ( requestContent instanceof RpcRequest ) { span . name ( ( ( RpcRequest ) requestContent ) . method ( ) ) ; } } | Adds information about the raw HTTP request RPC request and endpoint to the span . |
10,731 | public static int packLongSize ( long value ) { int shift = 63 - Long . numberOfLeadingZeros ( value ) ; shift -= shift % 7 ; int ret = 1 ; while ( shift != 0 ) { shift -= 7 ; ret ++ ; } return ret ; } | Calculate how much bytes packed long consumes . |
10,732 | static public long unpackRecid ( DataInput2 in ) throws IOException { long val = in . readPackedLong ( ) ; val = DataIO . parity1Get ( val ) ; return val >>> 1 ; } | Unpack RECID value from the input stream with 3 bit checksum . |
10,733 | public static String toHexa ( byte [ ] bb ) { char [ ] HEXA_CHARS = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' } ; char [ ] ret = new char [ bb . length * 2 ] ; for ( int i = 0 ; i < bb . length ; i ++ ) { ret [ i * 2 ] = HEXA_CHARS [ ( ( bb [ i ] & 0xF0 ) >> 4 ) ] ; ret [ i * 2 + 1 ] = HEXA_CHARS [ ( ( bb [ i ] & 0x0F ) ) ] ; } return new String ( ret ) ; } | Converts binary array into its hexadecimal representation . |
10,734 | public static byte [ ] fromHexa ( String s ) { byte [ ] ret = new byte [ s . length ( ) / 2 ] ; for ( int i = 0 ; i < ret . length ; i ++ ) { ret [ i ] = ( byte ) Integer . parseInt ( s . substring ( i * 2 , i * 2 + 2 ) , 16 ) ; } return ret ; } | Converts hexadecimal string into binary data |
10,735 | public static boolean isWindows ( ) { String os = System . getProperty ( "os.name" ) ; return os != null && os . toLowerCase ( ) . startsWith ( "windows" ) ; } | return true if operating system is Windows |
10,736 | public static boolean JVMSupportsLargeMappedFiles ( ) { String arch = System . getProperty ( "os.arch" ) ; if ( arch == null || ! arch . contains ( "64" ) ) { return false ; } if ( isWindows ( ) ) return false ; return true ; } | Check if large files can be mapped into memory . For example 32bit JVM can only address 2GB and large files can not be mapped so for 32bit JVM this function returns false . |
10,737 | public static < K , V > Map < K , V > toSortedMap ( Map < K , V > map , Comparator < ? super K > comparator ) { Map < K , V > sortedMap ; if ( comparator == null ) sortedMap = new LinkedHashMap < > ( ) ; else sortedMap = new TreeMap < > ( comparator ) ; sortedMap . putAll ( map ) ; return sortedMap ; } | Returns the the Map either ordered or as - is if the comparator is null . |
10,738 | private String determineDefinitionTitle ( Parameters params ) { if ( params . model . getTitle ( ) != null ) { return params . model . getTitle ( ) ; } else { return params . definitionName ; } } | Determines title for definition . If title is present it is used definitionName is returned otherwise . |
10,739 | public static Object generateExample ( Property property , MarkupDocBuilder markupDocBuilder ) { if ( property . getType ( ) == null ) { return "untyped" ; } switch ( property . getType ( ) ) { case "integer" : return ExamplesUtil . generateIntegerExample ( property instanceof IntegerProperty ? ( ( IntegerProperty ) property ) . getEnum ( ) : null ) ; case "number" : return 0.0 ; case "boolean" : return true ; case "string" : return ExamplesUtil . generateStringExample ( property . getFormat ( ) , property instanceof StringProperty ? ( ( StringProperty ) property ) . getEnum ( ) : null ) ; case "ref" : if ( property instanceof RefProperty ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "generateExample RefProperty for " + property . getName ( ) ) ; return markupDocBuilder . copy ( false ) . crossReference ( ( ( RefProperty ) property ) . getSimpleRef ( ) ) . toString ( ) ; } else { if ( logger . isDebugEnabled ( ) ) logger . debug ( "generateExample for ref not RefProperty" ) ; } case "array" : if ( property instanceof ArrayProperty ) { return generateArrayExample ( ( ArrayProperty ) property , markupDocBuilder ) ; } default : return property . getType ( ) ; } } | Generate a default example value for property . |
10,740 | private static Object generateArrayExample ( ArrayProperty property , MarkupDocBuilder markupDocBuilder ) { Property itemProperty = property . getItems ( ) ; List < Object > exampleArray = new ArrayList < > ( ) ; exampleArray . add ( generateExample ( itemProperty , markupDocBuilder ) ) ; return exampleArray ; } | Generate example for an ArrayProperty |
10,741 | public Optional < Object > getDefaultValue ( ) { if ( property instanceof BooleanProperty ) { BooleanProperty booleanProperty = ( BooleanProperty ) property ; return Optional . ofNullable ( booleanProperty . getDefault ( ) ) ; } else if ( property instanceof StringProperty ) { StringProperty stringProperty = ( StringProperty ) property ; return Optional . ofNullable ( stringProperty . getDefault ( ) ) ; } else if ( property instanceof DoubleProperty ) { DoubleProperty doubleProperty = ( DoubleProperty ) property ; return Optional . ofNullable ( doubleProperty . getDefault ( ) ) ; } else if ( property instanceof FloatProperty ) { FloatProperty floatProperty = ( FloatProperty ) property ; return Optional . ofNullable ( floatProperty . getDefault ( ) ) ; } else if ( property instanceof IntegerProperty ) { IntegerProperty integerProperty = ( IntegerProperty ) property ; return Optional . ofNullable ( integerProperty . getDefault ( ) ) ; } else if ( property instanceof LongProperty ) { LongProperty longProperty = ( LongProperty ) property ; return Optional . ofNullable ( longProperty . getDefault ( ) ) ; } else if ( property instanceof UUIDProperty ) { UUIDProperty uuidProperty = ( UUIDProperty ) property ; return Optional . ofNullable ( uuidProperty . getDefault ( ) ) ; } return Optional . empty ( ) ; } | Retrieves the default value of a property |
10,742 | public Optional < Integer > getMinlength ( ) { if ( property instanceof StringProperty ) { StringProperty stringProperty = ( StringProperty ) property ; return Optional . ofNullable ( stringProperty . getMinLength ( ) ) ; } else if ( property instanceof UUIDProperty ) { UUIDProperty uuidProperty = ( UUIDProperty ) property ; return Optional . ofNullable ( uuidProperty . getMinLength ( ) ) ; } return Optional . empty ( ) ; } | Retrieves the minLength of a property |
10,743 | public Optional < Integer > getMaxlength ( ) { if ( property instanceof StringProperty ) { StringProperty stringProperty = ( StringProperty ) property ; return Optional . ofNullable ( stringProperty . getMaxLength ( ) ) ; } else if ( property instanceof UUIDProperty ) { UUIDProperty uuidProperty = ( UUIDProperty ) property ; return Optional . ofNullable ( uuidProperty . getMaxLength ( ) ) ; } return Optional . empty ( ) ; } | Retrieves the maxLength of a property |
10,744 | public Optional < String > getPattern ( ) { if ( property instanceof StringProperty ) { StringProperty stringProperty = ( StringProperty ) property ; return Optional . ofNullable ( stringProperty . getPattern ( ) ) ; } else if ( property instanceof UUIDProperty ) { UUIDProperty uuidProperty = ( UUIDProperty ) property ; return Optional . ofNullable ( uuidProperty . getPattern ( ) ) ; } return Optional . empty ( ) ; } | Retrieves the pattern of a property |
10,745 | public boolean getExclusiveMin ( ) { if ( property instanceof AbstractNumericProperty ) { AbstractNumericProperty numericProperty = ( AbstractNumericProperty ) property ; return BooleanUtils . isTrue ( numericProperty . getExclusiveMinimum ( ) ) ; } return false ; } | Retrieves the exclusiveMinimum value of a property |
10,746 | public boolean getExclusiveMax ( ) { if ( property instanceof AbstractNumericProperty ) { AbstractNumericProperty numericProperty = ( AbstractNumericProperty ) property ; return BooleanUtils . isTrue ( ( numericProperty . getExclusiveMaximum ( ) ) ) ; } return false ; } | Retrieves the exclusiveMaximum value of a property |
10,747 | private Configuration getDefaultConfiguration ( ) { Configurations configs = new Configurations ( ) ; try { return configs . properties ( PROPERTIES_DEFAULT ) ; } catch ( ConfigurationException e ) { throw new RuntimeException ( String . format ( "Can't load default properties '%s'" , PROPERTIES_DEFAULT ) , e ) ; } } | Loads the default properties from the classpath . |
10,748 | public Swagger2MarkupConfigBuilder withMarkupLanguage ( MarkupLanguage markupLanguage ) { Validate . notNull ( markupLanguage , "%s must not be null" , "markupLanguage" ) ; config . markupLanguage = markupLanguage ; return this ; } | Specifies the markup language which should be used to generate the files . |
10,749 | public Swagger2MarkupConfigBuilder withSwaggerMarkupLanguage ( MarkupLanguage swaggerMarkupLanguage ) { Validate . notNull ( swaggerMarkupLanguage , "%s must not be null" , "swaggerMarkupLanguage" ) ; config . swaggerMarkupLanguage = swaggerMarkupLanguage ; return this ; } | Specifies the markup language used in Swagger descriptions . |
10,750 | public Swagger2MarkupConfigBuilder withListDelimiter ( Character delimiter ) { Validate . notNull ( delimiter , "%s must not be null" , "delimiter" ) ; config . listDelimiter = delimiter ; config . listDelimiterEnabled = true ; return this ; } | Specifies the list delimiter which should be used . |
10,751 | public Swagger2MarkupConfigBuilder withPathsGroupedBy ( GroupBy pathsGroupedBy ) { Validate . notNull ( pathsGroupedBy , "%s must not be null" , "pathsGroupedBy" ) ; config . pathsGroupedBy = pathsGroupedBy ; return this ; } | Specifies if the paths should be grouped by tags or stay as - is . |
10,752 | public Swagger2MarkupConfigBuilder withHeaderRegex ( String headerRegex ) { Validate . notNull ( headerRegex , "%s must not be null" , headerRegex ) ; config . headerPattern = Pattern . compile ( headerRegex ) ; return this ; } | Specifies the regex pattern to use for grouping paths . |
10,753 | public Swagger2MarkupConfigBuilder withOutputLanguage ( Language language ) { Validate . notNull ( language , "%s must not be null" , "language" ) ; config . outputLanguage = language ; return this ; } | Specifies labels language of output files . |
10,754 | public Swagger2MarkupConfigBuilder withTagOrdering ( Comparator < String > tagOrdering ) { Validate . notNull ( tagOrdering , "%s must not be null" , "tagOrdering" ) ; config . tagOrderBy = OrderBy . CUSTOM ; config . tagOrdering = tagOrdering ; return this ; } | Specifies a custom comparator function to order tags . |
10,755 | public Swagger2MarkupConfigBuilder withOperationOrdering ( Comparator < PathOperation > operationOrdering ) { Validate . notNull ( operationOrdering , "%s must not be null" , "operationOrdering" ) ; config . operationOrderBy = OrderBy . CUSTOM ; config . operationOrdering = operationOrdering ; return this ; } | Specifies a custom comparator function to order operations . |
10,756 | public Swagger2MarkupConfigBuilder withDefinitionOrdering ( Comparator < String > definitionOrdering ) { Validate . notNull ( definitionOrdering , "%s must not be null" , "definitionOrdering" ) ; config . definitionOrderBy = OrderBy . CUSTOM ; config . definitionOrdering = definitionOrdering ; return this ; } | Specifies a custom comparator function to order definitions . |
10,757 | public Swagger2MarkupConfigBuilder withParameterOrdering ( Comparator < Parameter > parameterOrdering ) { Validate . notNull ( parameterOrdering , "%s must not be null" , "parameterOrdering" ) ; config . parameterOrderBy = OrderBy . CUSTOM ; config . parameterOrdering = parameterOrdering ; return this ; } | Specifies a custom comparator function to order parameters . |
10,758 | public Swagger2MarkupConfigBuilder withPropertyOrdering ( Comparator < String > propertyOrdering ) { Validate . notNull ( propertyOrdering , "%s must not be null" , "propertyOrdering" ) ; config . propertyOrderBy = OrderBy . CUSTOM ; config . propertyOrdering = propertyOrdering ; return this ; } | Specifies a custom comparator function to order properties . |
10,759 | public Swagger2MarkupConfigBuilder withResponseOrdering ( Comparator < String > responseOrdering ) { Validate . notNull ( responseOrdering , "%s must not be null" , "responseOrdering" ) ; config . responseOrderBy = OrderBy . CUSTOM ; config . responseOrdering = responseOrdering ; return this ; } | Specifies a custom comparator function to order responses . |
10,760 | public Swagger2MarkupConfigBuilder withInterDocumentCrossReferences ( String prefix ) { Validate . notNull ( prefix , "%s must not be null" , "prefix" ) ; config . interDocumentCrossReferencesEnabled = true ; config . interDocumentCrossReferencesPrefix = prefix ; return this ; } | Enable use of inter - document cross - references when needed . |
10,761 | public Swagger2MarkupConfigBuilder withAnchorPrefix ( String anchorPrefix ) { Validate . notNull ( anchorPrefix , "%s must not be null" , "anchorPrefix" ) ; config . anchorPrefix = anchorPrefix ; return this ; } | Optionally prefix all anchors for uniqueness . |
10,762 | public Swagger2MarkupConfigBuilder withPageBreaks ( List < PageBreakLocations > locations ) { Validate . notNull ( locations , "%s must not be null" , "locations" ) ; config . pageBreakLocations = locations ; return this ; } | Set the page break locations |
10,763 | public Swagger2MarkupConfigBuilder withLineSeparator ( LineSeparator lineSeparator ) { Validate . notNull ( lineSeparator , "%s must no be null" , "lineSeparator" ) ; config . lineSeparator = lineSeparator ; return this ; } | Specifies the line separator which should be used . |
10,764 | public Optional < String > getString ( String key ) { return Optional . ofNullable ( configuration . getString ( key ) ) ; } | Returns an optional String property value associated with the given key . |
10,765 | public Optional < Integer > getInteger ( String key ) { return Optional . ofNullable ( configuration . getInteger ( key , null ) ) ; } | Returns an optional Integer property value associated with the given key . |
10,766 | private void buildOperationTitle ( MarkupDocBuilder markupDocBuilder , PathOperation operation ) { buildOperationTitle ( markupDocBuilder , operation . getTitle ( ) , operation . getId ( ) ) ; if ( operation . getTitle ( ) . equals ( operation . getOperation ( ) . getSummary ( ) ) ) { markupDocBuilder . block ( operation . getMethod ( ) + " " + operation . getPath ( ) , MarkupBlockStyle . LITERAL ) ; } } | Adds the operation title to the document . If the operation has a summary the title is the summary . Otherwise the title is the method of the operation and the URL of the operation . |
10,767 | private void buildOperationTitle ( MarkupDocBuilder markupDocBuilder , String title , String anchor ) { if ( config . getPathsGroupedBy ( ) == GroupBy . AS_IS ) { markupDocBuilder . sectionTitleWithAnchorLevel2 ( title , anchor ) ; } else { markupDocBuilder . sectionTitleWithAnchorLevel3 ( title , anchor ) ; } } | Adds a operation title to the document . |
10,768 | private void buildDeprecatedSection ( MarkupDocBuilder markupDocBuilder , PathOperation operation ) { if ( BooleanUtils . isTrue ( operation . getOperation ( ) . isDeprecated ( ) ) ) { markupDocBuilder . block ( DEPRECATED_OPERATION , MarkupBlockStyle . EXAMPLE , null , MarkupAdmonition . CAUTION ) ; } } | Builds a warning if method is deprecated . |
10,769 | private void buildDescriptionSection ( MarkupDocBuilder markupDocBuilder , PathOperation operation ) { MarkupDocBuilder descriptionBuilder = copyMarkupDocBuilder ( markupDocBuilder ) ; applyPathsDocumentExtension ( new PathsDocumentExtension . Context ( Position . OPERATION_DESCRIPTION_BEGIN , descriptionBuilder , operation ) ) ; String description = operation . getOperation ( ) . getDescription ( ) ; if ( isNotBlank ( description ) ) { descriptionBuilder . paragraph ( markupDescription ( config . getSwaggerMarkupLanguage ( ) , markupDocBuilder , description ) ) ; } applyPathsDocumentExtension ( new PathsDocumentExtension . Context ( Position . OPERATION_DESCRIPTION_END , descriptionBuilder , operation ) ) ; String descriptionContent = descriptionBuilder . toString ( ) ; applyPathsDocumentExtension ( new PathsDocumentExtension . Context ( Position . OPERATION_DESCRIPTION_BEFORE , markupDocBuilder , operation ) ) ; if ( isNotBlank ( descriptionContent ) ) { buildSectionTitle ( markupDocBuilder , labels . getLabel ( DESCRIPTION ) ) ; markupDocBuilder . text ( descriptionContent ) ; } applyPathsDocumentExtension ( new PathsDocumentExtension . Context ( Position . OPERATION_DESCRIPTION_AFTER , markupDocBuilder , operation ) ) ; } | Adds a operation description to the document . |
10,770 | private List < ObjectType > buildParametersSection ( MarkupDocBuilder markupDocBuilder , PathOperation operation ) { List < ObjectType > inlineDefinitions = new ArrayList < > ( ) ; parameterTableComponent . apply ( markupDocBuilder , ParameterTableComponent . parameters ( operation , inlineDefinitions , getSectionTitleLevel ( ) ) ) ; return inlineDefinitions ; } | Builds the parameters section |
10,771 | private List < ObjectType > buildBodyParameterSection ( MarkupDocBuilder markupDocBuilder , PathOperation operation ) { List < ObjectType > inlineDefinitions = new ArrayList < > ( ) ; bodyParameterComponent . apply ( markupDocBuilder , BodyParameterComponent . parameters ( operation , inlineDefinitions ) ) ; return inlineDefinitions ; } | Builds the body parameter section |
10,772 | private void buildSectionTitle ( MarkupDocBuilder markupDocBuilder , String title ) { if ( config . getPathsGroupedBy ( ) == GroupBy . AS_IS ) { markupDocBuilder . sectionTitleLevel3 ( title ) ; } else { markupDocBuilder . sectionTitleLevel4 ( title ) ; } } | Adds a operation section title to the document . |
10,773 | public static Map < String , Tag > toSortedMap ( List < Tag > tags , Comparator < String > comparator ) { Map < String , Tag > sortedMap ; if ( comparator == null ) sortedMap = new LinkedHashMap < > ( ) ; else sortedMap = new TreeMap < > ( comparator ) ; tags . forEach ( tag -> sortedMap . put ( tag . getName ( ) , tag ) ) ; return sortedMap ; } | Converts the global Tag list into a Map where the tag name is the key and the Tag the value . Either ordered or as - is if the comparator is null . |
10,774 | public static Multimap < String , PathOperation > groupOperationsByTag ( List < PathOperation > allOperations , Comparator < PathOperation > operationOrdering ) { Multimap < String , PathOperation > operationsGroupedByTag ; if ( operationOrdering == null ) { operationsGroupedByTag = LinkedHashMultimap . create ( ) ; } else { operationsGroupedByTag = MultimapBuilder . linkedHashKeys ( ) . treeSetValues ( operationOrdering ) . build ( ) ; } for ( PathOperation operation : allOperations ) { List < String > tags = operation . getOperation ( ) . getTags ( ) ; Validate . notEmpty ( tags , "Can't GroupBy.TAGS. Operation '%s' has no tags" , operation ) ; for ( String tag : tags ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Added path operation '{}' to tag '{}'" , operation , tag ) ; } operationsGroupedByTag . put ( tag , operation ) ; } } return operationsGroupedByTag ; } | Groups the operations by tag . The key of the Multimap is the tag name . The value of the Multimap is a PathOperation |
10,775 | public MarkupDocBuilder apply ( MarkupDocBuilder markupDocBuilder , PathsDocument . Parameters params ) { Map < String , Path > paths = params . paths ; if ( MapUtils . isNotEmpty ( paths ) ) { applyPathsDocumentExtension ( new Context ( Position . DOCUMENT_BEFORE , markupDocBuilder ) ) ; buildPathsTitle ( markupDocBuilder ) ; applyPathsDocumentExtension ( new Context ( Position . DOCUMENT_BEGIN , markupDocBuilder ) ) ; buildsPathsSection ( markupDocBuilder , paths ) ; applyPathsDocumentExtension ( new Context ( Position . DOCUMENT_END , markupDocBuilder ) ) ; applyPathsDocumentExtension ( new Context ( Position . DOCUMENT_AFTER , markupDocBuilder ) ) ; } return markupDocBuilder ; } | Builds the paths MarkupDocument . |
10,776 | private void buildsPathsSection ( MarkupDocBuilder markupDocBuilder , Map < String , Path > paths ) { List < PathOperation > pathOperations = PathUtils . toPathOperationsList ( paths , getHostname ( ) , getBasePath ( ) , config . getOperationOrdering ( ) ) ; if ( CollectionUtils . isNotEmpty ( pathOperations ) ) { if ( config . getPathsGroupedBy ( ) == GroupBy . AS_IS ) { pathOperations . forEach ( operation -> buildOperation ( markupDocBuilder , operation , config ) ) ; } else if ( config . getPathsGroupedBy ( ) == GroupBy . TAGS ) { Validate . notEmpty ( context . getSwagger ( ) . getTags ( ) , "Tags must not be empty, when operations are grouped by tags" ) ; Multimap < String , PathOperation > operationsGroupedByTag = TagUtils . groupOperationsByTag ( pathOperations , config . getOperationOrdering ( ) ) ; Map < String , Tag > tagsMap = TagUtils . toSortedMap ( context . getSwagger ( ) . getTags ( ) , config . getTagOrdering ( ) ) ; tagsMap . forEach ( ( String tagName , Tag tag ) -> { markupDocBuilder . sectionTitleWithAnchorLevel2 ( WordUtils . capitalize ( tagName ) , tagName + "_resource" ) ; String description = tag . getDescription ( ) ; if ( StringUtils . isNotBlank ( description ) ) { markupDocBuilder . paragraph ( description ) ; } operationsGroupedByTag . get ( tagName ) . forEach ( operation -> buildOperation ( markupDocBuilder , operation , config ) ) ; } ) ; } else if ( config . getPathsGroupedBy ( ) == GroupBy . REGEX ) { Validate . notNull ( config . getHeaderPattern ( ) , "Header regex pattern must not be empty when operations are grouped using regex" ) ; Pattern headerPattern = config . getHeaderPattern ( ) ; Multimap < String , PathOperation > operationsGroupedByRegex = RegexUtils . groupOperationsByRegex ( pathOperations , headerPattern ) ; Set < String > keys = operationsGroupedByRegex . keySet ( ) ; String [ ] sortedHeaders = RegexUtils . toSortedArray ( keys ) ; for ( String header : sortedHeaders ) { markupDocBuilder . sectionTitleWithAnchorLevel2 ( WordUtils . capitalize ( header ) , header + "_resource" ) ; operationsGroupedByRegex . get ( header ) . forEach ( operation -> buildOperation ( markupDocBuilder , operation , config ) ) ; } } } } | Builds the paths section . Groups the paths either as - is by tags or using regex . |
10,777 | private void buildPathsTitle ( MarkupDocBuilder markupDocBuilder ) { if ( config . getPathsGroupedBy ( ) == GroupBy . AS_IS ) { buildPathsTitle ( markupDocBuilder , labels . getLabel ( Labels . PATHS ) ) ; } else if ( config . getPathsGroupedBy ( ) == GroupBy . REGEX ) { buildPathsTitle ( markupDocBuilder , labels . getLabel ( Labels . OPERATIONS ) ) ; } else { buildPathsTitle ( markupDocBuilder , labels . getLabel ( Labels . RESOURCES ) ) ; } } | Builds the path title depending on the operationsGroupedBy configuration setting . |
10,778 | private void applyPathsDocumentExtension ( Context context ) { extensionRegistry . getPathsDocumentExtensions ( ) . forEach ( extension -> extension . apply ( context ) ) ; } | Apply extension context to all OperationsContentExtension . |
10,779 | private void buildOperation ( MarkupDocBuilder markupDocBuilder , PathOperation operation , Swagger2MarkupConfig config ) { if ( config . isSeparatedOperationsEnabled ( ) ) { MarkupDocBuilder pathDocBuilder = copyMarkupDocBuilder ( markupDocBuilder ) ; applyPathOperationComponent ( pathDocBuilder , operation ) ; java . nio . file . Path operationFile = context . getOutputPath ( ) . resolve ( operationDocumentNameResolver . apply ( operation ) ) ; pathDocBuilder . writeToFileWithoutExtension ( operationFile , StandardCharsets . UTF_8 ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Separate operation file produced : '{}'" , operationFile ) ; } buildOperationRef ( markupDocBuilder , operation ) ; } else { applyPathOperationComponent ( markupDocBuilder , operation ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Operation processed : '{}' (normalized id = '{}')" , operation , normalizeName ( operation . getId ( ) ) ) ; } } | Builds a path operation depending on generation mode . |
10,780 | private void applyPathOperationComponent ( MarkupDocBuilder markupDocBuilder , PathOperation operation ) { if ( operation != null ) { pathOperationComponent . apply ( markupDocBuilder , PathOperationComponent . parameters ( operation ) ) ; } } | Builds a path operation . |
10,781 | private void buildOperationRef ( MarkupDocBuilder markupDocBuilder , PathOperation operation ) { buildOperationTitle ( markupDocBuilder , crossReference ( markupDocBuilder , operationDocumentResolverDefault . apply ( operation ) , operation . getId ( ) , operation . getTitle ( ) ) , "ref-" + operation . getId ( ) ) ; } | Builds a cross - reference to a separated operation file |
10,782 | public static String [ ] toSortedArray ( Set < String > groups ) { String [ ] sortedArray = groups . toArray ( new String [ groups . size ( ) ] ) ; Arrays . sort ( sortedArray ) ; return sortedArray ; } | Alphabetically sort the list of groups |
10,783 | public static Multimap < String , PathOperation > groupOperationsByRegex ( List < PathOperation > allOperations , Pattern headerPattern ) { Multimap < String , PathOperation > operationsGroupedByRegex = LinkedHashMultimap . create ( ) ; for ( PathOperation operation : allOperations ) { String path = operation . getPath ( ) ; Matcher m = headerPattern . matcher ( path ) ; if ( m . matches ( ) && m . group ( 1 ) != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Added path operation '{}' to header '{}'" , operation , m . group ( 1 ) ) ; } operationsGroupedByRegex . put ( m . group ( 1 ) , operation ) ; } else { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "Operation '{}' does not match regex '{}' and will not be included in output" , operation , headerPattern . toString ( ) ) ; } } } return operationsGroupedByRegex ; } | Groups the operations by regex group . The key of the Multimap is the group name . The value of the Multimap is a PathOperation |
10,784 | public MarkupDocBuilder apply ( MarkupDocBuilder markupDocBuilder , SecurityDocument . Parameters params ) { Map < String , SecuritySchemeDefinition > definitions = params . securitySchemeDefinitions ; if ( MapUtils . isNotEmpty ( definitions ) ) { applySecurityDocumentExtension ( new Context ( Position . DOCUMENT_BEFORE , markupDocBuilder ) ) ; buildSecurityTitle ( markupDocBuilder , labels . getLabel ( SECURITY ) ) ; applySecurityDocumentExtension ( new Context ( Position . DOCUMENT_BEGIN , markupDocBuilder ) ) ; buildSecuritySchemeDefinitionsSection ( markupDocBuilder , definitions ) ; applySecurityDocumentExtension ( new Context ( Position . DOCUMENT_END , markupDocBuilder ) ) ; applySecurityDocumentExtension ( new Context ( Position . DOCUMENT_AFTER , markupDocBuilder ) ) ; } return markupDocBuilder ; } | Builds the security MarkupDocument . |
10,785 | private void applySecurityDocumentExtension ( Context context ) { extensionRegistry . getSecurityDocumentExtensions ( ) . forEach ( extension -> extension . apply ( context ) ) ; } | Apply extension context to all SecurityContentExtension |
10,786 | public static URI uriParent ( URI uri ) { return uri . getPath ( ) . endsWith ( "/" ) ? uri . resolve ( ".." ) : uri . resolve ( "." ) ; } | Return URI parent |
10,787 | public static URI convertUriWithoutSchemeToFileScheme ( URI uri ) { if ( uri . getScheme ( ) == null ) { return Paths . get ( uri . getPath ( ) ) . toUri ( ) ; } return uri ; } | Convert an URI without a scheme to a file scheme . |
10,788 | public static URI create ( String input ) { if ( isFile ( input ) || isURL ( input ) ) { return URI . create ( input ) ; } else { return Paths . get ( input ) . toUri ( ) ; } } | Creates a URI from a String representation of a URI or a Path . |
10,789 | public static Builder from ( URI swaggerUri ) { Validate . notNull ( swaggerUri , "swaggerUri must not be null" ) ; String scheme = swaggerUri . getScheme ( ) ; if ( scheme != null && swaggerUri . getScheme ( ) . startsWith ( "http" ) ) { try { return from ( swaggerUri . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( "Failed to convert URI to URL" , e ) ; } } else if ( scheme != null && swaggerUri . getScheme ( ) . startsWith ( "file" ) ) { return from ( Paths . get ( swaggerUri ) ) ; } else { return from ( URIUtils . convertUriWithoutSchemeToFileScheme ( swaggerUri ) ) ; } } | Creates a Swagger2MarkupConverter . Builder from a URI . |
10,790 | public static Builder from ( Path swaggerPath ) { Validate . notNull ( swaggerPath , "swaggerPath must not be null" ) ; if ( Files . notExists ( swaggerPath ) ) { throw new IllegalArgumentException ( String . format ( "swaggerPath does not exist: %s" , swaggerPath ) ) ; } try { if ( Files . isHidden ( swaggerPath ) ) { throw new IllegalArgumentException ( "swaggerPath must not be a hidden file" ) ; } } catch ( IOException e ) { throw new RuntimeException ( "Failed to check if swaggerPath is a hidden file" , e ) ; } return new Builder ( swaggerPath ) ; } | Creates a Swagger2MarkupConverter . Builder using a local Path . |
10,791 | public static Builder from ( String swaggerString ) { Validate . notEmpty ( swaggerString , "swaggerString must not be null" ) ; return from ( new StringReader ( swaggerString ) ) ; } | Creates a Swagger2MarkupConverter . Builder from a given Swagger YAML or JSON String . |
10,792 | public static Builder from ( Reader swaggerReader ) { Validate . notNull ( swaggerReader , "swaggerReader must not be null" ) ; Swagger swagger ; try { swagger = new SwaggerParser ( ) . parse ( IOUtils . toString ( swaggerReader ) ) ; } catch ( IOException e ) { throw new RuntimeException ( "Swagger source can not be parsed" , e ) ; } if ( swagger == null ) throw new IllegalArgumentException ( "Swagger source is in a wrong format" ) ; return new Builder ( swagger ) ; } | Creates a Swagger2MarkupConverter . Builder from a given Swagger YAML or JSON reader . |
10,793 | public static Map < String , Object > generateResponseExampleMap ( boolean generateMissingExamples , PathOperation operation , Map < String , Model > definitions , DocumentResolver definitionDocumentResolver , MarkupDocBuilder markupDocBuilder ) { Map < String , Object > examples = new LinkedHashMap < > ( ) ; Map < String , Response > responses = operation . getOperation ( ) . getResponses ( ) ; if ( responses != null ) for ( Map . Entry < String , Response > responseEntry : responses . entrySet ( ) ) { Response response = responseEntry . getValue ( ) ; Object example = response . getExamples ( ) ; if ( example == null ) { Model model = response . getResponseSchema ( ) ; if ( model != null ) { Property schema = new PropertyModelConverter ( ) . modelToProperty ( model ) ; if ( schema != null ) { example = schema . getExample ( ) ; if ( example == null && schema instanceof RefProperty ) { String simpleRef = ( ( RefProperty ) schema ) . getSimpleRef ( ) ; example = generateExampleForRefModel ( generateMissingExamples , simpleRef , definitions , definitionDocumentResolver , markupDocBuilder , new HashMap < > ( ) ) ; } if ( example == null && schema instanceof ArrayProperty && generateMissingExamples ) { example = generateExampleForArrayProperty ( ( ArrayProperty ) schema , definitions , definitionDocumentResolver , markupDocBuilder , new HashMap < > ( ) ) ; } if ( example == null && schema instanceof ObjectProperty && generateMissingExamples ) { example = exampleMapForProperties ( ( ( ObjectProperty ) schema ) . getProperties ( ) , definitions , definitionDocumentResolver , markupDocBuilder , new HashMap < > ( ) ) ; } if ( example == null && generateMissingExamples ) { example = PropertyAdapter . generateExample ( schema , markupDocBuilder ) ; } } } } if ( example != null ) examples . put ( responseEntry . getKey ( ) , example ) ; } return examples ; } | Generates a Map of response examples |
10,794 | private static Object getExamplesFromBodyParameter ( Parameter parameter ) { Object examples = ( ( BodyParameter ) parameter ) . getExamples ( ) ; if ( examples == null ) { examples = parameter . getVendorExtensions ( ) . get ( "x-examples" ) ; } return examples ; } | Retrieves example payloads for body parameter either from examples or from vendor extensions . |
10,795 | private static String encodeExampleForUrl ( Object example ) { try { return URLEncoder . encode ( String . valueOf ( example ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException exception ) { throw new RuntimeException ( exception ) ; } } | Encodes an example value for use in an URL |
10,796 | private static Object generateExampleForRefModel ( boolean generateMissingExamples , String simpleRef , Map < String , Model > definitions , DocumentResolver definitionDocumentResolver , MarkupDocBuilder markupDocBuilder , Map < String , Integer > refStack ) { Model model = definitions . get ( simpleRef ) ; Object example = null ; if ( model != null ) { example = model . getExample ( ) ; if ( example == null && generateMissingExamples ) { if ( ! refStack . containsKey ( simpleRef ) ) { refStack . put ( simpleRef , 1 ) ; } else { refStack . put ( simpleRef , refStack . get ( simpleRef ) + 1 ) ; } if ( refStack . get ( simpleRef ) <= MAX_RECURSION_TO_DISPLAY ) { if ( model instanceof ComposedModel ) { example = exampleMapForProperties ( ( ( ObjectType ) ModelUtils . getType ( model , definitions , definitionDocumentResolver ) ) . getProperties ( ) , definitions , definitionDocumentResolver , markupDocBuilder , new HashMap < > ( ) ) ; } else { example = exampleMapForProperties ( model . getProperties ( ) , definitions , definitionDocumentResolver , markupDocBuilder , refStack ) ; } } else { return "..." ; } refStack . put ( simpleRef , refStack . get ( simpleRef ) - 1 ) ; } } return example ; } | Generates an example object from a simple reference |
10,797 | private static Map < String , Object > exampleMapForProperties ( Map < String , Property > properties , Map < String , Model > definitions , DocumentResolver definitionDocumentResolver , MarkupDocBuilder markupDocBuilder , Map < String , Integer > refStack ) { Map < String , Object > exampleMap = new LinkedHashMap < > ( ) ; if ( properties != null ) { for ( Map . Entry < String , Property > property : properties . entrySet ( ) ) { Object exampleObject = property . getValue ( ) . getExample ( ) ; if ( exampleObject == null ) { if ( property . getValue ( ) instanceof RefProperty ) { exampleObject = generateExampleForRefModel ( true , ( ( RefProperty ) property . getValue ( ) ) . getSimpleRef ( ) , definitions , definitionDocumentResolver , markupDocBuilder , refStack ) ; } else if ( property . getValue ( ) instanceof ArrayProperty ) { exampleObject = generateExampleForArrayProperty ( ( ArrayProperty ) property . getValue ( ) , definitions , definitionDocumentResolver , markupDocBuilder , refStack ) ; } else if ( property . getValue ( ) instanceof MapProperty ) { exampleObject = generateExampleForMapProperty ( ( MapProperty ) property . getValue ( ) , markupDocBuilder ) ; } if ( exampleObject == null ) { Property valueProperty = property . getValue ( ) ; exampleObject = PropertyAdapter . generateExample ( valueProperty , markupDocBuilder ) ; } } exampleMap . put ( property . getKey ( ) , exampleObject ) ; } } return exampleMap ; } | Generates a map of examples from a map of properties . If defined examples are found those are used . Otherwise examples are generated from the type . |
10,798 | private static Object [ ] generateExampleForArrayProperty ( ArrayProperty value , Map < String , Model > definitions , DocumentResolver definitionDocumentResolver , MarkupDocBuilder markupDocBuilder , Map < String , Integer > refStack ) { Property property = value . getItems ( ) ; return getExample ( property , definitions , definitionDocumentResolver , markupDocBuilder , refStack ) ; } | Generates examples from an ArrayProperty |
10,799 | private static Object [ ] getExample ( Property property , Map < String , Model > definitions , DocumentResolver definitionDocumentResolver , MarkupDocBuilder markupDocBuilder , Map < String , Integer > refStack ) { if ( property . getExample ( ) != null ) { return new Object [ ] { property . getExample ( ) } ; } else if ( property instanceof ArrayProperty ) { return new Object [ ] { generateExampleForArrayProperty ( ( ArrayProperty ) property , definitions , definitionDocumentResolver , markupDocBuilder , refStack ) } ; } else if ( property instanceof RefProperty ) { return new Object [ ] { generateExampleForRefModel ( true , ( ( RefProperty ) property ) . getSimpleRef ( ) , definitions , definitionDocumentResolver , markupDocBuilder , refStack ) } ; } else { return new Object [ ] { PropertyAdapter . generateExample ( property , markupDocBuilder ) } ; } } | Get example from a property |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.