Example #1
0
  private void removeBuildPath(IResource resource, IProject project) {

    IScriptProject projrct = DLTKCore.create(project);
    IPath filePath = resource.getFullPath();

    oldBuildEntries = Arrays.asList(projrct.readRawBuildpath());

    newBuildEntries = new ArrayList<IBuildpathEntry>();

    newBuildEntries.addAll(oldBuildEntries);

    for (int i = 0; i < oldBuildEntries.size(); i++) {
      IBuildpathEntry fEntryToChange = oldBuildEntries.get(i);
      IPath entryPath = fEntryToChange.getPath();

      int mattchedPath = entryPath.matchingFirstSegments(filePath);

      if (mattchedPath == filePath.segmentCount()) {
        newBuildEntries.remove(fEntryToChange);
      } else {
        IBuildpathEntry newEntry =
            RefactoringUtility.createNewBuildpathEntry(
                fEntryToChange, fEntryToChange.getPath(), filePath, ""); // $NON-NLS-1$
        newBuildEntries.remove(fEntryToChange);
        newBuildEntries.add(newEntry);
      }
    }

    oldIncludePath = new ArrayList<IBuildpathEntry>();

    newIncludePathEntries = new ArrayList<IBuildpathEntry>();
    List<IncludePath> includePathEntries =
        Arrays.asList(IncludePathManager.getInstance().getIncludePaths(project));

    for (IncludePath entry : includePathEntries) {
      Object includePathEntry = entry.getEntry();
      IResource includeResource = null;
      if (!(includePathEntry instanceof IBuildpathEntry)) {
        includeResource = (IResource) includePathEntry;
        IPath entryPath = includeResource.getFullPath();

        IBuildpathEntry oldEntry =
            RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, entryPath);
        oldIncludePath.add((IBuildpathEntry) oldEntry);

        if (filePath.isPrefixOf(entryPath) || entryPath.equals(filePath)) {
        } else {
          IBuildpathEntry newEntry =
              RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, entryPath);
          newIncludePathEntries.add(newEntry);
        }
      } else {
        newIncludePathEntries.add((IBuildpathEntry) includePathEntry);
        oldIncludePath.add((IBuildpathEntry) includePathEntry);
      }
    }
  }
  protected void handleAdd() {
    ElementListSelectionDialog dialog =
        new ElementListSelectionDialog(getShell(), new StyledBundleLabelProvider(false, false));

    try {
      dialog.setElements(getValidBundles());
    } catch (CoreException e) {
      dialog.setMessage(e.getMessage());
    }

    dialog.setTitle(PDEUIMessages.PluginSelectionDialog_title);
    dialog.setMessage(PDEUIMessages.PluginSelectionDialog_message);
    dialog.setMultipleSelection(true);
    if (dialog.open() == Window.OK) {

      Object[] models = dialog.getResult();
      ArrayList<NameVersionDescriptor> pluginsToAdd = new ArrayList<NameVersionDescriptor>();
      for (int i = 0; i < models.length; i++) {
        BundleInfo desc = ((BundleInfo) models[i]);
        pluginsToAdd.add(new NameVersionDescriptor(desc.getSymbolicName(), null));
      }
      Set<NameVersionDescriptor> allDependencies = new HashSet<NameVersionDescriptor>();
      allDependencies.addAll(pluginsToAdd);
      NameVersionDescriptor[] currentBundles = getTargetDefinition().getImplicitDependencies();
      if (currentBundles != null) {
        allDependencies.addAll(Arrays.asList(currentBundles));
      }
      getTargetDefinition()
          .setImplicitDependencies(
              allDependencies.toArray(new NameVersionDescriptor[allDependencies.size()]));
      fElementViewer.refresh();
      updateImpButtons();
    }
  }
    public Object[] getElements(Object inputElement) {
      if (inputElement instanceof ITargetDefinition) {
        List result = new ArrayList();

        // Check if there are any errors for missing features/bundles to display
        if (fMissing == null) {
          fMissing = new ArrayList();
        } else {
          fMissing.clear();
        }
        IResolvedBundle[] bundles = fTargetDefinition.getBundles();
        for (int i = 0; i < bundles.length; i++) {
          if (!bundles[i].getStatus().isOK()) {
            fMissing.add(bundles[i]);
            result.add(bundles[i]);
          }
        }

        if (fFeaureModeButton.getSelection()) {
          IFeatureModel[] features = fTargetDefinition.getAllFeatures();
          result.addAll(Arrays.asList(features));

          // Check if we need the other category
          if (((TargetDefinition) fTargetDefinition).getOtherBundles().length > 0) {
            result.add(OTHER_CATEGORY);
          }
        } else if (fGrouping == GROUP_BY_CONTAINER) {
          result.addAll(Arrays.asList(fTargetDefinition.getBundleContainers()));
        } else if (fGrouping == GROUP_BY_NONE) {
          // Missing bundles are already handled by adding to fMissing, avoid adding twice
          IResolvedBundle[] allBundles = fTargetDefinition.getAllBundles();
          for (int i = 0; i < allBundles.length; i++) {
            if (allBundles[i].getStatus().isOK()) {
              result.add(allBundles[i]);
            }
          }
        } else {
          result.addAll(Arrays.asList(getFileBundleMapping().keySet().toArray()));
        }

        return result.toArray();
      }
      return new Object[] {inputElement};
    }
