Java Code Examples for org.eclipse.core.runtime.CoreException

The following are top voted examples for showing how to use org.eclipse.core.runtime.CoreException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: gemoc-studio   File: AbstractExampleWizard.java   View source code 6 votes vote down vote up
public boolean performFinish() {
	final Collection<ProjectDescriptor> projectDescriptors = getProjectDescriptors();
	
	WorkspaceJob job = new WorkspaceJob("Unzipping Projects") {
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			monitor.beginTask("Unzipping Projects", projectDescriptors.size());
			//System.out.println("Unzipping projects...");
			for ( ProjectDescriptor desc : projectDescriptors ) {
				unzipProject(desc, monitor);
				monitor.worked(1);
			}
			//System.out.println("Projects unzipped");
			return Status.OK_STATUS;
		}
	};
	job.setRule(ResourcesPlugin.getWorkspace().getRoot());
	job.schedule();
	return true;
}
 
Example 2
Project: gw4e.project   File: BuildPolicyManager.java   View source code 6 votes vote down vote up
/**
 * @param project
 * @param buildPolicyFile
 * @param graphFilePath
 * @param updatedGenerators
 * @throws IOException
 * @throws CoreException
 * @throws InterruptedException
 */
public static void update(IProject project, IFile buildPolicyFile, String graphFilePath,
		List<String> updatedGenerators) throws IOException, CoreException, InterruptedException {
	Job job = new WorkspaceJob("Updating policies") {
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			try {
				_update(project, buildPolicyFile, graphFilePath, updatedGenerators, monitor);
			} catch (FileNotFoundException e) {
				ResourceManager.logException(e);
			}
			return Status.OK_STATUS;
		}
	};
	job.setRule(buildPolicyFile.getProject());
	job.setUser(true);
	job.schedule();
}
 
Example 3
Project: incubator-netbeans   File: AbstractNbTaskWrapper.java   View source code 6 votes vote down vote up
@Override
public void taskDataUpdated (TaskDataListener.TaskDataEvent event) {
    if (event.getTask() == task) {
        if (event.getTaskData() != null && !event.getTaskData().isPartial()) {
            repositoryDataRef = new SoftReference<TaskData>(event.getTaskData());
        }
        if (event.getTaskDataUpdated()) {
            NbTaskDataModel m = model;
            if (m != null) {
                try {
                    m.refresh();
                } catch (CoreException ex) {
                    LOG.log(Level.INFO, null, ex);
                }
            }
            AbstractNbTaskWrapper.this.taskDataUpdated();
        }
    }
}
 
Example 4
Project: Hydrograph   File: PasteHandler.java   View source code 6 votes vote down vote up
private void createXmlFilesForPastedJobFiles(List<IFile> pastedFileList) {
	for (IFile file : pastedFileList) {
		try(InputStream inputStream=file.getContents()) {
			Container container = (Container) CanvasUtils.INSTANCE.fromXMLToObject(inputStream);
			IPath path = file.getFullPath().removeFileExtension().addFileExtension(XML);
			IFile xmlFile = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
			if(xmlFile.exists()){
				int userInput = showErrorMessage(xmlFile,xmlFile.getName()+" already exists.Do you want to replace it?");
				if (userInput == SWT.YES) {
					ConverterUtil.INSTANCE.convertToXML(container, true, xmlFile, null);
				} 
			}
			else {
				ConverterUtil.INSTANCE.convertToXML(container, true, xmlFile, null);
			}

		} catch (CoreException | InstantiationException | IllegalAccessException | InvocationTargetException
				| NoSuchMethodException | IOException exception) {
			logger.error("Error while generating xml files for pasted job files", exception);

		} 
	}
}
 
Example 5
Project: gemoc-studio-modeldebugging   File: DSLLaunchConfigurationTab.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse.debug.core.ILaunchConfiguration)
 */
public void initializeFrom(final ILaunchConfiguration configuration) {
	super.initializeFrom(configuration);
	disableUpdate = true;

	siriusResourceURIText.setText("");

	try {
		siriusResourceURIText.setText(configuration.getAttribute(
				AbstractDSLLaunchConfigurationDelegate.RESOURCE_URI, ""));
	} catch (CoreException e) {
		Activator.getDefault().error(e);
	}

	disableUpdate = false;
}
 
