Skip to main content
summaryrefslogtreecommitdiffstats
blob: 1414c3ee6c65c27edf1a94ced9a00f01a6501927 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
/*******************************************************************************
 * Copyright (c) 2001, 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 * IBM Corporation - initial API and implementation
 * yyyymmdd bug      Email and other contact information
 * -------- -------- -----------------------------------------------------------
 * 20060112   121199 jesper@selskabet.org - Jesper Møller
 * 20070813   188999 pmoogk@ca.ibm.com - Peter Moogk
 * 20080613   236523 makandre@ca.ibm.com - Andrew Mak, Overwrite setting on Web service wizard is coupled with preference
 * 20080625   237129 makandre@ca.ibm.com - Andrew Mak, Error moving resource: null
 * 20080711   240408 rkklai@ca.ibm.com - Raymond Lai, support case-insensitive platform makeFile when a file with variant case exists
 *******************************************************************************/
package org.eclipse.wst.command.internal.env.common;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.wst.command.internal.env.EnvironmentMessages;
import org.eclipse.wst.command.internal.env.context.PersistentResourceContext;
import org.eclipse.wst.command.internal.env.core.common.StatusUtils;
import org.eclipse.wst.command.internal.env.core.context.ResourceContext;
import org.eclipse.wst.common.environment.Choice;
import org.eclipse.wst.common.environment.IStatusHandler;
import org.eclipse.wst.common.environment.StatusException;



/**
* This class contains useful methods for working with Eclipse resources.
*/
public final class FileResourceUtils
{
  //
  // Keeps the IWorkspace hanging around. See getWorkspace().
  //
  private static IWorkspace workspace_ = null;
  //
  // Keeps the IWorkspaceRoot hanging around. See getWorkspaceRoot().
  //
  private static IWorkspaceRoot root_ = null;
  
//  private static MessageUtils msg_ = new MessageUtils( "org.eclipse.wst.command.internal.env.common.environment", new FileResourceUtils() );


 /**
  * Returns the IWorkspaceRoot object.
  * @return The IWorkspaceRoot object.
  */
  public static IWorkspaceRoot getWorkspaceRoot ()
  {
    if (root_ == null)
    {
      root_ = ResourcesPlugin.getWorkspace().getRoot();
    }
    return root_;
  }

  /**
	 * Returns the IWorkspace object.
	 * 
	 * @return The IWorkspace object.
	 */
  public static IWorkspace getWorkspace ()
  {
    if (workspace_ == null)
    {
      if (root_ == null)
      {
        root_ = ResourcesPlugin.getWorkspace().getRoot();
      }
      
      workspace_ = root_.getWorkspace();
    }
    
    return workspace_;
  }
  
  /**
   * 
   * @return returns an array of three common choices. (ie. Yes, yes all, and cancel )
   */
  public static Choice[] getThreeStateFileOptions() 
  {
    Vector choices = new Vector();
    
    choices.add(new Choice( 'Y', EnvironmentMessages.LABEL_YES));
    choices.add(new Choice( 'A', EnvironmentMessages.LABEL_YES_TO_ALL));
    choices.add(new Choice( 'C', EnvironmentMessages.LABEL_CANCEL));
    
    return (Choice[])choices.toArray(new Choice[choices.size()]);
  }
  
  /**
  * Returns an
  * {@link org.eclipse.core.resources.IResource IResource}
  * of the given absolute pathname or null if no such resource exists.
  * @param absolutePathname The absolute path of the resource.
  * @return The <code>IResource</code>.
  */
  public static IResource findResource ( String absolutePathname )
  {
    if (absolutePathname == null)
    {
      return null;
    }
    
    return findResource(new Path(absolutePathname));
  }

  /**
  * Returns an
  * {@link org.eclipse.core.resources.IResource IResource}
  * of the given absolute path or null if no such resource exists.
  * @param absolutePath The absolute <code>IPath</code> of the resource.
  * @return The <code>IResource</code>.
  */
  public static IResource findResource ( IPath absolutePath )
  {
    if (absolutePath == null)
    {
      return null;
    }
    
    return FileResourceUtils.getWorkspaceRoot().findMember(absolutePath);
  }
  