Example #4
0
 private void writeState(XMLWriter writer) {
   writer.startTag(RepositoriesViewContentHandler.REPOSITORIES_VIEW_TAG, null, true);
   // Write the repositories
   Collection repos = Arrays.asList(getKnownRepositoryLocations());
   Iterator it = repos.iterator();
   while (it.hasNext()) {
     CVSRepositoryLocation location = (CVSRepositoryLocation) it.next();
     RepositoryRoot root = getRepositoryRootFor(location);
     root.writeState(writer);
   }
   writer.endTag(RepositoriesViewContentHandler.REPOSITORIES_VIEW_TAG);
 }
Example #5
0
 /*
  * XXX I hope this methos is not needed in this form
  */
 public Map getKnownProjectsAndVersions(ICVSRepositoryLocation location) {
   Map knownTags = new HashMap();
   RepositoryRoot root = getRepositoryRootFor(location);
   String[] paths = root.getKnownRemotePaths();
   for (int i = 0; i < paths.length; i++) {
     String path = paths[i];
     Set result = new HashSet();
     result.addAll(Arrays.asList(root.getAllKnownTags(path)));
     knownTags.put(path, result);
   }
   return knownTags;
 }
Example #6
0
 /**
  * Method getKnownTags.
  *
  * @param repository
  * @param set
  * @param i
  * @param monitor
  * @return CVSTag[]
  */
 public CVSTag[] getKnownTags(
     ICVSRepositoryLocation repository, IWorkingSet set, int tagType, IProgressMonitor monitor)
     throws CVSException {
   if (set == null) {
     return getKnownTags(repository, tagType);
   }
   ICVSRemoteResource[] folders = getFoldersForTag(repository, CVSTag.DEFAULT, monitor);
   folders = filterResources(set, folders);
   Set tags = new HashSet();
   for (int i = 0; i < folders.length; i++) {
     ICVSRemoteFolder folder = (ICVSRemoteFolder) folders[i];
     tags.addAll(Arrays.asList(getKnownTags(folder, tagType)));
   }
   return (CVSTag[]) tags.toArray(new CVSTag[tags.size()]);
 }
