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

The following examples show how to use org.eclipse.core.runtime.CoreException. These examples are extracted from open source projects.
Example 1
Project: xtext-eclipse   File: AbstractProjectCreator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected IFile getModelFile(IProject project) throws CoreException {
	IFolder srcFolder = project.getFolder(getModelFolderName());
	final String expectedExtension = getPrimaryModelFileExtension();
	final IFile[] result = new IFile[1];
	srcFolder.accept(new IResourceVisitor() {
		@Override
		public boolean visit(IResource resource) throws CoreException {
			if (IResource.FILE == resource.getType() && expectedExtension.equals(resource.getFileExtension())) {
				result[0] = (IFile) resource;
				return false;
			}
			return IResource.FOLDER == resource.getType();
		}
	});
	return result[0];
}
 
Example 2
Project: eclipse.jdt.ls   File: RefactoringScopeFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static void addRelatedReferencing(IJavaProject focus, Set<IJavaProject> projects) throws CoreException {
	IProject[] referencingProjects = focus.getProject().getReferencingProjects();
	for (int i = 0; i < referencingProjects.length; i++) {
		IJavaProject candidate = JavaCore.create(referencingProjects[i]);
		if (candidate == null || projects.contains(candidate) || !candidate.exists()) {
			continue; // break cycle
		}
		IClasspathEntry entry = getReferencingClassPathEntry(candidate, focus);
		if (entry != null) {
			projects.add(candidate);
			if (entry.isExported()) {
				addRelatedReferencing(candidate, projects);
				addRelatedReferenced(candidate, projects);
			}
		}
	}
}
 
Example 3
Project: tesb-studio-se   File: CreateRouteAsOSGIPomTest.java    License: Apache License 2.0 6 votes vote down vote up
private void compareGeneratedFileWithReference(IProject genProject, String refProjectPath, String filepath)
        throws IOException, CoreException {
    File genFile = genProject.getFile(filepath).getLocation().toFile();

    Bundle b = Platform.getBundle("org.talend.esb.camel.designer.test");
    assertNotNull("Test  bundle cannot be loaded.", b);

    String path = FileLocator.toFileURL(b.getEntry("resources/" + refProjectPath + filepath)).getFile();
    File refFile = Paths.get(path).normalize().toFile();

    assertTrue("Generated '" + genFile + "' file does not exists.", genFile.exists());
    assertTrue("Reference '" + refFile + "' file does not exists.", refFile.exists());

    assertTrue("Generated '" + genFile + "' file is not a file.", genFile.isFile());
    assertTrue("Reference '" + refFile + "' file is not a file.", refFile.isFile());

    String expectedContent = FileUtils.readFileToString(refFile);
    String generatedContent = FileUtils.readFileToString(genFile);
    assertEquals("Content of " + filepath + " are not equals.", expectedContent, generatedContent);
}
 
Example 4
Project: neoscada   File: LaunchShortcut.java    License: Eclipse Public License 1.0 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 5
Project: Eclipse-Postfix-Code-Completion   File: ASTRewriteAnalyzer.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public boolean visit(WhileStatement node) {
	if (!hasChildrenChanges(node)) {
		return doVisitUnchangedChildren(node);
	}

	int pos= rewriteRequiredNode(node, WhileStatement.EXPRESSION_PROPERTY);

	try {
		if (isChanged(node, WhileStatement.BODY_PROPERTY)) {
			int startOffset= getScanner().getTokenEndOffset(TerminalTokens.TokenNameRPAREN, pos);
			rewriteBodyNode(node, WhileStatement.BODY_PROPERTY, startOffset, -1, getIndent(node.getStartPosition()), this.formatter.WHILE_BLOCK); // body
		} else {
			voidVisit(node, WhileStatement.BODY_PROPERTY);
		}
	} catch (CoreException e) {
		handleException(e);
	}
	return false;
}
 
Example 6
Project: APICloud-Studio   File: SVNCompareRevisionsInput.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
    * Runs the compare operation and returns the compare result.
    */
