idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
34,900 | public String nextSearch ( ) { if ( ! triedExact ) { triedExact = true ; return remainder + EXACT_SUFFIX ; } if ( ! triedFull ) { triedFull = true ; if ( remainder . endsWith ( ")/" ) ) { choppedPath = true ; } return remainder ; } if ( ! choppedArgs ) { choppedArgs = true ; int argStart = remainder . indexOf ( '?' ) ; if ( argStart != - 1 ) { remainder = remainder . substring ( 0 , argStart ) ; return remainder ; } } if ( ! choppedPath ) { int lastSlash = remainder . lastIndexOf ( '/' ) ; if ( lastSlash != - 1 ) { if ( lastSlash == ( remainder . length ( ) - 1 ) ) { if ( remainder . endsWith ( ")/" ) ) { String tmp = remainder ; remainder = remainder . substring ( 0 , lastSlash - 1 ) ; choppedPath = true ; return tmp ; } else { remainder = remainder . substring ( 0 , lastSlash ) ; return remainder ; } } if ( ( lastSlash > 0 ) && remainder . charAt ( lastSlash - 1 ) == ')' ) { String tmp = remainder . substring ( 0 , lastSlash + 1 ) ; remainder = remainder . substring ( 0 , lastSlash - 1 ) ; return tmp ; } else { remainder = remainder . substring ( 0 , lastSlash ) ; return remainder ; } } choppedPath = true ; } if ( ! choppedLogin ) { choppedLogin = true ; int lastAt = remainder . lastIndexOf ( '@' ) ; if ( lastAt != - 1 ) { String tmp = remainder ; remainder = remainder . substring ( 0 , lastAt ) ; return tmp ; } } if ( ! choppedPort ) { choppedPort = true ; int lastColon = remainder . lastIndexOf ( ':' ) ; if ( lastColon != - 1 ) { return remainder ; } } int lastComma = remainder . lastIndexOf ( ',' ) ; if ( lastComma == - 1 ) { return null ; } remainder = remainder . substring ( 0 , lastComma ) ; return remainder ; } | update internal state and return the next smaller search string for the url |
34,901 | public void afterPropertiesSet ( ) throws Exception { if ( cdxSource == null ) { cdxSource = zipnumSource ; } cdxLineFactory = new StandardCDXLineFactory ( cdxFormat ) ; if ( defaultParams == null ) { defaultParams = new ZipNumParams ( maxPageSize , maxPageSize , 0 , false ) ; } super . afterPropertiesSet ( ) ; } | protected FieldSplitFormat publicCdxFields ; |
34,902 | public final void setDate ( final Date date ) { this . date = ( Date ) date . clone ( ) ; dateStr = ArchiveUtils . get14DigitDate ( date ) ; } | set internal structure using Date argument |
34,903 | public static Date dateStrToDate ( final String dateStr ) { String paddedDateStr = padStartDateStr ( dateStr ) ; try { return ArchiveUtils . parse14DigitDate ( paddedDateStr ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; return new Date ( ( long ) SSE_YEAR_LOWER_LIMIT * 1000 ) ; } } | cleanup the dateStr argument assuming earliest values and return a GMT calendar set to the time described by the dateStr . |
34,904 | public static String padEndDateStr ( String timestamp ) { return boundTimestamp ( padDigits ( timestamp , LOWER_TIMESTAMP_LIMIT , UPPER_TIMESTAMP_LIMIT , UPPER_TIMESTAMP_LIMIT ) ) ; } | clean up timestamp argument assuming latest possible values for missing or bogus digits . |
34,905 | public static String padStartDateStr ( String timestamp ) { return boundTimestamp ( padDigits ( timestamp , LOWER_TIMESTAMP_LIMIT , UPPER_TIMESTAMP_LIMIT , LOWER_TIMESTAMP_LIMIT ) ) ; } | clean up timestamp argument assuming earliest possible values for missing or bogus digits . |
34,906 | public String [ ] nameToUrls ( final String name ) throws IOException { NameValuePair [ ] args = { new NameValuePair ( ResourceFileLocationDBServlet . OPERATION_ARGUMENT , ResourceFileLocationDBServlet . LOOKUP_OPERATION ) , new NameValuePair ( ResourceFileLocationDBServlet . NAME_ARGUMENT , name ) } ; String locations = doGetMethod ( args ) ; if ( locations != null ) { return locations . split ( "\n" ) ; } return null ; } | return an array of String URLs for all known locations of the file in the DB . |
34,907 | public void addNameUrl ( final String name , final String url ) throws IOException { doPostMethod ( ResourceFileLocationDBServlet . ADD_OPERATION , name , url ) ; } | add an Url location for an arcName unless it already exists |
34,908 | public void removeNameUrl ( final String name , final String url ) throws IOException { doPostMethod ( ResourceFileLocationDBServlet . REMOVE_OPERATION , name , url ) ; } | remove a single url location for a name if it exists |
34,909 | public void parseRange ( ) throws RangeNotSatisfiableException , IOException { if ( requestedRanges . length > 1 ) { throw new RangeNotSatisfiableException ( origResource , requestedRanges , "Multiple ranges are not supported yet" ) ; } final long [ ] firstRange = requestedRanges [ 0 ] ; long start = firstRange [ 0 ] ; long stop = firstRange [ 1 ] ; long [ ] availRange = availableRange ( ) ; if ( availRange == null ) { throw new RangeNotSatisfiableException ( origResource , requestedRanges , "available range cannot be determined" ) ; } if ( start < 0 ) { start = availRange [ 2 ] + start ; stop = availRange [ 2 ] ; } if ( stop < 0 ) { stop = availRange [ 2 ] ; } if ( start < availRange [ 0 ] || stop > availRange [ 1 ] ) { throw new RangeNotSatisfiableException ( origResource , requestedRanges , "requested range is not available in this capture" ) ; } if ( start > availRange [ 0 ] ) { origResource . skip ( start - availRange [ 0 ] ) ; } outputLength = stop - start ; setInputStream ( ByteStreams . limit ( origResource , outputLength ) ) ; httpHeaders = new HashMap < String , String > ( ) ; httpHeaders . putAll ( origResource . getHttpHeaders ( ) ) ; String contentRange = String . format ( "bytes %d-%d/%d" , start , stop - 1 , availRange [ 2 ] ) ; HttpHeaderOperation . replaceHeader ( httpHeaders , HttpHeaderOperation . HTTP_CONTENT_RANGE_HEADER , contentRange ) ; HttpHeaderOperation . replaceHeader ( httpHeaders , HttpHeaderOperation . HTTP_LENGTH_HEADER , Long . toString ( stop - start ) ) ; } | Prepare response for requested range . |
34,910 | protected long [ ] availableRange ( ) { Map < String , String > respHeaders = origResource . getHttpHeaders ( ) ; long [ ] contentRange = HttpHeaderOperation . getContentRange ( respHeaders ) ; long availStart , availStop , contentLength ; if ( contentRange == null ) { String clen = HttpHeaderOperation . getContentLength ( respHeaders ) ; if ( clen != null ) { try { contentLength = Long . parseLong ( clen ) ; } catch ( NumberFormatException ex ) { return null ; } } else { return null ; } availStart = 0 ; availStop = contentLength ; } else { if ( contentRange [ 0 ] < 0 ) { return null ; } availStart = contentRange [ 0 ] ; availStop = contentRange [ 1 ] ; contentLength = contentRange [ 2 ] ; if ( contentLength < 0 ) return null ; if ( availStop <= availStart ) return null ; if ( contentLength < availStop ) return null ; } return new long [ ] { availStart , availStop , contentLength } ; } | Look at resource HTTP header fields and determine the byte range available . |
34,911 | public static WaybackRequest createUrlQueryRequest ( String url , String start , String end ) { WaybackRequest r = new WaybackRequest ( ) ; r . setUrlQueryRequest ( ) ; r . setRequestUrl ( url ) ; r . setStartTimestamp ( start ) ; r . setEndTimestamp ( end ) ; return r ; } | create WaybackRequet for URL - Query request . |
34,912 | public static WaybackRequest createCaptureQueryRequet ( String url , String replay , String start , String end ) { WaybackRequest r = new WaybackRequest ( ) ; r . setCaptureQueryRequest ( ) ; r . setRequestUrl ( url ) ; r . setReplayTimestamp ( replay ) ; r . setStartTimestamp ( start ) ; r . setEndTimestamp ( end ) ; return r ; } | create WaybackRequest for Capture - Query request . |
34,913 | public static WaybackRequest createReplayRequest ( String url , String replay , String start , String end ) { WaybackRequest r = new WaybackRequest ( ) ; r . setReplayRequest ( ) ; r . setRequestUrl ( url ) ; r . setReplayTimestamp ( replay ) ; r . setStartTimestamp ( start ) ; r . setEndTimestamp ( end ) ; return r ; } | create WaybackRequet for Replay request . |
34,914 | public void setRequestUrl ( String urlStr ) { if ( ! urlStr . startsWith ( UrlOperations . HTTP_SCHEME ) && ! urlStr . startsWith ( UrlOperations . HTTPS_SCHEME ) && ! urlStr . startsWith ( UrlOperations . FTP_SCHEME ) && ! urlStr . startsWith ( UrlOperations . FTPS_SCHEME ) ) { if ( urlStr . startsWith ( "http:/" ) ) { urlStr = UrlOperations . HTTP_SCHEME + urlStr . substring ( 6 ) ; } else if ( urlStr . startsWith ( "https:/" ) ) { urlStr = UrlOperations . HTTPS_SCHEME + urlStr . substring ( 7 ) ; } else if ( urlStr . startsWith ( "ftp:/" ) ) { urlStr = UrlOperations . FTP_SCHEME + urlStr . substring ( 5 ) ; } else if ( urlStr . startsWith ( "ftps:/" ) ) { urlStr = UrlOperations . FTPS_SCHEME + urlStr . substring ( 6 ) ; } else { if ( UrlOperations . urlToScheme ( urlStr ) == null ) { urlStr = UrlOperations . HTTP_SCHEME + urlStr ; } } } try { String decodedUrlStr = URLDecoder . decode ( urlStr , "UTF-8" ) ; String idnEncodedHost = UsableURIFactory . getInstance ( decodedUrlStr , "UTF-8" ) . getHost ( ) ; if ( idnEncodedHost != null ) { String unicodeEncodedHost = URLEncoder . encode ( IDNA . toUnicode ( idnEncodedHost ) , "UTF-8" ) ; urlStr = urlStr . replace ( unicodeEncodedHost , idnEncodedHost ) ; } } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } catch ( URIException ex ) { throw new RuntimeException ( ex ) ; } put ( REQUEST_URL , urlStr ) ; } | Set the request URL . |
34,915 | public void extractHttpRequestInfo ( HttpServletRequest httpRequest ) { putUnlessNull ( REQUEST_REFERER_URL , httpRequest . getHeader ( "REFERER" ) ) ; String remoteAddr = httpRequest . getHeader ( "X-Forwarded-For" ) ; remoteAddr = ( remoteAddr == null ) ? httpRequest . getRemoteAddr ( ) : remoteAddr + ", " + httpRequest . getRemoteAddr ( ) ; putUnlessNull ( REQUEST_REMOTE_ADDRESS , remoteAddr ) ; String x_req_with = httpRequest . getHeader ( "X-Requested-With" ) ; if ( x_req_with != null ) { if ( x_req_with . equals ( "XMLHttpRequest" ) ) { this . setAjaxRequest ( true ) ; } } else if ( this . getRefererUrl ( ) != null && httpRequest . getParameter ( "ajaxpipe" ) != null ) { this . setAjaxRequest ( true ) ; } if ( isMementoEnabled ( ) ) { String acceptDateTime = httpRequest . getHeader ( MementoUtils . ACCEPT_DATETIME ) ; if ( acceptDateTime != null ) { this . setMementoAcceptDatetime ( true ) ; } } putUnlessNull ( REQUEST_WAYBACK_HOSTNAME , httpRequest . getLocalName ( ) ) ; putUnlessNull ( REQUEST_AUTH_TYPE , httpRequest . getAuthType ( ) ) ; putUnlessNull ( REQUEST_REMOTE_USER , httpRequest . getRemoteUser ( ) ) ; putUnlessNull ( REQUEST_AUTHORIZATION , httpRequest . getHeader ( REQUEST_AUTHORIZATION ) ) ; putUnlessNull ( REQUEST_WAYBACK_PORT , String . valueOf ( httpRequest . getLocalPort ( ) ) ) ; putUnlessNull ( REQUEST_WAYBACK_CONTEXT , httpRequest . getContextPath ( ) ) ; Locale l = null ; if ( accessPoint != null ) { l = accessPoint . getLocale ( ) ; } if ( l == null ) { l = httpRequest . getLocale ( ) ; } this . locale = l ; putUnlessNull ( REQUEST_LOCALE_LANG , l . getDisplayLanguage ( ) ) ; Cookie [ ] cookies = httpRequest . getCookies ( ) ; if ( cookies != null ) { for ( Cookie cookie : cookies ) { String name = cookie . getName ( ) ; String value = cookie . getValue ( ) ; String oldVal = get ( name ) ; if ( oldVal == null || oldVal . length ( ) == 0 ) { put ( name , value ) ; } } } } | extract REFERER remote IP and authorization information from the HttpServletRequest |
34,916 | public void addRequestHandler ( String host , String firstPath , RequestHandler requestHandler ) { String key = hostPathToKey ( host , firstPath ) ; if ( pathMap . containsKey ( key ) ) { LOGGER . warning ( "Duplicate port:path map for " + port + ":" + key ) ; } else { pathMap . put ( key , requestHandler ) ; if ( LOGGER . isLoggable ( Level . FINE ) ) { LOGGER . fine ( "Registered requestHandler(port/host/path) (" + port + "/" + host + "/" + firstPath + "): " + key ) ; } } } | Register the RequestHandler to accept requests for the given host and port . |
34,917 | public int updateQueue ( ) throws IOException { int added = 0 ; long lastMarkPoint = lastMark . getLastMark ( ) ; long currentMarkPoint = db . getCurrentMark ( ) ; if ( currentMarkPoint > lastMarkPoint ) { CloseableIterator < String > newNames = db . getNamesBetweenMarks ( lastMarkPoint , currentMarkPoint ) ; while ( newNames . hasNext ( ) ) { String newName = newNames . next ( ) ; LOGGER . info ( "Queued " + newName + " for indexing." ) ; queue . enqueue ( newName ) ; added ++ ; } newNames . close ( ) ; lastMark . setLastMark ( currentMarkPoint ) ; } return added ; } | Add new names to the IndexQueue . |
34,918 | public static String getTimestampForId ( String context , String ip ) { BDBMap bdbMap = getContextMap ( context ) ; String dateStr = bdbMap . get ( ip ) ; return ( dateStr != null ) ? dateStr : Timestamp . currentTimestamp ( ) . getDateStr ( ) ; } | return the timestamp associated with the identifier argument or now if no value is associated or something goes wrong . |
34,919 | public static void addTimestampForId ( String context , String ip , String time ) { BDBMap bdbMap = getContextMap ( context ) ; bdbMap . put ( ip , time ) ; } | associate timestamp time with idenfier ip persistantly |
34,920 | protected boolean shouldDetectMimeType ( String mimeType ) { for ( String prefix : untrustfulMimeTypes ) { if ( mimeType . startsWith ( prefix ) ) return true ; } return false ; } | check if mime - type detection is suggested for mimeType . |
34,921 | protected String getNodeContent ( Element e , String key ) { NodeList nodes = e . getElementsByTagName ( key ) ; String result = null ; if ( nodes != null && nodes . getLength ( ) > 0 ) { result = getNodeTextValue ( nodes . item ( 0 ) ) ; } return ( result == null || result . length ( ) == 0 ) ? null : result ; } | extract the text content of a single tag under a node |
34,922 | public String [ ] nameToUrls ( final String name ) throws IOException { String [ ] urls = null ; String valueString = get ( name ) ; if ( valueString != null && valueString . length ( ) > 0 ) { urls = valueString . split ( urlDelimiterRE ) ; } return urls ; } | return an array of String URLs for all known locations of name in the DB . |
34,923 | public void addNameUrl ( final String name , final String url ) throws IOException { String newValue = null ; String oldValue = get ( name ) ; if ( oldValue != null && oldValue . length ( ) > 0 ) { String curUrls [ ] = oldValue . split ( urlDelimiterRE ) ; boolean found = false ; for ( int i = 0 ; i < curUrls . length ; i ++ ) { if ( url . equals ( curUrls [ i ] ) ) { found = true ; break ; } } if ( found == false ) { newValue = oldValue + " " + url ; } } else { newValue = url ; if ( oldValue == null ) log . addName ( name ) ; } if ( newValue != null ) { put ( name , newValue ) ; } } | add an url location for a name unless it already exists |
34,924 | public void removeNameUrl ( final String name , final String url ) throws IOException { StringBuilder newValue = new StringBuilder ( ) ; String oldValue = get ( name ) ; if ( oldValue != null && oldValue . length ( ) > 0 ) { String curUrls [ ] = oldValue . split ( urlDelimiterRE ) ; for ( int i = 0 ; i < curUrls . length ; i ++ ) { if ( ! url . equals ( curUrls [ i ] ) ) { if ( newValue . length ( ) > 0 ) { newValue . append ( urlDelimiter ) ; } newValue . append ( curUrls [ i ] ) ; } } if ( newValue . length ( ) > 0 ) { put ( name , newValue . toString ( ) ) ; } else { delete ( name ) ; } } } | remove a single url location for an name if it exists |
34,925 | public static String getDateSpec ( WaybackRequest wbRequest , String datespec ) { int dateLen = 0 ; if ( datespec != null ) { dateLen = datespec . length ( ) ; } StringBuilder sb = new StringBuilder ( dateLen + 10 ) ; if ( dateLen > 0 ) { sb . append ( datespec ) ; } if ( wbRequest . isCSSContext ( ) ) { sb . append ( ArchivalUrlRequestParser . CSS_CONTEXT ) ; sb . append ( ArchivalUrlRequestParser . FLAG_DELIM ) ; dateLen ++ ; } if ( wbRequest . isJSContext ( ) ) { sb . append ( ArchivalUrlRequestParser . JS_CONTEXT ) ; sb . append ( ArchivalUrlRequestParser . FLAG_DELIM ) ; dateLen ++ ; } if ( wbRequest . isIMGContext ( ) ) { sb . append ( ArchivalUrlRequestParser . IMG_CONTEXT ) ; sb . append ( ArchivalUrlRequestParser . FLAG_DELIM ) ; dateLen ++ ; } if ( wbRequest . isObjectEmbedContext ( ) ) { sb . append ( ArchivalUrlRequestParser . OBJECT_EMBED_WRAPPED_CONTEXT ) ; sb . append ( ArchivalUrlRequestParser . FLAG_DELIM ) ; dateLen ++ ; } if ( wbRequest . isIdentityContext ( ) ) { sb . append ( ArchivalUrlRequestParser . IDENTITY_CONTEXT ) ; sb . append ( ArchivalUrlRequestParser . FLAG_DELIM ) ; dateLen ++ ; } if ( wbRequest . isIFrameWrapperContext ( ) ) { sb . append ( ArchivalUrlRequestParser . IFRAME_WRAPPED_CONTEXT ) ; sb . append ( ArchivalUrlRequestParser . FLAG_DELIM ) ; dateLen ++ ; } if ( wbRequest . isFrameWrapperContext ( ) ) { sb . append ( ArchivalUrlRequestParser . FRAME_WRAPPED_CONTEXT ) ; sb . append ( ArchivalUrlRequestParser . FLAG_DELIM ) ; dateLen ++ ; } return sb . toString ( ) ; } | Given a date create a new datespec + flags which represent the same options as requested by the WaybackRequest |
34,926 | public void setFilterGroup ( ExclusionCaptureFilterGroup filterGroup ) { super . setFilterGroup ( filterGroup ) ; if ( ( filterGroup != null ) && ( filterGroup . getCaptureFilterGroupCanonicalizer ( ) != null ) ) { this . canonicalizer = filterGroup . getCaptureFilterGroupCanonicalizer ( ) ; } } | Set the canonicalizer from the filter as it may be different from the default |
34,927 | public LiveWebState handleRedirect ( WaybackException e , WaybackRequest wbRequest , HttpServletRequest httpRequest , HttpServletResponse httpResponse ) throws IOException { if ( statusLiveWebPolicy == null ) { return LiveWebState . NOT_FOUND ; } if ( ( wbRequest == null ) || wbRequest . isIdentityContext ( ) || ( liveWebHandler == null ) ) { return LiveWebState . NOT_FOUND ; } int status = e . getStatus ( ) ; String stateName = statusLiveWebPolicy . getProperty ( String . valueOf ( status ) ) ; if ( stateName == null ) { stateName = statusLiveWebPolicy . getProperty ( DEFAULT ) ; } RedirectType state = RedirectType . ALL ; if ( stateName != null ) { state = RedirectType . valueOf ( stateName ) ; } String redirUrl = null ; if ( state == RedirectType . NONE ) { return LiveWebState . NOT_FOUND ; } if ( state == RedirectType . EMBEDS_ONLY ) { if ( ! wbRequest . isAnyEmbeddedContext ( ) ) { return LiveWebState . FOUND ; } } redirUrl = liveWebHandler . getLiveWebRedirect ( httpRequest , wbRequest , e ) ; if ( redirUrl == null ) { return LiveWebState . NOT_FOUND ; } if ( redirUrl . equals ( DEFAULT ) ) { redirUrl = getLiveWebPrefix ( ) + wbRequest . getRequestUrl ( ) ; } httpResponse . sendRedirect ( redirUrl ) ; return LiveWebState . REDIRECTED ; } | Check the statusLiveWebType to see if given the WaybackExceptions status code should redirect ALL NONE or EMBEDS_ONLY |
34,928 | public void filter ( CaptureSearchResults results ) { Iterator < CaptureSearchResult > itr = results . iterator ( ) ; while ( itr . hasNext ( ) ) { CaptureSearchResult result = itr . next ( ) ; String captureDate = result . getCaptureTimestamp ( ) ; if ( ( captureDate . compareTo ( startDateStr ) >= 0 ) && ( captureDate . compareTo ( endDateStr ) < 0 ) ) { matches . add ( result ) ; } } } | add all SearchResult objects from the SearchResults which fall within the time range of this partition into this partition . |
34,929 | public static byte [ ] copy ( byte [ ] src , int offset , int length ) { byte [ ] copy = new byte [ length ] ; System . arraycopy ( src , offset , copy , 0 , length ) ; return copy ; } | Create a new byte array with contents initialized to values from the argument byte array . |
34,930 | public static boolean cmp ( byte [ ] a , byte [ ] b ) { if ( a . length != b . length ) { return false ; } for ( int i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] != b [ i ] ) { return false ; } } return true ; } | Compare two byte arrays |
34,931 | public static void discardStream ( InputStream is , int size ) throws IOException { byte [ ] buffer = new byte [ size ] ; while ( is . read ( buffer , 0 , size ) != - 1 ) { } } | throw away all bytes from stream argument |
34,932 | public static long discardStreamCount ( InputStream is , int size ) throws IOException { long count = 0 ; byte [ ] buffer = new byte [ size ] ; int amt = 0 ; while ( ( amt = is . read ( buffer , 0 , size ) ) != - 1 ) { count += amt ; } return count ; } | throw away all bytes from stream argument and count how many bytes were discarded before reaching the end of the stream . |
34,933 | public void set ( int i , boolean value ) { int idx = i / 8 ; if ( idx >= bb . limit ( ) ) { throw new IndexOutOfBoundsException ( ) ; } int bit = 7 - ( i % 8 ) ; if ( value ) { bb . put ( idx , ( byte ) ( bb . get ( idx ) | MASKS [ bit ] ) ) ; } else { bb . put ( idx , ( byte ) ( bb . get ( idx ) & MASKSR [ bit ] ) ) ; } } | set the i th bit to 1 or 0 |
34,934 | public static String getTagAttr ( StringBuilder page , final String tag , final String attr ) { String found = null ; Pattern daPattern = TagMagix . getPattern ( tag , attr ) ; Matcher matcher = daPattern . matcher ( page ) ; int idx = 0 ; if ( matcher . find ( idx ) ) { found = matcher . group ( 1 ) ; found = trimAttrValue ( found ) ; } return found ; } | find and return the ATTR value within a TAG tag inside the HTML document within the StringBuffer page . returns null if no TAG - ATTR is found . |
34,935 | public static String getTagAttrWhere ( StringBuilder page , final String tag , final String findAttr , final String whereAttr , final String whereVal ) { Pattern tagPattern = getWholeTagPattern ( tag ) ; Pattern findAttrPattern = getAttrPattern ( findAttr ) ; Pattern whereAttrPattern = getAttrPattern ( whereAttr ) ; Matcher tagMatcher = tagPattern . matcher ( page ) ; while ( tagMatcher . find ( ) ) { String wholeTag = tagMatcher . group ( ) ; Matcher whereAttrMatcher = whereAttrPattern . matcher ( wholeTag ) ; if ( whereAttrMatcher . find ( ) ) { String attrValue = whereAttrMatcher . group ( 1 ) ; attrValue = trimAttrValue ( attrValue ) ; if ( attrValue . compareToIgnoreCase ( whereVal ) == 0 ) { Matcher findAttrMatcher = findAttrPattern . matcher ( wholeTag ) ; String value = null ; if ( findAttrMatcher . find ( ) ) { value = findAttrMatcher . group ( 1 ) ; value = trimAttrValue ( value ) ; } return value ; } } } return null ; } | Search through the HTML contained in page returning the value of a particular attribute . This version allows matching only tags that contain a particular attribute - value pair which is useful in extracting META tag values for example in returning the value of the content attribute in a META tag that also contains an attribute http - equiv with a value of Content - Type . All comparision is case - insensitive but the value returned is the original attribute value as unmolested as possible . |
34,936 | public static boolean isAuthority ( String authString ) { Matcher m = AUTHORITY_REGEX . matcher ( authString ) ; return ( m != null ) && m . matches ( ) ; } | Tests if the String argument looks like it could be a legitimate authority fragment of a URL that is is it an IP address or are the characters legal in an authority and does the string end with a legal TLD . |
34,937 | public static String resolveUrl ( String baseUrl , String url ) { String resolvedUrl = resolveUrl ( baseUrl , url , null ) ; if ( resolvedUrl == null ) { resolvedUrl = url . replace ( " " , "%20" ) ; resolvedUrl = resolvedUrl . replace ( "\r" , "%0D" ) ; } return resolvedUrl ; } | Resolve URL but return a minimally escaped version in case of error |
34,938 | public static String resolveUrl ( String baseUrl , String url , String defaultValue ) { for ( final String scheme : ALL_SCHEMES ) { if ( url . startsWith ( scheme ) ) { try { return UsableURIFactory . getInstance ( url ) . getEscapedURI ( ) ; } catch ( URIException e ) { LOGGER . warning ( e . getLocalizedMessage ( ) + ": " + url ) ; return defaultValue ; } } } UsableURI absBaseURI ; UsableURI resolvedURI = null ; try { absBaseURI = UsableURIFactory . getInstance ( baseUrl ) ; resolvedURI = UsableURIFactory . getInstance ( absBaseURI , url ) ; } catch ( URIException e ) { LOGGER . warning ( e . getLocalizedMessage ( ) + ": " + url ) ; return defaultValue ; } return resolvedURI . getEscapedURI ( ) ; } | Resolve a possibly relative url argument against a base URL . |
34,939 | public static int schemeToDefaultPort ( final String scheme ) { if ( scheme . equals ( HTTP_SCHEME ) ) { return 80 ; } if ( scheme . equals ( HTTPS_SCHEME ) ) { return 443 ; } if ( scheme . equals ( FTP_SCHEME ) ) { return 21 ; } if ( scheme . equals ( RTSP_SCHEME ) ) { return 554 ; } if ( scheme . equals ( MMS_SCHEME ) ) { return 1755 ; } return - 1 ; } | Return the default port for the scheme String argument if known . |
34,940 | public static String stripDefaultPortFromUrl ( String url ) { String scheme = urlToScheme ( url ) ; if ( scheme == null ) { return url ; } int defaultPort = schemeToDefaultPort ( scheme ) ; if ( defaultPort == - 1 ) { return url ; } String portStr = null ; int slashIdx = url . indexOf ( '/' , scheme . length ( ) ) ; if ( slashIdx == - 1 ) { portStr = String . format ( ":%d" , defaultPort ) ; if ( url . endsWith ( portStr ) ) { return url . substring ( 0 , url . length ( ) - portStr . length ( ) ) ; } } portStr = String . format ( ":%d/" , defaultPort ) ; int idx = url . indexOf ( portStr ) ; if ( idx == - 1 ) { return url ; } if ( slashIdx < idx ) { return url ; } StringBuilder sb = new StringBuilder ( url . length ( ) ) ; sb . append ( url . substring ( 0 , idx ) ) ; sb . append ( url . substring ( idx + ( portStr . length ( ) - 1 ) ) ) ; return sb . toString ( ) ; } | Attempt to strip default ports out of URL strings . |
34,941 | public static String urlToHost ( String url ) { String lcUrl = url . toLowerCase ( ) ; if ( lcUrl . startsWith ( DNS_SCHEME ) ) { return lcUrl . substring ( DNS_SCHEME . length ( ) ) ; } for ( String scheme : ALL_SCHEMES ) { if ( lcUrl . startsWith ( scheme ) ) { int authorityIdx = scheme . length ( ) ; Matcher m = HOST_REGEX_SIMPLE . matcher ( lcUrl . substring ( authorityIdx ) ) ; if ( m . find ( ) ) { return m . group ( 1 ) ; } } } return url ; } | Attempt to extract the hostname component of an absolute URL argument . |
34,942 | public static String urlToUserInfo ( String url ) { String lcUrl = url . toLowerCase ( ) ; if ( lcUrl . startsWith ( DNS_SCHEME ) ) { return null ; } for ( String scheme : ALL_SCHEMES ) { if ( lcUrl . startsWith ( scheme ) ) { int authorityIdx = scheme . length ( ) ; Matcher m = USERINFO_REGEX_SIMPLE . matcher ( lcUrl . substring ( authorityIdx ) ) ; if ( m . find ( ) ) { return m . group ( 1 ) ; } } } return null ; } | Extract userinfo from the absolute URL argument that is username |
34,943 | public static String getUrlParentDir ( String url ) { try { UsableURI uri = UsableURIFactory . getInstance ( url ) ; String path = uri . getPath ( ) ; if ( path . length ( ) > 1 ) { int startIdx = path . length ( ) - 1 ; if ( path . charAt ( path . length ( ) - 1 ) == '/' ) { startIdx -- ; } int idx = path . lastIndexOf ( '/' , startIdx ) ; if ( idx >= 0 ) { uri . setPath ( path . substring ( 0 , idx + 1 ) ) ; uri . setQuery ( null ) ; return uri . toUnicodeHostString ( ) ; } } } catch ( URIException e ) { LOGGER . warning ( e . getLocalizedMessage ( ) + ": " + url ) ; } return null ; } | Find and return the parent directory of the URL argument |
34,944 | public void shutdown ( ) { if ( collection != null ) { try { collection . shutdown ( ) ; } catch ( IOException e ) { LOGGER . severe ( "FAILED collection shutdown" + e . getMessage ( ) ) ; } } if ( exclusionFactory != null ) { exclusionFactory . shutdown ( ) ; } } | Release any resources associated with this AccessPoint including stopping any background processing threads |
34,945 | public void setLiveWebPrefix ( String liveWebPrefix ) { if ( liveWebPrefix == null || liveWebPrefix . isEmpty ( ) ) { this . liveWebRedirector = null ; } this . liveWebRedirector = new DefaultLiveWebRedirector ( liveWebPrefix ) ; } | Set standard liveweb redirector |
34,946 | protected boolean doStripRegexMatch ( StringBuilder url , Matcher matcher ) { if ( matcher != null && matcher . matches ( ) ) { url . delete ( matcher . start ( 1 ) , matcher . end ( 1 ) ) ; return true ; } return false ; } | Run a regex against a StringBuilder removing group 1 if it matches . |
34,947 | public String canonicalize ( String url ) { if ( url == null || url . length ( ) <= 0 ) { return url ; } url = url . toLowerCase ( ) ; StringBuilder sb = new StringBuilder ( url ) ; boolean changed = false ; for ( int i = 0 ; i < choosers . length ; i ++ ) { if ( sb . indexOf ( choosers [ i ] ) != - 1 ) { changed |= doStripRegexMatch ( sb , strippers [ i ] . matcher ( sb ) ) ; } } if ( changed ) { url = sb . toString ( ) ; } int index = url . lastIndexOf ( '?' ) ; if ( index > 0 ) { if ( index == ( url . length ( ) - 1 ) ) { url = url . substring ( 0 , url . length ( ) - 1 ) ; } else if ( url . charAt ( index + 1 ) == '&' ) { if ( url . length ( ) == ( index + 2 ) ) { url = url . substring ( 0 , url . length ( ) - 2 ) ; } else { url = url . substring ( 0 , index + 1 ) + url . substring ( index + 2 ) ; } } else if ( url . charAt ( url . length ( ) - 1 ) == '&' ) { url = url . substring ( 0 , url . length ( ) - 1 ) ; } } return url ; } | Idempotent operation that will determine the fuzziest form of the url argument . This operation is done prior to adding records to the ResourceIndex and prior to lookup . Current version is exactly the default found in Heritrix . When the configuration system for Heritrix stabilizes hopefully this can use the system directly within Heritrix . |
34,948 | public void addSearchResult ( CaptureSearchResult result , boolean append ) { String resultDate = result . getCaptureTimestamp ( ) ; if ( ( firstResultTimestamp == null ) || ( firstResultTimestamp . compareTo ( resultDate ) > 0 ) ) { firstResultTimestamp = resultDate ; } if ( ( lastResultTimestamp == null ) || ( lastResultTimestamp . compareTo ( resultDate ) < 0 ) ) { lastResultTimestamp = resultDate ; } if ( append ) { if ( ! results . isEmpty ( ) ) { results . getLast ( ) . setNextResult ( result ) ; result . setPrevResult ( results . getLast ( ) ) ; } results . add ( result ) ; } else { if ( ! results . isEmpty ( ) ) { results . getFirst ( ) . setPrevResult ( result ) ; result . setNextResult ( results . getFirst ( ) ) ; } results . add ( 0 , result ) ; } } | Add a result to this results at either the beginning or the end depending on the append argument |
34,949 | public static PartitionSize getSize ( String name ) { for ( PartitionSize pa : sizes ) { if ( pa . name ( ) . equals ( name ) ) { return pa ; } } return twoYearSize ; } | Get a PartitionSize object by it s name |
34,950 | public PartitionSize getSize ( Date first , Date last , int maxP ) { long diffMS = last . getTime ( ) - first . getTime ( ) ; for ( PartitionSize pa : sizes ) { long maxMS = maxP * pa . intervalMS ( ) ; if ( maxMS > diffMS ) { return pa ; } } return twoYearSize ; } | Attempt to find the smallest PartitionSize implementation which spanning the range first and last specified produces at most maxP partitions . |
34,951 | public List < Partition < T > > getRange ( PartitionSize size , Date start , Date end ) { List < Partition < T > > partitions = new ArrayList < Partition < T > > ( ) ; Calendar cStart = Calendar . getInstance ( TZ_UTC ) ; cStart . setTime ( start ) ; size . alignStart ( cStart ) ; Calendar cEnd = size . increment ( cStart , 1 ) ; while ( cStart . getTime ( ) . compareTo ( end ) < 0 ) { partitions . add ( new Partition < T > ( cStart . getTime ( ) , cEnd . getTime ( ) ) ) ; cStart = cEnd ; cEnd = size . increment ( cStart , 1 ) ; } return partitions ; } | Create a List of Partition objects of the specified size which span the date range specified . |
34,952 | public void populate ( List < Partition < T > > partitions , Iterator < T > itr ) { int idx = 0 ; int size = partitions . size ( ) ; T element = null ; while ( idx < size ) { Partition < T > partition = partitions . get ( idx ) ; if ( element == null ) { if ( itr . hasNext ( ) ) { element = itr . next ( ) ; } else { break ; } } while ( partition . containsDate ( map . elementToDate ( element ) ) ) { map . addElementToPartition ( element , partition ) ; element = null ; if ( itr . hasNext ( ) ) { element = itr . next ( ) ; } else { break ; } } idx ++ ; } if ( itr . hasNext ( ) ) { LOGGER . warning ( "Not all elements fit in partitions!" ) ; } } | Add elements from itr into the appropriate partitions . Assumes that all elements fit in one of the argument Partitions that the partitions are in ascending order by time and that elements returned from the Iterator are in ascending time order . |
34,953 | public void addRequestHandler ( int port , String host , String path , RequestHandler requestHandler ) { Integer portInt = Integer . valueOf ( port ) ; PortMapper portMapper = portMap . get ( portInt ) ; if ( portMapper == null ) { portMapper = new PortMapper ( portInt ) ; portMap . put ( portInt , portMapper ) ; } portMapper . addRequestHandler ( host , path , requestHandler ) ; LOGGER . info ( "Registered " + port + "/" + ( host == null ? "*" : host ) + "/" + ( path == null ? "*" : path ) + " + requestHandler ) ; } | Register the RequestHandler to accept requests on the given port for the specified host and path . |
34,954 | public boolean handleRequest ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { boolean handled = false ; if ( request . getAttribute ( UIResults . FERRET_NAME ) != null ) { return false ; } if ( globalPreRequestHandler != null ) { handled = globalPreRequestHandler . handleRequest ( request , response ) ; } if ( handled == false ) { RequestHandlerContext handlerContext = mapRequest ( request ) ; if ( handlerContext != null ) { RequestHandler requestHandler = handlerContext . getRequestHandler ( ) ; String pathPrefix = handlerContext . getPathPrefix ( ) ; if ( ! pathPrefix . equals ( "/" ) ) { pathPrefix += "/" ; } request . setAttribute ( REQUEST_CONTEXT_PREFIX , pathPrefix ) ; handled = requestHandler . handleRequest ( request , response ) ; } } if ( handled == false ) { if ( globalPostRequestHandler != null ) { handled = globalPostRequestHandler . handleRequest ( request , response ) ; } } return handled ; } | Map the incoming request to the appropriate RequestHandler including the PRE and POST RequestHandlers if configured . |
34,955 | public void shutdown ( ) { for ( ShutdownListener shutdownListener : shutdownListeners ) { try { shutdownListener . shutdown ( ) ; } catch ( Exception e ) { LOGGER . severe ( "failed shutdown" + e . getMessage ( ) ) ; } } } | notify all registered ShutdownListener objects that the ServletContext is being destroyed . |
34,956 | private boolean processCharsetSelect ( ArrayList < Object > options ) { int set = optionInt ( options , 0 ) ; char seq = ( ( Character ) options . get ( 1 ) ) . charValue ( ) ; processCharsetSelect ( set , seq ) ; return true ; } | Process character set sequence . |
34,957 | public static Appendable render ( final String input , Appendable target ) throws IOException { int i = 0 ; int j , k ; while ( true ) { j = input . indexOf ( BEGIN_TOKEN , i ) ; if ( j == - 1 ) { if ( i == 0 ) { target . append ( input ) ; return target ; } target . append ( input . substring ( i , input . length ( ) ) ) ; return target ; } target . append ( input . substring ( i , j ) ) ; k = input . indexOf ( END_TOKEN , j ) ; if ( k == - 1 ) { target . append ( input ) ; return target ; } j += BEGIN_TOKEN_LEN ; String spec = input . substring ( j , k ) ; String [ ] items = spec . split ( CODE_TEXT_SEPARATOR , 2 ) ; if ( items . length == 1 ) { target . append ( input ) ; return target ; } String replacement = render ( items [ 1 ] , items [ 0 ] . split ( CODE_LIST_SEPARATOR ) ) ; target . append ( replacement ) ; i = k + END_TOKEN_LEN ; } } | Renders the given input to the target Appendable . |
34,958 | static String zeroPrepend ( long num , int digits ) { String numStr = Long . toString ( num ) ; if ( numStr . length ( ) >= digits ) { return numStr ; } else { return String . format ( "%0" + digits + "d" , num ) ; } } | Return the string prepended with 0s . |
34,959 | static byte [ ] decodeBase32 ( String str ) { int numBytes = ( ( str . length ( ) * 5 ) + 7 ) / 8 ; byte [ ] result = new byte [ numBytes ] ; int resultIndex = 0 ; int which = 0 ; int working = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char ch = str . charAt ( i ) ; int val ; if ( ch >= 'a' && ch <= 'z' ) { val = ch - 'a' ; } else if ( ch >= 'A' && ch <= 'Z' ) { val = ch - 'A' ; } else if ( ch >= '2' && ch <= '7' ) { val = 26 + ( ch - '2' ) ; } else if ( ch == '=' ) { which = 0 ; break ; } else { throw new IllegalArgumentException ( "Invalid base-32 character: " + ch ) ; } switch ( which ) { case 0 : working = ( val & 0x1F ) << 3 ; which = 1 ; break ; case 1 : working |= ( val & 0x1C ) >> 2 ; result [ resultIndex ++ ] = ( byte ) working ; working = ( val & 0x03 ) << 6 ; which = 2 ; break ; case 2 : working |= ( val & 0x1F ) << 1 ; which = 3 ; break ; case 3 : working |= ( val & 0x10 ) >> 4 ; result [ resultIndex ++ ] = ( byte ) working ; working = ( val & 0x0F ) << 4 ; which = 4 ; break ; case 4 : working |= ( val & 0x1E ) >> 1 ; result [ resultIndex ++ ] = ( byte ) working ; working = ( val & 0x01 ) << 7 ; which = 5 ; break ; case 5 : working |= ( val & 0x1F ) << 2 ; which = 6 ; break ; case 6 : working |= ( val & 0x18 ) >> 3 ; result [ resultIndex ++ ] = ( byte ) working ; working = ( val & 0x07 ) << 5 ; which = 7 ; break ; case 7 : working |= ( val & 0x1F ) ; result [ resultIndex ++ ] = ( byte ) working ; which = 0 ; break ; } } if ( which != 0 ) { result [ resultIndex ++ ] = ( byte ) working ; } if ( resultIndex != result . length ) { result = Arrays . copyOf ( result , resultIndex ) ; } return result ; } | Decode base - 32 method . I didn t want to add a dependency to Apache Codec just for this decode method . Exposed for testing . |
34,960 | public final String getName ( ) { String name = getProperty ( AbstractNode . name ) ; if ( name == null ) { name = getUuid ( ) ; } return name ; } | Get name from underlying db node |
34,961 | public Set < PropertyKey > getPropertyKeys ( final String propertyView ) { if ( securityContext != null && securityContext . hasCustomView ( ) ) { final Set < PropertyKey > keys = new LinkedHashSet < > ( StructrApp . getConfiguration ( ) . getPropertySet ( entityType , PropertyView . All ) ) ; final Set < String > customView = securityContext . getCustomView ( ) ; for ( Iterator < PropertyKey > it = keys . iterator ( ) ; it . hasNext ( ) ; ) { if ( ! customView . contains ( it . next ( ) . jsonName ( ) ) ) { it . remove ( ) ; } } return keys ; } return StructrApp . getConfiguration ( ) . getPropertySet ( entityType , propertyView ) ; } | Returns the property set for the given view as an Iterable . |
34,962 | public final < T > Comparable getComparableProperty ( final PropertyKey < T > key ) { if ( key != null ) { final T propertyValue = getProperty ( key ) ; PropertyConverter < T , ? > converter = key . databaseConverter ( securityContext , this ) ; if ( converter != null ) { try { return converter . convertForSorting ( propertyValue ) ; } catch ( Throwable t ) { logger . warn ( "Unable to convert property {} of type {}: {}" , new Object [ ] { key . dbName ( ) , getClass ( ) . getSimpleName ( ) , t . getMessage ( ) } ) ; logger . warn ( "" , t ) ; } } if ( propertyValue instanceof Comparable ) { return ( Comparable ) propertyValue ; } if ( propertyValue != null ) { return propertyValue . toString ( ) ; } } return null ; } | Returns the property value for the given key as a Comparable |
34,963 | public final Map < String , Long > getRelationshipInfo ( final Direction dir ) throws FrameworkException { return StructrApp . getInstance ( securityContext ) . command ( NodeRelationshipStatisticsCommand . class ) . execute ( this , dir ) ; } | Return statistical information on all relationships of this node |
34,964 | public final Principal getOwnerNode ( ) { if ( cachedOwnerNode == null ) { final Ownership ownership = getIncomingRelationshipAsSuperUser ( PrincipalOwnsNode . class ) ; if ( ownership != null ) { Principal principal = ownership . getSourceNode ( ) ; cachedOwnerNode = ( Principal ) principal ; } } return cachedOwnerNode ; } | Returns the owner node of this node following an INCOMING OWNS relationship . |
34,965 | public final < A extends NodeInterface , B extends NodeInterface , S extends Source , T extends Target > boolean hasRelationship ( final Class < ? extends Relation < A , B , S , T > > type ) { return this . getRelationships ( type ) . iterator ( ) . hasNext ( ) ; } | Return true if this node has a relationship of given type and direction . |
34,966 | private boolean propagationAllowed ( final AbstractNode thisNode , final RelationshipInterface rel , final SchemaRelationshipNode . Direction propagationDirection , final boolean doLog ) { if ( propagationDirection . equals ( SchemaRelationshipNode . Direction . Both ) ) { return true ; } if ( propagationDirection . equals ( SchemaRelationshipNode . Direction . None ) ) { return false ; } final String sourceNodeId = rel . getSourceNode ( ) . getUuid ( ) ; final String thisNodeId = thisNode . getUuid ( ) ; if ( sourceNodeId . equals ( thisNodeId ) ) { switch ( propagationDirection ) { case Out : return false ; case In : return true ; } } else { switch ( propagationDirection ) { case Out : return true ; case In : return false ; } } return false ; } | Determines whether propagation of permissions is allowed along the given relationship . |
34,967 | private Agent createAgent ( Task forTask ) { logger . debug ( "Creating new agent for task {}" , forTask . getClass ( ) . getSimpleName ( ) ) ; Agent agent = null ; try { agent = lookupAgent ( forTask ) ; if ( agent != null ) { agent . setAgentService ( this ) ; } } catch ( Throwable t ) { t . printStackTrace ( ) ; } return ( agent ) ; } | Creates a new agent for the given Task . Note that the agent must be started manually after creation . |
34,968 | public < T > PropertyKey < T > getDirectAccessReferenceGroup ( String name , Class < T > type ) { if ( ! propertyKeys . containsKey ( name ) ) { throw new IllegalArgumentException ( "ReferenceGroup " + dbName + " does not contain grouped property " + name + "!" ) ; } return new GenericProperty ( propertyKeys . get ( name ) . dbName ( ) ) ; } | Returns a wrapped group property that can be used to access a nested group property directly i . e . without having to fetch the group first . |
34,969 | protected Principal checkExternalAuthentication ( final HttpServletRequest request , final HttpServletResponse response ) throws FrameworkException { final String path = PathHelper . clean ( request . getPathInfo ( ) ) ; final String [ ] uriParts = PathHelper . getParts ( path ) ; logger . debug ( "Checking external authentication ..." ) ; if ( uriParts == null || uriParts . length != 3 || ! ( "oauth" . equals ( uriParts [ 0 ] ) ) ) { logger . debug ( "Incorrect URI parts for OAuth process, need /oauth/<name>/<action>" ) ; return null ; } final String name = uriParts [ 1 ] ; final String action = uriParts [ 2 ] ; final StructrOAuthClient oauthServer = StructrOAuthClient . getServer ( name ) ; if ( oauthServer == null ) { logger . debug ( "No OAuth2 authentication server configured for {}" , path ) ; return null ; } if ( "login" . equals ( action ) ) { try { response . sendRedirect ( oauthServer . getEndUserAuthorizationRequestUri ( request ) ) ; return null ; } catch ( Exception ex ) { logger . error ( "Could not send redirect to authorization server" , ex ) ; } } else if ( "auth" . equals ( action ) ) { final String accessToken = oauthServer . getAccessToken ( request ) ; final SecurityContext superUserContext = SecurityContext . getSuperUserInstance ( ) ; if ( accessToken != null ) { logger . debug ( "Got access token {}" , accessToken ) ; String value = oauthServer . getCredential ( request ) ; logger . debug ( "Got credential value: {}" , new Object [ ] { value } ) ; if ( value != null ) { final PropertyKey credentialKey = oauthServer . getCredentialKey ( ) ; Principal user = AuthHelper . getPrincipalForCredential ( credentialKey , value ) ; if ( user == null && Settings . RestUserAutocreate . getValue ( ) ) { user = RegistrationResource . createUser ( superUserContext , credentialKey , value , true , getUserClass ( ) , null ) ; oauthServer . initializeUser ( user ) ; } if ( user != null ) { AuthHelper . doLogin ( request , user ) ; HtmlServlet . setNoCacheHeaders ( response ) ; try { logger . debug ( "Response status: {}" , response . getStatus ( ) ) ; response . sendRedirect ( oauthServer . getReturnUri ( ) ) ; } catch ( IOException ex ) { logger . error ( "Could not redirect to {}: {}" , new Object [ ] { oauthServer . getReturnUri ( ) , ex } ) ; } return user ; } } } } try { response . sendRedirect ( oauthServer . getErrorUri ( ) ) ; } catch ( IOException ex ) { logger . error ( "Could not redirect to {}: {}" , new Object [ ] { oauthServer . getReturnUri ( ) , ex } ) ; } return null ; } | This method checks all configured external authentication services . |
34,970 | public static boolean isValidStringMinLength ( final GraphObject node , final PropertyKey < String > key , final int minLength , final ErrorBuffer errorBuffer ) { String value = node . getProperty ( key ) ; String type = node . getType ( ) ; if ( StringUtils . isNotBlank ( value ) ) { if ( value . length ( ) >= minLength ) { return true ; } errorBuffer . add ( new TooShortToken ( type , key , minLength ) ) ; return false ; } errorBuffer . add ( new EmptyPropertyToken ( type , key ) ) ; return false ; } | Checks whether the value for the given property key of the given node has at least the given length . |
34,971 | public T listGetPrevious ( final T currentElement ) { Relation < T , T , OneStartpoint < T > , OneEndpoint < T > > prevRel = currentElement . getIncomingRelationship ( getSiblingLinkType ( ) ) ; if ( prevRel != null ) { return ( T ) prevRel . getSourceNode ( ) ; } return null ; } | Returns the predecessor of the given element in the list structure defined by this LinkedListManager . |
34,972 | public T listGetNext ( final T currentElement ) { Relation < T , T , OneStartpoint < T > , OneEndpoint < T > > nextRel = currentElement . getOutgoingRelationship ( getSiblingLinkType ( ) ) ; if ( nextRel != null ) { return ( T ) nextRel . getTargetNode ( ) ; } return null ; } | Returns the successor of the given element in the list structure defined by this LinkedListManager . |
34,973 | public void listInsertBefore ( final T currentElement , final T newElement ) throws FrameworkException { if ( currentElement . getUuid ( ) . equals ( newElement . getUuid ( ) ) ) { throw new IllegalStateException ( "Cannot link a node to itself!" ) ; } final T previousElement = listGetPrevious ( currentElement ) ; if ( previousElement == null ) { linkNodes ( getSiblingLinkType ( ) , newElement , currentElement ) ; } else { unlinkNodes ( getSiblingLinkType ( ) , previousElement , currentElement ) ; if ( ! previousElement . getUuid ( ) . equals ( newElement . getUuid ( ) ) ) { linkNodes ( getSiblingLinkType ( ) , previousElement , newElement ) ; } if ( ! newElement . getUuid ( ) . equals ( currentElement . getUuid ( ) ) ) { linkNodes ( getSiblingLinkType ( ) , newElement , currentElement ) ; } } } | Inserts newElement before currentElement in the list defined by this LinkedListManager . |
34,974 | public void listInsertAfter ( final T currentElement , final T newElement ) throws FrameworkException { if ( currentElement . getUuid ( ) . equals ( newElement . getUuid ( ) ) ) { throw new IllegalStateException ( "Cannot link a node to itself!" ) ; } final T next = listGetNext ( currentElement ) ; if ( next == null ) { linkNodes ( getSiblingLinkType ( ) , currentElement , newElement ) ; } else { unlinkNodes ( getSiblingLinkType ( ) , currentElement , next ) ; linkNodes ( getSiblingLinkType ( ) , currentElement , newElement ) ; if ( ! newElement . getUuid ( ) . equals ( next . getUuid ( ) ) ) { linkNodes ( getSiblingLinkType ( ) , newElement , next ) ; } } } | Inserts newElement after currentElement in the list defined by this LinkedListManager . |
34,975 | public void listRemove ( final T currentElement ) throws FrameworkException { final T previousElement = listGetPrevious ( currentElement ) ; final T nextElement = listGetNext ( currentElement ) ; if ( currentElement != null ) { if ( previousElement != null ) { unlinkNodes ( getSiblingLinkType ( ) , previousElement , currentElement ) ; } if ( nextElement != null ) { unlinkNodes ( getSiblingLinkType ( ) , currentElement , nextElement ) ; } } if ( previousElement != null && nextElement != null ) { Node previousNode = previousElement . getNode ( ) ; Node nextNode = nextElement . getNode ( ) ; if ( previousNode != null && nextNode != null ) { linkNodes ( getSiblingLinkType ( ) , previousElement , nextElement ) ; } } } | Removes the current element from the list defined by this LinkedListManager . |
34,976 | private void handleSetProperty ( final Element element , final Map < String , Object > entityData , final Map < String , Object > config ) { String propertyName = ( String ) config . get ( PROPERTY_NAME ) ; if ( propertyName == null ) { propertyName = element . tagName ; } entityData . put ( propertyName , element . text ) ; } | The setProperty action will not descend further into the collection of children but will instead evaluate a transformation expression . |
34,977 | public static JsonSchema createFromDatabase ( final App app , final List < String > types ) throws FrameworkException , URISyntaxException { try ( final Tx tx = app . tx ( ) ) { final JsonSchema schema = StructrSchemaDefinition . initializeFromDatabase ( app , types ) ; tx . success ( ) ; return schema ; } } | Creates JsonSchema instance from the current schema in Structr including only a subset of schema nodes . |
34,978 | public static JsonSchema createFromSource ( final String source ) throws InvalidSchemaException , URISyntaxException { return StructrSchema . createFromSource ( new StringReader ( source ) ) ; } | Parses a JsonSchema from the given string . |
34,979 | public static JsonSchema createFromSource ( final Reader reader ) throws InvalidSchemaException , URISyntaxException { final Gson gson = new GsonBuilder ( ) . create ( ) ; final Map < String , Object > rawData = gson . fromJson ( reader , Map . class ) ; return StructrSchemaDefinition . initializeFromSource ( rawData ) ; } | Parses a JsonSchema from the given reader . |
34,980 | public static void replaceDatabaseSchema ( final App app , final JsonSchema newSchema ) throws FrameworkException , URISyntaxException { Services . getInstance ( ) . setOverridingSchemaTypesAllowed ( true ) ; try ( final Tx tx = app . tx ( ) ) { for ( final SchemaRelationshipNode schemaRelationship : app . nodeQuery ( SchemaRelationshipNode . class ) . getAsList ( ) ) { app . delete ( schemaRelationship ) ; } for ( final SchemaNode schemaNode : app . nodeQuery ( SchemaNode . class ) . getAsList ( ) ) { app . delete ( schemaNode ) ; } for ( final SchemaMethod schemaMethod : app . nodeQuery ( SchemaMethod . class ) . getAsList ( ) ) { app . delete ( schemaMethod ) ; } for ( final SchemaMethodParameter schemaMethodParameter : app . nodeQuery ( SchemaMethodParameter . class ) . getAsList ( ) ) { app . delete ( schemaMethodParameter ) ; } for ( final SchemaProperty schemaProperty : app . nodeQuery ( SchemaProperty . class ) . getAsList ( ) ) { app . delete ( schemaProperty ) ; } for ( final SchemaView schemaView : app . nodeQuery ( SchemaView . class ) . getAsList ( ) ) { app . delete ( schemaView ) ; } newSchema . createDatabaseSchema ( app , JsonSchema . ImportMode . replace ) ; tx . success ( ) ; } } | Replaces the current Structr schema with the given new schema . This method is the reverse of createFromDatabase above . |
34,981 | public static void extendDatabaseSchema ( final App app , final JsonSchema newSchema ) throws FrameworkException , URISyntaxException { try ( final Tx tx = app . tx ( ) ) { newSchema . createDatabaseSchema ( app , JsonSchema . ImportMode . extend ) ; tx . success ( ) ; } } | Extend the current Structr schema by the elements contained in the given new schema . |
34,982 | public static char eatPercentage ( String a , int [ ] n ) { if ( ! a . startsWith ( "%" ) || a . length ( ) < 3 ) { n [ 0 ] = 0 ; return ( ( char ) 0 ) ; } char c ; try { c = ( char ) Integer . parseInt ( a . substring ( 1 , 3 ) , 16 ) ; } catch ( Exception e ) { n [ 0 ] = - 1 ; return ( ( char ) 0 ) ; } int len = Utf8Length ( c ) ; n [ 0 ] = 3 ; if ( len <= 1 ) return ( c ) ; String dec = "" + c ; for ( int i = 1 ; i < len ; i ++ ) { try { dec += ( char ) Integer . parseInt ( a . substring ( 1 + i * 3 , 3 + i * 3 ) , 16 ) ; } catch ( Exception e ) { return ( c ) ; } } int [ ] eatLength = new int [ 1 ] ; char utf8 = eatUtf8 ( dec , eatLength ) ; if ( eatLength [ 0 ] != len ) return ( c ) ; n [ 0 ] = len * 3 ; return ( utf8 ) ; } | Eats a String of the form %xx from a string where xx is a hexadecimal code . If xx is a UTF8 code start tries to complete the UTF8 - code and decodes it . |
34,983 | public static char eatAmpersand ( String a , int [ ] n ) { n [ 0 ] = 0 ; if ( ! a . startsWith ( "&" ) ) return ( ( char ) 0 ) ; while ( n [ 0 ] < a . length ( ) && ! Character . isSpaceChar ( a . charAt ( n [ 0 ] ) ) && a . charAt ( n [ 0 ] ) != ';' ) n [ 0 ] ++ ; if ( n [ 0 ] <= 1 ) { n [ 0 ] = - 1 ; return ( ( char ) 0 ) ; } if ( n [ 0 ] < a . length ( ) && a . charAt ( n [ 0 ] ) == ';' ) { a = a . substring ( 1 , n [ 0 ] ) ; n [ 0 ] ++ ; } else { a = a . substring ( 1 , n [ 0 ] ) ; } if ( a . startsWith ( "#x" ) ) { try { return ( ( char ) Integer . parseInt ( a . substring ( 2 ) , 16 ) ) ; } catch ( Exception e ) { n [ 0 ] = - 1 ; return ( ( char ) 0 ) ; } } if ( a . startsWith ( "#" ) ) { try { return ( ( char ) Integer . parseInt ( a . substring ( 1 ) ) ) ; } catch ( Exception e ) { n [ 0 ] = - 1 ; return ( ( char ) 0 ) ; } } if ( ampersandMap . get ( a ) != null ) return ( ampersandMap . get ( a ) ) ; else if ( ampersandMap . get ( a . toLowerCase ( ) ) != null ) return ( ampersandMap . get ( a . toLowerCase ( ) ) ) ; n [ 0 ] = - 1 ; return ( ( char ) 0 ) ; } | Eats an HTML ampersand code from a String |
34,984 | public static char eatUtf8 ( String a , int [ ] n ) { if ( a . length ( ) == 0 ) { n [ 0 ] = 0 ; return ( ( char ) 0 ) ; } n [ 0 ] = Utf8Length ( a . charAt ( 0 ) ) ; if ( a . length ( ) >= n [ 0 ] ) { switch ( n [ 0 ] ) { case 1 : return ( a . charAt ( 0 ) ) ; case 2 : if ( ( a . charAt ( 1 ) & 0xC0 ) != 0x80 ) break ; return ( ( char ) ( ( ( a . charAt ( 0 ) & 0x1F ) << 6 ) + ( a . charAt ( 1 ) & 0x3F ) ) ) ; case 3 : if ( ( a . charAt ( 1 ) & 0xC0 ) != 0x80 || ( a . charAt ( 2 ) & 0xC0 ) != 0x80 ) break ; return ( ( char ) ( ( ( a . charAt ( 0 ) & 0x0F ) << 12 ) + ( ( a . charAt ( 1 ) & 0x3F ) << 6 ) + ( ( a . charAt ( 2 ) & 0x3F ) ) ) ) ; case 4 : if ( ( a . charAt ( 1 ) & 0xC0 ) != 0x80 || ( a . charAt ( 2 ) & 0xC0 ) != 0x80 || ( a . charAt ( 3 ) & 0xC0 ) != 0x80 ) break ; return ( ( char ) ( ( ( a . charAt ( 0 ) & 0x07 ) << 18 ) + ( ( a . charAt ( 1 ) & 0x3F ) << 12 ) + ( ( a . charAt ( 2 ) & 0x3F ) << 6 ) + ( ( a . charAt ( 3 ) & 0x3F ) ) ) ) ; } } n [ 0 ] = - 1 ; return ( ( char ) 0 ) ; } | Eats a UTF8 code from a String . There is also a built - in way in Java that converts UTF8 to characters and back but it does not work with all characters . |
34,985 | public static String decodeUTF8 ( String s ) { StringBuilder result = new StringBuilder ( ) ; int [ ] eatLength = new int [ 1 ] ; while ( s . length ( ) != 0 ) { char c = eatUtf8 ( s , eatLength ) ; if ( eatLength [ 0 ] != - 1 ) { result . append ( c ) ; s = s . substring ( eatLength [ 0 ] ) ; } else { result . append ( s . charAt ( 0 ) ) ; s = s . substring ( 1 ) ; } } return ( result . toString ( ) ) ; } | Decodes all UTF8 characters in the string |
34,986 | public static String decodePercentage ( String s ) { StringBuilder result = new StringBuilder ( ) ; int [ ] eatLength = new int [ 1 ] ; while ( s . length ( ) != 0 ) { char c = eatPercentage ( s , eatLength ) ; if ( eatLength [ 0 ] > 1 ) { result . append ( c ) ; s = s . substring ( eatLength [ 0 ] ) ; } else { result . append ( s . charAt ( 0 ) ) ; s = s . substring ( 1 ) ; } } return ( result . toString ( ) ) ; } | Decodes all percentage characters in the string |
34,987 | public static String decodeAmpersand ( String s ) { if ( s == null || s . indexOf ( '&' ) == - 1 ) return ( s ) ; StringBuilder result = new StringBuilder ( ) ; int [ ] eatLength = new int [ 1 ] ; while ( s . length ( ) != 0 ) { char c = eatAmpersand ( s , eatLength ) ; if ( eatLength [ 0 ] > 1 ) { result . append ( c ) ; s = s . substring ( eatLength [ 0 ] ) ; } else { result . append ( s . charAt ( 0 ) ) ; s = s . substring ( 1 ) ; } } return ( result . toString ( ) ) ; } | Decodes all ampersand sequences in the string |
34,988 | public static String decodeBackslash ( String s ) { if ( s == null || s . indexOf ( '\\' ) == - 1 ) return ( s ) ; StringBuilder result = new StringBuilder ( ) ; int [ ] eatLength = new int [ 1 ] ; while ( s . length ( ) != 0 ) { char c = eatBackslash ( s , eatLength ) ; if ( eatLength [ 0 ] > 1 ) { result . append ( c ) ; s = s . substring ( eatLength [ 0 ] ) ; } else { result . append ( s . charAt ( 0 ) ) ; s = s . substring ( 1 ) ; } } return ( result . toString ( ) ) ; } | Decodes all backslash characters in the string |
34,989 | public static String encodeBackslash ( CharSequence s , Legal legal ) { StringBuilder b = new StringBuilder ( ( int ) ( s . length ( ) * 1.5 ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( legal . isLegal ( s . charAt ( i ) ) ) { b . append ( s . charAt ( i ) ) ; } else { if ( charToBackslash . containsKey ( s . charAt ( i ) ) ) { b . append ( charToBackslash . get ( s . charAt ( i ) ) ) ; continue ; } b . append ( "\\u" ) ; String hex = Integer . toHexString ( s . charAt ( i ) ) ; for ( int j = 0 ; j < 4 - hex . length ( ) ; j ++ ) b . append ( '0' ) ; b . append ( hex ) ; } } return ( b . toString ( ) ) ; } | Encodes with backslash all illegal characters |
34,990 | public static char eatBackslash ( String a , int [ ] n ) { if ( ! a . startsWith ( "\\" ) ) { n [ 0 ] = 0 ; return ( ( char ) 0 ) ; } if ( a . startsWith ( "\\u" ) ) { try { n [ 0 ] = 6 ; return ( ( char ) Integer . parseInt ( a . substring ( 2 , 6 ) , 16 ) ) ; } catch ( Exception e ) { n [ 0 ] = - 1 ; return ( ( char ) 0 ) ; } } if ( a . startsWith ( "\\uu" ) ) { try { n [ 0 ] = 7 ; return ( ( char ) Integer . parseInt ( a . substring ( 3 , 7 ) , 16 ) ) ; } catch ( Exception e ) { n [ 0 ] = - 1 ; return ( ( char ) 0 ) ; } } if ( a . startsWith ( "\\b" ) ) { n [ 0 ] = 2 ; return ( ( char ) 8 ) ; } if ( a . startsWith ( "\\t" ) ) { n [ 0 ] = 2 ; return ( ( char ) 9 ) ; } if ( a . startsWith ( "\\n" ) ) { n [ 0 ] = 2 ; return ( ( char ) 10 ) ; } if ( a . startsWith ( "\\f" ) ) { n [ 0 ] = 2 ; return ( ( char ) 12 ) ; } if ( a . startsWith ( "\\r" ) ) { n [ 0 ] = 2 ; return ( ( char ) 13 ) ; } if ( a . startsWith ( "\\\\" ) ) { n [ 0 ] = 2 ; return ( '\\' ) ; } if ( a . startsWith ( "\\\"" ) ) { n [ 0 ] = 2 ; return ( '"' ) ; } if ( a . startsWith ( "\\'" ) ) { n [ 0 ] = 2 ; return ( '\'' ) ; } n [ 0 ] = 1 ; while ( n [ 0 ] < a . length ( ) && a . charAt ( n [ 0 ] ) >= '0' && a . charAt ( n [ 0 ] ) <= '8' ) n [ 0 ] ++ ; if ( n [ 0 ] == 1 ) { n [ 0 ] = 0 ; return ( ( char ) 0 ) ; } try { return ( ( char ) Integer . parseInt ( a . substring ( 1 , n [ 0 ] ) , 8 ) ) ; } catch ( Exception e ) { } n [ 0 ] = - 1 ; return ( ( char ) 0 ) ; } | Eats a backslash sequence from a String |
34,991 | public static String decode ( String s ) { StringBuilder b = new StringBuilder ( ) ; int [ ] eatLength = new int [ 1 ] ; while ( s . length ( ) > 0 ) { char c = eatPercentage ( s , eatLength ) ; if ( eatLength [ 0 ] <= 0 ) { c = eatAmpersand ( s , eatLength ) ; if ( eatLength [ 0 ] <= 0 ) { c = eatBackslash ( s , eatLength ) ; if ( eatLength [ 0 ] <= 0 ) { c = eatUtf8 ( s , eatLength ) ; if ( eatLength [ 0 ] <= 0 ) { c = s . charAt ( 0 ) ; eatLength [ 0 ] = 1 ; } } } } b . append ( c ) ; s = s . substring ( eatLength [ 0 ] ) ; } return ( b . toString ( ) ) ; } | Replaces all codes in a String by the 16 bit Unicode characters |
34,992 | public static String encodeXmlAttribute ( String str ) { if ( str == null ) return null ; int len = str . length ( ) ; if ( len == 0 ) return str ; StringBuffer encoded = new StringBuffer ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = str . charAt ( i ) ; if ( c == '<' ) encoded . append ( "<" ) ; else if ( c == '\"' ) encoded . append ( """ ) ; else if ( c == '>' ) encoded . append ( ">" ) ; else if ( c == '\'' ) encoded . append ( "'" ) ; else if ( c == '&' ) encoded . append ( "&" ) ; else encoded . append ( c ) ; } return encoded . toString ( ) ; } | Encodes a String with reserved XML characters into a valid xml string for attributes . |
34,993 | public static String encodeURIPathComponent ( String s ) { StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { result . append ( Char . encodeURIPathComponent ( s . charAt ( i ) ) ) ; } return ( result . toString ( ) ) ; } | Encodes a char to percentage code if it is not a path character in the sense of URIs |
34,994 | public static String encodeURIPathComponentXML ( String s ) { StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '&' ) result . append ( Char . encodePercentage ( s . charAt ( i ) ) ) ; else if ( s . charAt ( i ) == '"' ) result . append ( Char . encodePercentage ( s . charAt ( i ) ) ) ; else result . append ( Char . encodeURIPathComponent ( s . charAt ( i ) ) ) ; } return ( result . toString ( ) ) ; } | Encodes a char to percentage code if it is not a path character in the sense of XMLs |
34,995 | public static String encodeUTF8 ( String c ) { StringBuilder r = new StringBuilder ( ) ; for ( int i = 0 ; i < c . length ( ) ; i ++ ) { r . append ( encodeUTF8 ( c . charAt ( i ) ) ) ; } return ( r . toString ( ) ) ; } | Encodes a String to UTF8 |
34,996 | public static String normalize ( String s ) { StringBuilder b = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) b . append ( normalize ( s . charAt ( i ) ) ) ; return ( b . toString ( ) ) ; } | Normalizes all chars in a String to characters 0x20 - 0x7F |
34,997 | public static String cutLast ( String s ) { return ( s . length ( ) == 0 ? "" : s . substring ( 0 , s . length ( ) - 1 ) ) ; } | Returns the String without the last character |
34,998 | public static String hexAll ( String s ) { StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { result . append ( Integer . toHexString ( s . charAt ( i ) ) . toUpperCase ( ) ) . append ( ' ' ) ; } return ( result . toString ( ) ) ; } | Returns the chars of a String in hex |
34,999 | public static String lowCaseFirst ( String s ) { if ( s == null || s . length ( ) == 0 ) return ( s ) ; return ( Character . toLowerCase ( s . charAt ( 0 ) ) + s . substring ( 1 ) ) ; } | Lowcases the first character in a String |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.