/** * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings. * Paths are ordered from most to least specific match. * * @param site The hosted site. * @param pathInfo Path to be rewritten. * @param queryString * @return The rewritten path. May be either: * <ul> * <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code> * <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code> * </ul> * * @return The rewritten paths. * @throws URISyntaxException */ private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString) throws URISyntaxException { final Map<String, List<String>> map = site.getMappings(); final IPath originalPath = pathInfo; IPath path = originalPath.removeTrailingSeparator(); List<URI> uris = new ArrayList<URI>(); String rest = null; final int count = path.segmentCount(); for (int i = 0; i <= count; i++) { List<String> base = map.get(path.toString()); if (base != null) { rest = originalPath.removeFirstSegments(count - i).toString(); for (int j = 0; j < base.size(); j++) { URI uri = rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest); uris.add( new URI( uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), queryString, uri.getFragment())); } } path = path.removeLastSegments(1); } if (uris.size() == 0) // No mapping for / return null; else return uris.toArray(new URI[uris.size()]); }
/** * 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; }
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { traceRequest(req); String pathInfoString = req.getPathInfo(); String queryString = getQueryString(req); IPath pathInfo = new Path( null /*don't parse host:port as device*/, pathInfoString == null ? "" : pathInfoString); // $NON-NLS-1$ if (pathInfo.segmentCount() > 0) { String hostedHost = pathInfo.segment(0); IHostedSite site = HostingActivator.getDefault().getHostingService().get(hostedHost); if (site != null) { IPath path = pathInfo.removeFirstSegments(1); IPath contextPath = new Path(req.getContextPath()); IPath contextlessPath = path.makeRelativeTo(contextPath).makeAbsolute(); URI[] mappedPaths; try { mappedPaths = getMapped(site, contextlessPath, queryString); } catch (URISyntaxException e) { handleException( resp, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Could not create target URI ", e)); return; } if (mappedPaths != null) { serve(req, resp, site, mappedPaths); } else { handleException( resp, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, NLS.bind("No mappings matched {0}", path), null)); } } else { String msg = NLS.bind("Hosted site {0} is stopped", hostedHost); handleException( resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } } else { super.doGet(req, resp); } }
// temp code for grabbing files from filesystem protected IFileStore tempGetFileStore(IPath path) { // first check if we have an alias registered if (path.segmentCount() > 0) { URI alias = aliasRegistry.lookupAlias(path.segment(0)); if (alias != null) try { return EFS.getStore(alias).getFileStore(path.removeFirstSegments(1)); } catch (CoreException e) { LogHelper.log( new Status( IStatus.WARNING, HostingActivator.PI_SERVER_HOSTING, 1, "An error occured when getting file store for path '" + path + "' and alias '" + alias + '\'', e)); //$NON-NLS-1$ //$NON-NLS-2$ // fallback is to try the same path relatively to the root } } // assume it is relative to the root try { return EFS.getStore(rootStoreURI).getFileStore(path); } catch (CoreException e) { LogHelper.log( new Status( IStatus.WARNING, HostingActivator.PI_SERVER_HOSTING, 1, "An error occured when getting file store for path '" + path + "' and root '" + rootStoreURI + '\'', e)); //$NON-NLS-1$ //$NON-NLS-2$ // fallback and return null } return null; }
/** * Creates a locale specific properties file within the fragment project based on the content of * the host plug-in's properties file. * * @param fragmentProject * @param locale * @throws CoreException * @throws IOException */ private void createLocaleSpecificPropertiesFile( final IProject fragmentProject, IPluginModelBase plugin, final Locale locale) throws CoreException, IOException { final IFolder localeResourceFolder = fragmentProject.getFolder(RESOURCE_FOLDER_PARENT).getFolder(locale.toString()); // Case 1: External plug-in if (plugin instanceof ExternalPluginModelBase) { final String installLocation = plugin.getInstallLocation(); // Case 1a: External plug-in is a jar file if (new File(installLocation).isFile()) { ZipFile zf = new ZipFile(installLocation); for (Enumeration e = zf.entries(); e.hasMoreElements(); ) { worked(); ZipEntry zfe = (ZipEntry) e.nextElement(); String name = zfe.getName(); String[] segments = name.split(SLASH); IPath path = Path.fromPortableString(join(SLASH, segments, 0, segments.length - 1)); String resourceName = segments[segments.length - 1]; String localizedResourceName = localeSpecificName(resourceName, locale); if (propertiesFilter.include(name)) { createParents(fragmentProject, path); IFile file = fragmentProject.getFile(path.append(localizedResourceName)); InputStream is = zf.getInputStream(zfe); file.create(is, false, getProgressMonitor()); } else if (resourceFilter.include(name)) { IPath target = localeResourceFolder.getFullPath().append(path).append(resourceName); createParents(fragmentProject, target.removeLastSegments(1).removeFirstSegments(1)); IFile file = fragmentProject.getFile(target.removeFirstSegments(1)); file.create(zf.getInputStream(zfe), false, getProgressMonitor()); } } } // Case 1b: External plug-in has a folder structure else { Visitor visitor = new Visitor() { public void visit(File file) throws CoreException, FileNotFoundException { worked(); String relativePath = file.getAbsolutePath() .substring(installLocation.length()) .replaceAll(File.separator, SLASH); String[] segments = relativePath.split(SLASH); IPath path = Path.fromPortableString(join(SLASH, segments, 0, segments.length - 1)); String resourceName = segments[segments.length - 1]; String localizedResourceName = localeSpecificName(resourceName, locale); if (propertiesFilter.include( relativePath + (file.isDirectory() ? SLASH : EMPTY_STRING))) { createParents(fragmentProject, path); IFile iFile = fragmentProject.getFile(path.append(localizedResourceName)); iFile.create(new FileInputStream(file), false, getProgressMonitor()); } else if (resourceFilter.include( relativePath + (file.isDirectory() ? SLASH : EMPTY_STRING))) { IPath target = localeResourceFolder.getFullPath().append(relativePath); createParents( fragmentProject, target.removeLastSegments(1).removeFirstSegments(1)); IFile iFile = fragmentProject.getFile(target.removeFirstSegments(1)); iFile.create(new FileInputStream(file), false, getProgressMonitor()); } if (file.isDirectory()) { File[] children = file.listFiles(); for (int i = 0; i < children.length; i++) { visit(children[i]); } } } }; visitor.visit(new File(installLocation)); } } // Case 2: Workspace plug-in else { final IProject project = plugin.getUnderlyingResource().getProject(); project.accept( new IResourceVisitor() { public boolean visit(IResource resource) throws CoreException { worked(); IPath parent = resource.getFullPath().removeLastSegments(1).removeFirstSegments(1); if (propertiesFilter.include(resource)) { String segment = localeSpecificName(resource.getFullPath().lastSegment(), locale); IPath fragmentResource = fragmentProject.getFullPath().append(parent).append(segment); createParents(fragmentProject, parent); resource.copy(fragmentResource, true, getProgressMonitor()); } else if (resourceFilter.include(resource)) { IPath target = localeResourceFolder .getFullPath() .append(parent) .append(resource.getFullPath().lastSegment()); createParents(fragmentProject, target.removeLastSegments(1).removeFirstSegments(1)); resource.copy(target, true, getProgressMonitor()); } return true; } }); } }
private boolean handlePost( HttpServletRequest request, HttpServletResponse response, String pathString) throws IOException, JSONException, ServletException, URISyntaxException, CoreException, NoHeadException, NoMessageException, ConcurrentRefUpdateException, WrongRepositoryStateException { // make sure required fields are set JSONObject toAdd = OrionServlet.readJSONRequest(request); if (toAdd.optBoolean(GitConstants.KEY_PULL, false)) { GitUtils.createGitCredentialsProvider(toAdd); GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd); boolean force = toAdd.optBoolean(GitConstants.KEY_FORCE, false); return pull(request, response, cp, pathString, force); } Clone clone = new Clone(); String url = toAdd.optString(GitConstants.KEY_URL, null); // method handles repository clone or just repository init // decision is based on existence of GitUrl argument boolean initOnly; if (url == null || url.isEmpty()) initOnly = true; else { initOnly = false; if (!validateCloneUrl(url, request, response)) return true; clone.setUrl(new URIish(url)); } String cloneName = toAdd.optString(ProtocolConstants.KEY_NAME, null); if (cloneName == null) cloneName = request.getHeader(ProtocolConstants.HEADER_SLUG); // expected path /workspace/{workspaceId} String workspacePath = toAdd.optString(ProtocolConstants.KEY_LOCATION, null); // expected path /file/{workspaceId}/{projectName}[/{path}] String filePathString = toAdd.optString(ProtocolConstants.KEY_PATH, null); IPath filePath = filePathString == null ? null : new Path(filePathString); if (filePath != null && filePath.segmentCount() < 3) filePath = null; if (filePath == null && workspacePath == null) { String msg = NLS.bind( "Either {0} or {1} should be provided: {2}", new Object[] {ProtocolConstants.KEY_PATH, ProtocolConstants.KEY_LOCATION, toAdd}); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } // only during init operation filePath or cloneName must be provided // during clone operation, name can be obtained from URL if (initOnly && filePath == null && cloneName == null) { String msg = NLS.bind( "Either {0} or {1} should be provided: {2}", new Object[] {ProtocolConstants.KEY_PATH, GitConstants.KEY_NAME, toAdd}); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } if (!validateCloneName(cloneName, request, response)) return true; // prepare the WebClone object, create a new project if necessary WebProject webProject = null; boolean webProjectExists = false; if (filePath != null) { // path format is /file/{workspaceId}/{projectName}/[filePath] clone.setId(filePath.toString()); webProject = GitUtils.projectFromPath(filePath); // workspace path format needs to be used if project does not exist if (webProject == null) { String msg = NLS.bind("Specified project does not exist: {0}", filePath.segment(2)); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } webProjectExists = true; clone.setContentLocation( webProject.getProjectStore().getFileStore(filePath.removeFirstSegments(3)).toURI()); if (cloneName == null) cloneName = filePath.segmentCount() > 2 ? filePath.lastSegment() : webProject.getName(); } else if (workspacePath != null) { IPath path = new Path(workspacePath); // TODO: move this to CloneJob // if so, modify init part to create a new project if necessary WebWorkspace workspace = WebWorkspace.fromId(path.segment(1)); String id = WebProject.nextProjectId(); if (cloneName == null) cloneName = new URIish(url).getHumanishName(); cloneName = getUniqueProjectName(workspace, cloneName); webProjectExists = false; webProject = WebProject.fromId(id); webProject.setName(cloneName); try { WorkspaceResourceHandler.computeProjectLocation(request, webProject, null, false); } catch (CoreException e) { // we are unable to write in the platform location! String msg = NLS.bind( "Server content location could not be written: {0}", Activator.getDefault().getRootLocationURI()); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); } catch (URISyntaxException e) { // should not happen, we do not allow linking at this point } try { // If all went well, add project to workspace WorkspaceResourceHandler.addProject(request.getRemoteUser(), workspace, webProject); } catch (CoreException e) { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error persisting project state", e)); } URI baseLocation = getURI(request); baseLocation = new URI( baseLocation.getScheme(), baseLocation.getUserInfo(), baseLocation.getHost(), baseLocation.getPort(), workspacePath, baseLocation.getQuery(), baseLocation.getFragment()); clone.setId(GitUtils.pathFromProject(workspace, webProject).toString()); clone.setContentLocation(webProject.getProjectStore().toURI()); } clone.setName(cloneName); clone.setBaseLocation(getURI(request)); JSONObject cloneObject = clone.toJSON(); String cloneLocation = cloneObject.getString(ProtocolConstants.KEY_LOCATION); if (initOnly) { // git init InitJob job = new InitJob( clone, TaskJobHandler.getUserId(request), request.getRemoteUser(), cloneLocation); return TaskJobHandler.handleTaskJob(request, response, job, statusHandler); } // git clone // prepare creds GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd); cp.setUri(new URIish(clone.getUrl())); // if all went well, clone CloneJob job = new CloneJob( clone, TaskJobHandler.getUserId(request), cp, request.getRemoteUser(), cloneLocation, webProjectExists ? null : webProject /* used for cleaning up, so null when not needed */); return TaskJobHandler.handleTaskJob(request, response, job, statusHandler); }
private boolean handleGet( HttpServletRequest request, HttpServletResponse response, String pathString) throws IOException, JSONException, ServletException, URISyntaxException, CoreException { IPath path = pathString == null ? Path.EMPTY : new Path(pathString); URI baseLocation = getURI(request); String user = request.getRemoteUser(); // expected path format is 'workspace/{workspaceId}' or // 'file/{workspaceId}/{projectName}/{path}]' if ("workspace".equals(path.segment(0)) && path.segmentCount() == 2) { // $NON-NLS-1$ // all clones in the workspace if (WebWorkspace.exists(path.segment(1))) { WebWorkspace workspace = WebWorkspace.fromId(path.segment(1)); JSONObject result = new JSONObject(); JSONArray children = new JSONArray(); for (WebProject webProject : workspace.getProjects()) { // this is the location of the project metadata if (isAccessAllowed(user, webProject)) { IPath projectPath = GitUtils.pathFromProject(workspace, webProject); Map<IPath, File> gitDirs = GitUtils.getGitDirs(projectPath, Traverse.GO_DOWN); for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) { children.put(new Clone().toJSON(entry, baseLocation)); } } } result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE); result.put(ProtocolConstants.KEY_CHILDREN, children); OrionServlet.writeJSONResponse(request, response, result); return true; } String msg = NLS.bind("Nothing found for the given ID: {0}", path); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } else if ("file".equals(path.segment(0)) && path.segmentCount() > 1) { // $NON-NLS-1$ // clones under given path WebProject webProject = GitUtils.projectFromPath(path); IPath projectRelativePath = path.removeFirstSegments(3); if (webProject != null && isAccessAllowed(user, webProject) && webProject.getProjectStore().getFileStore(projectRelativePath).fetchInfo().exists()) { Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.GO_DOWN); JSONObject result = new JSONObject(); JSONArray children = new JSONArray(); for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) { children.put(new Clone().toJSON(entry, baseLocation)); } result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE); result.put(ProtocolConstants.KEY_CHILDREN, children); OrionServlet.writeJSONResponse(request, response, result); return true; } String msg = NLS.bind("Nothing found for the given ID: {0}", path); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } // else the request is malformed String msg = NLS.bind("Invalid clone request: {0}", path); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); }
private boolean resourceExists(String location) { String bundleJar = null; IPath path = new Path(location); if ("platform:".equals(path.getDevice()) && path.segmentCount() > 2) { // $NON-NLS-1$ if ("plugin".equals(path.segment(0))) { // $NON-NLS-1$ String id = path.segment(1); IMonitorModelBase model = MonitorRegistry.findModel(id); if (model != null && model.isEnabled()) { path = path.setDevice(null).removeFirstSegments(2); String bundleLocation = model.getInstallLocation(); if (bundleLocation.endsWith(".jar")) { // $NON-NLS-1$ bundleJar = bundleLocation; } else { path = new Path(model.getInstallLocation()).append(path); } location = path.toString(); } } } else if (path.getDevice() == null && path.segmentCount() > 3 && "platform:".equals(path.segment(0))) { // $NON-NLS-1$ if ("plugin".equals(path.segment(1))) { // $NON-NLS-1$ String id = path.segment(2); IMonitorModelBase model = MonitorRegistry.findModel(id); if (model != null && model.isEnabled()) { path = path.removeFirstSegments(3); String bundleLocation = model.getInstallLocation(); if (bundleLocation.endsWith(".jar")) { // $NON-NLS-1$ bundleJar = bundleLocation; } else { path = new Path(model.getInstallLocation()).append(path); } location = path.toString(); } } } ArrayList paths = new ArrayList(); if (location.indexOf("$nl$") != -1) { // $NON-NLS-1$ StringTokenizer tokenizer = new StringTokenizer(TargetPlatform.getNL(), "_"); // $NON-NLS-1$ String language = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null; String country = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null; if (language != null && country != null) paths.add( location.replaceAll( "\\$nl\\$", "nl" + IPath.SEPARATOR + language + IPath.SEPARATOR + country)); //$NON-NLS-1$ //$NON-NLS-2$ if (language != null) paths.add( location.replaceAll( "\\$nl\\$", "nl" + IPath.SEPARATOR + language)); // $NON-NLS-1$ //$NON-NLS-2$ paths.add(location.replaceAll("\\$nl\\$", "")); // $NON-NLS-1$ //$NON-NLS-2$ } else { paths.add(location); } for (int i = 0; i < paths.size(); i++) { if (bundleJar == null) { IPath currPath = new Path(paths.get(i).toString()); if (currPath.isAbsolute() && currPath.toFile().exists()) return true; if (PDEProject.getBundleRoot(fFile.getProject()).findMember(currPath) != null) return true; if (fBuildModel != null && fBuildModel.getEntry("source." + paths.get(i)) != null) // $NON-NLS-1$ return true; } else { if (CoreUtility.jarContainsResource(new File(bundleJar), paths.get(i).toString(), false)) return true; } } return false; }
static String getKeyFor(IPath resourcePath) { return resourcePath.segmentCount() > 1 ? resourcePath.removeFirstSegments(1).toString() : PROJECT_KEY; }
private void updateBuildPath(IResource resource, IProject project) { String newElementName = resource.getName(); 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)) { int mattchedPath = entryPath.matchingFirstSegments(filePath); IPath truncatedPath = entryPath.uptoSegment(mattchedPath); IPath remaingPath = entryPath.removeFirstSegments(mattchedPath); IPath newPath; if (mattchedPath == filePath.segmentCount()) { newPath = truncatedPath.removeLastSegments(1).append(newElementName).append(remaingPath); } else { newPath = truncatedPath.append(newElementName).append(remaingPath); } IBuildpathEntry newEntry = RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, newPath); newIncludePathEntries.add(newEntry); } else { IBuildpathEntry newEntry = RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, entryPath); newIncludePathEntries.add(newEntry); } } else { newIncludePathEntries.add((IBuildpathEntry) includePathEntry); oldIncludePath.add((IBuildpathEntry) includePathEntry); } } }