protected Object prepareInput(IProgressMonitor monitor){
	initLabels();
	DiffNode diffRoot = new DiffNode(Differencer.NO_CHANGE);
	String localCharset = Utilities.getCharset(resource);
	for (int i = 0; i < logEntries.length; i++) {		
		ITypedElement left = new TypedBufferedContent(resource);
		ResourceRevisionNode right = new ResourceRevisionNode(logEntries[i]);
		try {
			right.setCharset(localCharset);
		} catch (CoreException e) {
		}
		diffRoot.add(new VersionCompareDiffNode(left, right));
	}
	return diffRoot;		
}
 
Example 7
Project: xds-ide   File: Sdk.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void checkDebuggerVersion() {
	if (isDebuggerSupportsIdeIntegration == null) {
		try {
			String stdOut = ProcessUtils.launchProcessAndCaptureStdout(new String[]{getDebuggerExecutablePath(), "-F"}, new File("."), new String[0]); //$NON-NLS-1$ //$NON-NLS-2$
			Matcher matcher = debuggerExecutableSignature.matcher(stdOut);
			isDebuggerSupportsIdeIntegration = matcher.matches();
			
			if (isDebuggerSupportsIdeIntegration) {
				protocolVersion = version(matcher, 0);
				debuggerVersion = version(matcher, 3);
			}
		} catch (CoreException e) {
			LogHelper.logError(e);
			isDebuggerSupportsIdeIntegration = false;
		}
		
	}
}
 
Example 8
Project: eclipse.jdt.ls   File: GradleProjectImporter.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean applies(IProgressMonitor monitor) throws CoreException {
	if (rootFolder == null) {
		return false;
	}
	Preferences preferences = getPreferences();
	if (!preferences.isImportGradleEnabled()) {
		return false;
	}
	if (directories == null) {
		BasicFileDetector gradleDetector = new BasicFileDetector(rootFolder.toPath(), BUILD_GRADLE_DESCRIPTOR)
				.includeNested(false)
				.addExclusions("**/build")//default gradle build dir
				.addExclusions("**/bin");
		directories = gradleDetector.scan(monitor);
	}
	return !directories.isEmpty();
}
 
Example 9
Project: uima-uimaj   File: DocumentUimaImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the content. The XCAS {@link InputStream} gets parsed.
 *
 * @param casFile the new content
 * @throws CoreException the core exception
 */
private void setContent(IFile casFile) throws CoreException {

  IPreferenceStore store = CasEditorPlugin.getDefault().getPreferenceStore();
  boolean withPartialTypesystem = store
          .getBoolean(AnnotationEditorPreferenceConstants.ANNOTATION_EDITOR_PARTIAL_TYPESYSTEM);

  URI uri = casFile.getLocationURI();
  if (casFile.isLinked()) {
    uri = casFile.getRawLocationURI();
  }
  File file = EFS.getStore(uri).toLocalFile(0, new NullProgressMonitor());
  try {
    format = CasIOUtils.load(file.toURI().toURL(), null, mCAS, withPartialTypesystem);
  } catch (IOException e) {
    throwCoreException(e);
  }

}
 
Example 10
Project: n4js   File: OpenTypeSelectionDialog.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void fillContentProvider(final AbstractContentProvider contentProvider, final ItemsFilter itemsFilter,
		final IProgressMonitor monitor) throws CoreException {

	monitor.beginTask("Searching for N4JS types...", UNKNOWN);

	final Iterable<IEObjectDescription> types = filter(indexSupplier.get().getExportedObjects(),
			desc -> searchKind.matches(desc.getEClass()));

	monitor.beginTask("Searching for N4JS types...", size(types));
	types.forEach(desc -> {
		contentProvider.add(desc, itemsFilter);
		monitor.worked(1);
	});

	monitor.done();
}
 
Example 11
Project: eclipse-cs   File: ConfigureDeconfigureNatureJob.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Helper method to disable the given nature for the project.
 * 
 * @throws CoreException
 *           an error while removing the nature occured
 */