  /**
   * Copies a file from a plugin's installation location
   * to an Eclipse folder.
   * @param plugin The plugin containing the files to copy.
   * Must not be null.
   * @param sourcePath The path, relative to the <code>plugin</code>
   * install location, containing the files to copy.
   * If null, then the plugin install location is the source path
   * (ie. null is equivalent to ".").
   * @param pathname The pathname of the file to copy.
   * The pathname is relative to the <code>plugin sourcePath</code>.
   * Must not be null.
   * @param targetPath The absolute Eclipse path of the folder to
   * which the file will be copied. The relative pathname of the
   * file is preserved.
   * Must not be null.
   * @param createFolders The intermediate folder creation policy, one of
   * {@link #CREATE CREATE} or {@link #DONT_CREATE DONT_CREATE}.
   * <ul>
   * <li><code>CREATE</code> -
   * If any intermediate folders in the given <code>absolutePath</code>
   * do not exist, they will be created.
   * <li><code>DONT_CREATE</code> -
   * If any intermediate folders in the given <code>absolutePath</code>
   * do not exist, the method will throw a <code>CoreException</code>.
   * </ul>
   * @param overwriteFile The policy for existing files, one of
   * {@link #OVERWRITE OVERWRITE} or {@link #DONT_OVERWRITE DONT_OVERWRITE}.
   * <ul>
   * <li><code>OVERWRITE</code> -
   * If a resource of the same name as the given
   * <code>absolutePath</code> already exists and is a file,
   * it will be replaced.
   * If the resource already exists and it is not a file,
   * then no file will be created and
   * a <code>CoreException</code> will be thrown.
   * <li><code>DONT_OVERWRITE</code> -
   * If any resource of the same name as the given
   * <code>absolutePath</code> already exists,
   * then no file will be created and
   * a <code>CoreException</code> will be thrown.
   * </ul>
   * @param progressMonitor The progress monitor for the operation, or null.
   * @throws CoreException An exception containing an
   * {@link org.eclipse.core.runtime.IStatus IStatus}
   * with a severity of <code>IStatus.ERROR</code> and a
   * locale-specific description of the cause.
   */
   static public void copyFile( ResourceContext resourceContext,
                                Plugin plugin,
                                IPath sourcePath,
                                IPath pathname,
                                IPath targetPath,
                                IProgressMonitor progressMonitor,
                                IStatusHandler statusMonitor )
     throws CoreException
   {
     try
     {
       IPath target = targetPath.append(pathname);
       IPath source = sourcePath == null ? pathname : sourcePath.append(pathname);
       InputStream input = plugin.openStream(source);
       createFile(resourceContext, target, input, progressMonitor, statusMonitor);
     }
     catch (IOException e)
     {
       throw new CoreException(new Status(IStatus.ERROR,
                               plugin.getBundle().getSymbolicName(),
                               0,
                               EnvironmentMessages.MSG_ERROR_IO,e));
     }
   }
   