Example 6
Project: neoscada   File: LaunchShortcut.java   View source code 6 votes vote down vote up
private void addJvmOptions ( final ILaunchConfigurationWorkingCopy cfg, final Profile profile, final IContainer container ) throws CoreException
{
    final List<String> args = new LinkedList<> ();

    args.addAll ( profile.getJvmArguments () );

    for ( final SystemProperty p : profile.getProperty () )
    {
        addSystemProperty ( profile, args, p.getKey (), p.getValue (), p.isEval () );
    }

    for ( final Map.Entry<String, String> entry : getInitialProperties ().entrySet () )
    {
        addSystemProperty ( profile, args, entry.getKey (), entry.getValue (), false );
    }

    final IFile dataJson = container.getFile ( new Path ( "data.json" ) ); //$NON-NLS-1$
    if ( dataJson.exists () )
    {
        addJvmArg ( args, "org.eclipse.scada.ca.file.provisionJsonUrl", escapeArgValue ( dataJson.getLocation ().toFile ().toURI ().toString () ) ); //$NON-NLS-1$
    }

    cfg.setAttribute ( IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, StringHelper.join ( args, "\n" ) );
    cfg.setAttribute ( IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, StringHelper.join ( profile.getArguments (), "\n" ) );
}
 
Example 7
Project: ec4e   File: EditorConfigCodeLensProvider.java   View source code 6 votes vote down vote up
@Override
protected ICodeLens resolveSyncCodeLens(ICodeLensContext context, ICodeLens codeLens, IProgressMonitor monitor) {
	ITextEditor textEditor = ((IEditorCodeLensContext) context).getTextEditor();
	IFile file = EditorUtils.getFile(textEditor);
	if (file == null) {
		return null;
	}
	EditorConfigCodeLens cl = (EditorConfigCodeLens) codeLens;
	CountSectionPatternVisitor visitor = new CountSectionPatternVisitor(cl.getSection());
	try {
		file.getParent().accept(visitor, IResource.NONE);
		cl.update(visitor.getNbFiles() + " files match");
	} catch (CoreException e) {
		cl.update(e.getMessage());
	}
	return cl;
}
 
Example 8
Project: neoscada   File: ServerHostImpl.java   View source code 6 votes vote down vote up
public Collection<? extends ServerDescriptor> startServer ( final URI exporterFileUri, final String locationLabel ) throws CoreException
{
    final ResourceSetImpl resourceSet = new ResourceSetImpl ();

    resourceSet.getResourceFactoryRegistry ().getExtensionToFactoryMap ().put ( "*", new ExporterResourceFactoryImpl () );

    final Resource resource = resourceSet.createResource ( exporterFileUri );
    try
    {
        resource.load ( null );
    }
    catch ( final IOException e )
    {
        throw new CoreException ( StatusHelper.convertStatus ( HivesPlugin.PLUGIN_ID, "Failed to load configuration", e ) );
    }

    final DocumentRoot root = (DocumentRoot)EcoreUtil.getObjectByType ( resource.getContents (), ExporterPackage.Literals.DOCUMENT_ROOT );
    if ( root == null )
    {
        throw new CoreException ( new Status ( IStatus.ERROR, HivesPlugin.PLUGIN_ID, "Failed to locate exporter configuration in: " + exporterFileUri ) );
    }
    return startServer ( root, locationLabel );
}
 
Example 9
Project: dacapobench   File: FullSourceWorkspaceTests.java   View source code 6 votes vote down vote up
/**
 * Returns all compilation units of a given project.
 * @param javaProject Project to collect units
 * @return List of org.eclipse.jdt.core.ICompilationUnit
 */
protected List getProjectCompilationUnits(IJavaProject javaProject) throws CoreException {
  IPackageFragmentRoot[] fragmentRoots = javaProject.getPackageFragmentRoots();
  int length = fragmentRoots.length;
  List allUnits = new ArrayList();
  for (int i = 0; i < length; i++) {
    if (fragmentRoots[i] instanceof JarPackageFragmentRoot)
      continue;
    IJavaElement[] packages = fragmentRoots[i].getChildren();
    for (int k = 0; k < packages.length; k++) {
      IPackageFragment pack = (IPackageFragment) packages[k];
      ICompilationUnit[] units = pack.getCompilationUnits();
      for (int u = 0; u < units.length; u++) {
        allUnits.add(units[u]);
      }
    }
  }
  return allUnits;
}
 
