From 76082512d97cf1c353aac1962d20c6322960fccb Mon Sep 17 00:00:00 2001 From: Sebastian Schulz Date: Mon, 13 Dec 2021 16:11:10 +0100 Subject: [PATCH] Use 'toURI()' before calling 'toURL()' --- .../udig/context/internal/URLWizardPage.java | 239 +++++++------ .../udig/project/ui/internal/MapFactory.java | 164 +++++---- .../ui/internal/actions/AddLayerFiles.java | 37 +- .../project/ui/internal/actions/DropMap.java | 13 +- .../ui/internal/actions/SLDDropAction.java | 57 +-- .../udig/tool/edit/DifferenceOp.java | 337 ++++++++++-------- .../raster/RasterTutorialHandler.java | 78 ++-- .../udig/tutorials/shpexport/ShpExportOp.java | 127 ++++--- 8 files changed, 549 insertions(+), 503 deletions(-) diff --git a/plugins/org.locationtech.udig.context/src/org/locationtech/udig/context/internal/URLWizardPage.java b/plugins/org.locationtech.udig.context/src/org/locationtech/udig/context/internal/URLWizardPage.java index d2b0ef2b21..1384ca66e0 100644 --- a/plugins/org.locationtech.udig.context/src/org/locationtech/udig/context/internal/URLWizardPage.java +++ b/plugins/org.locationtech.udig.context/src/org/locationtech/udig/context/internal/URLWizardPage.java @@ -1,4 +1,5 @@ -/* uDig - User Friendly Desktop Internet GIS client +/** + * uDig - User Friendly Desktop Internet GIS client * http://udig.refractions.net * (C) 2004, Refractions Research Inc. * @@ -33,236 +34,238 @@ /** * The most basic, simple annoying URL prompt you can imagine. *

- * This import page is similar the eclipse example and was - * last seen as the ShapefileImportPage in UDIG 0.7. Yes I am - * that lazy - lazy smart. + * This import page is similar the eclipse example and was last seen as the ShapefileImportPage in + * UDIG 0.7. Yes I am that lazy - lazy smart. *

*

- * This time around I am going to try and keep things - * reusable, so we can use this for Context Documents, SLD - * files whatever. Also will let us improve the "look" as - * needed. + * This time around I am going to try and keep things reusable, so we can use this for Context + * Documents, SLD files whatever. Also will let us improve the "look" as needed. *

+ *

* The following user-interface elements are used: *

*

*

- * In the future - I would really like to hook this into the - * generic DnD system Jesse is working on for UDIG 1.1.x. In - * such a use the end of this process would be the URL being - * "dropped" onto the current selection. + * In the future - I would really like to hook this into the generic DnD system Jesse is working on + * for UDIG 1.1.x. In such a use the end of this process would be the URL being "dropped" onto the + * current selection. *

- * + * * @author Jody Garnett * @since 1.0.5 */ public class URLWizardPage extends WizardPage implements KeyListener { - + protected URL url = null; + private Text text; - private String promptMessage = Messages.URLWizardPage_prompt_initial; - + + private String promptMessage = Messages.URLWizardPage_prompt_initial; + /** - * Force subclasses to actually cough up the stuff needed for - * a pretty user interface. + * Force subclasses to actually cough up the stuff needed for a pretty user interface. *

* Subclass should really: *

+ *

+ * * @param pageName * @param title * @param titleImage */ - protected URLWizardPage( String pageName, String title, ImageDescriptor titleImage ) { + protected URLWizardPage(String pageName, String title, ImageDescriptor titleImage) { super(pageName, title, titleImage); } - public void setMessage( String newMessage ) { - if( newMessage == null ) newMessage = promptMessage; + + @Override + public void setMessage(String newMessage) { + if (newMessage == null) + newMessage = promptMessage; super.setMessage(newMessage); } + /** * Called to create the user interface components. *

- * As per usual eclipse practice, both the constructor (duh) and - * init have been called. + * As per usual eclipse practice, both the constructor (duh) and init have been called. *

*/ - public void createControl( Composite parent ) { - Composite composite = new Composite(parent,SWT.NULL); + @Override + public void createControl(Composite parent) { + Composite composite = new Composite(parent, SWT.NULL); composite.setLayout(new GridLayout(3, false)); - - // add url - Label label = new Label( composite, SWT.NONE ); - label.setText(Messages.URLWizardPage_label_url_text ); - label.setLayoutData( new GridData(SWT.END, SWT.DEFAULT, false, false ) ); - text = new Text( composite, SWT.BORDER ); - text.setLayoutData( new GridData(GridData.FILL_HORIZONTAL) ); - text.setText( "" ); //$NON-NLS-1$ - text.addKeyListener( this ); - + // add URL + Label label = new Label(composite, SWT.NONE); + label.setText(Messages.URLWizardPage_label_url_text); + label.setLayoutData(new GridData(SWT.END, SWT.DEFAULT, false, false)); + + text = new Text(composite, SWT.BORDER); + text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + text.setText(""); //$NON-NLS-1$ + text.addKeyListener(this); + Button button = new Button(composite, SWT.PUSH); button.setLayoutData(new GridData()); - button.setText(Messages.URLWizardPage_button_browse_text); - button.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected( SelectionEvent e ) { + button.setText(Messages.URLWizardPage_button_browse_text); + button.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { Display display = Display.getCurrent(); - if (display == null) { // not on the ui thread? + if (display == null) { // not on the UI thread? display = Display.getDefault(); } - + FileDialog dialog = new FileDialog(display.getActiveShell(), SWT.OPEN); - //dialog.setFilterExtensions(new String[]{"*.shp"}); - dialog.setText( Messages.URLWizardPage_dialog_text ); // hope for open ? - + dialog.setText(Messages.URLWizardPage_dialog_text); // hope for open ? + String open = dialog.open(); - if(open == null){ + if (open == null) { // canceled - no change - } - else { - text.setText( open ); - setPageComplete(isPageComplete()); + } else { + text.setText(open); + setPageComplete(isPageComplete()); } } - }); + }); setControl(text); - -// eclipse ui guidelines say we must start with prompt (not error) - setMessage( null ); - setPageComplete(true); + + // Eclipse UI guidelines say we must start with prompt (not error) + setMessage(null); + setPageComplete(true); } - + /** - * We cannot assume how far we got in the consturction process. - * So we have to carefully tear the roof down over our heads and - * sweep away our footprints. + * We cannot assume how far we got in the construction process. So we have to carefully tear the + * roof down over our heads and sweep away our footprints. */ @Override public void dispose() { - if( text != null ){ - text.removeKeyListener( this ); + if (text != null) { + text.removeKeyListener(this); text.dispose(); text = null; } super.dispose(); } - - public void keyReleased( KeyEvent e ) { - if(isPageComplete()){ + + @Override + public void keyReleased(KeyEvent e) { + if (isPageComplete()) { setPageComplete(true); } } - public void keyPressed( KeyEvent e ) { + + @Override + public void keyPressed(KeyEvent e) { setPageComplete(false); } + /** * Default implementation will return true for a valid URL. *

* Valid URL is based on text containing: *

- * Subclasses may override to perform extra sanity checks on - * the URL (for things like extention, magic, etc...) + * Subclasses may override to perform extra sanity checks on the URL (for things like extention, + * magic, etc...) *

- * + * * @see org.eclipse.jface.wizard.IWizardPage#isPageComplete() * @return true if we have a useful URL */ + @Override public boolean isPageComplete() { url = null; - + String txt = text.getText(); - Exception errorMessage = null; - - if( txt == null || txt.length() == 0 ){ + Exception errorMessage = null; + + if (txt == null || txt.length() == 0) { // not available - } - else { + } else { try { - url = new URL( txt ); - } - catch( MalformedURLException erp ){ + url = new URL(txt); + } catch (MalformedURLException erp) { errorMessage = erp; } - if( errorMessage != null ){ // try file + if (errorMessage != null) { // try file try { - File file = new File( txt ); - url = file.toURL(); + File file = new File(txt); + url = file.toURI().toURL(); errorMessage = null; } catch (MalformedURLException notFile) { } } } - if( url == null ){ - if( errorMessage != null ){ - setErrorMessage( errorMessage.getLocalizedMessage() ); + if (url == null) { + if (errorMessage != null) { + setErrorMessage(errorMessage.getLocalizedMessage()); + } else { + setMessage(""); //$NON-NLS-1$ } - else { - setMessage( "" ); //$NON-NLS-1$ - } - } - setMessage( Messages.URLWizardPage_prompt_import ); + } + setMessage(Messages.URLWizardPage_prompt_import); return true; } + /** - * Called as a quick sanity check on the provided url. + * Called as a quick sanity check on the provided URL. *

- * Note this method is called before checking if the url - * is a file. You can assume that urlCheck is true if fileCheck - * is called. + * Note this method is called before checking if the URL is a file. You can assume that urlCheck + * is true if fileCheck is called. *

*

- * The default implementation just check that the url is non - * null. Please override to check for things like - * the correct extention ... + * The default implementation just check that the URL is non null. Please override + * to check for things like the correct extention ... *

- * + * * @param url - * @return true if url is okay + * @return true if URL is okay */ - protected boolean urlCheck( URL url ){ + protected boolean urlCheck(URL url) { return url != null; } - + /** * Used for a quick file check - don't open it! *

- * Default implementation checks that the file exists, override - * to check file extention or permissions or something. + * Default implementation checks that the file exists, override to check file extention or + * permissions or something. *

*

- * This method is being called on every key press so don't - * waste your user's time. Save that till they hit Next, that - * way you get a progress monitor... + * This method is being called on every key press so don't waste your user's time. Save that + * till they hit Next, that way you get a progress monitor... *

*

- * Method can call setErrorMessage to report reasonable user - * level explainations back to the user, default implementation - * will complain if the file does not exist. + * Method can call setErrorMessage to report reasonable user level explanations back to the + * user, default implementation will complain if the file does not exist. *

+ * * @param file * @return true if file passes a quick sanity check */ - protected boolean fileCheck( File file ){ - if( file.exists() ){ + protected boolean fileCheck(File file) { + if (file.exists()) { return true; - } - //file = file.getAbsoluteFile(); - while( file.getParent() != null && !file.exists() ){ + } + // file = file.getAbsoluteFile(); + while (file.getParent() != null && !file.exists()) { file = file.getParentFile(); } - setErrorMessage( MessageFormat.format(Messages.URLWizardPage_prompt_error_fileNotExist, file.getName())); - + setErrorMessage(MessageFormat.format(Messages.URLWizardPage_prompt_error_fileNotExist, + file.getName())); + return false; } } diff --git a/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/MapFactory.java b/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/MapFactory.java index a7a37428ca..51b7f2b5ad 100644 --- a/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/MapFactory.java +++ b/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/MapFactory.java @@ -1,7 +1,7 @@ -/* - * uDig - User Friendly Desktop Internet GIS client - * http://udig.refractions.net - * (C) 2004, Refractions Research Inc. +/** + * uDig - User Friendly Desktop Internet GIS client + * http://udig.refractions.net + * (C) 2004, Refractions Research Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -61,6 +61,7 @@ * * @deprecated use {@link ApplicationGIS} */ +@Deprecated public class MapFactory { /** @@ -76,9 +77,9 @@ private MapFactory() { } /** - * For each URL in resources, load the services at that location and access - * their layers. Then add the layers to the current map, or a new one if it doesn't exist. The - * new map will be created in the current project. + * For each URL in resources, load the services at that location and access their + * layers. Then add the layers to the current map, or a new one if it doesn't exist. The new map + * will be created in the current project. *

* This is equivalent to calling processURLs(resources, null). *

@@ -86,13 +87,14 @@ private MapFactory() { * @param resources a List of URLs pointing to services (WMS, Shapefile, etc) * @deprecated use {@link ApplicationGIS#createAndOpenMap(List)} */ - public void processURLs( List resources ) { + @Deprecated + public void processURLs(List resources) { processURLs(resources, null); } /** - * For each URL in resources, load the services at that location and access - * their layers. + * For each URL in resources, load the services at that location and access their + * layers. *

* The layers will then be added to the current map, if it exists, otherwise, a new map will be * created in the project designated by target. @@ -103,15 +105,17 @@ public void processURLs( List resources ) { * * @param resources a List of URLs pointing to services (WMS, Shapefile, etc) * @param target Project to use if a new map is going to be created - * @deprecated use {@link ApplicationGIS#createAndOpenMap(List, org.locationtech.udig.project.IProject)} + * @deprecated use + * {@link ApplicationGIS#createAndOpenMap(List, org.locationtech.udig.project.IProject)} */ - public void processURLs( List resources, Project target ) { + @Deprecated + public void processURLs(List resources, Project target) { processURLs(resources, target, false); } /** - * For each URL in resources, load the services at that location and access - * their layers. + * For each URL in resources, load the services at that location and access their + * layers. *

* If newMap is set to true or there is no current map, the layers * will be added to a new map, contained in the project designated by target, or @@ -121,10 +125,14 @@ public void processURLs( List resources, Project target ) { * @param resources a List of URLs pointing to services (WMS, Shapefile, etc) * @param target Project to use if a new map is going to be created * @param newMap if true, a new map will be created even if there is one already open - * @deprecated use {@link ApplicationGIS#addLayersToMap(org.locationtech.udig.project.IProject, List)} or {@link ApplicationGIS#createAndOpenMap(List, org.locationtech.udig.project.IProject)} + * @deprecated use + * {@link ApplicationGIS#addLayersToMap(org.locationtech.udig.project.IProject, List)} + * or + * {@link ApplicationGIS#createAndOpenMap(List, org.locationtech.udig.project.IProject)} * */ - public void processURLs( List resources, Project target, boolean newMap ) { + @Deprecated + public void processURLs(List resources, Project target, boolean newMap) { process(target, resources, newMap); } @@ -141,7 +149,7 @@ public void processURLs( List resources, Project target, boolean newMap ) { * @param target Project to use if a new map is going to be created * @param newMap if true, a new map will be created even if there is one already open */ - public void processResolves( List resources, Project target, boolean newMap ) { + public void processResolves(List resources, Project target, boolean newMap) { process(target, resources, newMap); } @@ -153,22 +161,23 @@ public void processResolves( List resources, Project target, boolean n * @param resources a List of IResolves * @param newMap forces a new map to be created */ - public void process( final Project target, final List resources, final boolean newMap ) { + public void process(final Project target, final List resources, final boolean newMap) { if (resources == null) { throw new InvalidParameterException("Parameter 'resources' cannot be null."); //$NON-NLS-1$ } - Job job = new Job(Messages.ProjectUIPlugin_loadingServices_title){ + Job job = new Job(Messages.ProjectUIPlugin_loadingServices_title) { + @Override @SuppressWarnings("unchecked") - protected IStatus run( final IProgressMonitor monitor ) { + protected IStatus run(final IProgressMonitor monitor) { - List exceptions = new ArrayList(); + List exceptions = new ArrayList<>(); - List services = new ArrayList(); - List geoResources = new ArrayList(); - List layers = new ArrayList(); + List services = new ArrayList<>(); + List geoResources = new ArrayList<>(); + List layers = new ArrayList<>(); - for( Object object : resources ) { + for (Object object : resources) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } @@ -178,7 +187,8 @@ protected IStatus run( final IProgressMonitor monitor ) { services.addAll(handleURL((URL) object, monitor)); } else if (object instanceof File) { try { - services.addAll(handleURL(((File) object).toURL(), monitor)); + services.addAll( + handleURL(((File) object).toURI().toURL(), monitor)); } catch (MalformedURLException e) { // ignore non-URL strings } @@ -195,8 +205,8 @@ protected IStatus run( final IProgressMonitor monitor ) { } else if (object instanceof Layer) { layers.add((Layer) object); } else if (object instanceof java.util.Map) { - services.addAll(CatalogPlugin.getDefault().getServiceFactory().createService( - (java.util.Map) object)); + services.addAll(CatalogPlugin.getDefault().getServiceFactory() + .createService((java.util.Map) object)); } } catch (IOException e) { exceptions.add(e); @@ -206,11 +216,11 @@ protected IStatus run( final IProgressMonitor monitor ) { monitor.worked(1); } - List unChosenServices = new ArrayList(); + List unChosenServices = new ArrayList<>(); - for( IResolve resolve : services ) { - monitor.beginTask( - Messages.ProjectUIPlugin_loadingServices_task, services.size()); + for (IResolve resolve : services) { + monitor.beginTask(Messages.ProjectUIPlugin_loadingServices_task, + services.size()); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } @@ -239,15 +249,18 @@ protected IStatus run( final IProgressMonitor monitor ) { Map map = new CurrentMapFinder().getCurrentMap(); boolean mapExists = (map != null); // this is used later, and I don't understand - // what for! + // what for! if (map == null || newMap) { map = getMap(monitor, target, newMap); } - if( map.getBlackboard().get(ProjectBlackboardConstants.MAP__BACKGROUND_COLOR)==null ){ + if (map.getBlackboard() + .get(ProjectBlackboardConstants.MAP__BACKGROUND_COLOR) == null) { IPreferenceStore store = ProjectPlugin.getPlugin().getPreferenceStore(); - RGB background = PreferenceConverter.getColor(store, PreferenceConstants.P_BACKGROUND); - map.getBlackboard().put(ProjectBlackboardConstants.MAP__BACKGROUND_COLOR, new Color(background.red, background.green, background.blue )); + RGB background = PreferenceConverter.getColor(store, + PreferenceConstants.P_BACKGROUND); + map.getBlackboard().put(ProjectBlackboardConstants.MAP__BACKGROUND_COLOR, + new Color(background.red, background.green, background.blue)); } if (monitor.isCanceled()) { @@ -263,7 +276,7 @@ protected IStatus run( final IProgressMonitor monitor ) { return Status.CANCEL_STATUS; } - for( IGeoResource resource : geoResources ) { + for (IGeoResource resource : geoResources) { monitor.beginTask(Messages.MapFactory_retrieveTask, geoResources.size()); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; @@ -283,8 +296,8 @@ protected IStatus run( final IProgressMonitor monitor ) { } monitor.worked(1); } - if( !layers.isEmpty() ) - map.getLayersInternal().addAll(layers); + if (!layers.isEmpty()) + map.getLayersInternal().addAll(layers); if (map.getLayersInternal().size() > 0 || newMap == true) { ProjectExplorer.getProjectExplorer().open(map); } else if (!mapExists) { @@ -305,21 +318,23 @@ protected IStatus run( final IProgressMonitor monitor ) { monitor.done(); return new Status(IStatus.OK, ProjectUIPlugin.ID, IStatus.OK, - Messages.ProjectUIPlugin_success, null); + Messages.ProjectUIPlugin_success, null); } }; job.schedule(); } - private List getResourcesFromUser( List unChosenServices ) { + private List getResourcesFromUser(List unChosenServices) { final ResourceSelectionPage page = new ResourceSelectionPage( - Messages.ProjectUIPlugin_resourceSelectionPage_title); + Messages.ProjectUIPlugin_resourceSelectionPage_title); page.setResources(unChosenServices, null); - final List chosenResources = new ArrayList(); + final List chosenResources = new ArrayList<>(); - PlatformGIS.syncInDisplayThread(new Runnable(){ + PlatformGIS.syncInDisplayThread(new Runnable() { + @Override public void run() { - Wizard wizard = new Wizard(){ + Wizard wizard = new Wizard() { + @Override public void addPages() { addPage(page); } @@ -327,7 +342,7 @@ public void addPages() { @Override public boolean performFinish() { List list = page.getCheckedElements(); - for( Object object : list ) { + for (Object object : list) { if (object instanceof IGeoResource) chosenResources.add((IGeoResource) object); } @@ -345,19 +360,19 @@ public boolean performFinish() { return chosenResources; } - private List handleResolve( IResolve resolve, IProgressMonitor monitor ) + private List handleResolve(IResolve resolve, IProgressMonitor monitor) throws IOException { - if( resolve instanceof IService ){ + if (resolve instanceof IService) { IService service = (IService) resolve; resources(service.resources(monitor)); } return Collections.emptyList(); } - private List handleURL( URL url, IProgressMonitor monitor ) throws IOException { + private List handleURL(URL url, IProgressMonitor monitor) throws IOException { if (url.getFile().toLowerCase().endsWith(".udig")) { //$NON-NLS-1$ handleProjectURL(url, monitor); - return Collections.emptyList(); + return Collections. emptyList(); } // Process URL (we are expecting a IService) @@ -369,12 +384,12 @@ private List handleURL( URL url, IProgressMonitor monitor ) throws IOE } } - private void handleProjectURL( URL url, IProgressMonitor monitor ) { + private void handleProjectURL(URL url, IProgressMonitor monitor) { monitor = validateMonitor(monitor); monitor.subTask(Messages.ProjectUIPlugin_loadingProject_task); File file = URLUtils.urlToFile(url); - ProjectPlugin.getPlugin().getProjectRegistry().getProject( file.getAbsolutePath() ); + ProjectPlugin.getPlugin().getProjectRegistry().getProject(file.getAbsolutePath()); return; } @@ -385,7 +400,7 @@ private void handleProjectURL( URL url, IProgressMonitor monitor ) { * @param resources * @return */ - public List processResources( IProgressMonitor monitor, List resources ) { + public List processResources(IProgressMonitor monitor, List resources) { return processResources(monitor, resources, null); } @@ -399,17 +414,17 @@ public List processResources( IProgressMonitor monitor, List reso * @return * @throws IOException */ - List acquireGoodServices( URL url, IProgressMonitor monitor ) throws IOException { + List acquireGoodServices(URL url, IProgressMonitor monitor) throws IOException { if (url == null) - return Collections.emptyList(); + return Collections. emptyList(); IServiceFactory factory = CatalogPlugin.getDefault().getServiceFactory(); List result = factory.createService(url); if (result.isEmpty()) { throw new IOException("Could not acquire a working service for " + url); //$NON-NLS-1$ } - List good = new ArrayList(); + List good = new ArrayList<>(); IOException notGood = null; - for( IService service : result ) { + for (IService service : result) { try { if (service.resources(monitor) != null) { @@ -428,6 +443,7 @@ List acquireGoodServices( URL url, IProgressMonitor monitor ) throws I return good; } + /** * Processes each element within the list of resources and returns all the Layers that have been * discovered as a result. This is typically used to turn URLs, Files, IServices and @@ -439,19 +455,19 @@ List acquireGoodServices( URL url, IProgressMonitor monitor ) throws I * @return a List containing all discovered layers */ @SuppressWarnings("unchecked") - public List processResources( IProgressMonitor monitor, List resources, - Object target ) { + public List processResources(IProgressMonitor monitor, List resources, + Object target) { monitor = validateMonitor(monitor); - List layers = new ArrayList(); - List services = new ArrayList(); - List georesources = new ArrayList(); + List layers = new ArrayList<>(); + List services = new ArrayList<>(); + List georesources = new ArrayList<>(); if (resources.isEmpty()) return layers; - for( Object object : resources ) { + for (Object object : resources) { if (monitor.isCanceled()) return null; if (object instanceof Layer) { @@ -462,27 +478,27 @@ public List processResources( IProgressMonitor monitor, List reso } else if (object instanceof IGeoResource) { georesources.add((IGeoResource) object); } else if (object instanceof java.util.Map) { - services.addAll(CatalogPlugin.getDefault().getServiceFactory().createService( - (java.util.Map) object)); + services.addAll(CatalogPlugin.getDefault().getServiceFactory() + .createService((java.util.Map) object)); } } return layers; } - List resources( List< ? extends IResolve> resolveList ) throws IOException { - List build = new ArrayList(); - for( IResolve resolve : resolveList ) { + List resources(List resolveList) throws IOException { + List build = new ArrayList<>(); + for (IResolve resolve : resolveList) { if (resolve instanceof IGeoResource) { build.add((IGeoResource) resolve); - } else if( resolve instanceof IService){ + } else if (resolve instanceof IService) { build.addAll(resources(((IService) resolve).resources(null))); } } return build; } - public Map getMap( IProgressMonitor monitor, Project project2, boolean createMap ) { + public Map getMap(IProgressMonitor monitor, Project project2, boolean createMap) { Map map = null; if (!createMap) { @@ -491,7 +507,7 @@ public Map getMap( IProgressMonitor monitor, Project project2, boolean createMap if (map != null) { return map; } - Project project=project2; + Project project = project2; if (project == null) { project = ProjectPlugin.getPlugin().getProjectRegistry().getCurrentProject(); } @@ -509,6 +525,7 @@ public Map getMap( IProgressMonitor monitor, Project project2, boolean createMap private static class CurrentMapFinder implements Runnable { Map map = null; + /** * @return */ @@ -523,6 +540,7 @@ Map getCurrentMap() { * * @see java.lang.Runnable#run() */ + @Override public void run() { if (isMapOpen()) { UDIGEditorInput input = (UDIGEditorInput) PlatformUI.getWorkbench() @@ -545,7 +563,7 @@ boolean isMapOpen() { } } - private String getNewMapName( Project currentProject ) { + private String getNewMapName(Project currentProject) { String name = Messages.ProjectUIPlugin_newMap_name; int count = currentProject.getElementsInternal().size() + 1; @@ -553,7 +571,7 @@ private String getNewMapName( Project currentProject ) { return name + count; } - IProgressMonitor validateMonitor( IProgressMonitor monitor ) { + IProgressMonitor validateMonitor(IProgressMonitor monitor) { if (monitor == null) { return new NullProgressMonitor(); } diff --git a/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/AddLayerFiles.java b/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/AddLayerFiles.java index 0c38d382e9..670a1535e5 100644 --- a/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/AddLayerFiles.java +++ b/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/AddLayerFiles.java @@ -1,7 +1,7 @@ -/* - * uDig - User Friendly Desktop Internet GIS client - * http://udig.refractions.net - * (C) 2004, Refractions Research Inc. +/** + * uDig - User Friendly Desktop Internet GIS client + * http://udig.refractions.net + * (C) 2004, Refractions Research Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -26,9 +26,9 @@ import org.locationtech.udig.project.ui.internal.ProjectUIPlugin; /** - * Performs the open action from the file menu of uDig. It is responseible for creating new maps + * Performs the open action from the file menu of uDig. It is responsible for creating new maps * from selected resources. - * + * * @author rgould * @since 0.6.0 */ @@ -36,18 +36,16 @@ public class AddLayerFiles extends WorkbenchWindowActionDelegate { public static final String ID = "org.locationtech.udig.project.ui.openFilesAction"; //$NON-NLS-1$ - /* - * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) - */ - public void run( IAction action ) { + @Override + public void run(IAction action) { addLayers(false); } - protected void addLayers( boolean forceNewMap ) { - String lastOpenedDirectory = ProjectUIPlugin.getDefault().getPluginPreferences().getString( - ProjectUIPlugin.PREF_OPEN_DIALOG_DIRECTORY); + protected void addLayers(boolean forceNewMap) { + String lastOpenedDirectory = ProjectUIPlugin.getDefault().getPluginPreferences() + .getString(ProjectUIPlugin.PREF_OPEN_DIALOG_DIRECTORY); FileDialog fileDialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.MULTI); - fileDialog.setFilterExtensions(new String[]{"*.shp", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$ + fileDialog.setFilterExtensions(new String[] { "*.shp", "*.*" }); //$NON-NLS-1$ //$NON-NLS-2$ if (lastOpenedDirectory != null) { fileDialog.setFilterPath(lastOpenedDirectory); } @@ -56,14 +54,15 @@ protected void addLayers( boolean forceNewMap ) { return; } String path = fileDialog.getFilterPath(); - ProjectUIPlugin.getDefault().getPluginPreferences().setValue( - ProjectUIPlugin.PREF_OPEN_DIALOG_DIRECTORY, path); + ProjectUIPlugin.getDefault().getPluginPreferences() + .setValue(ProjectUIPlugin.PREF_OPEN_DIALOG_DIRECTORY, path); ProjectUIPlugin.getDefault().savePluginPreferences(); String[] filenames = fileDialog.getFileNames(); - List urls = new ArrayList(); - for( int i = 0; i < filenames.length; i++ ) { + List urls = new ArrayList<>(); + for (int i = 0; i < filenames.length; i++) { try { - URL url = new File(path + System.getProperty("file.separator") + filenames[i]).toURL(); //$NON-NLS-1$ + URL url = new File(path + System.getProperty("file.separator") + filenames[i]) //$NON-NLS-1$ + .toURI().toURL(); urls.add(url); } catch (MalformedURLException e) { e.printStackTrace(); diff --git a/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/DropMap.java b/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/DropMap.java index 453b9bc150..8997ab846a 100644 --- a/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/DropMap.java +++ b/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/DropMap.java @@ -1,4 +1,5 @@ -/* uDig - User Friendly Desktop Internet GIS client +/** + * uDig - User Friendly Desktop Internet GIS client * http://udig.refractions.net * (C) 2004, Refractions Research Inc. * @@ -70,7 +71,7 @@ public boolean accept() { && ApplicationGIS.getActiveMap() != ApplicationGIS.NO_MAP) { return false; } - // layer droppe in map if special too + // layer dropped in map if special too if (getData() instanceof ILayer && getDestination() instanceof MapPart) { return false; } @@ -81,7 +82,7 @@ public boolean accept() { if (getData() instanceof String) { String string = (String) getData(); try { - string = URLDecoder.decode(string, "UTF-8"); + string = URLDecoder.decode(string, "UTF-8"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e2) { // so ignore... } @@ -133,7 +134,7 @@ public void perform(IProgressMonitor monitor) { } else if (getData() instanceof String) { String string = (String) getData(); try { - string = URLDecoder.decode(string, "UTF-8"); + string = URLDecoder.decode(string, "UTF-8"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e2) { // so ignore... } @@ -144,7 +145,7 @@ public void perform(IProgressMonitor monitor) { File file = new File(string); if (file.exists()) try { - url = file.toURL(); + url = file.toURI().toURL(); } catch (MalformedURLException e1) { // oh well } @@ -165,7 +166,7 @@ public void perform(IProgressMonitor monitor) { return; } } catch (Exception e) { - // ok not a file either + // OK not a file either ProjectUIPlugin.log("Some how accept() accepted: " + getData(), new Exception()); //$NON-NLS-1$ return; } diff --git a/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/SLDDropAction.java b/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/SLDDropAction.java index f6b2f318a1..f54954cf86 100644 --- a/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/SLDDropAction.java +++ b/plugins/org.locationtech.udig.project.ui/src/org/locationtech/udig/project/ui/internal/actions/SLDDropAction.java @@ -1,7 +1,7 @@ -/* - * uDig - User Friendly Desktop Internet GIS client - * http://udig.refractions.net - * (C) 2012, Refractions Research Inc. +/** + * uDig - User Friendly Desktop Internet GIS client + * http://udig.refractions.net + * (C) 2012, Refractions Research Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -27,21 +27,20 @@ public class SLDDropAction extends IDropAction { - private Style style; @Override - public boolean accept( ) { - - if( getViewerLocation()==ViewerDropLocation.NONE ) + public boolean accept() { + + if (getViewerLocation() == ViewerDropLocation.NONE) return false; - URL url=null; - // make sure we can turn the object into an sld + URL url = null; + // make sure we can turn the object into an SLD try { if (getData() instanceof URL) { url = (URL) getData(); } else if (getData() instanceof File) { - url = ((File) getData()).toURL(); + url = ((File) getData()).toURI().toURL(); } else if (getData() instanceof String) { try { url = new URL((String) getData()); @@ -50,54 +49,56 @@ public boolean accept( ) { url = new URL("file:///" + (String) getData()); //$NON-NLS-1$ } if (url != null) { - if( !url.getFile().toLowerCase().endsWith(".sld") || url.getQuery()!=null ) //$NON-NLS-1$ - url=null; + if (!url.getFile().toLowerCase().endsWith(".sld") || url.getQuery() != null) //$NON-NLS-1$ + url = null; } } } catch (MalformedURLException e) { - String msg = Messages.SLDDropAction_badSldUrl; + String msg = Messages.SLDDropAction_badSldUrl; ProjectUIPlugin.log(msg, e); } - if( url==null ) + if (url == null) return false; try { style = SLDContent.parse(url); } catch (Throwable e) { return false; } - - return style != null && (getDestination() instanceof Layer || getDestination() instanceof Map); + + return style != null + && (getDestination() instanceof Layer || getDestination() instanceof Map); } @Override - public void perform( IProgressMonitor monitor ) { + public void perform(IProgressMonitor monitor) { - if ( !accept() ) - throw new IllegalStateException("Data is not acceptable for this action! Programatic Error!!!"); //$NON-NLS-1$ + if (!accept()) + throw new IllegalStateException( + "Data is not acceptable for this action! Programatic Error!!!"); //$NON-NLS-1$ // grab the actual target Object target = getDestination(); - if ( target instanceof Layer) { + if (target instanceof Layer) { dropOnLayer(monitor, (Layer) target); - }else{ - if( target instanceof Map ){ - dropOnLayer(monitor, (Layer)((Map)target).getEditManagerInternal().getSelectedLayer()); + } else { + if (target instanceof Map) { + dropOnLayer(monitor, ((Map) target).getEditManagerInternal().getSelectedLayer()); } } } - private void dropOnLayer( IProgressMonitor monitor, Layer target ) { - Layer layer = (Layer) target; - // parse the sld object + private void dropOnLayer(IProgressMonitor monitor, Layer target) { + Layer layer = target; + // parse the SLD object try { SLDContent.apply(layer, style, monitor); layer.refresh(null); } catch (IOException e) { - String msg = Messages.SLDDropAction_sldParseError; + String msg = Messages.SLDDropAction_sldParseError; ProjectUIPlugin.log(msg, e); } } diff --git a/plugins/org.locationtech.udig.tool.edit/src/org/locationtech/udig/tool/edit/DifferenceOp.java b/plugins/org.locationtech.udig.tool.edit/src/org/locationtech/udig/tool/edit/DifferenceOp.java index eba739565e..842d9d8417 100644 --- a/plugins/org.locationtech.udig.tool.edit/src/org/locationtech/udig/tool/edit/DifferenceOp.java +++ b/plugins/org.locationtech.udig.tool.edit/src/org/locationtech/udig/tool/edit/DifferenceOp.java @@ -1,4 +1,5 @@ -/* uDig - User Friendly Desktop Internet GIS client +/** + * uDig - User Friendly Desktop Internet GIS client * http://udig.refractions.net * (C) 2004, Refractions Research Inc. * @@ -62,232 +63,256 @@ /** * Cuts the polygons in layer 1 out of the polygons in layer 2. - * + * * @author jones * @since 1.1.0 */ public class DifferenceOp implements IOp { + @Override @SuppressWarnings("unchecked") - public void op( final Display display, Object target, IProgressMonitor monitor ) throws Exception { - final ILayer[] layers=(ILayer[]) target; - final int[] value=new int[1]; - final ILayer[] from=new ILayer[1]; - final ILayer[] diff=new ILayer[1]; - PlatformGIS.syncInDisplayThread(new Runnable(){ + public void op(final Display display, Object target, IProgressMonitor monitor) + throws Exception { + final ILayer[] layers = (ILayer[]) target; + final int[] value = new int[1]; + final ILayer[] from = new ILayer[1]; + final ILayer[] diff = new ILayer[1]; + PlatformGIS.syncInDisplayThread(new Runnable() { + @Override public void run() { - LayerSelection selection=new LayerSelection(display.getActiveShell(), layers); - value[0]= selection.open(); - from[0]=selection.fromLayer; - diff[0]=selection.diffLayer; + LayerSelection selection = new LayerSelection(display.getActiveShell(), layers); + value[0] = selection.open(); + from[0] = selection.fromLayer; + diff[0] = selection.diffLayer; } }); - if( value[0]==Window.CANCEL ) + if (value[0] == Window.CANCEL) return; - ILayer fromLayer=from[0]; - ILayer diffLayer=diff[0]; - - if( !fromLayer.hasResource(FeatureSource.class) ){ - MessageDialog.openError(display.getActiveShell(), Messages.differenceOp_inputError1, fromLayer.getName()+Messages.differenceOp_inputError2); + ILayer fromLayer = from[0]; + ILayer diffLayer = diff[0]; + + if (!fromLayer.hasResource(FeatureSource.class)) { + MessageDialog.openError(display.getActiveShell(), Messages.differenceOp_inputError1, + fromLayer.getName() + Messages.differenceOp_inputError2); return; } - if( !diffLayer.hasResource(FeatureSource.class) ){ - MessageDialog.openError(display.getActiveShell(), Messages.differenceOp_inputError1, diffLayer.getName()+Messages.differenceOp_inputError2); + if (!diffLayer.hasResource(FeatureSource.class)) { + MessageDialog.openError(display.getActiveShell(), Messages.differenceOp_inputError1, + diffLayer.getName() + Messages.differenceOp_inputError2); return; } - + ShapefileDataStoreFactory dsfac = new ShapefileDataStoreFactory(); - File tmp = File.createTempFile(layers[0].getName() + "_" + layers[1].getName() + "_diff", ".shp"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - DataStore ds = dsfac.createDataStore(tmp.toURL()); + File tmp = File.createTempFile(layers[0].getName() + "_" + layers[1].getName() + "_diff", //$NON-NLS-1$ //$NON-NLS-2$ + ".shp"); //$NON-NLS-1$ + DataStore ds = dsfac.createDataStore(tmp.toURI().toURL()); final SimpleFeatureType newSchema = FeatureTypes.newFeatureType( - fromLayer.getSchema().getAttributeDescriptors().toArray( - new AttributeDescriptor[0]), "diff"); //$NON-NLS-1$ + fromLayer.getSchema().getAttributeDescriptors().toArray(new AttributeDescriptor[0]), + "diff"); //$NON-NLS-1$ ds.createSchema(newSchema); - - final FeatureSource fromSource = fromLayer.getResource(FeatureSource.class, monitor); - final FeatureSource diffSource = diffLayer.getResource(FeatureSource.class, monitor); + + final FeatureSource fromSource = fromLayer + .getResource(FeatureSource.class, monitor); + final FeatureSource diffSource = diffLayer + .getResource(FeatureSource.class, monitor); if (isGeometryCollection(fromSource.getSchema().getGeometryDescriptor())) { - MessageDialog.openError(display.getActiveShell(), Messages.differenceOp_inputError, fromLayer.getName() + Messages.differenceOp_multiGeoms); + MessageDialog.openError(display.getActiveShell(), Messages.differenceOp_inputError, + fromLayer.getName() + Messages.differenceOp_multiGeoms); return; } if (isGeometryCollection(diffSource.getSchema().getGeometryDescriptor())) { - MessageDialog.openError(display.getActiveShell(), Messages.differenceOp_inputError, fromLayer.getName() + Messages.differenceOp_multiGeoms); + MessageDialog.openError(display.getActiveShell(), Messages.differenceOp_inputError, + fromLayer.getName() + Messages.differenceOp_multiGeoms); return; } - + final DefaultFeatureCollection diffFeatures = new DefaultFeatureCollection(); diffFeatures.addAll(diffSource.getFeatures()); - - FeatureStore destStore = (FeatureStore)ds.getFeatureSource("diff"); //$NON-NLS-1$ - - // TODO: figure out whatever this FeatureReader is doing; and make it a feature collection instead - destStore.addFeatures(DataUtilities.collection(new FeatureReader(){ - // TODO this needs an undo -// ((FeatureStore)fromSource).setFeatures(new FeatureReader() { - FeatureCollection coll = fromSource.getFeatures(); - FeatureIterator iter = coll.features(); - FeatureIterator peek = coll.features(); - boolean hasNextCalled = false; - - public SimpleFeatureType getFeatureType() { - return newSchema; - } - - private Geometry diff(SimpleFeature f) { - Geometry geom = (Geometry) f.getDefaultGeometry(); - FeatureIterator i = diffFeatures.features(); - try { - while (i.hasNext()) { - SimpleFeature diff = i.next(); - Geometry g = geom.difference((Geometry) diff.getDefaultGeometry()); - if (g.isEmpty()) { - return null; + + FeatureStore destStore = (FeatureStore) ds + .getFeatureSource("diff"); //$NON-NLS-1$ + + // TODO: figure out whatever this FeatureReader is doing; and make it a feature collection + // instead + destStore.addFeatures( + DataUtilities.collection(new FeatureReader() { + // TODO this needs an undo + FeatureCollection coll = fromSource + .getFeatures(); + + FeatureIterator iter = coll.features(); + + FeatureIterator peek = coll.features(); + + boolean hasNextCalled = false; + + @Override + public SimpleFeatureType getFeatureType() { + return newSchema; + } + + private Geometry diff(SimpleFeature f) { + Geometry geom = (Geometry) f.getDefaultGeometry(); + FeatureIterator i = diffFeatures.features(); + try { + while (i.hasNext()) { + SimpleFeature diff = i.next(); + Geometry g = geom.difference((Geometry) diff.getDefaultGeometry()); + if (g.isEmpty()) { + return null; + } + geom = g; + } + } finally { + i.close(); } - geom = g; + return geom; } - } finally { - i.close(); - } - return geom; - } - - public SimpleFeature next() throws IOException, IllegalAttributeException, NoSuchElementException { - SimpleFeature source=iter.next(); - Geometry geom = diff(source); - if (geom == null || !hasNextCalled) { - throw new NoSuchElementException("Use hasNext()."); //$NON-NLS-1$ - } - - if (geom instanceof LineString) { - geom = geom.getFactory().createMultiLineString(new LineString[] {(LineString) geom}); - } - if (geom instanceof Polygon) { - geom = geom.getFactory().createMultiPolygon(new Polygon[]{(Polygon) geom}); - } - source.setDefaultGeometry(geom); - - hasNextCalled = false; - return source; - } - public boolean hasNext() throws IOException { - if (hasNextCalled) { - return iter.hasNext(); - } + @Override + public SimpleFeature next() + throws IOException, IllegalAttributeException, NoSuchElementException { + SimpleFeature source = iter.next(); + Geometry geom = diff(source); + if (geom == null || !hasNextCalled) { + throw new NoSuchElementException("Use hasNext()."); //$NON-NLS-1$ + } - // pointer chase forward to the next different geometry - try { - Geometry g = null; - while (g == null) { - if (!peek.hasNext()) { - return false; + if (geom instanceof LineString) { + geom = geom.getFactory() + .createMultiLineString(new LineString[] { (LineString) geom }); } - SimpleFeature f = peek.next(); - g = diff(f); - - if (g == null) { - iter.next(); - } else { - return true; + if (geom instanceof Polygon) { + geom = geom.getFactory() + .createMultiPolygon(new Polygon[] { (Polygon) geom }); } - } - } finally { - hasNextCalled = true; - } - return false; - } + source.setDefaultGeometry(geom); - public void close() throws IOException { - iter.close(); - peek.close(); - } - })); - - // add the diff shapefile as a udig resource + hasNextCalled = false; + return source; + } + + @Override + public boolean hasNext() throws IOException { + if (hasNextCalled) { + return iter.hasNext(); + } + + // pointer chase forward to the next different geometry + try { + Geometry g = null; + while (g == null) { + if (!peek.hasNext()) { + return false; + } + SimpleFeature f = peek.next(); + g = diff(f); + + if (g == null) { + iter.next(); + } else { + return true; + } + } + } finally { + hasNextCalled = true; + } + return false; + } + + @Override + public void close() throws IOException { + iter.close(); + peek.close(); + } + })); + + // Add the diff shapefile as a uDig resource URL url = tmp.toURI().toURL(); IRepository local = CatalogPlugin.getDefault().getLocal(); - IService service = local.acquire( url, null ); - - // List services = CatalogPlugin.getDefault().getServiceFactory().createService(tmp.toURL()); - // IService service = services.get(0); - // CatalogPlugin.getDefault().getLocalCatalog().add(service); - List< ? extends IGeoResource> resources = service.resources(null); - + IService service = local.acquire(url, null); + + List resources = service.resources(null); + IGeoResource resource = resources.get(0); - - Map map = ((Map)layers[0].getMap()); + + Map map = ((Map) layers[0].getMap()); LayerFactory factory = map.getLayerFactory(); Layer outLayer = factory.createLayer(resource); map.getLayersInternal().add(outLayer); } - static class LayerSelection extends Dialog{ + static class LayerSelection extends Dialog { private ILayer[] layers; + Combo fromCombo; + Combo diffCombo; + ILayer fromLayer; + ILayer diffLayer; - protected LayerSelection( Shell parentShell, ILayer[] layers ) { + protected LayerSelection(Shell parentShell, ILayer[] layers) { super(parentShell); - this.layers=layers; - fromLayer=layers[0]; - diffLayer=layers[1]; + this.layers = layers; + fromLayer = layers[0]; + diffLayer = layers[1]; } - - + @Override - protected Control createDialogArea( Composite parent ) { - Composite comp= (Composite) super.createDialogArea(parent); - Composite c=new Composite(comp, SWT.NONE); - c.setLayout(new GridLayout(2,true)); - - String[] names=new String[]{ - layers[0].getName(), - layers[1].getName() - }; - - Label layer2=new Label(c, SWT.NONE); + protected Control createDialogArea(Composite parent) { + Composite comp = (Composite) super.createDialogArea(parent); + Composite c = new Composite(comp, SWT.NONE); + c.setLayout(new GridLayout(2, true)); + + String[] names = new String[] { layers[0].getName(), layers[1].getName() }; + + Label layer2 = new Label(c, SWT.NONE); layer2.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); layer2.setText("Subtract: "); //$NON-NLS-1$ - - diffCombo=new Combo(c, SWT.DEFAULT); + + diffCombo = new Combo(c, SWT.DEFAULT); diffCombo.setLayoutData(new GridData(GridData.FILL_BOTH)); diffCombo.setItems(names); diffCombo.select(1); - - Label layer1=new Label(c, SWT.NONE); + + Label layer1 = new Label(c, SWT.NONE); layer1.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); layer1.setText("From: "); //$NON-NLS-1$ - - fromCombo=new Combo(c, SWT.DEFAULT); + + fromCombo = new Combo(c, SWT.DEFAULT); fromCombo.setLayoutData(new GridData(GridData.FILL_BOTH)); fromCombo.setItems(names); fromCombo.select(0); - - diffCombo.addSelectionListener(new SelectionListener(){ - public void widgetSelected( SelectionEvent e ) { + diffCombo.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { widgetDefaultSelected(e); } - public void widgetDefaultSelected( SelectionEvent e ) { - diffLayer=layers[diffCombo.getSelectionIndex()]; + @Override + public void widgetDefaultSelected(SelectionEvent e) { + diffLayer = layers[diffCombo.getSelectionIndex()]; } - + }); - - fromCombo.addSelectionListener(new SelectionListener(){ - public void widgetSelected( SelectionEvent e ) { + fromCombo.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { widgetDefaultSelected(e); } - public void widgetDefaultSelected( SelectionEvent e ) { - fromLayer=layers[fromCombo.getSelectionIndex()]; + @Override + public void widgetDefaultSelected(SelectionEvent e) { + fromLayer = layers[fromCombo.getSelectionIndex()]; } - + }); return c; } diff --git a/plugins/org.locationtech.udig.tutorials.raster/src/org/locationtech/udig/tutorials/raster/RasterTutorialHandler.java b/plugins/org.locationtech.udig.tutorials.raster/src/org/locationtech/udig/tutorials/raster/RasterTutorialHandler.java index 291351cd58..70a26d1646 100644 --- a/plugins/org.locationtech.udig.tutorials.raster/src/org/locationtech/udig/tutorials/raster/RasterTutorialHandler.java +++ b/plugins/org.locationtech.udig.tutorials.raster/src/org/locationtech/udig/tutorials/raster/RasterTutorialHandler.java @@ -1,7 +1,7 @@ -/* - * uDig - User Friendly Desktop Internet GIS client - * http://udig.refractions.net - * (C) 2012, Refractions Research Inc. +/** + * uDig - User Friendly Desktop Internet GIS client + * http://udig.refractions.net + * (C) 2012, Refractions Research Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -28,67 +28,67 @@ import org.geotools.coverage.grid.GridCoverage2D; import org.geotools.coverage.grid.GridCoverageFactory; import org.geotools.coverage.processing.CoverageProcessor; -import org.geotools.util.factory.Hints; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; +import org.geotools.util.factory.Hints; import org.opengis.parameter.ParameterValueGroup; import org.opengis.referencing.crs.CoordinateReferenceSystem; public class RasterTutorialHandler extends AbstractHandler { - public Object execute( ExecutionEvent event ) throws ExecutionException { + @Override + public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbench workbench = PlatformUI.getWorkbench(); - + Shell shell = workbench.getActiveWorkbenchWindow().getShell(); - FileDialog dialog = new FileDialog( shell, SWT.OPEN ); - dialog.setFilterExtensions(new String[]{"*.jpeg;*.jpg","*.png"}); + FileDialog dialog = new FileDialog(shell, SWT.OPEN); + dialog.setFilterExtensions(new String[] { "*.jpeg;*.jpg", "*.png" }); //$NON-NLS-1$ //$NON-NLS-2$ String filename = dialog.open(); - if( filename == null ) { + if (filename == null) { return null; } - File file = new File( filename ); - - System.out.println( file ); + File file = new File(filename); + + System.out.println(file); try { - example( file ); - } - catch( Throwable t ){ - throw new ExecutionException("Example Failed", t ); + example(file); + } catch (Throwable t) { + throw new ExecutionException("Example Failed", t); } return null; } - public static void example( File file ) throws Exception { - URL url = file.toURL(); + public static void example(File file) throws Exception { + URL url = file.toURI().toURL(); BufferedImage image = ImageIO.read(url); - - //coordinates of our raster image, in lat/lon + + // coordinates of our raster image, in lat/lon double minx = -92.36918018580701; double miny = -49.043520894708884; - + double maxx = -42.25153935511384; double maxy = 2.1002762835725868; - - CoordinateReferenceSystem crs = CRS.decode("EPSG:4326"); - ReferencedEnvelope envelope = new ReferencedEnvelope(minx,maxx,miny,maxy,crs); - + + CoordinateReferenceSystem crs = CRS.decode("EPSG:4326"); //$NON-NLS-1$ + ReferencedEnvelope envelope = new ReferencedEnvelope(minx, maxx, miny, maxy, crs); + String name = "GridCoverage"; - - GridCoverageFactory factory = new GridCoverageFactory(); - GridCoverage2D gridCoverage = (GridCoverage2D) factory.create(name,image,envelope); - - CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:24882"); - RenderingHints hints = new RenderingHints(Hints.LENIENT_DATUM_SHIFT, Boolean.TRUE); + GridCoverageFactory factory = new GridCoverageFactory(); + GridCoverage2D gridCoverage = factory.create(name, image, envelope); + + CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:24882"); //$NON-NLS-1$ + + RenderingHints hints = new RenderingHints(Hints.LENIENT_DATUM_SHIFT, Boolean.TRUE); CoverageProcessor processor = new CoverageProcessor(hints); - - ParameterValueGroup param = processor.getOperation("Resample").getParameters(); - param.parameter("Source").setValue( gridCoverage ); - param.parameter("CoordinateReferenceSystem").setValue(targetCRS); - param.parameter("InterpolationType").setValue("NearestNeighbor"); - + + ParameterValueGroup param = processor.getOperation("Resample").getParameters(); //$NON-NLS-1$ + param.parameter("Source").setValue(gridCoverage); //$NON-NLS-1$ + param.parameter("CoordinateReferenceSystem").setValue(targetCRS); //$NON-NLS-1$ + param.parameter("InterpolationType").setValue("NearestNeighbor"); //$NON-NLS-1$ //$NON-NLS-2$ + GridCoverage2D reprojected = (GridCoverage2D) processor.doOperation(param); - + ImageViewer.show(gridCoverage, "Normal Grid Coverage"); ImageViewer.show(reprojected, "Reprojected Grid Coverage"); } diff --git a/plugins/org.locationtech.udig.tutorials.shpexport/src/org/locationtech/udig/tutorials/shpexport/ShpExportOp.java b/plugins/org.locationtech.udig.tutorials.shpexport/src/org/locationtech/udig/tutorials/shpexport/ShpExportOp.java index 4cd2b3bf71..3fc8674f1c 100644 --- a/plugins/org.locationtech.udig.tutorials.shpexport/src/org/locationtech/udig/tutorials/shpexport/ShpExportOp.java +++ b/plugins/org.locationtech.udig.tutorials.shpexport/src/org/locationtech/udig/tutorials/shpexport/ShpExportOp.java @@ -1,7 +1,7 @@ -/* - * uDig - User Friendly Desktop Internet GIS client - * http://udig.refractions.net - * (C) 2012, Refractions Research Inc. +/** + * uDig - User Friendly Desktop Internet GIS client + * http://udig.refractions.net + * (C) 2012, Refractions Research Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -15,9 +15,6 @@ import java.util.HashMap; import java.util.Map; -import org.locationtech.udig.ui.PlatformGIS; -import org.locationtech.udig.ui.operations.IOp; - import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; @@ -29,6 +26,8 @@ import org.geotools.data.FeatureStore; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.data.shapefile.ShapefileDataStoreFactory; +import org.locationtech.udig.ui.PlatformGIS; +import org.locationtech.udig.ui.operations.IOp; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.GeometryDescriptor; @@ -36,74 +35,74 @@ public class ShpExportOp implements IOp { -public void op(Display display, Object target, IProgressMonitor monitor) - throws Exception { - FeatureSource source = - (FeatureSource) target; - - SimpleFeatureType featureType = source.getSchema(); - GeometryDescriptor geometryType = featureType.getGeometryDescriptor(); - CoordinateReferenceSystem crs = geometryType.getCoordinateReferenceSystem(); - - String typeName = featureType.getTypeName(); - - // String filename = promptSaveDialog( typeName ) - String filename = typeName.replace(':', '_'); - URL directory = FileLocator.toFileURL( Platform.getInstanceLocation().getURL() ); - URL shpURL = new URL(directory.toExternalForm() + filename + ".shp"); - final File file = new File( shpURL.toURI() ); - - // promptOverwrite( file ) - if (file.exists()){ - return; + @Override + public void op(Display display, Object target, IProgressMonitor monitor) throws Exception { + FeatureSource source = (FeatureSource) target; + + SimpleFeatureType featureType = source.getSchema(); + GeometryDescriptor geometryType = featureType.getGeometryDescriptor(); + CoordinateReferenceSystem crs = geometryType.getCoordinateReferenceSystem(); + + String typeName = featureType.getTypeName(); + + String filename = typeName.replace(':', '_'); + URL directory = FileLocator.toFileURL(Platform.getInstanceLocation().getURL()); + URL shpURL = new URL(directory.toExternalForm() + filename + ".shp"); //$NON-NLS-1$ + final File file = new File(shpURL.toURI()); + + // promptOverwrite( file ) + if (file.exists()) { + return; + } + + // create and write the new shapefile + ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); + Map params = new HashMap(); + params.put("url", file.toURI().toURL()); + ShapefileDataStore dataStore = (ShapefileDataStore) factory.createNewDataStore(params); + dataStore.createSchema(featureType); + + FeatureStore store = (FeatureStore) dataStore.getFeatureSource(); + store.addFeatures(source.getFeatures()); + dataStore.forceSchemaCRS(crs); } - - // create and write the new shapefile - ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); - Map params = new HashMap(); - params.put( "url", file.toURL() ); - ShapefileDataStore dataStore = - (ShapefileDataStore) factory.createNewDataStore( params ); - dataStore.createSchema( featureType ); - - FeatureStore store = (FeatureStore) dataStore.getFeatureSource(); - store.addFeatures( source.getFeatures() ); - dataStore.forceSchemaCRS( crs ); -} - -private void promptOverwrite(final Display display, final File file){ - if (!file.exists()) return; - - display.syncExec(new Runnable() { - public void run() { - boolean overwrite = MessageDialog.openConfirm(display - .getActiveShell(), "Warning", - "File Exists do you wish to overwrite?"); - if (overwrite){ - file.delete(); + + private void promptOverwrite(final Display display, final File file) { + if (!file.exists()) + return; + + display.syncExec(new Runnable() { + @Override + public void run() { + boolean overwrite = MessageDialog.openConfirm(display.getActiveShell(), "Warning", + "File Exists do you wish to overwrite?"); + if (overwrite) { + file.delete(); + } } - } - }); -} + }); + } + /** * Example of opening a save dialog in the display thread. - * + * * @param typeName * @return filename provided by the user, or null */ - private String promptSaveDialog( final String typeName ){ + private String promptSaveDialog(final String typeName) { final String filename = typeName.replace(':', '_'); final String[] result = new String[1]; - - PlatformGIS.syncInDisplayThread( new Runnable(){ + + PlatformGIS.syncInDisplayThread(new Runnable() { + @Override public void run() { Display display = Display.getCurrent(); - FileDialog dialog = new FileDialog( display.getActiveShell(), SWT.SAVE ); - - dialog.setFileName( filename+".shp"); - dialog.setText("Export "+typeName ); - dialog.setFilterExtensions( new String[]{"shp", "SHP"} ); - result[0] = dialog.open(); + FileDialog dialog = new FileDialog(display.getActiveShell(), SWT.SAVE); + + dialog.setFileName(filename + ".shp"); //$NON-NLS-1$ + dialog.setText("Export " + typeName); + dialog.setFilterExtensions(new String[] { "shp", "SHP" }); //$NON-NLS-1$ //$NON-NLS-2$ + result[0] = dialog.open(); } });