javatips.net counter

Java Examples for org.eclipse.core.runtime.IPath

The following java examples will help you to understand the usage of org.eclipse.core.runtime.IPath. These source code samples are taken from different open source projects.

Example 1
Project: cdt-tests-runner-master  File: IndexBugsTests.java View source code
public void testUpdateNonSrcFolderHeader_283080() throws Exception {
    IIndexBinding[] r;
    final IProject prj = fCProject.getProject();
    final IFolder src = prj.getFolder("src");
    final IFolder h = prj.getFolder("h");
    src.create(true, false, null);
    h.create(true, false, null);
    assertTrue(src.exists());
    assertTrue(h.exists());
    ICProjectDescription desc = CCorePlugin.getDefault().getProjectDescription(prj);
    assertNotNull(desc);
    desc.getActiveConfiguration().setSourceEntries(new ICSourceEntry[] { new CSourceEntry(src, new IPath[0], ICSettingEntry.SOURCE_PATH) });
    CCorePlugin.getDefault().setProjectDescription(prj, desc);
    TestSourceReader.createFile(h, "a.h", "int version1;");
    waitForIndexer(fCProject);
    final IIndex index = CCorePlugin.getIndexManager().getIndex(fCProject);
    index.acquireReadLock();
    try {
        r = index.findBindings("version1".toCharArray(), IndexFilter.ALL_DECLARED, null);
        assertEquals(0, r.length);
    } finally {
        index.releaseReadLock();
    }
    IFile s = TestSourceReader.createFile(h, "a.h", "int version2;");
    waitForIndexer(fCProject);
    index.acquireReadLock();
    try {
        r = index.findBindings("version2".toCharArray(), IndexFilter.ALL_DECLARED, null);
        assertEquals(0, r.length);
    } finally {
        index.releaseReadLock();
    }
    s = TestSourceReader.createFile(src, "source.cpp", "#include \"../h/a.h\"");
    waitUntilFileIsIndexed(s, INDEX_WAIT_TIME);
    index.acquireReadLock();
    try {
        r = index.findBindings("version2".toCharArray(), IndexFilter.ALL_DECLARED, null);
        assertEquals(1, r.length);
    } finally {
        index.releaseReadLock();
    }
    s = TestSourceReader.createFile(h, "a.h", "int version3;");
    waitUntilFileIsIndexed(s, INDEX_WAIT_TIME);
    index.acquireReadLock();
    try {
        r = index.findBindings("version2".toCharArray(), IndexFilter.ALL_DECLARED, null);
        assertEquals(0, r.length);
        r = index.findBindings("version3".toCharArray(), IndexFilter.ALL_DECLARED, null);
        assertEquals(1, r.length);
    } finally {
        index.releaseReadLock();
    }
}
Example 2
Project: extFM-Tooling-master  File: SXFM2FMTransformator.java View source code
public static void parseFiles(List<IFile> files, String featureModelExtension) {
    for (IFile iFile : files) {
        IPath filePath = iFile.getRawLocation();
        String xmlExtension = filePath.getFileExtension();
        if (filePath != null && StringUtils.equalsIgnoreCase(sxfmModelExtension, xmlExtension)) {
            String sxfmFile = filePath.toOSString();
            IPath fmFilePath = filePath.removeFileExtension();
            fmFilePath = fmFilePath.addFileExtension(featureModelExtension);
            String fmFile = fmFilePath.toOSString();
            transform(sxfmFile, fmFile);
        }
    }
}
Example 3
Project: tdq-studio-se-master  File: AbstractJarSelectDialog.java View source code
@Override
public void widgetSelected(SelectionEvent e) {
    FileDialog dialog = new FileDialog(dialogComposite.getShell(), SWT.NONE | SWT.MULTI);
    //$NON-NLS-1$
    dialog.setFilterExtensions(new String[] { "*.jar" });
    String path = dialog.open();
    if (path != null) {
        String[] fileNames = dialog.getFileNames();
        for (String name : fileNames) {
            IPath filePath = new Path(path);
            filePath = filePath.removeLastSegments(1).append(name);
            // TDQ-7451 Replace File copy with eclipse IFile create.make svn could syn and control.
            IFile targetFile = ResourceManager.getUDIJarFolder().getFile(filePath.lastSegment());
            createIFileFromFile(filePath.toFile(), targetFile, getDescriptionMessage(name));
        }
    }
    // MOD msjian 2011-7-14 22092 feature: Java UDI: not convinient to delete udi jar files
    fViewer.refresh();
    fManageViewer.refresh();
    fViewer.setInput(ResourceManager.getUDIJarFolder());
    fManageViewer.setInput(ResourceManager.getUDIJarFolder());
    fIsEmpty = evaluateIfTreeEmpty(fInput);
    // getTreeViewer().setCheckedElements(new Object[0]);
    updateOKStatus();
}
Example 4
Project: Eclipse-Postfix-Code-Completion-master  File: ClasspathEntry.java View source code
/**
	 * Decode some element tag containing a sequence of patterns into IPath[]
	 */
private static IPath[] decodePatterns(NamedNodeMap nodeMap, String tag) {
    String sequence = removeAttribute(tag, nodeMap);
    if (//$NON-NLS-1$
    !sequence.equals("")) {
        char[][] patterns = CharOperation.splitOn('|', sequence.toCharArray());
        int patternCount;
        if ((patternCount = patterns.length) > 0) {
            IPath[] paths = new IPath[patternCount];
            int index = 0;
            for (int j = 0; j < patternCount; j++) {
                char[] pattern = patterns[j];
                // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=105581
                if (pattern.length == 0)
                    continue;
                paths[index++] = new Path(new String(pattern));
            }
            if (index < patternCount)
                System.arraycopy(paths, 0, paths = new IPath[index], 0, index);
            return paths;
        }
    }
    return null;
}
Example 5
Project: windowtester-master  File: WTAPIUsage.java View source code
private void collectPluginsReferencedByClasspathEntry(PrintWriter writer, Collection<String> pluginIds, IJavaProject proj, IClasspathEntry entry) throws IOException {
    IPath path = entry.getPath();
    switch(entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_VARIABLE:
            for (int i = path.segmentCount() - 1; i >= 0; i--) {
                String segment = path.segment(i);
                if (segment.startsWith("com.windowtester.")) {
                    String id = segment;
                    i++;
                    while (i < path.segmentCount()) id += "/" + path.segment(i++);
                    pluginIds.add(id);
                    break;
                }
            }
            break;
        case IClasspathEntry.CPE_CONTAINER:
            if (path.segmentCount() >= 1 && path.segment(0).equals("org.eclipse.pde.core.requiredPlugins"))
                collectPluginsReferencedInManifest(pluginIds, proj);
            break;
        case IClasspathEntry.CPE_SOURCE:
        case IClasspathEntry.CPE_PROJECT:
            // ignored
            break;
        default:
            pluginIds.add("unknown " + entry.getEntryKind() + " - " + entry);
            break;
    }
}
Example 6
Project: c4jplugin-master  File: C4JUtils.java View source code
/**
	 * Attempt to update the project's build classpath by removing any occurance
	 * of the C4J library.
	 * 
	 * @param project
	 */