  /**
   * Deletes a file under a container.
   * The container must already exist.
   * @param file - the IFile to be deleted
   * @param progressMonitor
   * @param statusMonitor
   * @return True if the file does not exist or if it exists and is successfully deleted. False otherwise.
   */
  public static boolean deleteFile( ResourceContext resourceContext, 
                                    IFile file,
                                    IProgressMonitor progressMonitor, 
                                    IStatusHandler statusMonitor)
    throws CoreException
  {
    if (file.exists())
    {
      if (!resourceContext.isOverwriteFilesEnabled())
      {
        IStatus status 
          = StatusUtils.warningStatus( NLS.bind(EnvironmentMessages.MSG_ERROR_FILE_OVERWRITE_DISABLED,
                                                        new Object[]{ file.getParent().getFullPath().toString(),
                                                                      file.getName()}) );
                            
        
        Choice choice = statusMonitor.report( status, getThreeStateFileOptions() );
        
        if( choice.getShortcut() == 'C' ) return false;
        
        if( choice.getShortcut() == 'A' ) {
        	resourceContext.setOverwriteFilesEnabled(true);
        	PersistentResourceContext.getInstance().setOverwriteFilesEnabled(true);
        }
      }
      
      //We have permission to overwrite so check if file is read-only
      if (file.isReadOnly())
      {
        if (!resourceContext.isCheckoutFilesEnabled())
        {
          IStatus status 
            = StatusUtils.warningStatus( NLS.bind(EnvironmentMessages.MSG_ERROR_FILE_CHECKOUT_DISABLED,
                                                          new Object[]{ file.getParent().getFullPath().toString(),
                                                                        file.getName()}) );
          
          Choice choice = statusMonitor.report( status, getThreeStateFileOptions() );
          
          if( choice.getShortcut() == 'C' ) return false;
          
          if( choice.getShortcut() == 'A' ) {
        	  resourceContext.setCheckoutFilesEnabled(true);
        	  PersistentResourceContext.getInstance().setCheckoutFilesEnabled(true);
          }
        }
        
        IFile[] files = new IFile[1];
        files[0] = file;
        IStatus status = getWorkspace().validateEdit(files, null);
        
        if( status.getSeverity() == IStatus.ERROR )
        {
          statusMonitor.reportError( status );
          return false;
        }
      }
      
      file.delete(true, null);
    }
    //At this point, either the file did not exist or we successfully deleted
    // it. Return success.
    return true;
  }

  /**
   * Deletes a folder under a container.
   * @param folder - the IFolder to be deleted
   * @param progressMonitor
   * @param statusMonitor
   * @return True if the folder does not exist or if it exists and is successfully deleted along with its members. False otherwise.
   */
   public static boolean deleteFolder( ResourceContext resourceContext,
                                       IFolder folder,
                                       IProgressMonitor progressMonitor,
                                       IStatusHandler statusMonitor )
     throws CoreException
   {
     if (!folder.exists()) return true;

     boolean     deleted   = true;
     IResource[] resources = folder.members();
     
     for (int i=0; i<resources.length; i++)
     {
       IResource resource = resources[i];
       if (resource instanceof IFile)
       {
         deleted = deleteFile(resourceContext, (IFile)resource, progressMonitor, statusMonitor);
       }
       if (resource instanceof IFolder)
       {
         deleted = deleteFolder( resourceContext, (IFolder)resource, progressMonitor, statusMonitor);
       }

       if( !deleted ) break;
     }
     
     if( deleted )
     {
       folder.delete(true, true, null);
       return true;
     }
     else
       return false;
   }

  /**
  * Creates a file of the given <code>absolutePath</code>
  * and returns its handle as an <code>IFile</code>.
  * If the file cannot be created, a
  * <code>CoreException</code> containing an
  * <code>IStatus</code> object is thrown.
  * @param absolutePath The absolute path of the file to create.
  * The project at the beginning of the path must already exist,
  * that is, this method cannot be used to create projects.
  * @param progressMonitor The progress monitor for the operation, or null.
  * @return The {@link org.eclipse.core.resources.IFile IFile}
  * handle of the file.
  * @throws CoreException An exception containing an
  * {@link org.eclipse.core.runtime.IStatus IStatus}
  * with a severity of <code>IStatus.ERROR</code> and a
  * locale-specific description of the cause.
  */
  public static IFile createFile (
    ResourceContext resourceContext,
    IPath           absolutePath,
    InputStream     inputStream,
    IProgressMonitor progressMonitor,
    IStatusHandler   statusHandler )

    throws CoreException 
  {    
    if (!absolutePath.isAbsolute())
    {
      throw new CoreException(new Status(IStatus.ERROR, "ResourceUtils",0,NLS.bind(EnvironmentMessages.MSG_ERROR_PATH_NOT_ABSOLUTE,new Object[] {absolutePath.toString()}),null));
    }
    if (absolutePath.segmentCount() < 1)
    {
      throw new CoreException(new Status(IStatus.ERROR,"ResourceUtils",0,NLS.bind(EnvironmentMessages.MSG_ERROR_PATH_EMPTY,new Object[] {absolutePath.toString()}),null));
    }
    if (absolutePath.segmentCount() < 2)
    {
      throw new CoreException(new Status(IStatus.ERROR,"ResourceUtils",0,NLS.bind(EnvironmentMessages.MSG_ERROR_PATH_NOT_FOLDER,new Object[] {absolutePath.toString()}),null));
    }
    IContainer parent   = makeFolderPath(resourceContext, absolutePath.removeLastSegments(1), progressMonitor, statusHandler);
    String     fileName = absolutePath.lastSegment();
    
    return makeFile(resourceContext, parent, fileName, inputStream, progressMonitor, statusHandler);
  }

