at.spardat.xma.gui.projectw.AbstractOpenXmaProjectContentProvider.java Source code

Java tutorial

Introduction

Here is the source code for at.spardat.xma.gui.projectw.AbstractOpenXmaProjectContentProvider.java

Source

/*******************************************************************************
 * Copyright (c) 2010 s IT Solutions AT Spardat GmbH .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     s IT Solutions AT Spardat GmbH - initial API and implementation
 *******************************************************************************/
package at.spardat.xma.gui.projectw;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.emf.common.util.WrappedException;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.search.internal.ui.text.FileSearchResult;
import org.eclipse.search.internal.ui.text.ReplaceRefactoring;
import org.eclipse.search.ui.ISearchQuery;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.search.ui.text.FileTextSearchScope;
import org.eclipse.search.ui.text.TextSearchQueryProvider;
import org.eclipse.search.ui.text.TextSearchQueryProvider.TextSearchInput;
import org.eclipse.ui.PlatformUI;

import at.spardat.xma.gui.projectw.refactoring.RenameSupport;

/**
 * Abstract base implementation of interface
 * <code>OpenXmaProjectContentProvider</code> providing some commonly used
 * infrastructure helper methods required for importing and refactoring (e.g.
 * rename and replace) new project contents.
 */
@SuppressWarnings("restriction")
public class AbstractOpenXmaProjectContentProvider implements OpenXmaProjectContentProvider {

    public void contributeProjectContent(IProject project, IProgressMonitor monitor) {
    }

    public String getDisplayName() {
        return getClass().getName();
    }

    public List<IFile> getFilesToOpen(IProject project) {
        return new ArrayList<IFile>();
    }

    public IClasspathEntry[] getDefaultClasspathEntries() {
        return new IClasspathEntry[] {};
    }

    public IClasspathEntry[] getSourceClasspathEntries(String projectName) {
        return new IClasspathEntry[] {};
    }

    public void postProcessProject(IProject project, IRunnableContext context) {
    }

    protected List<IFile> findModelFiles(IProject project, final Set<String> fileExtensionsToMatch) {
        final List<IFile> modelResources = new ArrayList<IFile>();
        try {
            project.accept(new IResourceVisitor() {

                public boolean visit(IResource resource) throws CoreException {
                    if (fileExtensionsToMatch.contains(resource.getFileExtension())) {
                        modelResources.add((IFile) resource);
                    }
                    return false;
                }
            });
        } catch (CoreException coreException) {
            coreException.printStackTrace();
        }
        return modelResources;
    }

    protected File downloadFile(IProject project, URL url, IProgressMonitor monitor) {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        File tempFile = null;
        try {
            tempFile = File.createTempFile(project.getName(), "zip");
            outputStream = new FileOutputStream(tempFile);
            URLConnection urlConnection = createUrlConnection(url);
            int totalWork = urlConnection instanceof HttpURLConnection
                    ? ((HttpURLConnection) urlConnection).getContentLength()
                    : 1000;
            monitor.beginTask("Download..", totalWork);
            monitor.subTask(url.getFile().substring(url.getFile().lastIndexOf("/")));
            inputStream = new BufferedInputStream(urlConnection.getInputStream());
            byte[] buffer = new byte[2048];
            int readBytes = -1;
            while ((readBytes = inputStream.read(buffer)) != -1 && !monitor.isCanceled()) {
                outputStream.write(buffer, 0, readBytes);
                monitor.worked(buffer.length);
            }
        } catch (Exception exception) {
            throw new WrappedException(exception);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
            monitor.done();
        }
        return tempFile;
    }

    protected URLConnection createUrlConnection(URL url)
            throws NoSuchAlgorithmException, KeyManagementException, IOException {
        URLConnection urlConnection = null;
        if ("https".equalsIgnoreCase(url.getProtocol())) {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { NullX509TrustManager }, new SecureRandom());
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
            httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
            urlConnection = httpsURLConnection;
        } else {
            urlConnection = url.openConnection();
        }

