protected boolean writeClassFileCheck(IFile file, String fileName, byte[] newBytes) throws CoreException { try { byte[] oldBytes = Util.getResourceContentsAsByteArray(file); notEqual: if (newBytes.length == oldBytes.length) { for (int i = newBytes.length; --i >= 0; ) if (newBytes[i] != oldBytes[i]) break notEqual; return false; // bytes are identical so skip them } URI location = file.getLocationURI(); if (location == null) return false; // unable to determine location of this class file String filePath = location.getSchemeSpecificPart(); ClassFileReader reader = new ClassFileReader(oldBytes, filePath.toCharArray()); // ignore local types since they're only visible inside a single method if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) { if (JavaBuilder.DEBUG) System.out.println("Type has structural changes " + fileName); // $NON-NLS-1$ addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } } catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } return true; }
private static IFileEditorInput getFileStorage(int index) throws CoreException { String filename = getBatchDateString(); filename += (index > 0 ? "_" + index : "") + ".tcl"; IFolder templateFolder = SicsVisualBatchViewer.getProjectFolder( SicsVisualBatchViewer.EXPERIMENT_PROJECT, FOLDER_TEMPLATE); IFile templateFile = templateFolder.getFile(FILE_TEMPLATE); IFolder folder = SicsVisualBatchViewer.getProjectFolder( SicsVisualBatchViewer.EXPERIMENT_PROJECT, SicsVisualBatchViewer.AUTOSAVE_FOLDER); IFileEditorInput input = new FileEditorInput(folder.getFile(filename)); if (input.exists()) { return getFileStorage(index++); } else { try { byte[] read = null; if (templateFile.exists()) { long size = EFS.getStore(templateFile.getLocationURI()).fetchInfo().getLength(); // long size = templateFolder.getLocation().toFile().length(); read = new byte[(int) size]; InputStream inputStream = templateFile.getContents(); inputStream.read(read); } else { read = new byte[0]; templateFile.create(new ByteArrayInputStream(read), IResource.ALLOW_MISSING_LOCAL, null); } input.getFile().create(new ByteArrayInputStream(read), IResource.ALLOW_MISSING_LOCAL, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return input; }
@Override public void doSave(IProgressMonitor monitor) { super.doSave(monitor); final ActivitiDiagramEditorInput adei = (ActivitiDiagramEditorInput) getEditorInput(); try { final IFile dataFile = adei.getDataFile(); final String diagramFileString = dataFile.getLocationURI().getPath(); BpmnMemoryModel model = ModelHandler.getModel(EcoreUtil.getURI(getDiagramTypeProvider().getDiagram())); // Save the bpmn diagram file doSaveToBpmn(model, diagramFileString); // Save an image of the diagram doSaveImage(diagramFileString, model); // Refresh the resources in the workspace before invoking export // marshallers, as they may need access to resources dataFile.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); // Invoke export marshallers to produce additional output doInvokeExportMarshallers(model); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } ((BasicCommandStack) getEditingDomain().getCommandStack()).saveIsDone(); updateDirtyState(); }
/** * Method "replace". * * @return true if ok */ public boolean replace(String migrationTaskName) { IFolder librariesFolder = ResourceManager.getLibrariesFolder(); IFile definitionFile = librariesFolder.getFile(TALENDDEFINITIONFILENAME); if (definitionFile.exists()) { File file = new File(definitionFile.getLocationURI()); try { String content = FileUtils.readFileToString(file, EMFUtil.ENCODING); for (String oldString : old2new.keySet()) { String newString = old2new.get(oldString); if (log.isInfoEnabled()) { log.info( DefaultMessagesImpl.getString( "TalendDefinitionFileUpdate_MigLog", migrationTaskName, oldString, newString)); //$NON-NLS-1$ } content = StringUtils.replace(content, oldString, newString); } FileUtils.writeStringToFile(file, content, EMFUtil.ENCODING); } catch (IOException e) { log.error(e.getMessage(), e); return false; } } return true; }
protected void addOrUpdateProjectToConf(EditorProject editorProject, IProject gemocProject) { IFile configFile = gemocProject.getFile(new Path(Activator.GEMOC_PROJECT_CONFIGURATION_FILE)); if (configFile.exists()) { Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE; Map<String, Object> m = reg.getExtensionToFactoryMap(); m.put(Activator.GEMOC_PROJECT_CONFIGURATION_FILE_EXTENSION, new XMIResourceFactoryImpl()); // Obtain a new resource set ResourceSet resSet = new ResourceSetImpl(); // get the resource Resource resource = resSet.getResource(URI.createURI(configFile.getLocationURI().toString()), true); LanguageDefinition gemocLanguageWorkbenchConfiguration = (LanguageDefinition) resource.getContents().get(0); addOrUpdateProjectToConf(editorProject, gemocLanguageWorkbenchConfiguration); try { resource.save(null); } catch (IOException e) { Activator.error(e.getMessage(), e); } } try { configFile.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor()); } catch (CoreException e) { Activator.error(e.getMessage(), e); } }
public void testFindFilesByLocation() throws Exception { fProject.create(new NullProgressMonitor()); fProject.open(new NullProgressMonitor()); createFolder(fProject, "folder1"); createFolder(fProject, "folder2"); IFile file = createFile(fProject, "abc.h"); createFile(fProject, "folder1/abc.h"); createFile(fProject, "folder2/abC.h"); URI uri = file.getLocationURI(); IPath path = file.getLocation(); IFile[] files = ResourceLookup.findFilesForLocationURI(uri); assertEquals(1, files.length); files = ResourceLookup.findFilesForLocation(path); assertEquals(1, files.length); if (new File("a").equals(new File("A"))) { URI upperCase = new URI(uri.getScheme(), uri.getSchemeSpecificPart().toUpperCase(), uri.getFragment()); IPath upperCasePath = new Path(path.toString().toUpperCase()); files = ResourceLookup.findFilesForLocationURI(upperCase); assertEquals(1, files.length); files = ResourceLookup.findFilesForLocation(upperCasePath); assertEquals(1, files.length); } }
/** * Computes file metrics. * * @param file File. * @return Map that contains key-value pairs if object metrics. */ private Map<String, String> computeFileMetrics(IFile file) { // Adds statechange DevEvent. Map<String, String> statechangeKeyValueMap = new HashMap<String, String>(); statechangeKeyValueMap.put(EclipseSensorConstants.SUBTYPE, "StateChange"); // Process file size String sizeString = String.valueOf(activeBufferSize); statechangeKeyValueMap.put(PROP_CURRENT_SIZE, sizeString); if (file.getName().endsWith(EclipseSensorConstants.JAVA_EXT)) { // Fully qualified class path String className = this.getFullyQualifedClassName(file); statechangeKeyValueMap.put(PROP_CLASS_NAME, className); // Measure java file. JavaStatementMeter testCounter = measureJavaFile(file); this.class2FileMap.put(className, file.getLocationURI()); String methodCountString = String.valueOf(testCounter.getNumOfMethods()); statechangeKeyValueMap.put(PROP_CURRENT_METHODS, methodCountString); String statementCountString = String.valueOf(testCounter.getNumOfStatements()); statechangeKeyValueMap.put(PROP_CURRENT_STATEMENTS, statementCountString); // Number of test method and assertion statements. if (testCounter.hasTest()) { String testMethodCount = String.valueOf(testCounter.getNumOfTestMethods()); statechangeKeyValueMap.put(PROP_CURRENT_TEST_METHODS, testMethodCount); String testAssertionCount = String.valueOf(testCounter.getNumOfTestAssertions()); statechangeKeyValueMap.put(PROP_CURRENT_TEST_ASSERTIONS, testAssertionCount); } } return statechangeKeyValueMap; }
private List<Configuration> createConfigurations( final Collection<String> unusedFeatures, final IMonitor monitor, boolean collect) { monitor.setTaskName("Create configurations"); monitor.setRemainingWork(unusedFeatures.size()); final List<Configuration> confs = new LinkedList<Configuration>(); final FileHandler<Configuration> writer = new FileHandler<>(ConfigurationManager.getDefaultFormat()); Configuration configuration = new Configuration(featureModel, false); try { List<List<String>> solutions = configuration.coverFeatures(unusedFeatures, monitor, false); for (List<String> solution : solutions) { configuration = new Configuration(featureModel, false); for (String feature : solution) { if (!"True".equals(feature)) { configuration.setManual(feature, Selection.SELECTED); } } if (collect) { confs.add(configuration); } else { final IFile configurationFile = getConfigurationFile(project.getConfigFolder()); writer.write(Paths.get(configurationFile.getLocationURI()), configuration); } } } catch (TimeoutException e1) { e1.printStackTrace(); } return confs; }
private ITraceabilityStorage getStorage(IProject p) { IFile file = p.getFile(new Path(TraceabilityAttributesManager.STORAGE_PATH)); // get the storage for the file path String uri = file.getLocationURI().getPath(); ITraceabilityStorage storage = storageProvider.getStorage(uri); return storage; }
/** * (non-Javadoc) * * @see org.eclipse.ice.core.iCore.ICore#importFileAsItem(org.eclipse.core.resources.IFile, * java.lang.String) */ @Override public String importFileAsItem(IFile file, String itemType) { // This is an IFile, meaning it came from an existing // IProject, call importFileAsItem with the file URI and its // corresponding IProject return importFileAsItem(file.getLocationURI(), itemType, file.getProject()); }
/** * Moves a file to the output directory with a new name. * * @param project the current project * @param sourceFile output file to be moved * @param destDir the destination directory of the file * @param destName the new name of the file * @param monitor progress monitor * @throws CoreException if an error occurs * @return file in the new location */ private static IFile moveFile( IProject project, IFile sourceFile, IContainer destContainer, String destName, IProgressMonitor monitor) throws CoreException { if (sourceFile != null && sourceFile.exists() && destName != null) { final IPath destRelPath = new Path(destName); final IFile dest = destContainer.getFile(destRelPath); if (dest.exists()) { File outFile = new File(sourceFile.getLocationURI()); File destFile = new File(dest.getLocationURI()); try { // Try to move the content instead of deleting the old file // and replace it by the new one. This is better for some // viewers like Sumatrapdf FileOutputStream out = new FileOutputStream(destFile); out.getChannel().tryLock(); BufferedInputStream in = new BufferedInputStream(new FileInputStream(outFile)); byte[] buf = new byte[4096]; int l; while ((l = in.read(buf)) != -1) { out.write(buf, 0, l); } in.close(); out.close(); sourceFile.delete(true, monitor); } catch (IOException e) { // try to delete and move the file dest.delete(true, monitor); sourceFile.move(dest.getFullPath(), true, monitor); } } else { // move the file sourceFile.move(dest.getFullPath(), true, monitor); } monitor.worked(1); return dest; } else { return null; } }
/* * (non-Javadoc) * * @see org.eclipse.jface.action.Action#run() */ @Override protected void doRun() { RepositoryNode node = (RepositoryNode) ((IStructuredSelection) getSelection()).getFirstElement(); Item item = node.getObject().getProperty().getItem(); if (item == null) { return; } URL url = null; // String extension = null; if (item instanceof DocumentationItem) { DocumentationItem documentationItem = (DocumentationItem) item; // if (documentationItem.getExtension() != null) { // extension = documentationItem.getExtension(); // } IFile file = LinkDocumentationHelper.getTempFile( documentationItem.getName(), documentationItem.getExtension()); try { documentationItem.getContent().setInnerContentToFile(file.getLocation().toFile()); url = file.getLocationURI().toURL(); } catch (Exception e) { showErrorMessage(); return; } } else if (item instanceof LinkDocumentationItem) { // link documenation LinkDocumentationItem linkDocItem = (LinkDocumentationItem) item; if (!LinkUtils.validateLink(linkDocItem.getLink())) { showErrorMessage(); return; } // if (linkDocItem.getExtension() != null) { // extension = linkDocItem.getExtension(); // } String uri = linkDocItem.getLink().getURI(); if (LinkUtils.isRemoteFile(uri)) { try { url = new URL(uri); } catch (MalformedURLException e) { // } } else if (LinkUtils.existedFile(uri)) { try { url = new File(uri).toURL(); } catch (MalformedURLException e) { // } } } openedByBrowser(item, url); // progress(item, extension); }
/** * Gets the URI of the associated file. It will return file URI in format such as * file:/D:/cvs/foobarproject/src/foo/bar/Bar.java. When a developers is not editing an active * file, this method will return a dummy file resource. * * @param textEditor A ITextEditor instance form which the file name is retrieved. * @return The fully qualified file name. For example, C:\cvs\foobarproject\src\foo\bar\Bar.java. */ private URI getFileResource(ITextEditor textEditor) { if (textEditor != null) { IEditorInput editorInput = textEditor.getEditorInput(); if (editorInput instanceof IFileEditorInput) { IFileEditorInput input = (IFileEditorInput) editorInput; IFile file = input.getFile(); if (file != null) { return file.getLocationURI(); } } } // Return a dummy unknown resource if can not resolve the file being edited. return URI.create("file:///Unknown"); }
/** * Method "indexOf". * * @return the index of the first occurrence of the character in the character sequence * represented by this object, or <code>-1</code> if the character does not occur. */ public int indexOf(String str) { IFolder librariesFolder = ResourceManager.getLibrariesFolder(); IFile definitionFile = librariesFolder.getFile(TALENDDEFINITIONFILENAME); if (definitionFile.exists()) { File file = new File(definitionFile.getLocationURI()); try { String content = FileUtils.readFileToString(file, EMFUtil.ENCODING); return content.indexOf(str); } catch (IOException e) { log.error(e.getMessage(), e); return -1; } } return -1; }
protected CMElementDeclaration checkExternalSchema(Element element) { final Document document = element.getOwnerDocument(); if (document instanceof IDOMDocument) { final String baseLocation = ((IDOMDocument) document).getModel().getBaseLocation(); if (baseLocation != null) { final IPath basePath = new Path(baseLocation); IFile file = null; if (basePath.segmentCount() > 1) { file = ResourcesPlugin.getWorkspace().getRoot().getFile(basePath); } final URI uri = (file == null || !file.isAccessible()) ? new File(baseLocation).toURI() : file.getLocationURI(); if (uri != null) { IExternalSchemaLocationProvider[] providers = ExternalSchemaLocationProviderRegistry.getInstance().getProviders(); for (int i = 0; i < providers.length; i++) { long time = _trace ? System.currentTimeMillis() : 0; final Map locations = providers[i].getExternalSchemaLocation(uri); if (_trace) { long diff = System.currentTimeMillis() - time; if (diff > 250) Logger.log( Logger.INFO, "Schema location provider took [" + diff + "ms] for URI [" + uri + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } if (locations != null && !locations.isEmpty()) { Object location = locations.get(IExternalSchemaLocationProvider.NO_NAMESPACE_SCHEMA_LOCATION); if (location != null) return getCMElementDeclaration( element, NamespaceTable.getElementLineage(element), uri.toString(), location.toString()); } } } } } return null; }
private Process create(IFile file) throws CoreException { Process process = null; try { JAXBContext context = JAXBContext.newInstance(Process.class); Unmarshaller unmarshaller = context.createUnmarshaller(); File location = new File(file.getLocationURI()); FileReader reader = new FileReader(location); process = (Process) unmarshaller.unmarshal(reader); ModelHelper.processModel(process, location); ModelHelper.buildCascade(process); } catch (Exception e) { process = new Process(); } return process; }
private void loadInput(IEditorInput input) { NPNetsPackage.eINSTANCE.eClass(); ResourceSet resourceSet = new ResourceSetImpl(); if (input instanceof IFileEditorInput) { IFileEditorInput fileInput = (IFileEditorInput) input; IFile file = fileInput.getFile(); resourceNPN = resourceSet.createResource(URI.createURI(file.getLocationURI().toString())); try { resourceNPN.load(null); npnetMarked = (NPnetMarked) resourceNPN.getContents().get(0); } catch (IOException e) { e.printStackTrace(); npnetMarked = null; } } }
public static void updateMavenDependencies( final List<Dependency> dependencies, final IProject project) throws CoreException { final IFile pomIFile = project.getProject().getFile("pom.xml"); final File pomFile = new File(pomIFile.getLocationURI()); final org.apache.maven.model.Model pom = MavenPlugin.getMaven().readModel(pomFile); // Check if dependency already in the pom final List<Dependency> missingDependencies = new ArrayList<>(); for (final Dependency dependency : dependencies) { boolean found = false; for (final org.apache.maven.model.Dependency pomDependency : pom.getDependencies()) { if (pomDependency.getGroupId().equalsIgnoreCase(dependency.getGroupId()) && pomDependency.getArtifactId().equalsIgnoreCase(dependency.getArtifactId())) { // check for correct version if (!pomDependency.getVersion().equalsIgnoreCase(dependency.getVersion())) { pomDependency.setVersion(dependency.getVersion()); } found = true; break; } } if (!found) { missingDependencies.add(dependency); } } for (final Dependency dependency : missingDependencies) { final org.apache.maven.model.Dependency pomDependency = new org.apache.maven.model.Dependency(); pomDependency.setGroupId(dependency.getGroupId()); pomDependency.setArtifactId(dependency.getArtifactId()); pomDependency.setVersion(dependency.getVersion()); pom.addDependency(pomDependency); } if (!missingDependencies.isEmpty()) { try (final OutputStream stream = new BufferedOutputStream(new FileOutputStream(pomFile))) { MavenPlugin.getMaven().writeModel(pom, stream); pomIFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (final Exception e) { Activator.error(e); } } }
@Override public void doSave(IProgressMonitor monitor) { try { JAXBContext context = JAXBContext.newInstance(Process.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK"); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); IFile file = ((IFileEditorInput) getEditorInput()).getFile(); File location = new File(file.getLocationURI()); marshaller.marshal(model, location); ModelHelper.processXML((Process) this.model, location); getCommandStack().markSaveLocation(); } catch (Exception e) { e.printStackTrace(); } }
@Override public void run(IAction arg0) { for (Iterator i = structuredSelection.iterator(); i.hasNext(); ) { Object nextSelected = i.next(); if (nextSelected instanceof IFile) { IFile file = (IFile) nextSelected; String path = file.getLocationURI().getPath(); if (path.startsWith("/")) { path = path.substring(1); } XmlParser xmlParser = new XmlParser(path); xmlParser.parse(xmlParser.getDocument().getDocumentElement(), false); MyVelocityEngine engine = new MyVelocityEngine(); Map map = new HashMap(); map.put("domObjectList", xmlParser.getObjList()); String generate = engine.generate(map, "genCVS.vm", true); System.out.println(generate); } } }
/** * Write the contents of the file to the tar archive. * * @param entry * @param contents * @exception java.io.IOException * @exception org.eclipse.core.runtime.CoreException */ private void write(TarEntry entry, IFile contents) throws IOException, CoreException { final URI location = contents.getLocationURI(); if (location == null) { throw new FileNotFoundException(contents.getFullPath().toOSString()); } InputStream contentStream = contents.getContents(false); entry.setSize(EFS.getStore(location).fetchInfo().getLength()); outputStream.putNextEntry(entry); try { int n; byte[] readBuffer = new byte[4096]; while ((n = contentStream.read(readBuffer)) > 0) { outputStream.write(readBuffer, 0, n); } } finally { if (contentStream != null) { contentStream.close(); } } outputStream.closeEntry(); }
/** * @see * org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration, * java.lang.String, org.eclipse.debug.core.ILaunch, * org.eclipse.core.runtime.IProgressMonitor) */ @Override public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { SubMonitor submonitor = SubMonitor.convert(monitor, 13); try { // wait RSE is initialized // TODO not sure this is the good way to wait for init everywhere in the code RSEUtil.waitForRSEInitialization(); // get configuration information String projectName = configuration.getAttribute(LuaRemoteDebugConstant.PROJECT_NAME, ""); // $NON-NLS-1$ String scriptName = configuration.getAttribute(LuaRemoteDebugConstant.SCRIPT_NAME, ""); // $NON-NLS-1$ IHost host = LuaRemoteLaunchConfigurationUtil.getHost(configuration); @SuppressWarnings("rawtypes") Map env = configuration.getAttribute( ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, Collections.EMPTY_MAP); // valid configuration information String errorMessage = LuaRemoteLaunchConfigurationUtil.validateRemoteLaunchConfiguration( projectName, scriptName, host); if (errorMessage != null) throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, errorMessage)); submonitor.worked(1); // get Project IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); // get the first found remote file SubSystem IRemoteFileSubSystem remoteFileSubSystem = RSEUtil.getRemoteFileSubsystem(host); // get the first found Lua SubSystem LuaSubSystem luaSubSystem = LuaRSEUtil.getLuaSubSystem(host); // try to connect to the target try { if (submonitor.isCanceled()) return; remoteFileSubSystem.connect(submonitor.newChild(1), false); // CHECKSTYLE:OFF } catch (Exception e) { // CHECKSTYLE:ON throw new CoreException( new Status( IStatus.ERROR, Activator.PLUGIN_ID, Messages.LuaRemoteLaunchConfigurationDelegate_error_connectionfailed, e)); } // create script project IScriptProject scriptProject = DLTKCore.create(project); // compute the remote project workingdir if (submonitor.isCanceled()) return; String outputDirectory = luaSubSystem.getOutputDirectory(); String defaultRemoteApplicationFolderPath = outputDirectory + remoteFileSubSystem.getSeparator() + configuration.getName(); String remoteApplicationFolderPath = configuration.getAttribute( LuaRemoteDebugConstant.OUTPUT_DIRECTORY, defaultRemoteApplicationFolderPath); // compute script file source path relative path String scriptProjectRelativePath = configuration.getAttribute( LuaRemoteDebugConstant.SCRIPT_NAME, LuaConstants.DEFAULT_MAIN_FILE); IFile scriptFile = project.getFile(scriptProjectRelativePath); IModuleSource moduleSource = LuaUtils.getModuleSourceFromAbsoluteURI(scriptFile.getLocationURI(), scriptProject); if (moduleSource == null) throw new CoreException( new Status( IStatus.ERROR, Activator.PLUGIN_ID, NLS.bind( Messages .LuaRemoteLaunchConfigurationDelegate_error_unabletofindsourcerelativepath, scriptProjectRelativePath))); IPath scriptSourcePathRelativePath = LuaUtils.getSourcePathRelativePath(moduleSource); // kill Process if already running // could happen if connection is closed and last process launch is not terminate Session session = RSEUtil.getCurrentSshSession(host.getConnectorServices()); SshProcess.killProcess(session, remoteApplicationFolderPath); // check an prepare remote folder try { if (submonitor.isCanceled()) return; IRemoteFile remoteApplicationPath = remoteFileSubSystem.getRemoteFileObject(outputDirectory, submonitor.newChild(1)); if (remoteApplicationPath.exists()) { if (remoteApplicationPath.isFile()) { throw new CoreException( new Status( IStatus.ERROR, Activator.PLUGIN_ID, NLS.bind( Messages.LuaRemoteLaunchConfigurationDelegate_error_filealreadyexist, outputDirectory))); } } else { remoteFileSubSystem.createFolder(remoteApplicationPath, submonitor.newChild(1)); } submonitor.setWorkRemaining(9); // remoteFile is a folder // create(or delete and recreate) the working directory if (submonitor.isCanceled()) return; IRemoteFile remoteWorkingFolder = remoteFileSubSystem.getRemoteFileObject( remoteApplicationFolderPath, submonitor.newChild(1)); if (remoteWorkingFolder.exists()) { if (remoteWorkingFolder.isFile()) { throw new CoreException( new Status( IStatus.ERROR, Activator.PLUGIN_ID, MessageFormat.format( Messages.LuaRemoteLaunchConfigurationDelegate_error_filealreadyexist, remoteApplicationFolderPath))); } else { remoteFileSubSystem.delete(remoteWorkingFolder, submonitor.newChild(1)); } } submonitor.setWorkRemaining(7); // create project application if (submonitor.isCanceled()) return; remoteFileSubSystem.createFolder(remoteWorkingFolder, submonitor.newChild(1)); // upload sourcecode LuaRSEUtil.uploadFiles( remoteFileSubSystem, scriptProject, remoteApplicationFolderPath, submonitor.newChild(2)); // upload Debug module if (mode.equals(ILaunchManager.DEBUG_MODE)) { SubMonitor debugmonitor = submonitor.newChild(1); debugmonitor.setWorkRemaining(DEBUG_FILES.length); String localEncoding = Charset.defaultCharset().name(); String remoteEncoding = remoteFileSubSystem.getRemoteEncoding(); for (String luaFile : DEBUG_FILES) { try { Bundle bundle = Platform.getBundle( org.eclipse.koneki.ldt.debug.core.internal.Activator.PLUGIN_ID); URL resource = bundle.getResource(luaFile); File result = new File(FileLocator.toFileURL(resource).getPath()); String remotePath = remoteApplicationFolderPath + remoteFileSubSystem.getSeparator() + result.getName(); remoteFileSubSystem.upload( result.getAbsolutePath(), localEncoding, remotePath, remoteEncoding, submonitor.newChild(1)); } catch (IOException e) { throw new CoreException( new Status( IStatus.ERROR, Activator.PLUGIN_ID, Messages .LuaRemoteLaunchConfigurationDelegate_error_unabletouploaddebuggerfiles, e)); } } } } catch (SystemMessageException e) { throw new CoreException( new Status( IStatus.ERROR, Activator.PLUGIN_ID, NLS.bind( Messages .LuaRemoteLaunchConfigurationDelegate_error_unabletoaccestoremoteapplicationdir, outputDirectory), e)); } // set environment var Map<String, String> envVars = new HashMap<String, String>(); String luaPath = luaSubSystem.getLuaPath(); // if no luapath defined at subsystem level used the default one. if (luaPath == null || luaPath.isEmpty()) luaPath = "$LUA_PATH;"; // $NON-NLS-1$ // add default lua envvar StringBuilder luaPathBuilder = new StringBuilder(luaPath); // check if lua path don't end with a ";" if (!luaPath.matches(".*;\\s*$")) // $NON-NLS-1$ luaPathBuilder.append(";"); // $NON-NLS-1$ // add working dir to lua path luaPathBuilder.append(remoteApplicationFolderPath); luaPathBuilder.append(remoteFileSubSystem.getSeparator()); luaPathBuilder.append(LuaDebugConstants.LUA_PATTERN); // add init pattern for working dir to lua path luaPathBuilder.append(remoteApplicationFolderPath); luaPathBuilder.append(remoteFileSubSystem.getSeparator()); luaPathBuilder.append(LuaDebugConstants.WILDCARD_PATTERN); luaPathBuilder.append(remoteFileSubSystem.getSeparator()); luaPathBuilder.append(LuaDebugConstants.LUA_INIT_PATTERN); envVars.put(LuaDebugConstants.LUA_PATH, luaPathBuilder.toString()); String luaCPath = luaSubSystem.getCLuaPath(); if (luaCPath != null && !luaCPath.isEmpty()) envVars.put(LuaDebugConstants.LUA_CPATH, luaCPath); String ldLibraryPath = luaSubSystem.getLDLibraryPath(); if (ldLibraryPath != null && !ldLibraryPath.isEmpty()) envVars.put(LuaDebugConstants.LUA_LDLIBRARYPATH, ldLibraryPath); // add launch configuration env vars for (Object oEntry : env.entrySet()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Entry) oEntry; envVars.put(entry.getKey().toString(), entry.getValue().toString()); } // add debug information String sessionID = null; if (mode.equals(ILaunchManager.DEBUG_MODE)) { sessionID = DbgpSessionIdGenerator.generate(); // try to find host ide IP Address only if it's not define by user if (!envVars.containsKey(LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_HOST)) { String bindedAddress = NetworkUtil.findBindedAddress(host.getHostName(), submonitor.newChild(1)); if (bindedAddress == null) throw new CoreException( new Status( IStatus.ERROR, Activator.PLUGIN_ID, NLS.bind( Messages.LuaRemoteLaunchConfigurationDelegate_error_unable_to_define_ideip, LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_HOST))); envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_HOST, bindedAddress); } // dbgp env vars envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_KEY, sessionID); envVars.put( LuaDebugConstants.ENV_VAR_KEY_DBGP_IDE_PORT, String.valueOf(DLTKDebugPlugin.getDefault().getDbgpService().getPort())); envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_PLATFORM, "unix"); // $NON-NLS-1$ envVars.put(LuaDebugConstants.ENV_VAR_KEY_DBGP_WORKINGDIR, remoteApplicationFolderPath); envVars.put( LuaDebugConstants.ENV_VAR_KEY_DBGP_TRANSPORT, "debugger.transport.luasocket_sched"); //$NON-NLS-1$ } // create lua execution command StringBuilder cmd = new StringBuilder(); // create command to run cmd.append(luaSubSystem.getLuaCommand()); cmd.append(SshProcess.ARGUMENT_SEPARATOR); // insert interpreter args String interpreterArgs = configuration.getAttribute(LuaRemoteDebugConstant.INTERPRETER_ARGS, ""); // $NON-NLS-1$ if (!interpreterArgs.isEmpty()) { cmd.append(interpreterArgs); cmd.append(SshProcess.ARGUMENT_SEPARATOR); } // FIXME is there a cleaner way to control buffering ? // see: http://lua-users.org/lists/lua-l/2011-05/msg00549.html String bootstrapCode = "io.stdout:setvbuf('line');"; // $NON-NLS-1$ if (mode.equals(ILaunchManager.DEBUG_MODE)) { // load debugging libraries. The -l parameter cannot be used here because the debugger MUST // be the first module to be loaded bootstrapCode += " require('" + DEBGUGGER_MODULE + "')();"; // $NON-NLS-1$//$NON-NLS-2$ } cmd.append("-e"); // $NON-NLS-1$ cmd.append(SshProcess.ARGUMENT_SEPARATOR); cmd.append("\"" + bootstrapCode + "\""); // $NON-NLS-1$//$NON-NLS-2$ cmd.append(SshProcess.ARGUMENT_SEPARATOR); cmd.append(SshProcess.escapeShell(scriptSourcePathRelativePath.toPortableString())); cmd.append(SshProcess.ARGUMENT_SEPARATOR); // insert script args String scriptArgs = configuration.getAttribute(LuaRemoteDebugConstant.SCRIPT_ARGS, ""); // $NON-NLS-1$ if (!scriptArgs.isEmpty()) { cmd.append(scriptArgs); cmd.append(SshProcess.ARGUMENT_SEPARATOR); } submonitor.setWorkRemaining(1); // Create Process if (submonitor.isCanceled()) return; SshProcess process = new SshProcess(session, launch, remoteApplicationFolderPath, cmd.toString(), envVars); if (mode.equals(ILaunchManager.DEBUG_MODE)) { // Desactivate DBGP Stream redirection // TODO manage DBGP Stream redirection (so deactivate process redirection in debug mode) launch.setAttribute( DLTKDebugLaunchConstants.ATTR_DEBUG_CONSOLE, DLTKDebugLaunchConstants.FALSE); // manage break on first line if (configuration.getAttribute(LuaRemoteDebugConstant.BREAK_ON_FIRST_LINE, false)) { launch.setAttribute( DLTKDebugLaunchConstants.ATTR_BREAK_ON_FIRST_LINE, DLTKDebugLaunchConstants.TRUE); } // create runner LuaRemoteDebuggingEngineRunner debugingEngine = new LuaRemoteDebuggingEngineRunner(process, sessionID, remoteApplicationFolderPath); debugingEngine.run(new InterpreterConfig(), launch, submonitor.newChild(1)); launch.addProcess(process); } else { process.start(); launch.addProcess(process); } } finally { submonitor.done(); } }
/** * @param file * @param loader * @throws Exception */ public TransformationConfig(final IFile file, final URLClassLoader loader) throws Exception { this.file = file; delegate = DozerMapperConfiguration.loadConfig(new File(file.getLocationURI()), loader); }
/** * Provides visitor pattern due to implement <code>IResourceDeltaVisitor</code>. This method * must not be called by client because it is called by EclipseSensorPlugin instance. Note that * <code>true</code> is returned if the parameter of IResourceDelta instance has children. * <code>false</code> is returned when either Project is opened, closed, or file is saved * because no more traverse of children of the IResourceDelta instance is needed. * * @param delta IResourceDelta instance to contains delta resource. * @return true if the resource delta's children should be visited; false if they should be * skipped. * @throws CoreException if the visit fails for some reason. */ public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); int flag = delta.getFlags(); int kind = delta.getKind(); // If there is compilation problem with the current java file then send out the activity data. if ((flag & IResourceDelta.MARKERS) != 0 && EclipseSensor.this.buildErrorSensor != null) { EclipseSensor.this.buildErrorSensor.findBuildProblem(delta); } // :RESOLVED: 26 May 2003 // Note that the 147456 enumeration type is not listed in the IResourceDelta static filed. // However, its number is generated when Project is either opened or closed so that // it is checked in the logical condition. if (resource instanceof IProject && ((flag == IResourceDelta.OPEN) || (flag == 147456))) { IProject project = resource.getProject(); String projectName = project.getName(); URI projectResoruce = project.getFile(".project").getLocationURI(); Map<String, String> keyValueMap = new HashMap<String, String>(); keyValueMap.put(EclipseSensorConstants.UNIT_TYPE, "project"); keyValueMap.put(EclipseSensorConstants.UNIT_NAME, projectName); if (((IProject) resource).isOpen()) { keyValueMap.put(EclipseSensorConstants.SUBTYPE, "Open"); EclipseSensor.this.addDevEvent( EclipseSensorConstants.DEVEVENT_EDIT, projectResoruce, keyValueMap, projectResoruce.toString()); } else { keyValueMap.put(EclipseSensorConstants.SUBTYPE, "Close"); EclipseSensor.this.addDevEvent( EclipseSensorConstants.DEVEVENT_EDIT, projectResoruce, keyValueMap, projectResoruce.toString()); } return false; } if ((kind == IResourceDelta.CHANGED) && (flag == IResourceDelta.CONTENT) && resource instanceof IFile) { if (resource.getLocation().toString().endsWith(EclipseSensorConstants.JAVA_EXT)) { IFile file = (IFile) resource; Map<String, String> keyValueMap = new HashMap<String, String>(); keyValueMap.put("Language", "java"); keyValueMap.put(EclipseSensorConstants.UNIT_TYPE, EclipseSensorConstants.FILE); // Fully qualified class path String className = EclipseSensor.this.getFullyQualifedClassName(file); keyValueMap.put("Class-Name", className); // Size of the file in buffer String bufferSize = String.valueOf(activeBufferSize); keyValueMap.put("Current-Size", bufferSize); // Measure java file. JavaStatementMeter testCounter = measureJavaFile(file); testCounter = measureJavaFile(file); String methodCount = String.valueOf(testCounter.getNumOfMethods()); keyValueMap.put("Current-Methods", methodCount); String statementCount = String.valueOf(testCounter.getNumOfStatements()); keyValueMap.put("Current-Statements", statementCount); // Number of test method and assertion statements. if (testCounter.hasTest()) { String testMethodCount = String.valueOf(testCounter.getNumOfTestMethods()); keyValueMap.put("Current-Test-Methods", testMethodCount); String testAssertionCount = String.valueOf(testCounter.getNumOfTestAssertions()); keyValueMap.put("Current-Test-Assertions", testAssertionCount); } // EclipseSensor.this.eclipseSensorShell.doCommand("Activity", activityData); // Construct message to display on Eclipse status bar. URI fileResource = file.getLocationURI(); StringBuffer message = new StringBuffer("Save File"); message.append(" : ").append(EclipseSensor.this.extractFileName(fileResource)); keyValueMap.put(EclipseSensorConstants.SUBTYPE, "Save"); EclipseSensor.this.addDevEvent( EclipseSensorConstants.DEVEVENT_EDIT, fileResource, keyValueMap, message.toString()); } // Visit the children because it is not necessary for the saving file to be only one file. return true; } return true; // visit the children }
/** @throws Exception */ public void save() throws Exception { try (FileOutputStream stream = new FileOutputStream(new File(file.getLocationURI()))) { saveConfig(stream); project().refreshLocal(IResource.DEPTH_INFINITE, null); } }
@Override protected void setInput(IEditorInput input) { super.setInput(input); final ActivitiDiagramEditorInput adei = (ActivitiDiagramEditorInput) input; final IFile dataFile = adei.getDataFile(); final BpmnMemoryModel model = new BpmnMemoryModel(getDiagramTypeProvider().getFeatureProvider(), dataFile); ModelHandler.addModel(EcoreUtil.getURI(getDiagramTypeProvider().getDiagram()), model); String filePath = dataFile.getLocationURI().getPath(); File bpmnFile = new File(filePath); try { if (bpmnFile.exists() == false) { model.setBpmnModel(new BpmnModel()); model.addMainProcess(); bpmnFile.createNewFile(); dataFile.refreshLocal(IResource.DEPTH_INFINITE, null); } else { FileInputStream fileStream = new FileInputStream(bpmnFile); XMLInputFactory xif = XMLInputFactory.newInstance(); InputStreamReader in = new InputStreamReader(fileStream, "UTF-8"); XMLStreamReader xtr = xif.createXMLStreamReader(in); BpmnXMLConverter bpmnConverter = new BpmnXMLConverter(); bpmnConverter.setUserTaskFormTypes( PreferencesUtil.getStringArray(Preferences.ALFRESCO_FORMTYPES_USERTASK)); bpmnConverter.setStartEventFormTypes( PreferencesUtil.getStringArray(Preferences.ALFRESCO_FORMTYPES_STARTEVENT)); BpmnModel bpmnModel = null; try { bpmnModel = bpmnConverter.convertToBpmnModel(xtr); } catch (Exception e) { bpmnModel = new BpmnModel(); } model.setBpmnModel(bpmnModel); if (bpmnModel.getLocationMap().size() == 0) { BpmnAutoLayout layout = new BpmnAutoLayout(bpmnModel); layout.execute(); } BasicCommandStack basicCommandStack = (BasicCommandStack) getEditingDomain().getCommandStack(); if (input instanceof DiagramEditorInput) { basicCommandStack.execute( new RecordingCommand(getEditingDomain()) { @Override protected void doExecute() { importDiagram(model); } }); } basicCommandStack.saveIsDone(); basicCommandStack.flush(); } } catch (Exception e) { e.printStackTrace(); } }