Example 10
Project: neoscada   File: AbstractPreferencesDiscoverer.java   View source code 6 votes vote down vote up
@Override
public void add ( final ConnectionDescriptor connectionInformation ) throws CoreException
{
    try
    {
        if ( addConnection ( connectionInformation ) )
        {
            performAdd ( connectionInformation );
        }
    }
    catch ( final Exception e )
    {
        throw new CoreException ( StatusHelper.convertStatus ( Activator.PLUGIN_ID, e ) );
    }

}
 
Example 11
Project: gw4e.project   File: GW4ENature.java   View source code 6 votes vote down vote up
/**
 * Set the GW4E Nature to the passed project
 * 
 * @param project
 * @return
 * @throws CoreException
 */
public static IStatus setGW4ENature(IProject project) throws CoreException {
	IProjectDescription description = project.getDescription();
	String[] natures = description.getNatureIds();
	String[] newNatures = new String[natures.length + 1];
	System.arraycopy(natures, 0, newNatures, 0, natures.length);

	// add our id
	newNatures[natures.length] = GW4ENature.NATURE_ID;

	// validate the natures
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IStatus status = workspace.validateNatureSet(newNatures);

	if (status.getCode() == IStatus.OK) {
		description.setNatureIds(newNatures);
		project.setDescription(description, null);
	}
	return status;
}
 
Example 12
Project: n4js   File: IndexableFilesDiscoveryUtil.java   View source code 6 votes vote down vote up
/**
 * Scans workspace for files that may end up in XtextIndex when given location is processed by the builder. This is
 * naive filtering based on {@link IndexableFilesDiscoveryUtil#INDEXABLE_FILTERS file extensions}. Symlinks are not
 * followed.
 *
 * @param workspace
 *            to scan
 * @return collection of indexable locations
 * @throws CoreException
 *             if scanning of the workspace is not possible.
 */
public static Collection<String> collectIndexableFiles(IWorkspace workspace) throws CoreException {
	Set<String> result = new HashSet<>();
	workspace.getRoot().accept(new IResourceVisitor() {

		@Override
		public boolean visit(IResource resource) throws CoreException {
			if (resource.getType() == IResource.FILE) {
				IFile file = (IFile) resource;
				if (INDEXABLE_FILTERS.contains(file.getFileExtension().toLowerCase())) {
					result.add(file.getFullPath().toString());
				}
			}
			return true;
		}
	});
	return result;
}
 
Example 13
Project: incubator-netbeans   File: BugzillaExecutor.java   View source code 6 votes vote down vote up
static ExceptionHandler createHandler(CoreException ce, BugzillaExecutor executor, BugzillaRepository repository, ValidateCommand validateCommand, boolean forRexecute) {
    String errormsg = getLoginError(repository, validateCommand, ce);
    if(errormsg != null) {
        return new LoginHandler(ce, errormsg, executor, repository);
    }
    errormsg = getKenaiRedirectError(ce);
    if(errormsg != null) {
        return new LoginHandler(ce, errormsg, executor, repository);
    }
    errormsg = getNotFoundError(ce);
    if(errormsg != null) {
        return new NotFoundHandler(ce, errormsg, executor, repository);
    }
    errormsg = getMidAirColisionError(ce);
    if(errormsg != null) {
        if(forRexecute) { 
            return new MidAirHandler(ce, errormsg, executor, repository);
        } else {
            errormsg = MessageFormat.format(errormsg, repository.getDisplayName());
            return new DefaultHandler(ce, errormsg, executor, repository);
        }
    }
    return new DefaultHandler(ce, null, executor, repository);
}
 
Example 14
Project: VerveineC-Cpp   File: FileUtil.java   View source code 6 votes vote down vote up
private static void mkdirs(IFolder destPath) {
	IContainer parent = destPath.getParent(); 
	if (! parent.exists()) {
		if (parent instanceof IFolder) {
			mkdirs((IFolder) parent);
		}
		else if (parent instanceof IProject) {
			mkdirs( ((IProject)parent).getFolder(".") );
		}
	}
	try {
		destPath.create(/*force*/true, /*local*/true, Constants.NULL_PROGRESS_MONITOR);
	} catch (CoreException e) {
		e.printStackTrace();
	}
}
 
