OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 149 | Rev 180 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.jopendocument.link;
15
 
16
import org.openconcerto.utils.CollectionUtils;
17
 
18
import java.io.File;
19
import java.io.FileNotFoundException;
73 ilm 20
import java.io.FilePermission;
13 ilm 21
import java.io.IOException;
22
import java.net.MalformedURLException;
73 ilm 23
import java.net.SocketPermission;
13 ilm 24
import java.net.URL;
25
import java.net.URLClassLoader;
73 ilm 26
import java.security.CodeSource;
27
import java.security.PermissionCollection;
13 ilm 28
import java.util.List;
29
import java.util.Map;
73 ilm 30
import java.util.PropertyPermission;
13 ilm 31
import java.util.WeakHashMap;
32
 
33
/**
34
 * Connexion avec une instance d'OO
35
 *
36
 * @author Administrateur
37
 */
144 ilm 38
public abstract class OOConnexion implements AutoCloseable {
13 ilm 39
 
40
    // weak to let go OOInstallation instances
41
    private static final Map<OOInstallation, ClassLoader> loaders = new WeakHashMap<OOInstallation, ClassLoader>(2);
42
    // TODO use OOInstallation.getVersion()
43
    // for now only one version (but also works with OO2)
44
    private static final String OO_VERSION = "3";
73 ilm 45
 
46
    protected static final int PORT = 8100;
144 ilm 47
    protected static final int PORT_MAX = 8250;
73 ilm 48
 
13 ilm 49
    static {
50
        // needed to access .class inside a jar inside a jar.
51
        org.openconcerto.utils.protocol.Helper.register();
52
    }
53
 
54
    static private final URL[] getURLs(final OOInstallation ooInstall) {
55
        final List<URL> res = ooInstall.getURLs(CollectionUtils.createSet("ridl.jar", "jurt.jar", "juh.jar", "unoil.jar"));
56
 
57
        final String jarName = "OO" + OO_VERSION + "-link.jar";
58
        final URL resource = OOConnexion.class.getResource(jarName);
59
        if (resource == null)
60
            // Did you run ant in the OO3Link project (or in ours) ?
61
            throw new IllegalStateException("Missing " + jarName);
62
        res.add(org.openconcerto.utils.protocol.Helper.toJarJar(resource));
63
 
64
        return res.toArray(new URL[res.size()]);
65
    }
66
 
67
    static private final ClassLoader getLoader(final OOInstallation ooInstall) {
68
        ClassLoader res = loaders.get(ooInstall);
69
        if (res == null) {
70
            // pass our classloader otherwise the system class loader will be used. This won't work
71
            // in webstart since the classpath is loaded by JNLPClassLoader, thus a class loaded by
72
            // res couldn't refer to the classpath (e.g. this class) but only to the java library.
73 ilm 73
            res = new URLClassLoader(getURLs(ooInstall), OOConnexion.class.getClassLoader()) {
74
                @Override
75
                protected PermissionCollection getPermissions(CodeSource codesource) {
76
                    final PermissionCollection perms = super.getPermissions(codesource);
77
                    perms.add(new FilePermission(ooInstall.getExecutable().getAbsolutePath(), "execute"));
144 ilm 78
                    perms.add(new SocketPermission("localhost:" + PORT + "-" + PORT_MAX, "connect"));
73 ilm 79
                    // needed by OO jars
80
                    perms.add(new PropertyPermission("*", "read"));
81
                    // to be able to open any document
82
                    perms.add(new FilePermission("<<ALL FILES>>", "read"));
83
                    // needed by ThreadPoolExecutor.shutdown()
84
                    perms.add(new RuntimePermission("modifyThread"));
149 ilm 85
                    // needed by PrinterJob.getPrinterJob()
86
                    perms.add(new RuntimePermission("queuePrintJob"));
174 ilm 87
 
88
                    // ProcessBuilder.start() calls SecurityManager.checkExec() which requires
89
                    // absolute path (or execute on "<<ALL FILES>>")
90
 
149 ilm 91
                    // needed by OOConnexion.init() to find the port
92
                    perms.add(new FilePermission("/usr/bin/lsof", "execute"));
174 ilm 93
                    // macOS path
94
                    perms.add(new FilePermission("/usr/sbin/lsof", "execute"));
149 ilm 95
                    perms.add(new FilePermission("/bin/ps", "execute"));
96
                    perms.add(new FilePermission("C:/Windows/System32/tasklist.exe", "execute"));
97
                    perms.add(new RuntimePermission("getenv.*"));
98
                    // needed by OOConnexion.convertToUrl()
99
                    perms.add(new FilePermission("/usr/bin/gvfs-info", "execute"));
73 ilm 100
                    return perms;
101
                }
102
            };
13 ilm 103
            loaders.put(ooInstall, res);
104
        }
105
        return res;
106
    }
107
 
108
    /**
109
     * Return a connection to the default OpenOffice installation.
110
     *
111
     * @return a connection to the default OpenOffice or <code>null</code> if none is found.
112
     * @throws IllegalStateException if an error occurs while searching.
113
     */
114
    static public OOConnexion create() throws IllegalStateException {
115
        final OOInstallation ooInstall;
116
        try {
117
            ooInstall = OOInstallation.getInstance();
118
        } catch (IOException e) {
119
            throw new IllegalStateException("Couldn't find default OO installation", e);
120
        }
121
        return create(ooInstall);
122
    }
123
 
124
    static public OOConnexion create(final OOInstallation ooInstall) throws IllegalStateException {
125
        if (ooInstall == null)
126
            return null;
127
        try {
128
            final Class<?> c = getLoader(ooInstall).loadClass("org.jopendocument.link" + OO_VERSION + ".OOConnexion");
129
            return (OOConnexion) c.getConstructor(OOInstallation.class).newInstance(ooInstall);
130
        } catch (Exception e) {
131
            throw new IllegalStateException("Couldn't create OOCOnnexion", e);
132
        }
133
    }
134
 
73 ilm 135
    public static void main(String[] args) throws IOException {
142 ilm 136
        if (args.length == 0 || args.length > 2) {
137
            System.out.println("Usage : " + OOConnexion.class.getName() + " officeFile | --type param");
73 ilm 138
            System.out.println("Open officeFile in the default installation of LibreOffice");
142 ilm 139
            System.out.println("--type is either file or url");
73 ilm 140
            System.exit(1);
141
        }
144 ilm 142
        try (final OOConnexion conn = OOConnexion.create()) {
143
            if (conn == null)
144
                throw new IllegalStateException("No Office found");
145
            final boolean file;
146
            final String arg;
147
            if (args.length == 1) {
148
                file = true;
149
                arg = args[0];
150
            } else if (args[0].equals("--file")) {
151
                file = true;
152
                arg = args[1];
153
            } else if (args[0].equals("--url")) {
154
                file = false;
155
                arg = args[1];
156
            } else {
157
                throw new IllegalArgumentException("Type not valid : " + args[0]);
158
            }
159
            if (file)
160
                conn.loadDocument(new File(arg), false);
161
            else
162
                conn.loadDocumentFromURLAsync(arg, false);
142 ilm 163
        }
73 ilm 164
    }
165
 
13 ilm 166
    protected abstract Component loadDocumentFromURLAsync(final String url, final boolean hidden);
167
 
168
    /**
169
     * Load a document in OpenOffice.
170
     *
171
     * @param f the file to load.
172
     * @param hidden <code>true</code> if no frame should be visible.
173
     * @return the new component.
174
     * @throws IOException if an error occurs.
175
     */
176
    public final Component loadDocument(final File f, final boolean hidden) throws IOException {
177
        if (!f.exists())
178
            throw new FileNotFoundException(f.getAbsolutePath());
179
 
180
        return loadDocumentFromURLAsync(convertToUrl(f.getAbsolutePath()), hidden);
181
    }
182
 
183
    protected abstract String convertToUrl(String path) throws MalformedURLException;
184
 
144 ilm 185
    @Override
186
    public final void close() {
187
        this.closeConnexion();
188
    }
189
 
13 ilm 190
    public abstract void closeConnexion();
191
 
192
    /**
193
     * Whether the bridge is closed.
194
     *
195
     * @return <code>true</code> if {@link #closeConnexion()} was called or OpenOffice is now longer
196
     *         running.
197
     */
198
    public abstract boolean isClosed();
199
}