public IStatus buildWSDD( IProject project, IFile serviceXmlFile, Map<String, String> overrideProperties) { SDKHelper antHelper = new SDKHelper(this); try { Map<String, String> properties = new HashMap<String, String>(); if (overrideProperties != null) { properties.putAll(overrideProperties); } String serviceFile = serviceXmlFile.getRawLocation().toOSString(); properties.put( ISDKConstants.PROPERTY_SERVICE_FILE, serviceXmlFile.getRawLocation().toOSString()); properties.put(ISDKConstants.PROPERTY_SERVICE_INPUT_FILE, serviceFile); final IPath buildFile = project.getFile(ISDKConstants.PROJECT_BUILD_XML).getRawLocation(); final String workingDir = getDefaultWorkingDir(buildFile); antHelper.runTarget(buildFile, ISDKConstants.TARGET_BUILD_WSDD, properties, true, workingDir); } catch (Exception e) { return SDKCorePlugin.createErrorStatus(e); } return Status.OK_STATUS; }
public IStatus runCommand( IProject project, IFile buildXmlFile, String command, Map<String, String> overrideProperties, IProgressMonitor monitor) { final SDKHelper antHelper = new SDKHelper(this, monitor); try { Map<String, String> properties = new HashMap<String, String>(); if (overrideProperties != null) { properties.putAll(overrideProperties); } final IPath buildFile = buildXmlFile.getRawLocation(); final String workingDir = getDefaultWorkingDir(buildFile); antHelper.runTarget(buildFile, command, properties, true, workingDir); } catch (Exception e) { return SDKCorePlugin.createErrorStatus(e); } return Status.OK_STATUS; }
private IFile makeIFile(String path) { IPath ipath = new Path(path); IFile ifile = mock(IFile.class); when(ifile.getRawLocation()).thenReturn(ipath); when(ifile.toString()).thenReturn(path); when(ifile.getName()).thenReturn(path); return ifile; }
private void copy(IFolder destinationFolder, String fileName) throws IOException { IFile destFile = destinationFolder.getFile(fileName); if (!destFile.exists()) { File destination = destFile.getRawLocation().toFile(); InputStream in = this.getClass().getResourceAsStream(fileName); OutputStream out = FileUtils.openOutputStream(destination); IOUtils.copy(in, out); IOUtils.closeQuietly(out); } }
public void annotate(final IFile file, final Iterable<RuleViolation> violations) throws CoreException, IOException { MarkerUtil.removeAllMarkers(file); if (!Iterables.isEmpty(violations)) { final String content = Files.toString(file.getRawLocation().toFile(), Charset.forName(file.getCharset())); for (final RuleViolation violation : violations) { MarkerUtil.addMarker(file, content, violation); } } }
protected List<String> getStoriesFullPaths() throws CoreException { List<String> stories = null; if (btnRadioSingleStory.getSelection() && storyFile != null) { String singleStory = (storyFile == null ? "" : storyFile.getRawLocation().toOSString()); stories = new ArrayList<String>(1); stories.add(singleStory); } else if (container != null) { stories = BehaviourSearch.findStoryPaths(container.getResource()); } return stories; }
/** * DOC xqliu Comment method "importFile". * * @param importFile * @param targetFile * @throws IOException */ public static void importFile(File importFile, IFile targetFile) throws IOException { if (importFile != null && targetFile != null) { File file = new File(targetFile.getRawLocation().toOSString()); if (file.exists()) { java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS"); // $NON-NLS-1$ File bakFile = new File( file.getAbsolutePath() + "." + simpleDateFormat.format(new Date()) + ".bak"); //$NON-NLS-1$ //$NON-NLS-2$ FilesUtils.copyFile(file, bakFile); } FilesUtils.copyFile(importFile, file); } }
/** * @param file * @return The content of the given file */ private String getFileContent(IFile file) { Scanner scanner = null; try { scanner = new Scanner(file.getRawLocation().toFile(), "UTF-8"); StringBuffer buffer = new StringBuffer(); if (scanner.hasNext()) { while (scanner.hasNext()) { buffer.append(scanner.nextLine()); buffer.append('\n'); } } return buffer.toString(); } catch (FileNotFoundException e) { CorePlugin.getDefault().logError(e); } finally { if (scanner != null) scanner.close(); } return ""; }
private void saveWorkflow() { wfDescription.addWorkflowNodesAndConnections(disabledWorkflowNodes, disabledConnections); WorkflowDescriptionPersistenceHandler persistenceHandler = new WorkflowDescriptionPersistenceHandler(); try (ByteArrayOutputStream content = persistenceHandler.writeWorkflowDescriptionToStream(wfDescription)) { ByteArrayInputStream input = new ByteArrayInputStream(content.toByteArray()); wfFile.setContents( input, // the file content true, // keep saving, even if IFile is out of sync with the Workspace false, // dont keep history null); // progress monitor wfFile.getProject().refreshLocal(IProject.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException | IOException e) { MessageDialog.openError( getShell(), "Error when Saving Workflow", "Failed to save workflow: " + e.getMessage()); LOG.error( StringUtils.format("Failed to save workflow: %s", wfFile.getRawLocation().toOSString())); } }
private Collection<IFile> execute(IFile model) throws Exception { Collection<IFile> result = new HashSet<IFile>(); for (String keyGenerator : getTransformation()) { monitor.addText("Start of model interpretation"); current_keyGenerator = keyGenerator; // Execute transformation TransformModel t = new TransformModel(); t.setASMFile(getASMFile(keyGenerator)); for (String key : getInputModels(keyGenerator).keySet()) { String _modelName = key; String _metamodelName = getInputModels(keyGenerator).get(key); // By default String _metamodelFile = "/com.bluexml.side.Requirements/model/requirements.ecore"; String _modelFile = model.getRawLocation().toString(); t.addInputModel(_modelName, _metamodelName, _modelFile, _metamodelFile); } IPath targetPath = new Path(getTargetPath()); targetPath = targetPath.append(new Path(getTEMP_FOLDER())); for (String key : getOutputModels(keyGenerator).keySet()) { String _modelName = key; String _metamodelName = getOutputModels(keyGenerator).get(key); // By default String _metamodelFile = "/com.bluexml.side.Requirements.generator/" + getTargetMetamodel(keyGenerator); String _modelFile = targetPath.append(getTargetModelName(keyGenerator)).toString(); t.addOutputModel(_modelName, _metamodelName, _modelFile, _metamodelFile); } t.setContributor(Activator.getDefault().getBundle().getSymbolicName()); try { t.execute(); } catch (Exception e) { e.printStackTrace(); } Set<String> outModels = t.getOutputModels(); for (String out : outModels) { IPath p = new Path(out.replaceAll("%20", " ")); IFile omodel = ResourcesPlugin.getWorkspace().getRoot().getFile(p); if (omodel.exists()) result.addAll(super.generate(omodel)); } postGeneration(); // Execute ANT scripts ExecuteANTScript a = new ExecuteANTScript(); a.setContributor(PLUGIN_ID); for (String script : getANTScripts(keyGenerator)) { a.addScript(script); } IWorkspaceRoot myWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); a.execute(myWorkspaceRoot.getFolder(new Path(getTemporaryFolder()))); monitor.addText("End of model interpretation"); } return result; }
public void run() { ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(); if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection) selection; if (structuredSelection.size() == 1) { if (structuredSelection.getFirstElement() instanceof IFile) { IFile implementationNote = (IFile) structuredSelection.getFirstElement(); if (implementationNote.getFileExtension().equals("int")) { InputStream inStream; try { inStream = implementationNote.getContents(); long byteCount = implementationNote.getRawLocation().toFile().length(); byte[] byteArray = new byte[(int) byteCount]; inStream.read(byteArray); IDocument document = new Document(new String(byteArray)); FindReplaceDocumentAdapter frda = new FindReplaceDocumentAdapter(document); IRegion startRegion = frda.find(0, "8. Code Changes", true, true, true, false); int startOffset = startRegion.getOffset() + 17; IRegion endRegion = frda.find(startOffset, "End", true, true, true, false); int endOffset = endRegion.getOffset(); String fileList = document.get(startOffset, endOffset - startOffset); fileList = fileList.replaceAll("---------------\r\n", ""); fileList = fileList.replaceAll("Branch name:.*\r\n", ""); fileList = fileList.replaceAll("\r\n ", ""); fileList = fileList.replaceAll("\r\n", ","); fileList = fileList.replaceAll(">", ""); String[] filesString = fileList.split(","); if (filesString.length == 0) return; ArrayList<IFile> list = new ArrayList<IFile>(); for (int i = 0; i < filesString.length; i++) { if (!filesString[i].equals("")) { IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(filesString[i]); if (resource instanceof IFile) { list.add((IFile) resource); } } } if (list.size() == 0) return; IWorkingSetManager workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager(); String workingSetName = "chgset-" + implementationNote.getName().replaceAll(".int", ""); IWorkingSet set = workingSetManager.createWorkingSet( workingSetName, list.toArray(new IFile[list.size()])); IWorkingSet existingSet = workingSetManager.getWorkingSet(workingSetName); if (existingSet != null) { workingSetManager.removeWorkingSet(existingSet); } workingSetManager.addWorkingSet(set); inStream.close(); } catch (CoreException e) { } catch (IOException e) { } catch (BadLocationException e) { } } } } } }
@Nullable public JetFile getJetFile(@NotNull IFile file) { return getJetFile(new File(file.getRawLocation().toOSString())); }
@Override public void run(IAction action) { if (action.getId() == FILE_LOCATION_ACTION) { // 文件 } else if (action.getId() == FOLDER_LOCATION_ACTION) { // 文件夹 } else { // 其他 } if (selection instanceof IStructuredSelection) { IStructuredSelection sel = (IStructuredSelection) selection; Object obj = sel.getFirstElement(); /* * Donot work on IWorkSpace if(obj instanceof IResource) { IResource resource = (IResource) Platform.getAdapterManager().getAdapter(obj,IResource.class); if (resource != null) { try { IPath path = resource.getRawLocation() ; File winfile = path.toFile(); String winPath = winfile.getParent(); Runtime.getRuntime().exec("explorer " + winPath); } catch (IOException e) { e.printStackTrace(); } } } */ IPath path = null; System.out.println(obj.getClass()); if (obj instanceof IFile) { IFile file = (IFile) Platform.getAdapterManager().getAdapter(obj, IFile.class); path = file.getRawLocation(); } else if (obj instanceof IFolder) { IFolder folder = (IFolder) Platform.getAdapterManager().getAdapter(obj, IFolder.class); path = folder.getRawLocation(); } else if (obj instanceof IPackageFragmentRoot) { if (obj.getClass() .toString() .equals("class org.eclipse.jdt.internal.core.JarPackageFragmentRoot")) { MessageDialog.openInformation( workbenchpart.getSite().getShell(), "NeoFactory Enhance Plugins", "Sorry, this operation is not supported. \n\n" + "JarPackageFragmentRoot extends from PackageFragmentRoot, \n" + "PackageFragmentRoot implements IPackageFragmentRoot, \n" + "so I cannot hide this menu as while as I need that shows on source packages."); } else { IPackageFragmentRoot packageFragRoot = (IPackageFragmentRoot) Platform.getAdapterManager().getAdapter(obj, IPackageFragmentRoot.class); path = packageFragRoot.getResource().getRawLocation(); } } else if (obj instanceof IPackageFragment) { IPackageFragment packageFrag = (IPackageFragment) Platform.getAdapterManager().getAdapter(obj, IPackageFragment.class); path = packageFrag.getResource().getRawLocation(); } else if (obj instanceof ICompilationUnit) { ICompilationUnit unit = (ICompilationUnit) Platform.getAdapterManager().getAdapter(obj, ICompilationUnit.class); path = unit.getResource().getRawLocation(); } if (path != null) { try { File winfile = path.toFile(); String winPath = winfile.getParent(); Runtime.getRuntime().exec("explorer " + winPath); } catch (IOException e) { e.printStackTrace(); } } } }
private void doFinish( String fileName, String dataSetName, String sqlQueryText, IProgressMonitor monitor) throws CoreException { // create a sample file monitor.beginTask("Creating " + fileName, 2); // IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); getShell() .getDisplay() .asyncExec( new Runnable() { public void run() { { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); page.saveEditor(page.getActiveEditor(), false); page.closeEditor(page.getActiveEditor(), true); } } }); // retrieve the full system path: String fullfilename = reportFile.getRawLocation().toOSString(); // String fullfilename=osfile+"/"+fileName; monitor.worked(1); monitor.setTaskName("Fetching SQL..."); queryList = SQLUtility.getBIRTSQLFields(sqlQueryText); monitor.worked(2); monitor.setTaskName("Generate SQL Data"); // SQLUtility.saveDataSetDesign(null, null, null); MAXIMOReportDesigner birtReport = new MAXIMOReportDesigner(fullfilename, fullfilename, sqlQueryText, queryList); birtReport.addDataSet(dataSetName); // Close Connection sqlpage.closeConnection(); monitor.worked(3); monitor.setTaskName("Opening file for editing..."); getShell() .getDisplay() .asyncExec( new Runnable() { public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { // page.close(); IDE.openEditor(page, reportFile, true); } catch (PartInitException e) { } } }); monitor.worked(4); }
public void setFilepath(IFile htmlfile) { if (htmlfile.exists()) { URL cleanUrl; URL dermUrl; try { IEclipsePreferences workPrefs = InstanceScope.INSTANCE.getNode("org.xtext.hipie.ui"); cleanUrl = htmlfile.getRawLocationURI().toURL(); cleanHtmlUrl = cleanUrl; IFile ddlFile = htmlfile .getProject() .getFile( htmlfile .getProjectRelativePath() .removeFileExtension() .addFileExtension("ddl")); IFile databombFile = htmlfile .getProject() .getFile( htmlfile .getProjectRelativePath() .removeFileExtension() .addFileExtension("databomb")); IFile persistFile = htmlfile .getProject() .getFile( htmlfile .getProjectRelativePath() .removeFileExtension() .addFileExtension("persist")); if (ddlFile.exists() && databombFile.exists() && persistFile.exists()) { InputStream inStreamDdl = ddlFile.getContents(); String streamStringDdl = ""; Scanner scInddl = new Scanner(inStreamDdl); if (scInddl.hasNext()) streamStringDdl = scInddl.useDelimiter("\\Z").next(); inStreamDdl.close(); scInddl.close(); InputStream inStreamDatabomb = databombFile.getContents(); String streamStringData = ""; Scanner scIndatabomb = new Scanner(inStreamDatabomb); if (scIndatabomb.hasNext()) streamStringData = scIndatabomb.useDelimiter("\\Z").next(); streamStringData = streamStringData.replace("\n", ""); streamStringData = streamStringData.replace("\t", ""); streamStringData = streamStringData.replace("\r", ""); inStreamDatabomb.close(); scIndatabomb.close(); InputStream inStreamPersist = persistFile.getContents(); String streamStringPersist = ""; Scanner scInper = new Scanner(inStreamPersist); if (scInper.hasNext()) streamStringPersist = scInper.useDelimiter("\\Z").next(); inStreamPersist.close(); scInper.close(); String ddl = streamStringDdl; String databomb = streamStringData; String persist = streamStringPersist; dermUrl = new URL("platform:/plugin/org.xtext.hipie/vis_files/dermatology.html"); InputStream inStreamDerm = dermUrl.openConnection().getInputStream(); String streamStringHtml = ""; Scanner scIn = new Scanner(inStreamDerm); if (scIn.hasNext()) streamStringHtml = scIn.useDelimiter("\\Z").next(); streamStringHtml = streamStringHtml.replace("%_data_%", databomb); streamStringHtml = streamStringHtml.replace("%_ddl_%", ddl); streamStringHtml = streamStringHtml.replace("%_persist_%", persist); inStreamDerm.close(); scIn.close(); String html = streamStringHtml; designModeBrowser.setText(html); String htmlFilepath = htmlfile.getRawLocation().toOSString(); workPrefs.put("clean_html_url_design", cleanHtmlUrl.toString()); workPrefs.put("clean_html_filepath_design", htmlFilepath); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (CoreException e) { e.printStackTrace(); } } }
// public for testing public static String calculateClasspath(IJavaProject javaProject) { try { Set accumulatedPathEntries = new LinkedHashSet(); IProject project = javaProject.getProject(); String projectName = project.getName(); IPath defaultOutputPath = javaProject.getOutputLocation(); String defaultOutputLocation = pathToString(defaultOutputPath, project); IClasspathEntry[] cpes = javaProject.getResolvedClasspath(true); if (cpes != null) { for (int i = 0, max = cpes.length; i < max; i++) { IClasspathEntry cpe = cpes[i]; if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) { continue; } // Two kinds of entry we are interested in - those relative and those absolute // relative example: grails/lib/hibernate3-3.3.1.jar (where grails is the project name) // absolute example: f:/grails-111/dist/grails-core-blah.jar // javaProject path is f:\grails\grails IPath cpePath = cpe.getPath(); String pathElement = null; String segmentZero = cpePath.segment(0); if (segmentZero.equals(projectName)) { pathElement = project.getFile(cpePath.removeFirstSegments(1)).getRawLocation().toOSString(); } else { // for GRECLIPSE-917. Entry is something like /SomeOtherProject/foo/bar/doodah.jar if (cpe.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { try { IProject iproject = project.getWorkspace().getRoot().getProject(segmentZero); if (iproject != null) { IFile ifile = iproject.getFile(cpePath.removeFirstSegments(1)); IPath ipath = (ifile == null ? null : ifile.getRawLocation()); pathElement = (ipath == null ? null : ipath.toOSString()); } } catch (Throwable t) { t.printStackTrace(); } } if (cpe.getEntryKind() == IClasspathEntry.CPE_PROJECT) { // the classpath entry is a dependency on another project computeDependenciesFromProject(project, segmentZero, accumulatedPathEntries); // FIXASC this ought to also allow for separate output folders in the project we // depend upon *sigh* // FIXASC what does all this look like for batch compilation? Should it be passed in // rather than computed here } else { if (pathElement == null) { pathElement = cpe.getPath().toOSString(); } } } if (pathElement != null) { accumulatedPathEntries.add(pathElement); } } accumulatedPathEntries.add(defaultOutputLocation); StringBuilder sb = new StringBuilder(); Iterator iter = accumulatedPathEntries.iterator(); while (iter.hasNext()) { sb.append((String) iter.next()); sb.append(File.pathSeparator); } String classpath = sb.toString(); // System.out.println("Project classpath for '"+projectName+"' is "+classpath); return classpath; } } catch (JavaModelException jme) { System.err.println( "Problem trying to determine classpath of project " + javaProject.getProject().getName() + ":"); //$NON-NLS-1$ //$NON-NLS-2$ jme.printStackTrace(); } return ""; //$NON-NLS-1$ }
/** * Run PMD against a resource * * @param resource the resource to process */ protected final void reviewResource(IResource resource) { IFile file = (IFile) resource.getAdapter(IFile.class); if (file == null || file.getFileExtension() == null) return; Reader input = null; try { boolean included = isIncluded(file); log.debug("Derived files included: " + projectProperties.isIncludeDerivedFiles()); log.debug("file " + file.getName() + " is derived: " + file.isDerived()); log.debug("file checked: " + included); prepareMarkerAccumulator(file); LanguageVersionDiscoverer languageDiscoverer = new LanguageVersionDiscoverer(); LanguageVersion languageVersion = languageDiscoverer.getDefaultLanguageVersionForFile(file.getName()); // in case it is java, select the correct java version if (languageVersion != null && languageVersion.getLanguage() == Language.JAVA) { languageVersion = PMDPlugin.javaVersionFor(file.getProject()); } if (languageVersion != null) { configuration().setDefaultLanguageVersion(languageVersion); } log.debug("discovered language: " + languageVersion); final File sourceCodeFile = file.getRawLocation().toFile(); if (included && getRuleSet().applies(sourceCodeFile) && isFileInWorkingSet(file) && languageVersion != null) { subTask("PMD checking: " + file.getName()); Timer timer = new Timer(); RuleContext context = PMD.newRuleContext(file.getName(), sourceCodeFile); context.setLanguageVersion(languageVersion); input = new InputStreamReader(file.getContents(), file.getCharset()); // getPmdEngine().processFile(input, getRuleSet(), context); // getPmdEngine().processFile(sourceCodeFile, getRuleSet(), context); RuleSets rSets = new RuleSets(getRuleSet()); new SourceCodeProcessor(configuration()).processSourceCode(input, rSets, context); timer.stop(); pmdDuration += timer.getDuration(); updateMarkers(file, context, isUseTaskMarker()); worked(1); fileCount++; } else { log.debug("The file " + file.getName() + " is not in the working set"); } } catch (CoreException e) { log.error("Core exception visiting " + file.getName(), e); // TODO: // complete message } catch (PMDException e) { log.error("PMD exception visiting " + file.getName(), e); // TODO: // complete message } catch (IOException e) { log.error("IO exception visiting " + file.getName(), e); // TODO: // complete message } catch (PropertiesException e) { log.error("Properties exception visiting " + file.getName(), e); // TODO: // complete message } finally { IOUtil.closeQuietly(input); } }