Example 15
Project: EclipseMinifyBuilder   File: PrefsAccess.java   View source code 6 votes vote down vote up
/**
 * Remove a resource (i.e. all its properties) from the builder's preferences.
 * 
 * @param prefs the preferences
 * @param resource the resource
 * @throws BackingStoreException
 */
public static void removeResource(Preferences prefs, IResource resource) 
		throws CoreException {
	try {
		String[] keys = prefs.keys();
		for (String key: keys) {
			if (key.endsWith("//" + resource.getProjectRelativePath().toPortableString())) {
				prefs.remove(key);
			}
		}
		prefs.flush();
	} catch (BackingStoreException e) {
		throw new CoreException(new Status(
				IStatus.ERROR, MinifyBuilder.BUILDER_ID, e.getMessage(), e));
	}
}
 
Example 16
Project: gemoc-studio-modeldebugging   File: AbstractDSLLaunchConfigurationDelegate.java   View source code 6 votes vote down vote up
/**
 * Gets the first {@link EObject instruction}.
 * 
 * @param configuration
 *            the {@link ILaunchConfiguration}
 * @return the first {@link EObject instruction}
 */
protected EObject getFirstInstruction(ILaunchConfiguration configuration) {
EObject res = null;
final ResourceSet rs = getResourceSet();

try {
	rs.getResource(URI.createPlatformResourceURI(configuration.getAttribute(RESOURCE_URI, ""),
		true), true);
	res = rs.getEObject(URI.createURI(configuration.getAttribute(FIRST_INSTRUCTION_URI, ""),
		true), true);
} catch (CoreException e) {
	Activator.getDefault().error(e);
}

return res;
}
 
Example 17
Project: EclipseMinifyBuilder   File: MinifyNature.java   View source code 6 votes vote down vote up
@Override
public void configure() throws CoreException {
	IProjectDescription desc = project.getDescription();
	ICommand[] commands = desc.getBuildSpec();

	for (int i = 0; i < commands.length; ++i) {
		if (commands[i].getBuilderName().equals(MinifyBuilder.BUILDER_ID)) {
			return;
		}
	}

	ICommand[] newCommands = new ICommand[commands.length + 1];
	System.arraycopy(commands, 0, newCommands, 0, commands.length);
	ICommand command = desc.newCommand();
	command.setBuilderName(MinifyBuilder.BUILDER_ID);
	newCommands[newCommands.length - 1] = command;
	desc.setBuildSpec(newCommands);
	project.setDescription(desc, null);
}
 
Example 18
Project: incubator-netbeans   File: BugzillaRepository.java   View source code 6 votes vote down vote up
/**
 * If oldUrl is not null, gets the repository for the oldUrl and rewrites it
 * to the new url.
 */
private static TaskRepository setupTaskRepository (String name, String oldUrl, String url, String user,
        char[] password, String httpUser, char[] httpPassword,
        boolean shortLoginEnabled) {
    TaskRepository repository;
    if (oldUrl == null) {
        repository = MylynSupport.getInstance().getTaskRepository(Bugzilla.getInstance().getRepositoryConnector(), url);
    } else {
        repository = MylynSupport.getInstance().getTaskRepository(Bugzilla.getInstance().getRepositoryConnector(), oldUrl);
        try {
            MylynSupport.getInstance().setRepositoryUrl(repository, url);
        } catch (CoreException ex) {
            Bugzilla.LOG.log(Level.WARNING, null, ex);
        }
    }
    setupProperties(repository, name, user, password, httpUser, httpPassword, shortLoginEnabled); 
    return repository;
}
 
Example 19
Project: eclipse-bash-editor   File: AbstractMarkerHelper.java   View source code 6 votes vote down vote up
private void createMarker(IResource resource, String message, int lineNumber, String markerType, int severity,
		int charStart, int charEnd) throws CoreException {
	if (lineNumber <= 0)
		lineNumber = 1;
	IMarker marker = findMarker(resource, message, lineNumber, markerType);
	if (marker == null) {
		HashMap<String, Object> map = new HashMap<>();
		map.put(IMarker.SEVERITY, new Integer(severity));
		map.put(IMarker.LOCATION, resource.getFullPath().toOSString());
		map.put(IMarker.MESSAGE, message);
		MarkerUtilities.setLineNumber(map, lineNumber);
		MarkerUtilities.setMessage(map, message);
		if (charStart != -1) {
			MarkerUtilities.setCharStart(map, charStart);
			MarkerUtilities.setCharEnd(map, charEnd);
		}
		internalCreateMarker(resource, map, markerType);
	}
}
 