        return urlConnection;
    }

    private static final X509TrustManager NullX509TrustManager = new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    };

    public void renameJavaPackages(IRunnableContext context, IProject project, String oldPackageName,
            String newPackageName) {
        IJavaProject javaProject = JavaCore.create(project);
        try {
            IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
            for (int i = 0; i < roots.length; i++) {
                IPackageFragmentRoot root = roots[i];
                if (root.getKind() == IPackageFragmentRoot.K_SOURCE
                        && root.getPackageFragment(oldPackageName).exists()) {
                    IPackageFragment packageFragment = root.getPackageFragment(oldPackageName);
                    renamePackage(context, packageFragment, newPackageName);
                }
            }
        } catch (Exception exception) {
            throw new WrappedException(exception);
        }
    }

    protected void renameFolder(IProject project, String oldFolderName, String newFolderName,
            IProgressMonitor progressMonitor) {
        if (project.getFolder(oldFolderName).exists()) {
            try {
                project.getFolder(oldFolderName).move(new Path(newFolderName), true, progressMonitor);
            } catch (CoreException exception) {
                throw new WrappedException(exception);
            }
        }
    }

    protected void renamePackage(IRunnableContext context, IPackageFragment packageFragment,
            String newPackageName) {
        try {
            RenameSupport renameSupport = RenameSupport.create(packageFragment, newPackageName.toLowerCase(),
                    RenameSupport.UPDATE_REFERENCES | RenameSupport.UPDATE_TEXTUAL_MATCHES
                            | RenameSupport.RENAME_SUBPACKAGES);
            renameSupport.perform(PlatformUI.getWorkbench().getDisplay().getActiveShell(), context);
        } catch (Exception exception) {
            throw new WrappedException(exception);
        }
    }

    protected void searchAndReplace(IRunnableContext runnableContext, String searchText, String replaceString,
            IResource... resources) {
        searchAndReplace(runnableContext, searchText, replaceString, false, false, resources, new String[] { "*" });
    }

    protected void searchAndReplace(IRunnableContext runnableContext, String searchText, String replaceString,
            boolean isCaseSensitive, boolean isRegEx, IResource[] resources, String[] fileNamePatterns) {
        Change change = null;
        try {
            final ISearchQuery searchQuery = TextSearchQueryProvider.getPreferred()
                    .createQuery(new TextSearchInputImpl(searchText, isCaseSensitive, isRegEx,
                            FileTextSearchScope.newSearchScope(resources, fileNamePatterns, false)));
            NullProgressMonitor pm = new NullProgressMonitor();
            NewSearchUI.runQueryInForeground(runnableContext, searchQuery);
            //ReplaceRefactoring refactoring = new ReplaceRefactoring((FileSearchResult) searchQuery.getSearchResult(), null, true);
            //changed to reflection to handle different constructor args in Eclipse 3.6 and 3.7:           
            Class<ReplaceRefactoring> clazz = ReplaceRefactoring.class;
            Constructor<ReplaceRefactoring> ctor = null;
            ReplaceRefactoring refactoring = null;
            try {
                // try first old API
                ctor = clazz.getConstructor(FileSearchResult.class, Object[].class, Boolean.TYPE);
                refactoring = ctor.newInstance((FileSearchResult) searchQuery.getSearchResult(), null, true);
            } catch (NoSuchMethodException nsmEx) {
                // if not, use new API
                ctor = clazz.getConstructor(FileSearchResult.class, Object[].class);
                refactoring = ctor.newInstance((FileSearchResult) searchQuery.getSearchResult(), null);
            }
            refactoring.setReplaceString(replaceString);
            refactoring.checkAllConditions(pm);
            change = refactoring.createChange(pm);
            if (change == null) {
                return;
            }
            change.initializeValidationData(pm);
            if (!change.isEnabled())
                return;
            RefactoringStatus valid = change.isValid(new SubProgressMonitor(pm, 1));
            if (valid.hasFatalError())
                return;
            Change undo = change.perform(new SubProgressMonitor(pm, 1));
            if (undo != null) {
                undo.initializeValidationData(new SubProgressMonitor(pm, 1));
            }
        } catch (Exception exception) {
            throw new WrappedException(exception);
        } finally {
            if (change != null) {
                change.dispose();
            }
        }
    }

    private static class TextSearchInputImpl extends TextSearchInput {

        private final String fSearchText;
        private final boolean fIsCaseSensitive;
        private final boolean fIsRegEx;
        private final FileTextSearchScope fScope;

        public TextSearchInputImpl(String searchText, boolean isCaseSensitive, boolean isRegEx,
                FileTextSearchScope scope) {
            fSearchText = searchText;
            fIsCaseSensitive = isCaseSensitive;
            fIsRegEx = isRegEx;
            fScope = scope;
        }

        public String getSearchText() {
            return fSearchText;
        }

        public boolean isCaseSensitiveSearch() {
            return fIsCaseSensitive;
        }

        public boolean isRegExSearch() {
            return fIsRegEx;
        }

        public FileTextSearchScope getScope() {
            return fScope;
        }
    }

    public boolean isDefaultContentProvider() {
        return false;
    }

}