idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
26,000 | public static AtomContent forEntry ( XmlNamespaceDictionary namespaceDictionary , Object entry ) { return new AtomContent ( namespaceDictionary , entry , true ) ; } | Returns a new instance of HTTP content for an Atom entry . |
26,001 | public static AtomContent forFeed ( XmlNamespaceDictionary namespaceDictionary , Object feed ) { return new AtomContent ( namespaceDictionary , feed , false ) ; } | Returns a new instance of HTTP content for an Atom feed . |
26,002 | public HttpMediaType setParameter ( String name , String value ) { if ( value == null ) { removeParameter ( name ) ; return this ; } Preconditions . checkArgument ( TOKEN_REGEX . matcher ( name ) . matches ( ) , "Name contains reserved characters" ) ; cachedBuildResult = null ; parameters . put ( name . toLowerCase ( Locale . US ) , value ) ; return this ; } | Sets the media parameter to the specified value . |
26,003 | public HttpMediaType removeParameter ( String name ) { cachedBuildResult = null ; parameters . remove ( name . toLowerCase ( Locale . US ) ) ; return this ; } | Removes the specified media parameter . |
26,004 | public String build ( ) { if ( cachedBuildResult != null ) { return cachedBuildResult ; } StringBuilder str = new StringBuilder ( ) ; str . append ( type ) ; str . append ( '/' ) ; str . append ( subType ) ; if ( parameters != null ) { for ( Entry < String , String > entry : parameters . entrySet ( ) ) { String value = entry . getValue ( ) ; str . append ( "; " ) ; str . append ( entry . getKey ( ) ) ; str . append ( "=" ) ; str . append ( ! matchesToken ( value ) ? quoteString ( value ) : value ) ; } } cachedBuildResult = str . toString ( ) ; return cachedBuildResult ; } | Builds the full media type string which can be passed in the Content - Type header . |
26,005 | public HttpMediaType setCharsetParameter ( Charset charset ) { setParameter ( "charset" , charset == null ? null : charset . name ( ) ) ; return this ; } | Sets the charset parameter of the media type . |
26,006 | public static String expand ( String baseUrl , String uriTemplate , Object parameters , boolean addUnusedParamsAsQueryParams ) { String pathUri ; if ( uriTemplate . startsWith ( "/" ) ) { GenericUrl url = new GenericUrl ( baseUrl ) ; url . setRawPath ( null ) ; pathUri = url . build ( ) + uriTemplate ; } else if ( uriTemplate . startsWith ( "http://" ) || uriTemplate . startsWith ( "https://" ) ) { pathUri = uriTemplate ; } else { pathUri = baseUrl + uriTemplate ; } return expand ( pathUri , parameters , addUnusedParamsAsQueryParams ) ; } | Expands templates in a URI template that is relative to a base URL . |
26,007 | public static StringBuilder computeMessageBuffer ( HttpResponse response ) { StringBuilder builder = new StringBuilder ( ) ; int statusCode = response . getStatusCode ( ) ; if ( statusCode != 0 ) { builder . append ( statusCode ) ; } String statusMessage = response . getStatusMessage ( ) ; if ( statusMessage != null ) { if ( statusCode != 0 ) { builder . append ( ' ' ) ; } builder . append ( statusMessage ) ; } return builder ; } | Returns an exception message string builder to use for the given HTTP response . |
26,008 | public static boolean next ( Sleeper sleeper , BackOff backOff ) throws InterruptedException , IOException { long backOffTime = backOff . nextBackOffMillis ( ) ; if ( backOffTime == BackOff . STOP ) { return false ; } sleeper . sleep ( backOffTime ) ; return true ; } | Runs the next iteration of the back - off policy and returns whether to continue to retry the operation . |
26,009 | public MultipartContent setContentParts ( Collection < ? extends HttpContent > contentParts ) { this . parts = new ArrayList < Part > ( contentParts . size ( ) ) ; for ( HttpContent contentPart : contentParts ) { addPart ( new Part ( contentPart ) ) ; } return this ; } | Sets the HTTP content parts of the HTTP multipart request where each part is assumed to have no HTTP headers and no encoding . |
26,010 | private static String toStringValue ( Object headerValue ) { return headerValue instanceof Enum < ? > ? FieldInfo . of ( ( Enum < ? > ) headerValue ) . getName ( ) : headerValue . toString ( ) ; } | Returns the string header value for the given header value as an object . |
26,011 | private < T > T getFirstHeaderValue ( List < T > internalValue ) { return internalValue == null ? null : internalValue . get ( 0 ) ; } | Returns the first header value based on the given internal list value . |
26,012 | private < T > List < T > getAsList ( T passedValue ) { if ( passedValue == null ) { return null ; } List < T > result = new ArrayList < T > ( ) ; result . add ( passedValue ) ; return result ; } | Returns the list value to use for the given parameter passed to the setter method . |
26,013 | public String getFirstHeaderStringValue ( String name ) { Object value = get ( name . toLowerCase ( Locale . US ) ) ; if ( value == null ) { return null ; } Class < ? extends Object > valueClass = value . getClass ( ) ; if ( value instanceof Iterable < ? > || valueClass . isArray ( ) ) { for ( Object repeatedValue : Types . iterableOf ( value ) ) { return toStringValue ( repeatedValue ) ; } } return toStringValue ( value ) ; } | Returns the first header string value for the given header name . |
26,014 | public List < String > getHeaderStringValues ( String name ) { Object value = get ( name . toLowerCase ( Locale . US ) ) ; if ( value == null ) { return Collections . emptyList ( ) ; } Class < ? extends Object > valueClass = value . getClass ( ) ; if ( value instanceof Iterable < ? > || valueClass . isArray ( ) ) { List < String > values = new ArrayList < String > ( ) ; for ( Object repeatedValue : Types . iterableOf ( value ) ) { values . add ( toStringValue ( repeatedValue ) ) ; } return Collections . unmodifiableList ( values ) ; } return Collections . singletonList ( toStringValue ( value ) ) ; } | Returns an unmodifiable list of the header string values for the given header name . |
26,015 | void parseHeader ( String headerName , String headerValue , ParseHeaderState state ) { List < Type > context = state . context ; ClassInfo classInfo = state . classInfo ; ArrayValueMap arrayValueMap = state . arrayValueMap ; StringBuilder logger = state . logger ; if ( logger != null ) { logger . append ( headerName + ": " + headerValue ) . append ( StringUtils . LINE_SEPARATOR ) ; } FieldInfo fieldInfo = classInfo . getFieldInfo ( headerName ) ; if ( fieldInfo != null ) { Type type = Data . resolveWildcardTypeOrTypeVariable ( context , fieldInfo . getGenericType ( ) ) ; if ( Types . isArray ( type ) ) { Class < ? > rawArrayComponentType = Types . getRawArrayComponentType ( context , Types . getArrayComponentType ( type ) ) ; arrayValueMap . put ( fieldInfo . getField ( ) , rawArrayComponentType , parseValue ( rawArrayComponentType , context , headerValue ) ) ; } else if ( Types . isAssignableToOrFrom ( Types . getRawArrayComponentType ( context , type ) , Iterable . class ) ) { @ SuppressWarnings ( "unchecked" ) Collection < Object > collection = ( Collection < Object > ) fieldInfo . getValue ( this ) ; if ( collection == null ) { collection = Data . newCollectionInstance ( type ) ; fieldInfo . setValue ( this , collection ) ; } Type subFieldType = type == Object . class ? null : Types . getIterableParameter ( type ) ; collection . add ( parseValue ( subFieldType , context , headerValue ) ) ; } else { fieldInfo . setValue ( this , parseValue ( type , context , headerValue ) ) ; } } else { @ SuppressWarnings ( "unchecked" ) ArrayList < String > listValue = ( ArrayList < String > ) this . get ( headerName ) ; if ( listValue == null ) { listValue = new ArrayList < String > ( ) ; this . set ( headerName , listValue ) ; } listValue . add ( headerValue ) ; } } | Parses the specified case - insensitive header pair into this HttpHeaders instance . |
26,016 | public final String buildAuthority ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( Preconditions . checkNotNull ( scheme ) ) ; buf . append ( "://" ) ; if ( userInfo != null ) { buf . append ( CharEscapers . escapeUriUserInfo ( userInfo ) ) . append ( '@' ) ; } buf . append ( Preconditions . checkNotNull ( host ) ) ; int port = this . port ; if ( port != - 1 ) { buf . append ( ':' ) . append ( port ) ; } return buf . toString ( ) ; } | Constructs the portion of the URL containing the scheme host and port . |
26,017 | public final String buildRelativeUrl ( ) { StringBuilder buf = new StringBuilder ( ) ; if ( pathParts != null ) { appendRawPathFromParts ( buf ) ; } addQueryParams ( entrySet ( ) , buf ) ; String fragment = this . fragment ; if ( fragment != null ) { buf . append ( '#' ) . append ( URI_FRAGMENT_ESCAPER . escape ( fragment ) ) ; } return buf . toString ( ) ; } | Constructs the portion of the URL beginning at the rooted path . |
26,018 | public Object getFirst ( String name ) { Object value = get ( name ) ; if ( value instanceof Collection < ? > ) { @ SuppressWarnings ( "unchecked" ) Collection < Object > collectionValue = ( Collection < Object > ) value ; Iterator < Object > iterator = collectionValue . iterator ( ) ; return iterator . hasNext ( ) ? iterator . next ( ) : null ; } return value ; } | Returns the first query parameter value for the given query parameter name . |
26,019 | public Collection < Object > getAll ( String name ) { Object value = get ( name ) ; if ( value == null ) { return Collections . emptySet ( ) ; } if ( value instanceof Collection < ? > ) { @ SuppressWarnings ( "unchecked" ) Collection < Object > collectionValue = ( Collection < Object > ) value ; return Collections . unmodifiableCollection ( collectionValue ) ; } return Collections . singleton ( value ) ; } | Returns all query parameter values for the given query parameter name . |
26,020 | public static List < String > toPathParts ( String encodedPath ) { if ( encodedPath == null || encodedPath . length ( ) == 0 ) { return null ; } List < String > result = new ArrayList < String > ( ) ; int cur = 0 ; boolean notDone = true ; while ( notDone ) { int slash = encodedPath . indexOf ( '/' , cur ) ; notDone = slash != - 1 ; String sub ; if ( notDone ) { sub = encodedPath . substring ( cur , slash ) ; } else { sub = encodedPath . substring ( cur ) ; } result . add ( CharEscapers . decodeUri ( sub ) ) ; cur = slash + 1 ; } return result ; } | Returns the decoded path parts for the given encoded path . |
26,021 | static void addQueryParams ( Set < Entry < String , Object > > entrySet , StringBuilder buf ) { boolean first = true ; for ( Map . Entry < String , Object > nameValueEntry : entrySet ) { Object value = nameValueEntry . getValue ( ) ; if ( value != null ) { String name = CharEscapers . escapeUriQuery ( nameValueEntry . getKey ( ) ) ; if ( value instanceof Collection < ? > ) { Collection < ? > collectionValue = ( Collection < ? > ) value ; for ( Object repeatedValue : collectionValue ) { first = appendParam ( first , buf , name , repeatedValue ) ; } } else { first = appendParam ( first , buf , name , value ) ; } } } } | Adds query parameters from the provided entrySet into the buffer . |
26,022 | private static void parseAttributeOrTextContent ( String stringValue , Field field , Type valueType , List < Type > context , Object destination , GenericXml genericXml , Map < String , Object > destinationMap , String name ) { if ( field != null || genericXml != null || destinationMap != null ) { valueType = field == null ? valueType : field . getGenericType ( ) ; Object value = parseValue ( valueType , context , stringValue ) ; setValue ( value , field , destination , genericXml , destinationMap , name ) ; } } | Parses the string value of an attribute value or text content . |
26,023 | private static void setValue ( Object value , Field field , Object destination , GenericXml genericXml , Map < String , Object > destinationMap , String name ) { if ( field != null ) { FieldInfo . setFieldValue ( field , destination , value ) ; } else if ( genericXml != null ) { genericXml . set ( name , value ) ; } else { destinationMap . put ( name , value ) ; } } | Sets the value of a given field or map entry . |
26,024 | public static void parseElement ( XmlPullParser parser , Object destination , XmlNamespaceDictionary namespaceDictionary , CustomizeParser customizeParser ) throws IOException , XmlPullParserException { ArrayList < Type > context = new ArrayList < Type > ( ) ; if ( destination != null ) { context . add ( destination . getClass ( ) ) ; } parseElementInternal ( parser , context , destination , null , namespaceDictionary , customizeParser ) ; } | Parses an XML element using the given XML pull parser into the given destination object . |
26,025 | private static void parseNamespacesForElement ( XmlPullParser parser , XmlNamespaceDictionary namespaceDictionary ) throws XmlPullParserException { int eventType = parser . getEventType ( ) ; Preconditions . checkState ( eventType == XmlPullParser . START_TAG , "expected start of XML element, but got something else (event type %s)" , eventType ) ; int depth = parser . getDepth ( ) ; int nsStart = parser . getNamespaceCount ( depth - 1 ) ; int nsEnd = parser . getNamespaceCount ( depth ) ; for ( int i = nsStart ; i < nsEnd ; i ++ ) { String namespace = parser . getNamespaceUri ( i ) ; if ( namespaceDictionary . getAliasForUri ( namespace ) == null ) { String prefix = parser . getNamespacePrefix ( i ) ; String originalAlias = prefix == null ? "" : prefix ; String alias = originalAlias ; int suffix = 1 ; while ( namespaceDictionary . getUriForAlias ( alias ) != null ) { suffix ++ ; alias = originalAlias + suffix ; } namespaceDictionary . set ( alias , namespace ) ; } } } | Parses the namespaces declared on the current element into the namespace dictionary . |
26,026 | private JavaClass getSuperclass ( JavaClass javaClass ) { try { return javaClass . getSuperClass ( ) ; } catch ( ClassNotFoundException e ) { bugReporter . reportMissingClass ( e ) ; return null ; } } | Returns the superclass of the specified class . |
26,027 | public synchronized XmlNamespaceDictionary set ( String alias , String uri ) { String previousUri = null ; String previousAlias = null ; if ( uri == null ) { if ( alias != null ) { previousUri = namespaceAliasToUriMap . remove ( alias ) ; } } else if ( alias == null ) { previousAlias = namespaceUriToAliasMap . remove ( uri ) ; } else { previousUri = namespaceAliasToUriMap . put ( Preconditions . checkNotNull ( alias ) , Preconditions . checkNotNull ( uri ) ) ; if ( ! uri . equals ( previousUri ) ) { previousAlias = namespaceUriToAliasMap . put ( uri , alias ) ; } else { previousUri = null ; } } if ( previousUri != null ) { namespaceUriToAliasMap . remove ( previousUri ) ; } if ( previousAlias != null ) { namespaceAliasToUriMap . remove ( previousAlias ) ; } return this ; } | Adds a namespace of the given alias and URI . |
26,028 | String getNamespaceUriForAliasHandlingUnknown ( boolean errorOnUnknown , String alias ) { String result = getUriForAlias ( alias ) ; if ( result == null ) { Preconditions . checkArgument ( ! errorOnUnknown , "unrecognized alias: %s" , alias . length ( ) == 0 ? "(default)" : alias ) ; return "http://unknown/" + alias ; } return result ; } | Returns the namespace URI to use for serialization for a given namespace alias possibly using a predictable made - up namespace URI if the alias is not recognized . |
26,029 | String getNamespaceAliasForUriErrorOnUnknown ( String namespaceUri ) { String result = getAliasForUri ( namespaceUri ) ; Preconditions . checkArgument ( result != null , "invalid XML: no alias declared for namesapce <%s>; " + "work-around by setting XML namepace directly by calling the set method of %s" , namespaceUri , XmlNamespaceDictionary . class . getName ( ) ) ; return result ; } | Returns the namespace alias to use for a given namespace URI throwing an exception if the namespace URI can be found in this dictionary . |
26,030 | public final boolean verifySignature ( PublicKey publicKey ) throws GeneralSecurityException { Signature signatureAlg = null ; String algorithm = getHeader ( ) . getAlgorithm ( ) ; if ( "RS256" . equals ( algorithm ) ) { signatureAlg = SecurityUtils . getSha256WithRsaSignatureAlgorithm ( ) ; } else { return false ; } return SecurityUtils . verify ( signatureAlg , publicKey , signatureBytes , signedContentBytes ) ; } | Verifies the signature of the content . |
26,031 | private static void appendInt ( StringBuilder sb , int num , int numDigits ) { if ( num < 0 ) { sb . append ( '-' ) ; num = - num ; } int x = num ; while ( x > 0 ) { x /= 10 ; numDigits -- ; } for ( int i = 0 ; i < numDigits ; i ++ ) { sb . append ( '0' ) ; } if ( num != 0 ) { sb . append ( num ) ; } } | Appends a zero - padded number to a string builder . |
26,032 | public Section readNextSection ( String titleToLookFor ) throws IOException { String title = null ; StringBuilder keyBuilder = null ; while ( true ) { String line = reader . readLine ( ) ; if ( line == null ) { Preconditions . checkArgument ( title == null , "missing end tag (%s)" , title ) ; return null ; } if ( keyBuilder == null ) { Matcher m = BEGIN_PATTERN . matcher ( line ) ; if ( m . matches ( ) ) { String curTitle = m . group ( 1 ) ; if ( titleToLookFor == null || curTitle . equals ( titleToLookFor ) ) { keyBuilder = new StringBuilder ( ) ; title = curTitle ; } } } else { Matcher m = END_PATTERN . matcher ( line ) ; if ( m . matches ( ) ) { String endTitle = m . group ( 1 ) ; Preconditions . checkArgument ( endTitle . equals ( title ) , "end tag (%s) doesn't match begin tag (%s)" , endTitle , title ) ; return new Section ( title , Base64 . decodeBase64 ( keyBuilder . toString ( ) ) ) ; } keyBuilder . append ( line ) ; } } } | Reads the next section in the PEM file optionally based on a title to look for . |
26,033 | public static Section readFirstSectionAndClose ( Reader reader , String titleToLookFor ) throws IOException { PemReader pemReader = new PemReader ( reader ) ; try { return pemReader . readNextSection ( titleToLookFor ) ; } finally { pemReader . close ( ) ; } } | Reads the first section in the PEM file optionally based on a title to look for and then closes the reader . |
26,034 | public static FieldInfo of ( Enum < ? > enumValue ) { try { FieldInfo result = FieldInfo . of ( enumValue . getClass ( ) . getField ( enumValue . name ( ) ) ) ; Preconditions . checkArgument ( result != null , "enum constant missing @Value or @NullValue annotation: %s" , enumValue ) ; return result ; } catch ( NoSuchFieldException e ) { throw new RuntimeException ( e ) ; } } | Returns the field information for the given enum value . |
26,035 | public static FieldInfo of ( Field field ) { if ( field == null ) { return null ; } synchronized ( CACHE ) { FieldInfo fieldInfo = CACHE . get ( field ) ; boolean isEnumContant = field . isEnumConstant ( ) ; if ( fieldInfo == null && ( isEnumContant || ! Modifier . isStatic ( field . getModifiers ( ) ) ) ) { String fieldName ; if ( isEnumContant ) { Value value = field . getAnnotation ( Value . class ) ; if ( value != null ) { fieldName = value . value ( ) ; } else { NullValue nullValue = field . getAnnotation ( NullValue . class ) ; if ( nullValue != null ) { fieldName = null ; } else { return null ; } } } else { Key key = field . getAnnotation ( Key . class ) ; if ( key == null ) { return null ; } fieldName = key . value ( ) ; field . setAccessible ( true ) ; } if ( "##default" . equals ( fieldName ) ) { fieldName = field . getName ( ) ; } fieldInfo = new FieldInfo ( field , fieldName ) ; CACHE . put ( field , fieldInfo ) ; } return fieldInfo ; } } | Returns the field information for the given field . |
26,036 | private Method [ ] settersMethodForField ( Field field ) { List < Method > methods = new ArrayList < > ( ) ; for ( Method method : field . getDeclaringClass ( ) . getDeclaredMethods ( ) ) { if ( Ascii . toLowerCase ( method . getName ( ) ) . equals ( "set" + Ascii . toLowerCase ( field . getName ( ) ) ) && method . getParameterTypes ( ) . length == 1 ) { methods . add ( method ) ; } } return methods . toArray ( new Method [ 0 ] ) ; } | Creates list of setter methods for a field only in declaring class . |
26,037 | public void setValue ( Object obj , Object value ) { if ( setters . length > 0 ) { for ( Method method : setters ) { if ( value == null || method . getParameterTypes ( ) [ 0 ] . isAssignableFrom ( value . getClass ( ) ) ) { try { method . invoke ( obj , value ) ; return ; } catch ( IllegalAccessException | InvocationTargetException e ) { } } } } setFieldValue ( field , obj , value ) ; } | Sets this field in the given object to the given value using reflection . |
26,038 | public static Object getFieldValue ( Field field , Object obj ) { try { return field . get ( obj ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( e ) ; } } | Returns the value of the given field in the given object using reflection . |
26,039 | public static void setFieldValue ( Field field , Object obj , Object value ) { if ( Modifier . isFinal ( field . getModifiers ( ) ) ) { Object finalValue = getFieldValue ( field , obj ) ; if ( value == null ? finalValue != null : ! value . equals ( finalValue ) ) { throw new IllegalArgumentException ( "expected final value <" + finalValue + "> but was <" + value + "> on " + field . getName ( ) + " field in " + obj . getClass ( ) . getName ( ) ) ; } } else { try { field . set ( obj , value ) ; } catch ( SecurityException e ) { throw new IllegalArgumentException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( e ) ; } } } | Sets the given field in the given object to the given value using reflection . |
26,040 | static void setPermissionsToOwnerOnly ( File file ) throws IOException { try { Method setReadable = File . class . getMethod ( "setReadable" , boolean . class , boolean . class ) ; Method setWritable = File . class . getMethod ( "setWritable" , boolean . class , boolean . class ) ; Method setExecutable = File . class . getMethod ( "setExecutable" , boolean . class , boolean . class ) ; if ( ! ( Boolean ) setReadable . invoke ( file , false , false ) || ! ( Boolean ) setWritable . invoke ( file , false , false ) || ! ( Boolean ) setExecutable . invoke ( file , false , false ) ) { LOGGER . warning ( "unable to change permissions for everybody: " + file ) ; } if ( ! ( Boolean ) setReadable . invoke ( file , true , true ) || ! ( Boolean ) setWritable . invoke ( file , true , true ) || ! ( Boolean ) setExecutable . invoke ( file , true , true ) ) { LOGGER . warning ( "unable to change permissions for owner: " + file ) ; } } catch ( InvocationTargetException exception ) { Throwable cause = exception . getCause ( ) ; Throwables . propagateIfPossible ( cause , IOException . class ) ; throw new RuntimeException ( cause ) ; } catch ( NoSuchMethodException exception ) { LOGGER . warning ( "Unable to set permissions for " + file + ", likely because you are running a version of Java prior to 1.6" ) ; } catch ( SecurityException exception ) { } catch ( IllegalAccessException exception ) { } catch ( IllegalArgumentException exception ) { } } | Attempts to set the given file s permissions such that it can only be read written and executed by the file s owner . |
26,041 | public static boolean isNull ( Object object ) { return object != null && object == NULL_CACHE . get ( object . getClass ( ) ) ; } | Returns whether the given object is the magic object that represents the null value of its class . |
26,042 | public static Map < String , Object > mapOf ( Object data ) { if ( data == null || isNull ( data ) ) { return Collections . emptyMap ( ) ; } if ( data instanceof Map < ? , ? > ) { @ SuppressWarnings ( "unchecked" ) Map < String , Object > result = ( Map < String , Object > ) data ; return result ; } Map < String , Object > result = new DataMap ( data , false ) ; return result ; } | Returns the map to use for the given data that is treated as a map from string key to some value . |
26,043 | public static Object parsePrimitiveValue ( Type type , String stringValue ) { Class < ? > primitiveClass = type instanceof Class < ? > ? ( Class < ? > ) type : null ; if ( type == null || primitiveClass != null ) { if ( primitiveClass == Void . class ) { return null ; } if ( stringValue == null || primitiveClass == null || primitiveClass . isAssignableFrom ( String . class ) ) { return stringValue ; } if ( primitiveClass == Character . class || primitiveClass == char . class ) { if ( stringValue . length ( ) != 1 ) { throw new IllegalArgumentException ( "expected type Character/char but got " + primitiveClass ) ; } return stringValue . charAt ( 0 ) ; } if ( primitiveClass == Boolean . class || primitiveClass == boolean . class ) { return Boolean . valueOf ( stringValue ) ; } if ( primitiveClass == Byte . class || primitiveClass == byte . class ) { return Byte . valueOf ( stringValue ) ; } if ( primitiveClass == Short . class || primitiveClass == short . class ) { return Short . valueOf ( stringValue ) ; } if ( primitiveClass == Integer . class || primitiveClass == int . class ) { return Integer . valueOf ( stringValue ) ; } if ( primitiveClass == Long . class || primitiveClass == long . class ) { return Long . valueOf ( stringValue ) ; } if ( primitiveClass == Float . class || primitiveClass == float . class ) { return Float . valueOf ( stringValue ) ; } if ( primitiveClass == Double . class || primitiveClass == double . class ) { return Double . valueOf ( stringValue ) ; } if ( primitiveClass == DateTime . class ) { return DateTime . parseRfc3339 ( stringValue ) ; } if ( primitiveClass == BigInteger . class ) { return new BigInteger ( stringValue ) ; } if ( primitiveClass == BigDecimal . class ) { return new BigDecimal ( stringValue ) ; } if ( primitiveClass . isEnum ( ) ) { if ( ! ClassInfo . of ( primitiveClass ) . names . contains ( stringValue ) ) { throw new IllegalArgumentException ( String . format ( "given enum name %s not part of " + "enumeration" , stringValue ) ) ; } @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) Enum result = ClassInfo . of ( primitiveClass ) . getFieldInfo ( stringValue ) . < Enum > enumValue ( ) ; return result ; } } throw new IllegalArgumentException ( "expected primitive class, but got: " + type ) ; } | Parses the given string value based on the given primitive type . |
26,044 | public static Collection < Object > newCollectionInstance ( Type type ) { if ( type instanceof WildcardType ) { type = Types . getBound ( ( WildcardType ) type ) ; } if ( type instanceof ParameterizedType ) { type = ( ( ParameterizedType ) type ) . getRawType ( ) ; } Class < ? > collectionClass = type instanceof Class < ? > ? ( Class < ? > ) type : null ; if ( type == null || type instanceof GenericArrayType || collectionClass != null && ( collectionClass . isArray ( ) || collectionClass . isAssignableFrom ( ArrayList . class ) ) ) { return new ArrayList < Object > ( ) ; } if ( collectionClass == null ) { throw new IllegalArgumentException ( "unable to create new instance of type: " + type ) ; } if ( collectionClass . isAssignableFrom ( HashSet . class ) ) { return new HashSet < Object > ( ) ; } if ( collectionClass . isAssignableFrom ( TreeSet . class ) ) { return new TreeSet < Object > ( ) ; } @ SuppressWarnings ( "unchecked" ) Collection < Object > result = ( Collection < Object > ) Types . newInstance ( collectionClass ) ; return result ; } | Returns a new collection instance for the given type . |
26,045 | public static Map < String , Object > newMapInstance ( Class < ? > mapClass ) { if ( mapClass == null || mapClass . isAssignableFrom ( ArrayMap . class ) ) { return ArrayMap . create ( ) ; } if ( mapClass . isAssignableFrom ( TreeMap . class ) ) { return new TreeMap < String , Object > ( ) ; } @ SuppressWarnings ( "unchecked" ) Map < String , Object > result = ( Map < String , Object > ) Types . newInstance ( mapClass ) ; return result ; } | Returns a new instance of a map based on the given field class . |
26,046 | public static void propagateTracingContext ( Span span , HttpHeaders headers ) { Preconditions . checkArgument ( span != null , "span should not be null." ) ; Preconditions . checkArgument ( headers != null , "headers should not be null." ) ; if ( propagationTextFormat != null && propagationTextFormatSetter != null ) { if ( ! span . equals ( BlankSpan . INSTANCE ) ) { propagationTextFormat . inject ( span . getContext ( ) , headers , propagationTextFormatSetter ) ; } } } | Propagate information of current tracing context . This information will be injected into HTTP header . |
26,047 | public HttpRequest buildRequest ( String requestMethod , GenericUrl url , HttpContent content ) throws IOException { HttpRequest request = transport . buildRequest ( ) ; if ( initializer != null ) { initializer . initialize ( request ) ; } request . setRequestMethod ( requestMethod ) ; if ( url != null ) { request . setUrl ( url ) ; } if ( content != null ) { request . setContent ( content ) ; } return request ; } | Builds a request for the given HTTP method URL and content . |
26,048 | public InputStream getContent ( ) throws IOException { if ( ! contentRead ) { InputStream lowLevelResponseContent = this . response . getContent ( ) ; if ( lowLevelResponseContent != null ) { boolean contentProcessed = false ; try { String contentEncoding = this . contentEncoding ; if ( ! returnRawInputStream && contentEncoding != null && contentEncoding . contains ( "gzip" ) ) { lowLevelResponseContent = new GZIPInputStream ( lowLevelResponseContent ) ; } Logger logger = HttpTransport . LOGGER ; if ( loggingEnabled && logger . isLoggable ( Level . CONFIG ) ) { lowLevelResponseContent = new LoggingInputStream ( lowLevelResponseContent , logger , Level . CONFIG , contentLoggingLimit ) ; } content = lowLevelResponseContent ; contentProcessed = true ; } catch ( EOFException e ) { } finally { if ( ! contentProcessed ) { lowLevelResponseContent . close ( ) ; } } } contentRead = true ; } return content ; } | Returns the content of the HTTP response . |
26,049 | public void download ( OutputStream outputStream ) throws IOException { InputStream inputStream = getContent ( ) ; IOUtils . copy ( inputStream , outputStream ) ; } | Writes the content of the HTTP response into the given destination output stream . |
26,050 | public static void loadKeyStore ( KeyStore keyStore , InputStream keyStream , String storePass ) throws IOException , GeneralSecurityException { try { keyStore . load ( keyStream , storePass . toCharArray ( ) ) ; } finally { keyStream . close ( ) ; } } | Loads a key store from a stream . |
26,051 | public static PrivateKey getPrivateKey ( KeyStore keyStore , String alias , String keyPass ) throws GeneralSecurityException { return ( PrivateKey ) keyStore . getKey ( alias , keyPass . toCharArray ( ) ) ; } | Returns the private key from the key store . |
26,052 | public static PrivateKey loadPrivateKeyFromKeyStore ( KeyStore keyStore , InputStream keyStream , String storePass , String alias , String keyPass ) throws IOException , GeneralSecurityException { loadKeyStore ( keyStore , keyStream , storePass ) ; return getPrivateKey ( keyStore , alias , keyPass ) ; } | Retrieves a private key from the specified key store stream and specified key store . |
26,053 | public static byte [ ] sign ( Signature signatureAlgorithm , PrivateKey privateKey , byte [ ] contentBytes ) throws InvalidKeyException , SignatureException { signatureAlgorithm . initSign ( privateKey ) ; signatureAlgorithm . update ( contentBytes ) ; return signatureAlgorithm . sign ( ) ; } | Signs content using a private key . |
26,054 | public static boolean verify ( Signature signatureAlgorithm , PublicKey publicKey , byte [ ] signatureBytes , byte [ ] contentBytes ) throws InvalidKeyException , SignatureException { signatureAlgorithm . initVerify ( publicKey ) ; signatureAlgorithm . update ( contentBytes ) ; try { return signatureAlgorithm . verify ( signatureBytes ) ; } catch ( SignatureException e ) { return false ; } } | Verifies the signature of signed content based on a public key . |
26,055 | public static X509Certificate verify ( Signature signatureAlgorithm , X509TrustManager trustManager , List < String > certChainBase64 , byte [ ] signatureBytes , byte [ ] contentBytes ) throws InvalidKeyException , SignatureException { CertificateFactory certificateFactory ; try { certificateFactory = getX509CertificateFactory ( ) ; } catch ( CertificateException e ) { return null ; } X509Certificate [ ] certificates = new X509Certificate [ certChainBase64 . size ( ) ] ; int currentCert = 0 ; for ( String certBase64 : certChainBase64 ) { byte [ ] certDer = Base64 . decodeBase64 ( certBase64 ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( certDer ) ; try { Certificate cert = certificateFactory . generateCertificate ( bis ) ; if ( ! ( cert instanceof X509Certificate ) ) { return null ; } certificates [ currentCert ++ ] = ( X509Certificate ) cert ; } catch ( CertificateException e ) { return null ; } } try { trustManager . checkServerTrusted ( certificates , "RSA" ) ; } catch ( CertificateException e ) { return null ; } PublicKey pubKey = certificates [ 0 ] . getPublicKey ( ) ; if ( verify ( signatureAlgorithm , pubKey , signatureBytes , contentBytes ) ) { return certificates [ 0 ] ; } return null ; } | Verifies the signature of signed content based on a certificate chain . |
26,056 | public static byte [ ] getBytesUtf8 ( String string ) { if ( string == null ) { return null ; } return string . getBytes ( StandardCharsets . UTF_8 ) ; } | Encodes the given string into a sequence of bytes using the UTF - 8 charset storing the result into a new byte array . |
26,057 | public static void copy ( InputStream inputStream , OutputStream outputStream ) throws IOException { copy ( inputStream , outputStream , true ) ; } | Writes the content provided by the given source input stream into the given destination output stream . |
26,058 | public static void copy ( InputStream inputStream , OutputStream outputStream , boolean closeInputStream ) throws IOException { try { ByteStreams . copy ( inputStream , outputStream ) ; } finally { if ( closeInputStream ) { inputStream . close ( ) ; } } } | Writes the content provided by the given source input stream into the given destination output stream optionally closing the input stream . |
26,059 | public static byte [ ] serialize ( Object value ) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; serialize ( value , out ) ; return out . toByteArray ( ) ; } | Serializes the given object value to a newly allocated byte array . |
26,060 | public static void serialize ( Object value , OutputStream outputStream ) throws IOException { try { new ObjectOutputStream ( outputStream ) . writeObject ( value ) ; } finally { outputStream . close ( ) ; } } | Serializes the given object value to an output stream and close the output stream . |
26,061 | public static < S extends Serializable > S deserialize ( byte [ ] bytes ) throws IOException { if ( bytes == null ) { return null ; } return deserialize ( new ByteArrayInputStream ( bytes ) ) ; } | Deserializes the given byte array into to a newly allocated object . |
26,062 | @ SuppressWarnings ( "unchecked" ) public static < S extends Serializable > S deserialize ( InputStream inputStream ) throws IOException { try { return ( S ) new ObjectInputStream ( inputStream ) . readObject ( ) ; } catch ( ClassNotFoundException exception ) { IOException ioe = new IOException ( "Failed to deserialize object" ) ; ioe . initCause ( exception ) ; throw ioe ; } finally { inputStream . close ( ) ; } } | Deserializes the given input stream into to a newly allocated object and close the input stream . |
26,063 | public final V set ( int index , V value ) { int size = this . size ; if ( index < 0 || index >= size ) { throw new IndexOutOfBoundsException ( ) ; } int valueDataIndex = 1 + ( index << 1 ) ; V result = valueAtDataIndex ( valueDataIndex ) ; this . data [ valueDataIndex ] = value ; return result ; } | Sets the value at the given index overriding any existing value mapping . |
26,064 | public final V put ( K key , V value ) { int index = getIndexOfKey ( key ) ; if ( index == - 1 ) { index = this . size ; } return set ( index , key , value ) ; } | Sets the value for the given key overriding any existing value . |
26,065 | public final void ensureCapacity ( int minCapacity ) { if ( minCapacity < 0 ) { throw new IndexOutOfBoundsException ( ) ; } Object [ ] data = this . data ; int minDataCapacity = minCapacity << 1 ; int oldDataCapacity = data == null ? 0 : data . length ; if ( minDataCapacity > oldDataCapacity ) { int newDataCapacity = oldDataCapacity / 2 * 3 + 1 ; if ( newDataCapacity % 2 != 0 ) { newDataCapacity ++ ; } if ( newDataCapacity < minDataCapacity ) { newDataCapacity = minDataCapacity ; } setDataCapacity ( newDataCapacity ) ; } } | Ensures that the capacity of the internal arrays is at least a given capacity . |
26,066 | public static ClassInfo of ( Class < ? > underlyingClass , boolean ignoreCase ) { if ( underlyingClass == null ) { return null ; } final Map < Class < ? > , ClassInfo > cache = ignoreCase ? CACHE_IGNORE_CASE : CACHE ; ClassInfo classInfo ; synchronized ( cache ) { classInfo = cache . get ( underlyingClass ) ; if ( classInfo == null ) { classInfo = new ClassInfo ( underlyingClass , ignoreCase ) ; cache . put ( underlyingClass , classInfo ) ; } } return classInfo ; } | Returns the class information for the given underlying class . |
26,067 | public void submitTag ( ) { final TagView inputTag = getInputTag ( ) ; if ( inputTag != null && inputTag . isInputAvailable ( ) ) { inputTag . endInput ( ) ; if ( mOnTagChangeListener != null ) { mOnTagChangeListener . onAppend ( TagGroup . this , inputTag . getText ( ) . toString ( ) ) ; } appendInputTag ( ) ; } } | Call this to submit the INPUT tag . |
26,068 | protected TagView getInputTag ( ) { if ( isAppendMode ) { final int inputTagIndex = getChildCount ( ) - 1 ; final TagView inputTag = getTagAt ( inputTagIndex ) ; if ( inputTag != null && inputTag . mState == TagView . STATE_INPUT ) { return inputTag ; } else { return null ; } } else { return null ; } } | Returns the INPUT tag view in this group . |
26,069 | public String getInputTagText ( ) { final TagView inputTagView = getInputTag ( ) ; if ( inputTagView != null ) { return inputTagView . getText ( ) . toString ( ) ; } return null ; } | Returns the INPUT state tag in this group . |
26,070 | protected TagView getLastNormalTagView ( ) { final int lastNormalTagIndex = isAppendMode ? getChildCount ( ) - 2 : getChildCount ( ) - 1 ; TagView lastNormalTagView = getTagAt ( lastNormalTagIndex ) ; return lastNormalTagView ; } | Return the last NORMAL state tag view in this group . |
26,071 | public String [ ] getTags ( ) { final int count = getChildCount ( ) ; final List < String > tagList = new ArrayList < > ( ) ; for ( int i = 0 ; i < count ; i ++ ) { final TagView tagView = getTagAt ( i ) ; if ( tagView . mState == TagView . STATE_NORMAL ) { tagList . add ( tagView . getText ( ) . toString ( ) ) ; } } return tagList . toArray ( new String [ tagList . size ( ) ] ) ; } | Returns the tag array in group except the INPUT tag . |
26,072 | public void setTags ( String ... tags ) { removeAllViews ( ) ; for ( final String tag : tags ) { appendTag ( tag ) ; } if ( isAppendMode ) { appendInputTag ( ) ; } } | Set the tags . It will remove all previous tags first . |
26,073 | protected int getCheckedTagIndex ( ) { final int count = getChildCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { final TagView tag = getTagAt ( i ) ; if ( tag . isChecked ) { return i ; } } return - 1 ; } | Return the checked tag index . |
26,074 | protected void appendInputTag ( String tag ) { final TagView previousInputTag = getInputTag ( ) ; if ( previousInputTag != null ) { throw new IllegalStateException ( "Already has a INPUT tag in group." ) ; } final TagView newInputTag = new TagView ( getContext ( ) , TagView . STATE_INPUT , tag ) ; newInputTag . setOnClickListener ( mInternalTagClickListener ) ; addView ( newInputTag ) ; } | Append a INPUT tag to this group . It will throw an exception if there has a previous INPUT tag . |
26,075 | protected void appendTag ( CharSequence tag ) { final TagView newTag = new TagView ( getContext ( ) , TagView . STATE_NORMAL , tag ) ; newTag . setOnClickListener ( mInternalTagClickListener ) ; addView ( newTag ) ; } | Append tag to this group . |
26,076 | public File getEmbeddingDirectory ( ) { return new File ( getReportDirectory ( ) . getAbsolutePath ( ) , ReportBuilder . BASE_DIRECTORY + File . separatorChar + Configuration . EMBEDDINGS_DIRECTORY ) ; } | Gets directory where the attachments are stored . |
26,077 | public void setTagsToExcludeFromChart ( String ... patterns ) { for ( String pattern : patterns ) { try { tagsToExcludeFromChart . add ( Pattern . compile ( pattern ) ) ; } catch ( PatternSyntaxException e ) { throw new ValidationException ( e ) ; } } } | Stores the regex patterns to be used for filtering out tags from the Tags Overview chart |
26,078 | public void incrementFor ( Status status ) { final int statusCounter = getValueFor ( status ) + 1 ; this . counter . put ( status , statusCounter ) ; size ++ ; if ( finalStatus == Status . PASSED && status != Status . PASSED ) { finalStatus = Status . FAILED ; } } | Increments finalStatus counter by single value . |
26,079 | public void setMetaData ( int jsonFileNo , Configuration configuration ) { for ( Element element : elements ) { element . setMetaData ( this ) ; if ( element . isScenario ( ) ) { scenarios . add ( element ) ; } } reportFileName = calculateReportFileName ( jsonFileNo ) ; featureStatus = calculateFeatureStatus ( ) ; calculateSteps ( ) ; } | Sets additional information and calculates values which should be calculated during object creation . |
26,080 | public void addBuild ( String buildNumber , Reportable reportable ) { buildNumbers = ( String [ ] ) ArrayUtils . add ( buildNumbers , buildNumber ) ; passedFeatures = ArrayUtils . add ( passedFeatures , reportable . getPassedFeatures ( ) ) ; failedFeatures = ArrayUtils . add ( failedFeatures , reportable . getFailedFeatures ( ) ) ; totalFeatures = ArrayUtils . add ( totalFeatures , reportable . getFeatures ( ) ) ; passedScenarios = ArrayUtils . add ( passedScenarios , reportable . getPassedScenarios ( ) ) ; failedScenarios = ArrayUtils . add ( failedScenarios , reportable . getFailedScenarios ( ) ) ; totalScenarios = ArrayUtils . add ( totalScenarios , reportable . getScenarios ( ) ) ; passedSteps = ArrayUtils . add ( passedSteps , reportable . getPassedSteps ( ) ) ; failedSteps = ArrayUtils . add ( failedSteps , reportable . getFailedSteps ( ) ) ; skippedSteps = ArrayUtils . add ( skippedSteps , reportable . getSkippedSteps ( ) ) ; pendingSteps = ArrayUtils . add ( pendingSteps , reportable . getPendingSteps ( ) ) ; undefinedSteps = ArrayUtils . add ( undefinedSteps , reportable . getUndefinedSteps ( ) ) ; totalSteps = ArrayUtils . add ( totalSteps , reportable . getSteps ( ) ) ; durations = ArrayUtils . add ( durations , reportable . getDuration ( ) ) ; applyPatchForFeatures ( ) ; if ( pendingSteps . length < buildNumbers . length ) { fillMissingSteps ( ) ; } if ( durations . length < buildNumbers . length ) { fillMissingDurations ( ) ; } } | Adds build into the trends . |
26,081 | public void limitItems ( int limit ) { buildNumbers = copyLastElements ( buildNumbers , limit ) ; passedFeatures = copyLastElements ( passedFeatures , limit ) ; failedFeatures = copyLastElements ( failedFeatures , limit ) ; totalFeatures = copyLastElements ( totalFeatures , limit ) ; passedScenarios = copyLastElements ( passedScenarios , limit ) ; failedScenarios = copyLastElements ( failedScenarios , limit ) ; totalScenarios = copyLastElements ( totalScenarios , limit ) ; passedSteps = copyLastElements ( passedSteps , limit ) ; failedSteps = copyLastElements ( failedSteps , limit ) ; skippedSteps = copyLastElements ( skippedSteps , limit ) ; pendingSteps = copyLastElements ( pendingSteps , limit ) ; undefinedSteps = copyLastElements ( undefinedSteps , limit ) ; totalSteps = copyLastElements ( totalSteps , limit ) ; durations = copyLastElements ( durations , limit ) ; } | Removes elements that points to the oldest items . Leave trends unchanged if the limit is bigger than current trends length . |
26,082 | private void fillMissingSteps ( ) { passedFeatures = fillMissingArray ( passedFeatures ) ; passedScenarios = fillMissingArray ( passedScenarios ) ; passedSteps = fillMissingArray ( passedSteps ) ; skippedSteps = fillMissingArray ( skippedSteps ) ; pendingSteps = fillMissingArray ( pendingSteps ) ; undefinedSteps = fillMissingArray ( undefinedSteps ) ; } | Since pending and undefined steps were added later there is need to fill missing data for those statuses . |
26,083 | private void fillMissingDurations ( ) { long [ ] extendedArray = new long [ buildNumbers . length ] ; Arrays . fill ( extendedArray , - 1 ) ; System . arraycopy ( durations , 0 , extendedArray , buildNumbers . length - durations . length , durations . length ) ; durations = extendedArray ; } | Since durations were added later there is need to fill missing data for those statuses . |
26,084 | public List < Feature > parseJsonFiles ( List < String > jsonFiles ) { if ( jsonFiles . isEmpty ( ) ) { throw new ValidationException ( "None report file was added!" ) ; } List < Feature > featureResults = new ArrayList < > ( ) ; for ( int i = 0 ; i < jsonFiles . size ( ) ; i ++ ) { String jsonFile = jsonFiles . get ( i ) ; if ( new File ( jsonFile ) . length ( ) == 0 && configuration . containsReducingMethod ( ReducingMethod . SKIP_EMPTY_JSON_FILES ) ) { continue ; } Feature [ ] features = parseForFeature ( jsonFile ) ; LOG . log ( Level . INFO , String . format ( "File '%s' contains %d features" , jsonFile , features . length ) ) ; featureResults . addAll ( Arrays . asList ( features ) ) ; } if ( featureResults . isEmpty ( ) ) { throw new ValidationException ( "Passed files have no features!" ) ; } return featureResults ; } | Parsed passed files and extracts features files . |
26,085 | private Feature [ ] parseForFeature ( String jsonFile ) { try ( Reader reader = new InputStreamReader ( new FileInputStream ( jsonFile ) , StandardCharsets . UTF_8 ) ) { Feature [ ] features = mapper . readValue ( reader , Feature [ ] . class ) ; if ( ArrayUtils . isEmpty ( features ) ) { LOG . log ( Level . INFO , "File '{}' does not contain features" , jsonFile ) ; } return features ; } catch ( JsonMappingException e ) { throw new ValidationException ( String . format ( "File '%s' is not proper Cucumber report!" , jsonFile ) , e ) ; } catch ( IOException e ) { throw new ValidationException ( e ) ; } } | Reads passed file and returns parsed features . |
26,086 | public void parseClassificationsFiles ( List < String > propertiesFiles ) { if ( isNotEmpty ( propertiesFiles ) ) { for ( String propertyFile : propertiesFiles ) { if ( StringUtils . isNotEmpty ( propertyFile ) ) { processClassificationFile ( propertyFile ) ; } } } } | Parses passed properties files for classifications . These classifications within each file get added to the overview - features page as metadata . File and metadata order within the individual files are preserved when classifications are added . |
26,087 | public static String formatAsPercentage ( int value , int total ) { float average = total == 0 ? 0 : 1F * value / total ; return PERCENT_FORMATTER . format ( average ) ; } | Returns value converted to percentage format . |
26,088 | public static String toValidFileName ( String fileName ) { return Long . toString ( ( long ) fileName . hashCode ( ) + Integer . MAX_VALUE ) ; } | Converts characters of passed string and replaces to hash which can be treated as valid file name . |
26,089 | public Reportable generateReports ( ) { Trends trends = null ; try { copyStaticResources ( ) ; createEmbeddingsDirectory ( ) ; reportParser . parseClassificationsFiles ( configuration . getClassificationFiles ( ) ) ; List < Feature > features = reportParser . parseJsonFiles ( jsonFiles ) ; reportResult = new ReportResult ( features , configuration ) ; Reportable reportable = reportResult . getFeatureReport ( ) ; if ( configuration . isTrendsAvailable ( ) ) { trends = updateAndSaveTrends ( reportable ) ; } generatePages ( trends ) ; return reportable ; } catch ( Exception e ) { generateErrorPage ( e ) ; if ( ! wasTrendsFileSaved && configuration . isTrendsAvailable ( ) ) { Reportable reportable = new EmptyReportable ( ) ; updateAndSaveTrends ( reportable ) ; } return null ; } } | Parses provided files and generates the report . When generating process fails report with information about error is provided . |
26,090 | Geometry buffer ( Geometry geometry , double distance , SpatialReference sr , double densify_dist , int max_vertex_in_complete_circle , ProgressTracker progress_tracker ) { if ( geometry == null ) throw new IllegalArgumentException ( ) ; if ( densify_dist < 0 ) throw new IllegalArgumentException ( ) ; if ( geometry . isEmpty ( ) ) return new Polygon ( geometry . getDescription ( ) ) ; Envelope2D env2D = new Envelope2D ( ) ; geometry . queryLooseEnvelope2D ( env2D ) ; if ( distance > 0 ) env2D . inflate ( distance , distance ) ; m_progress_tracker = progress_tracker ; m_original_geom_type = geometry . getType ( ) . value ( ) ; m_geometry = geometry ; m_tolerance = InternalUtils . calculateToleranceFromGeometry ( sr , env2D , true ) ; m_small_tolerance = InternalUtils . calculateToleranceFromGeometry ( null , env2D , true ) ; if ( max_vertex_in_complete_circle <= 0 ) { max_vertex_in_complete_circle = 96 ; } m_spatialReference = sr ; m_distance = distance ; m_abs_distance = Math . abs ( m_distance ) ; m_abs_distance_reversed = m_abs_distance != 0 ? 1.0 / m_abs_distance : 0 ; if ( NumberUtils . isNaN ( densify_dist ) || densify_dist == 0 ) { densify_dist = m_abs_distance * 1e-5 ; } else { if ( densify_dist > m_abs_distance * 0.5 ) densify_dist = m_abs_distance * 0.5 ; } if ( max_vertex_in_complete_circle < 12 ) max_vertex_in_complete_circle = 12 ; double max_dd = Math . abs ( distance ) * ( 1 - Math . cos ( Math . PI / max_vertex_in_complete_circle ) ) ; if ( max_dd > densify_dist ) densify_dist = max_dd ; else { double vertex_count = Math . PI / Math . acos ( 1.0 - densify_dist / Math . abs ( distance ) ) ; if ( vertex_count < ( double ) max_vertex_in_complete_circle - 1.0 ) { max_vertex_in_complete_circle = ( int ) vertex_count ; if ( max_vertex_in_complete_circle < 12 ) { max_vertex_in_complete_circle = 12 ; densify_dist = Math . abs ( distance ) * ( 1 - Math . cos ( Math . PI / max_vertex_in_complete_circle ) ) ; } } } m_densify_dist = densify_dist ; m_max_vertex_in_complete_circle = max_vertex_in_complete_circle ; m_filter_tolerance = Math . min ( m_small_tolerance , densify_dist * 0.25 ) ; m_circle_template_size = calcN_ ( ) ; if ( m_circle_template_size != m_old_circle_template_size ) { m_circle_template . clear ( ) ; m_old_circle_template_size = m_circle_template_size ; } Geometry result_geom = buffer_ ( ) ; m_geometry = null ; return result_geom ; } | Result is always a polygon . For non positive distance and non - areas returns an empty polygon . For points returns circles . |
26,091 | public void setup ( int width , int height , ScanCallback callback ) { width_ = width ; height_ = height ; ySortedEdges_ = null ; activeEdgesTable_ = null ; numEdges_ = 0 ; callback_ = callback ; if ( scanBuffer_ == null ) scanBuffer_ = new int [ 128 * 3 ] ; startAddingEdges ( ) ; } | Sets up the rasterizer . |
26,092 | public final void addTriangle ( double x1 , double y1 , double x2 , double y2 , double x3 , double y3 ) { addEdge ( x1 , y1 , x2 , y2 ) ; addEdge ( x2 , y2 , x3 , y3 ) ; addEdge ( x1 , y1 , x3 , y3 ) ; } | Adds edges of a triangle . |
26,093 | public final void addRing ( double xy [ ] ) { for ( int i = 2 ; i < xy . length ; i += 2 ) { addEdge ( xy [ i - 2 ] , xy [ i - 1 ] , xy [ i ] , xy [ i + 1 ] ) ; } } | Adds edges of the ring to the rasterizer . |
26,094 | public final void startAddingEdges ( ) { if ( numEdges_ > 0 ) { for ( int i = 0 ; i < height_ ; i ++ ) { for ( Edge e = ySortedEdges_ [ i ] ; e != null ; ) { Edge p = e ; e = e . next ; p . next = null ; } ySortedEdges_ [ i ] = null ; } activeEdgesTable_ = null ; } minY_ = height_ ; maxY_ = - 1 ; numEdges_ = 0 ; } | Call before starting the edges . |
26,095 | public final void addEdge ( double x1 , double y1 , double x2 , double y2 ) { if ( y1 == y2 ) return ; int dir = 1 ; if ( y1 > y2 ) { double temp ; temp = x1 ; x1 = x2 ; x2 = temp ; temp = y1 ; y1 = y2 ; y2 = temp ; dir = - 1 ; } if ( y2 < 0 || y1 >= height_ ) return ; if ( x1 < 0 && x2 < 0 ) { x1 = - 1 ; x2 = - 1 ; } else if ( x1 >= width_ && x2 >= width_ ) { x1 = width_ ; x2 = width_ ; } double dxdy = ( x2 - x1 ) / ( y2 - y1 ) ; if ( y2 > height_ ) { y2 = height_ ; x2 = dxdy * ( y2 - y1 ) + x1 ; } if ( y1 < 0 ) { x1 = dxdy * ( 0 - y1 ) + x1 ; y1 = 0 ; } int bigX = Math . max ( width_ + 1 , 0x7fffff ) ; if ( x1 < - 0x7fffff ) { y1 = ( 0 - x1 ) / dxdy + y1 ; x1 = 0 ; } else if ( x1 > bigX ) { y1 = ( width_ - x1 ) / dxdy + y1 ; x1 = width_ ; } if ( x2 < - 0x7fffff ) { y2 = ( 0 - x1 ) / dxdy + y1 ; x2 = 0 ; } else if ( x2 > bigX ) { y2 = ( width_ - x1 ) / dxdy + y1 ; x2 = width_ ; } int ystart = ( int ) y1 ; int yend = ( int ) y2 ; if ( ystart == yend ) return ; Edge e = new Edge ( ) ; e . x = ( long ) ( x1 * 4294967296.0 ) ; e . y = ystart ; e . ymax = yend ; e . dxdy = ( long ) ( dxdy * 4294967296.0 ) ; e . dir = dir ; if ( ySortedEdges_ == null ) { ySortedEdges_ = new Edge [ height_ ] ; } e . next = ySortedEdges_ [ e . y ] ; ySortedEdges_ [ e . y ] = e ; if ( e . y < minY_ ) minY_ = e . y ; if ( e . ymax > maxY_ ) maxY_ = e . ymax ; numEdges_ ++ ; } | Add a single edge . |
26,096 | int intersectionWithEnvelope2D ( Envelope2D clipEnv2D , boolean includeEnvBoundary , double [ ] segParams , double [ ] envelopeDistances ) { Point2D p1 = getStartXY ( ) ; Point2D p2 = getEndXY ( ) ; int modified = clipEnv2D . clipLine ( p1 , p2 , 0 , segParams , envelopeDistances ) ; return modified != 0 ? 2 : 0 ; } | inside clipEnv2D . |
26,097 | int _side ( double ptX , double ptY ) { Point2D v1 = new Point2D ( ptX , ptY ) ; v1 . sub ( getStartXY ( ) ) ; Point2D v2 = new Point2D ( ) ; v2 . sub ( getEndXY ( ) , getStartXY ( ) ) ; double cross = v2 . crossProduct ( v1 ) ; double crossError = 4 * NumberUtils . doubleEps ( ) * ( Math . abs ( v2 . x * v1 . y ) + Math . abs ( v2 . y * v1 . x ) ) ; return cross > crossError ? - 1 : cross < - crossError ? 1 : 0 ; } | of the roundoff error ) |
26,098 | static boolean _isIntersectingHelper ( Line line1 , Line line2 ) { int s11 = line1 . _side ( line2 . m_xStart , line2 . m_yStart ) ; int s12 = line1 . _side ( line2 . m_xEnd , line2 . m_yEnd ) ; if ( s11 < 0 && s12 < 0 || s11 > 0 && s12 > 0 ) return false ; int s21 = line2 . _side ( line1 . m_xStart , line1 . m_yStart ) ; int s22 = line2 . _side ( line1 . m_xEnd , line1 . m_yEnd ) ; if ( s21 < 0 && s22 < 0 || s21 > 0 && s22 > 0 ) return false ; double len1 = line1 . calculateLength2D ( ) ; double len2 = line2 . calculateLength2D ( ) ; if ( len1 > len2 ) { return line1 . _projectionIntersect ( line2 ) ; } else { return line2 . _projectionIntersect ( line1 ) ; } } | Tests if two lines intersect using projection of one line to another . |
26,099 | public static String geometryToJson ( int wkid , Geometry geometry ) { return GeometryEngine . geometryToJson ( wkid > 0 ? SpatialReference . create ( wkid ) : null , geometry ) ; } | Exports the specified geometry instance to it s JSON representation . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.