Example 20
Project: gw4e.project   File: GW4ELaunchConfigurationTab.java   View source code 6 votes vote down vote up
private ModelData[] getModels(ILaunchConfiguration config) throws CoreException {
	List<ModelData> temp = new ArrayList<ModelData>();
	String paths = config.getAttribute(CONFIG_GRAPH_MODEL_PATHS, "");
	 
	if (paths == null || paths.trim().length() == 0)
		return new ModelData[0];
	StringTokenizer st = new StringTokenizer(paths, ";");
	st.nextToken(); // the main model path
	st.nextToken(); // main model : Always "1"
	st.nextToken(); // the main path generator
	while (st.hasMoreTokens()) {
		String path = st.nextToken();
		IFile file = (IFile) ResourceManager
				.getResource(new Path(path).toString());
		if (file==null) continue;
		ModelData data = new ModelData(file);
		boolean selected = st.nextToken().equalsIgnoreCase("1");
		String pathGenerator = st.nextToken();
		data.setSelected(selected);
		data.setSelectedPolicy(pathGenerator);
		temp.add(data);
	}
	ModelData[] ret = new ModelData[temp.size()];
	temp.toArray(ret);
	return ret;
}
 
Example 21
Project: EclipseMinifyBuilder   File: MinifyNature.java   View source code 6 votes vote down vote up
@Override
public void deconfigure() throws CoreException {
	IProjectDescription description = getProject().getDescription();
	ICommand[] commands = description.getBuildSpec();
	for (int i = 0; i < commands.length; ++i) {
		if (commands[i].getBuilderName().equals(MinifyBuilder.BUILDER_ID)) {
			ICommand[] newCommands = new ICommand[commands.length - 1];
			System.arraycopy(commands, 0, newCommands, 0, i);
			System.arraycopy(commands, i + 1, newCommands, i,
					commands.length - i - 1);
			description.setBuildSpec(newCommands);
			project.setDescription(description, null);
			return;
		}
	}
}
 
Example 22
Project: Hydrograph   File: ExternalSchemaUpdaterHandler.java   View source code 6 votes vote down vote up
/**
 * This method update schema of component. for all selectedJobFiles.
 */
private void updatedExternalSchema(List<File> selectedJobFiles) {

	LOGGER.debug("Updating external schema");
	for (File file : selectedJobFiles) {

		Container container = null;
		try {
			container = (Container) CanvasUtils.INSTANCE.fromXMLToObject(file.getContents());
		} catch (CoreException e) {
			LOGGER.error("Error while converting job file to container.");
		}
		if (container != null) {
			List<Component> externalSchemaComps = getExternalSchemaComponent(container.getUIComponentList());
			updateExternalSchema(container, externalSchemaComps, file);
		}
	}
}
 
Example 23
Project: incubator-netbeans   File: HgHookTest.java   View source code 6 votes vote down vote up
public void testAfterCommitLinkResolve() throws MalformedURLException, CoreException, IOException, InterruptedException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    HgHookImpl hook = getHook();

    VCSHooksConfig.getInstance(HookType.HG).setAfterCommit(true);
    VCSHooksConfig.getInstance(HookType.HG).setLink(true);
    VCSHooksConfig.getInstance(HookType.HG).setResolve(true);

    // give some time to NbPreferences to get back from knees
    // fix for #198665 seems to brought regression and sync issues
    Thread.sleep(2000);

    String msg = "msg";
    HgHookContext ctx = getContext(msg);
    HookPanel panel = getPanel(hook, ctx); // initiate panel

    hook.afterCommit(ctx);
    assertNotNull(HookIssue.getInstance().comment);
    assertNotSame(-1, HookIssue.getInstance().comment.indexOf(msg));
    assertTrue(HookIssue.getInstance().closed);
}
 
