idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
15,200 | @ Override public void draw ( Canvas canvas ) { float width = canvas . getWidth ( ) ; float margin = ( width / 3 ) + mState . mMarginSide ; float posY = canvas . getHeight ( ) - mState . mMarginBottom ; canvas . drawLine ( margin , posY , width - margin , posY , mPaint ) ; } | It is based on the canvas width and height instead of the bounds in order not to consider the margins of the button it is drawn in . | 81 | 28 |
15,201 | static void addAttachObserver ( HTMLElement element , ObserverCallback callback ) { if ( ! ready ) { startObserving ( ) ; } attachObservers . add ( createObserver ( element , callback , ATTACH_UID_KEY ) ) ; } | Check if the observer is already started if not it will start it then register and callback for when the element is attached to the dom . | 56 | 27 |
15,202 | static void addDetachObserver ( HTMLElement element , ObserverCallback callback ) { if ( ! ready ) { startObserving ( ) ; } detachObservers . add ( createObserver ( element , callback , DETACH_UID_KEY ) ) ; } | Check if the observer is already started if not it will start it then register and callback for when the element is removed from the dom . | 57 | 27 |
15,203 | public static < DateInstantT extends DateInstant > DatePickerFragment newInstance ( int pickerId , DateInstantT selectedInstant ) { DatePickerFragment f = new DatePickerFragment ( ) ; Bundle args = new Bundle ( ) ; args . putInt ( ARG_PICKER_ID , pickerId ) ; args . putParcelable ( ARG_SELECTED_INSTANT , selectedInstant ) ; f . setArguments ( args ) ; return f ; } | Create a new date picker | 106 | 6 |
15,204 | private void abortWithError ( Element element , String msg , Object ... args ) throws AbortProcessingException { error ( element , msg , args ) ; throw new AbortProcessingException ( ) ; } | Issue a compilation error and abandon the processing of this template . This does not prevent the processing of other templates . | 43 | 22 |
15,205 | public static AccentPalette getPalette ( Context context ) { Resources resources = context . getResources ( ) ; if ( ! ( resources instanceof AccentResources ) ) return null ; return ( ( AccentResources ) resources ) . getPalette ( ) ; } | Get the AccentPalette instance from the the context . | 56 | 12 |
15,206 | public void prepareDialog ( Context c , Window window ) { if ( mDividerPainter == null ) mDividerPainter = initPainter ( c , mOverrideColor ) ; mDividerPainter . paint ( window ) ; } | Paint the dialog s divider if required to correctly customize it . | 51 | 14 |
15,207 | public static < E extends HTMLElement > EmptyContentBuilder < E > emptyElement ( String tag , Class < E > type ) { return emptyElement ( ( ) -> createElement ( tag , type ) ) ; } | Returns a builder for the specified empty tag . | 46 | 9 |
15,208 | public static < E extends HTMLElement > TextContentBuilder < E > textElement ( String tag , Class < E > type ) { return new TextContentBuilder <> ( createElement ( tag , type ) ) ; } | Returns a builder for the specified text tag . | 47 | 9 |
15,209 | public static < E extends HTMLElement > HtmlContentBuilder < E > htmlElement ( String tag , Class < E > type ) { return new HtmlContentBuilder <> ( createElement ( tag , type ) ) ; } | Returns a builder for the specified html tag . | 49 | 9 |
15,210 | public static < E > Stream < E > stream ( JsArrayLike < E > nodes ) { if ( nodes == null ) { return Stream . empty ( ) ; } else { return StreamSupport . stream ( spliteratorUnknownSize ( iterator ( nodes ) , 0 ) , false ) ; } } | Returns a stream for the elements in the given array - like . | 62 | 13 |
15,211 | public static Stream < Node > stream ( Node parent ) { if ( parent == null ) { return Stream . empty ( ) ; } else { return StreamSupport . stream ( spliteratorUnknownSize ( iterator ( parent ) , 0 ) , false ) ; } } | Returns a stream for the child nodes of the given parent node . | 53 | 13 |
15,212 | public static void lazyAppend ( Element parent , Element child ) { if ( ! parent . contains ( child ) ) { parent . appendChild ( child ) ; } } | Appends the specified element to the parent element if not already present . If parent already contains child this method does nothing . | 35 | 24 |
15,213 | public static void insertAfter ( Element newElement , Element after ) { after . parentNode . insertBefore ( newElement , after . nextSibling ) ; } | Inserts the specified element into the parent of the after element . | 33 | 13 |
15,214 | public static void lazyInsertAfter ( Element newElement , Element after ) { if ( ! after . parentNode . contains ( newElement ) ) { after . parentNode . insertBefore ( newElement , after . nextSibling ) ; } } | Inserts the specified element into the parent of the after element if not already present . If parent already contains child this method does nothing . | 50 | 27 |
15,215 | public static void insertBefore ( Element newElement , Element before ) { before . parentNode . insertBefore ( newElement , before ) ; } | Inserts the specified element into the parent of the before element . | 29 | 13 |
15,216 | public static void lazyInsertBefore ( Element newElement , Element before ) { if ( ! before . parentNode . contains ( newElement ) ) { before . parentNode . insertBefore ( newElement , before ) ; } } | Inserts the specified element into the parent of the before element if not already present . If parent already contains child this method does nothing . | 46 | 27 |
15,217 | public static boolean failSafeRemoveFromParent ( Element element ) { return failSafeRemove ( element != null ? element . parentNode : null , element ) ; } | Removes the element from its parent if the element is not null and has a parent . | 33 | 18 |
15,218 | public static boolean failSafeRemove ( Node parent , Element child ) { //noinspection SimplifiableIfStatement if ( parent != null && child != null && parent . contains ( child ) ) { return parent . removeChild ( child ) != null ; } return false ; } | Removes the child from parent if both parent and child are not null and parent contains child . | 56 | 19 |
15,219 | public static void onAttach ( HTMLElement element , ObserverCallback callback ) { if ( element != null ) { BodyObserver . addAttachObserver ( element , callback ) ; } } | Registers a callback when an element is appended to the document body . Note that the callback will be called only once if the element is appended more than once a new callback should be registered . | 40 | 40 |
15,220 | public static void onDetach ( HTMLElement element , ObserverCallback callback ) { if ( element != null ) { BodyObserver . addDetachObserver ( element , callback ) ; } } | Registers a callback when an element is removed from the document body . Note that the callback will be called only once if the element is removed and re - appended a new callback should be registered . | 42 | 40 |
15,221 | public void setSwitchTextAppearance ( Context context , int resid ) { TypedArray appearance = context . obtainStyledAttributes ( resid , R . styleable . TextAppearanceAccentSwitch ) ; ColorStateList colors ; int ts ; colors = appearance . getColorStateList ( R . styleable . TextAppearanceAccentSwitch_android_textColor ) ; if ( colors != null ) { mTextColors = colors ; } else { // If no color set in TextAppearance, default to the view's // textColor mTextColors = getTextColors ( ) ; } ts = appearance . getDimensionPixelSize ( R . styleable . TextAppearanceAccentSwitch_android_textSize , 0 ) ; if ( ts != 0 ) { if ( ts != mTextPaint . getTextSize ( ) ) { mTextPaint . setTextSize ( ts ) ; requestLayout ( ) ; } } int typefaceIndex , styleIndex ; typefaceIndex = appearance . getInt ( R . styleable . TextAppearanceAccentSwitch_android_typeface , - 1 ) ; styleIndex = appearance . getInt ( R . styleable . TextAppearanceAccentSwitch_android_textStyle , - 1 ) ; setSwitchTypefaceByIndex ( typefaceIndex , styleIndex ) ; boolean allCaps = appearance . getBoolean ( R . styleable . TextAppearanceAccentSwitch_android_textAllCaps , false ) ; if ( allCaps ) { mSwitchTransformationMethod = new AllCapsTransformationMethod ( getContext ( ) ) ; mSwitchTransformationMethod . setLengthChangesAllowed ( true ) ; } else { mSwitchTransformationMethod = null ; } appearance . recycle ( ) ; } | Sets the switch text color size style hint color and highlight color from the specified TextAppearance resource . | 365 | 20 |
15,222 | private void stopDrag ( MotionEvent ev ) { mTouchMode = TOUCH_MODE_IDLE ; // Up and not canceled, also checks the switch has not been disabled // during the drag boolean commitChange = ev . getAction ( ) == MotionEvent . ACTION_UP && isEnabled ( ) ; cancelSuperTouch ( ev ) ; if ( commitChange ) { boolean newState ; mVelocityTracker . computeCurrentVelocity ( 1000 ) ; float xvel = mVelocityTracker . getXVelocity ( ) ; if ( Math . abs ( xvel ) > mMinFlingVelocity ) { // newState = isLayoutRtl() ? (xvel < 0) : (xvel > 0); newState = xvel > 0 ; } else { newState = getTargetCheckedState ( ) ; } animateThumbToCheckedState ( newState ) ; } else { animateThumbToCheckedState ( isChecked ( ) ) ; } } | Called from onTouchEvent to end a drag operation . | 205 | 12 |
15,223 | public static < TimeInstantT extends TimeInstant > TimePickerFragment newInstance ( int pickerId , TimeInstantT selectedInstant ) { TimePickerFragment f = new TimePickerFragment ( ) ; Bundle args = new Bundle ( ) ; args . putInt ( ARG_PICKER_ID , pickerId ) ; args . putParcelable ( ARG_SELECTED_INSTANT , selectedInstant ) ; f . setArguments ( args ) ; return f ; } | Create a new time picker | 106 | 6 |
15,224 | @ SuppressWarnings ( "deprecation" ) @ SuppressLint ( "NewApi" ) private void setBackground ( View view , Drawable drawable ) { if ( Build . VERSION . SDK_INT >= SET_DRAWABLE_MIN_SDK ) view . setBackground ( drawable ) ; else view . setBackgroundDrawable ( drawable ) ; } | Call the appropriate method to set the background to the View | 83 | 11 |
15,225 | void sendAccessibilityEvent ( View view ) { // Since the view is still not attached we create, populate, // and send the event directly since we do not know when it // will be attached and posting commands is not as clean. AccessibilityManager accessibilityManager = ( AccessibilityManager ) getContext ( ) . getSystemService ( Context . ACCESSIBILITY_SERVICE ) ; if ( accessibilityManager == null ) return ; if ( mSendClickAccessibilityEvent && accessibilityManager . isEnabled ( ) ) { AccessibilityEvent event = AccessibilityEvent . obtain ( ) ; event . setEventType ( AccessibilityEvent . TYPE_VIEW_CLICKED ) ; view . onInitializeAccessibilityEvent ( event ) ; view . dispatchPopulateAccessibilityEvent ( event ) ; accessibilityManager . sendAccessibilityEvent ( event ) ; } mSendClickAccessibilityEvent = false ; } | As defined in TwoStatePreference source | 183 | 8 |
15,226 | public static String unescape ( String string , char escape ) { CharArrayWriter out = new CharArrayWriter ( string . length ( ) ) ; for ( int i = 0 ; i < string . length ( ) ; i ++ ) { char c = string . charAt ( i ) ; if ( c == escape ) { try { out . write ( Integer . parseInt ( string . substring ( i + 1 , i + 3 ) , 16 ) ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( e ) ; } i += 2 ; } else { out . write ( c ) ; } } return new String ( out . toCharArray ( ) ) ; } | Unescapes string using escape symbol . | 146 | 9 |
15,227 | public static String escape ( String string , char escape , boolean isPath ) { try { BitSet validChars = isPath ? URISaveEx : URISave ; byte [ ] bytes = string . getBytes ( "utf-8" ) ; StringBuffer out = new StringBuffer ( bytes . length ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { int c = bytes [ i ] & 0xff ; if ( validChars . get ( c ) && c != escape ) { out . append ( ( char ) c ) ; } else { out . append ( escape ) ; out . append ( hexTable [ ( c >> 4 ) & 0x0f ] ) ; out . append ( hexTable [ ( c ) & 0x0f ] ) ; } } return out . toString ( ) ; } catch ( Exception exc ) { throw new InternalError ( exc . toString ( ) ) ; } } | Escapes string using escape symbol . | 200 | 7 |
15,228 | public static String relativizePath ( String path , boolean withIndex ) { if ( path . startsWith ( "/" ) ) path = path . substring ( 1 ) ; if ( ! withIndex && path . endsWith ( "]" ) ) { int index = path . lastIndexOf ( ' ' ) ; return index == - 1 ? path : path . substring ( 0 , index ) ; } return path ; } | Creates relative path from string . | 89 | 7 |
15,229 | public static String removeIndexFromPath ( String path ) { if ( path . endsWith ( "]" ) ) { int index = path . lastIndexOf ( ' ' ) ; if ( index != - 1 ) { return path . substring ( 0 , index ) ; } } return path ; } | Removes the index from the path if it has an index defined | 62 | 13 |
15,230 | public static String pathOnly ( String path ) { String curPath = path ; curPath = curPath . substring ( curPath . indexOf ( "/" ) ) ; curPath = curPath . substring ( 0 , curPath . lastIndexOf ( "/" ) ) ; if ( "" . equals ( curPath ) ) { curPath = "/" ; } return curPath ; } | Cuts the path from string . | 82 | 7 |
15,231 | public static String nameOnly ( String path ) { int index = path . lastIndexOf ( ' ' ) ; String name = index == - 1 ? path : path . substring ( index + 1 ) ; if ( name . endsWith ( "]" ) ) { index = name . lastIndexOf ( ' ' ) ; return index == - 1 ? name : name . substring ( 0 , index ) ; } return name ; } | Cuts the current name from the path . | 90 | 9 |
15,232 | public static String getExtension ( String filename ) { int index = filename . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { return filename . substring ( index + 1 ) ; } return "" ; } | Extracts the extension of the file . | 47 | 9 |
15,233 | protected boolean isPredecessor ( NodeData mergeVersion , NodeData corrVersion ) throws RepositoryException { SessionDataManager mergeDataManager = mergeSession . getTransientNodesManager ( ) ; PropertyData predecessorsProperty = ( PropertyData ) mergeDataManager . getItemData ( mergeVersion , new QPathEntry ( Constants . JCR_PREDECESSORS , 0 ) , ItemType . PROPERTY ) ; if ( predecessorsProperty != null ) { for ( ValueData pv : predecessorsProperty . getValues ( ) ) { String pidentifier = ValueDataUtil . getString ( pv ) ; if ( pidentifier . equals ( corrVersion . getIdentifier ( ) ) ) { return true ; // got it } // search in predecessors of the predecessor NodeData predecessor = ( NodeData ) mergeDataManager . getItemData ( pidentifier ) ; if ( predecessor != null ) { if ( isPredecessor ( predecessor , corrVersion ) ) { return true ; } } else { throw new RepositoryException ( "Merge. Predecessor is not found by uuid " + pidentifier + ". Version " + mergeSession . getLocationFactory ( ) . createJCRPath ( mergeVersion . getQPath ( ) ) . getAsString ( false ) ) ; } } // else it's a root version } return false ; } | Is a predecessor of the merge version | 290 | 7 |
15,234 | protected boolean isSuccessor ( NodeData mergeVersion , NodeData corrVersion ) throws RepositoryException { SessionDataManager mergeDataManager = mergeSession . getTransientNodesManager ( ) ; PropertyData successorsProperty = ( PropertyData ) mergeDataManager . getItemData ( mergeVersion , new QPathEntry ( Constants . JCR_SUCCESSORS , 0 ) , ItemType . PROPERTY ) ; if ( successorsProperty != null ) { for ( ValueData sv : successorsProperty . getValues ( ) ) { String sidentifier = ValueDataUtil . getString ( sv ) ; if ( sidentifier . equals ( corrVersion . getIdentifier ( ) ) ) { return true ; // got it } // search in successors of the successor NodeData successor = ( NodeData ) mergeDataManager . getItemData ( sidentifier ) ; if ( successor != null ) { if ( isSuccessor ( successor , corrVersion ) ) { return true ; } } else { throw new RepositoryException ( "Merge. Ssuccessor is not found by uuid " + sidentifier + ". Version " + mergeSession . getLocationFactory ( ) . createJCRPath ( mergeVersion . getQPath ( ) ) . getAsString ( false ) ) ; } } // else it's a end of version graph node } return false ; } | Is a successor of the merge version | 288 | 7 |
15,235 | public PersistedNodeData read ( ObjectReader in ) throws UnknownClassIdException , IOException { // read id int key ; if ( ( key = in . readInt ( ) ) != SerializationConstants . PERSISTED_NODE_DATA ) { throw new UnknownClassIdException ( "There is unexpected class [" + key + "]" ) ; } QPath qpath ; try { String sQPath = in . readString ( ) ; qpath = QPath . parse ( sQPath ) ; } catch ( final IllegalPathException e ) { throw new IOException ( "Deserialization error. " + e ) { /** * {@inheritDoc} */ @ Override public Throwable getCause ( ) { return e ; } } ; } String identifier = in . readString ( ) ; String parentIdentifier = null ; if ( in . readByte ( ) == SerializationConstants . NOT_NULL_DATA ) { parentIdentifier = in . readString ( ) ; } int persistedVersion = in . readInt ( ) ; // -------------- int orderNum = in . readInt ( ) ; // primary type InternalQName primaryTypeName ; try { primaryTypeName = InternalQName . parse ( in . readString ( ) ) ; } catch ( final IllegalNameException e ) { throw new IOException ( e . getMessage ( ) ) { private static final long serialVersionUID = 3489809179234435267L ; /** * {@inheritDoc} */ @ Override public Throwable getCause ( ) { return e ; } } ; } // mixins InternalQName [ ] mixinTypeNames = null ; if ( in . readByte ( ) == SerializationConstants . NOT_NULL_DATA ) { int count = in . readInt ( ) ; mixinTypeNames = new InternalQName [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { try { mixinTypeNames [ i ] = InternalQName . parse ( in . readString ( ) ) ; } catch ( final IllegalNameException e ) { throw new IOException ( e . getMessage ( ) ) { private static final long serialVersionUID = 3489809179234435268L ; // eclipse // gen /** * {@inheritDoc} */ @ Override public Throwable getCause ( ) { return e ; } } ; } } } // acl AccessControlList acl = null ; if ( in . readByte ( ) == SerializationConstants . NOT_NULL_DATA ) { ACLReader rdr = new ACLReader ( ) ; acl = rdr . read ( in ) ; } return new PersistedNodeData ( identifier , qpath , parentIdentifier , persistedVersion , orderNum , primaryTypeName , mixinTypeNames , acl ) ; } | Read and set PersistedNodeData data . | 600 | 9 |
15,236 | protected void prepareRenamingApproachScripts ( ) throws DBCleanException { cleaningScripts . addAll ( getTablesRenamingScripts ( ) ) ; cleaningScripts . addAll ( getDBInitializationScripts ( ) ) ; cleaningScripts . addAll ( getFKRemovingScripts ( ) ) ; cleaningScripts . addAll ( getConstraintsRemovingScripts ( ) ) ; cleaningScripts . addAll ( getIndexesDroppingScripts ( ) ) ; committingScripts . addAll ( getOldTablesDroppingScripts ( ) ) ; committingScripts . addAll ( getIndexesAddingScripts ( ) ) ; committingScripts . addAll ( getConstraintsAddingScripts ( ) ) ; committingScripts . addAll ( getFKAddingScripts ( ) ) ; rollbackingScripts . addAll ( getTablesDroppingScripts ( ) ) ; rollbackingScripts . addAll ( getOldTablesRenamingScripts ( ) ) ; } | Prepares scripts for renaming approach database cleaning . | 218 | 10 |
15,237 | protected void prepareDroppingTablesApproachScripts ( ) throws DBCleanException { cleaningScripts . addAll ( getTablesDroppingScripts ( ) ) ; cleaningScripts . addAll ( getDBInitializationScripts ( ) ) ; cleaningScripts . addAll ( getFKRemovingScripts ( ) ) ; cleaningScripts . addAll ( getIndexesDroppingScripts ( ) ) ; committingScripts . addAll ( getIndexesAddingScripts ( ) ) ; committingScripts . addAll ( getFKAddingScripts ( ) ) ; } | Prepares scripts for dropping tables approach database cleaning . | 123 | 10 |
15,238 | protected void prepareSimpleCleaningApproachScripts ( ) { cleaningScripts . addAll ( getFKRemovingScripts ( ) ) ; cleaningScripts . addAll ( getSingleDbWorkspaceCleaningScripts ( ) ) ; committingScripts . addAll ( getFKAddingScripts ( ) ) ; rollbackingScripts . addAll ( getFKAddingScripts ( ) ) ; } | Prepares scripts for simple cleaning database . | 85 | 8 |
15,239 | protected Collection < String > getFKRemovingScripts ( ) { List < String > scripts = new ArrayList < String > ( ) ; String constraintName = "JCR_FK_" + itemTableSuffix + "_PARENT" ; scripts . add ( "ALTER TABLE " + itemTableName + " " + constraintDroppingSyntax ( ) + " " + constraintName ) ; return scripts ; } | Returns SQL scripts for removing FK on JCR_ITEM table . | 88 | 15 |
15,240 | protected Collection < String > getFKAddingScripts ( ) { List < String > scripts = new ArrayList < String > ( ) ; String constraintName = "JCR_FK_" + itemTableSuffix + "_PARENT FOREIGN KEY(PARENT_ID) REFERENCES " + itemTableName + "(ID)" ; scripts . add ( "ALTER TABLE " + itemTableName + " ADD CONSTRAINT " + constraintName ) ; return scripts ; } | Returns SQL scripts for adding FK on JCR_ITEM table . | 103 | 15 |
15,241 | protected Collection < String > getOldTablesDroppingScripts ( ) { List < String > scripts = new ArrayList < String > ( ) ; scripts . add ( "DROP TABLE " + valueTableName + "_OLD" ) ; scripts . add ( "DROP TABLE " + refTableName + "_OLD" ) ; scripts . add ( "DROP TABLE " + itemTableName + "_OLD" ) ; return scripts ; } | Returns SQL scripts for dropping existed old JCR tables . | 92 | 11 |
15,242 | protected Collection < String > getDBInitializationScripts ( ) throws DBCleanException { String dbScripts ; try { dbScripts = DBInitializerHelper . prepareScripts ( wsEntry , dialect ) ; } catch ( IOException e ) { throw new DBCleanException ( e ) ; } catch ( RepositoryConfigurationException e ) { throw new DBCleanException ( e ) ; } List < String > scripts = new ArrayList < String > ( ) ; for ( String query : JDBCUtils . splitWithSQLDelimiter ( dbScripts ) ) { if ( query . contains ( itemTableName + "_SEQ" ) || query . contains ( itemTableName + "_NEXT_VAL" ) ) { continue ; } scripts . add ( JDBCUtils . cleanWhitespaces ( query ) ) ; } scripts . add ( DBInitializerHelper . getRootNodeInitializeScript ( itemTableName , multiDb ) ) ; return scripts ; } | Returns SQL scripts for database initalization . | 207 | 9 |
15,243 | public < T > List < T > getComponentInstancesOfType ( Class < T > componentType ) { return container . getComponentInstancesOfType ( componentType ) ; } | Returns list of components of specific type . | 38 | 8 |
15,244 | public int getState ( ) { boolean hasSuspendedComponents = false ; boolean hasResumedComponents = false ; List < Suspendable > suspendableComponents = getComponentInstancesOfType ( Suspendable . class ) ; for ( Suspendable component : suspendableComponents ) { if ( component . isSuspended ( ) ) { hasSuspendedComponents = true ; } else { hasResumedComponents = true ; } } if ( hasSuspendedComponents && ! hasResumedComponents ) { return ManageableRepository . SUSPENDED ; } else if ( ! hasSuspendedComponents ) { return ManageableRepository . ONLINE ; } else { return ManageableRepository . UNDEFINED ; } } | Returns current workspace state . | 167 | 5 |
15,245 | public void setState ( final int state ) throws RepositoryException { // Need privileges to manage repository. SecurityManager security = System . getSecurityManager ( ) ; if ( security != null ) { security . checkPermission ( JCRRuntimePermissions . MANAGE_REPOSITORY_PERMISSION ) ; } try { SecurityHelper . doPrivilegedExceptionAction ( new PrivilegedExceptionAction < Void > ( ) { public Void run ( ) throws RepositoryException { switch ( state ) { case ManageableRepository . ONLINE : resume ( ) ; break ; case ManageableRepository . OFFLINE : suspend ( ) ; break ; case ManageableRepository . SUSPENDED : suspend ( ) ; break ; default : return null ; } return null ; } } ) ; } catch ( PrivilegedActionException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof RepositoryException ) { throw new RepositoryException ( cause ) ; } else { throw new RuntimeException ( cause ) ; } } } | Set new workspace state . | 221 | 5 |
15,246 | private void suspend ( ) throws RepositoryException { WorkspaceResumer workspaceResumer = getWorkspaceResumer ( ) ; if ( workspaceResumer != null ) { workspaceResumer . onSuspend ( ) ; } List < Suspendable > components = getComponentInstancesOfType ( Suspendable . class ) ; Comparator < Suspendable > c = new Comparator < Suspendable > ( ) { public int compare ( Suspendable s1 , Suspendable s2 ) { return s2 . getPriority ( ) - s1 . getPriority ( ) ; } ; } ; Collections . sort ( components , c ) ; for ( Suspendable component : components ) { try { if ( ! component . isSuspended ( ) ) { component . suspend ( ) ; } } catch ( SuspendException e ) { throw new RepositoryException ( "Can't suspend component" , e ) ; } } } | Suspend all components in workspace . | 198 | 8 |
15,247 | private void resume ( ) throws RepositoryException { WorkspaceResumer workspaceResumer = getWorkspaceResumer ( ) ; if ( workspaceResumer != null ) { workspaceResumer . onResume ( ) ; } // components should be resumed in reverse order List < Suspendable > components = getComponentInstancesOfType ( Suspendable . class ) ; Comparator < Suspendable > c = new Comparator < Suspendable > ( ) { public int compare ( Suspendable s1 , Suspendable s2 ) { return s1 . getPriority ( ) - s2 . getPriority ( ) ; } ; } ; Collections . sort ( components , c ) ; for ( Suspendable component : components ) { try { if ( component . isSuspended ( ) ) { component . resume ( ) ; } } catch ( ResumeException e ) { throw new RepositoryException ( "Can't set component online" , e ) ; } } } | Set all components online . | 205 | 5 |
15,248 | private Set < QName > propertyNames ( HierarchicalProperty body ) { HashSet < QName > names = new HashSet < QName > ( ) ; HierarchicalProperty propBody = body . getChild ( PropertyConstants . DAV_ALLPROP_INCLUDE ) ; if ( propBody != null ) { names . add ( PropertyConstants . DAV_ALLPROP_INCLUDE ) ; } else { propBody = body . getChild ( 0 ) ; } List < HierarchicalProperty > properties = propBody . getChildren ( ) ; Iterator < HierarchicalProperty > propIter = properties . iterator ( ) ; while ( propIter . hasNext ( ) ) { HierarchicalProperty property = propIter . next ( ) ; names . add ( property . getName ( ) ) ; } return names ; } | Returns the set of properties names . | 180 | 7 |
15,249 | protected String getCurrentFolderPath ( GenericWebAppContext context ) { // To limit browsing set Servlet init param "digitalAssetsPath" with desired JCR path String rootFolderStr = ( String ) context . get ( "org.exoplatform.frameworks.jcr.command.web.fckeditor.digitalAssetsPath" ) ; if ( rootFolderStr == null ) rootFolderStr = "/" ; // set current folder String currentFolderStr = ( String ) context . get ( "CurrentFolder" ) ; if ( currentFolderStr == null ) currentFolderStr = "" ; else if ( currentFolderStr . length ( ) < rootFolderStr . length ( ) ) currentFolderStr = rootFolderStr ; return currentFolderStr ; } | Return FCKeditor current folder path . | 158 | 8 |
15,250 | protected String makeRESTPath ( String repoName , String workspace , String resource ) { final StringBuilder sb = new StringBuilder ( 512 ) ; ExoContainer container = ExoContainerContext . getCurrentContainerIfPresent ( ) ; if ( container instanceof PortalContainer ) { PortalContainer pContainer = ( PortalContainer ) container ; sb . append ( ' ' ) . append ( pContainer . getRestContextName ( ) ) . append ( ' ' ) ; } else { sb . append ( ' ' ) . append ( PortalContainer . DEFAULT_REST_CONTEXT_NAME ) . append ( ' ' ) ; } return sb . append ( "jcr/" ) . append ( repoName ) . append ( ' ' ) . append ( workspace ) . append ( resource ) . toString ( ) ; } | Compile REST path of the given resource . | 173 | 9 |
15,251 | protected String getLockToken ( String tokenHash ) { for ( String token : tokens . keySet ( ) ) { if ( tokens . get ( token ) . equals ( tokenHash ) ) { return token ; } } return null ; } | Returns real token if session has it . | 49 | 8 |
15,252 | public LockData getPendingLock ( String nodeId ) { if ( pendingLocks . contains ( nodeId ) ) { return lockedNodes . get ( nodeId ) ; } else { return null ; } } | Return pending lock . | 45 | 4 |
15,253 | public int getNodeIndex ( NodeData parentData , InternalQName name , String skipIdentifier ) throws PathNotFoundException , IllegalPathException , RepositoryException { if ( name instanceof QPathEntry ) { name = new InternalQName ( name . getNamespace ( ) , name . getName ( ) ) ; } int newIndex = 1 ; NodeDefinitionData nodedef = nodeTypeDataManager . getChildNodeDefinition ( name , parentData . getPrimaryTypeName ( ) , parentData . getMixinTypeNames ( ) ) ; List < ItemState > transientAddChilds = getItemStatesList ( parentData , name , ItemState . ADDED , skipIdentifier ) ; List < ItemState > transientDeletedChilds ; if ( nodedef . isAllowsSameNameSiblings ( ) ) { transientDeletedChilds = getItemStatesList ( parentData , name , ItemState . DELETED , null ) ; } else { transientDeletedChilds = getItemStatesList ( parentData , new QPathEntry ( name , 0 ) , ItemState . DELETED , null ) ; ItemData sameNameNode = null ; try { sameNameNode = dataConsumer . getItemData ( parentData , new QPathEntry ( name , 0 ) , ItemType . NODE , false ) ; } catch ( PathNotFoundException e ) { // Ok no same name node; return newIndex ; } if ( ( ( sameNameNode != null ) || ( transientAddChilds . size ( ) > 0 ) ) ) { if ( ( sameNameNode != null ) && ( transientDeletedChilds . size ( ) < 1 ) ) { throw new ItemExistsException ( "The node already exists in " + sameNameNode . getQPath ( ) . getAsString ( ) + " and same name sibling is not allowed " ) ; } else if ( transientAddChilds . size ( ) > 0 ) { throw new ItemExistsException ( "The node already exists in add state " + " and same name sibling is not allowed " ) ; } } } newIndex += transientAddChilds . size ( ) ; List < NodeData > existedChilds = dataConsumer . getChildNodesData ( parentData ) ; // Calculate SNS index for dest root main : for ( int n = 0 , l = existedChilds . size ( ) ; n < l ; n ++ ) { NodeData child = existedChilds . get ( n ) ; if ( child . getQPath ( ) . getName ( ) . equals ( name ) ) { // skip deleted items if ( ! transientDeletedChilds . isEmpty ( ) ) { for ( int i = 0 , length = transientDeletedChilds . size ( ) ; i < length ; i ++ ) { ItemState state = transientDeletedChilds . get ( i ) ; if ( state . getData ( ) . equals ( child ) ) { transientDeletedChilds . remove ( i ) ; continue main ; } } } newIndex ++ ; // next sibling index } } // searching return newIndex ; } | Return new node index . | 656 | 5 |
15,254 | public void setAncestorToSave ( QPath newAncestorToSave ) { if ( ! ancestorToSave . equals ( newAncestorToSave ) ) { isNeedReloadAncestorToSave = true ; } this . ancestorToSave = newAncestorToSave ; } | Set new ancestorToSave . | 64 | 6 |
15,255 | protected void createVersionHistory ( ImportNodeData nodeData ) throws RepositoryException { // Generate new VersionHistoryIdentifier and BaseVersionIdentifier // if uuid changed after UC boolean newVersionHistory = nodeData . isNewIdentifer ( ) || ! nodeData . isContainsVersionhistory ( ) ; if ( newVersionHistory ) { nodeData . setVersionHistoryIdentifier ( IdGenerator . generate ( ) ) ; nodeData . setBaseVersionIdentifier ( IdGenerator . generate ( ) ) ; } PlainChangesLogImpl changes = new PlainChangesLogImpl ( ) ; // using VH helper as for one new VH, all changes in changes log new VersionHistoryDataHelper ( nodeData , changes , dataConsumer , nodeTypeDataManager , nodeData . getVersionHistoryIdentifier ( ) , nodeData . getBaseVersionIdentifier ( ) ) ; if ( ! newVersionHistory ) { for ( ItemState state : changes . getAllStates ( ) ) { if ( ! state . getData ( ) . getQPath ( ) . isDescendantOf ( Constants . JCR_SYSTEM_PATH ) ) { changesLog . add ( state ) ; } } } else { changesLog . addAll ( changes . getAllStates ( ) ) ; } } | Create new version history . | 268 | 5 |
15,256 | protected void checkReferenceable ( ImportNodeData currentNodeInfo , String olUuid ) throws RepositoryException { // if node is in version storage - do not assign new id from jcr:uuid // property if ( Constants . JCR_VERSION_STORAGE_PATH . getDepth ( ) + 3 <= currentNodeInfo . getQPath ( ) . getDepth ( ) && currentNodeInfo . getQPath ( ) . getEntries ( ) [ Constants . JCR_VERSION_STORAGE_PATH . getDepth ( ) + 3 ] . equals ( Constants . JCR_FROZENNODE ) && currentNodeInfo . getQPath ( ) . isDescendantOf ( Constants . JCR_VERSION_STORAGE_PATH ) ) { return ; } String identifier = validateUuidCollision ( olUuid ) ; if ( identifier != null ) { reloadChangesInfoAfterUC ( currentNodeInfo , identifier ) ; } else { currentNodeInfo . setIsNewIdentifer ( true ) ; } if ( uuidBehavior == ImportUUIDBehavior . IMPORT_UUID_COLLISION_REPLACE_EXISTING ) { NodeData parentNode = getParent ( ) ; currentNodeInfo . setParentIdentifer ( parentNode . getIdentifier ( ) ) ; if ( parentNode instanceof ImportNodeData && ( ( ImportNodeData ) parentNode ) . isTemporary ( ) ) { // remove the temporary parent tree . pop ( ) ; } } } | Check uuid collision . If collision happen reload path information . | 322 | 12 |
15,257 | private List < ItemState > getItemStatesList ( NodeData parentData , InternalQName name , int state , String skipIdentifier ) { List < ItemState > states = new ArrayList < ItemState > ( ) ; for ( ItemState itemState : changesLog . getAllStates ( ) ) { ItemData stateData = itemState . getData ( ) ; if ( isParent ( stateData , parentData ) && stateData . getQPath ( ) . getName ( ) . equals ( name ) ) { if ( ( state != 0 ) && ( state != itemState . getState ( ) ) || stateData . getIdentifier ( ) . equals ( skipIdentifier ) ) { continue ; } states . add ( itemState ) ; } } return states ; } | Return list of changes for item . | 163 | 7 |
15,258 | protected ItemState getLastItemState ( String identifer ) { List < ItemState > allStates = changesLog . getAllStates ( ) ; for ( int i = allStates . size ( ) - 1 ; i >= 0 ; i -- ) { ItemState state = allStates . get ( i ) ; if ( state . getData ( ) . getIdentifier ( ) . equals ( identifer ) ) return state ; } return null ; } | Return last item state in changes log . If no state exist return null . | 93 | 15 |
15,259 | private void removeExisted ( NodeData sameUuidItem ) throws RepositoryException , ConstraintViolationException , PathNotFoundException { if ( ! nodeTypeDataManager . isNodeType ( Constants . MIX_REFERENCEABLE , sameUuidItem . getPrimaryTypeName ( ) , sameUuidItem . getMixinTypeNames ( ) ) ) { throw new RepositoryException ( "An incoming referenceable node has the same " + " UUID as a identifier of non mix:referenceable" + " node already existing in the workspace!" ) ; } // If an incoming referenceable node has the same UUID as a node // already existing in the workspace then the already existing // node (and its subtree) is removed from wherever it may be in // the workspace before the incoming node is added. Note that this // can result in nodes disappearing from locations in the // workspace that are remote from the location to which the // incoming subtree is being written. // parentNodeData = (NodeData) sameUuidItem.getParent().getData(); QPath sameUuidPath = sameUuidItem . getQPath ( ) ; if ( ancestorToSave . isDescendantOf ( sameUuidPath ) || ancestorToSave . equals ( sameUuidPath ) ) { throw new ConstraintViolationException ( "The imported document contains a element" + " with jcr:uuid attribute the same as the parent of the import target." ) ; } setAncestorToSave ( QPath . getCommonAncestorPath ( ancestorToSave , sameUuidPath ) ) ; ItemDataRemoveVisitor visitor = new ItemDataRemoveVisitor ( dataConsumer , getAncestorToSave ( ) , nodeTypeDataManager , accessManager , userState ) ; sameUuidItem . accept ( visitor ) ; changesLog . addAll ( visitor . getRemovedStates ( ) ) ; // Refresh the indexes if needed boolean reloadSNS = uuidBehavior == ImportUUIDBehavior . IMPORT_UUID_COLLISION_REMOVE_EXISTING || uuidBehavior == ImportUUIDBehavior . IMPORT_UUID_COLLISION_REPLACE_EXISTING ; if ( reloadSNS ) { NodeData parentData = ( NodeData ) dataConsumer . getItemData ( sameUuidItem . getParentIdentifier ( ) ) ; ItemState lastState = getLastItemState ( sameUuidItem . getParentIdentifier ( ) ) ; if ( sameUuidItem != null && ( lastState == null || ! lastState . isDeleted ( ) ) ) { InternalQName name = new InternalQName ( sameUuidItem . getQPath ( ) . getName ( ) . getNamespace ( ) , sameUuidItem . getQPath ( ) . getName ( ) . getName ( ) ) ; List < ItemState > transientAddChilds = getItemStatesList ( parentData , name , ItemState . ADDED , null ) ; if ( transientAddChilds . isEmpty ( ) ) return ; List < ItemState > statesToReLoad = new LinkedList < ItemState > ( ) ; for ( int i = 0 , length = transientAddChilds . size ( ) ; i < length ; i ++ ) { ItemState state = transientAddChilds . get ( i ) ; if ( sameUuidItem . getQPath ( ) . getIndex ( ) < state . getData ( ) . getQPath ( ) . getIndex ( ) && state . getData ( ) instanceof ImportNodeData ) { statesToReLoad . add ( state ) ; } } if ( statesToReLoad . isEmpty ( ) ) return ; for ( ItemState state : statesToReLoad ) { ImportNodeData node = ( ImportNodeData ) state . getData ( ) ; reloadChangesInfoAfterUC ( parentData , node , node . getIdentifier ( ) ) ; } } } } | Remove existed item . | 844 | 4 |
15,260 | private void removeVersionHistory ( NodeData mixVersionableNode ) throws RepositoryException , ConstraintViolationException , VersionException { try { PropertyData vhpd = ( PropertyData ) dataConsumer . getItemData ( mixVersionableNode , new QPathEntry ( Constants . JCR_VERSIONHISTORY , 1 ) , ItemType . PROPERTY ) ; String vhID = ValueDataUtil . getString ( vhpd . getValues ( ) . get ( 0 ) ) ; VersionHistoryRemover historyRemover = new VersionHistoryRemover ( vhID , dataConsumer , nodeTypeDataManager , repository , currentWorkspaceName , null , ancestorToSave , changesLog , accessManager , userState ) ; historyRemover . remove ( ) ; } catch ( IllegalStateException e ) { throw new RepositoryException ( e ) ; } } | Remove version history of versionable node . | 183 | 8 |
15,261 | protected void notifyListeners ( ) { synchronized ( listeners ) { Thread notifier = new NotifyThread ( listeners . toArray ( new BackupJobListener [ listeners . size ( ) ] ) , this ) ; notifier . start ( ) ; } } | Notify all listeners about the job state changed | 52 | 9 |
15,262 | protected void notifyError ( String message , Throwable error ) { synchronized ( listeners ) { Thread notifier = new ErrorNotifyThread ( listeners . toArray ( new BackupJobListener [ listeners . size ( ) ] ) , this , message , error ) ; notifier . start ( ) ; } } | Notify all listeners about an error | 62 | 7 |
15,263 | private UserProfile readProfile ( Session session , String userName ) throws Exception { Node profileNode ; try { profileNode = utils . getProfileNode ( session , userName ) ; } catch ( PathNotFoundException e ) { return null ; } return readProfile ( userName , profileNode ) ; } | Reads user profile from storage based on user name . | 64 | 11 |
15,264 | private UserProfile removeUserProfile ( Session session , String userName , boolean broadcast ) throws Exception { Node profileNode ; try { profileNode = utils . getProfileNode ( session , userName ) ; } catch ( PathNotFoundException e ) { return null ; } UserProfile profile = readProfile ( userName , profileNode ) ; if ( broadcast ) { preDelete ( profile , broadcast ) ; } profileNode . remove ( ) ; session . save ( ) ; removeFromCache ( profile ) ; if ( broadcast ) { postDelete ( profile ) ; } return profile ; } | Remove user profile from storage . | 120 | 6 |
15,265 | void migrateProfile ( Node oldUserNode ) throws Exception { UserProfile userProfile = new UserProfileImpl ( oldUserNode . getName ( ) ) ; Node attrNode = null ; try { attrNode = oldUserNode . getNode ( JCROrganizationServiceImpl . JOS_PROFILE + "/" + MigrationTool . JOS_ATTRIBUTES ) ; } catch ( PathNotFoundException e ) { return ; } PropertyIterator props = attrNode . getProperties ( ) ; while ( props . hasNext ( ) ) { Property prop = props . nextProperty ( ) ; // ignore system properties if ( ! ( prop . getName ( ) ) . startsWith ( "jcr:" ) && ! ( prop . getName ( ) ) . startsWith ( "exo:" ) && ! ( prop . getName ( ) ) . startsWith ( "jos:" ) ) { userProfile . setAttribute ( prop . getName ( ) , prop . getString ( ) ) ; } } if ( findUserProfileByName ( userProfile . getUserName ( ) ) != null ) { removeUserProfile ( userProfile . getUserName ( ) , false ) ; } saveUserProfile ( userProfile , false ) ; } | Migrates user profile from old storage into new . | 264 | 11 |
15,266 | private void saveUserProfile ( Session session , UserProfile profile , boolean broadcast ) throws RepositoryException , Exception { Node userNode = utils . getUserNode ( session , profile . getUserName ( ) ) ; Node profileNode = getProfileNode ( userNode ) ; boolean isNewProfile = profileNode . isNew ( ) ; if ( broadcast ) { preSave ( profile , isNewProfile ) ; } writeProfile ( profile , profileNode ) ; session . save ( ) ; putInCache ( profile ) ; if ( broadcast ) { postSave ( profile , isNewProfile ) ; } } | Persist user profile to the storage . | 125 | 8 |
15,267 | private Node getProfileNode ( Node userNode ) throws RepositoryException { try { return userNode . getNode ( JCROrganizationServiceImpl . JOS_PROFILE ) ; } catch ( PathNotFoundException e ) { return userNode . addNode ( JCROrganizationServiceImpl . JOS_PROFILE ) ; } } | Create new profile node . | 71 | 5 |
15,268 | private UserProfile readProfile ( String userName , Node profileNode ) throws RepositoryException { UserProfile profile = createUserProfileInstance ( userName ) ; PropertyIterator attributes = profileNode . getProperties ( ) ; while ( attributes . hasNext ( ) ) { Property prop = attributes . nextProperty ( ) ; if ( prop . getName ( ) . startsWith ( ATTRIBUTE_PREFIX ) ) { String name = prop . getName ( ) . substring ( ATTRIBUTE_PREFIX . length ( ) ) ; String value = prop . getString ( ) ; profile . setAttribute ( name , value ) ; } } return profile ; } | Read user profile from storage . | 141 | 6 |
15,269 | private void writeProfile ( UserProfile userProfile , Node profileNode ) throws RepositoryException { for ( Entry < String , String > attribute : userProfile . getUserInfoMap ( ) . entrySet ( ) ) { profileNode . setProperty ( ATTRIBUTE_PREFIX + attribute . getKey ( ) , attribute . getValue ( ) ) ; } } | Write profile to storage . | 77 | 5 |
15,270 | private UserProfile getFromCache ( String userName ) { return ( UserProfile ) cache . get ( userName , CacheType . USER_PROFILE ) ; } | Returns user profile from cache . Can return null . | 35 | 10 |
15,271 | private void putInCache ( UserProfile profile ) { cache . put ( profile . getUserName ( ) , profile , CacheType . USER_PROFILE ) ; } | Putting user profile in cache if profile is not null . | 36 | 11 |
15,272 | private void preSave ( UserProfile userProfile , boolean isNew ) throws Exception { for ( UserProfileEventListener listener : listeners ) { listener . preSave ( userProfile , isNew ) ; } } | Notifying listeners before profile creation . | 42 | 7 |
15,273 | private void postSave ( UserProfile userProfile , boolean isNew ) throws Exception { for ( UserProfileEventListener listener : listeners ) { listener . postSave ( userProfile , isNew ) ; } } | Notifying listeners after profile creation . | 42 | 7 |
15,274 | private void preDelete ( UserProfile userProfile , boolean broadcast ) throws Exception { for ( UserProfileEventListener listener : listeners ) { listener . preDelete ( userProfile ) ; } } | Notifying listeners before profile deletion . | 38 | 7 |
15,275 | private void postDelete ( UserProfile userProfile ) throws Exception { for ( UserProfileEventListener listener : listeners ) { listener . postDelete ( userProfile ) ; } } | Notifying listeners after profile deletion . | 35 | 7 |
15,276 | protected void addScripts ( ) { if ( loadPlugins == null || loadPlugins . size ( ) == 0 ) { return ; } for ( GroovyScript2RestLoaderPlugin loadPlugin : loadPlugins ) { // If no one script configured then skip this item, // there is no reason to do anything. if ( loadPlugin . getXMLConfigs ( ) . size ( ) == 0 ) { continue ; } Session session = null ; try { ManageableRepository repository = repositoryService . getRepository ( loadPlugin . getRepository ( ) ) ; String workspace = loadPlugin . getWorkspace ( ) ; session = repository . getSystemSession ( workspace ) ; String nodeName = loadPlugin . getNode ( ) ; Node node = null ; try { node = ( Node ) session . getItem ( nodeName ) ; } catch ( PathNotFoundException e ) { StringTokenizer tokens = new StringTokenizer ( nodeName , "/" ) ; node = session . getRootNode ( ) ; while ( tokens . hasMoreTokens ( ) ) { String t = tokens . nextToken ( ) ; if ( node . hasNode ( t ) ) { node = node . getNode ( t ) ; } else { node = node . addNode ( t , "nt:folder" ) ; } } } for ( XMLGroovyScript2Rest xg : loadPlugin . getXMLConfigs ( ) ) { String scriptName = xg . getName ( ) ; if ( node . hasNode ( scriptName ) ) { LOG . debug ( "Script {} already created" , scriptName ) ; continue ; } createScript ( node , scriptName , xg . isAutoload ( ) , configurationManager . getInputStream ( xg . getPath ( ) ) ) ; } session . save ( ) ; } catch ( Exception e ) { LOG . error ( "Failed add scripts. " , e ) ; } finally { if ( session != null ) { session . logout ( ) ; } } } } | Add scripts that specified in configuration . | 428 | 7 |
15,277 | protected Node createScript ( Node parent , String name , boolean autoload , InputStream stream ) throws Exception { Node scriptFile = parent . addNode ( name , "nt:file" ) ; Node script = scriptFile . addNode ( "jcr:content" , getNodeType ( ) ) ; script . setProperty ( "exo:autoload" , autoload ) ; script . setProperty ( "jcr:mimeType" , "script/groovy" ) ; script . setProperty ( "jcr:lastModified" , Calendar . getInstance ( ) ) ; script . setProperty ( "jcr:data" , stream ) ; return scriptFile ; } | Create JCR node . | 147 | 5 |
15,278 | protected void setAttributeSmart ( Element element , String attr , String value ) { if ( value == null ) { element . removeAttribute ( attr ) ; } else { element . setAttribute ( attr , value ) ; } } | Set attribute value . If value is null the attribute will be removed . | 49 | 14 |
15,279 | @ POST @ Path ( "load/{repository}/{workspace}/{path:.*}" ) @ RolesAllowed ( { "administrators" } ) public Response load ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ PathParam ( "path" ) String path , @ DefaultValue ( "true" ) @ QueryParam ( "state" ) boolean state , @ QueryParam ( "sources" ) List < String > sources , @ QueryParam ( "file" ) List < String > files , MultivaluedMap < String , String > properties ) { try { return load ( repository , workspace , path , state , properties , createSourceFolders ( sources ) , createSourceFiles ( files ) ) ; } catch ( MalformedURLException e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . BAD_REQUEST ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } } | Deploy groovy script as REST service . If this property set to true then script will be deployed as REST service if false the script will be undeployed . NOTE is script already deployed and state is true script will be re - deployed . | 238 | 48 |
15,280 | @ POST @ Path ( "delete/{repository}/{workspace}/{path:.*}" ) public Response deleteScript ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ PathParam ( "path" ) String path ) { Session ses = null ; try { ses = sessionProviderService . getSessionProvider ( null ) . getSession ( workspace , repositoryService . getRepository ( repository ) ) ; ses . getItem ( "/" + path ) . remove ( ) ; ses . save ( ) ; return Response . status ( Response . Status . NO_CONTENT ) . build ( ) ; } catch ( PathNotFoundException e ) { String msg = "Path " + path + " does not exists" ; LOG . error ( msg ) ; return Response . status ( Response . Status . NOT_FOUND ) . entity ( msg ) . entity ( MediaType . TEXT_PLAIN ) . build ( ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } finally { if ( ses != null ) { ses . logout ( ) ; } } } | Remove node that contains groovy script . | 301 | 8 |
15,281 | @ POST @ Produces ( { "script/groovy" } ) @ Path ( "src/{repository}/{workspace}/{path:.*}" ) public Response getScript ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ PathParam ( "path" ) String path ) { Session ses = null ; try { ses = sessionProviderService . getSessionProvider ( null ) . getSession ( workspace , repositoryService . getRepository ( repository ) ) ; Node scriptFile = ( Node ) ses . getItem ( "/" + path ) ; return Response . status ( Response . Status . OK ) . entity ( scriptFile . getNode ( "jcr:content" ) . getProperty ( "jcr:data" ) . getStream ( ) ) . type ( "script/groovy" ) . build ( ) ; } catch ( PathNotFoundException e ) { String msg = "Path " + path + " does not exists" ; LOG . error ( msg ) ; return Response . status ( Response . Status . NOT_FOUND ) . entity ( msg ) . entity ( MediaType . TEXT_PLAIN ) . build ( ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } finally { if ( ses != null ) { ses . logout ( ) ; } } } | Get source code of groovy script . | 350 | 8 |
15,282 | @ POST @ Produces ( { MediaType . APPLICATION_JSON } ) @ Path ( "meta/{repository}/{workspace}/{path:.*}" ) public Response getScriptMetadata ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ PathParam ( "path" ) String path ) { Session ses = null ; try { ses = sessionProviderService . getSessionProvider ( null ) . getSession ( workspace , repositoryService . getRepository ( repository ) ) ; Node script = ( ( Node ) ses . getItem ( "/" + path ) ) . getNode ( "jcr:content" ) ; ResourceId key = new NodeScriptKey ( repository , workspace , script ) ; ScriptMetadata meta = new ScriptMetadata ( script . getProperty ( "exo:autoload" ) . getBoolean ( ) , // groovyPublisher . isPublished ( key ) , // script . getProperty ( "jcr:mimeType" ) . getString ( ) , // script . getProperty ( "jcr:lastModified" ) . getDate ( ) . getTimeInMillis ( ) ) ; return Response . status ( Response . Status . OK ) . entity ( meta ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } catch ( PathNotFoundException e ) { String msg = "Path " + path + " does not exists" ; LOG . error ( msg ) ; return Response . status ( Response . Status . NOT_FOUND ) . entity ( msg ) . entity ( MediaType . TEXT_PLAIN ) . build ( ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } finally { if ( ses != null ) { ses . logout ( ) ; } } } | Get groovy script s meta - information . | 447 | 9 |
15,283 | @ POST @ Produces ( MediaType . APPLICATION_JSON ) @ Path ( "list/{repository}/{workspace}" ) public Response list ( @ PathParam ( "repository" ) String repository , @ PathParam ( "workspace" ) String workspace , @ QueryParam ( "name" ) String name ) { Session ses = null ; try { ses = sessionProviderService . getSessionProvider ( null ) . getSession ( workspace , repositoryService . getRepository ( repository ) ) ; String xpath = "//element(*, exo:groovyResourceContainer)" ; Query query = ses . getWorkspace ( ) . getQueryManager ( ) . createQuery ( xpath , Query . XPATH ) ; QueryResult result = query . execute ( ) ; NodeIterator nodeIterator = result . getNodes ( ) ; ArrayList < String > scriptList = new ArrayList < String > ( ) ; if ( name == null || name . length ( ) == 0 ) { while ( nodeIterator . hasNext ( ) ) { Node node = nodeIterator . nextNode ( ) ; scriptList . add ( node . getParent ( ) . getPath ( ) ) ; } } else { StringBuilder p = new StringBuilder ( ) ; // add '.*' pattern at the start p . append ( ".*" ) ; for ( int i = 0 ; i < name . length ( ) ; i ++ ) { char c = name . charAt ( i ) ; if ( c == ' ' || c == ' ' ) { p . append ( ' ' ) ; } if ( ".()[]^$|" . indexOf ( c ) != - 1 ) { p . append ( ' ' ) ; } p . append ( c ) ; } // add '.*' pattern at he end p . append ( ".*" ) ; Pattern pattern = Pattern . compile ( p . toString ( ) , Pattern . CASE_INSENSITIVE ) ; while ( nodeIterator . hasNext ( ) ) { Node node = nodeIterator . nextNode ( ) ; String scriptName = node . getParent ( ) . getPath ( ) ; if ( pattern . matcher ( scriptName ) . matches ( ) ) { scriptList . add ( scriptName ) ; } } } Collections . sort ( scriptList ) ; return Response . status ( Response . Status . OK ) . entity ( new ScriptList ( scriptList ) ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) , e ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( e . getMessage ( ) ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; } finally { if ( ses != null ) { ses . logout ( ) ; } } } | Returns the list of all groovy - scripts found in workspace . | 615 | 13 |
15,284 | protected static String getPath ( String fullPath ) { int sl = fullPath . lastIndexOf ( ' ' ) ; return sl > 0 ? "/" + fullPath . substring ( 0 , sl ) : "/" ; } | Extract path to node s parent from full path . | 48 | 11 |
15,285 | protected static String getName ( String fullPath ) { int sl = fullPath . lastIndexOf ( ' ' ) ; return sl >= 0 ? fullPath . substring ( sl + 1 ) : fullPath ; } | Extract node s name from full node path . | 45 | 10 |
15,286 | public HierarchicalProperty getChild ( QName name ) { for ( HierarchicalProperty child : children ) { if ( child . getName ( ) . equals ( name ) ) return child ; } return null ; } | retrieves children property by name . | 46 | 8 |
15,287 | public static String md5 ( String data , String enc ) throws UnsupportedEncodingException { try { return digest ( "MD5" , data . getBytes ( enc ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new InternalError ( "MD5 digest not available???" ) ; } } | Calculate an MD5 hash of the string given . | 66 | 12 |
15,288 | public static String [ ] explode ( String str , int ch , boolean respectEmpty ) { if ( str == null || str . length ( ) == 0 ) { return new String [ 0 ] ; } ArrayList strings = new ArrayList ( ) ; int pos ; int lastpos = 0 ; // add snipples while ( ( pos = str . indexOf ( ch , lastpos ) ) >= 0 ) { if ( pos - lastpos > 0 || respectEmpty ) { strings . add ( str . substring ( lastpos , pos ) ) ; } lastpos = pos + 1 ; } // add rest if ( lastpos < str . length ( ) ) { strings . add ( str . substring ( lastpos ) ) ; } else if ( respectEmpty && lastpos == str . length ( ) ) { strings . add ( "" ) ; } // return stringarray return ( String [ ] ) strings . toArray ( new String [ strings . size ( ) ] ) ; } | returns an array of strings decomposed of the original string split at every occurance of ch . | 203 | 20 |
15,289 | public static String implode ( String [ ] arr , String delim ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i > 0 ) { buf . append ( delim ) ; } buf . append ( arr [ i ] ) ; } return buf . toString ( ) ; } | Concatenates all strings in the string array using the specified delimiter . | 77 | 16 |
15,290 | public static String encodeIllegalXMLCharacters ( String text ) { if ( text == null ) { throw new IllegalArgumentException ( "null argument" ) ; } StringBuilder buf = null ; int length = text . length ( ) ; int pos = 0 ; for ( int i = 0 ; i < length ; i ++ ) { int ch = text . charAt ( i ) ; switch ( ch ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : if ( buf == null ) { buf = new StringBuilder ( ) ; } if ( i > 0 ) { buf . append ( text . substring ( pos , i ) ) ; } pos = i + 1 ; break ; default : continue ; } if ( ch == ' ' ) { buf . append ( "<" ) ; } else if ( ch == ' ' ) { buf . append ( ">" ) ; } else if ( ch == ' ' ) { buf . append ( "&" ) ; } else if ( ch == ' ' ) { buf . append ( """ ) ; } else if ( ch == ' ' ) { buf . append ( "'" ) ; } } if ( buf == null ) { return text ; } else { if ( pos < length ) { buf . append ( text . substring ( pos ) ) ; } return buf . toString ( ) ; } } | Replaces illegal XML characters in the given string by their corresponding predefined entity references . | 304 | 17 |
15,291 | public static String getName ( String path ) { int pos = path . lastIndexOf ( ' ' ) ; return pos >= 0 ? path . substring ( pos + 1 ) : "" ; } | Returns the name part of the path | 41 | 7 |
15,292 | public static boolean isSibling ( String p1 , String p2 ) { int pos1 = p1 . lastIndexOf ( ' ' ) ; int pos2 = p2 . lastIndexOf ( ' ' ) ; return ( pos1 == pos2 && pos1 >= 0 && p1 . regionMatches ( 0 , p2 , 0 , pos1 ) ) ; } | Determines if two paths denote hierarchical siblins . | 79 | 12 |
15,293 | private InternalQName getNodeTypeName ( Node config ) throws IllegalNameException , RepositoryException { String ntString = config . getAttributes ( ) . getNamedItem ( "primaryType" ) . getNodeValue ( ) ; return resolver . parseJCRName ( ntString ) . getInternalName ( ) ; } | Reads the node type of the root node of the indexing aggregate . | 71 | 15 |
15,294 | @ SuppressWarnings ( "unchecked" ) private boolean isIndexRecoveryRequired ( ) throws RepositoryException { // instantiate filters first, if not initialized if ( recoveryFilters == null ) { recoveryFilters = new ArrayList < AbstractRecoveryFilter > ( ) ; log . info ( "Initializing RecoveryFilters." ) ; // add default filter, if none configured. if ( recoveryFilterClasses . isEmpty ( ) ) { this . recoveryFilterClasses . add ( DocNumberRecoveryFilter . class . getName ( ) ) ; } for ( String recoveryFilterClassName : recoveryFilterClasses ) { AbstractRecoveryFilter filter = null ; Class < ? extends AbstractRecoveryFilter > filterClass ; try { filterClass = ( Class < ? extends AbstractRecoveryFilter > ) ClassLoading . forName ( recoveryFilterClassName , this ) ; Constructor < ? extends AbstractRecoveryFilter > constuctor = filterClass . getConstructor ( SearchIndex . class ) ; filter = constuctor . newInstance ( this ) ; recoveryFilters . add ( filter ) ; } catch ( ClassNotFoundException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( InstantiationException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( SecurityException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } catch ( NoSuchMethodException e ) { throw new RepositoryException ( e . getMessage ( ) , e ) ; } } } // invoke filters for ( AbstractRecoveryFilter filter : recoveryFilters ) { if ( filter . accept ( ) ) { return true ; } } return false ; } | Invokes all recovery filters from the set | 444 | 8 |
15,295 | public MultiColumnQueryHits executeQuery ( SessionImpl session , AbstractQueryImpl queryImpl , Query query , QPath [ ] orderProps , boolean [ ] orderSpecs , long resultFetchHint ) throws IOException , RepositoryException { waitForResuming ( ) ; checkOpen ( ) ; workingThreads . incrementAndGet ( ) ; try { FieldComparatorSource scs = queryImpl . isCaseInsensitiveOrder ( ) ? this . sics : this . scs ; Sort sort = new Sort ( createSortFields ( orderProps , orderSpecs , scs ) ) ; final IndexReader reader = getIndexReader ( queryImpl . needsSystemTree ( ) ) ; @ SuppressWarnings ( "resource" ) JcrIndexSearcher searcher = new JcrIndexSearcher ( session , reader , getContext ( ) . getItemStateManager ( ) ) ; searcher . setSimilarity ( getSimilarity ( ) ) ; return new FilterMultiColumnQueryHits ( searcher . execute ( query , sort , resultFetchHint , QueryImpl . DEFAULT_SELECTOR_NAME ) ) { @ Override public void close ( ) throws IOException { try { super . close ( ) ; } finally { PerQueryCache . getInstance ( ) . dispose ( ) ; Util . closeOrRelease ( reader ) ; } } } ; } finally { workingThreads . decrementAndGet ( ) ; if ( isSuspended . get ( ) && workingThreads . get ( ) == 0 ) { synchronized ( workingThreads ) { workingThreads . notifyAll ( ) ; } } } } | Executes the query on the search index . | 347 | 9 |
15,296 | public IndexFormatVersion getIndexFormatVersion ( ) { if ( indexFormatVersion == null ) { if ( getContext ( ) . getParentHandler ( ) instanceof SearchIndex ) { SearchIndex parent = ( SearchIndex ) getContext ( ) . getParentHandler ( ) ; if ( parent . getIndexFormatVersion ( ) . getVersion ( ) < indexRegister . getDefaultIndex ( ) . getIndexFormatVersion ( ) . getVersion ( ) ) { indexFormatVersion = parent . getIndexFormatVersion ( ) ; } else { indexFormatVersion = indexRegister . getDefaultIndex ( ) . getIndexFormatVersion ( ) ; } } else { indexFormatVersion = indexRegister . getDefaultIndex ( ) . getIndexFormatVersion ( ) ; } } return indexFormatVersion ; } | Returns the index format version that this search index is able to support when a query is executed on this index . | 163 | 22 |
15,297 | protected IndexReader getIndexReader ( boolean includeSystemIndex ) throws IOException { // deny query execution if index in offline mode and allowQuery is false if ( ! indexRegister . getDefaultIndex ( ) . isOnline ( ) && ! allowQuery . get ( ) ) { throw new IndexOfflineIOException ( "Index is offline" ) ; } QueryHandler parentHandler = getContext ( ) . getParentHandler ( ) ; CachingMultiIndexReader parentReader = null ; if ( parentHandler instanceof SearchIndex && includeSystemIndex ) { parentReader = ( ( SearchIndex ) parentHandler ) . indexRegister . getDefaultIndex ( ) . getIndexReader ( ) ; } IndexReader reader ; if ( parentReader != null ) { CachingMultiIndexReader [ ] readers = { indexRegister . getDefaultIndex ( ) . getIndexReader ( ) , parentReader } ; reader = new CombinedIndexReader ( readers ) ; } else { reader = indexRegister . getDefaultIndex ( ) . getIndexReader ( ) ; } return new JcrIndexReader ( reader ) ; } | Returns an index reader for this search index . The caller of this method is responsible for closing the index reader when he is finished using it . | 222 | 28 |
15,298 | protected SortField [ ] createSortFields ( QPath [ ] orderProps , boolean [ ] orderSpecs , FieldComparatorSource scs ) throws RepositoryException { List < SortField > sortFields = new ArrayList < SortField > ( ) ; for ( int i = 0 ; i < orderProps . length ; i ++ ) { if ( orderProps [ i ] . getEntries ( ) . length == 1 && Constants . JCR_SCORE . equals ( orderProps [ i ] . getName ( ) ) ) { // order on jcr:score does not use the natural order as // implemented in lucene. score ascending in lucene means that // higher scores are first. JCR specs that lower score values // are first. sortFields . add ( new SortField ( null , SortField . SCORE , orderSpecs [ i ] ) ) ; } else { String jcrPath = npResolver . createJCRPath ( orderProps [ i ] ) . getAsString ( false ) ; sortFields . add ( new SortField ( jcrPath , scs , ! orderSpecs [ i ] ) ) ; } } return sortFields . toArray ( new SortField [ sortFields . size ( ) ] ) ; } | Creates the SortFields for the order properties . | 274 | 11 |
15,299 | public MultiIndex createNewIndex ( String suffix ) throws IOException { IndexInfos indexInfos = new IndexInfos ( ) ; IndexUpdateMonitor indexUpdateMonitor = new DefaultIndexUpdateMonitor ( ) ; IndexerIoModeHandler modeHandler = new IndexerIoModeHandler ( IndexerIoMode . READ_WRITE ) ; MultiIndex newIndex = new MultiIndex ( this , getContext ( ) . getIndexingTree ( ) , modeHandler , indexInfos , indexUpdateMonitor , cloneDirectoryManager ( this . getDirectoryManager ( ) , suffix ) ) ; return newIndex ; } | Create a new index with the same actual context . | 127 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.