public boolean performFinish() {
    FeatureModel featureModel = new FeatureModel();
    featureModel.createDefaultValues("");

    Path fullFilePath = new Path(page.fileName.getText());
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IPath rootPath = root.getLocation();
    if (rootPath.isPrefixOf(fullFilePath)) {
      // case: is file in workspace
      int matchingFirstSegments = rootPath.matchingFirstSegments(fullFilePath);
      IPath localFilePath = fullFilePath.removeFirstSegments(matchingFirstSegments);
      String[] segments = localFilePath.segments();
      localFilePath = new Path("");
      for (String segment : segments) {
        localFilePath = localFilePath.append(segment);
      }
      IFile file = root.getFile(localFilePath);
      featureModel.initFMComposerExtension(file.getProject());
      try {
        new FeatureModelWriterIFileWrapper(new XmlFeatureModelWriter(featureModel))
            .writeToFile(file);
        file.refreshLocal(IResource.DEPTH_INFINITE, null);
      } catch (CoreException e) {
        FMUIPlugin.getDefault().logError(e);
      }
      open(file);
    } else {
      // case: is no file in workspace
      File file = fullFilePath.toFile();
      new XmlFeatureModelWriter(featureModel).writeToFile(file);
    }
    return true;
  }
  private boolean handlePost(HttpServletRequest request, HttpServletResponse response, String path)
      throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
    Path p = new Path(path);
    if (p.segment(0).equals("file")) { // $NON-NLS-1$
      // handle adding new remote
      // expected path: /git/remote/file/{path}
      return addRemote(request, response, path);
    } else {
      JSONObject requestObject = OrionServlet.readJSONRequest(request);
      boolean fetch = Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_FETCH, null));
      String srcRef = requestObject.optString(GitConstants.KEY_PUSH_SRC_REF, null);
      boolean tags = requestObject.optBoolean(GitConstants.KEY_PUSH_TAGS, false);
      boolean force = requestObject.optBoolean(GitConstants.KEY_FORCE, false);

      // prepare creds
      GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(requestObject);

      // if all went well, continue with fetch or push
      if (fetch) {
        return fetch(request, response, cp, path, force);
      } else if (srcRef != null) {
        return push(request, response, path, cp, srcRef, tags, force);
      } else {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST,
                "Only Fetch:true is currently supported.",
                null));
      }
    }
  }
 @Override
 public String getSourceLocation() {
   IResource sourceResource;
   String sourceLocation = null;
   if (fFileSystemObject.isDirectory()) {
     sourceResource =
         ResourcesPlugin.getWorkspace()
             .getRoot()
             .getContainerForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
   } else {
     sourceResource =
         ResourcesPlugin.getWorkspace()
             .getRoot()
             .getFileForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
   }
   if (sourceResource != null && sourceResource.exists()) {
     try {
       sourceLocation = sourceResource.getPersistentProperty(TmfCommonConstants.SOURCE_LOCATION);
     } catch (CoreException e) {
       // Something went wrong with the already existing resource.
       // This is not a problem, we'll assign a new location below.
     }
   }
   if (sourceLocation == null) {
     try {
       sourceLocation = URIUtil.toUnencodedString(fFileSystemObject.getCanonicalFile().toURI());
     } catch (IOException e) {
       // Something went wrong canonicalizing the file. We can still
       // use the URI but there might be extra ../ in it.
       sourceLocation = URIUtil.toUnencodedString(fFileSystemObject.toURI());
     }
   }
   return sourceLocation;
 }