Example 24
Project: neoscada   File: AEViewSection.java   View source code 6 votes vote down vote up
protected IPluginElement createAlarmsMenu ( final IPluginModelFactory factory, final IPluginBase plugin ) throws CoreException
{
    final IPluginExtension menuExt = createExtension ( "org.eclipse.ui.menus", false ); //$NON-NLS-1$
    plugin.add ( menuExt );

    final IPluginElement menuEle = factory.createElement ( menuExt );
    menuExt.add ( menuEle );
    menuEle.setName ( "menuContribution" ); //$NON-NLS-1$
    menuEle.setAttribute ( "locationURI", "menu:org.eclipse.ui.main.menu?after=file" ); //$NON-NLS-1$ //$NON-NLS-2$

    final IPluginElement menu = factory.createElement ( menuEle );
    menuEle.add ( menu );
    menu.setName ( "menu" ); //$NON-NLS-1$
    menu.setAttribute ( "label", "Alarms" ); //$NON-NLS-1$

    return menu;
}
 
Example 25
Project: n4js   File: AvoidRefreshDocumentProvider.java   View source code 5 votes vote down vote up
@Override
protected void refreshFile(IFile file, IProgressMonitor monitor) throws CoreException {
	// Note that file.isSynchronized does not require a scheduling rule and thus helps to identify a no-op attempt
	// to refresh the file. The no-op will otherwise be blocked by a running build or cancel a running build
	if (!file.isSynchronized(IResource.DEPTH_ZERO)) {
		super.refreshFile(file, monitor);
	}
}
 
Example 26
Project: neoscada   File: ClientTemplate.java   View source code 5 votes vote down vote up
private IPluginElement addMenuCommand ( final IPluginModelFactory factory, final IPluginElement m, final String commandId, final String label ) throws CoreException
{
    final IPluginElement c = addElement ( factory, m, "command", null ); //$NON-NLS-1$
    c.setAttribute ( "commandId", commandId ); //$NON-NLS-1$
    if ( label != null )
    {
        c.setAttribute ( "label", label ); //$NON-NLS-1$
    }
    return c;
}
 
Example 27
Project: pgcodekeeper   File: SQLEditor.java   View source code 5 votes vote down vote up
/**
 * Use only for non-project parsers
 * @param {@link IFileEditorInput} {@link IResource} or null
 * @return true if refresh was triggered successfully
 */
private boolean refreshParser(PgDbParser parser, IResource res, IProgressMonitor monitor)
        throws InterruptedException, IOException, CoreException {
    if (res instanceof IFile && res.getProject().hasNature(NATURE.ID)) {
        parser.getObjFromProjFile((IFile) res, monitor);
        return true;
    }

    IEditorInput in = getEditorInput();
    if (in instanceof IURIEditorInput) {
        IURIEditorInput uri = (IURIEditorInput) in;
        IDocument document = getDocumentProvider().getDocument(getEditorInput());
        InputStream stream = new ByteArrayInputStream(document.get().getBytes(StandardCharsets.UTF_8));
        parser.fillRefsFromInputStream(stream, Paths.get(uri.getURI()).toString(), monitor);
        return true;
    }
    return false;
}
 
Example 28
Project: gw4e.project   File: SourceHelper.java   View source code 5 votes vote down vote up
public static void updatePathGenerator (IFile ifile, String oldPathGenerator,String newPathGenerator) throws CoreException {
	ICompilationUnit cu = JavaCore.createCompilationUnitFrom(ifile);
	 
	ICompilationUnit workingCopy = cu.getWorkingCopy(new NullProgressMonitor());
	
	IBuffer buffer = ((IOpenable)workingCopy).getBuffer();
	String source = buffer.getContents();
	int start = source.indexOf(oldPathGenerator);
	buffer.replace(start, oldPathGenerator.length(), newPathGenerator);
	workingCopy.reconcile(ICompilationUnit.NO_AST, false, workingCopy.getOwner(), new NullProgressMonitor());
    workingCopy.commitWorkingCopy(true, null);
    workingCopy.discardWorkingCopy();
    
    ifile.touch(new NullProgressMonitor ());
}
 
Example 29
Project: neoscada   File: LaunchShortcut.java   View source code 5 votes vote down vote up
private ILaunchConfiguration[] findConfigurationsAsArray ( final IResource resource )
{
    try
    {
        return findConfigurations ( resource ).toArray ( new ILaunchConfiguration[0] );
    }
    catch ( CoreException | IOException e )
    {
        return null;
    }
}
 
