idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
6,800
private String getResourceId ( String response , String resourceResponseAction , String resourceIdXpath , String resourceIdExceptionMessage ) throws ParserConfigurationException , SAXException , XPathExpressionException , IOException { if ( WSManUtils . isSpecificResponseAction ( response , resourceResponseAction ) ) { String shellId = XMLUtils . parseXml ( response , resourceIdXpath ) ; if ( StringUtils . isNotBlank ( shellId ) ) { return shellId ; } else { throw new RuntimeException ( resourceIdExceptionMessage ) ; } } else if ( WSManUtils . isFaultResponse ( response ) ) { throw new RuntimeException ( WSManUtils . getResponseFault ( response ) ) ; } else { throw new RuntimeException ( UNEXPECTED_SERVICE_RESPONSE + response ) ; } }
This method retrieves the resource id from the create resource request response and throws the appropriate exceptions in case of failure .
6,801
private void deleteShell ( HttpClientService csHttpClient , HttpClientInputs httpClientInputs , String shellId , WSManRequestInputs wsManRequestInputs ) throws RuntimeException , IOException , URISyntaxException , TransformerException , XPathExpressionException , SAXException , ParserConfigurationException { String documentStr = ResourceLoader . loadAsString ( DELETE_SHELL_REQUEST_XML ) ; documentStr = createDeleteShellRequestBody ( documentStr , httpClientInputs . getUrl ( ) , shellId , String . valueOf ( wsManRequestInputs . getMaxEnvelopeSize ( ) ) , wsManRequestInputs . getWinrmLocale ( ) , String . valueOf ( wsManRequestInputs . getOperationTimeout ( ) ) ) ; Map < String , String > deleteShellResult = executeRequestWithBody ( csHttpClient , httpClientInputs , documentStr ) ; if ( WSManUtils . isSpecificResponseAction ( deleteShellResult . get ( RETURN_RESULT ) , DELETE_RESPONSE_ACTION ) ) { return ; } else if ( WSManUtils . isFaultResponse ( deleteShellResult . get ( RETURN_RESULT ) ) ) { throw new RuntimeException ( WSManUtils . getResponseFault ( deleteShellResult . get ( RETURN_RESULT ) ) ) ; } else { throw new RuntimeException ( UNEXPECTED_SERVICE_RESPONSE + deleteShellResult . get ( RETURN_RESULT ) ) ; } }
Deletes the remote shell .
6,802
private Map < String , String > processCommandExecutionResponse ( Map < String , String > receiveResult ) throws ParserConfigurationException , SAXException , XPathExpressionException , IOException { Map < String , String > scriptResults = new HashMap < > ( ) ; scriptResults . put ( RETURN_RESULT , buildResultFromResponseStreams ( receiveResult . get ( RETURN_RESULT ) , OutputStream . STDOUT ) ) ; scriptResults . put ( Constants . OutputNames . STDERR , buildResultFromResponseStreams ( receiveResult . get ( RETURN_RESULT ) , OutputStream . STDERR ) ) ; scriptResults . put ( Constants . OutputNames . SCRIPT_EXIT_CODE , WSManUtils . getScriptExitCode ( receiveResult . get ( RETURN_RESULT ) ) ) ; return scriptResults ; }
This method separates the stdout and stderr response streams from the received execution response .
6,803
private String buildResultFromResponseStreams ( String response , OutputStream outputStream ) throws ParserConfigurationException , SAXException , XPathExpressionException , IOException { StringBuilder commandResult = new StringBuilder ( ) ; int noOfStreams = WSManUtils . countStreamElements ( response ) ; for ( int streamNo = 0 ; streamNo < noOfStreams ; streamNo ++ ) { String stream = XMLUtils . parseXml ( response , String . format ( RECEIVE_RESPONSE_XPATH , outputStream . getValue ( ) , streamNo ) ) ; if ( ! "DQo=" . equals ( stream ) ) { commandResult . append ( EncoderDecoder . decodeBase64String ( stream ) ) ; } } return commandResult . toString ( ) ; }
Constructs the executed command response from multiple streams of data containing the encoded result of the execution .
6,804
private boolean executionIsTimedOut ( long aStartTime , int aTimeout ) { if ( aTimeout != 0 ) { long now = System . currentTimeMillis ( ) / 1000 ; if ( ( now - aStartTime ) >= aTimeout ) { return true ; } } return false ; }
Check whether or not the command execution reach the timeout value .
6,805
public static String [ ] toArrayWithEscaped ( final String stringArray , final String delimiter ) { if ( StringUtils . isEmpty ( stringArray ) ) { return new String [ 0 ] ; } return StringUtils . splitByWholeSeparatorPreserveAllTokens ( stringArray , delimiter ) ; }
Splits the stringArray by the delimiter into an array of strings without ignoring the escaped delimiters
6,806
public static String [ ] toArray ( final String stringArray , final String delimiter ) { if ( StringUtils . isEmpty ( stringArray ) ) { return new String [ 0 ] ; } final String regex = "(?<!\\\\)" + Pattern . quote ( delimiter ) ; return stringArray . split ( regex ) ; }
Splits the stringArray by the delimiter into an array of strings ignoring the escaped delimiters
6,807
public static List < String > toListWithEscaped ( final String stringList , final String delimiter ) { return new ArrayList < > ( Arrays . asList ( toArrayWithEscaped ( stringList , delimiter ) ) ) ; }
Splits the stringList by the delimiter into a List of strings without ignoring the escaped delimiters
6,808
public static List < String > toList ( final String stringList , final String delimiter ) { return new ArrayList < > ( Arrays . asList ( toArray ( stringList , delimiter ) ) ) ; }
Splits the stringList by the delimiter into a List of strings ignoring the escaped delimiters
6,809
public static synchronized RequestBundle get ( SlingHttpServletRequest request ) { RequestBundle instance = ( RequestBundle ) request . getAttribute ( ATTRIBUTE_KEY ) ; if ( instance == null ) { instance = new RequestBundle ( request ) ; request . setAttribute ( ATTRIBUTE_KEY , instance ) ; } return instance ; }
returns the requests instance
6,810
public static String getPrimaryType ( Resource resource ) { String result = null ; if ( resource != null ) { if ( resource instanceof JcrResource ) { result = ( ( JcrResource ) resource ) . getPrimaryType ( ) ; } else { Node node = resource . adaptTo ( Node . class ) ; if ( node != null ) { try { NodeType type = node . getPrimaryNodeType ( ) ; if ( type != null ) { result = type . getName ( ) ; } } catch ( RepositoryException ignore ) { } } if ( result == null ) { ValueMap values = resource . adaptTo ( ValueMap . class ) ; if ( values != null ) { result = values . get ( JcrConstants . JCR_PRIMARYTYPE , ( String ) null ) ; } } } } return result ; }
retrieves the primary type of the resources node
6,811
public static Resource getOrCreateChild ( Resource resource , String relPath , String primaryTypes ) throws RepositoryException { Resource child = null ; if ( resource != null ) { ResourceResolver resolver = resource . getResourceResolver ( ) ; String path = resource . getPath ( ) ; while ( relPath . startsWith ( "/" ) ) { relPath = relPath . substring ( 1 ) ; } if ( StringUtils . isNotBlank ( relPath ) ) { path += "/" + relPath ; } child = getOrCreateResource ( resolver , path , primaryTypes ) ; } return child ; }
Retrieves the resources child resource creates this child if not existing .
6,812
public static boolean isFile ( Resource resource ) { Node node = resource . adaptTo ( Node . class ) ; if ( node != null ) { try { NodeType type = node . getPrimaryNodeType ( ) ; if ( type != null ) { String typeName = type . getName ( ) ; switch ( typeName ) { case TYPE_FILE : return true ; case TYPE_RESOURCE : case TYPE_UNSTRUCTURED : try { Property mimeType = node . getProperty ( PROP_MIME_TYPE ) ; if ( mimeType != null && StringUtils . isNotBlank ( mimeType . getString ( ) ) ) { node . getProperty ( ResourceUtil . PROP_DATA ) ; return true ; } } catch ( PathNotFoundException pnfex ) { } break ; } } } catch ( RepositoryException e ) { LOG . error ( e . getMessage ( ) , e ) ; } } return false ; }
Returns true is this resource represents a file .
6,813
public void initialize ( BeanContext context ) { Resource resource = ConsoleUtil . getConsoleResource ( context ) ; initialize ( context , ResourceHandle . use ( resource ) ) ; }
extract the resource referenced to display in the browsers view as the components resource
6,814
protected void renderTagEnd ( ) { try { if ( StringUtils . isNotEmpty ( this . output ) ) { this . output = toString ( this . escape ? escape ( this . output ) : this . output ) ; JspWriter writer = this . pageContext . getOut ( ) ; boolean renderTag = renderTag ( ) && ( StringUtils . isNotBlank ( this . tagName ) || StringUtils . isNotBlank ( getClasses ( ) ) ) ; if ( renderTag ) { super . renderTagStart ( ) ; } writer . write ( this . output ) ; if ( renderTag ) { super . renderTagEnd ( ) ; } } } catch ( IOException ioex ) { LOG . error ( ioex . getMessage ( ) , ioex ) ; } }
is rendering the text and a tag around if tagName is set or CSS classes are specified
6,815
protected Object escape ( Object value ) { EscapeFunction function = ESCAPE_FUNCTION_MAP . get ( this . type ) ; return function != null ? function . escape ( TagUtil . getRequest ( this . pageContext ) , value ) : CpnlElFunctions . text ( toString ( value ) ) ; }
the extension hook for the various types of encoding ; must work with Object values to ensure that non String values can be used as is
6,816
public static void exportJson ( JsonWriter writer , Resource resource ) throws RepositoryException , IOException { exportJson ( writer , resource , MappingRules . getDefaultMappingRules ( ) ) ; }
Writes a resources JSON view to a writer using the default application rules for filtering .
6,817
public static JsonProperty parseJsonProperty ( JsonReader reader , String name ) throws RepositoryException , IOException { JsonToken token = reader . peek ( ) ; JsonProperty property = new JsonProperty ( ) ; property . name = name ; switch ( token ) { case BOOLEAN : property . type = PropertyType . nameFromValue ( PropertyType . BOOLEAN ) ; property . value = reader . nextBoolean ( ) ; break ; case NUMBER : property . type = PropertyType . nameFromValue ( PropertyType . LONG ) ; property . value = reader . nextLong ( ) ; break ; case STRING : parseJsonString ( reader , property ) ; break ; case NULL : reader . nextNull ( ) ; break ; } return property ; }
Parses a single property of the first element of an array and returns the result as a JSON POJO object .
6,818
public static String getValueString ( Object value , int type , MappingRules mapping ) { String string = value . toString ( ) ; if ( type != PropertyType . STRING && mapping . propertyFormat . embedType && mapping . propertyFormat . scope == MappingRules . PropertyFormat . Scope . value ) { string = "{" + PropertyType . nameFromValue ( type ) + "}" + string ; } return string ; }
Embeds the property type in the string value if the formats scope is value .
6,819
public static Value makeJcrValue ( Node node , int type , Object object , MappingRules mapping ) throws PropertyValueFormatException , RepositoryException { Session session = node . getSession ( ) ; ValueFactory factory = session . getValueFactory ( ) ; Value value = null ; if ( object != null ) { switch ( type ) { case PropertyType . BINARY : if ( mapping . propertyFormat . binary != MappingRules . PropertyFormat . Binary . skip ) { InputStream input = null ; if ( object instanceof InputStream ) { input = ( InputStream ) object ; } else if ( object instanceof String ) { if ( mapping . propertyFormat . binary == MappingRules . PropertyFormat . Binary . base64 ) { byte [ ] decoded = Base64 . decodeBase64 ( ( String ) object ) ; input = new ByteArrayInputStream ( decoded ) ; } } if ( input != null ) { Binary binary = factory . createBinary ( input ) ; value = factory . createValue ( binary ) ; } } break ; case PropertyType . BOOLEAN : value = factory . createValue ( object instanceof Boolean ? ( Boolean ) object : Boolean . parseBoolean ( object . toString ( ) ) ) ; break ; case PropertyType . DATE : Date date = object instanceof Date ? ( Date ) object : null ; if ( date == null ) { String string = object . toString ( ) ; date = mapping . dateParser . parse ( string ) ; } if ( date != null ) { GregorianCalendar cal = new GregorianCalendar ( ) ; cal . setTime ( date ) ; value = factory . createValue ( cal ) ; } else { throw new PropertyValueFormatException ( "invalid date/time value: " + object ) ; } break ; case PropertyType . DECIMAL : value = factory . createValue ( object instanceof BigDecimal ? ( BigDecimal ) object : new BigDecimal ( object . toString ( ) ) ) ; break ; case PropertyType . DOUBLE : value = factory . createValue ( object instanceof Double ? ( Double ) object : Double . parseDouble ( object . toString ( ) ) ) ; break ; case PropertyType . LONG : value = factory . createValue ( object instanceof Long ? ( Long ) object : Long . parseLong ( object . toString ( ) ) ) ; break ; case PropertyType . REFERENCE : case PropertyType . WEAKREFERENCE : final Node refNode = session . getNodeByIdentifier ( object . toString ( ) ) ; final String identifier = refNode . getIdentifier ( ) ; value = factory . createValue ( identifier , type ) ; break ; case PropertyType . NAME : case PropertyType . PATH : case PropertyType . STRING : case PropertyType . URI : value = factory . createValue ( object . toString ( ) , type ) ; break ; case PropertyType . UNDEFINED : break ; } } return value ; }
Create a JCR value from string value for the designated JCR type .
6,820
public static void setupGroupsAndUsers ( InstallContext ctx , Map < String , List < String > > groups , Map < String , List < String > > systemUsers , Map < String , List < String > > users ) throws PackageException { UserManagementService userManagementService = getService ( UserManagementService . class ) ; try { JackrabbitSession session = ( JackrabbitSession ) ctx . getSession ( ) ; UserManager userManager = session . getUserManager ( ) ; if ( groups != null ) { for ( Map . Entry < String , List < String > > entry : groups . entrySet ( ) ) { Group group = userManagementService . getOrCreateGroup ( session , userManager , entry . getKey ( ) ) ; if ( group != null ) { for ( String memberName : entry . getValue ( ) ) { userManagementService . assignToGroup ( session , userManager , memberName , group ) ; } } } session . save ( ) ; } if ( systemUsers != null ) { for ( Map . Entry < String , List < String > > entry : systemUsers . entrySet ( ) ) { Authorizable user = userManagementService . getOrCreateUser ( session , userManager , entry . getKey ( ) , true ) ; if ( user != null ) { for ( String groupName : entry . getValue ( ) ) { userManagementService . assignToGroup ( session , userManager , user , groupName ) ; } } } session . save ( ) ; } if ( users != null ) { for ( Map . Entry < String , List < String > > entry : users . entrySet ( ) ) { Authorizable user = userManagementService . getOrCreateUser ( session , userManager , entry . getKey ( ) , false ) ; if ( user != null ) { for ( String groupName : entry . getValue ( ) ) { userManagementService . assignToGroup ( session , userManager , user , groupName ) ; } } } session . save ( ) ; } } catch ( RepositoryException | RuntimeException rex ) { LOG . error ( rex . getMessage ( ) , rex ) ; throw new PackageException ( rex ) ; } }
Creates or updates a set of groups users and system users
6,821
@ SuppressWarnings ( "unchecked" ) public static < T > T getService ( Class < T > type ) { Bundle serviceBundle = FrameworkUtil . getBundle ( type ) ; BundleContext serviceBundleContext = serviceBundle . getBundleContext ( ) ; ServiceReference serviceReference = serviceBundleContext . getServiceReference ( type . getName ( ) ) ; return ( T ) serviceBundleContext . getService ( serviceReference ) ; }
retrieve a service during setup
6,822
protected void alreadyProcessed ( ClientlibRef ref , VisitorMode mode , ClientlibResourceFolder folder ) { if ( mode == EMBEDDED ) { LOG . warn ( "Trying to embed already embedded / dependency {} again at {}" , ref , folder ) ; } }
Warns about everything that should be embedded but is already processed and not in this
6,823
public Authorizable getOrCreateUser ( JackrabbitSession session , UserManager userManager , String path , boolean systemUser ) throws RepositoryException { String [ ] pathAndName = pathAndName ( path ) ; Authorizable user = userManager . getAuthorizable ( pathAndName [ 1 ] ) ; LOG . debug ( "user.check: " + pathAndName [ 1 ] + " - " + user ) ; if ( user == null ) { LOG . info ( "user.create: " + pathAndName [ 1 ] ) ; Principal principal = new NamePrincipal ( pathAndName [ 1 ] ) ; if ( systemUser ) { try { Method createSystemUser = userManager . getClass ( ) . getMethod ( "createSystemUser" , String . class , String . class ) ; user = ( User ) createSystemUser . invoke ( userManager , pathAndName [ 1 ] , pathAndName [ 0 ] ) ; } catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException ex ) { LOG . error ( ex . toString ( ) ) ; } } else { user = userManager . createUser ( pathAndName [ 1 ] , pathAndName [ 1 ] , principal , pathAndName [ 0 ] ) ; } } return user ; }
Retrieves a user by its name ; if the user doesn t exist the user will be created .
6,824
public Group getOrCreateGroup ( JackrabbitSession session , UserManager userManager , String path ) throws RepositoryException { String [ ] pathAndName = pathAndName ( path ) ; Group group = ( Group ) userManager . getAuthorizable ( pathAndName [ 1 ] ) ; LOG . debug ( "group.check: " + pathAndName [ 1 ] + " - " + group ) ; if ( group == null ) { LOG . info ( "group.create: " + pathAndName [ 1 ] ) ; group = userManager . createGroup ( new NamePrincipal ( pathAndName [ 1 ] ) , pathAndName [ 0 ] ) ; } return group ; }
Retrieves a group by their name ; if the group doesn t exist the group will be created .
6,825
public boolean isSatisfiedby ( ClientlibLink link ) { if ( ! type . equals ( link . type ) ) return false ; if ( isCategory ( ) ) { if ( ! link . isCategory ( ) || ! category . equals ( link . path ) ) return false ; } else if ( isExternalUri ( ) ) { if ( ! link . isExternalUri ( ) || ! externalUri . equals ( link . path ) ) return false ; } else { if ( link . isCategory ( ) || link . isExternalUri ( ) || ! pattern . matcher ( link . path ) . matches ( ) ) return false ; } if ( ! properties . equals ( link . properties ) ) return false ; return true ; }
Checks whether the link matches this up to version patterns .
6,826
public boolean isSatisfiedby ( Collection < ClientlibLink > links ) { for ( ClientlibLink link : links ) if ( isSatisfiedby ( link ) ) return true ; return false ; }
Checks whether one of the links matches this up to version patterns .
6,827
public static String getAbsoluteUrl ( SlingHttpServletRequest request , String url ) { if ( ! isExternalUrl ( url ) && url . startsWith ( "/" ) ) { String scheme = request . getScheme ( ) . toLowerCase ( ) ; url = scheme + "://" + getAuthority ( request ) + url ; } return url ; }
Makes a URL already built external ; the url should be built by the getUrl method .
6,828
public static Resource resolveUrl ( SlingHttpServletRequest request , String url ) { return request . getResourceResolver ( ) . getResource ( url ) ; }
Returns the resource referenced by an URL .
6,829
public static String getFinalTarget ( Resource resource ) throws RedirectLoopException { ResourceHandle handle = ResourceHandle . use ( resource ) ; String finalTarget = getFinalTarget ( handle , new ArrayList < String > ( ) ) ; return finalTarget ; }
Retrieves the target for a resource if there are redirects declared .
6,830
protected static String getFinalTarget ( ResourceHandle resource , List < String > trace ) throws RedirectLoopException { String finalTarget = null ; if ( resource . isValid ( ) ) { String path = resource . getPath ( ) ; if ( trace . contains ( path ) ) { throw new RedirectLoopException ( trace , path ) ; } String redirect = resource . getProperty ( PROP_TARGET ) ; if ( StringUtils . isBlank ( redirect ) ) { redirect = resource . getProperty ( PROP_REDIRECT ) ; } if ( StringUtils . isBlank ( redirect ) ) { ResourceHandle contentResource = resource . getContentResource ( ) ; if ( resource != contentResource ) { redirect = contentResource . getProperty ( PROP_TARGET ) ; if ( StringUtils . isBlank ( redirect ) ) { redirect = contentResource . getProperty ( PROP_REDIRECT ) ; } } } if ( StringUtils . isNotBlank ( redirect ) ) { trace . add ( path ) ; finalTarget = redirect ; if ( ! URL_PATTERN . matcher ( finalTarget ) . matches ( ) ) { ResourceResolver resolver = resource . getResourceResolver ( ) ; Resource targetResource = resolver . getResource ( finalTarget ) ; if ( targetResource != null ) { String target = getFinalTarget ( ResourceHandle . use ( targetResource ) , trace ) ; if ( StringUtils . isNotBlank ( target ) ) { finalTarget = target ; } } } } } return finalTarget ; }
Determines the final URL of a link to a resource by traversing along the redirect properties .
6,831
protected boolean checkConsoleAccess ( BeanContext context ) { String consolePath = getConsolePath ( context ) ; if ( StringUtils . isNotBlank ( consolePath ) ) { return context . getResolver ( ) . getResource ( consolePath ) != null ; } return true ; }
Check access rights to the servlets path - is checking ACLs of the console path
6,832
public ClientlibLink makeLink ( ) { return new ClientlibLink ( getType ( ) , ClientlibLink . Kind . CLIENTLIB , resource . getPath ( ) , null ) ; }
A link that matches this .
6,833
public static String child ( Resource base , String path ) { Resource child = base . getChild ( path ) ; return child != null ? child . getPath ( ) : path ; }
Returns the repository path of a child of a resource .
6,834
public static String map ( SlingHttpServletRequest request , String value ) { StringBuilder result = new StringBuilder ( ) ; Matcher matcher = HREF_PATTERN . matcher ( value ) ; int len = value . length ( ) ; int pos = 0 ; while ( matcher . find ( pos ) ) { String unmapped = matcher . group ( 3 ) ; String mapped = url ( request , unmapped ) ; result . append ( value , pos , matcher . start ( ) ) ; result . append ( matcher . group ( 1 ) ) ; result . append ( mapped ) ; result . append ( matcher . group ( 4 ) ) ; pos = matcher . end ( ) ; } if ( pos >= 0 && pos < len ) { result . append ( value , pos , len ) ; } return result . toString ( ) ; }
Replaces all href attribute values found in the text value by the resolver mapped value .
6,835
public static String path ( String value ) { return value != null ? LinkUtil . encodePath ( value ) : null ; }
Returns the encoded path of a of a repository path .
6,836
public static Format getFormatter ( final Locale locale , final String format , final Class < ? > ... type ) { Format formatter = null ; Pattern TEXT_FORMAT_STRING = Pattern . compile ( "^\\{([^}]+)}(.+)$" ) ; Matcher matcher = TEXT_FORMAT_STRING . matcher ( format ) ; if ( matcher . matches ( ) ) { switch ( matcher . group ( 1 ) ) { case "Message" : formatter = new MessageFormat ( matcher . group ( 2 ) , locale ) ; break ; case "Date" : formatter = new SimpleDateFormat ( matcher . group ( 2 ) , locale ) ; break ; case "String" : formatter = new FormatterFormat ( matcher . group ( 2 ) , locale ) ; break ; default : case "Log" : formatter = new LoggerFormat ( matcher . group ( 2 ) ) ; break ; } } else { if ( type != null && type . length == 1 && type [ 0 ] != null && ( Calendar . class . isAssignableFrom ( type [ 0 ] ) || Date . class . isAssignableFrom ( type [ 0 ] ) ) ) { formatter = new SimpleDateFormat ( format , locale ) ; } else { formatter = new LoggerFormat ( format ) ; } } return formatter ; }
Creates the formatter for a describing string rule
6,837
public static ResourceHandle use ( Resource resource ) { return resource instanceof ResourceHandle ? ( ( ResourceHandle ) resource ) : new ResourceHandle ( resource ) ; }
The adaptTo like wrapping helper .
6,838
public static boolean isValid ( Resource resource ) { return resource instanceof ResourceHandle ? ( ( ResourceHandle ) resource ) . isValid ( ) : resource != null && resource . getResourceResolver ( ) . getResource ( resource . getPath ( ) ) != null ; }
the universal validation test
6,839
public boolean isValid ( ) { if ( valid == null ) { valid = ( this . resource != null ) ; if ( valid ) { valid = ( getResourceResolver ( ) . getResource ( getPath ( ) ) != null ) ; } } return valid ; }
a resource is valid if not null and resolvable
6,840
public String getId ( ) { if ( id == null ) { if ( isValid ( ) ) { id = getProperty ( ResourceUtil . PROP_UUID ) ; } if ( StringUtils . isBlank ( id ) ) { id = Base64 . encodeBase64String ( getPath ( ) . getBytes ( MappingRules . CHARSET ) ) ; } } return id ; }
Lazy getter for the ID of the resources . The ID is the UUID of the resources node if available otherwise the Base64 encoded path .
6,841
public List < ResourceHandle > getChildrenByType ( final String type ) { final ArrayList < ResourceHandle > children = new ArrayList < > ( ) ; if ( this . isValid ( ) ) { for ( final Resource child : this . resource . getChildren ( ) ) { ResourceHandle handle = ResourceHandle . use ( child ) ; if ( handle . isOfType ( type ) ) { children . add ( handle ) ; } } } return children ; }
retrieves all children of a type
6,842
public String getId ( Node node ) { String id = null ; try { id = node . getIdentifier ( ) ; } catch ( RepositoryException e ) { id = node . toString ( ) ; } return id ; }
Retrieves the nodes id .
6,843
public static String getTitle ( Node node ) { String title = getNodeTitle ( node ) ; if ( StringUtils . isBlank ( title ) ) { try { title = node . getName ( ) ; } catch ( RepositoryException rex ) { LOG . error ( rex . getMessage ( ) , rex ) ; } } return title ; }
Retrieves the title with a fallback to the nodes name .
6,844
private static Manifest getManifest ( final RegisteredResource rsrc ) throws IOException { try ( final InputStream ins = rsrc . getInputStream ( ) ) { if ( ins != null ) { try ( JarInputStream jis = new JarInputStream ( ins ) ) { return jis . getManifest ( ) ; } } else { return null ; } } }
Read the manifest from supplied input stream which is closed before return .
6,845
public static < T > T readValue ( Value value , Class < T > type ) throws RepositoryException { try { if ( null == value ) return null ; if ( type . isAssignableFrom ( value . getClass ( ) ) ) return type . cast ( value ) ; if ( Long . class . equals ( type ) ) return type . cast ( value . getLong ( ) ) ; if ( Integer . class . equals ( type ) ) return type . cast ( value . getLong ( ) ) ; if ( Short . class . equals ( type ) ) return type . cast ( ( short ) value . getLong ( ) ) ; if ( Byte . class . equals ( type ) ) return type . cast ( ( byte ) value . getLong ( ) ) ; if ( Float . class . equals ( type ) ) return type . cast ( ( float ) value . getLong ( ) ) ; if ( Double . class . equals ( type ) ) return type . cast ( value . getDouble ( ) ) ; if ( String . class . equals ( type ) ) return type . cast ( value . getString ( ) ) ; if ( Boolean . class . equals ( type ) ) return type . cast ( value . getBoolean ( ) ) ; if ( java . net . URI . class . equals ( type ) ) return type . cast ( new URI ( value . getString ( ) ) ) ; if ( java . net . URL . class . equals ( type ) ) return type . cast ( new URL ( value . getString ( ) ) ) ; if ( Date . class . equals ( type ) ) return type . cast ( value . getDate ( ) . getTime ( ) ) ; if ( Calendar . class . equals ( type ) ) return type . cast ( value . getDate ( ) ) ; if ( BigDecimal . class . equals ( type ) ) return type . cast ( value . getDecimal ( ) ) ; if ( Binary . class . equals ( type ) ) return type . cast ( value . getBinary ( ) ) ; if ( InputStream . class . equals ( type ) ) return type . cast ( value . getBinary ( ) . getStream ( ) ) ; Class defaultType = DEFAULT_PROPERTY_TYPES . get ( value . getType ( ) ) ; if ( null != defaultType && type . isAssignableFrom ( defaultType ) ) return type . cast ( readValue ( value , defaultType ) ) ; throw new IllegalArgumentException ( "Type " + type + " not supported yet." ) ; } catch ( URISyntaxException | MalformedURLException | RuntimeException e ) { throw new ValueFormatException ( "Can't convert to " + type , e ) ; } }
Reads the value of a property as the given type .
6,846
private static MimeType getParentMimeType ( Resource resource ) { MimeType result = null ; if ( resource != null && ( resource = resource . getParent ( ) ) != null ) { ResourceHandle handle = ResourceHandle . use ( resource ) ; result = getMimeType ( handle . getProperty ( ResourceUtil . PROP_MIME_TYPE , "" ) ) ; if ( result == null ) { String filename = getResourceName ( resource ) ; result = getMimeType ( filename ) ; } } return result ; }
a helper if the resource is a content node an should use its parent as a fallback
6,847
private static MimeType getContentMimeType ( Resource resource ) { MimeType result = null ; if ( resource != null && ( resource = resource . getChild ( ResourceUtil . CONTENT_NODE ) ) != null ) { ResourceHandle handle = ResourceHandle . use ( resource ) ; result = getMimeType ( handle . getProperty ( ResourceUtil . PROP_MIME_TYPE , "" ) ) ; } return result ; }
a helper if the resource has a content node an should use this content as a fallback
6,848
public static MimeType getMimeType ( String value ) { if ( StringUtils . isNotBlank ( value ) ) { try { return getMimeTypes ( ) . forName ( value ) ; } catch ( MimeTypeException e ) { MediaType mediaType = getMediaType ( null , value ) ; if ( mediaType != null ) { try { return getMimeTypes ( ) . forName ( mediaType . toString ( ) ) ; } catch ( MimeTypeException e1 ) { } } } } return null ; }
Retrieves the MimeType object according to a name value
6,849
public void initialize ( BeanContext context , Resource resource ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "initialize (" + context + ", " + resource + ")" ) ; } this . context = context ; this . resource = ResourceHandle . use ( resource ) ; }
This basic initialization sets up the context and resource attributes only all the other attributes are set lazy during their getter calls .
6,850
public ResourceHandle getParent ( String resourceType ) { ResourceHandle result = getResource ( ) ; while ( result . isValid ( ) && ! result . isResourceType ( resourceType ) ) { result = result . getParent ( ) ; } if ( ! result . isValid ( ) ) { result = getParent ( resourceType , getPath ( ) ) ; } return result ; }
Determine a typed parent resource .
6,851
public String getExtension ( ) { String extension = getSlingRequest ( ) . getRequestPathInfo ( ) . getExtension ( ) ; return StringUtils . isBlank ( extension ) ? "" : ( "." + extension ) ; }
Returns the request extension with a leading . if present .
6,852
public boolean isCurrentUserAdmin ( ) throws RepositoryException { boolean isAdmin = false ; final JackrabbitSession session = ( JackrabbitSession ) getSession ( ) ; final UserManager userManager = session . getUserManager ( ) ; Authorizable a = userManager . getAuthorizable ( getRequest ( ) . getUserPrincipal ( ) ) ; if ( a instanceof org . apache . jackrabbit . api . security . user . User ) { isAdmin = ( ( org . apache . jackrabbit . api . security . user . User ) a ) . isAdmin ( ) ; } return isAdmin ; }
Returns true if the current request user is the admin user .
6,853
public < T > Future < T > submit ( Callable < T > callable ) { return executorService . submit ( callable ) ; }
Schedules something for execution in the future .
6,854
public static < T extends Enum > T getExtension ( SlingHttpServletRequest request , T defaultValue ) { String extension = request . getRequestPathInfo ( ) . getExtension ( ) ; if ( extension != null ) { Class type = defaultValue . getClass ( ) ; try { T value = ( T ) T . valueOf ( type , extension . toLowerCase ( ) ) ; return value ; } catch ( IllegalArgumentException iaex ) { } } return defaultValue ; }
Returns the enum value of the requests extension if appropriate otherwise the default value .
6,855
public static < T extends Enum > T getSelector ( SlingHttpServletRequest request , T defaultValue ) { String [ ] selectors = request . getRequestPathInfo ( ) . getSelectors ( ) ; Class type = defaultValue . getClass ( ) ; for ( String selector : selectors ) { try { T value = ( T ) T . valueOf ( type , selector ) ; return value ; } catch ( IllegalArgumentException iaex ) { } } return defaultValue ; }
Returns an enum value from selectors if an appropriate selector can be found otherwise the default value given .
6,856
public static boolean checkSelector ( SlingHttpServletRequest request , String key ) { String [ ] selectors = request . getRequestPathInfo ( ) . getSelectors ( ) ; for ( String selector : selectors ) { if ( selector . equals ( key ) ) { return true ; } } return false ; }
Retrieves a key in the selectors and returns true is the key is present .
6,857
protected com . composum . sling . core . util . ExpressionUtil getExpressionUtil ( ) { if ( expressionUtil == null ) { expressionUtil = new ExpressionUtil ( pageContext ) ; } return expressionUtil ; }
Returns or creates the expressionUtil . Not null .
6,858
public HierarchyScanResult findOriginAndValue ( String name , Class < ? > type ) { Object value ; findEntryPoint ( ) ; String path = getRelativePath ( name ) ; for ( Resource parent = entryPoint ; parent != null ; parent = parent . getParent ( ) ) { ValueMap parentProps = parent . adaptTo ( ValueMap . class ) ; if ( parentProps != null ) { value = parentProps . get ( path , type ) ; if ( value != null ) { return new HierarchyScanResult ( parent , value ) ; } } if ( exitPoint != null && parent . getPath ( ) . equals ( exitPoint . getPath ( ) ) ) { break ; } } return null ; }
Searches the value along the repositories hierarchy by the entry point and path determined before .
6,859
public ClientlibLink withHash ( String newHash ) { return new ClientlibLink ( type , kind , path , properties , newHash ) ; }
Creates a new link with parameters as this except hash .
6,860
public Calendar getLastUpdateTime ( ) { if ( null != lastUpdateTime && lastUpdateTime . after ( Calendar . getInstance ( ) ) ) { LOG . warn ( "Last update time newer than now {} for {}" , lastUpdateTime , owner ) ; return null ; } return lastUpdateTime ; }
Returns the last update time estimated from the file update times and clientlib folder create times . This is only a lower bound for the update time of the client library including its embedded files .
6,861
public static String appendHashSuffix ( String url , String hash ) { if ( null == hash ) return url ; Matcher matcher = FILENAME_PATTERN . matcher ( url ) ; String fname = "" ; if ( matcher . find ( ) ) fname = matcher . group ( 0 ) ; return url + "/" + hash + "/" + fname ; }
Appends a suffix containing the hash code if given . The file name is repeated to satisfy browsers with the correct type and file name though it is not used by the servlet .
6,862
public boolean isClientlibRendered ( ClientlibRef reference ) { for ( ClientlibLink link : renderedClientlibs ) { if ( reference . isSatisfiedby ( link ) ) { LOG . debug ( "already rendered: {} by {}" , reference , link . path ) ; return true ; } } return false ; }
Checks whether a referenced resource or client library is satisfied by an already rendered resource .
6,863
protected Class < ? extends SlingBean > getComponentType ( ) throws ClassNotFoundException { if ( componentType == null ) { String type = getType ( ) ; if ( StringUtils . isNotBlank ( type ) ) { componentType = ( Class < ? extends SlingBean > ) context . getType ( type ) ; } } return componentType ; }
get the content type class object
6,864
protected Object available ( ) throws ClassNotFoundException { Object result = null ; if ( getVar ( ) != null ) { Object value = pageContext . getAttribute ( getVar ( ) , getVarScope ( ) ) ; if ( value instanceof SlingBean ) { Class < ? > type = getComponentType ( ) ; if ( type != null && type . isAssignableFrom ( value . getClass ( ) ) ) { result = value ; } } } return result ; }
Check for an existing instance of the same var and assignable type
6,865
protected SlingBean createComponent ( ) throws ClassNotFoundException , IllegalAccessException , InstantiationException { SlingBean component = null ; Class < ? extends SlingBean > type = getComponentType ( ) ; if ( type != null ) { BeanFactory factoryRule = type . getAnnotation ( BeanFactory . class ) ; if ( factoryRule != null ) { SlingBeanFactory factory = context . getService ( factoryRule . serviceClass ( ) ) ; if ( factory != null ) { return factory . createBean ( context , getModelResource ( context ) , type ) ; } } BeanContext baseContext = context . withResource ( getModelResource ( context ) ) ; component = baseContext . adaptTo ( type ) ; injectServices ( component ) ; additionalInitialization ( component ) ; } return component ; }
Create the requested component instance
6,866
protected Map < String , Object > getReplacedAttributes ( int scope ) { if ( replacedAttributes == null ) { replacedAttributes = new ArrayList < > ( ) ; } while ( replacedAttributes . size ( ) <= scope ) { replacedAttributes . add ( new HashMap < String , Object > ( ) ) ; } return replacedAttributes . get ( scope ) ; }
retrieves the registry for one scope
6,867
protected void setAttribute ( String key , Object value , int scope ) { Map < String , Object > replacedInScope = getReplacedAttributes ( scope ) ; if ( ! replacedInScope . containsKey ( key ) ) { Object current = pageContext . getAttribute ( key , scope ) ; replacedInScope . put ( key , current ) ; } pageContext . setAttribute ( key , value , scope ) ; }
each attribute set by a tag should use this method for attribute declaration ; an existing value with the same key is registered and restored if the tag rendering ends
6,868
protected void restoreAttributes ( ) { if ( replacedAttributes != null ) { for ( int scope = 0 ; scope < replacedAttributes . size ( ) ; scope ++ ) { Map < String , Object > replaced = replacedAttributes . get ( scope ) ; for ( Map . Entry < String , Object > entry : replaced . entrySet ( ) ) { String key = entry . getKey ( ) ; Object value = entry . getValue ( ) ; if ( value != null ) { pageContext . setAttribute ( key , value , scope ) ; } else { pageContext . removeAttribute ( key , scope ) ; } } } } }
restores all replaced values and removes all attributes declared in this tag
6,869
public ServletOperation getOperation ( SlingHttpServletRequest request , Method method ) { ServletOperation operation = null ; E extension = RequestUtil . getExtension ( request , defaultExtension ) ; Map < E , O > extensionDefaults = operationDefaults . get ( method ) ; if ( extensionDefaults != null ) { O defaultOperation = extensionDefaults . get ( extension ) ; if ( defaultOperation != null ) { Map < E , Map < O , ServletOperation > > extensions = operationMap . get ( method ) ; if ( extensions != null ) { Map < O , ServletOperation > operations = extensions . get ( extension ) ; if ( operations != null ) { operation = operations . get ( RequestUtil . getSelector ( request , defaultOperation ) ) ; } } } } return operation ; }
Retrieves the servlet operation requested for the used HTTP method . Looks in the selectors for a operation and gives their implementation in the extensions context .
6,870
protected synchronized void bindFilterConfiguration ( final FilterConfiguration config ) { if ( filterConfigurations == null ) { filterConfigurations = new ArrayList < > ( ) ; } filterConfigurations . add ( config ) ; String key = config . getName ( ) ; ResourceFilter filter = config . getFilter ( ) ; if ( StringUtils . isNotBlank ( key ) && filter != null ) { nodeFilters . put ( key , buildTreeFilter ( filter ) ) ; } }
for each configured filter in the OSGi configuration a tree filter is added to the filter set
6,871
protected synchronized void unbindFilterConfiguration ( final FilterConfiguration config ) { nodeFilters . remove ( config . getName ( ) ) ; filterConfigurations . remove ( config ) ; }
removing of a configuration which is not longer available ; removes the corresponding tree filter also
6,872
protected ResourceFilter getNodeFilter ( SlingHttpServletRequest request ) { ResourceFilter filter = null ; String filterParam = RequestUtil . getParameter ( request , PARAM_FILTER , ( String ) null ) ; if ( StringUtils . isNotBlank ( filterParam ) ) { filter = nodeFilters . get ( filterParam ) ; } if ( filter == null ) { RequestPathInfo pathInfo = request . getRequestPathInfo ( ) ; for ( String selector : pathInfo . getSelectors ( ) ) { filter = nodeFilters . get ( selector ) ; if ( filter != null ) { break ; } } } if ( filter == null ) { filter = nodesConfig . getDefaultNodeFilter ( ) ; } return filter ; }
Determines the filter to use for node retrieval ; scans the request for filter parameter or selector .
6,873
protected List < Resource > prepareTreeItems ( ResourceHandle resource , List < Resource > items ) { if ( ! nodesConfig . getOrderableNodesFilter ( ) . accept ( resource ) ) { Collections . sort ( items , new Comparator < Resource > ( ) { public int compare ( Resource r1 , Resource r2 ) { return getSortName ( r1 ) . compareTo ( getSortName ( r2 ) ) ; } } ) ; } return items ; }
sort children of orderable nodes
6,874
protected void activate ( ComponentContext context ) { Dictionary properties = context . getProperties ( ) ; name = ( String ) properties . get ( "name" ) ; filter = ResourceFilterMapping . fromString ( ( String ) properties . get ( "filter" ) ) ; }
creates the filter instance for the configured rule
6,875
public static ResourceHandle getResource ( SlingHttpServletRequest request ) { ResourceResolver resolver = request . getResourceResolver ( ) ; String path = getPath ( request ) ; ResourceHandle resource = ResourceHandle . use ( resolver . resolve ( path ) ) ; return resource ; }
Retrieves the resource using the suffix from the request .
6,876
public static Resource getConsoleResource ( BeanContext context ) { SlingHttpServletRequest request = context . getRequest ( ) ; ResourceResolver resolver = request . getResourceResolver ( ) ; String path = null ; Resource resource = context . getAttribute ( "resource" , Resource . class ) ; if ( resource == null ) { resource = request . getResource ( ) ; } if ( resource != null ) { path = resource . getPath ( ) ; } if ( StringUtils . isBlank ( path ) || path . startsWith ( "/bin/" ) ) { RequestPathInfo requestPathInfo = request . getRequestPathInfo ( ) ; path = requestPathInfo . getSuffix ( ) ; resource = null ; } if ( resource == null && StringUtils . isNotBlank ( path ) ) { resource = resolver . getResource ( path ) ; } if ( resource == null ) { resource = resolver . getResource ( "/" ) ; } return resource ; }
determines the addressed resource by the suffix if the requests resource is the servlet itself
6,877
private boolean areClassesEqual ( Class < ? > c1 , Class < ? > c2 ) { if ( isMap ( c1 ) ) { return isMap ( c2 ) ; } else if ( isList ( c1 ) ) { return isList ( c2 ) ; } else { return c1 . equals ( c2 ) ; } }
When comparing literals allow subclasses of Maps and Lists to be directly compared even if they have different implementations .
6,878
protected MatchingPart toPart ( List < MatchingPart > leadingParts , String part ) { switch ( leadingParts . size ( ) ) { case 0 : MatchingPart resolvedPart = createEmoPermissionPart ( part , PartType . CONTEXT ) ; checkArgument ( resolvedPart instanceof ConstantPart || resolvedPart . impliesAny ( ) , "First part must be a constant or pure wildcard" ) ; return resolvedPart ; case 1 : checkArgument ( ! MatchingPart . getContext ( leadingParts ) . impliesAny ( ) , "Cannot narrow permission without initial scope" ) ; return createEmoPermissionPart ( part , PartType . ACTION ) ; case 2 : PartType partType ; if ( MatchingPart . contextImpliedBy ( SOR_PART , leadingParts ) ) { partType = PartType . SOR_TABLE ; } else if ( MatchingPart . contextImpliedBy ( BLOB_PART , leadingParts ) ) { partType = PartType . BLOB_TABLE ; } else { partType = PartType . NAMED_RESOURCE ; } return createEmoPermissionPart ( part , partType ) ; case 3 : if ( MatchingPart . contextImpliedBy ( ROLE_PART , leadingParts ) ) { return createEmoPermissionPart ( part , PartType . NAMED_RESOURCE ) ; } break ; } throw new IllegalArgumentException ( format ( "Too many parts for EmoPermission in \"%s\" context" , MatchingPart . getContext ( leadingParts ) ) ) ; }
Override the logic in the parent to meet the requirements for EmoPermission .
6,879
private MatchingPart createEmoPermissionPart ( String part , PartType partType ) { part = unescapeSeparators ( part ) ; switch ( part . charAt ( 0 ) ) { case 'c' : if ( isTableResource ( partType ) && part . startsWith ( "createTable(" ) && part . endsWith ( ")" ) ) { String rison = part . substring ( 12 , part . length ( ) - 1 ) ; return RisonHelper . fromORison ( rison , CreateTablePart . class ) ; } break ; case 'i' : if ( part . startsWith ( "if(" ) && part . endsWith ( ")" ) ) { String condition = part . substring ( 3 , part . length ( ) - 1 ) ; switch ( partType ) { case SOR_TABLE : return new SorTableConditionPart ( Conditions . fromString ( condition ) , _dataStore ) ; case BLOB_TABLE : return new BlobTableConditionPart ( Conditions . fromString ( condition ) , _blobStore ) ; default : return new ConditionPart ( Conditions . fromString ( condition ) ) ; } } break ; case '*' : if ( part . length ( ) == 1 ) { return getAnyPart ( ) ; } break ; case '?' : if ( part . length ( ) == 1 ) { return EmoImpliedPartExistsPart . instance ( ) ; } break ; } Condition condition = Conditions . like ( part ) ; if ( condition instanceof EqualCondition ) { return new EmoConstantPart ( part ) ; } return new ConditionPart ( condition ) ; }
Creates a TableIdentificationPart for the third value in a data or blob store permission .
6,880
private boolean isJsonProcessingException ( Exception e ) { return e instanceof JsonProcessingException && ! ( e instanceof JsonParseException && e . getMessage ( ) != null && e . getMessage ( ) . startsWith ( "Unexpected end-of-input" ) ) ; }
Returns true if the exception is a JsonProcessingException whose root cause is not a premature end of data since this is more likely caused by a connection error .
6,881
public static boolean synchronousSync ( CuratorFramework curator , Duration timeout ) { try { final CountDownLatch latch = new CountDownLatch ( 1 ) ; curator . sync ( ) . inBackground ( new BackgroundCallback ( ) { public void processResult ( CuratorFramework curator , CuratorEvent event ) throws Exception { if ( event . getType ( ) == CuratorEventType . SYNC ) { latch . countDown ( ) ; } } } ) . forPath ( curator . getNamespace ( ) . isEmpty ( ) ? "/" : "" ) ; return latch . await ( timeout . toMillis ( ) , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { return false ; } catch ( Exception e ) { throw Throwables . propagate ( e ) ; } }
Performs a blocking sync operation . Returns true if the sync completed normally false if it timed out or was interrupted .
6,882
protected void initializePermission ( ) { try { List < MatchingPart > parts = Lists . newArrayList ( ) ; for ( String partString : split ( _permission ) ) { partString = partString . trim ( ) ; checkArgument ( ! "" . equals ( partString ) , "Permission cannot contain empty parts" ) ; MatchingPart part = toPart ( Collections . unmodifiableList ( parts ) , partString ) ; parts . add ( part ) ; } _parts = ImmutableList . copyOf ( parts ) ; } catch ( InvalidPermissionStringException e ) { throw e ; } catch ( Exception e ) { throw new InvalidPermissionStringException ( e . getMessage ( ) , _permission ) ; } }
Parses and initializes the permission s parts . By default this is performed by the constructor . If a subclass needs to perform its own initialization prior to initializing the permissions then it should call the constructor with the initialization parameter set to false and then call this method when ready .
6,883
private int getSeparatorIndex ( ByteBuffer buf ) { int colon = BufferUtils . indexOf ( buf , ( byte ) ':' ) ; if ( colon == - 1 ) { throw new IllegalStateException ( "Unknown encoding format: " + ByteBufferUtil . bytesToHex ( buf ) ) ; } return colon ; }
Returns the index of the colon that separates the encoding prefix from the body suffix .
6,884
public List < ScanRange > unwrapped ( ) { if ( compare ( _from , _to ) < 0 ) { return ImmutableList . of ( this ) ; } ImmutableList . Builder < ScanRange > ranges = ImmutableList . builder ( ) ; if ( compare ( _from , MAX_VALUE ) < 0 ) { ranges . add ( new ScanRange ( _from , MAX_VALUE ) ) ; } if ( compare ( _to , MIN_VALUE ) > 0 ) { ranges . add ( new ScanRange ( MIN_VALUE , _to ) ) ; } return ranges . build ( ) ; }
If necessary splits the scan range into two range such that from is less than to in each range . This is necessary if the scan range wraps the token range .
6,885
public void clear ( ) { _sample . clear ( ) ; _count = 0 ; _max = null ; _min = null ; _sum = BigDecimal . ZERO ; _m = - 1 ; _s = 0 ; }
Clears all recorded values .
6,886
public List < Token > resplitLocally ( String startToken , String endToken , int numResplits ) { List < Token > splitTokens = ImmutableList . of ( _tokenFactory . fromString ( startToken ) , _tokenFactory . fromString ( endToken ) ) ; for ( int i = 0 ; i < numResplits ; i ++ ) { List < Token > newTokens = new ArrayList < > ( splitTokens . size ( ) * 2 - 1 ) ; for ( int j = 0 ; j < splitTokens . size ( ) - 1 ; j ++ ) { newTokens . add ( splitTokens . get ( j ) ) ; newTokens . add ( ByteOrderedPartitioner . instance . midpoint ( splitTokens . get ( j ) , splitTokens . get ( j + 1 ) ) ) ; } newTokens . add ( splitTokens . get ( splitTokens . size ( ) - 1 ) ) ; splitTokens = newTokens ; } return splitTokens ; }
Manually split the token ranges using ByteOrderedPartitioner s midpoint method
6,887
private Iterator < Record > rowQuery ( DeltaPlacement placement , List < Map . Entry < ByteBuffer , Key > > keys , ReadConsistency consistency ) { List < ByteBuffer > rowIds = Lists . transform ( keys , entryKeyFunction ( ) ) ; final Rows < ByteBuffer , DeltaKey > rows = execute ( placement . getKeyspace ( ) . prepareQuery ( placement . getBlockedDeltaColumnFamily ( ) , SorConsistencies . toAstyanax ( consistency ) ) . getKeySlice ( rowIds ) . withColumnRange ( _maxColumnsRange ) , "query %d keys from placement %s" , rowIds . size ( ) , placement . getName ( ) ) ; _randomReadMeter . mark ( rowIds . size ( ) ) ; return decodeRows ( keys , rows , _maxColumnsRange . getLimit ( ) , consistency ) ; }
Queries for rows given an enumerated list of Cassandra row keys .
6,888
private Iterator < String > decodeKeys ( final Iterator < Row < ByteBuffer , DeltaKey > > iter ) { return new AbstractIterator < String > ( ) { protected String computeNext ( ) { while ( iter . hasNext ( ) ) { Row < ByteBuffer , DeltaKey > row = iter . next ( ) ; if ( ! row . getColumns ( ) . isEmpty ( ) ) { return AstyanaxStorage . getContentKey ( row . getRawKey ( ) ) ; } } return endOfData ( ) ; } } ; }
Decodes row keys returned by scanning a table .
6,889
private Iterator < Record > decodeRows ( List < Map . Entry < ByteBuffer , Key > > keys , final Rows < ByteBuffer , DeltaKey > rows , final int largeRowThreshold , final ReadConsistency consistency ) { return Iterators . transform ( keys . iterator ( ) , new Function < Map . Entry < ByteBuffer , Key > , Record > ( ) { public Record apply ( Map . Entry < ByteBuffer , Key > entry ) { Row < ByteBuffer , DeltaKey > row = rows . getRow ( entry . getKey ( ) ) ; if ( row == null ) { return emptyRecord ( entry . getValue ( ) ) ; } return newRecord ( entry . getValue ( ) , row . getRawKey ( ) , row . getColumns ( ) , largeRowThreshold , consistency , null ) ; } } ) ; }
Decodes rows returned by querying for a specific set of rows .
6,890
private < T > Iterator < T > touch ( Iterator < T > iter ) { iter . hasNext ( ) ; return iter ; }
Force computation of the first item in an iterator so metrics calculations for a method reflect the cost of the first batch of results .
6,891
public ConsistencyLevel clamp ( ConsistencyLevel consistencyLevel ) { if ( ( consistencyLevel == ConsistencyLevel . CL_LOCAL_QUORUM || consistencyLevel == ConsistencyLevel . CL_EACH_QUORUM ) && ! _networkTopology ) { consistencyLevel = ConsistencyLevel . CL_QUORUM ; } if ( consistencyLevel == ConsistencyLevel . CL_LOCAL_ONE && ! _networkTopology ) { consistencyLevel = ConsistencyLevel . CL_ONE ; } if ( consistencyLevel == ConsistencyLevel . CL_THREE && _replicationFactor < 3 ) { consistencyLevel = ConsistencyLevel . CL_TWO ; } if ( consistencyLevel == ConsistencyLevel . CL_TWO && _replicationFactor < 2 ) { consistencyLevel = ConsistencyLevel . CL_ONE ; } return consistencyLevel ; }
Reduce the desired consistency level to be compatible with the deployed ring topology .
6,892
public < V > V getValue ( Serializer < V > serializer ) { return _content != null ? serializer . fromByteBuffer ( _content ) : _oldColumn . getValue ( serializer ) ; }
content will be null if delta fit in a single block as no stitching was performed
6,893
private static void startLocalCassandra ( String cassandraYamlPath ) throws IOException { System . setProperty ( "cassandra.config" , "file:" + cassandraYamlPath ) ; final CassandraDaemon cassandra = new CassandraDaemon ( ) ; cassandra . init ( null ) ; Futures . getUnchecked ( service . submit ( new Callable < Object > ( ) { public Object call ( ) throws Exception { cassandra . start ( ) ; return null ; } } ) ) ; }
Start an in - memory Cassandra .
6,894
private static TestingServer startLocalZooKeeper ( ) throws Exception { ( ( Logger ) LoggerFactory . getLogger ( "org.apache.zookeeper" ) ) . setLevel ( Level . ERROR ) ; TestingServer zooKeeperServer = new TestingServer ( 2181 ) ; System . setProperty ( "dw.zooKeeper.connectString" , zooKeeperServer . getConnectString ( ) ) ; return zooKeeperServer ; }
Start an in - memory copy of ZooKeeper .
6,895
public MigratorStatus resubmitWorkflowTasks ( String placement ) { MigratorStatus status = _statusDAO . getMigratorStatus ( placement ) ; if ( status == null ) { return null ; } if ( status . getCompleteTime ( ) == null ) { for ( ScanRangeStatus active : status . getActiveScanRanges ( ) ) { _workflow . addScanRangeTask ( placement , active . getTaskId ( ) , active . getPlacement ( ) , active . getScanRange ( ) ) ; } _workflow . scanStatusUpdated ( placement ) ; } return status ; }
Sometimes due to unexpected errors while submitting migrator ranges to the underlying queues a migration can get stuck . This method takes all available tasks for a migration and resubmits them . This method is safe because the underlying system is resilient to task resubmissions and concurrent work on the same task .
6,896
public Record read ( Key key , ReadConsistency consistency ) { checkNotNull ( key , "key" ) ; checkNotNull ( consistency , "consistency" ) ; AstyanaxTable table = ( AstyanaxTable ) key . getTable ( ) ; AstyanaxStorage storage = table . getReadStorage ( ) ; DeltaPlacement placement = ( DeltaPlacement ) storage . getPlacement ( ) ; ByteBuffer rowKey = storage . getRowKey ( key . getKey ( ) ) ; return read ( key , rowKey , consistency , placement ) ; }
This CQL based read method works for a row with 64 deltas of 3 MB each . The same read with the AstyanaxDataReaderDAO would give Thrift frame errors .
6,897
public List < String > getSplits ( Table table , int recordsPerSplit , int localResplits ) throws TimeoutException { return _astyanaxReaderDAO . getSplits ( table , recordsPerSplit , localResplits ) ; }
support for this call using CQL . Therefore they must always defer to the Asytanax implementation .
6,898
private ScanStatus resplitPartiallyCompleteTasks ( ScanStatus status ) { boolean anyUpdated = false ; int nextTaskId = - 1 ; for ( ScanRangeStatus complete : status . getCompleteScanRanges ( ) ) { if ( complete . getResplitRange ( ) . isPresent ( ) ) { if ( nextTaskId == - 1 ) { nextTaskId = getNextTaskId ( status ) ; } ScanRange resplitRange = complete . getResplitRange ( ) . get ( ) ; List < ScanRange > subRanges = resplit ( complete . getPlacement ( ) , resplitRange , status . getOptions ( ) . getRangeScanSplitSize ( ) ) ; List < ScanRangeStatus > resplitStatuses = Lists . newArrayListWithCapacity ( subRanges . size ( ) ) ; for ( ScanRange subRange : subRanges ) { resplitStatuses . add ( new ScanRangeStatus ( nextTaskId ++ , complete . getPlacement ( ) , subRange , complete . getBatchId ( ) , complete . getBlockedByBatchId ( ) , complete . getConcurrencyId ( ) ) ) ; } _scanStatusDAO . resplitScanRangeTask ( status . getScanId ( ) , complete . getTaskId ( ) , resplitStatuses ) ; anyUpdated = true ; } } if ( ! anyUpdated ) { return status ; } return _scanStatusDAO . getScanStatus ( status . getScanId ( ) ) ; }
Checks whether any completed tasks returned before scanning the entire range . If so then the unscanned ranges are resplit and new tasks are created from them .
6,899
public static < T > T getEntity ( InputStream in , Class < T > clazz ) { if ( clazz == InputStream . class ) { return ( T ) clazz ; } try { return JsonHelper . readJson ( in , clazz ) ; } catch ( IOException e ) { throw Throwables . propagate ( e ) ; } }
Reads the entity input stream and deserializes the JSON content to the given class .