Example #7
0
 public ICVSRemoteResource[] getFoldersForTag(
     ICVSRepositoryLocation location, CVSTag tag, IProgressMonitor monitor) throws CVSException {
   monitor = Policy.monitorFor(monitor);
   try {
     monitor.beginTask(
         NLS.bind(
             CVSUIMessages.RepositoryManager_fetchingRemoteFolders, new String[] {tag.getName()}),
         100);
     if (tag.getType() == CVSTag.HEAD) {
       ICVSRemoteResource[] resources =
           location.members(tag, false, Policy.subMonitorFor(monitor, 60));
       RepositoryRoot root = getRepositoryRootFor(location);
       ICVSRemoteResource[] modules =
           root.getDefinedModules(tag, Policy.subMonitorFor(monitor, 40));
       ICVSRemoteResource[] result = new ICVSRemoteResource[resources.length + modules.length];
       System.arraycopy(resources, 0, result, 0, resources.length);
       System.arraycopy(modules, 0, result, resources.length, modules.length);
       return result;
     }
     if (tag.getType() == CVSTag.DATE) {
       ICVSRemoteResource[] resources =
           location.members(tag, false, Policy.subMonitorFor(monitor, 60));
       RepositoryRoot root = getRepositoryRootFor(location);
       ICVSRemoteResource[] modules =
           root.getDefinedModules(tag, Policy.subMonitorFor(monitor, 40));
       ICVSRemoteResource[] result = new ICVSRemoteResource[resources.length + modules.length];
       System.arraycopy(resources, 0, result, 0, resources.length);
       System.arraycopy(modules, 0, result, resources.length, modules.length);
       return result;
     }
     Set result = new HashSet();
     // Get the tags for the location
     RepositoryRoot root = getRepositoryRootFor(location);
     String[] paths = root.getKnownRemotePaths();
     for (int i = 0; i < paths.length; i++) {
       String path = paths[i];
       List tags = Arrays.asList(root.getAllKnownTags(path));
       if (tags.contains(tag)) {
         ICVSRemoteFolder remote =
             root.getRemoteFolder(path, tag, Policy.subMonitorFor(monitor, 100));
         result.add(remote);
       }
     }
     return (ICVSRemoteResource[]) result.toArray(new ICVSRemoteResource[result.size()]);
   } finally {
     monitor.done();
   }
 }
 private void handleRemove() {
   LinkedList<NameVersionDescriptor> bundles = new LinkedList<NameVersionDescriptor>();
   bundles.addAll(Arrays.asList(getTargetDefinition().getImplicitDependencies()));
   Object[] removeBundles = ((IStructuredSelection) fElementViewer.getSelection()).toArray();
   if (removeBundles.length > 0) {
     for (int i = 0; i < removeBundles.length; i++) {
       if (removeBundles[i] instanceof NameVersionDescriptor) {
         bundles.remove(removeBundles[i]);
       }
     }
     getTargetDefinition()
         .setImplicitDependencies(bundles.toArray((new NameVersionDescriptor[bundles.size()])));
     fElementViewer.refresh();
     updateImpButtons();
   }
 }
