org.eclipse.core.runtime.FileLocator Java Examples

The following examples show how to use org.eclipse.core.runtime.FileLocator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WorkspacePreferences.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static String getCurrentGamaStampString() {
	String gamaStamp = null;
	try {
		final URL tmpURL = new URL("platform:/plugin/msi.gama.models/models/");
		final URL resolvedFileURL = FileLocator.toFileURL(tmpURL);
		// We need to use the 3-arg constructor of URI in order to properly escape file system chars
		final URI resolvedURI = new URI(resolvedFileURL.getProtocol(), resolvedFileURL.getPath(), null).normalize();
		final File modelsRep = new File(resolvedURI);

		// loading file from URL Path is not a good idea. There are some bugs
		// File modelsRep = new File(urlRep.getPath());

		final long time = modelsRep.lastModified();
		gamaStamp = ".built_in_models_" + time;
		DEBUG.OUT(
			">GAMA version " + Platform.getProduct().getDefiningBundle().getVersion().toString() + " loading...");
		DEBUG.OUT(">GAMA models library version: " + gamaStamp);
	} catch (final IOException | URISyntaxException e) {
		e.printStackTrace();
	}
	return gamaStamp;
}
 
Example #2
Source File: MovableColumnEventsEditorTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Test Class setup
 */
@BeforeClass
public static void init() {
    SWTBotUtils.initialize();

    /* set up test trace */
    URL location = FileLocator.find(TmfCoreTestPlugin.getDefault().getBundle(), new Path(COLUMN_TRACE_PATH), null);
    URI uri;
    try {
        uri = FileLocator.toFileURL(location).toURI();
        fTestFile = new File(uri);
    } catch (URISyntaxException | IOException e) {
        fail(e.getMessage());
    }

    assumeTrue(fTestFile.exists());

    /* Set up for swtbot */
    SWTBotPreferences.TIMEOUT = 20000; /* 20 second timeout */
    fLogger.removeAllAppenders();
    fLogger.addAppender(new ConsoleAppender(new SimpleLayout(), ConsoleAppender.SYSTEM_OUT));
    fBot = new SWTWorkbenchBot();

    /* Finish waiting for eclipse to load */
    WaitUtils.waitForJobs();
}
 
Example #3
Source File: Utils.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Provisions a project that's part of the "testProjects"
 * @param folderName the folderName under "testProjects" to provision from
 * @return the provisioned project
 * @throws CoreException
 * @throws IOException
 */
