Author: stefanegli
Date: Wed Jul 31 14:49:54 2013
New Revision: 1508890

URL: http://svn.apache.org/r1508890
Log:
SLING-2984 : improve import-content wizard:
 * made it a standard import wizard again (still also accessible via context 
menu)
 * warnings if project is not added to a server
 * restricting target location choice to a project and the option to change the 
jcr_root of that project
 * more beautify to come later (not scope of this ticket)

Modified:
    
sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/ISlingLaunchpadServer.java
    
sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/internal/SlingLaunchpadServer.java
    sling/trunk/tooling/ide/eclipse-ui/META-INF/MANIFEST.MF
    sling/trunk/tooling/ide/eclipse-ui/plugin.xml
    
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizard.java
    
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizardPage.java
    
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/SelectionUtils.java

Modified: 
sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/ISlingLaunchpadServer.java
URL: 
http://svn.apache.org/viewvc/sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/ISlingLaunchpadServer.java?rev=1508890&r1=1508889&r2=1508890&view=diff
==============================================================================
--- 
sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/ISlingLaunchpadServer.java
 (original)
+++ 
sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/ISlingLaunchpadServer.java
 Wed Jul 31 14:49:54 2013
@@ -16,6 +16,8 @@
  */
 package org.apache.sling.ide.eclipse.core;
 