Example 30
Project: visuflow-plugin   File: JimpleBreakpointManager.java   View source code 5 votes vote down vote up
private void loadBreakpoints(IResource project) {
	try {
		IMarker[] markers = project.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE);
		List<IMarker> methodBreakpoints = filterJavaMethodBreakpoints(markers);
		List<IMarker> jimpleChildBreakpoints = filterJimpleChildBreakpoints(methodBreakpoints);
		for (IMarker marker : jimpleChildBreakpoints) {
			String unitFqn = (String) marker.getAttribute("Jimple.unit.fqn");
			WorkspaceJob createBreakpoint = new WorkspaceJob("Create Jimple breakpoint") {
				@Override
				public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
					JimpleBreakpoint jimpleBreakpoint = getJimpleBreakpoint(unitFqn);
					if(jimpleBreakpoint == null) {
						IMarker jimpleMarker = createJimpleMarker(marker);
						jimpleBreakpoint = createBreakpointWithoutJavaBreakpoints(jimpleMarker);
						addBreakpoint(jimpleBreakpoint);
					}

					IBreakpoint javaBreakpoint = DebugPlugin.getDefault().getBreakpointManager().getBreakpoint(marker);
					jimpleBreakpoint.addJavaBreakpoint(javaBreakpoint);
					return Status.OK_STATUS;
				}
			};
			createBreakpoint.schedule();
		}
	} catch (CoreException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 31
Project: Hydrograph   File: PasteHandler.java   View source code 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	List<IFile> jobFiles = new ArrayList<>();
	List<IFile> pastedFileList = new ArrayList<>();
	IWorkbenchPart part = HandlerUtil.getActivePart(event);
	if(part instanceof CommonNavigator){
		PasteAction action = new PasteAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart().getSite());
		action.run();
		IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot();
		IProject project = workSpaceRoot.getProject(JobCopyParticipant.getCopyToPath().split("/")[1]);
		IFolder jobFolder = project.getFolder(
				JobCopyParticipant.getCopyToPath().substring(JobCopyParticipant.getCopyToPath().indexOf('/', 2)));
		IFolder paramFolder = project.getFolder(PARAMETER_FOLDER_NAME);
		try {
			createCurrentJobFileList(jobFolder, jobFiles);
			pastedFileList=getPastedFileList(jobFiles);
			generateUniqueJobIdForPastedFiles(pastedFileList);
			createXmlFilesForPastedJobFiles(pastedFileList);
			List<String> copiedPropertiesList = getCopiedPropertiesList();
			createPropertiesFilesForPastedFiles(paramFolder, pastedFileList, copiedPropertiesList);
			JobCopyParticipant.cleanUpStaticResourcesAfterPasteOperation();

		} catch (CoreException  coreException) {
			logger.warn("Error while copy paste jobFiles",coreException.getMessage() );
		}
		
	}
	
	else if(part instanceof ELTGraphicalEditor){
		IEditorPart editor = HandlerUtil.getActiveEditor(event);
		((ELTGraphicalEditor)editor).pasteSelection();
	}
	
	return null;
}
 
Example 32
Project: Equella   File: NewRegistryWizard.java   View source code 5 votes vote down vote up
@Override
protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException
{
	fSecondPage.performFinish(monitor);
	IProject project = fSecondPage.getJavaProject().getProject();
	IProjectDescription description = project.getDescription();
	JPFJarNature.addNature(description);
	project.setDescription(description, SubMonitor.convert(monitor, "Add JPF Registry Nature", 1));
}
 
Example 33
Project: VerveineC-Cpp   File: VerveineCParser.java   View source code 5 votes vote down vote up
private void configWorkspace(IWorkspace workspace) {
	IWorkspaceDescription workspaceDesc = workspace.getDescription();
	workspaceDesc.setAutoBuilding(false); // we do not want the workspace to rebuild the project every time a new resource is added
	try {
		workspace.setDescription(workspaceDesc);
	} catch (CoreException exc) {
		Activator.log(IStatus.ERROR, "Error trying to set workspace description: " + exc.getMessage());
	}

}
 
Example 34
Project: Tarski   File: MarkUtilities.java   View source code 5 votes vote down vote up
/**
 * Sets the MarkElement.getTargetAttributeName() named attribute of marker with given parameter
 * targetList
 *
 * @param iMarker
 * @param sourceList
 */