public static IProject provisionTestProject(String folderName) throws CoreException, IOException {
	URL url = FileLocator.find(Platform.getBundle("org.eclipse.wildwebdeveloper.tests"),
			Path.fromPortableString("testProjects/" + folderName), null);
	url = FileLocator.toFileURL(url);
	File folder = new File(url.getFile());
	if (folder.exists()) {
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("testProject" + System.nanoTime());
		project.create(null);
		project.open(null);
		java.nio.file.Path sourceFolder = folder.toPath();
		java.nio.file.Path destFolder = project.getLocation().toFile().toPath();

		Files.walk(sourceFolder).forEach(source -> {
			try {
				Files.copy(source, destFolder.resolve(sourceFolder.relativize(source)), StandardCopyOption.REPLACE_EXISTING);
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
		project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
		return project;
	}
	return null;
}
 
Example #4
Source File: ZoomOutToolEntry.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private static ImageDescriptor findIconImageDescriptor(String iconPath) {
    String pluginId = "org.eclipse.gmf.runtime.diagram.ui.providers";
    Bundle bundle = Platform.getBundle(pluginId);
    try
    {
        if (iconPath != null) {
            URL fullPathString = FileLocator.find(bundle, new Path(iconPath), null);
            fullPathString = fullPathString != null ? fullPathString : new URL(iconPath);
            if (fullPathString != null) {
                return ImageDescriptor.createFromURL(fullPathString);
            }
        }
    }
    catch (MalformedURLException e)
    {
        Trace.catching(DiagramUIPlugin.getInstance(),
            DiagramUIDebugOptions.EXCEPTIONS_CATCHING,
            DefaultPaletteProvider.class, e.getLocalizedMessage(), e); 
        Log.error(DiagramUIPlugin.getInstance(),
            DiagramUIStatusCodes.RESOURCE_FAILURE, e.getMessage(), e);
    }
    
    return null;
}
 
Example #5
Source File: ManifestParserTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testServicesWithSpacesManifest() throws Exception {
	String manifestName = "servicesWithSpaces.yml"; //$NON-NLS-1$

	URL entry = ServerTestsActivator.getContext().getBundle().getEntry(MANIFEST_LOCATION);
	File manifestFile = new File(FileLocator.toFileURL(entry).getPath().concat(manifestName));

	InputStream inputStream = new FileInputStream(manifestFile);
	ManifestParseTree manifest = parse(inputStream);

	ManifestParseTree application = manifest.get("applications").get(0); //$NON-NLS-1$
	ManifestParseTree services = application.get("services"); //$NON-NLS-1$

	assertEquals(2, services.getChildren().size());

	String service = services.get(0).getValue();
	assertEquals("Redis Cloud-fo service", service); //$NON-NLS-1$

	service = services.get(1).getValue();
	assertEquals("Redis-two", service); //$NON-NLS-1$
}
 
Example #6
Source File: JSTSLanguageServer.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
public JSTSLanguageServer() {
	List<String> commands = new ArrayList<>();
	commands.add(InitializeLaunchConfigurations.getNodeJsLocation());
	try {
		URL url = FileLocator.toFileURL(getClass().getResource("/node_modules/typescript-language-server/lib/cli.js"));
		URL tsServer = FileLocator.toFileURL(getClass().getResource("/node_modules/typescript/lib/tsserver.js"));
		commands.add(new File(url.getPath()).getAbsolutePath());
		commands.add("--stdio");
		commands.add("--tsserver-path");
		commands.add(new File(tsServer.getPath()).getAbsolutePath());
		URL nodeDependencies = FileLocator.toFileURL(getClass().getResource("/"));
		setCommands(commands);
		setWorkingDirectory(nodeDependencies.getPath()); //Required for typescript-eslint-language-service to find it's dependencies

	} catch (IOException e) {
		Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.getDefault().getBundle().getSymbolicName(), e.getMessage(), e));
	}
}
 
Example #7
Source File: ImporterFactory.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
public void configure(final IConfigurationElement desc) {
    name = desc.getAttribute("inputName");
    filterExtension = desc.getAttribute("filterExtensions");
    description = desc.getAttribute("description");
    priorityDisplay = Integer.valueOf(desc.getAttribute("priorityDisplay"));
    final String menuIcon = desc.getAttribute("menuIcon");
    try {
        if (menuIcon != null) {
            final Bundle b = Platform.getBundle(desc.getContributor().getName());
            final URL iconURL = b.getResource(menuIcon);
            final File imageFile = new File(FileLocator.toFileURL(iconURL).getFile());
            try (final FileInputStream inputStream = new FileInputStream(imageFile);) {
                descriptionImage = new Image(Display.getDefault(), inputStream);
            }
        }
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
}
 
Example #8
Source File: ZoomInToolEntry.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private static ImageDescriptor findIconImageDescriptor(String iconPath) {
	String pluginId = "org.eclipse.gmf.runtime.diagram.ui.providers";
	Bundle bundle = Platform.getBundle(pluginId);
	try
	{
		if (iconPath != null) {
			URL fullPathString = FileLocator.find(bundle, new Path(iconPath), null);
			fullPathString = fullPathString != null ? fullPathString : new URL(iconPath);
			if (fullPathString != null) {
				return ImageDescriptor.createFromURL(fullPathString);
			}
		}
	}
	catch (MalformedURLException e)
	{
		Trace.catching(DiagramUIPlugin.getInstance(),
				DiagramUIDebugOptions.EXCEPTIONS_CATCHING,
				DefaultPaletteProvider.class, e.getLocalizedMessage(), e); 
		Log.error(DiagramUIPlugin.getInstance(),
				DiagramUIStatusCodes.RESOURCE_FAILURE, e.getMessage(), e);
	}

	return null;
}
 
Example #9
Source File: ImportFileAction.java    From ice with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Constructor
 */
public ImportFileAction(IWorkbenchWindow window) {

	// Set the action ID, Menu Text, and a tool tip.
	workbenchWindow = window;

	// Set the text properties.
	setId(ID);
	setText("&Import a file");
	setToolTipText("Import a file into ICE's "
			+ "project space for use by your items.");

	// Find the client bundle
	Bundle bundle = FrameworkUtil.getBundle(ImportFileAction.class);
	Path imagePath = new Path("icons"
			+ System.getProperty("file.separator") + "importArrow.gif");
	URL imageURL = FileLocator.find(bundle, imagePath, null);
	setImageDescriptor(ImageDescriptor.createFromURL(imageURL));

	return;
}
 
Example #10
Source File: ManifestParseTreeTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testToJSONAgainsCorrectManifests() throws Exception {
	URL entry = ServerTestsActivator.getContext().getBundle().getEntry(CORRECT_MANIFEST_LOCATION);
	File manifestSource = new File(FileLocator.toFileURL(entry).getPath());

	File[] manifests = manifestSource.listFiles(new FilenameFilter() {

		public boolean accept(File dir, String name) {
			return name.toLowerCase().endsWith(".yml"); //$NON-NLS-1$
		}
	});

	for (File manifestFile : manifests) {
		InputStream inputStream = new FileInputStream(manifestFile);

		/* export the manifest to JSON - pass if no exceptions occurred */
		exportManifestJSON(inputStream);
	}
}
 
Example #11
Source File: ImportLegacyBDMIT.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_import_a_legacy_bdm_and_convert_it_to_xml_file() throws Exception {
    final ImportBosArchiveOperation operation = new ImportBosArchiveOperation(repositoryAccessor);
    operation.setCurrentRepository(repositoryAccessor.getCurrentRepository());
    operation.setArchiveFile(
            new File(FileLocator.toFileURL(ImportLegacyBDMIT.class.getResource("/legacyBDM.bos")).getFile())
                    .getAbsolutePath());
    operation.run(Repository.NULL_PROGRESS_MONITOR);

    StatusAssert.assertThat(operation.getStatus()).hasSeverity(IStatus.INFO);
    assertThat(defStore.getResource().getFile(BusinessObjectModelFileStore.ZIP_FILENAME).getLocation().toFile().exists())
            .isFalse();
    assertThat(defStore.getChild(BusinessObjectModelFileStore.BOM_FILENAME, true)).isNotNull();
    final BusinessObjectModel model = defStore.getChild(BusinessObjectModelFileStore.BOM_FILENAME, true).getContent();
    assertThat(model).isNotNull();
    assertThat(model.getBusinessObjectsClassNames()).contains("com.bonita.lr.model.VacationRequest");

    assertThat(defStore.getChildren()).hasSize(1);
    assertThat(depStore.getChild(BusinessObjectModelFileStore.BDM_JAR_NAME, true)).isNotNull();
}
 
Example #12
Source File: BuiltInConfigurationType.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected URL resolveLocation(ICheckConfiguration checkConfiguration) {

  String contributorName = checkConfiguration.getAdditionalData().get(CONTRIBUTOR_KEY);

  Bundle contributor = Platform.getBundle(contributorName);
  URL locationUrl = FileLocator.find(contributor, new Path(checkConfiguration.getLocation()),
          null);

  // suggested by https://sourceforge.net/p/eclipse-cs/bugs/410/
  if (locationUrl == null) {
    locationUrl = contributor.getResource(checkConfiguration.getLocation());
  }

  return locationUrl;
}
 
Example #13
Source File: Activator.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Return a path to a file relative to this plugin's base directory
 *
 * @param relativePath
 *            The path relative to the plugin's root directory
 * @return The path corresponding to the relative path in parameter
 */
public static @NonNull IPath getAbsoluteFilePath(String relativePath) {
    Activator plugin = Activator.getDefault();
    if (plugin == null) {
        /*
         * Shouldn't happen but at least throw something to get the test to
         * fail early
         */
        throw new IllegalStateException();
    }
    URL location = FileLocator.find(plugin.getBundle(), new Path(relativePath), null);
    try {
        return new Path(FileLocator.toFileURL(location).getPath());
    } catch (IOException e) {
        throw new IllegalStateException();
    }
}
 
Example #14
Source File: UIUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return Report Designer UI plugin installation directory as OS string.
 */
public static String getFragmentDirectory( )
{
	Bundle bundle = Platform.getBundle( IResourceLocator.FRAGMENT_RESOURCE_HOST );
	if ( bundle == null )
	{
		return null;
	}
	URL url = bundle.getEntry( "/" ); //$NON-NLS-1$
	if ( url == null )
	{
		return null;
	}
	String directory = null;
	try
	{
		directory = FileLocator.resolve( url ).getPath( );
	}
	catch ( IOException e )
	{
		logger.log( Level.SEVERE, e.getMessage( ), e );
	}
	return directory;
}
 
Example #15
Source File: CommonFunction.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 当程序开始运行时,检查 qa 插件是否存在,如果不存在,则不执行任何操作,如果存在,则检查 configuration\net.heartsome.cat.ts.ui\hunspell 
 * 下面是否有 hunspell 运行所需要的词典以及运行函数库。如果没有,则需要从 qa 插件中进行获取,并且解压到上述目录下。
 * robert	2013-02-28
 */
public static void unZipHunspellDics() throws Exception{
	Bundle bundle = Platform.getBundle("net.heartsome.cat.ts.ui.qa");
	if (bundle == null) {
		return;
	}
	
	// 查看解压的 hunspell词典 文件夹是否存在
	String configHunspllDicFolder = Platform.getConfigurationLocation().getURL().getPath() 
			+ "net.heartsome.cat.ts.ui" + System.getProperty("file.separator") + "hunspell"
			+ System.getProperty("file.separator") + "hunspellDictionaries";
	if (!new File(configHunspllDicFolder).exists()) {
		new File(configHunspllDicFolder).mkdirs();
		String hunspellDicZipPath = FileLocator.toFileURL(bundle.getEntry("hunspell/hunspellDictionaries.zip")).getPath();
		upZipFile(hunspellDicZipPath, configHunspllDicFolder);
	}
}
 
Example #16
Source File: BundleUtil.java    From sarl with Apache License 2.0 6 votes vote down vote up
private static IPath getSourceRootProjectFolderPath(Bundle bundle) {
	for (final String srcFolder : SRC_FOLDERS) {
		final IPath relPath = Path.fromPortableString(srcFolder);
		final URL srcFolderURL = FileLocator.find(bundle, relPath, null);
		if (srcFolderURL != null) {
			try {
				final URL srcFolderFileURL = FileLocator.toFileURL(srcFolderURL);
				IPath absPath = new Path(srcFolderFileURL.getPath()).makeAbsolute();
				absPath = absPath.removeLastSegments(relPath.segmentCount());
				return absPath;
			} catch (IOException e) {
				//
			}
		}
	}
	return null;
}
 
Example #17
Source File: TransferTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testImportWithPost() throws CoreException, IOException, SAXException {
	//create a directory to upload to
	String directoryPath = "sample/testImportWithPost/path" + System.currentTimeMillis();
	createDirectory(directoryPath);

	//start the import
	URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/client.zip");
	File source = new File(FileLocator.toFileURL(entry).getPath());
	long length = source.length();
	InputStream in = new BufferedInputStream(new FileInputStream(source));
	PostMethodWebRequest request = new PostMethodWebRequest(getImportRequestPath(directoryPath), in, "application/zip");
	request.setHeaderField("Content-Length", "" + length);
	request.setHeaderField("Content-Type", "application/zip");
	setAuthentication(request);
	WebResponse postResponse = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_CREATED, postResponse.getResponseCode());
	String location = postResponse.getHeaderField("Location");
	assertNotNull(location);
	String type = postResponse.getHeaderField("Content-Type");
	assertNotNull(type);
	assertTrue(type.contains("text/html"));

	//assert the file has been unzipped in the workspace
	assertTrue(checkFileExists(directoryPath + "/org.eclipse.e4.webide/static/js/navigate-tree/navigate-tree.js"));
}
 
Example #18
Source File: ReflectivityViewPart.java    From ice with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void createPartControl(Composite parent) {

	try {
		Bundle bundle = FrameworkUtil.getBundle(this.getClass());
		URL picBundleURL = bundle.getEntry("reflectivityExample.png");
		URL picFileURL = FileLocator.toFileURL(picBundleURL);
		File picture = new File(picFileURL.getFile());

		Image image = new Image(Display.getCurrent(),picture.getAbsolutePath());
		Label label = new Label(parent, SWT.NONE);
		label.setImage(image);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		logger.error(getClass().getName() + " Exception!",e);
	}


}
 
Example #19
Source File: TestTokenDispatcher.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private ProcessDiagramEditor importBos(final String processResourceName)
        throws IOException, InvocationTargetException, InterruptedException {
    final ImportBosArchiveOperation op = new ImportBosArchiveOperation(repositoryAccessor);
    final URL fileURL = FileLocator.toFileURL(TestTokenDispatcher.class.getResource(processResourceName));
    op.setArchiveFile(FileLocator.toFileURL(fileURL).getFile());
    op.setCurrentRepository(repositoryAccessor.getCurrentRepository());
    op.run(new NullProgressMonitor());
    ProcessDiagramEditor processEditor = null;
    for (final IRepositoryFileStore f : op.getFileStoresToOpen()) {
        final IWorkbenchPart iWorkbenchPart = f.open();
        if (iWorkbenchPart instanceof ProcessDiagramEditor) {
            processEditor = (ProcessDiagramEditor) iWorkbenchPart;

        }
    }
    return processEditor;
}
 
Example #20
Source File: TmfCoreTestPlugin.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Return a path to a file relative to this plugin's base directory
 *
 * @param relativePath
 *            The path relative to the plugin's root directory
 * @return The path corresponding to the relative path in parameter
 */
public static @NonNull IPath getAbsoluteFilePath(String relativePath) {
    Plugin plugin = TmfCoreTestPlugin.getDefault();
    if (plugin == null) {
        /*
         * Shouldn't happen but at least throw something to get the test to
         * fail early
         */
        throw new IllegalStateException();
    }
    URL location = FileLocator.find(plugin.getBundle(), new Path(relativePath), null);
    try {
        return new Path(FileLocator.toFileURL(location).getPath());
    } catch (IOException e) {
        throw new IllegalStateException();
    }
}
 
Example #21
Source File: ExportToTsvTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test Class setup
 */
@BeforeClass
public static void beforeClass() {
    SWTBotUtils.initialize();

    /* set up test trace */
    URL location = FileLocator.find(TmfCoreTestPlugin.getDefault().getBundle(), new Path(TRACE_PATH), null);
    URI uri;
    try {
        uri = FileLocator.toFileURL(location).toURI();
        fTestFile = new File(uri);
    } catch (URISyntaxException | IOException e) {
        fail(e.getMessage());
    }

    File testFile = fTestFile;
    assertNotNull(testFile);
    assumeTrue(testFile.exists());

    /* Set up for swtbot */
    SWTBotPreferences.TIMEOUT = TIMEOUT;
    SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US";
    fLogger.removeAllAppenders();
    fLogger.addAppender(new ConsoleAppender(new SimpleLayout(), ConsoleAppender.SYSTEM_OUT));
    fBot = new SWTWorkbenchBot();

    /* Finish waiting for eclipse to load */
    WaitUtils.waitForJobs();

    SWTBotUtils.createProject(TRACE_PROJECT_NAME);
}
 
Example #22
Source File: GTestRunner.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
private CharSequence readSourceFile(String sourceFile) throws IOException {
		Bundle bundle = getTestBundle();
//		System.out.println("[GTestRunner] Loaded bundle " + bundle.getSymbolicName());
		InputStream is = FileLocator.openStream(bundle, new Path(sourceFile), false);
		Reader reader = new InputStreamReader(is);
		char[] buffer = new char[4096];
		StringBuilder sb = new StringBuilder(buffer.length);
		int count;
		while ((count = reader.read(buffer)) != -1) {
			sb.append(buffer, 0, count);
		}
		reader.close();
		is.close();
		return sb;
	}
 
Example #23
Source File: CtfTestTraceUtils.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get a CTFTrace instance of a test trace.
 *
 * @param trace
 *            The test trace to use
 * @return The CTFTrace object
 * @throws CTFException
 *             If there is an error initializing the trace
 */
public static synchronized CTFTrace getTrace(CtfTestTrace trace) throws CTFException {
    String tracePath;
    try {
        tracePath = FileUtils.toFile(FileLocator.toFileURL(trace.getTraceURL())).getAbsolutePath();
    } catch (IOException e) {
        throw new IllegalStateException();
    }

    return new CTFTrace(tracePath);
}
 
Example #24
Source File: SamplePart.java    From codeexamples-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
private void addFonts(Display display) {

		Bundle bundle = FrameworkUtil.getBundle(getClass());
		final String pathString = "fonts/Roboto-ThinItalic.ttf";
		Path path = new Path(pathString);
		URL url = FileLocator.find(bundle, path, Collections.EMPTY_MAP);
		final boolean isFontLoaded = display.loadFont(url.toExternalForm());
		if (!isFontLoaded) {
			new RuntimeException("Did not load font");
		}
	}
 
Example #25
Source File: CustomTraceDefinition.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get all the custom trace definition paths contributed by extensions, for
 * a given content type (XML or Text).
 *
 * @param traceContentTypeToLoad
 *            XML or Text (extension attribute value)
 * @return the paths
 *
 * Note: This method is package-visible by design.
 */
static final Collection<String> getExtensionDefinitionsPaths(String traceContentTypeToLoad) {
    List<String> extensionDefinitionsPaths = new ArrayList<>();
    IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(TMF_CUSTOM_TRACE_BUILTIN_EXTENSION_ID);
    for (IConfigurationElement element : elements) {
        if (!element.getName().equals(ELEMENT_NAME_CUSTOM_TRACE)) {
            continue;
        }

        final String traceContentType = element.getAttribute(ATTRIBUTE_NAME_TRACE_CONTENT_TYPE);
        if (!traceContentType.equals(traceContentTypeToLoad)) {
            continue;
        }

        final String filename = element.getAttribute(ATTRIBUTE_NAME_FILE);
        final String name = element.getContributor().getName();
        SafeRunner.run(new ISafeRunnable() {
            @Override
            public void run() throws IOException {
                if (name != null) {
                    Bundle bundle = Platform.getBundle(name);
                    if (bundle != null) {
                        URL xmlUrl = bundle.getResource(filename);
                        URL locatedURL = FileLocator.toFileURL(xmlUrl);
                        extensionDefinitionsPaths.add(locatedURL.getPath());
                    }
                }
            }

            @Override
            public void handleException(Throwable exception) {
                // Handled sufficiently in SafeRunner
            }
        });

    }
    return extensionDefinitionsPaths;
}
 
Example #26
Source File: ImageUtils.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
private final static void declareRegistryImage(String key, String path) {
    ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor();
    Bundle bundle = Platform.getBundle(XdsPlugin.PLUGIN_ID);
    URL url = null;
    if (bundle != null){
        url = FileLocator.find(bundle, new Path(path), null);
        if(url != null) {
            desc = ImageDescriptor.createFromURL(url);
        }
    }
    imageRegistry.put(key, desc);
}
 
Example #27
Source File: CtfTmfExperimentTrimmingTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Setup before the test suite
 *
 * @throws IOException
 *             failed to load the file
 */
@BeforeClass
public static void beforeClass() throws IOException {
    SWTBotUtils.initialize();

    /* set up for swtbot */
    SWTBotPreferences.TIMEOUT = 50000; /* 50 second timeout */
    fLogger.removeAllAppenders();
    fLogger.addAppender(new NullAppender());

    File parentDir = FileUtils.toFile(FileLocator.toFileURL(CtfTestTrace.TRACE_EXPERIMENT.getTraceURL()));
    File[] traceFiles = parentDir.listFiles();
    ITmfTrace traceValidator = new CtfTmfTrace();
    fBot = new SWTWorkbenchBot();
    SWTBotUtils.createProject(PROJECT_NAME);

    int openedTraces = 0;
    for (File traceFile : traceFiles) {
        String absolutePath = traceFile.getAbsolutePath();
        if (traceValidator.validate(null, absolutePath).isOK()) {
            SWTBotUtils.openTrace(PROJECT_NAME, absolutePath, TRACE_TYPE);
            fBot.closeAllEditors();
            openedTraces++;
            if (openedTraces >= NUM_TRACES) {
                break;
            }
        }
    }
    traceValidator.dispose();

    /* finish waiting for eclipse to load */
    WaitUtils.waitForJobs();
}
 
Example #28
Source File: TestEnvironmentUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Installs an SDK or other development resource that is bundled in a testing plug-in into that
 * plug-in's data area and returns the absolute path where it was installed.
 *
 * @param bundle the {@link Bundle} in which the SDK is bundled
 * @param fileUrl the path to the zip
 * @return the absolute path of the installed bundle
 */
public static IPath installTestSdk(Bundle bundle, URL fileUrl) {
  byte[] buffer = new byte[1024];
  IPath sdkRootPath = null;
  File output = bundle.getDataFile("");
  try (ZipInputStream is =
      new ZipInputStream(new FileInputStream(new File(FileLocator.toFileURL(fileUrl).getPath())))) {
    ZipEntry entry = is.getNextEntry();
    if (entry != null) {
      String rootEntryPath = Path.fromPortableString(entry.getName()).segment(0);
      sdkRootPath = Path.fromPortableString(new File(output, rootEntryPath).getAbsolutePath());
      if (!sdkRootPath.toFile().exists()) {
        while (entry != null) {
          IPath fileName = Path.fromPortableString(entry.getName());
          if (!"demos".equals(fileName.segment(1)) && !"samples".equals(fileName.segment(1))) {
            File newFile = new File(output + File.separator + fileName);
            if (!entry.isDirectory()) {
              new File(newFile.getParent()).mkdirs();
              try (FileOutputStream os = new FileOutputStream(newFile)) {
                int bytesRead;
                while ((bytesRead = is.read(buffer)) > 0) {
                  os.write(buffer, 0, bytesRead);
                }
              }
            }
          }
          entry = is.getNextEntry();
        }
      }
    }
    is.closeEntry();
  } catch (IOException e) {
    throw new IllegalStateException("Unable to install the SDK. fileUrl=" + fileUrl, e);
  }
  return sdkRootPath;
}
 
Example #29
Source File: BuildPathManager.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public void processElement(IConfigurationElement element)
{
	// get extension pt's bundle
	IExtension extension = element.getDeclaringExtension();
	String pluginId = extension.getNamespaceIdentifier();
	Bundle bundle = Platform.getBundle(pluginId);

	// grab the item's display name
	String name = element.getAttribute(ATTR_NAME);

	// get the item's URI, resolved to a local file
	String resource = element.getAttribute(ATTR_PATH);
	URL url = FileLocator.find(bundle, new Path(resource), null);

	// add item to master list
	URI localFileURI = ResourceUtil.resourcePathToURI(url);

	if (localFileURI != null)
	{
		addBuildPath(name, localFileURI);
	}
	else
	{
		// @formatter:off
		String message = MessageFormat.format(
			Messages.BuildPathManager_UnableToConvertURLToURI,
			url.toString(),
			ELEMENT_BUILD_PATH,
			BUILD_PATHS_ID,
			pluginId
		);
		// @formatter:on

		IdeLog.logError(BuildPathCorePlugin.getDefault(), message);
	}
}
 
Example #30
Source File: NodesLoader.java    From jbt with Apache License 2.0 5 votes vote down vote up
/**
 * Loads all the standard nodes defined in the file
 * {@link #STANDARD_NODES_FILE}. After doing so, standard nodes can be
 * accessed through {@link #getStandardNodes()} and
 * {@link #getNode(String, String)}.
 * <p>
 * Throws an exception if there is any error loading the standard nodes.
 */
public static void loadStandardNodes() throws IOException {
	loadRoot();

	URL url = FileLocator.find(Activator.getDefault().getBundle(),
			new Path(STANDARD_NODES_FILE), Collections.EMPTY_MAP);

	URL fileUrl = null;
	fileUrl = FileLocator.toFileURL(url);
	FileInputStream file = new FileInputStream(fileUrl.getPath());

	parseStandardNodesFile(file);
}