+import org.eclipse.core.runtime.IProgressMonitor;
+
 public interface ISlingLaunchpadServer {
 
     public static final int PUBLISH_STATE_NEVER = 1;
@@ -27,7 +29,7 @@ public interface ISlingLaunchpadServer {
     public static final String PROP_CONTEXT_PATH = "launchpad.contextPath";
     public static final String PROP_PORT = "launchpad.port";
 
-    void setPublishState(int publishState);
+    void setPublishState(int publishState, IProgressMonitor monitor);
 
     int getPublishState();
 

Modified: 
sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/internal/SlingLaunchpadServer.java
URL: 
http://svn.apache.org/viewvc/sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/internal/SlingLaunchpadServer.java?rev=1508890&r1=1508889&r2=1508890&view=diff
==============================================================================
--- 
sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/internal/SlingLaunchpadServer.java
 (original)
+++ 
sling/trunk/tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/internal/SlingLaunchpadServer.java
 Wed Jul 31 14:49:54 2013
@@ -23,6 +23,7 @@ import org.eclipse.core.runtime.IProgres
 import org.eclipse.core.runtime.IStatus;
 import org.eclipse.core.runtime.Status;
 import org.eclipse.wst.server.core.IModule;
+import org.eclipse.wst.server.core.IServerWorkingCopy;
 import org.eclipse.wst.server.core.model.ServerDelegate;
 
 public class SlingLaunchpadServer extends ServerDelegate implements 
ISlingLaunchpadServer {
@@ -133,11 +134,17 @@ public class SlingLaunchpadServer extend
     public int getPublishState() {
         return getAttribute(PROP_AUTO_PUBLISH_SETTING, PUBLISH_STATE_NEVER);
     }
-
+    
     @Override
-    public void setPublishState(int publishState) {
+    public void setPublishState(int publishState, IProgressMonitor monitor) {
         System.out.println("[" + Thread.currentThread().getName() + "] Set " + 
PROP_AUTO_PUBLISH_SETTING + " to "
                 + publishState);
-        setAttribute(PROP_AUTO_PUBLISH_SETTING, publishState);
+        IServerWorkingCopy wc = getServer().createWorkingCopy();
+               wc.setAttribute(PROP_AUTO_PUBLISH_SETTING, publishState);
+               try {
+                       wc.save(false, monitor);
+               } catch (CoreException e) {
+                       throw new RuntimeException(e);
+               }
     }
 }

Modified: sling/trunk/tooling/ide/eclipse-ui/META-INF/MANIFEST.MF
URL: 
http://svn.apache.org/viewvc/sling/trunk/tooling/ide/eclipse-ui/META-INF/MANIFEST.MF?rev=1508890&r1=1508889&r2=1508890&view=diff
==============================================================================
--- sling/trunk/tooling/ide/eclipse-ui/META-INF/MANIFEST.MF (original)
+++ sling/trunk/tooling/ide/eclipse-ui/META-INF/MANIFEST.MF Wed Jul 31 14:49:54 
2013
@@ -49,3 +49,4 @@ Import-Package: org.apache.sling.ide.ecl
  org.osgi.framework,
  org.osgi.util.tracker;version="1.5.0"
 Bundle-ActivationPolicy: lazy
+Require-Bundle: org.eclipse.wst.common.project.facet.ui

Modified: sling/trunk/tooling/ide/eclipse-ui/plugin.xml
URL: 
http://svn.apache.org/viewvc/sling/trunk/tooling/ide/eclipse-ui/plugin.xml?rev=1508890&r1=1508889&r2=1508890&view=diff
==============================================================================
--- sling/trunk/tooling/ide/eclipse-ui/plugin.xml (original)
+++ sling/trunk/tooling/ide/eclipse-ui/plugin.xml Wed Jul 31 14:49:54 2013
@@ -78,6 +78,23 @@
          </enablement>
                </objectContribution>
   </extension>
+   <extension
+         point="org.eclipse.ui.importWizards">
+      <category
+            id="org.apache.sling.ide.eclipse.ui.internal.sampleCategory"
+            name="Sling">
+      </category>
+      <wizard
+            category="org.apache.sling.ide.eclipse.ui.internal.sampleCategory"
+            class="org.apache.sling.ide.eclipse.ui.internal.ImportWizard"
+            icon="icons/obj16/sling.gif"
+            id="org.apache.sling.ide.eclipse.ui.internal.ImportWizard"
+            name="Import from Sling Repository">
+         <description>
+            Import a file from the local file system into the workspace.
+         </description>
+      </wizard>
+   </extension>
   
    <!-- Property page for project to select directory to sync -->
    <extension point="org.eclipse.ui.propertyPages"> 
@@ -96,5 +113,5 @@
              </and>
           </enabledWhen>
         </page> 
-    </extension> 
+    </extension>
 </plugin>    

Modified: 
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizard.java
URL: 
http://svn.apache.org/viewvc/sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizard.java?rev=1508890&r1=1508889&r2=1508890&view=diff
==============================================================================
--- 
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizard.java
 (original)
+++ 
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizard.java
 Wed Jul 31 14:49:54 2013
@@ -1,300 +1,300 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.ide.eclipse.ui.internal;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Map;
-
-import org.apache.sling.ide.eclipse.core.ISlingLaunchpadServer;
-import org.apache.sling.ide.eclipse.core.ServerUtil;
-import org.apache.sling.ide.filter.Filter;
-import org.apache.sling.ide.filter.FilterLocator;
-import org.apache.sling.ide.filter.FilterResult;
-import org.apache.sling.ide.serialization.SerializationManager;
-import org.apache.sling.ide.transport.Command;
-import org.apache.sling.ide.transport.Repository;
-import org.apache.sling.ide.transport.RepositoryException;
-import org.apache.sling.ide.transport.ResourceProxy;
-import org.apache.sling.ide.transport.Result;
-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.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ui.IImportWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.wst.server.core.IServer;
-
-/**
- * Renders the import wizard container page for the Slingclipse repository
- * import.
- */
-public class ImportWizard extends Wizard implements IImportWizard {
-       private ImportWizardPage mainPage;
-    private SerializationManager serializationManager;
-
-       /**
-        * Construct a new Import Wizard container instance.
-        */
-       public ImportWizard() {
-               super();
-        Activator activator = Activator.getDefault();
-        serializationManager = activator.getSerializationManager();
-       }
-
-       /*
-        * (non-Javadoc)
-        * 
-        * @see org.eclipse.jface.wizard.Wizard#performFinish()
-        */
-       public boolean performFinish() {
-
-        if (!mainPage.isPageComplete()) {
-            return false;
-        }
-
-        final IServer server = mainPage.getServer();
-
-        IPath destinationPath = mainPage.getResourcePath();
-               
-        final IProject project = 
ResourcesPlugin.getWorkspace().getRoot().getProject(destinationPath.segments()[0]);
-        final IPath projectRelativePath = 
destinationPath.removeFirstSegments(1);
-        final String repositoryPath = mainPage.getRepositoryPath();
-        final IFile filterFile = mainPage.getFilterFile();
-        try {
-            getContainer().run(false, true, new IRunnableWithProgress() {
-
-                @Override
-                public void run(IProgressMonitor monitor) throws 
InvocationTargetException, InterruptedException {
-                    Repository repository = ServerUtil.getRepository(server, 
monitor);
-
-                    monitor.setTaskName("Loading configuration...");
-                    ISlingLaunchpadServer launchpad = (ISlingLaunchpadServer) 
server.loadAdapter(
-                            ISlingLaunchpadServer.class, monitor);
-
-                    int oldPublishState = launchpad.getPublishState();
-                    // TODO disabling publish does not work; since the publish 
is done async
-                    // Not sure if there is a simple workaround. Anyway, the 
only side effect is that we
-                    // make too many calls after the import, functionality is 
not affected
-                    if (server.canPublish().isOK() && oldPublishState != 
ISlingLaunchpadServer.PUBLISH_STATE_NEVER) {
-                        
launchpad.setPublishState(ISlingLaunchpadServer.PUBLISH_STATE_NEVER);
-                    }
-
-                    Filter filter = null;
-                    if (filterFile != null) {
-                        FilterLocator filterLocator = 
Activator.getDefault().getFilterLocator();
-                        InputStream contents = null;
-                        try {
-                            contents = filterFile.getContents();
-                            filter = filterLocator.loadFilter(contents);
-                        } catch (IOException e) {
-                            throw new InvocationTargetException(e);
-                        } catch (CoreException e) {
-                            throw new InvocationTargetException(e);
-                        } finally {
-                            if (contents != null) {
-                                try {
-                                    contents.close();
-                                } catch (IOException e) {
-                                    // don't care
-                                }
-                            }
-                        }
-                    }
-                    monitor.worked(5);
-
-                    try {
-
-                        // TODO: We should try to make this give 'nice' 
progress feedback (aka here's what I'm
-                        // processing)
-                        monitor.setTaskName("Importing...");
-                        monitor.worked(10);
-
-                        // we create the root node and assume this is a folder
-                        createRoot(project, projectRelativePath, 
repositoryPath);
-
-                        crawlChildrenAndImport(repository, filter, 
repositoryPath, project, projectRelativePath);
-
-                        monitor.setTaskName("Import Complete");
-                        monitor.worked(100);
-                    } catch (Exception e) {
-                        throw new InvocationTargetException(e);
-                    } finally {
-                        if (oldPublishState != 
ISlingLaunchpadServer.PUBLISH_STATE_NEVER) {
-                            launchpad.setPublishState(oldPublishState);
-                        }
-                        monitor.done();
-                        }
-
-                }
-
-            });
-        } catch (InvocationTargetException e) {
-            Throwable cause = e.getCause();
-            mainPage.setErrorMessage("Import error : " + cause.getMessage()
-                    + " . Please see the error log for details.");
-            Activator.getDefault().getLog()
-                    .log(new Status(Status.ERROR, Constants.PLUGIN_ID, 
"Repository import failed", cause));
-            return false;
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            return false;
-        }
-
-        return true;
-       }
-
-       /*
-        * (non-Javadoc)
-        * 
-        * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench,
-        * org.eclipse.jface.viewers.IStructuredSelection)
-        */
-       public void init(IWorkbench workbench, IStructuredSelection selection) {
-               setWindowTitle("Repositoy Import"); // NON-NLS-1
-               setNeedsProgressMonitor(true);
-               mainPage = new ImportWizardPage("Import from Repository", 
selection); // NON-NLS-1
-        setDefaultPageImageDescriptor(SharedImages.SLING_LOG);
-
-       }
-
-       /*
-        * (non-Javadoc)
-        * 
-        * @see org.eclipse.jface.wizard.IWizard#addPages()
-        */
-       public void addPages() {
-               super.addPages();
-               addPage(mainPage);
-       }
-       
-    private void createRoot(final IProject project, final IPath 
projectRelativePath, final String repositoryPath)
-            throws CoreException {
-
-        IPath rootImportPath = projectRelativePath.append(repositoryPath);
-
-        for (int i = rootImportPath.segmentCount() - 1; i > 0; i--)
-            createFolder(project, rootImportPath.removeLastSegments(i));
-    }
-
-               /**
-     * Crawls the repository and recursively imports founds resources
-     * 
-     * @param repository the sling repository to import from
-     * @param filter
-     * @param path the current path to import from
-     * @param project the project to create resources in
-     * @param projectRelativePath the path, relative to the project root, 
where the resources should be created
-     * @param tracer
-     * @throws JSONException
-     * @throws RepositoryException
-     * @throws CoreException
-     * @throws IOException
-     */
-       // TODO: This probably should be pushed into the service layer  
-    private void crawlChildrenAndImport(Repository repository, Filter filter, 
String path, IProject project,
-            IPath projectRelativePath) throws RepositoryException, 
CoreException, IOException {
-
-        System.out.println("crawlChildrenAndImport(" + repository + ", " + 
path + ", " + project + ", "
-                + projectRelativePath + ")");
-
-        ResourceProxy resource = 
executeCommand(repository.newListChildrenNodeCommand(path));
-        String primaryType = (String) 
resource.getProperties().get(Repository.JCR_PRIMARY_TYPE);
- 
-               if (Repository.NT_FILE.equals(primaryType)){
-            importFile(repository, path, project, projectRelativePath);
-               }else if (Repository.NT_FOLDER.equals(primaryType)){
-                       createFolder(project, projectRelativePath.append(path));
-               }else if(Repository.NT_RESOURCE.equals(primaryType)){
-                       //DO NOTHING
-        } else {
-                       createFolder(project, projectRelativePath.append(path));
-            Map<String, Object> content = 
executeCommand(repository.newGetNodeContentCommand(path));
-            
-            String out = serializationManager.buildSerializationData(content);
-            if (out != null) {
-                createFile(project, 
projectRelativePath.append(serializationManager.getSerializationFilePath(path)),
-                    out.getBytes("UTF-8"));
-            }
-               }
-
-        System.out.println("Children: " + resource.getChildren());
-
-        for (ResourceProxy child : resource.getChildren()) {
-
-            if 
(Repository.NT_RESOURCE.equals(child.getProperties().get(Repository.JCR_PRIMARY_TYPE)))
 {
-                continue;
-            }
-
-            if (filter != null) {
-                FilterResult filterResult = filter.filter(child.getPath());
-                if (filterResult == FilterResult.DENY) {
-                    continue;
-                }
-            }
-
-            crawlChildrenAndImport(repository, filter, child.getPath(), 
project,
-                    projectRelativePath);
-               }
-       }
-
-    private <T> T executeCommand(Command<T> command) throws 
RepositoryException {
-               
-               Result<T> result = command.execute();
-               return result.get();
-       }       
-       
-    private void importFile(Repository repository, String path, IProject 
project, IPath destinationPath)
-            throws RepositoryException, CoreException {
-
-        System.out.println("importFile: " + path + " -> " + destinationPath);
-
-        byte[] node = executeCommand(repository.newGetNodeCommand(path));
-                       createFile(project, destinationPath.append(path), node 
);
-       }
-       
-       private void createFolder(IProject project, IPath destinationPath) 
throws CoreException{
-
-               IFolder destinationFolder = project.getFolder(destinationPath);
-               if ( destinationFolder.exists() )
-                       return;
-
-               destinationFolder.create(true, true, null /* TODO progress 
monitor */);
-       }
-       
-    private void createFile(IProject project, IPath path, byte[] node) throws 
CoreException {
-               
-               IFile destinationFile = project.getFile(path);
-               if ( destinationFile.exists() ) {
-            /* TODO progress monitor */
-            destinationFile.setContents(new ByteArrayInputStream(node), 
IResource.KEEP_HISTORY, null);
-               } else {
-            /* TODO progress monitor */
-            destinationFile.create(new ByteArrayInputStream(node), true, null);
-               }
-       }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.ide.eclipse.ui.internal;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Map;
+
+import org.apache.sling.ide.eclipse.core.ISlingLaunchpadServer;
+import org.apache.sling.ide.eclipse.core.ServerUtil;
+import org.apache.sling.ide.filter.Filter;
+import org.apache.sling.ide.filter.FilterLocator;
+import org.apache.sling.ide.filter.FilterResult;
+import org.apache.sling.ide.serialization.SerializationManager;
+import org.apache.sling.ide.transport.Command;
+import org.apache.sling.ide.transport.Repository;
+import org.apache.sling.ide.transport.RepositoryException;
+import org.apache.sling.ide.transport.ResourceProxy;
+import org.apache.sling.ide.transport.Result;
+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.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.ui.IImportWizard;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.wst.server.core.IServer;
+
+/**
+ * Renders the import wizard container page for the Slingclipse repository
+ * import.
+ */
+public class ImportWizard extends Wizard implements IImportWizard {
+       private ImportWizardPage mainPage;
+    private SerializationManager serializationManager;
+
+       /**
+        * Construct a new Import Wizard container instance.
+        */
+       public ImportWizard() {
+               super();
+        Activator activator = Activator.getDefault();
+        serializationManager = activator.getSerializationManager();
+       }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see org.eclipse.jface.wizard.Wizard#performFinish()
+        */
+       public boolean performFinish() {
+
+        if (!mainPage.isPageComplete()) {
+            return false;
+        }
+
+        final IServer server = mainPage.getServer();
+
+        IPath destinationPath = mainPage.getResourcePath();
+               
+        final IProject project = 
ResourcesPlugin.getWorkspace().getRoot().getProject(destinationPath.segments()[0]);
+        final IPath projectRelativePath = 
destinationPath.removeFirstSegments(1);
+        final String repositoryPath = mainPage.getRepositoryPath();
+        final IFile filterFile = mainPage.getFilterFile();
+        try {
+            getContainer().run(false, true, new IRunnableWithProgress() {
+
+                @Override
+                public void run(IProgressMonitor monitor) throws 
InvocationTargetException, InterruptedException {
+                    Repository repository = ServerUtil.getRepository(server, 
monitor);
+
+                    monitor.setTaskName("Loading configuration...");
+                    ISlingLaunchpadServer launchpad = (ISlingLaunchpadServer) 
server.loadAdapter(
+                            ISlingLaunchpadServer.class, monitor);
+
+                    int oldPublishState = launchpad.getPublishState();
+                    // TODO disabling publish does not work; since the publish 
is done async
+                    // Not sure if there is a simple workaround. Anyway, the 
only side effect is that we
+                    // make too many calls after the import, functionality is 
not affected
+                    if (server.canPublish().isOK() && oldPublishState != 
ISlingLaunchpadServer.PUBLISH_STATE_NEVER) {
+                        
launchpad.setPublishState(ISlingLaunchpadServer.PUBLISH_STATE_NEVER, monitor);
+                    }
+
+                    Filter filter = null;
+                    if (filterFile != null && filterFile.exists()) {
+                        FilterLocator filterLocator = 
Activator.getDefault().getFilterLocator();
+                        InputStream contents = null;
+                        try {
+                            contents = filterFile.getContents();
+                            filter = filterLocator.loadFilter(contents);
+                        } catch (IOException e) {
+                            throw new InvocationTargetException(e);
+                        } catch (CoreException e) {
+                            throw new InvocationTargetException(e);
+                        } finally {
+                            if (contents != null) {
+                                try {
+                                    contents.close();
+                                } catch (IOException e) {
+                                    // don't care
+                                }
+                            }
+                        }
+                    }
+                    monitor.worked(5);
+
+                    try {
+
+                        // TODO: We should try to make this give 'nice' 
progress feedback (aka here's what I'm
+                        // processing)
+                        monitor.setTaskName("Importing...");
+                        monitor.worked(10);
+
+                        // we create the root node and assume this is a folder
+                        createRoot(project, projectRelativePath, 
repositoryPath);
+
+                        crawlChildrenAndImport(repository, filter, 
repositoryPath, project, projectRelativePath);
+
+                        monitor.setTaskName("Import Complete");
+                        monitor.worked(100);
+                    } catch (Exception e) {
+                        throw new InvocationTargetException(e);
+                    } finally {
+                        if (oldPublishState != 
ISlingLaunchpadServer.PUBLISH_STATE_NEVER) {
+                            launchpad.setPublishState(oldPublishState, 
monitor);
+                        }
+                        monitor.done();
+                        }
+
+                }
+
+            });
+        } catch (InvocationTargetException e) {
+            Throwable cause = e.getCause();
+            mainPage.setErrorMessage("Import error : " + cause.getMessage()
+                    + " . Please see the error log for details.");
+            Activator.getDefault().getLog()
+                    .log(new Status(Status.ERROR, Constants.PLUGIN_ID, 
"Repository import failed", cause));
+            return false;
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            return false;
+        }
+
+        return true;
+       }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench,
+        * org.eclipse.jface.viewers.IStructuredSelection)
+        */
+       public void init(IWorkbench workbench, IStructuredSelection selection) {
+               setWindowTitle("Repositoy Import"); // NON-NLS-1
+               setNeedsProgressMonitor(true);
+               mainPage = new ImportWizardPage("Import from Repository", 
selection); // NON-NLS-1
+        setDefaultPageImageDescriptor(SharedImages.SLING_LOG);
+
+       }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see org.eclipse.jface.wizard.IWizard#addPages()
+        */
+       public void addPages() {
+               super.addPages();
+               addPage(mainPage);
+       }
+       
+    private void createRoot(final IProject project, final IPath 
projectRelativePath, final String repositoryPath)
+            throws CoreException {
+
+        IPath rootImportPath = projectRelativePath.append(repositoryPath);
+
+        for (int i = rootImportPath.segmentCount() - 1; i > 0; i--)
+            createFolder(project, rootImportPath.removeLastSegments(i));
+    }
+
+               /**
+     * Crawls the repository and recursively imports founds resources
+     * 
+     * @param repository the sling repository to import from
+     * @param filter
+     * @param path the current path to import from
+     * @param project the project to create resources in
+     * @param projectRelativePath the path, relative to the project root, 
where the resources should be created
+     * @param tracer
+     * @throws JSONException
+     * @throws RepositoryException
+     * @throws CoreException
+     * @throws IOException
+     */
+       // TODO: This probably should be pushed into the service layer  
+    private void crawlChildrenAndImport(Repository repository, Filter filter, 
String path, IProject project,
+            IPath projectRelativePath) throws RepositoryException, 
CoreException, IOException {
+
+        System.out.println("crawlChildrenAndImport(" + repository + ", " + 
path + ", " + project + ", "
+                + projectRelativePath + ")");
+
+        ResourceProxy resource = 
executeCommand(repository.newListChildrenNodeCommand(path));
+        String primaryType = (String) 
resource.getProperties().get(Repository.JCR_PRIMARY_TYPE);
+ 
+               if (Repository.NT_FILE.equals(primaryType)){
+            importFile(repository, path, project, projectRelativePath);
+               }else if (Repository.NT_FOLDER.equals(primaryType)){
+                       createFolder(project, projectRelativePath.append(path));
+               }else if(Repository.NT_RESOURCE.equals(primaryType)){
+                       //DO NOTHING
+        } else {
+                       createFolder(project, projectRelativePath.append(path));
+            Map<String, Object> content = 
executeCommand(repository.newGetNodeContentCommand(path));
+            
+            String out = serializationManager.buildSerializationData(content);
+            if (out != null) {
+                createFile(project, 
projectRelativePath.append(serializationManager.getSerializationFilePath(path)),
+                    out.getBytes("UTF-8"));
+            }
+               }
+
+        System.out.println("Children: " + resource.getChildren());
+
+        for (ResourceProxy child : resource.getChildren()) {
+
+            if 
(Repository.NT_RESOURCE.equals(child.getProperties().get(Repository.JCR_PRIMARY_TYPE)))
 {
+                continue;
+            }
+
+            if (filter != null) {
+                FilterResult filterResult = filter.filter(child.getPath());
+                if (filterResult == FilterResult.DENY) {
+                    continue;
+                }
+            }
+
+            crawlChildrenAndImport(repository, filter, child.getPath(), 
project,
+                    projectRelativePath);
+               }
+       }
+
+    private <T> T executeCommand(Command<T> command) throws 
RepositoryException {
+               
+               Result<T> result = command.execute();
+               return result.get();
+       }       
+       
+    private void importFile(Repository repository, String path, IProject 
project, IPath destinationPath)
+            throws RepositoryException, CoreException {
+
+        System.out.println("importFile: " + path + " -> " + destinationPath);
+
+        byte[] node = executeCommand(repository.newGetNodeCommand(path));
+                       createFile(project, destinationPath.append(path), node 
);
+       }
+       
+       private void createFolder(IProject project, IPath destinationPath) 
throws CoreException{
+
+               IFolder destinationFolder = project.getFolder(destinationPath);
+               if ( destinationFolder.exists() )
+                       return;
+
+               destinationFolder.create(true, true, null /* TODO progress 
monitor */);
+       }
+       
+    private void createFile(IProject project, IPath path, byte[] node) throws 
CoreException {
+               
+               IFile destinationFile = project.getFile(path);
+               if ( destinationFile.exists() ) {
+            /* TODO progress monitor */
+            destinationFile.setContents(new ByteArrayInputStream(node), 
IResource.KEEP_HISTORY, null);
+               } else {
+            /* TODO progress monitor */
+            destinationFile.create(new ByteArrayInputStream(node), true, null);
+               }
+       }
+}

Modified: 
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizardPage.java
URL: 
http://svn.apache.org/viewvc/sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizardPage.java?rev=1508890&r1=1508889&r2=1508890&view=diff
==============================================================================
--- 
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizardPage.java
 (original)
+++ 
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/ImportWizardPage.java
 Wed Jul 31 14:49:54 2013
@@ -1,287 +1,436 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.ide.eclipse.ui.internal;
-
-
-import java.io.File;
-import java.util.List;
-
-import org.apache.sling.ide.eclipse.core.ProjectUtil;
-import org.apache.sling.ide.filter.FilterLocator;
-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.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.WizardResourceImportPage;
-import org.eclipse.wst.server.core.IServer;
-import org.eclipse.wst.server.core.ServerCore;
-
-/**
- * Wizard page for importing content from Sling Repositories.
- */
-public class ImportWizardPage extends WizardResourceImportPage {
-
-       private IStructuredSelection selection;
-       private Text path;
-       private ModifyListener modifyListener = new ModifyListener() {
-               @Override
-               public void modifyText(ModifyEvent event) {
-            determinePageCompletion();
-            updateWidgetEnablements();
-               }
-       };
-    private Combo repositoryCombo;
-    private Label importLabel;
-
-       /**
-        * Creates an import wizard page for importing from a Sling Repository. 
If
-        * the initial resource selection contains exactly one container 
resource
-        * then it will be used as the default import destination. Multiple
-        * selections are not supported, but are not disallowed.
-        * 
-        * @param pageName
-        *            the name of the page
-        * @param selection
-        *            the current resource selection
-        */
-       public ImportWizardPage(String pageName, IStructuredSelection 
selection) {
-               super(pageName, selection);
-               this.selection = selection;
-               setTitle(pageName); // NON-NLS-1
-               setDescription("Import content from a Sling Repository into the 
workspace"); // NON-NLS-1
-
-        IProject project = getProject(selection);
-        
setContainerFieldValue(project.getFullPath().append(ProjectUtil.getSyncDirectoryValue(project)).toOSString());
-       }
-
-    private IProject getProject(IStructuredSelection selection) {
-        return (IProject) selection.getFirstElement();
-    }
-
-       /*
-        * (non-Javadoc)
-        * 
-        * @see
-        * 
org.eclipse.ui.dialogs.WizardResourceImportPage#allowNewContainerName()
-        */
-       @Override
-       protected boolean allowNewContainerName() {
-               return false;
-       }
-
-       @Override
-       protected void createOptionsGroup(Composite parent) {
-
-        // not really options but to placement is good enough
-        Composite container = new Composite(parent, SWT.NONE);
-        container.setLayout(new GridLayout());
-        GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
-        container.setLayoutData(gridData);
-
-        importLabel = new Label(container, SWT.NONE);
-
-       }
-
-    @Override
-       protected void createSourceGroup(Composite parent) {
-
-               Composite container = new Composite(parent, SWT.NONE);
-               container.setLayout(new GridLayout(2, false));
-               GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, 
false);
-               gridData.minimumWidth = 450;
-               container.setLayoutData(gridData);
-
-        new Label(container, SWT.NONE).setText("Repository: ");
-
-        repositoryCombo = new Combo(container, SWT.DROP_DOWN);
-        repositoryCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, 
false));
-        List<IServer> servers = 
SelectionUtils.getServersLinkedToProject(selection, new NullProgressMonitor());
-        if (servers.size() > 1) {
-            repositoryCombo.add(""); // force selection only if there is more 
than one server
-        }
-        for (IServer server : servers) {
-            repositoryCombo.add(server.getId());
-        }
-
-        if (servers.size() == 1) {
-            repositoryCombo.select(0);
-        }
-
-        Label pathLabel = new Label(container, SWT.NONE);
-        pathLabel.setText("Repository Path:");
-        path = new Text(container, SWT.BORDER);
-        path.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-        path.addModifyListener(modifyListener);
-       }
-
-       /*
-        * (non-Javadoc)
-        * 
-        * @see 
org.eclipse.ui.dialogs.WizardResourceImportPage#getFileProvider()
-        */
-       @Override
-       protected ITreeContentProvider getFileProvider() {
-               // TODO Not sure if I need to return anything here...
-               return null;
-       }
-
-       /*
-        * (non-Javadoc)
-        * 
-        * @see 
org.eclipse.ui.dialogs.WizardResourceImportPage#getFolderProvider()
-        */
-       @Override
-       protected ITreeContentProvider getFolderProvider() {
-               // TODO Not sure if I need to return anything here...
-               return null;
-       }
-
-       /**
-        * Returns the path from which to import from the Sling Repository.
-        * 
-        * @return the repository path
-        */
-       public String getRepositoryPath() {
-               return path != null ? path.getText() : null;
-       }
-
-       public void handleEvent(Event event) {
-               super.handleEvent(event);
-               determinePageCompletion();
-       }
-
-    @Override
-    public IPath getResourcePath() {
-        return super.getResourcePath();
-    }
-
-    public IServer getServer() {
-        for (IServer server : ServerCore.getServers())
-            if (server.getId().equals(repositoryCombo.getText()))
-                return server;
-
-        return null;
-    }
-
-       /*
-        * (non-Javadoc)
-        * 
-        * @see 
org.eclipse.ui.dialogs.WizardDataTransferPage#validateOptionsGroup()
-        */
-       @Override
-       protected boolean validateOptionsGroup() {
-        if (this.repositoryCombo == null || 
this.repositoryCombo.getSelectionIndex() == -1) {
-            setErrorMessage("Please select a valid index");
-                       return false;
-               }
-               
-               if ( !getRepositoryPath().startsWith("/") ) {
-                       setErrorMessage("The repository path needs to be 
absolute");
-                       return false;
-               }
-               
-        IProject project = getProject(selection);
-        String syncDirectoryPath = ProjectUtil.getSyncDirectoryValue(project);
-        IFolder syncFolder = project.getFolder(syncDirectoryPath);
-
-        if (!syncFolder.getFullPath().isPrefixOf(getResourcePath())) {
-            setErrorMessage("The destination directory must be " + 
syncFolder.getFullPath().toPortableString()
-                    + " or one of its descendants.");
-                       return false;
-               }
-               
-               return true;
-       }
-
-    @Override
-    protected void updateWidgetEnablements() {
-        super.updateWidgetEnablements();
-
-        // called too early
-        if (importLabel == null) {
-            return;
-        }
-
-        IResource syncLocation = 
getProject(selection).getWorkspace().getRoot().findMember(getResourcePath());
-        // error message will be displayed, no need for the info label
-        if (syncLocation == null) {
-            importLabel.setVisible(false);
-            importLabel.getParent().layout();
-            return;
-        }
-
-        IFile filterFile = getFilter(syncLocation);
-
-        if (filterFile.exists()) {
-            importLabel.setText("Will apply import filter from /" + 
filterFile.getProjectRelativePath() + ".");
-        } else {
-            importLabel.setText("No filter found at /" + 
filterFile.getProjectRelativePath()
-                    + ", will import all resources.");
-        }
-        importLabel.setVisible(true);
-        importLabel.getParent().layout();
-    }
-
-    public IFile getFilterFile() {
-
-        IResource syncLocation = 
getProject(selection).getWorkspace().getRoot().findMember(getResourcePath());
-        if (syncLocation == null) {
-            return null;
-        }
-
-        return getFilter(syncLocation);
-    }
-
-    private IFile getFilter(IResource syncLocation) {
-
-        FilterLocator filterLocator = 
Activator.getDefault().getFilterLocator();
-        File filterLocation = 
filterLocator.findFilterLocation(syncLocation.getLocation().toFile());
-        IPath filterPath = Path.fromOSString(filterLocation.getAbsolutePath());
-        return 
ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(filterPath);
-    }
-
-       /*
-        * (non-Javadoc)
-        * 
-        * @see 
org.eclipse.ui.dialogs.WizardDataTransferPage#validateSourceGroup()
-        */
-       @Override
-       protected boolean validateSourceGroup() {
-               if (getRepositoryPath() == null
-                               || getRepositoryPath().trim().length() == 0) {
-                       setErrorMessage("Please enter a valid Sling Repository 
path");
-                       return false;
-               }
-               return true;
-       }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.ide.eclipse.ui.internal;
+
+
+import java.io.File;
+import java.util.List;
+
+import org.apache.sling.ide.eclipse.core.ProjectUtil;
+import org.apache.sling.ide.filter.FilterLocator;
+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.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.preference.PreferenceDialog;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Link;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.dialogs.ContainerSelectionDialog;
+import org.eclipse.ui.dialogs.ISelectionValidator;
+import org.eclipse.ui.dialogs.PreferencesUtil;
+import org.eclipse.ui.dialogs.WizardDataTransferPage;
+import org.eclipse.wst.server.core.IServer;
+import org.eclipse.wst.server.core.ServerCore;
+
+/**
+ * Wizard page for importing content from Sling Repositories.
+ */
+public class ImportWizardPage extends WizardDataTransferPage {
+
+       private Text path;
+       private ModifyListener modifyListener = new ModifyListener() {
+               @Override
+               public void modifyText(ModifyEvent event) {
+            determinePageCompletion();
+            updateWidgetEnablements();
+               }
+       };
+    private Combo repositoryCombo;
+    private Label importLabel;
+       private Button containerBrowseButton;
+       private IProject project;
+       private Text containerNameField;
+       private Label adjustJcrRootText;
+
+       /**
+        * Creates an import wizard page for importing from a Sling Repository. 
If
+        * the initial resource selection contains exactly one container 
resource
+        * then it will be used as the default import destination. Multiple
+        * selections are not supported, but are not disallowed.
+        * 
+        * @param pageName
+        *            the name of the page
+        * @param selection
+        *            the current resource selection
+        */
+       public ImportWizardPage(String pageName, IStructuredSelection 
selection) {
+               super(pageName);
+               setTitle(pageName); // NON-NLS-1
+               setDescription("Import content from a Sling Repository into the 
workspace"); // NON-NLS-1
+
+               if (selection!=null && selection.getFirstElement()!=null && 
(selection.getFirstElement() instanceof IProject)) {
+                       this.project = (IProject) selection.getFirstElement();
+               }
+       }
+       
+    IPath getResourcePath() {
+        String resourcePath = 
project.getFullPath().append(ProjectUtil.getSyncDirectoryValue(project)).toOSString();
+       return new Path(resourcePath);
+       }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see
+        * 
org.eclipse.ui.dialogs.WizardResourceImportPage#allowNewContainerName()
+        */
+       @Override
+       protected boolean allowNewContainerName() {
+               return false;
+       }
+
+       @Override
+       protected void createOptionsGroup(Composite parent) {
+
+        // not really options but to placement is good enough
+        Composite container = new Composite(parent, SWT.NONE);
+        container.setLayout(new GridLayout());
+        GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
+        container.setLayoutData(gridData);
+
+        importLabel = new Label(container, SWT.NONE);
+
+       }
+       
+       @Override
+       public void createControl(Composite parent) {
+        Composite composite = new Composite(parent, SWT.NULL);
+        composite.setLayout(new GridLayout());
+        composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL
+                | GridData.HORIZONTAL_ALIGN_FILL));
+        composite.setSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+
+               Composite container = new Composite(composite, SWT.NONE);
+               container.setLayout(new GridLayout(2, false));
+               GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, 
false);
+               gridData.minimumWidth = 450;
+               container.setLayoutData(gridData);
+
+        new Label(container, SWT.NONE).setText("Repository: ");
+
+        repositoryCombo = new Combo(container, SWT.DROP_DOWN);
+        repositoryCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, 
false));
+        repositoryCombo.addSelectionListener(new SelectionListener() {
+                       
+                       @Override
+                       public void widgetSelected(SelectionEvent e) {
+                   determinePageCompletion();
+                   updateWidgetEnablements();
+                       }
+                       
+                       @Override
+                       public void widgetDefaultSelected(SelectionEvent e) {
+                   determinePageCompletion();
+                   updateWidgetEnablements();
+                       }
+               });
+        updateRepositoryList();
+
+        Label pathLabel = new Label(container, SWT.NONE);
+        pathLabel.setText("Repository Path:");
+        path = new Text(container, SWT.BORDER);
+        path.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+        path.addModifyListener(modifyListener);
+        
+        Composite containerGroup = new Composite(composite, SWT.NONE);
+        GridLayout layout = new GridLayout();
+        layout.numColumns = 3;
+        containerGroup.setLayout(layout);
+        containerGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, 
false, 2, 1));
+        containerGroup.setFont(composite.getFont());
+
+        // container label
+        Label resourcesLabel = new Label(containerGroup, SWT.NONE);
+        resourcesLabel.setText("Import into:");
+        resourcesLabel.setFont(composite.getFont());
+
+        containerNameField = new Text(containerGroup, SWT.SINGLE | SWT.BORDER);
+        containerNameField.addListener(SWT.Modify, this);
+        GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL
+                | GridData.GRAB_HORIZONTAL);
+        data.widthHint = SIZING_TEXT_FIELD_WIDTH;
+        containerNameField.setLayoutData(data);
+        containerNameField.setFont(composite.getFont());
+
+        containerBrowseButton = new Button(containerGroup, SWT.PUSH);
+        containerBrowseButton.setText("Select Project...");
+        containerBrowseButton.setLayoutData(new GridData(
+                GridData.HORIZONTAL_ALIGN_FILL));
+        containerBrowseButton.addListener(SWT.Selection, this);
+        containerBrowseButton.setFont(composite.getFont());
+        setButtonLayoutData(containerBrowseButton);
+        
+        if (project!=null) {
+               containerNameField.setText(project.getName());
+        } else {
+               setErrorMessage("Select a project first");
+        }
+        
+        adjustJcrRootText = new Label(composite, SWT.NONE);
+        adjustJcrRootText.setFont(containerGroup.getFont());
+        adjustJcrRootText();
+        
+        Link openPropertiesLink = new Link(composite, SWT.NONE);
+        openPropertiesLink.setText("<a>Modify location here</a>");
+        openPropertiesLink.addSelectionListener(new SelectionAdapter() {
+                       
+                       public void widgetSelected(SelectionEvent e) {
+                               PreferenceDialog dialog = 
PreferencesUtil.createPropertyDialogOn(getShell(), project, 
+                                               
"org.apache.sling.ide.projectPropertyPage", 
+                                               new String[] 
{"org.apache.sling.ide.projectPropertyPage"}, null);
+                               dialog.open();
+                               updateWidgetEnablements();
+                       }
+               });
+        
+        
+        
+        createOptionsGroup(composite);
+        
+        setControl(composite);
+
+        setPageComplete(false);
+       }
+
+       private void updateRepositoryList() {
+               repositoryCombo.removeAll();
+               List<IServer> servers = 
SelectionUtils.getServersLinkedToProject(project, new NullProgressMonitor());
+        if (servers.size() > 1) {
+            repositoryCombo.add(""); // force selection only if there is more 
than one server
+        }
+        for (IServer server : servers) {
+            repositoryCombo.add(server.getId());
+        }
+
+        if (servers.size() == 1) {
+            repositoryCombo.select(0);
+        }
+       }
+
+    /**
+        * Returns the path from which to import from the Sling Repository.
+        * 
+        * @return the repository path
+        */
+       public String getRepositoryPath() {
+               return path != null ? path.getText() : null;
+       }
+
+       public void handleEvent(Event event) {
+               if (event.widget == containerBrowseButton) {
+                       handleContainerBrowseButtonPressed();
+               }
+               
+               determinePageCompletion();
+       }
+
+    protected IPath queryForProject(IProject initialSelection, String msg,
+            String title) {
+        ContainerSelectionDialog dialog = new ContainerSelectionDialog(
+                getControl().getShell(), initialSelection,
+                allowNewContainerName(), msg);
+        if (title != null) {
+                       dialog.setTitle(title);
+               }
+        dialog.showClosedProjects(false);
+        dialog.setValidator(new ISelectionValidator() {
+                       
+                       @Override
+                       public String isValid(Object selection) {
+                               if (!(selection instanceof IPath)) {
+                                       return "You must select a project";
+                               } 
+                               IWorkspaceRoot root = 
ResourcesPlugin.getWorkspace().getRoot();
+                       IContainer container = (IContainer) root
+                               .findMember((IPath) selection);
+                               if (container instanceof IProject) {
+                                       return null;
+                               } else {
+                                       return "You must select a project";
+                               }
+                       }
+               });
+        dialog.open();
+        Object[] result = dialog.getResult();
+        if (result != null && result.length == 1) {
+            return (IPath) result[0];
+        }
+        return null;
+    }
+
+    private void handleContainerBrowseButtonPressed() {
+       IPath result = queryForProject(project, "Select a project to import 
data to", "Select project");
+       if (result!=null) {
+                       IWorkspaceRoot root = 
ResourcesPlugin.getWorkspace().getRoot();
+               project = root
+                       .findMember(result).getProject();
+               
+               containerNameField.setText(project.getName());
+               updateRepositoryList();
+       }
+       }
+
+       public IServer getServer() {
+        for (IServer server : ServerCore.getServers())
+            if (server.getId().equals(repositoryCombo.getText()))
+                return server;
+
+        return null;
+    }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see 
org.eclipse.ui.dialogs.WizardDataTransferPage#validateOptionsGroup()
+        */
+       @Override
+       protected boolean validateOptionsGroup() {
+               if (getControl() == null) {
+                       // still under construction
+                       return true;
+               }
+        if (this.repositoryCombo == null || 
this.repositoryCombo.getSelectionIndex() == -1) {
+            setErrorMessage("Please select a valid index");
+                       return false;
+               }
+               
+               if ( !getRepositoryPath().startsWith("/") ) {
+                       setErrorMessage("The repository path needs to be 
absolute");
+                       return false;
+               }
+               
+        String syncDirectoryPath = ProjectUtil.getSyncDirectoryValue(project);
+        IFolder syncFolder = project.getFolder(syncDirectoryPath);
+
+        if (!syncFolder.getFullPath().isPrefixOf(getResourcePath())) {
+            setErrorMessage("The destination directory must be " + 
syncFolder.getFullPath().toPortableString()
+                    + " or one of its descendants.");
+                       return false;
+               }
+               
+               return true;
+       }
+
+    @Override
+    protected void updateWidgetEnablements() {
+        super.updateWidgetEnablements();
+        
+        boolean pageComplete = determinePageCompletion();
+        setPageComplete(pageComplete);
+        if (pageComplete) {
+                       setMessage(null);
+               }
+
+        // called too early
+        if (importLabel == null) {
+            return;
+        }
+
+        IResource syncLocation = 
project.getWorkspace().getRoot().findMember(getResourcePath());
+        // error message will be displayed, no need for the info label
+        if (syncLocation == null) {
+            importLabel.setVisible(false);
+            importLabel.getParent().layout();
+            return;
+        }
+
+        IFile filterFile = getFilter(syncLocation);
+
+        if (filterFile!=null && filterFile.exists()) {
+            importLabel.setText("Will apply import filter from /" + 
filterFile.getProjectRelativePath() + ".");
+        } else {
+            importLabel.setText("No filter found at /" + 
filterFile.getProjectRelativePath()
+                    + ", will import all resources.");
+        }
+        importLabel.setVisible(true);
+        importLabel.getParent().layout();
+    }
+
+       public IFile getFilterFile() {
+
+        IResource syncLocation = 
project.getWorkspace().getRoot().findMember(getResourcePath());
+        if (syncLocation == null) {
+            return null;
+        }
+
+        return getFilter(syncLocation);
+    }
+
+    private IFile getFilter(IResource syncLocation) {
+
+        FilterLocator filterLocator = 
Activator.getDefault().getFilterLocator();
+        File filterLocation = 
filterLocator.findFilterLocation(syncLocation.getLocation().toFile());
+        IPath filterPath = Path.fromOSString(filterLocation.getAbsolutePath());
+        return 
ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(filterPath);
+    }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see 
org.eclipse.ui.dialogs.WizardDataTransferPage#validateSourceGroup()
+        */
+       @Override
+       protected boolean validateSourceGroup() {
+               if (getControl() == null) {
+                       // still under construction
+                       return true;
+               }
+        if (project!=null && adjustJcrRootText!=null) {
+            adjustJcrRootText();
+            adjustJcrRootText.pack();
+        }
+        if (repositoryCombo.getItemCount() == 0 && project != null) {
+               setErrorMessage("The selected project is not configured 
with/added to any Sling server");
+               return false;
+        }
+        if ((repositoryCombo.getSelectionIndex() == -1) || 
+               (repositoryCombo.getText().length() == 0)) {
+               setErrorMessage("Please select a repository");
+               return false;
+        }
+               if (getRepositoryPath() == null
+                               || getRepositoryPath().trim().length() == 0) {
+                       setErrorMessage("Please enter a valid Sling Repository 
path");
+                       return false;
+               }
+               return true;
+       }
+
+       private void adjustJcrRootText() {
+               adjustJcrRootText.setText("Content will be stored under: 
"+project.getName()+"/"+ProjectUtil.getSyncDirectoryValue(project));
+       }
+}

Modified: 
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/SelectionUtils.java
URL: 
http://svn.apache.org/viewvc/sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/SelectionUtils.java?rev=1508890&r1=1508889&r2=1508890&view=diff
==============================================================================
--- 
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/SelectionUtils.java
 (original)
+++ 
sling/trunk/tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/internal/SelectionUtils.java
 Wed Jul 31 14:49:54 2013
@@ -43,7 +43,15 @@ public abstract class SelectionUtils {
         }
 
         IProject project = (IProject) first;
-        List<IServer> servers = new ArrayList<IServer>();
+        return getServersLinkedToProject(project, monitor);
+    }
+
+       public static List<IServer> getServersLinkedToProject(IProject project,
+                       IProgressMonitor monitor) {
+               if (project == null) {
+                       return Collections.emptyList();
+               }
+               List<IServer> servers = new ArrayList<IServer>();
 
         IModule module = ServerUtil.getModule(project);
 
@@ -58,7 +66,7 @@ public abstract class SelectionUtils {
         }
 
         return servers;
-    }
+       }
 
     private SelectionUtils() {
 


Reply via email to