private void disableNature() throws CoreException {

  IProjectDescription desc = mProject.getDescription();
  String[] natures = desc.getNatureIds();

  // remove given nature from the array
  List<String> newNaturesList = new ArrayList<>();
  for (int i = 0; i < natures.length; i++) {
    if (!mNatureId.equals(natures[i])) {
      newNaturesList.add(natures[i]);
    }
  }

  String[] newNatures = newNaturesList.toArray(new String[newNaturesList.size()]);

  // set natures
  desc.setNatureIds(newNatures);
  mProject.setDescription(desc, mMonitor);
}
 
Example 12
Project: textuml   File: ClassifierTests.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void testOperationParameterSet() throws CoreException {
    String source = "";
    source += "model someModel;\n";
    source += "import base;\n";
    source += "class SomeClass\n";
    source += "operation op1(par1 : Boolean, par2 : Integer, par3 : String)\n";
    source += "  parameterset set1 (par1, par2)\n";
    source += "  parameterset set2 (par1, par3)\n";
    source += "  parameterset (par2);\n";
    source += "end;\n";
    source += "end.";
    parseAndCheck(source);
    Operation operation = getOperation("someModel::SomeClass::op1");
    EList<ParameterSet> sets = operation.getOwnedParameterSets();
    Function<ParameterSet, List<String>> collectParameterNames = set -> set.getParameters().stream().map(it -> it.getName()).collect(toList());
    assertEquals(3, sets.size());
    assertEquals("set1", sets.get(0).getName());
    assertEquals(asList("par1", "par2"), collectParameterNames.apply(sets.get(0)));
    assertEquals("set2", sets.get(1).getName());
    assertEquals(asList("par1", "par3"), collectParameterNames.apply(sets.get(1)));
    assertNull(sets.get(2).getName());
    assertEquals(asList("par2"), collectParameterNames.apply(sets.get(2)));
}
 
Example 13
Project: CogniCrypt   File: ProblemMarkerBuilder.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * addMarker Method that adds a Marker to a File, which can then be displayed as an error/warning in the IDE.
 *
 * @param file the IResource of the File to which the Marker is added
 * @param message the message the Marker is supposed to display
 * @param lineNumber the Line to which the Marker is supposed to be added
 * @param start the number of the start character for the Marker
 * @param end the number of the end character for the Marker
 */
private void addMarker(final IResource file, final String message, int lineNumber, final int start, final int end) {
	try {
		final IMarker marker = file.createMarker(Constants.MARKER_TYPE);
		marker.setAttribute(IMarker.MESSAGE, message);
		marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
		if (lineNumber == -1) {
			lineNumber = 1;
		}
		marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
		marker.setAttribute(IMarker.CHAR_START, start);
		marker.setAttribute(IMarker.CHAR_END, end);
		// IJavaModelMarker is important for the Quickfix Processor to work
		// correctly
		marker.setAttribute(IJavaModelMarker.ID, Constants.JDT_PROBLEM_ID);
	}
	catch (final CoreException e) {}
}
 
Example 14
Project: Eclipse-Postfix-Code-Completion   File: JarWriter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void registerInWorkspaceIfNeeded() {
	IPath jarPath= fJarPackage.getAbsoluteJarLocation();
	IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
	for (int i= 0; i < projects.length; i++) {
		IProject project= projects[i];
		// The Jar is always put into the local file system. So it can only be
		// part of a project if the project is local as well. So using getLocation
		// is currently save here.
		IPath projectLocation= project.getLocation();
		if (projectLocation != null && projectLocation.isPrefixOf(jarPath)) {
			try {
				jarPath= jarPath.removeFirstSegments(projectLocation.segmentCount());
				jarPath= jarPath.removeLastSegments(1);
				IResource containingFolder= project.findMember(jarPath);
				if (containingFolder != null && containingFolder.isAccessible())
					containingFolder.refreshLocal(IResource.DEPTH_ONE, null);
			} catch (CoreException ex) {
				// don't refresh the folder but log the problem
				JavaPlugin.log(ex);
			}
		}
	}
}
 