Esempio n. 4
0
  /**
   * Create a resource from the given URI and append a new Network instance to its contents. The
   * resourceSet used must be authorized to write on the disk. This means that the default
   * EditingDomain's resourceSet must be used in a write transaction (for example). If it is not
   * possible, do not provide a resourceSet, the default one will be used.
   *
   * @param resourceSet
   * @param uri
   * @return The created network
   * @throws IOException
   */
  public static Network createNetworkResource(final ResourceSet resourceSet, final URI uri)
      throws IOException {

    final String fileName;
    if (uri.isPlatform()) {
      fileName = uri.toPlatformString(true);
    } else {
      fileName = uri.toString();
    }

    // Create the network
    final Network network = DfFactory.eINSTANCE.createNetwork(fileName);

    // Compute the new network name
    final Path networkPath = new Path(uri.trimFileExtension().path());
    // 3 first segments are resource/<PROJECT>/src
    network.setName(networkPath.removeFirstSegments(3).toString().replace('/', '.'));

    // Create the resource
    Resource res = resourceSet.createResource(uri);
    res.getContents().add(network);
    res.save(Collections.EMPTY_MAP);

    return network;
  }
Esempio n. 5
0
  private String getWorkspaceRelativePath(File folder) {

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    IPath rootPath = root.getLocation();
    Path path = new Path(folder.getAbsolutePath());
    return path.makeRelativeTo(rootPath).toString();
  }
Esempio n. 6
0
  /**
   * This method is used for generating HTML file base on given folder, job name and xsl file name.
   *
   * @param tempFolderPath a string
   * @param jobNameOrComponentName a string
   * @param externalNodeHTMLList
   * @param xslFileName a string
   */
  public static void generateHTMLFile(
      String tempFolderPath, String xslFilePath, String xmlFilePath, String htmlFilePath) {
    FileOutputStream output = null;
    Writer writer = null;
    try {
      File xmlFile = new File(xmlFilePath);
      javax.xml.transform.Source xmlSource = new javax.xml.transform.stream.StreamSource(xmlFile);

      // will create the path needed
      Path htmlPath = new Path(htmlFilePath);
      File htmlFile = new File(htmlPath.removeLastSegments(1).toPortableString());
      htmlFile.mkdirs();

      output = new FileOutputStream(htmlFilePath);

      // Note that if the are chinese in the file, should set the encoding
      // type to "UTF-8", this is caused by DOM4J.
      writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")); // $NON-NLS-1$

      javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(writer);

      // clear cache, otherwise won't change style if have the same path as last
      transformerCache.clear();
      // get transformer from cache
      javax.xml.transform.Transformer trans = transformerCache.get(xslFilePath);
      if (trans == null) {
        File xsltFile = new File(xslFilePath);
        javax.xml.transform.Source xsltSource =
            new javax.xml.transform.stream.StreamSource(xsltFile);
        trans = transformerFactory.newTransformer(xsltSource);
        // put transformer into cache
        transformerCache.put(xslFilePath, trans);
      }

      trans.transform(xmlSource, result);

    } catch (Exception e) {
      ExceptionHandler.process(e);
    } finally {
      try {
        if (output != null) {
          output.close();
        }
      } catch (Exception e) {
        ExceptionHandler.process(e);
      }
      try {
        if (writer != null) {
          writer.close();
        }

      } catch (Exception e1) {
        ExceptionHandler.process(e1);
      }
    }
  }
Esempio n. 7
0
  private ArrayList getTemplates() {
    ArrayList templates = new ArrayList();
    CFMLPropertyManager propertyManager = new CFMLPropertyManager();

    Path snipBase = new Path(propertyManager.defaultSnippetsPath());
    File file = snipBase.toFile();
    logger.debug("Getting snippets from " + file.getAbsolutePath());

    // Now we iterate over the items I guess

    return null;
  }