public static void setTargetList(final IMarker iMarker, final ArrayList<MarkElement> targetList) {
  try {
    iMarker.setAttribute(MarkUtilities.getTargetAttributeName(),
        Serialization.getInstance().toString(targetList));
  } catch (CoreException | IOException e) {
    e.printStackTrace();
  }
}
 
Example 35
Project: visuflow-plugin   File: StackExaminer.java   View source code 5 votes vote down vote up
public static VFUnit getUnitFromStack(IJavaThread thread) throws CoreException {
	String fqn = getUnitFromTopStackFrame(thread);
	if(fqn == null) {
		throw new RuntimeException("No unit found on top stackframe");
	} else {
		DataModel model = ServiceUtil.getService(DataModel.class);
		VFUnit unit = model.getVFUnit(fqn);
		if(unit == null) {
			throw new RuntimeException("Unit not found in jimple model ["+fqn+"]");
		}
		return unit;
	}
}
 
Example 36
Project: incubator-netbeans   File: PerformQueryCommand.java   View source code 5 votes vote down vote up
@Override
public void execute() throws CoreException {
    
    Logger log = Logger.getLogger(this.getClass().getName());
    if(log.isLoggable(Level.FINE)) {
        Map<String, String> attrs = query.getAttributes();
        log.log(
            Level.FINE, 
            "executing PerformQueryCommand for query {0} on repository {1} with url \n\t{2} and parameters \n\t{3}", // NOI18N
            new Object[] {query.getSummary(), taskRepository.getUrl(), query.getUrl(), attrs != null ? attrs : null});
    }
    
    status = repositoryConnector.performQuery(taskRepository, query, collector, null, new NullProgressMonitor());
}
 
Example 37
Project: dacapobench   File: FullSourceWorkspaceCompleteSearchTests.java   View source code 5 votes vote down vote up
protected void search(String patternString, int searchFor, int limitTo, JavaSearchResultCollector resultCollector) throws CoreException {
  int matchMode = patternString.indexOf('*') != -1 || patternString.indexOf('?') != -1 ? SearchPattern.R_PATTERN_MATCH : SearchPattern.R_EXACT_MATCH;
  SearchPattern pattern = SearchPattern.createPattern(patternString, searchFor, limitTo, matchMode | SearchPattern.R_CASE_SENSITIVE);

  IJavaSearchScope scope = org.eclipse.jdt.core.search.SearchEngine.createJavaSearchScope(ALL_PROJECTS, org.eclipse.jdt.core.search.IJavaSearchScope.SOURCES);
  new SearchEngine().search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, resultCollector, null);
}
 
Example 38
Project: n4js   File: N4IDEXpectCompareEditorInput.java   View source code 5 votes vote down vote up
@Override
public void setContent(byte[] newContent) {
	ByteArrayInputStream inputStream = new ByteArrayInputStream(newContent);
	try {
		file.setContents(inputStream, true, true, new NullProgressMonitor());
	} catch (CoreException e) {
		LOG.error(e);
	}
}
 
Example 39
Project: pgcodekeeper   File: ProjectEditorDiffer.java   View source code 5 votes vote down vote up
private IEditorInput createProjectScriptFile(String content, String filename) throws CoreException, IOException {
    Log.log(Log.LOG_INFO, "Creating file " + filename); //$NON-NLS-1$
    IProject iProject = proj.getProject();
    IFolder folder = iProject.getFolder(PROJ_PATH.MIGRATION_DIR);
    if (!folder.exists()){
        folder.create(IResource.NONE, true, null);
    }
    IFile file = folder.getFile(filename + ".sql"); //$NON-NLS-1$
    InputStream source = new ByteArrayInputStream(content.getBytes(proj.getProjectCharset()));
    file.create(source, IResource.NONE, null);
    return new FileEditorInput(iProject.getFile(file.getProjectRelativePath()));
}
 
Example 40
Project: neoscada   File: DefaultFileResourceDiscoverer.java   View source code 5 votes vote down vote up
@Override
public void remove ( final ConnectionDescriptor connectionInformation ) throws CoreException
{
    if ( removeConnection ( connectionInformation ) )
    {
        store ();
    }
}