Example 15
Project: Eclipse-Postfix-Code-Completion   File: ConvertIterableLoopOperation.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
	final TextEditGroup group= createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, cuRewrite);

	final ASTRewrite astRewrite= cuRewrite.getASTRewrite();

	TightSourceRangeComputer rangeComputer;
	if (astRewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) {
		rangeComputer= (TightSourceRangeComputer)astRewrite.getExtendedSourceRangeComputer();
	} else {
		rangeComputer= new TightSourceRangeComputer();
	}
	rangeComputer.addTightSourceNode(getForStatement());
	astRewrite.setTargetSourceRangeComputer(rangeComputer);

	Statement statement= convert(cuRewrite, group, positionGroups);
	astRewrite.replace(getForStatement(), statement, group);
}
 
Example 16
Project: xtext-eclipse   File: BuildCancellationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void build(IBuildContext context, IProgressMonitor monitor) throws CoreException {
	super.build(context, monitor);
	if(isExternalInterrupt) {
		try {
			// simulate a workspace operation that interrupts the auto build like in
			// {@link Workspace#prepareOperation(org.eclipse.core.runtime.jobs.ISchedulingRule, IProgressMonitor)}
			BuildManager buildManager = ((Workspace) ResourcesPlugin.getWorkspace()).getBuildManager();
			Field field0 = buildManager.getClass().getDeclaredField("autoBuildJob");
			field0.setAccessible(true);
			Object autoBuildJob = field0.get(buildManager);
			Field field1 = autoBuildJob.getClass().getDeclaredField("interrupted");
			field1.setAccessible(true);
			field1.set(autoBuildJob, true);
			isExternalInterrupt = false;
		} catch(Exception exc) {
			throw new RuntimeException(exc);
		}
	}
	if(cancelException != null) 
		throw cancelException;
}
 
Example 17
Project: translationstudio8   File: ArchiveFileExportOperation2.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Answer the total number of file resources that exist at or below self in the resources hierarchy.
 * @return int
 * @param checkResource
 *            org.eclipse.core.resources.IResource
 */
protected int countChildrenOf(IResource checkResource) throws CoreException {
	if (checkResource.getType() == IResource.FILE) {
		return 1;
	}

	int count = 0;
	if (checkResource.isAccessible()) {
		IResource[] children = ((IContainer) checkResource).members();
		for (int i = 0; i < children.length; i++) {
			count += countChildrenOf(children[i]);
		}
	}

	return count;
}
 
Example 18
Project: gwt-eclipse-plugin   File: WebAppMainTab.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void doPerformApply(ILaunchConfigurationWorkingCopy configuration) {
  super.performApply(configuration);

  // Link the launch configuration to the project. This will cause the
  // launch config to be deleted automatically if the project is deleted.
  IProject project = getProjectNamed(getEnteredProjectName());
  if (project != null) {
    configuration.setMappedResources(new IResource[] {project});
  }

  try {
    saveLaunchConfiguration(configuration);
  } catch (CoreException e) {
    CorePluginLog.logError(e, "Could not update arguments to reflect main tab changes");
  }
}
 
Example 19
Project: Pydev   File: CopyFilesAndFoldersOperation.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether the destination is valid for copying the source file
 * stores.
 * <p>
 * Note this method is for internal use only. It is not API.
 * </p>
 * <p>
 * TODO Bug 117804. This method has been renamed to avoid a bug in the
 * Eclipse compiler with regards to visibility and type resolution when
 * linking.
 * </p>
 *
 * @param destination
 *            the destination container
 * @param sourceStores
 *            the source IFileStore
 * @return an error message, or <code>null</code> if the path is valid
 */