Esempio n. 8
0
 public static IVMInstall getVMInstall(ILaunchConfiguration configuration) throws CoreException {
   String jre =
       configuration.getAttribute(
           IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, (String) null);
   IVMInstall vm = null;
   if (jre == null) {
     String name = configuration.getAttribute(IPDELauncherConstants.VMINSTALL, (String) null);
     if (name == null) {
       name = getDefaultVMInstallName(configuration);
     }
     vm = getVMInstall(name);
     if (vm == null) {
       throw new CoreException(
           LauncherUtils.createErrorStatus(
               NLS.bind(MDEMessages.WorkbenchLauncherConfigurationDelegate_noJRE, name)));
     }
   } else {
     IPath jrePath = Path.fromPortableString(jre);
     vm = JavaRuntime.getVMInstall(jrePath);
     if (vm == null) {
       String id = JavaRuntime.getExecutionEnvironmentId(jrePath);
       if (id == null) {
         String name = JavaRuntime.getVMInstallName(jrePath);
         throw new CoreException(
             LauncherUtils.createErrorStatus(
                 NLS.bind(MDEMessages.WorkbenchLauncherConfigurationDelegate_noJRE, name)));
       }
       throw new CoreException(
           LauncherUtils.createErrorStatus(NLS.bind(MDEMessages.VMHelper_cannotFindExecEnv, id)));
     }
   }
   return vm;
 }
  @Override
  protected void setUp() throws Exception {
    File baseTempFile = File.createTempFile("test", ".txt"); // $NON-NLS-1$ //$NON-NLS-2$
    baseTempFile.deleteOnExit();

    File baseDirectory = baseTempFile.getParentFile();

    LocalConnectionPoint lcp = new LocalConnectionPoint();
    lcp.setPath(new Path(baseDirectory.getAbsolutePath()));
    clientManager = lcp;

    SFTPConnectionPoint ftpcp = new SFTPConnectionPoint();
    ftpcp.setHost(getConfig().getProperty("sftp.host")); // $NON-NLS-1$
    ftpcp.setLogin(getConfig().getProperty("sftp.username")); // $NON-NLS-1$
    ftpcp.setPassword(getConfig().getProperty("sftp.password").toCharArray());
    ftpcp.setPort(
        Integer.valueOf(getConfig().getProperty("sftp.port", "22"))); // $NON-NLS-1$ //$NON-NLS-2$
    ftpcp.setPath(Path.fromPortableString(getConfig().getProperty("sftp.path"))); // $NON-NLS-1$
    serverManager = ftpcp;

    ConnectionContext context = new ConnectionContext();
    context.put(ConnectionContext.COMMAND_LOG, System.out);
    CoreIOPlugin.setConnectionContext(ftpcp, context);

    fileName = "file name.txt";
    folderName = "folder name";

    super.setUp();
  }
 public void openEditor(File file) {
   try {
     refreshDistProjects();
     OMElement documentElement = new StAXOMBuilder(new FileInputStream(file)).getDocumentElement();
     OMElement firstElement = documentElement.getFirstElement();
     String templateType = "template.sequence";
     if ("endpoint".equals(firstElement.getLocalName())) {
       templateType = "template.endpoint";
       String localName = firstElement.getFirstElement().getLocalName();
       if ("address".equals(localName)) {
         templateType = templateType + "-1";
       } else if ("wsdl".equals(localName)) {
         templateType = templateType + "-2";
       } else {
         templateType = templateType + "-0";
       }
     }
     IFile dbsFile =
         ResourcesPlugin.getWorkspace()
             .getRoot()
             .getFileForLocation(Path.fromOSString(file.getAbsolutePath()));
     String path = dbsFile.getParent().getFullPath() + "/";
     String source = FileUtils.getContentAsString(file);
     Openable openable = ESBGraphicalEditor.getOpenable();
     openable.editorOpen(file.getName(), templateType, path + "template_", source);
   } catch (Exception e) {
     log.error("Cannot open the editor", e);
   }
 }