  /**
  * Creates under the given <code>project</code>
  * a file of the given <code>relativePath</code>
  * and returns its handle as an <code>IFile</code>.
  * If the file cannot be created, a
  * <code>CoreException</code> containing an
  * <code>IStatus</code> object is thrown.
  * @param absolutePath The absolute path of the file to create.
  * The project at the beginning of the path must already exist,
  * that is, this method cannot be used to create projects.
  * @param createFolders The intermediate folder creation policy, one of
  * {@link #CREATE CREATE} or {@link #DONT_CREATE DONT_CREATE}.
  * <ul>
  * <li><code>CREATE</code> -
  * If any intermediate folders in the given <code>absolutePath</code>
  * do not exist, they will be created.
  * <li><code>DONT_CREATE</code> -
  * If any intermediate folders in the given <code>absolutePath</code>
  * do not exist, the method will throw a <code>CoreException</code>.
  * </ul>
  * @param overwriteFile The policy for existing files, one of
  * {@link #OVERWRITE OVERWRITE} or {@link #DONT_OVERWRITE DONT_OVERWRITE}.
  * <ul>
  * <li><code>OVERWRITE</code> -
  * If a resource of the same name as the given
  * <code>absolutePath</code> already exists and is a file,
  * it will be replaced.
  * If the resource already exists and it is not a file,
  * then no file will be created and
  * a <code>CoreException</code> will be thrown.
  * <li><code>DONT_OVERWRITE</code> -
  * If any resource of the same name as the given
  * <code>absolutePath</code> already exists,
  * then no file will be created and
  * a <code>CoreException</code> will be thrown.
  * </ul>
  * @param progressMonitor The progress monitor for the operation, or null.
  * @return The {@link org.eclipse.core.resources.IFile IFile}
  * handle of the file.
  * @throws CoreException An exception containing an
  * {@link org.eclipse.core.runtime.IStatus IStatus}
  * with a severity of <code>IStatus.ERROR</code> and a
  * locale-specific description of the cause.
  */
  public static IFile createFile (
    ResourceContext resourceContext,
    IProject        project,
    IPath           relativePath,
    InputStream     inputStream,
    IProgressMonitor progressMonitor,
    IStatusHandler   statusMonitor )
 
    throws CoreException 
  {
    IPath absolutePath = project.getFullPath().append(relativePath);
    return createFile(resourceContext, absolutePath, inputStream, progressMonitor, statusMonitor);
  }

  /**
  * Creates an output stream that can be used to write to the
  * given <code>file</code>. Actual changes to the workspace
  * may occur during creation of the stream, while writing to
  * the stream, or when the stream is closed.
  * A <code>CoreException</code> containing
  * an <code>IStatus</code> will be thrown
  * at some point in the lifecycle of the stream
  * if the file resource cannot be created.
  * @param file The {@link org.eclipse.core.resources.IFile IFile}
  * handle of the file resource to create. The project implied by the
  * pathname of the file must already exist,
  * that is, this method cannot be used to create projects.
  * @param progressMonitor The progress monitor for the operation, or null.
  * @return An <code>OutputStream</code> tied to the file resource.
  * Actual checks of or changes to the workspace may occur as early during
  * stream creation, closure, or any time in between.
  * @throws CoreException An exception containing an
  * {@link org.eclipse.core.runtime.IStatus IStatus}
  * with a severity of <code>IStatus.ERROR</code> and a
  * locale-specific description of the cause.
  * Reasons include:
  * <ol>
  * <li>The project of the given file's path does not exist.
  * <li>A non-file resource of the same name of the given file
  * already exists.
  * <li>A file resource of the same name of the given file
  * already exists, and <code>overwriteFile</code> is false.
  * <li>One or more intermediate folders to the given file
  * do not exist, and <code>createFolders</code> is false.
  * </ol>
  */