private String validateImportDestinationInternal(IContainer destination, IFileStore[] sourceStores) {
    if (!isAccessible(destination)) {
        return IDEWorkbenchMessages.CopyFilesAndFoldersOperation_destinationAccessError;
    }

    IFileStore destinationStore;
    try {
        destinationStore = EFS.getStore(destination.getLocationURI());
    } catch (CoreException exception) {
        IDEWorkbenchPlugin.log(exception.getLocalizedMessage(), exception);
        return NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_internalError,
                exception.getLocalizedMessage());
    }
    for (int i = 0; i < sourceStores.length; i++) {
        IFileStore sourceStore = sourceStores[i];
        IFileStore sourceParentStore = sourceStore.getParent();

        if (sourceStore != null) {
            if (destinationStore.equals(sourceStore)
                    || (sourceParentStore != null && destinationStore.equals(sourceParentStore))) {
                return NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_importSameSourceAndDest,
                        sourceStore.getName());
            }
            // work around bug 16202. replacement for
            // sourcePath.isPrefixOf(destinationPath)
            IFileStore destinationParent = destinationStore.getParent();
            if (sourceStore.isParentOf(destinationParent)) {
                return IDEWorkbenchMessages.CopyFilesAndFoldersOperation_destinationDescendentError;
            }

        }
    }
    return null;
}
 
Example 20
Project: typescript.java   File: AbstractMainTab.java    License: MIT License 5 votes vote down vote up
private String resolveValue(String expression) throws CoreException {
	String expanded = null;
	try {
		expanded = getValue(expression);
	} catch (CoreException e) { // possibly just a variable that needs to be
								// resolved at runtime
		validateVaribles(expression);
		return null;
	}
	return expanded;
}
 
Example 21
Project: Eclipse-Postfix-Code-Completion   File: ReplaceInvocationsAction.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(IStructuredSelection selection) {
	try {
		Assert.isTrue(RefactoringAvailabilityTester.isReplaceInvocationsAvailable(selection));
		Object first= selection.getFirstElement();
		Assert.isTrue(first instanceof IMethod);
		IMethod method= (IMethod) first;
		if (ActionUtil.isProcessable(getShell(), method))
			RefactoringExecutionStarter.startReplaceInvocationsRefactoring(method, getShell());
	} catch (CoreException e) {
		handleException(e);
	}
}
 
Example 22
Project: texlipse   File: TexlipseProjectCreationWizard.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handle the exceptions of project creation here.
 * @param target
 */
private void handleTargetException(Throwable target) {
    
    if (target instanceof CoreException) {
        
        IStatus status = ((CoreException) target).getStatus();
        ErrorDialog.openError(getShell(), TexlipsePlugin.getResourceString("projectWizardErrorTitle"),
                TexlipsePlugin.getResourceString("projectWizardErrorMessage"), status);

    } else {
        
        MessageDialog.openError(getShell(), TexlipsePlugin.getResourceString("projectWizardErrorTitle"),
                target.getMessage());
    }
}
 
Example 23
Project: eclipse-extras   File: LaunchConfigProviderPDETest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testKeepWhenMappedProjectWasClosedAndFilterDeletedOptionOn() throws CoreException {
  setFilterLaunchConfigsInDeletedProjects( true );
  IResource resource = createLaunchConfigForResource();
  resource.getProject().close( null );

  ILaunchConfiguration[] launchConfigs = launchConfigProvider.getLaunchConfigurations();

  assertThat( launchConfigs ).hasSize( 1 );
}
 
Example 24
Project: Eclipse-Postfix-Code-Completion   File: MoveCuUpdateCreator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void addUpdates(TextChangeManager changeManager, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	pm.beginTask("", fCus.length);  //$NON-NLS-1$
	for (int i= 0; i < fCus.length; i++){
		if (pm.isCanceled())
			throw new OperationCanceledException();

		addUpdates(changeManager, fCus[i], new SubProgressMonitor(pm, 1), status);
	}
}
 
Example 25
Project: goclipse   File: ResourceUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static void refresh(IResource resource, IOperationMonitor om) throws CommonException {
	try {
		resource.refreshLocal(IResource.DEPTH_INFINITE, EclipseUtils.pm(om));
	} catch(CoreException e) {
		throw EclipseUtils.createCommonException(e);
	}
}
 
Example 26
Project: google-cloud-eclipse   File: ToServlet25QuickFixTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertServlet_sunNamespace() throws IOException, ParserConfigurationException,
    SAXException, CoreException {
  String webXml = "<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\" version='3.0'>"
      + "<foo></foo></web-app>";
  Document transformed = transform(webXml);
  Element documentElement = transformed.getDocumentElement();
  assertEquals("2.5", documentElement.getAttribute("version"));
  Element element = (Element) documentElement
      .getElementsByTagNameNS("http://java.sun.com/xml/ns/javaee", "foo").item(0);
  assertEquals("foo", element.getTagName());
}
 