private static void removeC4JFromBuildPath(IProject project) {
    IJavaProject javaProject = JavaCore.create(project);
    try {
        IClasspathEntry[] originalCPs = javaProject.getRawClasspath();
        ArrayList<IClasspathEntry> tempCP = new ArrayList<IClasspathEntry>();
        // to the collection of new classpath entries.
        for (IClasspathEntry originalCP : originalCPs) {
            IPath path = originalCP.getPath();
            if (!(originalCP.getEntryKind() == IClasspathEntry.CPE_CONTAINER && path.segment(0).equals(C4JRuntime.C4JRT_CONTAINER))) {
                tempCP.add(originalCP);
            }
        // end for
        }
        // above filtration process.
        if (originalCPs.length != tempCP.size()) {
            IClasspathEntry[] newCP = (IClasspathEntry[]) tempCP.toArray(new IClasspathEntry[tempCP.size()]);
            javaProject.setRawClasspath(newCP, new NullProgressMonitor());
        }
    // end if at least one classpath element removed
    } catch (JavaModelException e) {
    }
}
Example 7
Project: liferay-ide-master  File: NewLiferayPluginProjectOpBase.java View source code
protected void testPluginTypeListener(Boolean versionRestriction) throws Exception {
    final NewLiferayPluginProjectOp op = newProjectOp("test-plugin-type-listener");
    final String projectName = op.getProjectName().content();
    op.setProjectProvider("ant");
    op.setUseDefaultLocation(true);
    final SDK sdk = SDKUtil.createSDKFromLocation(getLiferayPluginsSdkDir());
    final String[] pluginTypes = { "portlet", "hook", "layouttpl", "theme", "ext" };
    IPath exceptedLocation = null;
    for (String pluginType : pluginTypes) {
        op.setPluginType(pluginType);
        if (pluginType.equals("portlet")) {
            exceptedLocation = sdk.getLocation().append("portlets").append(projectName + "-portlet");
        } else if (pluginType.equals("hook")) {
            exceptedLocation = sdk.getLocation().append("hooks").append(projectName + "-hook");
        } else if (pluginType.equals("layouttpl")) {
            exceptedLocation = sdk.getLocation().append("layouttpl").append(projectName + "-layouttpl");
        } else if (pluginType.equals("theme")) {
            exceptedLocation = sdk.getLocation().append("themes").append(projectName + "-theme");
        } else {
            exceptedLocation = sdk.getLocation().append("ext").append(projectName + "-ext");
        }
        assertEquals(exceptedLocation, PathBridge.create(op.getLocation().content()));
    }
}
Example 8
Project: tern.java-master  File: JavaScriptElementLabels.java View source code
private static boolean getVariableLabel(IPackageFragmentRoot root, long flags, StringBuffer buf) {
    try {
        IIncludePathEntry rawEntry = root.getRawIncludepathEntry();
        if (rawEntry != null && rawEntry.getEntryKind() == IIncludePathEntry.CPE_VARIABLE) {
            IPath path = rawEntry.getPath().makeRelative();
            if (getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED)) {
                int segements = path.segmentCount();
                if (segements > 0) {
                    buf.append(path.segment(segements - 1));
                    if (segements > 1) {
                        buf.append(CONCAT_STRING);
                        buf.append(path.removeLastSegments(1).toOSString());
                    }
                } else {
                    buf.append(path.toString());
                }
            } else {
                buf.append(path.toString());
            }
            buf.append(CONCAT_STRING);
            if (root.isExternal())
                buf.append(root.getPath().toOSString());
            else
                buf.append(root.getPath().makeRelative().toString());
            return true;
        }
    } catch (JavaScriptModelException e) {
        JavaScriptPlugin.log(e);
    }
    return false;
}
Example 9
Project: eclipse.jdt.ui-master  File: CopyTest.java View source code
public void testCopy_Bug67124() throws Exception {
    String fileName = "A.java";
    ICompilationUnit cu = getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor());
    IPath cuPath = cu.getResource().getFullPath();
    IProject superFolder = RefactoringTestSetup.getProject().getProject();
    IFolder destinationFolder = superFolder.getFolder("folder");
    destinationFolder.create(true, true, null);
    FileBuffers.getTextFileBufferManager().connect(cuPath, LocationKind.IFILE, null);
    ITextFileBuffer buffer = FileBuffers.getTextFileBufferManager().getTextFileBuffer(cuPath, LocationKind.IFILE);
    buffer.getDocument().replace(0, 0, "Dirty");
    INewNameQueries queries = new MockNewNameQueries();
    IJavaElement[] javaElements = { cu };
    IResource[] resources = {};
    JavaCopyProcessor ref = verifyEnabled(resources, javaElements, queries, createReorgQueries());
    Object destination = destinationFolder;
    verifyValidDestination(ref, destination);
    assertTrue("source cu does not exist before copying", cu.exists());
    RefactoringStatus status = performRefactoring(ref, false);
    assertEquals(null, status);
    assertTrue("source cu does not exist after copying", cu.exists());
    IFile newFile = destinationFolder.getFile(fileName);
    assertTrue("new cu does not exist after copying", newFile.exists());
    IPath newFilePath = newFile.getFullPath();
    try {
        FileBuffers.getTextFileBufferManager().connect(newFilePath, LocationKind.IFILE, null);
        ITextFileBuffer newBuffer = FileBuffers.getTextFileBufferManager().getTextFileBuffer(newFilePath, LocationKind.IFILE);
        assertEquals(buffer.getDocument().get(), newBuffer.getDocument().get());
    } finally {
        FileBuffers.getTextFileBufferManager().disconnect(cuPath, LocationKind.IFILE, null);
    }
}
Example 10
Project: CodingSpectator-master  File: MatchLocator.java View source code
/*
 * Returns the working copies that can see the given focus.
 */
private static HashMap workingCopiesThatCanSeeFocus(org.eclipse.jdt.core.ICompilationUnit[] copies, SearchPattern pattern, SearchParticipant participant) {
    if (copies == null)
        return new HashMap();
    HashMap result = new HashMap();
    for (int i = 0, length = copies.length; i < length; i++) {
        org.eclipse.jdt.core.ICompilationUnit workingCopy = copies[i];
        IPath projectOrJar = MatchLocator.getProjectOrJar(workingCopy).getPath();
        if (pattern.focus == null || IndexSelector.canSeeFocus(pattern, projectOrJar)) {
            result.put(workingCopy.getPath().toString(), new WorkingCopyDocument(workingCopy, participant));
        }
    }
    return result;
}
Example 11
Project: eclipse.jdt.core-master  File: JavaSearchBugsTests.java View source code
/**
 * @bug 97606: [1.5][search] Raw type reference is reported as exact match for qualified names
 * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=97606"
 */
public void testBug97606() throws CoreException {
    this.workingCopies = new ICompilationUnit[4];
    this.workingCopies[0] = getWorkingCopy("/JavaSearchBugs/src/b97606/pack/def/L.java", "package b97606.pack.def;\n" + "public interface L<E> {}\n");
    this.workingCopies[1] = getWorkingCopy("/JavaSearchBugs/src/b97606/pack/def/LL.java", "package b97606.pack.def;\n" + "public class LL<E> implements L<E> {\n" + "	public Object clone() {\n" + "		return null;\n" + "	}\n" + "}\n");
    this.workingCopies[2] = getWorkingCopy("/JavaSearchBugs/src/b97606/pack/ref/K.java", "package b97606.pack.ref;\n" + "public interface K {}\n");
    this.workingCopies[3] = getWorkingCopy("/JavaSearchBugs/src/b97606/pack/ref/X.java", "package b97606.pack.ref;\n" + "public class X implements K {\n" + "	private b97606.pack.def.LL sg;\n" + "	protected synchronized b97606.pack.def.L<K> getSG() {\n" + "		return (sg != null) \n" + "			? (b97606.pack.def.L) sg.clone()\n" + "			: null;\n" + "	}\n" + "}\n");
    IPath rootPath = new Path("/JavaSearchBugs/src/b97606");
    IPath pathDef = rootPath.append("pack").append("def");
    IPath pathRef = rootPath.append("pack").append("ref");
    try {
        createFolder(pathDef);
        createFolder(pathRef);
        this.workingCopies[0].commitWorkingCopy(true, null);
        this.workingCopies[1].commitWorkingCopy(true, null);
        this.workingCopies[2].commitWorkingCopy(true, null);
        this.workingCopies[3].commitWorkingCopy(true, null);
        this.resultCollector.showRule();
        IType type = this.workingCopies[0].getType("L");
        search(type, REFERENCES, SearchPattern.R_ERASURE_MATCH);
        assertSearchResults("src/b97606/pack/def/LL.java b97606.pack.def.LL [L] ERASURE_MATCH\n" + "src/b97606/pack/ref/X.java b97606.pack.def.L<K> b97606.pack.ref.X.getSG() [b97606.pack.def.L] ERASURE_MATCH\n" + "src/b97606/pack/ref/X.java b97606.pack.def.L<K> b97606.pack.ref.X.getSG() [b97606.pack.def.L] ERASURE_RAW_MATCH");
    } finally {
        deleteFolder(rootPath);
    }
}
Example 12
Project: teiid-designer-master  File: ModelUtilities.java View source code
/**
     * Get the representative [email protected] IFile} from the given container path and model name.
     *
     * @param containerPath
     * @param modelName
     *
     * @return [email protected] IFile} of the model
     *
     * @throws ModelWorkspaceException
     */