  public static OutputStream newFileOutputStream (
       ResourceContext  context,
       IPath            file,
       IProgressMonitor progressMonitor,
       IStatusHandler    statusHandler )
 
  {
    return new FileResourceOutputStream(context, file, progressMonitor, statusHandler);
  }

  //----------------------------------------------------------------------
  // Naughty bits...
  //----------------------------------------------------------------------

  //
  // Creates a path of folders.
  // Do not call with an absolutePath of less than one segment.
  //
  /**
   * Creates a path of folders.
   * Do not call with an absolutePath of less than one segment.
   * @param resourceContext the resource context for making folders.
   * @param absolutePath the path of folders that will be created.
   * @param progressMonitor the progress monitor to be used.
   * @param statusHandler the status handler.
   * @return returns the IContainer of the created folder.
   */
  public static IContainer makeFolderPath (
    ResourceContext  resourceContext,
    IPath            absolutePath,
    IProgressMonitor progressMonitor,
    IStatusHandler    statusHandler )
  
    throws CoreException
  {
    if (absolutePath.segmentCount() <= 1)
    {
      return getWorkspaceRoot().getProject(absolutePath.segment(0));
    }
    else
    {
      IContainer parent = makeFolderPath(resourceContext, absolutePath.removeLastSegments(1), progressMonitor, statusHandler );
      String folderName = absolutePath.lastSegment();
      
      checkParent( parent, absolutePath );
      return makeFolder(resourceContext, parent,folderName, progressMonitor , statusHandler );
    }
  }
  
  private static void checkParent( IContainer parent, IPath absolutePath ) throws CoreException
  {
    if( parent == null )
    {
      // The parent is null, so there must have been problems creating it.  We will throw
      // a CoreException warning for this problem.
      IPath  parentPath = absolutePath.removeLastSegments(1);
      String folderPath = absolutePath.lastSegment();
      throw new CoreException( StatusUtils.warningStatus(
                                  NLS.bind(EnvironmentMessages.MSG_ERROR_FOLDER_CREATION_DISABLED,
                                  new Object[]{ parentPath.toString(), folderPath} ) ) );
    }  
  }
  
  //
  // Creates a folder under a container.
  // The container must already exist.
  //
 private static IFolder makeFolder (
    ResourceContext  resourceContext,
    IContainer       parent,
    String           folderName,
    IProgressMonitor progressMonitor,
    IStatusHandler    statusHandler )
  
  throws CoreException
  {
    IResource child  = parent.findMember(folderName);
    Choice    result = null;
    
    if( child == null )
    {
      if (!resourceContext.isCreateFoldersEnabled())  
      {
        result = statusHandler.report(
                StatusUtils.warningStatus(
                		NLS.bind(EnvironmentMessages.MSG_ERROR_FOLDER_CREATION_DISABLED,
        	                      new Object[]{ parent.getFullPath().toString(), folderName} ) ), 
                getThreeStateFileOptions() );
        
        if( result == null || result.getShortcut() == 'C' )
        {
          return null;
        }
        else if( result.getShortcut() == 'A' )
        {
          resourceContext.setCreateFoldersEnabled(true);
          PersistentResourceContext.getInstance().setCreateFoldersEnabled(true);
        }
      }
      
      IFolder folder = parent.getFolder(new Path(folderName));
      folder.create(true,true,null);
      return folder;
    }
    else if( child.getType() == IResource.FOLDER )
    {
      return (IFolder)child;
    }
    else
    {
      throw new CoreException(
        new Status( IStatus.ERROR, 
                    "ResourceUtils",
                    0, 
                    NLS.bind(EnvironmentMessages.MSG_ERROR_RESOURCE_NOT_FOLDER,
					                 new Object[]{ parent.getFullPath().append(folderName).toString() }),
			null ) );
    }
  }