Esempio n. 11
0
 /**
  * @param repos available repositories
  * @param suggestedRepo relative path to git repository
  * @return a repository mapping which corresponds to a suggested repository location, <code>null
  *     </code> otherwise
  */
 private RepositoryMapping findActualRepository(
     Collection<RepositoryMapping> repos, File suggestedRepo) {
   for (RepositoryMapping rm : repos) {
     if (rm.getGitDirAbsolutePath().equals(Path.fromOSString(suggestedRepo.getPath()))) return rm;
   }
   return null;
 }
  protected void perfValidate(String filename, int iterations) throws Exception {
    // read in the file
    InputStream in =
        FileLocator.openStream(
            Platform.getBundle(JSCorePlugin.PLUGIN_ID),
            Path.fromPortableString("performance/" + filename),
            false);
    IFile file = project.createFile(filename, IOUtil.read(in));
    RebuildIndexJob job = new RebuildIndexJob(project.getURI());
    job.run(null);

    // Ok now actually validate the thing, the real work
    for (int i = 0; i < iterations; i++) {
      EditorTestHelper.joinBackgroundActivities();

      BuildContext context = new BuildContext(file);
      // Don't measure reading in string...
      context.getContents();

      startMeasuring();
      validator.buildFile(context, null);
      stopMeasuring();
    }
    commitMeasurements();
    assertPerformance();
  }
Esempio n. 13
0
  public void run(ItemPointer p, IProject project) {
    editor = null;
    Object file = p.file;
    String zipFilePath = p.zipFilePath;

    if (zipFilePath != null) {
      // currently, only open zip file
      editor = PyOpenEditor.doOpenEditor((File) file, zipFilePath);

    } else if (file instanceof IFile) {
      IFile f = (IFile) file;
      editor = PyOpenEditor.doOpenEditor(f);

    } else if (file instanceof IPath) {
      IPath path = (IPath) file;
      editor = PyOpenEditor.doOpenEditor(path, project);

    } else if (file instanceof File) {
      String absPath = FileUtils.getFileAbsolutePath((File) file);
      IPath path = Path.fromOSString(absPath);
      editor = PyOpenEditor.doOpenEditor(path, project);
    }

    if (editor instanceof ITextEditor && p.start.line >= 0) {
      EditorUtils.showInEditor((ITextEditor) editor, p.start, p.end);
    }
  }
Esempio n. 14
0
  private static void loadFromStream(InputSource inputSource, Map<IPath, String> oldLocations)
      throws CoreException {
    Element cpElement;
    try {
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      parser.setErrorHandler(new DefaultHandler());
      cpElement = parser.parse(inputSource).getDocumentElement();
    } catch (SAXException e) {
      throw createException(e, CorextMessages.JavaDocLocations_error_readXML);
    } catch (ParserConfigurationException e) {
      throw createException(e, CorextMessages.JavaDocLocations_error_readXML);
    } catch (IOException e) {
      throw createException(e, CorextMessages.JavaDocLocations_error_readXML);
    }

    if (cpElement == null) return;
    if (!cpElement.getNodeName().equalsIgnoreCase(NODE_ROOT)) {
      return;
    }
    NodeList list = cpElement.getChildNodes();
    int length = list.getLength();
    for (int i = 0; i < length; ++i) {
      Node node = list.item(i);
      short type = node.getNodeType();
      if (type == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        if (element.getNodeName().equalsIgnoreCase(NODE_ENTRY)) {
          String varPath = element.getAttribute(NODE_PATH);
          String varURL = parseURL(element.getAttribute(NODE_URL)).toExternalForm();

          oldLocations.put(Path.fromPortableString(varPath), varURL);
        }
      }
    }
  }