public static IFile getModelFile(String containerPath, String modelName) throws ModelWorkspaceException {
    if (containerPath == null || modelName == null) {
        return null;
    }
    IPath modelPath = new Path(containerPath).append(modelName);
    if (!modelPath.toString().toLowerCase().endsWith(DOT_MODEL_FILE_EXTENSION)) {
        modelPath = modelPath.addFileExtension(MODEL_FILE_EXTENSION);
    }
    ModelWorkspaceItem item = ModelWorkspaceManager.getModelWorkspaceManager().findModelWorkspaceItem(modelPath, IResource.FILE);
    if (item != null) {
        return (IFile) item.getCorrespondingResource();
    }
    return null;
}
Example 13
Project: erlide-master  File: IErlModelTest.java View source code
// IErlModule findIncludeFromModule(IErlModule module, String includeName,
// String includePath, Scope scope) throws ErlModelException;
@Test
public void findIncludeFromModule() throws Exception {
    File externalIncludeFile = null;
    final IErlProject myProject = projects[0];
    final IProject workspaceProject = myProject.getWorkspaceProject();
    final IProject[] referencedProjects = workspaceProject.getReferencedProjects();
    final Collection<IPath> includeDirs = myProject.getProperties().getIncludeDirs();
    // directory as the module
    try {
        final String xxHrl = "xx.hrl";
        externalIncludeFile = ErlideTestUtils.createTmpFile(xxHrl, "-record(rec2, {field, another=def}.");
        final String externalIncludePath = externalIncludeFile.getAbsolutePath();
        final IPath p = new Path(externalIncludePath).removeLastSegments(1);
        final List<IPath> newIncludeDirs = Lists.newArrayList(includeDirs);
        newIncludeDirs.add(p);
        ((ErlProject) myProject).setIncludeDirs(newIncludeDirs);
        final IErlModule include = ErlideTestUtils.createInclude(myProject, "yy.hrl", "-define(Y, include).\n");
        final IErlProject project1 = projects[1];
        final IErlModule referencedInclude = ErlideTestUtils.createInclude(project1, "zz.hrl", "-define(Z, referenced).\n");
        final IErlModule includeInModuleDir = ErlideTestUtils.createModule(myProject, "ww.hrl", "-define(WW, x).\n");
        myProject.open(null);
        // when
        // looking for includes
        final String xx = "xx";
        final IErlModule x1 = model.findIncludeFromModule(module, xx, null, IErlElementLocator.Scope.PROJECT_ONLY);
        final IErlModule x2 = model.findIncludeFromModule(module, xx, null, IErlElementLocator.Scope.ALL_PROJECTS);
        final IErlModule x3 = model.findIncludeFromModule(module, xx, null, IErlElementLocator.Scope.REFERENCED_PROJECTS);
        final String yy = "yy";
        final IErlModule y1 = model.findIncludeFromModule(module, yy, null, IErlElementLocator.Scope.PROJECT_ONLY);
        final IErlModule y2 = model.findIncludeFromModule(module, yy, null, IErlElementLocator.Scope.ALL_PROJECTS);
        final IErlModule y3 = model.findIncludeFromModule(module, yy, null, IErlElementLocator.Scope.REFERENCED_PROJECTS);
        final String zz = "zz";
        final IErlModule z1 = model.findIncludeFromModule(module, zz, null, IErlElementLocator.Scope.PROJECT_ONLY);
        final IErlModule z2 = model.findIncludeFromModule(module, zz, null, IErlElementLocator.Scope.ALL_PROJECTS);
        final IErlModule z3 = model.findIncludeFromModule(module, zz, null, IErlElementLocator.Scope.REFERENCED_PROJECTS);
        final IProjectDescription description = workspaceProject.getDescription();
        description.setReferencedProjects(new IProject[] { project1.getWorkspaceProject() });
        workspaceProject.setDescription(description, null);
        myProject.open(null);
        final IErlModule z4 = model.findIncludeFromModule(module, zz, null, IErlElementLocator.Scope.PROJECT_ONLY);
        final IErlModule z5 = model.findIncludeFromModule(module, zz, null, IErlElementLocator.Scope.ALL_PROJECTS);
        final IErlModule z6 = model.findIncludeFromModule(module, zz, null, IErlElementLocator.Scope.REFERENCED_PROJECTS);
        final String ww = "ww";
        final IErlModule w1 = model.findIncludeFromModule(module, ww, null, IErlElementLocator.Scope.PROJECT_ONLY);
        final IErlElementLocator mymodel = ErlangEngine.getInstance().getModel();
        final IErlModule w2 = mymodel.findIncludeFromProject(myProject, ww, null, IErlElementLocator.Scope.PROJECT_ONLY);
        // then
        // scope should be respected
        assertNotNull(x1);
        assertEquals(xxHrl, x1.getName());
        assertNotNull(x2);
        assertEquals(xxHrl, x2.getName());
        assertNotNull(x3);
        assertEquals(xxHrl, x3.getName());
        assertEquals(include, y1);
        assertEquals(include, y2);
        assertEquals(include, y3);
        assertNull(z1);
        assertEquals(referencedInclude, z2);
        assertNull(z3);
        assertNull(z4);
        assertEquals(referencedInclude, z5);
        assertEquals(referencedInclude, z6);
        assertEquals(includeInModuleDir, w1);
        assertNull(w2);
    } finally {
        if (externalIncludeFile != null && externalIncludeFile.exists()) {
            externalIncludeFile.delete();
        }
        ((ErlProject) myProject).setIncludeDirs(includeDirs);
        final IProjectDescription description = workspaceProject.getDescription();
        description.setReferencedProjects(referencedProjects);
        workspaceProject.setDescription(description, null);
    }
}
Example 14
Project: tcf-master  File: MemoryMapWidget.java View source code
private void locateSymbolFile(IMemoryMap.MemoryRegion r) {
    Assert.isNotNull(r);
    Map<String, Object> props = new HashMap<String, Object>(r.getProperties());
    FileDialog dialog = new FileDialog(map_table.getShell(), SWT.OPEN);
    IPath workSpacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
    dialog.setFilterPath(workSpacePath.toString());
    //$NON-NLS-1$
    dialog.setText("Locate Symbol File");
    String symbolFile = dialog.open();
    if (symbolFile != null && new File(symbolFile).exists()) {
        // Create the new path map rule
        Map<String, Object> properties = new LinkedHashMap<String, Object>();
        properties.put(IPathMap.PROP_SOURCE, props.get(IMemoryMap.PROP_FILE_NAME));
        properties.put(IPathMap.PROP_DESTINATION, symbolFile);
        PathMapRule rule = new PathMapRule(properties);
        if (cfg != null) {
            try {
                ILaunchConfigurationWorkingCopy wc = cfg instanceof ILaunchConfigurationWorkingCopy ? (ILaunchConfigurationWorkingCopy) cfg : cfg.getWorkingCopy();
                //$NON-NLS-1$
                String s = wc.getAttribute(TCFLaunchDelegate.ATTR_PATH_MAP, "");
                List<PathMapRule> map = TCFLaunchDelegate.parsePathMapAttribute(s);
                map.add(0, rule);
                StringBuilder bf = new StringBuilder();
                for (IPathMap.PathMapRule m : map) {
                    bf.append(m.toString());
                }
                if (bf.length() == 0)
                    wc.removeAttribute(TCFLaunchDelegate.ATTR_PATH_MAP);
                else
                    wc.setAttribute(TCFLaunchDelegate.ATTR_PATH_MAP, bf.toString());
                if (wc.isDirty())
                    wc.doSave();
            } catch (CoreException e) {
                Activator.getDefault().getLog().log(e.getStatus());
            }
        }
    }
}
Example 15
Project: eclipse-commons-master  File: FileView.java View source code
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
    super.init(site, memento);
    IConfigurationElement[] configurationElements = Platform.getExtensionRegistry().getConfigurationElementsFor(Activator.getId(), BINDINGS);
    for (IConfigurationElement configurationElement : configurationElements) {
        if (site.getId().equals(configurationElement.getAttribute(VIEW_ID))) {
            // Type
            try {
                Object type = configurationElement.createExecutableExtension(TYPE);
                if (type instanceof IFileViewType) {
                    @SuppressWarnings("unchecked") IFileViewType<? super Composite> fileViewType = (IFileViewType<? super Composite>) type;
                    this.setType(fileViewType);
                }
            } catch (CoreException e) {
                Activator.logError(format("Can't initialize type of file view {0}", site.getId()), e);
            }
            // Extensions
            for (//$NON-NLS-1$
            IConfigurationElement extensionElement : //$NON-NLS-1$
            configurationElement.getChildren("fileExtension")) {
                extensions.add(//$NON-NLS-1$
                extensionElement.getAttribute(//$NON-NLS-1$
                "extension"));
            }
            // Error message
            String errorMessage = //$NON-NLS-1$
            configurationElement.getAttribute(//$NON-NLS-1$
            "errorMessage");
            if (errorMessage != null) {
                this.errorMessage = errorMessage;
            }
        }
    }
    // Toolbar
    toolbar = site.getActionBars().getToolBarManager();
    toolbarContributions = getType().getToolbarContributions();
    registerToolbarActionShortcuts();
    // Restore settings
    IDialogSettings dialogSettings = Activator.getInstance().getDialogSettings();
    if (dialogSettings != null) {
        // Path
        String pathString = dialogSettings.get(getSettingsKey(PATH));
        if (pathString != null) {
            IPath path = Path.fromPortableString(pathString);
            IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
            setFile(file);
        }
        // Linked
        Boolean linked = dialogSettings.getBoolean(getSettingsKey(LINKED));
        if (linked != null) {
            this.linked = linked;
        }
    }
    toggleLinkedAction.setChecked(this.linked);
}
Example 16
Project: cdt-master  File: GCCBuildCommandParserTest.java View source code
/**
	 * Sets build working directory for DefaultSettingConfiguration being tested.
	 */