Example #9
0
  public void fill(Menu menu, int index) {
    final IFileRevision fileRevision = getFileRevision();
    if (fileRevision == null) {
      return;
    }

    IEditorDescriptor defaultTextEditor =
        registry.findEditor("org.eclipse.ui.DefaultTextEditor"); // $NON-NLS-1$
    IEditorDescriptor preferredEditor = Utils.getDefaultEditor(fileRevision);

    Object[] editors = Utils.getEditors(fileRevision);
    Collections.sort(Arrays.asList(editors), comparer);
    boolean defaultFound = false;

    // Check that we don't add it twice. This is possible
    // if the same editor goes to two mappings.
    ArrayList alreadyMapped = new ArrayList();

    for (int i = 0; i < editors.length; i++) {
      IEditorDescriptor editor = (IEditorDescriptor) editors[i];
      if (!alreadyMapped.contains(editor)) {
        createMenuItem(menu, editor, preferredEditor);
        if (defaultTextEditor != null && editor.getId().equals(defaultTextEditor.getId())) {
          defaultFound = true;
        }
        alreadyMapped.add(editor);
      }
    }

    // Only add a separator if there is something to separate
    if (editors.length > 0) {
      new MenuItem(menu, SWT.SEPARATOR);
    }

    // Add default editor. Check it if it is saved as the preference.
    if (!defaultFound && defaultTextEditor != null) {
      createMenuItem(menu, defaultTextEditor, preferredEditor);
    }

    // TODO : We might perhaps enable inplace and system external editors menu items
    /*// Add system editor
    IEditorDescriptor descriptor = registry
    		.findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
    final MenuItem systemEditorMenuItem = createMenuItem(menu, descriptor,
    		preferredEditor);
    systemEditorMenuItem.setEnabled(false);

    // Add system in-place editor
    descriptor = registry
    		.findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID);

    final MenuItem inPlaceEditorMenuItem = (descriptor != null) ? createMenuItem(
    		menu, descriptor, preferredEditor)
    		: null;
    if (inPlaceEditorMenuItem != null)
    	inPlaceEditorMenuItem.setEnabled(false);

    Job job = new Job("updateOpenWithMenu") { //$NON-NLS-1$
    	protected IStatus run(IProgressMonitor monitor) {
    		try {
    			final boolean isFile = fileRevision.getStorage(monitor) instanceof IFile;
    			Display.getDefault().asyncExec(new Runnable() {
    				public void run() {
    					if (inPlaceEditorMenuItem != null
    							&& !inPlaceEditorMenuItem.isDisposed())
    						inPlaceEditorMenuItem.setEnabled(isFile);
    					if (!systemEditorMenuItem.isDisposed())
    						systemEditorMenuItem.setEnabled(isFile);
    				}
    			});
    			return Status.OK_STATUS;
    		} catch (CoreException e) {
    			return new Status(IStatus.WARNING, TeamUIPlugin.ID, null, e);
    		}
    	};
    };
    job.setSystem(true);
    job.schedule();*/

    createDefaultMenuItem(menu, fileRevision);

    // add Other... menu item
    createOtherMenuItem(menu);
  }
Example #10
0
public class GitUtils {

  public enum Traverse {
    GO_UP,
    GO_DOWN,
    CURRENT
  }

  /*
   * White list for URL schemes we can allow since they can't be used to gain access to git repositories
   * in another Orion workspace since they require a daemon to serve them. Especially file protocol needs
   * to be prohibited (bug 408270).
   */
  private static Set<String> uriSchemeWhitelist =
      new HashSet<String>(Arrays.asList("ftp", "git", "http", "https", "sftp", "ssh"));