Esempio n. 15
0
 private void openFile(File file, DotGraphView view) {
   if (view.currentFile == null) { // no workspace file for cur. graph
     IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path("")); // $NON-NLS-1$
     fileStore = fileStore.getChild(file.getAbsolutePath());
     if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {
       IWorkbenchPage page = view.getSite().getPage();
       try {
         IDE.openEditorOnFileStore(page, fileStore);
       } catch (PartInitException e) {
         e.printStackTrace();
       }
     }
   } else {
     IWorkspace workspace = ResourcesPlugin.getWorkspace();
     IPath location = Path.fromOSString(file.getAbsolutePath());
     IFile copy = workspace.getRoot().getFileForLocation(location);
     IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry();
     if (registry.isSystemExternalEditorAvailable(copy.getName())) {
       try {
         view.getViewSite()
             .getPage()
             .openEditor(new FileEditorInput(copy), IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
       } catch (PartInitException e) {
         e.printStackTrace();
       }
     }
   }
 }
 public void finish() {
   String destination = destinationText.getText().trim();
   if (!"".equals(destination)) {
     IPath path = Path.fromOSString(destination);
     getDialogSettings().put(getClass().getName(), path.removeLastSegments(1).toOSString());
   }
 }
 private ArrayList<Entry<IPath, IResource>> getSourceArchivesToCleanUp(IProgressMonitor monitor)
     throws CoreException {
   Set<IPath> projectSourcePaths = null;
   for (IProject project : CeylonBuilder.getProjects()) {
     for (JDTModule module : CeylonBuilder.getProjectExternalModules(project)) {
       String sourceArchivePathString = module.getSourceArchivePath();
       if (sourceArchivePathString != null) {
         if (projectSourcePaths == null) {
           projectSourcePaths = new HashSet<>();
         }
         projectSourcePaths.add(Path.fromOSString(sourceArchivePathString));
       }
     }
   }
   if (projectSourcePaths == null) return null;
   Map<IPath, IResource> knownSourceArchives = getSourceArchives();
   ArrayList<Entry<IPath, IResource>> result = null;
   synchronized (knownSourceArchives) {
     Iterator<Entry<IPath, IResource>> iterator = knownSourceArchives.entrySet().iterator();
     while (iterator.hasNext()) {
       Map.Entry<IPath, IResource> entry = iterator.next();
       IPath path = entry.getKey();
       if (!projectSourcePaths.contains(path)) {
         if (entry.getValue() != null) {
           if (result == null) result = new ArrayList<>();
           result.add(entry);
         }
       }
     }
   }
   return result;
 }
Esempio n. 18
0
  public static IFile convert(File file) {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IPath location = Path.fromOSString(file.getAbsolutePath());
    IFile iFile = workspace.getRoot().getFileForLocation(location);

    return iFile;
  }
  public void testExpandingResourcePath() throws Exception {
    URL dotProjectResource =
        getClass().getResource("/testData/projects/buckminster.test.build_a/.project"); // $NON-NLS
    assertNotNull("No resource found for .project file", dotProjectResource);
    dotProjectResource = FileLocator.toFileURL(dotProjectResource);
    assertNotNull("Unable to resolve .project resource into a file", dotProjectResource);
    File dotProjectFile = new File(dotProjectResource.toURI());

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IProject project = workspace.getRoot().getProject("buckminster.test.build_a");
    if (!project.isOpen()) {
      IProgressMonitor monitor = new NullProgressMonitor();
      if (!project.exists()) {
        IProjectDescription projectDesc =
            workspace.loadProjectDescription(Path.fromOSString(dotProjectFile.getAbsolutePath()));
        project.create(projectDesc, monitor);
      }
      project.open(monitor);
    }

    assertTrue("No open project was found after materialization", project.isOpen());
    ExpandingProperties<String> properties = new ExpandingProperties<String>();
    String projectPath = properties.get("workspace_loc:buckminster.test.build_a");
    assertNotNull("workspace_loc:<project name> doesn't resolve existing project", projectPath);
    assertEquals(
        "Unexpected physical project location",
        new File(projectPath),
        dotProjectFile.getParentFile());
  }
  /**
   * Performs a git clone to a temporary location and then copies the files over top the already
   * generated project. This is because git cannot clone into an existing directory.
   *
   * @param monitor
   * @throws Exception
   */
  protected void cloneAfter(IProgressMonitor monitor) throws Exception {
    SubMonitor sub =
        SubMonitor.convert(monitor, Messages.AbstractNewProjectWizard_CloningFromGitMsg, 100);
    // clone to tmp dir then copy files over top the project!
    File tmpFile = File.createTempFile("delete_me", "tmp"); // $NON-NLS-1$ //$NON-NLS-2$
    File dest = new File(tmpFile.getParent(), "git_clone_tmp"); // $NON-NLS-1$
    GitExecutable.instance()
        .clone(
            selectedTemplate.getLocation(),
            Path.fromOSString(dest.getAbsolutePath()),
            true,
            sub.newChild(85));

    IFileStore tmpClone = EFS.getStore(dest.toURI());
    // Wipe the .git folder before copying? Wipe the .project file before copying?
    IFileStore dotGit = tmpClone.getChild(".git"); // $NON-NLS-1$
    dotGit.delete(EFS.NONE, sub.newChild(2));

    IFileStore dotProject = tmpClone.getChild(IProjectDescription.DESCRIPTION_FILE_NAME);
    if (dotProject.fetchInfo().exists()) {
      dotProject.delete(EFS.NONE, sub.newChild(1));
    }
    // OK, copy the cloned template's contents over
    IFileStore projectStore = EFS.getStore(newProject.getLocationURI());
    tmpClone.copy(projectStore, EFS.OVERWRITE, sub.newChild(9));
    // Now get rid of the temp clone!
    tmpClone.delete(EFS.NONE, sub.newChild(3));
    sub.done();
  }