private void setBuilderCWD(IProject project, IPath buildCWD) throws CoreException {
    CProjectDescriptionManager manager = CProjectDescriptionManager.getInstance();
    {
        ICProjectDescription prjDescription = manager.getProjectDescription(project, true);
        assertNotNull(prjDescription);
        ICConfigurationDescription cfgDescription = prjDescription.getDefaultSettingConfiguration();
        assertNotNull(cfgDescription);
        cfgDescription.getBuildSetting().setBuilderCWD(buildCWD);
        manager.setProjectDescription(project, prjDescription);
        // doublecheck builderCWD
        IPath actualBuildCWD = cfgDescription.getBuildSetting().getBuilderCWD();
        assertEquals(buildCWD, actualBuildCWD);
    }
    {
        // triplecheck builderCWD for different project/configuration descriptions
        ICProjectDescription prjDescription = CProjectDescriptionManager.getInstance().getProjectDescription(project, false);
        assertNotNull(prjDescription);
        ICConfigurationDescription cfgDescription = prjDescription.getDefaultSettingConfiguration();
        assertNotNull(cfgDescription);
    }
}
Example 17
Project: aws-toolkit-eclipse-master  File: ElasticBeanstalkPublishingUtils.java View source code
public void publishApplicationToElasticBeanstalk(IPath war, String versionLabel, IProgressMonitor monitor) throws CoreException {
    trace("Publishing application to AWS Elastic Beanstalk");
    monitor.beginTask("Deploying application with AWS Elastic Beanstalk", 100);
    String bucketName;
    String applicationName = environment.getApplicationName();
    String environmentName = environment.getEnvironmentName();
    String key = formVersionKey(applicationName, versionLabel);
    checkForCancellation(monitor);
    long deployStartTime = System.currentTimeMillis();
    try {
        bucketName = beanstalkClient.createStorageLocation().getS3Bucket();
        if (s3.doesBucketExist(bucketName) == false) {
            trace("Creating Amazon S3 bucket");
            monitor.setTaskName("Creating Amazon S3 bucket");
            s3.createBucket(bucketName);
            checkForCancellation(monitor);
        }
        trace("Uploading application to Amazon S3");
        monitor.setTaskName("Uploading application to Amazon S3");
        long startTime = System.currentTimeMillis();
        s3.putObject(bucketName, key, war.toFile());
        long endTime = System.currentTimeMillis();
        ElasticBeanstalkAnalytics.trackUploadMetrics(endTime - startTime, war.toFile().length());
        checkForCancellation(monitor);
        monitor.worked(40);
    } catch (AmazonClientException ace) {
        throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to upload application to Amazon S3: " + ace.getMessage(), ace));
    }
    try {
        trace("Registering new application version from " + war.toOSString());
        monitor.setTaskName("Registering application version " + versionLabel);
        beanstalkClient.createApplicationVersion(new CreateApplicationVersionRequest().withApplicationName(applicationName).withAutoCreateApplication(true).withDescription(environment.getApplicationDescription()).withVersionLabel(versionLabel).withSourceBundle(new S3Location().withS3Bucket(bucketName).withS3Key(key)));
        checkForCancellation(monitor);
        monitor.worked(40);
    } catch (AmazonClientException ace) {
        throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to register application version with AWS Elastic Beanstalk: " + ace.getMessage(), ace));
    }
    trace("Updating environment");
    monitor.setTaskName("Updating environment with latest version");
    if (beanstalkClientExtensions.doesEnvironmentExist(environmentName)) {
        try {
            beanstalkClient.updateEnvironment(new UpdateEnvironmentRequest().withEnvironmentName(environmentName).withVersionLabel(versionLabel));
        } catch (AmazonClientException ace) {
            throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to update environment with new application version: " + ace.getMessage(), ace));
        }
    } else {
        try {
            createNewEnvironment(versionLabel);
        } catch (AmazonClientException ace) {
            throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to create new environment: " + ace.getMessage(), ace));
        }
    }
    ElasticBeanstalkAnalytics.trackDeployTotalTime(System.currentTimeMillis() - deployStartTime);
    trace("Done publishing to AWS Elastic Beanstalk, waiting for env to become available...");
    checkForCancellation(monitor);
    monitor.worked(20);
    monitor.done();
}
Example 18
Project: dltk.ruby-master  File: TestUnitTestRunnerUI.java View source code
private boolean testFragmentPath(IPath fragmentPath, IPath path) {
    if (pathEquality.isPrefixOf(fragmentPath, path) && path.segmentCount() > fragmentPath.segmentCount() + TEST_UNIT.length) {
        for (int j = 0; j < TEST_UNIT.length; ++j) {
            if (!TEST_UNIT[j].equals(path.segment(fragmentPath.segmentCount() + j))) {
                return false;
            }
        }
        return true;
    }
    return false;
}
Example 19
Project: turmeric-eclipse-master  File: MavenCoreUtils.java View source code
/*
	 * public static String[] translateLibraryNames(final String... libNames ) {
	 * final Transformer< String > transformer = new Transformer< String >() {
	 * private static final long serialVersionUID = 3166012544618628824L; public
	 * String transform( final Object input ) { if( ArrayUtils.contains(
	 * SOAProjectConstants.SOA_FRAMEWORK_JARS, input.toString() ) ) try { return
	 * getLibraryIdentifier( input.toString()).toString(); } catch
	 * (MavenEclipseApiException e) { throw new RuntimeException(e); } return
	 * input.toString(); } }; return ListUtil.transformed( transformer, (
	 * Object[] )libNames ).toArray( new String[ 0 ] ); }
	 */
/**
	 * Gets the asset location.
	 *
	 * @param projectName the project name
	 * @return the asset location
	 * @throws Exception the exception
	 */