Example 27
Project: google-cloud-eclipse   File: DataflowPipelineLaunchDelegateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSetCredential_originalEnvironmentMapUntouched_loginAccount()
    throws CoreException, IOException {
  pipelineArguments.put("accountEmail", "[email protected]");

  dataflowDelegate.setCredential(configurationWorkingCopy, pipelineArguments);
  verifyLoginAccountSet();
  assertTrue(environmentMap.isEmpty());
}
 
Example 28
Project: gama   File: GamlUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void waitForBuild(final IProgressMonitor monitor) {
	try {
		ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
	} catch (final CoreException e) {
		throw new OperationCanceledException(e.getMessage());
	}
}
 
Example 29
Project: Pydev   File: SystemPythonNature.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Map<String, String> getVariableSubstitution() throws CoreException, MisconfigurationException,
        PythonNatureWithoutProjectException {
    Properties stringSubstitutionVariables = SystemPythonNature.this.info.getStringSubstitutionVariables();
    Map<String, String> variableSubstitution;
    if (stringSubstitutionVariables == null) {
        variableSubstitution = new HashMap<String, String>();
    } else {
        variableSubstitution = PropertiesHelper.createMapFromProperties(stringSubstitutionVariables);
    }
    return variableSubstitution;

}
 
Example 30
Project: google-cloud-eclipse   File: TemplatesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateFileContent_objectifyWebListenerWithPackage()
    throws CoreException, IOException {
  dataMap.put("package", "com.example");
  dataMap.put("servletVersion", "2.5");
  Templates.createFileContent(fileLocation, Templates.OBJECTIFY_WEB_LISTENER_TEMPLATE, dataMap);

  compareToFile("objectifyWebListenerWithPackage.txt");
}
 
Example 31
Project: netbeans   File: HgHookTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testBeforeCommitWithLink() throws MalformedURLException, CoreException, IOException, InterruptedException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    HgHookImpl hook = getHook();

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

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

    ctx = hook.beforeCommit(ctx);
    assertNotNull(ctx);
    assertNotNull(ctx.getMessage());
    assertNotSame("", ctx.getMessage());
    assertNotSame(msg, ctx.getMessage()); // issue info was added
}
 
Example 32
Project: Pydev   File: PythonBaseModelProvider.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected Set<String> getSourcePathSet(Map<PythonNature, Set<String>> natureToSourcePathSet, PythonNature nature) {
    Set<String> sourcePathSet = natureToSourcePathSet.get(nature);
    if (sourcePathSet == null) {
        sourcePathSet = new HashSet<String>();
        try {
            sourcePathSet = nature.getPythonPathNature().getProjectSourcePathSet(true);
        } catch (CoreException e) {
            Log.log(e);
        }
        natureToSourcePathSet.put(nature, sourcePathSet);
    }
    return Collections.unmodifiableSet(sourcePathSet);
}
 
Example 33
Project: txtUML   File: ProjectUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates project or returns the existing.
 * 
 * @param name
 *            - The Name of the Project
 * @return Existing or created project
 */