Esempio n. 21
0
  /** @return This is the Path that the editor is editing. */
  private IPath getPathFromInput(IEditorInput otherInput) {
    IPath path = null;
    if (otherInput instanceof IPathEditorInput) {
      IPathEditorInput iPathEditorInput = (IPathEditorInput) otherInput;
      try {
        path = iPathEditorInput.getPath();
      } catch (IllegalArgumentException e) {
        // ignore: we may have the trace below inside the FileEditorInput.
        // java.lang.IllegalArgumentException
        // at org.eclipse.ui.part.FileEditorInput.getPath(FileEditorInput.java:208)
        // at org.python.pydev.editor.PyEditTitle.getPathFromInput(PyEditTitle.java:751)

      }
    }
    if (path == null) {
      if (otherInput instanceof IFileEditorInput) {
        IFileEditorInput iFileEditorInput = (IFileEditorInput) otherInput;
        path = iFileEditorInput.getFile().getFullPath();
      }
    }
    if (path == null) {
      try {
        if (otherInput instanceof IURIEditorInput) {
          IURIEditorInput iuriEditorInput = (IURIEditorInput) otherInput;
          path = Path.fromOSString(new File(iuriEditorInput.getURI()).toString());
        }
      } catch (Throwable e) {
        // Ignore (IURIEditorInput not available on 3.2)
      }
    }
    return path;
  }
  /* (non-Javadoc)
   * @see org.eclipse.jdt.core.IClasspathContainer#getClasspathEntries()
   */
  @Override
  public IClasspathEntry[] getClasspathEntries() {
    Set<IClasspathEntry> entries = new HashSet<IClasspathEntry>();
    if (project != null && project.exists()) {
      File projectFolder = project.getProject().getLocation().toFile();
      File libFolder = new File(projectFolder, "lib");
      if (libFolder.exists()) {
        File[] listFiles =
            libFolder.listFiles(
                new FileFilter() {

                  @Override
                  public boolean accept(File file) {
                    return file.getName().endsWith(".jar");
                  }
                });
        if (listFiles != null) {
          for (File f : listFiles) {
            entries.add(
                JavaCore.newLibraryEntry(Path.fromOSString(f.getAbsolutePath()), null, null, true));
          }
        }
      }
    }
    return entries.toArray(new IClasspathEntry[entries.size()]);
  }
  protected List getStartClasspath() {
    List startClasspath = super.getStartClasspath();
    GenericServerRuntime runtime = getRuntimeDelegate();

    IVMInstall vmInstall = runtime.getVMInstall();
    File jdkLib = new File(vmInstall.getInstallLocation(), "lib");

    if (jdkLib.exists() && jdkLib.isDirectory()) {
      for (String cpath : jdkLib.list()) {
        Path newCPath = new Path(new File(jdkLib, cpath).toString());
        String fileExtension = newCPath.getFileExtension();
        if (fileExtension != null && fileExtension.equalsIgnoreCase("jar"))
          startClasspath.add(JavaRuntime.newArchiveRuntimeClasspathEntry(newCPath));
      }
    }
    return startClasspath;
  }
  private void launch(String pName, String fName, String mode) {
    try {
      ILaunchConfiguration found = null;
      ILaunchManager lm = DebugPlugin.getDefault().getLaunchManager();
      ILaunchConfigurationType lct =
          lm.getLaunchConfigurationType(GoLaunchConfigurationDelegate.ID);
      ILaunchConfiguration[] lcfgs = lm.getLaunchConfigurations(lct);

      for (ILaunchConfiguration lcf : lcfgs) {
        String project = lcf.getAttribute(GoConstants.GO_CONF_ATTRIBUTE_PROJECT, "");
        String mainfile = lcf.getAttribute(GoConstants.GO_CONF_ATTRIBUTE_MAIN, "");
        String prgArgs = lcf.getAttribute(GoConstants.GO_CONF_ATTRIBUTE_ARGS, "");

        if (prgArgs.isEmpty()) {
          // this is an empty run, no params, don't mix with already
          // definded with params
          if (project.equalsIgnoreCase(pName)
              && Path.fromOSString(fName).equals(Path.fromOSString(mainfile))) {
            found = lcf;
            break;
          }
        }
      }

      if (found == null) {
        // create a new launch configuration
        String cfgName = lm.generateLaunchConfigurationName(Path.fromOSString(fName).lastSegment());
        ILaunchConfigurationWorkingCopy workingCopy = lct.newInstance(null, cfgName);
        workingCopy.setAttribute(GoConstants.GO_CONF_ATTRIBUTE_PROJECT, pName);
        workingCopy.setAttribute(GoConstants.GO_CONF_ATTRIBUTE_MAIN, fName);
        workingCopy.setAttribute(GoConstants.GO_CONF_ATTRIBUTE_ARGS, "");
        workingCopy.setAttribute(
            GoConstants.GO_CONF_ATTRIBUTE_BUILD_CONFIG, BuildConfiguration.RELEASE.toString());
        workingCopy.setAttribute(DebugPlugin.ATTR_CAPTURE_OUTPUT, true);
        workingCopy.setAttribute(DebugPlugin.ATTR_CONSOLE_ENCODING, "UTF-8");

        found = workingCopy.doSave();
      }

      if (found != null) {
        found.launch(mode, null, true, true);
      }
    } catch (CoreException ce) {
      Activator.logError(ce);
    }
  }