public static String getAssetLocation(String projectName) throws Exception {
    if (StringUtils.isNotEmpty(projectName)) {
        final IProject project = WorkspaceUtil.getProject(projectName);
        if (project != null && project.isAccessible()) {
            // this approach would convert white spaces into %20
            return project.getLocation().makeAbsolute().toString();
        } else {
            // interface projects
            IPath jarPath = getServiceJarLocation(projectName);
            if (jarPath != null)
                return jarPath.toString();
            // FIXME we need SOA framework group ID here
            for (String groupID : getMavenOrgProviderInstance().getAllProjectTypeGroupIds()) {
                jarPath = getArtifactJarLocation(groupID, projectName);
                if (jarPath != null)
                    return jarPath.toString();
            }
        }
    }
    return null;
}
Example 20
Project: tmdm-studio-se-master  File: RepositoryResourceUtil.java View source code
public static IRepositoryViewObject createFolderViewObject(ERepositoryObjectType type, String folderName, Item pItem, boolean isSystem) {
    Property prop = PropertiesFactory.eINSTANCE.createProperty();
    prop.setId(EcoreUtil.generateUUID());
    //
    ContainerItem item = MdmpropertiesFactory.eINSTANCE.createContainerItem();
    isSystem = isSystemFolder(pItem, folderName);
    item.setType(isSystem ? FolderType.STABLE_SYSTEM_FOLDER_LITERAL : FolderType.FOLDER_LITERAL);
    item.setLabel(folderName);
    item.setRepObjType(type);
    ItemState itemState = PropertiesFactory.eINSTANCE.createItemState();
    itemState.setDeleted(false);
    item.setState(itemState);
    //
    prop.setItem(item);
    prop.setLabel(folderName);
    try {
        if (!isSystem) {
            Project project = ProjectManager.getInstance().getCurrentProject();
            IProject fsProject = ResourceUtils.getProject(project);
            ItemState state = pItem.getState();
            itemState.setPath(state.getPath() + IPath.SEPARATOR + folderName);
            String path = ERepositoryObjectType.getFolderName(type);
            if (!path.isEmpty()) {
                path += itemState.getPath();
            }
            IFolder folder = fsProject.getFolder(path);
            if (!folder.exists()) {
                Path parentPath = new Path(pItem.getState().getPath());
                ProxyRepositoryFactory.getInstance().createFolder(project, type, parentPath, folderName);
            }
        } else {
            itemState.setPath(folderName);
        }
    } catch (PersistenceException e) {
        log.error(e.getMessage(), e);
    }
    FolderRepositoryObject containerRepositoryObject = new FolderRepositoryObject(prop);
    //
    ContainerCacheService.putContainer(containerRepositoryObject);
    //
    return containerRepositoryObject;
}
Example 21
Project: EclipseTrader-master  File: ChartViewPart.java View source code
/* (non-Javadoc)
     * @see org.eclipse.ui.part.ViewPart#init(org.eclipse.ui.IViewSite, org.eclipse.ui.IMemento)
     */
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
    super.init(site, memento);
    this.memento = memento;
    this.preferenceStore = UIActivator.getDefault().getPreferenceStore();
    try {
        dialogSettings = UIActivator.getDefault().getDialogSettings().getSection(K_VIEWS).getSection(site.getSecondaryId());
        uri = new URI(dialogSettings.get(K_URI));
        IRepositoryService repositoryService = UIActivator.getDefault().getRepositoryService();
        security = repositoryService.getSecurityFromURI(uri);
        String privateTemplate = dialogSettings.get(K_PRIVATE_TEMPLATE);
        if (privateTemplate != null) {
            template = unmarshal(privateTemplate);
        }
        if (template == null) {
            //$NON-NLS-1$
            IPath templatePath = new Path("data");
            if (dialogSettings.get(K_TEMPLATE) != null) {
                templatePath = templatePath.append(dialogSettings.get(K_TEMPLATE));
            } else {
                templatePath = templatePath.append("basic-template.xml");
            }
            InputStream stream = FileLocator.openStream(UIActivator.getDefault().getBundle(), templatePath, false);
            template = unmarshal(stream);
        }
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, UIActivator.PLUGIN_ID, Messages.ChartViewPart_LoadingErrorMessage + site.getSecondaryId(), e);
        UIActivator.getDefault().getLog().log(status);
    }
    site.setSelectionProvider(new SelectionProvider());
    createActions();
    createPeriodActions();
    IActionBars actionBars = site.getActionBars();
    IMenuManager menuManager = actionBars.getMenuManager();
    //$NON-NLS-1$
    menuManager.add(new Separator("periods.top"));
    //$NON-NLS-1$
    menuManager.add(new Separator("periods"));
    //$NON-NLS-1$
    menuManager.add(new Separator("periods.bottom"));
    menuManager.add(currentPriceLineAction);
    menuManager.add(currentBookAction);
    //$NON-NLS-1$
    menuManager.appendToGroup("periods.top", periodAllAction);
    if (periodActions != null) {
        for (int i = 0; i < periodActions.length; i++) {
            menuManager.appendToGroup("periods", periodActions[i]);
        }
    }
    IToolBarManager toolBarManager = actionBars.getToolBarManager();
    //$NON-NLS-1$
    toolBarManager.add(new Separator("additions"));
    toolBarManager.add(updateAction);
    TimeSpan periodTimeSpan = TimeSpan.fromString(dialogSettings.get(K_PERIOD));
    TimeSpan resolutionTimeSpan = TimeSpan.fromString(dialogSettings.get(K_RESOLUTION));
    setPeriodActionSelection(periodTimeSpan, resolutionTimeSpan);
    actionBars.setGlobalActionHandler(cutAction.getId(), cutAction);
    actionBars.setGlobalActionHandler(copyAction.getId(), copyAction);
    actionBars.setGlobalActionHandler(pasteAction.getId(), pasteAction);
    actionBars.setGlobalActionHandler(deleteAction.getId(), deleteAction);
    actionBars.setGlobalActionHandler(ActionFactory.PRINT.getId(), printAction);
    ToolAction toolAction = new ToolAction(Messages.ChartViewPart_LineAction, this, "org.eclipsetrader.ui.charts.tools.line");
    actionBars.setGlobalActionHandler(toolAction.getId(), toolAction);
    toolAction = new ToolAction(Messages.ChartViewPart_FiboLineAction, this, "org.eclipsetrader.ui.charts.tools.fiboline");
    actionBars.setGlobalActionHandler(toolAction.getId(), toolAction);
    toolAction = new ToolAction(Messages.ChartViewPart_FanLineAction, this, "org.eclipsetrader.ui.charts.tools.fanline");
    actionBars.setGlobalActionHandler(toolAction.getId(), toolAction);
    toolAction = new ToolAction(Messages.ChartViewPart_FiboArcAction, this, "org.eclipsetrader.ui.charts.tools.fiboarc");
    actionBars.setGlobalActionHandler(toolAction.getId(), toolAction);
    actionBars.setGlobalActionHandler(zoomInAction.getActionDefinitionId(), zoomInAction);
    actionBars.setGlobalActionHandler(zoomOutAction.getActionDefinitionId(), zoomOutAction);
    actionBars.setGlobalActionHandler(zoomResetAction.getActionDefinitionId(), zoomResetAction);
    actionBars.setGlobalActionHandler(propertiesAction.getId(), propertiesAction);
    actionBars.updateActionBars();
}
Example 22
Project: platform_tools_motodev-master  File: ActivityBasedOnTemplate.java View source code
private void parseStringXmlNodes(String sampleStringFileName) {
    List<StringArrayNode> newArrayList = new ArrayList<StringArrayNode>();
    List<StringNode> newStrList = new ArrayList<StringNode>();
    try {
        File sampleStringXmlFile = new File(FileLocator.toFileURL(CodeUtilsActivator.getDefault().getBundle().getEntry(ACTIVITY_SAMPLES_FOLDER + IPath.SEPARATOR + sampleStringFileName)).getFile());
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(sampleStringXmlFile);
        doc.getDocumentElement().normalize();
        //string nodes elements
        //$NON-NLS-1$
        NodeList nodeLst = doc.getElementsByTagName("string");
        for (int s = 0; s < nodeLst.getLength(); s++) {
            Node fstNode = nodeLst.item(s);
            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element fstElmnt = (Element) fstNode;
                //$NON-NLS-1$
                String nameAtr = fstElmnt.getAttribute("name");
                String stringValue = fstElmnt.getTextContent();
                if ((nameAtr != null) && (nameAtr.length() > 0)) {
                    newStrList.add(new StringNode(nameAtr, stringValue));
                }
            }
        }
        //array nodes elements
        //$NON-NLS-1$
        nodeLst = doc.getElementsByTagName("string-array");
        for (int s = 0; s < nodeLst.getLength(); s++) {
            Node fstNode = nodeLst.item(s);
            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element fstElmnt = (Element) fstNode;
                //$NON-NLS-1$
                String nameAtr = fstElmnt.getAttribute("name");
                StringArrayNode strArray = new StringArrayNode(nameAtr);
                NodeList arrayItems = fstElmnt.getChildNodes();
                for (int i = 0; i < arrayItems.getLength(); i++) {
                    Node itemNode = arrayItems.item(i);
                    if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element itemElmnt = (Element) itemNode;
                        String itemValue = itemElmnt.getTextContent();
                        strArray.addValue(itemValue);
                    }
                }
                newArrayList.add(strArray);
            }
        }
        setSampleStringNodes(newStrList);
        setSampleArrayNodes(newArrayList);
    } catch (Exception e) {
        StudioLogger.error(ActivityBasedOnTemplate.class, e.getMessage() + " " + CodeUtilsNLS.UI_SampleSelectionPage_ErrorParsingStringXml, e);
    }
    return;
}
Example 23
Project: xmind-master  File: CathyPlugin.java View source code
private void upgradeWorkspace() {
    IPath stateLocation;
    try {
        stateLocation = Platform.getStateLocation(getBundle());
    } catch (Exception e) {
        return;
    }
    String versionFileName = //$NON-NLS-1$
    String.format(//$NON-NLS-1$
    "workspace-upgraded-v%s", getBundle().getVersion().toString());
    File versionFile = stateLocation.append(versionFileName).toFile();
    if (versionFile.exists())
        return;
    /// delete old workbench state on first launch
    File workbenchFile = stateLocation.removeLastSegments(1).append(//$NON-NLS-1$
    "org.eclipse.e4.workbench").append(//$NON-NLS-1$
    "workbench.xmi").toFile();
    if (workbenchFile.exists()) {
        workbenchFile.delete();
    }
    try {
        File parentDir = versionFile.getParentFile();
        if (parentDir != null)
            parentDir.mkdirs();
        OutputStream output = new FileOutputStream(versionFile);
        try {
            //$NON-NLS-1$
            output.write("done".getBytes());
        } finally {
            output.close();
        }
    } catch (IOException e) {
    }
}
Example 24
Project: pmd-eclipse-plugin-master  File: PreferencesManagerImpl.java View source code
/**
     * Initialize 'loadPreferencesStore' to deal with backward compatibility issues.
     * The old preferences use the net.sourceforge.pmd.runtime package instead of the
     * new net.sourceforge.pmd.eclipse.plugin package.
     */