  //
  // Creates a file under a container.
  // The container must already exist.
  //
 private static IFile makeFile (
    ResourceContext  resourceContext,
    IContainer       parent,
    String           fileName,
    InputStream      inputStream,
    IProgressMonitor progressMonitor,
    IStatusHandler    statusHandler )
 
    throws CoreException
  {
	 IFile file = parent.getFile( new Path(fileName) );

	 // create the file if it doesn't exist
	 if (!file.exists()) {
		 try {
			 file.create( inputStream, true, null);    
			 return file;
		 } catch (CoreException coreException) {
			 // this error only happens in a case-insensitive file system; so ignore the cases.
			 if (coreException.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
				 boolean foundIgnoringCase = false;

				 for (IResource resource : parent.members()) {
					 if (resource.getName().equalsIgnoreCase(fileName)) {
						 // found the file
						 foundIgnoringCase = true;
						 fileName = resource.getName();
						 file = parent.getFile( new Path(fileName));
						 break;
					 }
				 }

				 // can't find the file causing the CASE_VARIANT_EXISTS exception; throw the exception
				 if (!foundIgnoringCase)
					 throw coreException;
			 } else {
				 // throw other exceptions
				 throw coreException;
			 }
		 }
	 }

	 
    Choice    result = null;
    

    if( file.getType() == IResource.FILE )
    {
      if( !resourceContext.isOverwriteFilesEnabled() )   
      {
        result = statusHandler.report( 
              StatusUtils.warningStatus( NLS.bind(EnvironmentMessages.MSG_ERROR_FILE_OVERWRITE_DISABLED,
                                         new Object[] {parent.getFullPath().toString(),fileName}) ),					  		    
              getThreeStateFileOptions() );
        
        if( result == null || result.getShortcut() == 'C' )
        {
          return null;
        }
        else if( result.getShortcut() == 'A' )
        {
          resourceContext.setOverwriteFilesEnabled(true);
          PersistentResourceContext.getInstance().setOverwriteFilesEnabled(true);
        }
      }	
        
      //We have permission to overwrite so check if file is read-only
      if( file.getResourceAttributes() == null )
      {
      	// resource is likely out-of-sync with filesystem
      	throw new CoreException( 
      	          new Status( IStatus.ERROR,
      	                      "ResourceUtils",
      	                      0, 
      	                      file.getFullPath().toString(),
      						  null ) );
      }
      else if( file.getResourceAttributes().isReadOnly() )
      {
        if( !resourceContext.isCheckoutFilesEnabled() ) 
        {            
          result = statusHandler.report( 
                       StatusUtils.errorStatus( NLS.bind(EnvironmentMessages.MSG_ERROR_FILE_CHECKOUT_DISABLED,
                                                new Object[]{ parent.getFullPath().toString(),fileName} ) ), 
                       getThreeStateFileOptions() );
          
          if( result == null || result.getShortcut() == 'C' )
          {
            return null;
		  }
          else if( result.getShortcut() == 'A' )
          {
            resourceContext.setCheckoutFilesEnabled(true);
            PersistentResourceContext.getInstance().setCheckoutFilesEnabled(true);
          }
        }

        IFile[] files = new IFile[1];
        files[0] = (IFile)file;
          
        IStatus status = getWorkspace().validateEdit(files,null);
        
        try
        {
          statusHandler.report( status );
        }
        catch( StatusException exc )
        {
          return null;
        }
      }
      file.setContents( inputStream, true, true, null );
        
      return file;
      
    }
    else
    {
      throw new CoreException( 
        new Status( IStatus.ERROR,
                    "ResourceUtils",
                    0, 
                    NLS.bind(EnvironmentMessages.MSG_ERROR_RESOURCE_NOT_FILE,
		                       new Object[] {parent.getFullPath().append(fileName)}),
		                       null ) );
    }
  }

 
 /**
   * Creates a file of the given <code>absolutePath</code>
   * and returns its handle as an <code>IFile</code>.
   * If the file cannot be created, a
   * <code>CoreException</code> containing an
   * <code>IStatus</code> object is thrown.
   * @param absolutePath The absolute path of the file to create.
   * The project at the beginning of the path must already exist,
   * that is, this method cannot be used to create projects.
   * @param progressMonitor The progress monitor for the operation, or null.
   * @return The {@link org.eclipse.core.resources.IFile IFile}
   * handle of the file.
   * @throws CoreException An exception containing an
   * {@link org.eclipse.core.runtime.IStatus IStatus}
   * with a severity of <code>IStatus.ERROR</code> and a
   * locale-specific description of the cause.
   */
   public static IFile createFileAtLocation (
     ResourceContext resourceContext,
     IPath           absolutePath,
     InputStream     inputStream,
     IProgressMonitor progressMonitor,
     IStatusHandler   statusHandler )

