I'm wondering how I can create a new file with an existing emf resource. At the moment I've the following code in my org.eclipse.ui.menus DefaultHandler, which get me the existing emf resource and create a new (empty) file:
if (element instanceof IResource) {
IResource pldFile = (IResource) element;
String path = pldFile.getLocation().toString();
URI uri = URI.createFileURI(path);
// Obtain a new resource set
ResourceSet resSet = new ResourceSetImpl();
// Get the existing resource
Resource emfResource = resSet.getResource(uri, true);
IProject project = pldFile.getProject();
String fileName = pldFile.getName().replace(pldFile.getFileExtension(), "plc");
IFile plcFile = project.getFile(new Path(fileName));
byte[] bytes = "".getBytes();
try {
InputStream source = new ByteArrayInputStream(bytes);
if (plcFile.exists()) {
int i = 1;
String tmp = "";
do {
tmp = fileName;
int index = tmp.indexOf(".plc");
tmp = tmp.substring(0, index) + i + tmp.substring(index, tmp.length());
plcFile = project.getFile(new Path(tmp));
i++;
} while (plcFile.exists());
plcFile.create(source, IResource.NONE, null);
} else {
plcFile.create(source, IResource.NONE, null);
}
PlcEditorInput input = new PlcEditorInput(emfResource);
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IDE.openEditor(page, plcFile);
} catch (CoreException e) {
e.printStackTrace();
}
How can I assign now the existing emf resource to my newly created file?
Cheers,
Phil
I'm not sure but try to import the resource as new file. I mean define a new file or project and then import the resource.
To be honestly I try a similary way but it didn't work with my resource(--> it's a 10-years-old-code).
Related
Is there a way to list up all img links from google image search with this class?:
//The url of the website. This is just an example
private static final String webSiteURL = "http://www.supercars.net/gallery/119513/2841/5.html";
//The path of the folder that you want to save the images to
private static final String folderPath = "<FOLDER PATH>";
public static void main(String[] args) {
try {
//Connect to the website and get the html
Document doc = Jsoup.connect(webSiteURL).get();
//Get all elements with img tag ,
Elements img = doc.getElementsByTag("img");
for (Element el : img) {
//for each element get the srs url
String src = el.absUrl("src");
System.out.println("Image Found!");
System.out.println("src attribute is : "+src);
getImages(src);
}
} catch (IOException ex) {
System.err.println("There was an error");
Logger.getLogger(DownloadImages.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void getImages(String src) throws IOException {
String folder = null;
//Exctract the name of the image from the src attribute
int indexname = src.lastIndexOf("/");
if (indexname == src.length()) {
src = src.substring(1, indexname);
}
indexname = src.lastIndexOf("/");
String name = src.substring(indexname, src.length());
System.out.println(name);
//Open a URL Stream
URL url = new URL(src);
InputStream in = url.openStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream( folderPath+ name));
for (int b; (b = in.read()) != -1;) {
out.write(b);
}
out.close();
in.close();
}
I am fetching image links from other websites but I cant fetch images just from the google image search. Is it possible to fetch these images with this class or do I have to use another method ?
I have a problem with a relative path to an image folder.
I want to list the images into a folder to add their urls to a list and show them in a jsp.
The code is this:
File carpetaImagenes = new File("../../../../../webapp/resources/img/maquinas/"+seleccion);
List<String> listaUrlImagenes = new ArrayList<String>();
/** Recorremos el directorio de imagenes de la maquina */
for(File imagen : carpetaImagenes.listFiles()){
String imageFileName = imagen.getName();
listaUrlImagenes.add(imageFileName);
}
The result of "carpetaImagenes.listFiles()" is always null. I suppose the path is bad.
Here you can see the image of the folder tree. The class is into "controlador" folder and the images are into "webbapp/resources/img/maquinas/1"
I haeve tried several paths with no luck.
Thank you very much.
User following method getImageList and it should work
relativeFilePath = "img/maquinas/"+seleccion;
This is a relative path from classpath. I assume ../../../../../webapp/resources is your actual folder where everyrthing is deployed .
private List getImageList(String relativeFilePath) {
List<String> listaUrlImagenes = new ArrayList<String>();
try {
InputStream in = getResourceAsStream(relativeFilePath);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String resource;
while ((resource = br.readLine()) != null) {
listaUrlImagenes.add(resource);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listaUrlImagenes;
}
private InputStream getResourceAsStream(String resource) {
final InputStream in = ClassLoader cl = this.getClass().getClassLoader().getResourceAsStream(
resource);
return in == null ? getClass().getResourceAsStream(resource) : in;
}
And in spring following should work.
ClassLoader cl = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
cl);
Resource[] resources = resolver.getResources("classpath:/img/maquinas/"+seleccion);// or *.png
for (Resource resource : resources) {
listaUrlImagenes.add(resource.getFilename());
}
Finally working!!
File carpetaImagenes = new ClassPathResource("imagenes/maquinas/"+seleccion).getFile();
File[] listaImagenes = carpetaImagenes.listFiles();
I used E4XMIResourceFactory to save perspective in my eclipse 4 application. But when I went to load my perspective from xmi file, I could found my data in the part. In other world I'd like to save dirty part inside my xmi file. Somebody can help me I cannot find any resurce online to solve my problem.
public class SaveHandler {
#Execute
public void execute(EModelService modelService, MWindow window, MApplication app, Shell shell) {
MPerspective savePerspective = modelService.getActivePerspective(window);
E4XMIResourceFactory e4xmiResourceFactory = new E4XMIResourceFactory();
Resource resource = e4xmiResourceFactory.createResource(null);
MUIElement clonedPerspective = modelService.cloneElement(savePerspective, window);
resource.getContents().add((EObject) clonedPerspective);
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.xmi"});
//dialog.setFilterPath("c:\\temp");
String result = dialog.open();
FileOutputStream outputStream = null;
try {
// Use a stream to save the model element
outputStream = new FileOutputStream(result);
resource.save(outputStream, null);
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And the loader method is
public class OpenHandler {
#Execute
public void execute(EPartService partService,EModelService modelService,MWindow window, MApplication app, Shell shell) {
E4XMIResourceFactory e4xmiResourceFactory = new E4XMIResourceFactory();
Resource resource = e4xmiResourceFactory.createResource(null);
FileInputStream inputStream = null;
try {
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.xmi"});
//dialog.setFilterPath("c:\\temp");
String result = dialog.open();
inputStream = new FileInputStream(result);
resource.load(inputStream, null);
if (!resource.getContents().isEmpty()) {
MPerspective loadedPerspective = (MPerspective) resource.getContents().get(0);
//MPerspective perspective = (MPerspective)modelService.find("ktool_aie.perspective.connectionandmaps",app);
MPerspective perspective = modelService.getActivePerspective(window);
MElementContainer<MUIElement> perspectiveParent = perspective.getParent();
List<MPerspective> alreadyPresentPerspective = modelService.findElements(window,loadedPerspective.getElementId(), MPerspective.class, null);
for (MPerspective i_perspective : alreadyPresentPerspective) {
modelService.removePerspectiveModel(i_perspective, window);
}
// add the loaded perspective and switch to it
perspectiveParent.getChildren().add(loadedPerspective);
partService.switchPerspective(loadedPerspective);
}
if (inputStream != null) inputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
I am running Mac OSX Mavericks. Right now I am creating a JAR file from a folder (org, the package). When I use this code from here:
public void run() throws IOException
{
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
JarOutputStream target = new JarOutputStream(new FileOutputStream("/Users/username/Library/Application Support/VSE/temp/output.jar"), manifest);
add(new File("/Users/username/Library/Application Support/VSE/temp/org"), target);
target.close();
}
private void add(File source, JarOutputStream target) throws IOException
{
BufferedInputStream in = null;
try
{
if (source.isDirectory())
{
String name = source.getPath().replace("\\", "/");
if (!name.isEmpty())
{
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile: source.listFiles())
add(nestedFile, target);
return;
}
JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true)
{
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
}
finally
{
if (in != null)
in.close();
}
}
When I extract the JAR file, There is a META-INF folder, but instead of having the org folder in the extracted jar, I have my Users folder copied into it (except because of it's size, its wasn't filled with all my stuff and my application crashed). I'm expecting this is because the code was written for a Windows system, and the differences with the filesystem (such as \ or /). How would I make the code include only the "org" directory, and not everything leading up to it?
Provided you use Java 7+ you may easily do this by using one of my packages in combination with the zip filesystem provider of the JDK to create it:
private static final Map<String, ?> ENV = Collections.singletonMap("create", "true");
public void run()
throws IOException
{
final Path zipPath = Paths.get("/Users/username/Library/Application Support/VSE/temp/output.jar");
final Path srcdir = Paths.get("/Users/username/Library/Application Support/VSE/temp/org");
final URI uri = URI.create("jar:" + zipPath.toUri());
Files.deleteIfExists(zipPath);
try (
final FileSystem zipfs = FileSystems.newFileSystem(uri, ENV);
) {
copyManifest(zipfs);
copyDirectory(srcdir, zipfs);
}
}
private void copyManifest(final FileSystem zipfs)
throws IOException
{
final Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
Files.createDirectory(zipfs.getPath("META-INF/");
try (
final OutputStream out = Files.newOutputStream(zipfs.getPath("META-INF/MANIFEST.MF"));
) {
manifest.write(out);
}
}
private void copyDirectory(final Path srcdir, final FileSystem zipfs)
{
final String lastName = srcdir.getFileName().toString();
final Path dstDir = zipfs.getPath(lastName);
Files.createDirectory(dstDir);
MoreFiles.copyRecursive(srcDir, dstDir, RecursionMode.FAIL_FAST);
}
How do you get a compiled jasper report to load from within the jar file, instead of via a specific path on your hard drive?
My report was working fine on my machine as I had set the path to the reports with:
jasperReport1 = (JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg1.jasper");
jasperReport2 =(JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg2.jasper");
But the reports were not loading when working from the finished jar on a different computer. So I am trying to use Input stream and passing it to JasperFillManager but nothing is working - the InputStream is not finding the files. Have I the path wrong?
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
My original working code:
private void yTDReportBtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
JasperReport jasperReport1 = null;
JasperReport jasperReport2 = null;
JasperPrint jasperPrint = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
SimpleDateFormat formatter = new SimpleDateFormat("dd-mmm-yyyy");
String today = formatter.format(new java.util.Date());
//load just the compiled jasper files, to save time
//First merge the two jasper reports into one to get page1 and page 2 in same document
jasperReport1 = (JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg1.jasper");
jasperReport2 =(JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg2.jasper");
JasperPrint jp1 = JasperFillManager.fillReport(jasperReport1, parameters,new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
JasperPrint jp2 = JasperFillManager.fillReport(jasperReport2, parameters, new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage)pages.get(j);
jp1.addPage(object);
jp1.setName(unitNameLbl.getText() + " - Financial Year To Date - " + today );
}
JasperViewer.viewReport(jp1, false);
}
catch(Exception ex)
{
System.out.println("EXCEPTION: "+ex.getMessage() + ex);
}
}
And now the changed code that is not working:
private void yTDReportBtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
JasperReport jasperReport1 = null;
JasperReport jasperReport2 = null;
JasperPrint jasperPrint = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
SimpleDateFormat formatter = new SimpleDateFormat("dd-mmm-yyyy");
String today = formatter.format(new java.util.Date());
//load just the compiled jasper files, to save time
//First merge the two jasper reports into one to get page1 and page 2 in same document
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
JasperPrint jp1 = JasperFillManager.fillReport(jasper1, parameters,new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
JasperPrint jp2 = JasperFillManager.fillReport(jasper2, parameters, new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage)pages.get(j);
jp1.addPage(object);
jp1.setName(unitNameLbl.getText() + " - Financial Year To Date - " + today );
}
JasperViewer.viewReport(jp1, false);
}
catch(Exception ex)
{
System.out.println("EXCEPTION: "+ex.getMessage() + ex);
}
}
Any help greatly appreciated!
Ok update: I got the InputStreams to work by creating a new package called "reports" and using
InputStream jasper1 = getClass().getResourceAsStream("/reports/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("/reports/OMACYTDReportFinalpg2.jasper");
And this works fine in Netbeans BUT it still won't load the files when I compile to jar!!?
Any ideas what I'm doing wrong?
you should put jasper reports in
yourapp/src/main/resources/reports
then you invoke that reports from class java
JasperReport jp = JasperCompileManager.compileReport(getClass().getResourceAsStream("/reports/yourReport.jrxml"));
See you!
Old topic, but could be useful.
I thing where is no src folder inside your jar.
InputStream jasper2 = getClass().getResourceAsStream("/ie/test/OMACYTDReportFinalpg2.jasper");
Where is more advanced way:
Put your jasper reports, images and other resources into jar.
Put YourClass inside jar file and load resources using class.getResourceAsStream() and you need to add loader extention before load resource
(JasperReport) JRLoader.loadObject("stream or path");
// DefaultJasperReportsContext user ExtensionsEnvironment
ExtensionsEnvironment.setThreadExtensionsRegistry(LoaderExtention.INSTANCE);
The following example of loading resources
public class LoaderService
implements RepositoryService
{
public static final RepositoryService INSTANCE = new LoaderService();
#Override
public void setContext(RepositoryContext repositoryContext)
{
}
#Override
public void revertContext()
{
}
#Override
public InputStream getInputStream(String file)
{
LOGGER.fine(String.format("getInputStream('%s')", file));
return <YourClass>.class.getResourceAsStream(file);
}
#Override
public Resource getResource(String file)
{
LOGGER.fine(String.format("getResource('%s') not implemented", file));
return null;
}
#Override
public <K extends Resource> K getResource(String file, Class<K> cls)
{
LOGGER.fine(String.format("getResource('%s', %s)", file, cls != null? cls.getName(): null));
try
{
if (cls == ReportResource.class)
{
InputStream resource = getInputStream(file);
if (resource != null)
{
JasperReport report = (JasperReport) JRLoader.loadObject(resource);
if (report != null)
{
ReportResource res = new ReportResource();
res.setName(file);
res.setReport(report);
return (K) res;
}
}
}
else if (cls == InputStreamResource.class)
{
InputStream resource = getInputStream(file);
if (resource != null)
{
InputStreamResource res = new InputStreamResource();
res.setInputStream(resource);
return (K) res;
}
}
}
catch (JRException e)
{
}
return null;
}
#Override
public void saveResource(String string, Resource resource)
{
// TODO Implement this method
}
}
public class LoaderExtention
implements ExtensionsRegistry
{
public static final LoaderExtention INSTANCE = new LoaderExtention();
#Override
public <T extends Object> List<T> getExtensions(Class<T> cls)
{
ExtensionsRegistry system = ExtensionsEnvironment.getSystemExtensionsRegistry();
List<T> services = null;
if (system != null)
services = system.getExtensions(cls);
if (cls == RepositoryService.class)
{
List<T> servicesAll = new ArrayList<T>();
if (services != null)
servicesAll.addAll(services);
servicesAll.add((T) LoaderService.INSTANCE); // Try to use system resource loaders then my
services = servicesAll;
}
LOGGER.fine(String.format("getExtensions(%s) = %s", cls.getName(), services));
return services;
}
}
I use JasperReport 5.5
Have fun.
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");