  /**
   * Returns the file representing the Git repository directory for the given file path or any of
   * its parent in the filesystem. If the file doesn't exits, is not a Git repository or an error
   * occurred while transforming the given path into a store <code>null</code> is returned.
   *
   * @param path expected format /file/{Workspace}/{projectName}[/{path}]
   * @return the .git folder if found or <code>null</code> the give path cannot be resolved to a
   *     file or it's not under control of a git repository
   * @throws CoreException
   */
  public static File getGitDir(IPath path) throws CoreException {
    Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.GO_UP);
    if (gitDirs == null) return null;
    Collection<File> values = gitDirs.values();
    if (values.isEmpty()) return null;
    return values.toArray(new File[] {})[0];
  }

  public static File getGitDir(File file) {
    if (file.exists()) {
      while (file != null) {
        if (RepositoryCache.FileKey.isGitRepository(file, FS.DETECTED)) {
          return file;
        } else if (RepositoryCache.FileKey.isGitRepository(
            new File(file, Constants.DOT_GIT), FS.DETECTED)) {
          return new File(file, Constants.DOT_GIT);
        }
        file = file.getParentFile();
      }
    }
    return null;
  }

  /**
   * Returns the existing git repositories for the given file path, following the given traversal
   * rule.
   *
   * @param path expected format /file/{Workspace}/{projectName}[/{path}]
   * @return a map of all git repositories found, or <code>null</code> if the provided path format
   *     doesn't match the expected format.
   * @throws CoreException
   */
  public static Map<IPath, File> getGitDirs(IPath path, Traverse traverse) throws CoreException {
    IPath p = path.removeFirstSegments(1); // remove /file
    IFileStore fileStore = NewFileServlet.getFileStore(null, p);
    if (fileStore == null) return null;
    Map<IPath, File> result = new HashMap<IPath, File>();
    File file = fileStore.toLocalFile(EFS.NONE, null);
    // jgit can only handle a local file
    if (file == null) return result;
    switch (traverse) {
      case CURRENT:
        if (RepositoryCache.FileKey.isGitRepository(file, FS.DETECTED)) {
          result.put(new Path(""), file); // $NON-NLS-1$
        } else if (RepositoryCache.FileKey.isGitRepository(
            new File(file, Constants.DOT_GIT), FS.DETECTED)) {
          result.put(new Path(""), new File(file, Constants.DOT_GIT)); // $NON-NLS-1$
        }
        break;
      case GO_UP:
        getGitDirsInParents(file, result);
        break;
      case GO_DOWN:
        getGitDirsInChildren(file, p, result);
        break;
    }
    return result;
  }

  private static void getGitDirsInParents(File file, Map<IPath, File> gitDirs) {
    int levelUp = 0;
    File workspaceRoot = Activator.getDefault().getPlatformLocation().toFile();
    while (file != null && !file.getAbsolutePath().equals(workspaceRoot.getAbsolutePath())) {
      if (file.exists()) {
        if (RepositoryCache.FileKey.isGitRepository(file, FS.DETECTED)) {
          gitDirs.put(getPathForLevelUp(levelUp), file);
          return;
        } else if (RepositoryCache.FileKey.isGitRepository(
            new File(file, Constants.DOT_GIT), FS.DETECTED)) {
          gitDirs.put(getPathForLevelUp(levelUp), new File(file, Constants.DOT_GIT));
          return;
        }
      }
      file = file.getParentFile();
      levelUp++;
    }
    return;
  }

  private static IPath getPathForLevelUp(int levelUp) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < levelUp; i++) {
      sb.append("../"); // $NON-NLS-1$
    }
    return new Path(sb.toString());
  }

  /** Recursively walks down a directory tree and collects the paths of all git repositories. */
  private static void getGitDirsInChildren(File localFile, IPath path, Map<IPath, File> gitDirs)
      throws CoreException {
    if (localFile.exists() && localFile.isDirectory()) {
      if (RepositoryCache.FileKey.isGitRepository(localFile, FS.DETECTED)) {
        gitDirs.put(path.addTrailingSeparator(), localFile);
        return;
      } else if (RepositoryCache.FileKey.isGitRepository(
          new File(localFile, Constants.DOT_GIT), FS.DETECTED)) {
        gitDirs.put(path.addTrailingSeparator(), new File(localFile, Constants.DOT_GIT));
        return;
      }
      File[] folders =
          localFile.listFiles(
              new FileFilter() {
                public boolean accept(File file) {
                  return file.isDirectory() && !file.getName().equals(Constants.DOT_GIT);
                }
              });
      for (File folder : folders) {
        getGitDirsInChildren(folder, path.append(folder.getName()), gitDirs);
      }
      return;
    }
  }

  public static String getRelativePath(IPath filePath, IPath pathToGitRoot) {
    StringBuilder sb = new StringBuilder();
    String file = null;
    if (!filePath.hasTrailingSeparator()) {
      file = filePath.lastSegment();
      filePath = filePath.removeLastSegments(1);
    }
    for (int i = 0; i < pathToGitRoot.segments().length; i++) {
      if (pathToGitRoot.segments()[i].equals(".."))
        sb.append(
                filePath.segment(filePath.segments().length - pathToGitRoot.segments().length + i))
            .append("/");
      // else TODO
    }
    if (file != null) sb.append(file);
    return sb.toString();
  }

  static GitCredentialsProvider createGitCredentialsProvider(final JSONObject json) {
    String username = json.optString(GitConstants.KEY_USERNAME, null);
    char[] password = json.optString(GitConstants.KEY_PASSWORD, "").toCharArray(); // $NON-NLS-1$
    String knownHosts = json.optString(GitConstants.KEY_KNOWN_HOSTS, null);
    byte[] privateKey = json.optString(GitConstants.KEY_PRIVATE_KEY, "").getBytes(); // $NON-NLS-1$
    byte[] publicKey = json.optString(GitConstants.KEY_PUBLIC_KEY, "").getBytes(); // $NON-NLS-1$
    byte[] passphrase = json.optString(GitConstants.KEY_PASSPHRASE, "").getBytes(); // $NON-NLS-1$

    GitCredentialsProvider cp =
        new GitCredentialsProvider(null /* set by caller */, username, password, knownHosts);
    cp.setPrivateKey(privateKey);
    cp.setPublicKey(publicKey);
    cp.setPassphrase(passphrase);
    return cp;
  }

  public static String encode(String s) {
    try {
      return URLEncoder.encode(s, "UTF-8"); // $NON-NLS-1$
    } catch (UnsupportedEncodingException e) {
      // should never happen since "UTF-8" is used
    }
    return s;
  }

  public static String decode(String s) {
    try {
      return URLDecoder.decode(s, "UTF-8"); // $NON-NLS-1$
    } catch (UnsupportedEncodingException e) {
      // should never happen since "UTF-8" is used
    }
    return s;
  }

  /**
   * Returns the existing WebProject corresponding to the provided path, or <code>null</code> if no
   * such project exists.
   *
   * @param path path in the form /file/{workspaceId}/{projectName}/[filePath]
   * @return the web project, or <code>null</code>
   */
  public static ProjectInfo projectFromPath(IPath path) {
    if (path == null || path.segmentCount() < 3) return null;
    String workspaceId = path.segment(1);
    String projectName = path.segment(2);
    try {
      return OrionConfiguration.getMetaStore().readProject(workspaceId, projectName);
    } catch (CoreException e) {
      return null;
    }
  }

  /**
   * Returns the HTTP path for the content resource of the given project.
   *
   * @param workspace The web workspace
   * @param project The web project
   * @return the HTTP path of the project content resource
   */
  public static IPath pathFromProject(WorkspaceInfo workspace, ProjectInfo project) {
    return new Path(org.eclipse.orion.internal.server.servlets.Activator.LOCATION_FILE_SERVLET)
        .append(workspace.getUniqueId())
        .append(project.getFullName());
  }

  /**
   * Returns whether or not the git repository URI is forbidden. If a scheme of the URI is matched,
   * check if the scheme is a supported protocol. Otherwise, match for a scp-like ssh URI:
   * [user@]host.xz:path/to/repo.git/ and ensure the URI does not represent a local file path.
   *
   * @param uri A git repository URI
   * @return a boolean of whether or not the git repository URI is forbidden.
   */
  public static boolean isForbiddenGitUri(URIish uri) {
    String scheme = uri.getScheme();
    String host = uri.getHost();
    String path = uri.getPath();
    boolean isForbidden = false;

    if (scheme != null) {
      isForbidden = !uriSchemeWhitelist.contains(scheme);
    } else {
      // match for a scp-like ssh URI
      if (host != null) {
        isForbidden = host.length() == 1 || path == null;
      } else {
        isForbidden = true;
      }
    }

    return isForbidden;
  }

  /**
   * Returns whether the key gerrit.createchangeid is set to true in the git configuration
   *
   * @param config the configuration of the git repository
   * @return true if the key gerrit.createchangeid is set to true
   */
  public static boolean isGerrit(Config config) {
    return config.getBoolean(
        ConfigConstants.CONFIG_GERRIT_SECTION, ConfigConstants.CONFIG_KEY_CREATECHANGEID, false);
  }

  public static void _testAllowFileScheme(boolean allow) {
    if (allow) {
      uriSchemeWhitelist.add("file"); // $NON-NLS-1$
    } else {
      uriSchemeWhitelist.remove("file"); // $NON-NLS-1$
    }
  }

  // Used for enabling SSO git operations over http
  private static java.lang.reflect.Method SET_SSO_METHOD;
  private static boolean SET_SSO_METHOD_INITIALIZED;
  // Touch the Transport class so it gets initalized before TransportHttp
  //	private static final boolean FORCE_INITIALIZE = Transport.DEFAULT_PUSH_THIN;
  private static final RefSpec FORCE_INITIALIZE = Transport.REFSPEC_TAGS;

  public static void setSSOToken(Cookie c) {
    if (SET_SSO_METHOD == null && !SET_SSO_METHOD_INITIALIZED) {
      try {
        SET_SSO_METHOD_INITIALIZED = true;
        SET_SSO_METHOD = TransportHttp.class.getMethod("setSSOToken", Cookie.class);
      } catch (RuntimeException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "RuntimeException while trying to look up
        // JGit call", e));
      } catch (NoSuchMethodException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "NoSuchMethodException while trying to look
        // up JGit call", e));
      }
    }
    if (SET_SSO_METHOD != null) {
      try {
        SET_SSO_METHOD.invoke(null, c);
      } catch (IllegalArgumentException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IllegalArgumentException while trying to
        // set token", e));
      } catch (IllegalAccessException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IllegalAccessException while trying to set
        // token", e));
      } catch (InvocationTargetException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "InvocationTargetException while trying to
        // set token", e));
      }
    }
  }

  private static java.lang.reflect.Method GET_SSO_METHOD;
  private static boolean GET_SSO_METHOD_INITIALIZED;

  public static Cookie getSSOToken() {
    if (GET_SSO_METHOD == null && !GET_SSO_METHOD_INITIALIZED) {
      try {
        GET_SSO_METHOD_INITIALIZED = true;
        GET_SSO_METHOD = TransportHttp.class.getMethod("getSSOToken");
      } catch (RuntimeException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "RuntimeException while trying to look up
        // JGit call", e));
      } catch (NoSuchMethodException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "NoSuchMethodException while trying to look
        // up JGit call", e));
      }
    }
    if (GET_SSO_METHOD != null) {
      try {
        return (Cookie) GET_SSO_METHOD.invoke(null);
      } catch (IllegalArgumentException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IllegalArgumentException while trying to
        // set token", e));
      } catch (IllegalAccessException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IllegalAccessException while trying to set
        // token", e));
      } catch (InvocationTargetException e) {
        //				return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
        // HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "InvocationTargetException while trying to
        // set token", e));
      }
    }
    return null;
  }
}
Example #11
0
  /**
   * Creates the text changes for all the affected files. Updates all the include statements in the
   * current file and all the includes in the "including " files. In case of folders, creates the
   * changes recursively
   *
   * @param pm - progress monitor
   * @param rootChange - the root change that the new changes are added to
   * @param sourceResources
   * @return the root change after the additions
   * @throws CoreException
   */
  private Change createTextChanges(
      IProgressMonitor pm,
      CompositeChange rootChange,
      Set<IFile> phpFiles,
      IResource[] sourceResources)
      throws CoreException {
    List<ProgramFileChange> changes = new ArrayList<ProgramFileChange>();
    try {
      pm.beginTask(PhpRefactoringCoreMessages.getString("MoveDelegate.1"), 100); // $NON-NLS-1$

      // creat text changes:
      // for each file that will be moved, update its includes
      // and update all the files that include it,

      IResource[] uniqueSourceResources = removeDuplicateResources(sourceResources);

      for (Iterator<IFile> it = phpFiles.iterator(); it.hasNext(); ) {
        IFile currentMovedResource = it.next();

        Map<IFile, Program> participantFiles = collectReferencingFiles(currentMovedResource, pm);

        for (Entry<IFile, Program> entry : participantFiles.entrySet()) {
          final IFile file = entry.getKey();
          if (phpFiles.contains(file)) {
            continue;
          }
          final Program program = entry.getValue();

          final ChangeIncludePath rename =
              new ChangeIncludePath(
                  currentMovedResource, file, fMainDestinationPath, false, uniqueSourceResources);
          // aggregate the changes identifiers
          program.accept(rename);

          if (pm.isCanceled()) throw new OperationCanceledException();

          pm.worked(1);

          if (rename.hasChanges()) {
            ProgramFileChange change = new ProgramFileChange(file.getName(), file, program);
            change.setEdit(new MultiTextEdit());
            change.setTextType("php"); // $NON-NLS-1$

            changes.add(change);
            rename.updateChange(change);
          }
        }

        ISourceModule sourceModule = DLTKCore.createSourceModuleFrom(currentMovedResource);

        if (sourceModule instanceof ISourceModule) {

          Program program = null;
          try {
            program = ASTUtils.createProgramFromSource(sourceModule);
          } catch (Exception e) {
          }

          if (program != null) {
            final ChangeIncludePath rename =
                new ChangeIncludePath(
                    currentMovedResource,
                    currentMovedResource,
                    fMainDestinationPath,
                    true,
                    uniqueSourceResources);

            // aggregate the changes identifiers
            program.accept(rename);

            if (pm.isCanceled()) throw new OperationCanceledException();

            pm.worked(1);

            if (rename.hasChanges()) {
              ProgramFileChange change =
                  new ProgramFileChange(
                      currentMovedResource.getName(), currentMovedResource, program);
              change.setEdit(new MultiTextEdit());
              change.setTextType("php"); // $NON-NLS-1$

              changes.add(change);
              rename.updateChange(change);
            }
          }
        }
      }
      pm.worked(70);

    } finally {
      pm.done();
    } // getChildren()

    Map<IFile, List<TextEdit>> changeMap = new HashMap<IFile, List<TextEdit>>();
    Map<IFile, ProgramFileChange> fileMap = new HashMap<IFile, ProgramFileChange>();
    for (ProgramFileChange programFileChange : changes) {
      List<TextEdit> list = changeMap.get(programFileChange.getFile());
      if (list == null) {
        list = new ArrayList<TextEdit>();
        changeMap.put(programFileChange.getFile(), list);
        fileMap.put(programFileChange.getFile(), programFileChange);
      } else {

      }
      list.addAll(Arrays.asList(programFileChange.getEdit().getChildren()));
    }
    for (IFile file : changeMap.keySet()) {
      ProgramFileChange change =
          new ProgramFileChange(file.getName(), file, fileMap.get(file).getProgram());
      change.setEdit(new MultiTextEdit());
      change.setTextType("php"); // $NON-NLS-1$

      List<TextEdit> list = changeMap.get(file);
      Collections.sort(
          list,
          new Comparator<TextEdit>() {
            public int compare(TextEdit o1, TextEdit o2) {
              return o2.getOffset() - o1.getOffset();
            }
          });

      for (TextEdit textEdit : list) {
        if (textEdit instanceof ReplaceEdit) {
          ReplaceEdit replaceEdit = (ReplaceEdit) textEdit;
          change.addEdit(
              new ReplaceEdit(
                  replaceEdit.getOffset(), replaceEdit.getLength(), replaceEdit.getText()));
        }
      }
      rootChange.add(change);
    }
    return rootChange;
  }