Esempio n. 25
0
  public void testAsPortableString() throws Exception {
    ItemPointer pointer =
        new ItemPointer(
            Path.fromPortableString("c:/temp/a.py"), new Location(1, 2), new Location(3, 4));
    String asPortableString = pointer.asPortableString();
    assertEquals(pointer, ItemPointer.fromPortableString(asPortableString));

    pointer =
        new ItemPointer(
            Path.fromPortableString("c:/temp/a.py"),
            new Location(1, 2),
            new Location(3, 4),
            null,
            "zipLocation");
    asPortableString = pointer.asPortableString();
    assertEquals(pointer, ItemPointer.fromPortableString(asPortableString));
  }
 private static IPath decodePath(String str) {
   if ("#".equals(str)) { // $NON-NLS-1$
     return null;
   } else if ("&".equals(str)) { // $NON-NLS-1$
     return Path.EMPTY;
   } else {
     return Path.fromPortableString(decode(str));
   }
 }
 public File[] getWebAppClasspathFiles(IProject project) {
   File[] files = new File[1];
   String jarPath =
       AppsMarketplacePlugin.getDefault().getStateLocation()
           + "/"
           + AppsMarketplacePlugin.APPS_MARKETPLACE_JAR_NAME;
   files[0] = Path.fromOSString(jarPath).toFile();
   return files;
 }