private void initLoadPreferencesStore() {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IPath path = root.getLocation();
    File newPrefs = new File(path.append(NEW_PREFERENCE_LOCATION).toString());
    File oldPrefs = new File(path.append(OLD_PREFERENCE_LOCATION).toString());
    loadPreferencesStore = storePreferencesStore;
    if (!newPrefs.exists() && oldPrefs.exists()) {
        // only retrieve old style preferences if new file doesn't exist
        try {
            Properties props = new Properties();
            FileInputStream in = new FileInputStream(oldPrefs);
            props.load(in);
            in.close();
            loadPreferencesStore = new PreferenceStore();
            for (Map.Entry<Object, Object> entry : props.entrySet()) {
                String key = (String) entry.getKey();
                if (key.startsWith(OLD_PREFERENCE_PREFIX)) {
                    key = key.replaceFirst(OLD_PREFERENCE_PREFIX, PMDPlugin.PLUGIN_ID);
                }
                loadPreferencesStore.putValue(key, (String) entry.getValue());
            }
        } catch (IOException ioe) {
            PMDPlugin.getDefault().logError("IOException in loading old format preferences", ioe);
            loadPreferencesStore = storePreferencesStore;
        }
    }
}
Example 25
Project: substeps-eclipse-plugin-master  File: SubstepsPropertyPage.java View source code
private boolean isSafeSubstepsFolderChange() {
    final IPath previousPath = oldSubstepsFolderLocation();
    final IPath newPath = newSubstepsFolderLocation();
    final Collection<SubstepsFolderChangedListener> listenersRequiringConfirmationAction = new ArrayList<SubstepsFolderChangedListener>();
    boolean cancelled = false;
    if (!previousPath.equals(newPath)) {
        for (final SubstepsFolderChangedListener folderChangeListener : substepsFolderChangeListeners) {
            final ConfirmationStatus confirmationStatus = handleFolderChanged(previousPath, newPath, folderChangeListener);
            if (ConfirmationStatus.YES.equals(confirmationStatus)) {
                listenersRequiringConfirmationAction.add(folderChangeListener);
            } else if (ConfirmationStatus.CANCEL.equals(confirmationStatus)) {
                listenersRequiringConfirmationAction.clear();
                cancelled = true;
                break;
            }
        }
    }
    for (final SubstepsFolderChangedListener folderChangedListener : listenersRequiringConfirmationAction) {
        folderChangedListener.onConfirmation(previousPath, newPath);
    }
    return !cancelled;
}
Example 26
Project: Curators-Workbench-master  File: PickOriginalLocationsPage.java View source code
public void checkStateChanged(CheckStateChangedEvent event) {
    // If the item is checked . . .
    if (event.getChecked()) {
        // uncheck all its parents and all descendants
        IFileStore f = (IFileStore) event.getElement();
        IPath fpath = new Path(f.toURI().getPath());
        for (Object checkedThing : fileTreeViewer.getCheckedElements()) {
            IFileStore thing = (IFileStore) checkedThing;
            IPath path = new Path(thing.toURI().getPath());
            if (fpath.equals(path)) {
                continue;
            } else if (fpath.isPrefixOf(path)) {
                fileTreeViewer.setChecked(checkedThing, false);
            } else if (path.isPrefixOf(fpath)) {
                fileTreeViewer.setChecked(checkedThing, false);
            }
        }
    }
}
Example 27
Project: cdo-master  File: AcoreDiagramEditorUtil.java View source code
/**
   * @generated
   */