public static IProject createProject(String name) {
	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	final IProject project = root.getProject(name);
	if (!project.exists()) {
		try {
			project.create(null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
	return project;
}
 
Example 34
Project: sarl   File: SARLProjectConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
/** Validate the version of the SARL library in the dependencies.
 *
 * <p>The test works for standard Java or Maven projects.
 *
 * <p>Caution: This function should not be called for Eclipse plugins.
 *
 * @throws CoreException if internal error occurs.
 */
protected void validateSARLLibraryVersion() throws CoreException {
	final Map<String, Artifact> artifacts = getMavenProjectFacade().getMavenProject().getArtifactMap();
	final Artifact artifact = artifacts.get(ArtifactUtils.versionlessKey(SARL_GROUP_ID, SARL_ARTIFACT_ID));
	if (artifact != null) {
		validateSARLVersion(SARL_GROUP_ID, SARL_ARTIFACT_ID, artifact.getVersion());
	} else {
		getBuildContext().addMessage(
				getMavenProjectFacade().getPomFile(),
				-1, -1,
				Messages.SARLProjectConfigurator_6,
				BuildContext.SEVERITY_ERROR,
				null);
	}
}
 
Example 35
Project: typescript.java   File: NewTypeScriptProjectWizard.java    License: MIT License 5 votes vote down vote up
private IFile generateJsonFile(Object jsonObject, IPath path, IProject project) throws InvocationTargetException {
	Gson gson = new GsonBuilder().setPrettyPrinting().create();
	String content = gson.toJson(jsonObject);
	IFile file = project.getFile(path);
	try {
		if (file.exists()) {
			file.setContents(IOUtils.toInputStream(content), 1, new NullProgressMonitor());
		} else {
			file.create(IOUtils.toInputStream(content), 1, new NullProgressMonitor());
		}
	} catch (CoreException e) {
		throw new InvocationTargetException(e);
	}
	return file;
}
 
Example 36
Project: goclipse   File: LangNature.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** Removes the given builder from the build spec for the configured project. */
protected void removeFromBuildSpec(String builderID) throws CoreException {
	IProjectDescription description = project.getDescription();
	
	ICommand[] commands = description.getBuildSpec();
	int commandIndex = getCommandIndex(commands, builderID);
	if(commandIndex != -1) {
		commands = ArrayUtil.removeAt(commands, commandIndex);
		description.setBuildSpec(commands);
		project.setDescription(description, null);
	}
}
 
Example 37
Project: google-cloud-eclipse   File: WebProjectUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHasJsps_jspInSub() throws CoreException {
  IVirtualFolder root = mock(IVirtualFolder.class, "/");
  IVirtualFolder folder = mock(IVirtualFolder.class, "/a");
  IVirtualFile jsp = mock(IVirtualFile.class, "/a/a.jsp");
  when(jsp.getFileExtension()).thenReturn("jsp");
  when(root.members()).thenReturn(new IVirtualResource[] {folder});
  when(folder.members()).thenReturn(new IVirtualResource[] {jsp});

  assertTrue(WebProjectUtil.hasJsps(root));
  verify(root, times(2)).members();
  verify(folder).members();
  verify(jsp).getFileExtension();
  verifyNoMoreInteractions(root, folder, jsp);
}
 
Example 38
Project: dawnsci   File: MarshallerServiceClassRegistry.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public MarshallerServiceClassRegistry(List<IClassRegistry> extraRegistries) throws ClassRegistryDuplicateIdException, CoreException {
	List<IClassRegistry> registries = new ArrayList<IClassRegistry>();
	platformIsRunning = Platform.isRunning();

	if (extraRegistries!=null) registries.addAll(extraRegistries);

	// Extensions not available for unit tests / non-OSGI mode.
	registries.addAll(getAvailableRegistryExtensions());

	for (IClassRegistry registry : registries) {
		populateClassMap(registry);
	}
}
 
Example 39
Project: RADL   File: RadlValidatingVisitorTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void doesntValidateNonFile() throws CoreException {
  IResourceDelta delta = someResourceDelta();
  when(delta.getResource()).thenReturn(mock(IResource.class));

  visitor.visit(delta);

  verify(validator, never()).validate(any(InputStream.class), any(Collection.class));
}
 
Example 40
Project: tm4e   File: TMPresentationReconciler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds a grammar for the given document.
 * @param newDocument
 * @return
 * @throws CoreException
 */
protected IGrammar findGrammar(@NonNull IDocument newDocument) throws CoreException {
	IGrammar localGrammar = forcedGrammar ? TMPresentationReconciler.this.grammar : null;
	if (localGrammar != null) {
		return localGrammar;
	}
	ContentTypeInfo info = ContentTypeHelper.findContentTypes(newDocument);
	if (info == null) {
		return null;
	}
	return findGrammar(info);
}