Esempio n. 28
0
 private boolean push(
     HttpServletRequest request,
     HttpServletResponse response,
     String path,
     GitCredentialsProvider cp,
     String srcRef,
     boolean tags,
     boolean force)
     throws ServletException, CoreException, IOException, JSONException, URISyntaxException {
   Path p = new Path(path);
   // FIXME: what if a remote or branch is named "file"?
   if (p.segment(2).equals("file")) { // $NON-NLS-1$
     // /git/remote/{remote}/{branch}/file/{path}
     PushJob job = new PushJob(TaskJobHandler.getUserId(request), cp, p, srcRef, tags, force);
     return TaskJobHandler.handleTaskJob(request, response, job, statusHandler);
   }
   return false;
 }
Esempio n. 29
0
  // remove remote
  private boolean handleDelete(
      HttpServletRequest request, HttpServletResponse response, String path)
      throws CoreException, IOException, URISyntaxException, JSONException, ServletException {
    Path p = new Path(path);
    if (p.segment(1).equals("file")) { // $NON-NLS-1$
      // expected path: /gitapi/remote/{remote}/file/{path}
      String remoteName = p.segment(0);

      File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
      Repository db = new FileRepository(gitDir);
      StoredConfig config = db.getConfig();
      config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName);
      config.save();
      // TODO: handle result
      return true;
    }
    return false;
  }
Esempio n. 30
0
 private void fillTreeItemWithGitDirectory(
     RepositoryMapping m, TreeItem treeItem, boolean isAlternative) {
   if (m.getGitDir() == null)
     treeItem.setText(2, UIText.ExistingOrNewPage_SymbolicValueEmptyMapping);
   else {
     IPath relativePath = new Path(m.getGitDir());
     if (isAlternative) {
       IPath withoutLastSegment = relativePath.removeLastSegments(1);
       IPath path;
       if (withoutLastSegment.isEmpty()) path = Path.fromPortableString("."); // $NON-NLS-1$
       else path = withoutLastSegment;
       treeItem.setText(0, path.toString());
     }
     treeItem.setText(2, relativePath.toOSString());
     try {
       IProject project = m.getContainer().getProject();
       Repository repo =
           new RepositoryBuilder().setGitDir(m.getGitDirAbsolutePath().toFile()).build();
       File workTree = repo.getWorkTree();
       IPath workTreePath = Path.fromOSString(workTree.getAbsolutePath());
       if (workTreePath.isPrefixOf(project.getLocation())) {
         IPath makeRelativeTo = project.getLocation().makeRelativeTo(workTreePath);
         String repoRelativePath =
             makeRelativeTo.append("/.project").toPortableString(); // $NON-NLS-1$
         ObjectId headCommitId = repo.resolve(Constants.HEAD);
         if (headCommitId != null) {
           // Not an empty repo
           RevWalk revWalk = new RevWalk(repo);
           RevCommit headCommit = revWalk.parseCommit(headCommitId);
           RevTree headTree = headCommit.getTree();
           TreeWalk projectInRepo = TreeWalk.forPath(repo, repoRelativePath, headTree);
           if (projectInRepo != null) {
             // the .project file is tracked by this repo
             treeItem.setChecked(true);
           }
           revWalk.dispose();
         }
       }
       repo.close();
     } catch (IOException e1) {
       Activator.logError(UIText.ExistingOrNewPage_FailedToDetectRepositoryMessage, e1);
     }
   }
 }