public static String getUniqueFileName(IPath containerFullPath, String fileName, String extension) {
    if (containerFullPath == null) {
        //$NON-NLS-1$
        containerFullPath = new Path("");
    }
    if (fileName == null || fileName.trim().length() == 0) {
        //$NON-NLS-1$
        fileName = "default";
    }
    IPath filePath = containerFullPath.append(fileName);
    if (extension != null && !extension.equals(filePath.getFileExtension())) {
        filePath = filePath.addFileExtension(extension);
    }
    extension = filePath.getFileExtension();
    fileName = filePath.removeFileExtension().lastSegment();
    int i = 1;
    while (ResourcesPlugin.getWorkspace().getRoot().exists(filePath)) {
        i++;
        filePath = containerFullPath.append(fileName + i);
        if (extension != null) {
            filePath = filePath.addFileExtension(extension);
        }
    }
    return filePath.lastSegment();
}
Example 28
Project: LanguageBuddy-master  File: TestView.java View source code
public void setTestItem(TestItemType ti) {
    if (ti == null)
        return;
    try {
        savePictureWeights();
        IEditorPart editor = getSite().getPage().getActiveEditor();
        IContainer basePath = null;
        if (editor != null && editor.getEditorInput() != null && editor.getEditorInput() instanceof FileEditorInput) {
            FileEditorInput fei = (FileEditorInput) editor.getEditorInput();
            basePath = fei.getFile().getParent();
        }
        if (ti.isSetImg() && ti.getImg() != null) {
            if (basePath != null) {
                ImageLoader loader = new ImageLoader();
                try {
                    IFile imgFile = null;
                    try {
                        if (basePath instanceof IFolder) {
                            imgFile = ((IFolder) basePath).getFile(ti.getImg());
                        } else if (basePath instanceof IProject) {
                            imgFile = ((IProject) basePath).getFile(ti.getImg());
                        }
                    } catch (IllegalArgumentException e) {
                    }
                    ImageData[] imageDatas = null;
                    if (imgFile != null && imgFile.exists()) {
                        imageDatas = loader.load(imgFile.getRawLocation().toOSString());
                    } else {
                        //picture.setText(MessageUtil.getString("FileNotFound",
                        //        imgFile.toString()));
                        File file = new File(ti.getImg());
                        if (file.exists())
                            imageDatas = loader.load(ti.getImg());
                    }
                    if (imageDatas != null) {
                        horizontalSash.setWeights(pictureWeights);
                        //Image image = new Image(display, imageData[0]);
                        imageData = imageDatas[0];
                        setPicture();
                    } else {
                        picture.setImage(null);
                    }
                    if (nativeViewer.getTextWidget().isVisible())
                        picture.setToolTipText(ti.getImg());
                    else
                        picture.setToolTipText("");
                } catch (SWTException e) {
                    picture.setImage(null);
                    picture.setToolTipText(e.getLocalizedMessage());
                    horizontalSash.setWeights(NO_PICTURE_WEIGHTS);
                    LanguageTestPlugin.log(IStatus.WARNING, e.getLocalizedMessage(), e);
                }
            }
        } else {
            imageData = null;
            picture.setImage(null);
            picture.setToolTipText("");
            horizontalSash.setWeights(NO_PICTURE_WEIGHTS);
        }
        NativeLangType[] nLang = ti.getNativeLangArray();
        if (nLang.length > 0) {
            setText(NATIVE_ID, nLang[0].getStringValue(), null);
        } else {
            setText(NATIVE_ID, "", null);
        }
        ForeignLangType[] fLang = ti.getForeignLangArray();
        if (fLang.length > 0) {
            setText(FOREIGN_ID, fLang[0].getStringValue(), null);
        } else {
            setText(FOREIGN_ID, "", null);
        }
        if (ti.isSetSoundFile() && ti.getSoundFile().getStringValue() != null) {
            IPath path = new Path(ti.getSoundFile().getStringValue());
            if (path.isAbsolute() && path.toFile().exists()) {
                controlPanel.player().setFile(ti.getSoundFile().getStringValue());
            } else if (basePath != null && basePath.exists(path) && path.segmentCount() > 0) {
                IFile file = basePath.getFile(path);
                controlPanel.player().setFile(file.getRawLocation().toOSString());
            } else {
                controlPanel.player().setFile(null);
            }
            long start = 0;
            long end = -1;
            if (ti.getSoundFile().isSetStart()) {
                start = ti.getSoundFile().getStart();
            }
            if (ti.getSoundFile().isSetEnd()) {
                end = ti.getSoundFile().getEnd();
            }
            controlPanel.player().seek(start);
            if (end > start)
                controlPanel.player().stopAfter(end - start);
        } else
            controlPanel.player().setFile(null);
        nativeViewer.refresh();
        foreignViewer.refresh();
        //nativeViewer.getTextWidget().redraw();
        picture.redraw();
    } catch (org.apache.xmlbeans.XmlRuntimeException xmlE) {
        LanguageTestPlugin.log(IStatus.WARNING, xmlE.getLocalizedMessage(), xmlE);
    }
}
Example 29
Project: arquillian-eclipse-master  File: ArquillianSearchEngine.java View source code
private static List<File> getDeploymentArchives(IType type, boolean force) {
    List<File> archives = new ArrayList<File>();
    if (type == null || !hasDeploymentMethod(type)) {
        return archives;
    }
    Bundle bundle = Platform.getBundle(ArquillianCoreActivator.PLUGIN_ID);
    if (bundle == null) {
        ArquillianCoreActivator.log("The " + ArquillianCoreActivator.PLUGIN_ID + "bundle is invalid.");
        return archives;
    }
    IPath stateLocation = InternalPlatform.getDefault().getStateLocation(bundle, true);
    String projectName = null;
    ICompilationUnit cu = type.getCompilationUnit();
    IJavaProject javaProject = null;
    if (cu != null) {
        IResource resource = cu.getResource();
        if (resource != null) {
            //				try {
            //		            resource.deleteMarkers(ArquillianConstants.MARKER_RESOURCE_ID, false, IResource.DEPTH_INFINITE);
            //		        } catch (CoreException e) {
            //		            ArquillianCoreActivator.log(e);
            //		        }
            IProject project = resource.getProject();
            if (project != null) {
                projectName = project.getName();
                javaProject = JavaCore.create(project);
            }
        }
    }
    if (projectName == null) {
        ArquillianCoreActivator.log("Cannot find any project for the " + type.getElementName() + "type.");
        return archives;
    }
    IPath location = stateLocation.append(projectName);
    location = location.append("arquillianDeploymentArchives");
    String fqn = type.getFullyQualifiedName();
    fqn = fqn.replace(".", "/");
    location = location.append(fqn);
    try {
        List<IMethodBinding> deploymentMethods = getDeploymentMethods(type);
        for (IMethodBinding deploymentMethod : deploymentMethods) {
            String name = deploymentMethod.getName();
            IPath methodLocation = location.append(name);
            File file = methodLocation.toFile();
            if (file.exists()) {
                if (force) {
                    if (!ArquillianUtility.deleteFile(file)) {
                        ArquillianCoreActivator.log("Cannot delete " + file.getAbsolutePath());
                    }
                }
            }
            if (!file.exists()) {
                createArchive(javaProject, type, deploymentMethod, file);
            }
            if (file.isDirectory()) {
                File[] files = file.listFiles(new FileFilter() {

                    @Override
                    public boolean accept(File pathname) {
                        return pathname.isFile() && pathname.getName().startsWith("archive");
                    }
                });
                if (files != null && files.length > 0 && files[0].isFile()) {
                    archives.add(files[0]);
                }
            }
        }
    } catch (JavaModelException e) {
        ArquillianCoreActivator.log(e);
    }
    return archives;
}
Example 30
Project: eclipse-integration-commons-master  File: QuickSearchDialog.java View source code
@Override
public void update(ViewerCell cell) {
    LineItem item = (LineItem) cell.getElement();
    if (item != null) {
        IPath path = item.getFile().getFullPath();
        String name = path.lastSegment();
        String dir = path.removeLastSegments(1).toString();
        cell.setText(name + " - " + dir);
        StyleRange[] styleRanges = new StyleRange[] { new StyleRange(name.length(), dir.length() + 3, GREY, null) };
        cell.setStyleRanges(styleRanges);
    } else {
        cell.setText("");
        cell.setStyleRanges(null);
    }
    cell.setImage(getBlankImage());
    super.update(cell);
}
Example 31
Project: rinzo-xml-editor-master  File: BindingFilesWizardPage.java View source code
@Override
public void widgetSelected(SelectionEvent e) {
    // ElementTreeSelectionDialog selectionDialog = new
    // ElementTreeSelectionDialog(null, new
    // WorkbenchLabelProvider(), new WorkbenchContentProvider());
    // selectionDialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
    // selectionDialog.open();
    FilteredElementTreeSelectionDialog dialog = new FilteredElementTreeSelectionDialog(null, new WorkbenchLabelProvider(), new WorkbenchContentProvider());
    dialog.setTitle("Binding files selection");
    dialog.setMessage("Select the files to be used as JAXB binding files.");
    dialog.setInitialFilter("*.xjb");
    dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
    dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
    ArrayList<IResource> usedJars = new ArrayList<IResource>();
    dialog.addFilter(new ArchiveFileFilter(usedJars, true, true));
    if (dialog.open() == Window.OK) {
        Object[] elements = dialog.getResult();
        IPath[] res = new IPath[elements.length];
        for (int i = 0; i < res.length; i++) {
            IResource elem = (IResource) elements[i];
            files.add(elem.getLocation().toOSString());
        }
    }
    listViewer.refresh(false);
}
Example 32
Project: felinx-master  File: BundleBuilder.java View source code
public ActionResult createBundle(IProject project, IProgressMonitor monitor) {
    ActionResult result = new ActionResult("Creating bundle...");
    try {
        IJavaProject javaProject = JavaCore.create(project);
        final IFolder generated = javaProject.getProject().getFolder(new Path("generated"));
        if (!generated.exists()) {
            generated.create(true, true, monitor);
        }
        IPath location = getJarPath(project);
        IFolder metaFolder = javaProject.getProject().getFolder("META-INF");
        IFile file = metaFolder.getFile("MANIFEST.MF");
        Manifest manifest = new Manifest(file.getContents());
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        JarOutputStream target = new JarOutputStream(new FileOutputStream(location.toOSString()), manifest);
        // add(new File("inputDirectory"), target);
        // // http://stackoverflow.com/questions/3273022/getting-all-classes-from-the-current-workspace-in-eclipse
        // System.out.println("Class files:");
        // for (IPackageFragment packageFragment : javaProject.getPackageFragments()) {
        // // Package fragments include all packages in the class path. We will only look at the package from the source folder.
        // // K_BINARY would include also included JARS, e.g. rt.jar
        // if (packageFragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
        // System.out.println("Handling packageFragment " + packageFragment.getElementName() +" "+ packageFragment.getPath() + " ");
        // for (final IJavaElement element : packageFragment.getChildren()) {
        // System.out.println(">> "+element.getPath());
        // }
        // }
        // }
        System.out.println("Adding classes...");
        File projectRoot = project.getLocation().toFile();
        File classesFolder = getClassesFolder(javaProject);
        //do not add bin or classes folder, but directly its content
        addFiles(classesFolder, classesFolder, target);
        final IFolder lib = javaProject.getProject().getFolder(new Path("lib"));
        if (lib.exists()) {
            monitor.setTaskName("Adding libraries...");
            addFiles(new File(lib.getLocationURI()), projectRoot, target);
        }
        target.close();
        File jar = new File(location.toOSString());
        System.out.println("Performing iPOJO manipulation...");
        IPojoManipulator man = new IPojoManipulator();
        man.setInput(jar);
        System.out.println("Executing...");
        man.execute();
        System.out.println("Installing... ");
        String symbolicName = null;
        String bundleVersion = null;
        Map<Object, Object> bundleSymbolicNameAtrrs = manifest.getMainAttributes();
        for (Object obj : bundleSymbolicNameAtrrs.keySet()) {
            if (obj.toString().equals("Bundle-SymbolicName")) {
                symbolicName = bundleSymbolicNameAtrrs.get(obj).toString();
            } else if (obj.toString().equals("Bundle-Version")) {
                bundleVersion = bundleSymbolicNameAtrrs.get(obj).toString();
            }
            if (symbolicName != null && bundleVersion != null) {
                break;
            }
        }
        Activator.updateBundle(symbolicName, bundleVersion, jar);
    } catch (Throwable e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        result.setError(e);
    }
    return result;
}
Example 33
Project: WS171-development-master  File: AndroidLaunchController.java View source code
/**
     * Syncs the application on the device/emulator.
     *
     * @param launchInfo The Launch information object.
     * @param device the device on which to sync the application
     * @return true if the install succeeded.
     */
private boolean doSyncApp(DelayedLaunchInfo launchInfo, IDevice device) {
    SyncService sync = device.getSyncService();
    if (sync != null) {
        IPath path = launchInfo.getPackageFile().getLocation();
        String message = String.format("Uploading %1$s onto device '%2$s'", path.lastSegment(), device.getSerialNumber());
        AdtPlugin.printToConsole(launchInfo.getProject(), message);
        String osLocalPath = path.toOSString();
        String apkName = launchInfo.getPackageFile().getName();
        //$NON-NLS-1$
        String remotePath = "/data/local/tmp/" + apkName;
        SyncResult result = sync.pushFile(osLocalPath, remotePath, SyncService.getNullProgressMonitor());
        if (result.getCode() != SyncService.RESULT_OK) {
            String msg = String.format("Failed to upload %1$s on '%2$s': %3$s", apkName, device.getSerialNumber(), result.getMessage());
            AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg);
            return false;
        }
        // Now that the package is uploaded, we can install it properly.
        // This will check that there isn't another apk declaring the same package, or
        // that another install used a different key.
        boolean installResult = installPackage(launchInfo, remotePath, device);
        // now we delete the app we sync'ed
        try {
            device.executeShellCommand("rm " + remotePath, new //$NON-NLS-1$
            MultiLineReceiver() {

                @Override
                public void processNewLines(String[] lines) {
                // pass
                }

                public boolean isCancelled() {
                    return false;
                }
            });
        } catch (IOException e) {
            AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format("Failed to delete temporary package: %1$s", e.getMessage()));
            return false;
        }
        // if the installation succeeded, we register it.
        if (installResult) {
            ApkInstallManager.getInstance().registerInstallation(launchInfo.getProject(), device);
        }
        return installResult;
    }
    String msg = String.format("Failed to upload %1$s on device '%2$s': Unable to open sync connection!", launchInfo.getPackageFile().getName(), device.getSerialNumber());
    AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg);
    return false;
}
Example 34
Project: Disco-Build-System-master  File: FileGroupPattern.java View source code
/*-------------------------------------------------------------------------------------*/
/**
	 * Given something that represents a file within the Eclipse IDE, return the full OS-specific
	 * path to that file.
	 * 
	 * @param fileObject The object that represents a file.
	 * @return The full OS-specific path to the file, or null if this is not a file.
	 */