     throws CoreException 
   {    
     if (!absolutePath.isAbsolute())
     {
       throw new CoreException(new Status(IStatus.ERROR, "ResourceUtils",0,NLS.bind(EnvironmentMessages.MSG_ERROR_PATH_NOT_ABSOLUTE,new Object[] {absolutePath.toString()}),null));
     }
     if (absolutePath.segmentCount() < 1)
     {
       throw new CoreException(new Status(IStatus.ERROR,"ResourceUtils",0,NLS.bind(EnvironmentMessages.MSG_ERROR_PATH_EMPTY,new Object[] {absolutePath.toString()}),null));
     }
     if (absolutePath.segmentCount() < 2)
     {
       throw new CoreException(new Status(IStatus.ERROR,"ResourceUtils",0,NLS.bind(EnvironmentMessages.MSG_ERROR_PATH_NOT_FOLDER,new Object[] {absolutePath.toString()}),null));
     }
     IContainer parent   = makeFolderPathAtLocation(resourceContext, absolutePath.removeLastSegments(1), progressMonitor, statusHandler);
     String     fileName = absolutePath.lastSegment();
     
     checkParent( parent, absolutePath );
     
     return makeFile(resourceContext, parent, fileName, inputStream, progressMonitor, statusHandler);
   }

/**
  * Creates a path of folders using absolute filenames.
  * Do not call with an absolutePath of less than one segment.
  * @param resourceContext the resource context for making folders.
  * @param resource the resource that will be created.
  * @param progressMonitor the progress monitor to be used.
  * @param statusHandler the status handler.
  * @return returns the IContainer of the created folder.
  */
 public static IContainer makeFolderPathAtLocation (
   ResourceContext  resourceContext,
   IContainer       resource,
   IProgressMonitor progressMonitor,
   IStatusHandler   statusHandler )
 
   throws CoreException
   {
	 if (resource.exists())
	 {
		 if (resource instanceof IContainer)
		 {
			 return (IContainer) resource;
		 }
		 else
		 {
			 throw new CoreException(
					 new Status( IStatus.ERROR, 
							 "ResourceUtils",
							 0, 
							 NLS.bind(EnvironmentMessages.MSG_ERROR_RESOURCE_NOT_FOLDER,
									 new Object[]{ resource.getFullPath().toString() }),
									 null ) );
		 }
	 }
	 else
	 {
		 IContainer parent = makeFolderPathAtLocation(resourceContext, resource.getParent(), progressMonitor, statusHandler );
		 String folderName = resource.getName();
		 
		 return makeFolder(resourceContext, parent, folderName, progressMonitor , statusHandler );
	 }
 }
 
 /**
  * Creates a path of folders.
  * Do not call with an absolutePath of less than one segment.
  * @param resourceContext the resource context for making folders.
  * @param absolutePath the path of folders that will be created.
  * @param progressMonitor the progress monitor to be used.
  * @param statusHandler the status handler.
  * @return returns the IContainer of the created folder.
  */
 public static IContainer makeFolderPathAtLocation (
   ResourceContext  resourceContext,
   IPath            absolutePath,
   IProgressMonitor progressMonitor,
   IStatusHandler    statusHandler )
 
   throws CoreException
 {
 	return makeFolderPathAtLocation(resourceContext,
 		getWorkspaceRoot().getContainerForLocation(absolutePath),
 		progressMonitor, statusHandler);
 }
 
 

}

Back to the top