idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
15,200
public static String readFileFromClasspath ( String file ) { logger . trace ( "Reading file [{}]..." , file ) ; String content = null ; try ( InputStream asStream = SettingsReader . class . getClassLoader ( ) . getResourceAsStream ( file ) ) { if ( asStream == null ) { logger . trace ( "Can not find [{}] in class loader." , file ) ; return null ; } content = IOUtils . toString ( asStream , "UTF-8" ) ; } catch ( IOException e ) { logger . warn ( "Can not read [{}]." , file ) ; } return content ; }
Read a file content from the classpath
15,201
public static String [ ] getResources ( final String root ) throws URISyntaxException , IOException { logger . trace ( "Reading classpath resources from {}" , root ) ; URL dirURL = ResourceList . class . getClassLoader ( ) . getResource ( root ) ; if ( dirURL != null && dirURL . getProtocol ( ) . equals ( "file" ) ) { logger . trace ( "found a file resource: {}" , dirURL ) ; String [ ] resources = new File ( dirURL . toURI ( ) ) . list ( ) ; Arrays . sort ( resources ) ; return resources ; } if ( dirURL == null ) { String me = ResourceList . class . getName ( ) . replace ( "." , "/" ) + ".class" ; dirURL = ResourceList . class . getClassLoader ( ) . getResource ( me ) ; } if ( dirURL == null ) { throw new RuntimeException ( "can not get resource file " + root ) ; } if ( dirURL . getProtocol ( ) . equals ( "jar" ) ) { logger . trace ( "found a jar file resource: {}" , dirURL ) ; String jarPath = dirURL . getPath ( ) . substring ( 5 , dirURL . getPath ( ) . indexOf ( "!" ) ) ; String prefix = dirURL . getPath ( ) . substring ( 5 + jarPath . length ( ) ) . replaceAll ( "!" , "" ) . substring ( 1 ) ; Set < String > result = new HashSet < > ( ) ; try ( JarFile jar = new JarFile ( URLDecoder . decode ( jarPath , "UTF-8" ) ) ) { Enumeration < JarEntry > entries = jar . entries ( ) ; while ( entries . hasMoreElements ( ) ) { String name = entries . nextElement ( ) . getName ( ) ; if ( name . startsWith ( prefix ) ) { String entry = name . substring ( prefix . length ( ) ) ; int checkSubdir = entry . indexOf ( "/" ) ; if ( checkSubdir >= 0 ) { entry = entry . substring ( 0 , checkSubdir ) ; } result . add ( entry ) ; } } } String [ ] resources = result . toArray ( new String [ result . size ( ) ] ) ; Arrays . sort ( resources ) ; return resources ; } logger . trace ( "did not find any resource. returning empty array" ) ; return NO_RESOURCE ; }
List directory contents for a resource folder . Not recursive . This is basically a brute - force implementation . Works for regular files and also JARs .
15,202
public static List < String > findTemplates ( String root ) throws IOException , URISyntaxException { if ( root == null ) { return findTemplates ( ) ; } logger . debug ( "Looking for templates in classpath under [{}]." , root ) ; final List < String > templateNames = new ArrayList < > ( ) ; String [ ] resources = ResourceList . getResources ( root + "/" + Defaults . TemplateDir + "/" ) ; for ( String resource : resources ) { if ( ! resource . isEmpty ( ) ) { String withoutIndex = resource . substring ( resource . indexOf ( "/" ) + 1 ) ; String template = withoutIndex . substring ( 0 , withoutIndex . indexOf ( Defaults . JsonFileExtension ) ) ; logger . trace ( " - found [{}]." , template ) ; templateNames . add ( template ) ; } } return templateNames ; }
Find all templates
15,203
public static void createIndex ( Client client , String root , String index , boolean force ) throws Exception { String settings = IndexSettingsReader . readSettings ( root , index ) ; createIndexWithSettings ( client , index , settings , force ) ; }
Create a new index in Elasticsearch . Read also _settings . json if exists .
15,204
public static void createIndex ( RestClient client , String index , boolean force ) throws Exception { String settings = IndexSettingsReader . readSettings ( index ) ; createIndexWithSettings ( client , index , settings , force ) ; }
Create a new index in Elasticsearch . Read also _settings . json if exists in default classpath dir .
15,205
private void inflateWidgetLayout ( Context context , int layoutId ) { inflate ( context , layoutId , this ) ; floatingLabel = ( TextView ) findViewById ( R . id . flw_floating_label ) ; if ( floatingLabel == null ) { throw new RuntimeException ( "Your layout must have a TextView whose ID is @id/flw_floating_label" ) ; } View iw = findViewById ( R . id . flw_input_widget ) ; if ( iw == null ) { throw new RuntimeException ( "Your layout must have an input widget whose ID is @id/flw_input_widget" ) ; } try { inputWidget = ( InputWidgetT ) iw ; } catch ( ClassCastException e ) { throw new RuntimeException ( "The input widget is not of the expected type" ) ; } }
Inflate the widget layout and make sure we have everything in there
15,206
public B css ( String ... classes ) { if ( classes != null ) { List < String > failSafeClasses = new ArrayList < > ( ) ; for ( String c : classes ) { if ( c != null ) { if ( c . contains ( " " ) ) { failSafeClasses . addAll ( asList ( c . split ( " " ) ) ) ; } else { failSafeClasses . add ( c ) ; } } } for ( String failSafeClass : failSafeClasses ) { get ( ) . classList . add ( failSafeClass ) ; } } return that ( ) ; }
Adds the specified CSS classes to the class list of the element .
15,207
public B attr ( String name , String value ) { get ( ) . setAttribute ( name , value ) ; return that ( ) ; }
Sets the specified attribute of the element .
15,208
public < V extends Event > B on ( EventType < V , ? > type , EventCallbackFn < V > callback ) { bind ( get ( ) , type , callback ) ; return that ( ) ; }
Adds the given callback to the element .
15,209
public void setInputWidgetText ( CharSequence text , TextView . BufferType type ) { getInputWidget ( ) . setText ( text , type ) ; }
Delegate method for the input widget
15,210
protected void onTextChanged ( String s ) { if ( ! isFloatOnFocusEnabled ( ) ) { if ( s . length ( ) == 0 ) { anchorLabel ( ) ; } else { floatLabel ( ) ; } } if ( editTextListener != null ) editTextListener . onTextChanged ( this , s ) ; }
Called when the text within the input widget is updated
15,211
public static Bitmap applyColor ( Bitmap bitmap , int accentColor ) { int r = Color . red ( accentColor ) ; int g = Color . green ( accentColor ) ; int b = Color . blue ( accentColor ) ; int width = bitmap . getWidth ( ) ; int height = bitmap . getHeight ( ) ; int [ ] pixels = new int [ width * height ] ; bitmap . getPixels ( pixels , 0 , width , 0 , 0 , width , height ) ; for ( int i = 0 ; i < pixels . length ; i ++ ) { int color = pixels [ i ] ; int alpha = Color . alpha ( color ) ; pixels [ i ] = Color . argb ( alpha , r , g , b ) ; } return Bitmap . createBitmap ( pixels , width , height , Bitmap . Config . ARGB_8888 ) ; }
Creates a copy of the bitmap by replacing the color of every pixel by accentColor while keeping the alpha value .
15,212
public static Bitmap changeTintColor ( Bitmap bitmap , int originalColor , int destinationColor ) { int [ ] o = new int [ ] { Color . red ( originalColor ) , Color . green ( originalColor ) , Color . blue ( originalColor ) } ; int [ ] d = new int [ ] { Color . red ( destinationColor ) , Color . green ( destinationColor ) , Color . blue ( destinationColor ) } ; int width = bitmap . getWidth ( ) ; int height = bitmap . getHeight ( ) ; int [ ] pixels = new int [ width * height ] ; bitmap . getPixels ( pixels , 0 , width , 0 , 0 , width , height ) ; int maxIndex = getMaxIndex ( o ) ; int mintIndex = getMinIndex ( o ) ; for ( int i = 0 ; i < pixels . length ; i ++ ) { int color = pixels [ i ] ; int [ ] p = new int [ ] { Color . red ( color ) , Color . green ( color ) , Color . blue ( color ) } ; int alpha = Color . alpha ( color ) ; float [ ] transformation = calculateTransformation ( o [ maxIndex ] , o [ mintIndex ] , p [ maxIndex ] , p [ mintIndex ] ) ; pixels [ i ] = applyTransformation ( d , alpha , transformation ) ; } return Bitmap . createBitmap ( pixels , width , height , Bitmap . Config . ARGB_8888 ) ; }
Creates a copy of the bitmap by calculating the transformation based on the original color and applying it to the the destination color .
15,213
public static Bitmap processTintTransformationMap ( Bitmap transformationMap , int tintColor ) { int [ ] t = new int [ ] { Color . red ( tintColor ) , Color . green ( tintColor ) , Color . blue ( tintColor ) } ; int width = transformationMap . getWidth ( ) ; int height = transformationMap . getHeight ( ) ; int [ ] pixels = new int [ width * height ] ; transformationMap . getPixels ( pixels , 0 , width , 0 , 0 , width , height ) ; float [ ] transformation = new float [ 2 ] ; for ( int i = 0 ; i < pixels . length ; i ++ ) { int color = pixels [ i ] ; int alpha = Color . alpha ( color ) ; transformation [ 0 ] = Color . red ( color ) / 255f ; transformation [ 1 ] = Color . green ( color ) / 255f ; pixels [ i ] = applyTransformation ( t , alpha , transformation ) ; } return Bitmap . createBitmap ( pixels , width , height , Bitmap . Config . ARGB_8888 ) ; }
Apply the given tint color to the transformation map .
15,214
public static void writeToFile ( Bitmap bitmap , String dir , String filename ) throws FileNotFoundException , IOException { File sdCard = Environment . getExternalStorageDirectory ( ) ; File dirFile = new File ( sdCard . getAbsolutePath ( ) + "/" + dir ) ; dirFile . mkdirs ( ) ; File f = new File ( dirFile , filename ) ; FileOutputStream fos = new FileOutputStream ( f , false ) ; bitmap . compress ( CompressFormat . PNG , 100 , fos ) ; fos . flush ( ) ; fos . close ( ) ; }
Write the given bitmap to a file in the external storage . Requires android . permission . WRITE_EXTERNAL_STORAGE permission .
15,215
public static int getIdentifier ( String name ) { Resources res = Resources . getSystem ( ) ; return res . getIdentifier ( name , TYPE_ID , NATIVE_PACKAGE ) ; }
Get a native identifier by name as in R . id . name .
15,216
public static int getStringIdentifier ( String name ) { Resources res = Resources . getSystem ( ) ; return res . getIdentifier ( name , TYPE_STRING , NATIVE_PACKAGE ) ; }
Get a native string id by name as in R . string . name .
15,217
public static int getDrawableIdentifier ( String name ) { Resources res = Resources . getSystem ( ) ; return res . getIdentifier ( name , TYPE_DRAWABLE , NATIVE_PACKAGE ) ; }
Get a native drawable id by name as in R . drawable . name .
15,218
static TodoItemElement create ( Provider < ApplicationElement > application , TodoItemRepository repository ) { return new Templated_TodoItemElement ( application , repository ) ; }
Don t use ApplicationElement directly as this will lead to a dependency cycle in the generated GIN code!
15,219
public void addTintResourceId ( int resId ) { if ( mCustomTintDrawableIds == null ) mCustomTintDrawableIds = new ArrayList < Integer > ( ) ; mCustomTintDrawableIds . add ( resId ) ; }
Add a drawable resource to which to apply the tint technique .
15,220
public void addTintTransformationResourceId ( int resId ) { if ( mCustomTransformationDrawableIds == null ) mCustomTransformationDrawableIds = new ArrayList < Integer > ( ) ; mCustomTransformationDrawableIds . add ( resId ) ; }
Add a drawable resource to which to apply the tint transformation technique .
15,221
private InputStream getTintendResourceStream ( int id , TypedValue value , int color ) { Bitmap bitmap = getBitmapFromResource ( id , value ) ; bitmap = BitmapUtils . applyColor ( bitmap , color ) ; return getStreamFromBitmap ( bitmap ) ; }
Get a reference to a resource that is equivalent to the one requested but with the accent color applied to it .
15,222
private InputStream getTintTransformationResourceStream ( int id , TypedValue value , int color ) { Bitmap bitmap = getBitmapFromResource ( id , value ) ; bitmap = BitmapUtils . processTintTransformationMap ( bitmap , color ) ; return getStreamFromBitmap ( bitmap ) ; }
Get a reference to a resource that is equivalent to the one requested but changing the tint from the original red to the given color .
15,223
public Collection < ItemT > getSelectedItems ( ) { if ( availableItems == null || selectedIndices == null || selectedIndices . length == 0 ) { return new ArrayList < ItemT > ( 0 ) ; } ArrayList < ItemT > items = new ArrayList < ItemT > ( selectedIndices . length ) ; for ( int index : selectedIndices ) { items . add ( availableItems . get ( index ) ) ; } return items ; }
Get the items currently selected
15,224
protected static Bundle buildCommonArgsBundle ( int pickerId , String title , String positiveButtonText , String negativeButtonText , boolean enableMultipleSelection , int [ ] selectedItemIndices ) { Bundle args = new Bundle ( ) ; args . putInt ( ARG_PICKER_ID , pickerId ) ; args . putString ( ARG_TITLE , title ) ; args . putString ( ARG_POSITIVE_BUTTON_TEXT , positiveButtonText ) ; args . putString ( ARG_NEGATIVE_BUTTON_TEXT , negativeButtonText ) ; args . putBoolean ( ARG_ENABLE_MULTIPLE_SELECTION , enableMultipleSelection ) ; args . putIntArray ( ARG_SELECTED_ITEMS_INDICES , selectedItemIndices ) ; return args ; }
Utility method for implementations to create the base argument bundle
15,225
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 .
15,226
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 .
15,227
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 .
15,228
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
15,229
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 .
15,230
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 .
15,231
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 .
15,232
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 .
15,233
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 .
15,234
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 .
15,235
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 .
15,236
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 .
15,237
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 .
15,238
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 .
15,239
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 .
15,240
public static void insertBefore ( Element newElement , Element before ) { before . parentNode . insertBefore ( newElement , before ) ; }
Inserts the specified element into the parent of the before element .
15,241
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 .
15,242
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 .
15,243
public static boolean failSafeRemove ( Node parent , Element child ) { 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 .
15,244
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 .
15,245
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 .
15,246
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 { 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 .
15,247
private void stopDrag ( MotionEvent ev ) { mTouchMode = TOUCH_MODE_IDLE ; 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 = xvel > 0 ; } else { newState = getTargetCheckedState ( ) ; } animateThumbToCheckedState ( newState ) ; } else { animateThumbToCheckedState ( isChecked ( ) ) ; } }
Called from onTouchEvent to end a drag operation .
15,248
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
15,249
@ 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
15,250
void sendAccessibilityEvent ( View view ) { 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
15,251
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 .
15,252
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 .
15,253
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 .
15,254
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
15,255
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 .
15,256
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 .
15,257
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 .
15,258
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 ; } 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 ) ) ; } } } return false ; }
Is a predecessor of the merge version
15,259
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 ; } 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 ) ) ; } } } return false ; }
Is a successor of the merge version
15,260
public PersistedNodeData read ( ObjectReader in ) throws UnknownClassIdException , IOException { 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 ) { 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 ( ) ; InternalQName primaryTypeName ; try { primaryTypeName = InternalQName . parse ( in . readString ( ) ) ; } catch ( final IllegalNameException e ) { throw new IOException ( e . getMessage ( ) ) { private static final long serialVersionUID = 3489809179234435267L ; public Throwable getCause ( ) { return e ; } } ; } 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 ; public Throwable getCause ( ) { return e ; } } ; } } } 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 .
15,261
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 .
15,262
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 .
15,263
protected void prepareSimpleCleaningApproachScripts ( ) { cleaningScripts . addAll ( getFKRemovingScripts ( ) ) ; cleaningScripts . addAll ( getSingleDbWorkspaceCleaningScripts ( ) ) ; committingScripts . addAll ( getFKAddingScripts ( ) ) ; rollbackingScripts . addAll ( getFKAddingScripts ( ) ) ; }
Prepares scripts for simple cleaning database .
15,264
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 .
15,265
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 .
15,266
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 .
15,267
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 .
15,268
public < T > List < T > getComponentInstancesOfType ( Class < T > componentType ) { return container . getComponentInstancesOfType ( componentType ) ; }
Returns list of components of specific type .
15,269
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 .
15,270
public void setState ( final int state ) throws RepositoryException { 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 .
15,271
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 .
15,272
private void resume ( ) throws RepositoryException { WorkspaceResumer workspaceResumer = getWorkspaceResumer ( ) ; if ( workspaceResumer != null ) { workspaceResumer . onResume ( ) ; } 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 .
15,273
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 .
15,274
protected String getCurrentFolderPath ( GenericWebAppContext context ) { String rootFolderStr = ( String ) context . get ( "org.exoplatform.frameworks.jcr.command.web.fckeditor.digitalAssetsPath" ) ; if ( rootFolderStr == null ) rootFolderStr = "/" ; 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 .
15,275
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 .
15,276
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 .
15,277
public LockData getPendingLock ( String nodeId ) { if ( pendingLocks . contains ( nodeId ) ) { return lockedNodes . get ( nodeId ) ; } else { return null ; } }
Return pending lock .
15,278
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 ) { 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 ) ; main : for ( int n = 0 , l = existedChilds . size ( ) ; n < l ; n ++ ) { NodeData child = existedChilds . get ( n ) ; if ( child . getQPath ( ) . getName ( ) . equals ( name ) ) { 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 ++ ; } } return newIndex ; }
Return new node index .
15,279
public void setAncestorToSave ( QPath newAncestorToSave ) { if ( ! ancestorToSave . equals ( newAncestorToSave ) ) { isNeedReloadAncestorToSave = true ; } this . ancestorToSave = newAncestorToSave ; }
Set new ancestorToSave .
15,280
protected void createVersionHistory ( ImportNodeData nodeData ) throws RepositoryException { boolean newVersionHistory = nodeData . isNewIdentifer ( ) || ! nodeData . isContainsVersionhistory ( ) ; if ( newVersionHistory ) { nodeData . setVersionHistoryIdentifier ( IdGenerator . generate ( ) ) ; nodeData . setBaseVersionIdentifier ( IdGenerator . generate ( ) ) ; } PlainChangesLogImpl changes = new PlainChangesLogImpl ( ) ; 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 .
15,281
protected void checkReferenceable ( ImportNodeData currentNodeInfo , String olUuid ) throws RepositoryException { 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 ( ) ) { tree . pop ( ) ; } } }
Check uuid collision . If collision happen reload path information .
15,282
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 .
15,283
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 .
15,284
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!" ) ; } 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 ( ) ) ; 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 .
15,285
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 .
15,286
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
15,287
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
15,288
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 .
15,289
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 .
15,290
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 ( ) ; 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 .
15,291
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 .
15,292
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 .
15,293
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 .
15,294
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 .
15,295
private UserProfile getFromCache ( String userName ) { return ( UserProfile ) cache . get ( userName , CacheType . USER_PROFILE ) ; }
Returns user profile from cache . Can return null .
15,296
private void putInCache ( UserProfile profile ) { cache . put ( profile . getUserName ( ) , profile , CacheType . USER_PROFILE ) ; }
Putting user profile in cache if profile is not null .
15,297
private void preSave ( UserProfile userProfile , boolean isNew ) throws Exception { for ( UserProfileEventListener listener : listeners ) { listener . preSave ( userProfile , isNew ) ; } }
Notifying listeners before profile creation .
15,298
private void postSave ( UserProfile userProfile , boolean isNew ) throws Exception { for ( UserProfileEventListener listener : listeners ) { listener . postSave ( userProfile , isNew ) ; } }
Notifying listeners after profile creation .
15,299
private void preDelete ( UserProfile userProfile , boolean broadcast ) throws Exception { for ( UserProfileEventListener listener : listeners ) { listener . preDelete ( userProfile ) ; } }
Notifying listeners before profile deletion .