private String getPathOf(Object fileObject) {
    /* all IFile objects are files (not directories) */
    if (fileObject instanceof IFile) {
        IFile file = (IFile) fileObject;
        return file.getFullPath().toOSString();
    } else /* 
		 * Anything that adapts to IResource might be a file, but we need to double check
		 * that it's not a directory.
		 */
    if (fileObject instanceof IAdaptable) {
        Object iResource = ((IAdaptable) fileObject).getAdapter(IResource.class);
        if (iResource != null) {
            IPath location = ((IResource) iResource).getLocation();
            if ((location != null) && (location.toFile().isFile())) {
                return location.toOSString();
            }
        }
    }
    return null;
}
Example 35
Project: yarn-comment-master  File: RunOnHadoopWizard.java View source code
/**
   * Performs any actions appropriate in response to the user having pressed
   * the Finish button, or refuse if finishing now is not permitted.
   */
/* @inheritDoc */
@Override
public boolean performFinish() {
    /*
     * Create a new location or get an existing one
     */
    HadoopServer location = null;
    if (mainPage.createNew.getSelection()) {
        location = createNewPage.performFinish();
    } else if (mainPage.table.getSelection().length == 1) {
        location = (HadoopServer) mainPage.table.getSelection()[0].getData();
    }
    if (location == null)
        return false;
    /*
     * Get the base directory of the plug-in for storing configurations and
     * JARs
     */
    File baseDir = Activator.getDefault().getStateLocation().toFile();
    // Package the Job into a JAR
    File jarFile = JarModule.createJarPackage(resource);
    if (jarFile == null) {
        ErrorMessageDialog.display("Run on Hadoop", "Unable to create or locate the JAR file for the Job");
        return false;
    }
    /*
     * Generate a temporary Hadoop configuration directory and add it to the
     * classpath of the launch configuration
     */
    File confDir;
    try {
        confDir = File.createTempFile("hadoop-conf-", "", baseDir);
        confDir.delete();
        confDir.mkdirs();
        if (!confDir.isDirectory()) {
            ErrorMessageDialog.display("Run on Hadoop", "Cannot create temporary directory: " + confDir);
            return false;
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return false;
    }
    // Prepare the Hadoop configuration
    JobConf conf = new JobConf(location.getConfiguration());
    conf.setJar(jarFile.getAbsolutePath());
    // Write it to the disk file
    try {
        // File confFile = File.createTempFile("core-site-", ".xml",
        // confDir);
        File confFile = new File(confDir, "core-site.xml");
        FileOutputStream fos = new FileOutputStream(confFile);
        try {
            conf.writeXml(fos);
            fos.close();
            fos = null;
        } finally {
            IOUtils.closeStream(fos);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return false;
    }
    // Setup the Launch class path
    List<String> classPath;
    try {
        classPath = iConf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, new ArrayList());
        IPath confIPath = new Path(confDir.getAbsolutePath());
        IRuntimeClasspathEntry cpEntry = JavaRuntime.newArchiveRuntimeClasspathEntry(confIPath);
        classPath.add(0, cpEntry.getMemento());
        iConf.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classPath);
        iConf.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, mainPage.argumentsText.getText());
    } catch (CoreException e) {
        e.printStackTrace();
        return false;
    }
    // location.runResource(resource, progressMonitor);
    return true;
}
Example 36
Project: eclipse-license-management-tools-master  File: LicensesPreferencePage.java View source code
private void createTable(Composite parent) {
    tree = new TreeViewer(parent, SWT.SINGLE);
    tree.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    tree.setContentProvider(new ITreeContentProvider() {

        @Override
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }

        @Override
        public void dispose() {
        }

        @Override
        public Object[] getElements(Object inputElement) {
            return (ILicensedProduct[]) inputElement;
        }

        @Override
        public Object[] getChildren(Object parentElement) {
            ILicensedProduct product = (ILicensedProduct) parentElement;
            LicenseKey[] licenseKeys = LicensingUtils.getLicenseKeys();
            List<LicenseKey> children = new ArrayList<LicenseKey>();
            for (LicenseKey licenseKey : licenseKeys) {
                if (product.getId().equals(licenseKey.getProductId())) {
                    children.add(licenseKey);
                }
            }
            return children.toArray();
        }

        @Override
        public Object getParent(Object element) {
            if (element instanceof LicenseKey) {
                LicenseKey licenseKey = (LicenseKey) element;
                return LicensedProducts.getLicensedProduct(licenseKey.getProductId());
            }
            return null;
        }

        @Override
        public boolean hasChildren(Object element) {
            return element instanceof ILicensedProduct;
        }
    });
    tree.setLabelProvider(new LabelProvider() {

        @Override
        public String getText(Object element) {
            if (element instanceof ILicensedProduct) {
                ILicensedProduct product = (ILicensedProduct) element;
                return String.format("%s %s", product.getName(), product.getVersion());
            }
            if (element instanceof LicenseKey) {
                LicenseKey licenseKey = (LicenseKey) element;
                StringBuilder builder = new StringBuilder(licenseKey.getType());
                VersionRange versions = licenseKey.getProductVersions();
                if (versions != null) {
                    builder.append(" for versions ").append(versions);
                }
                String expirationDate = licenseKey.getExpirationDate();
                if (expirationDate != null) {
                    builder.append(", Expires on ").append(expirationDate);
                }
                return builder.toString();
            }
            return super.getText(element);
        }

        @Override
        public Image getImage(Object element) {
            String file = "product.png";
            if (element instanceof LicenseKey) {
                file = "key.png";
            }
            Bundle bundle = Platform.getBundle(LicensingUI.PLUGIN_ID);
            IPath path = new Path("icons/" + file);
            URL url = FileLocator.find(bundle, path, null);
            ImageDescriptor desc = ImageDescriptor.createFromURL(url);
            return desc.createImage();
        }
    });
    tree.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            Object element = ((IStructuredSelection) event.getSelection()).getFirstElement();
            removeButton.setEnabled(element != null && element instanceof LicenseKey);
            detailsButton.setEnabled(element != null);
        }
    });
    refreshTable();
}
Example 37
Project: earthsci-master  File: ChooseWorkspaceWithSettingsDialog.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.internal.ide.ChooseWorkspaceDialog#okPressed()
	 */
protected void okPressed() {
    Iterator settingsIterator = selectedSettings.iterator();
    MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, IDEWorkbenchMessages.ChooseWorkspaceWithSettingsDialog_ProblemsTransferTitle, null);
    IPath path = new Path(getWorkspaceLocation());
    String[] selectionIDs = new String[selectedSettings.size()];
    int index = 0;
    while (settingsIterator.hasNext()) {
        IConfigurationElement elem = (IConfigurationElement) settingsIterator.next();
        result.add(transferSettings(elem, path));
        selectionIDs[index] = elem.getAttribute(ATT_ID);
    }
    if (result.getSeverity() != IStatus.OK) {
        ErrorDialog.openError(getShell(), IDEWorkbenchMessages.ChooseWorkspaceWithSettingsDialog_TransferFailedMessage, IDEWorkbenchMessages.ChooseWorkspaceWithSettingsDialog_SaveSettingsFailed, result);
        return;
    }
    saveSettings(selectionIDs);
    super.okPressed();
}
Example 38
Project: codemap-master  File: NewCodemapCreationWizardPage.java View source code
@SuppressWarnings("unchecked")
private IFolder chooseFolder(String title, String message, IPath initialPath) {
    Class[] acceptedClasses = new Class[] { IContainer.class };
    ViewerFilter filter = new TypedViewerFilter(acceptedClasses, null);
    ILabelProvider lp = new WorkbenchLabelProvider();
    ITreeContentProvider cp = new WorkbenchContentProvider();
    ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), lp, cp);
    dialog.setTitle(title);
    dialog.setMessage(message);
    dialog.addFilter(filter);
    dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
    dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
    if (dialog.open() == Window.OK) {
        return (IFolder) dialog.getFirstResult();
    }
    return null;
}
Example 39
Project: swtbot-master  File: LogicEditor.java View source code
protected boolean performSaveAs() {
    SaveAsDialog dialog = new SaveAsDialog(getSite().getWorkbenchWindow().getShell());
    dialog.setOriginalFile(((IFileEditorInput) getEditorInput()).getFile());
    dialog.open();
    IPath path = dialog.getResult();
    if (path == null)
        return false;
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final IFile file = workspace.getRoot().getFile(path);
    if (!file.exists()) {
        WorkspaceModifyOperation op = new WorkspaceModifyOperation() {

            public void execute(final IProgressMonitor monitor) {
                saveProperties();
                try {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    writeToOutputStream(out);
                    file.create(new ByteArrayInputStream(out.toByteArray()), true, monitor);
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        try {
            new ProgressMonitorDialog(getSite().getWorkbenchWindow().getShell()).run(false, true, op);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    try {
        superSetInput(new FileEditorInput(file));
        getCommandStack().markSaveLocation();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}