-
Notifications
You must be signed in to change notification settings - Fork 278
/
LocalOfficeUtils.java
399 lines (349 loc) · 15.2 KB
/
LocalOfficeUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
* Copyright (c) 2004 - 2012; Mirko Nasato and contributors
* 2016 - 2022; Simon Braconnier and contributors
* 2022 - present; JODConverter
*
* This file is part of JODConverter - Java OpenDocument Converter.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jodconverter.local.office;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import com.sun.star.beans.PropertyValue;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XServiceInfo;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jodconverter.core.document.DocumentFamily;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.util.AssertUtils;
import org.jodconverter.core.util.OSUtils;
import org.jodconverter.core.util.StringUtils;
import org.jodconverter.local.office.utils.Lo;
import org.jodconverter.local.office.utils.Props;
import org.jodconverter.local.process.FreeBSDProcessManager;
import org.jodconverter.local.process.MacProcessManager;
import org.jodconverter.local.process.ProcessManager;
import org.jodconverter.local.process.PureJavaProcessManager;
import org.jodconverter.local.process.UnixProcessManager;
import org.jodconverter.local.process.WindowsProcessManager;
/** Provides helper functions for local office. */
public final class LocalOfficeUtils {
public static final int DEFAULT_PORT = 2002;
private static final String EXECUTABLE_DEFAULT = "program/soffice.bin";
private static final String EXECUTABLE_MAC = "program/soffice";
private static final String EXECUTABLE_MAC_41 = "MacOS/soffice";
private static final String EXECUTABLE_WINDOWS = "program/soffice.exe";
private static final Logger LOGGER = LoggerFactory.getLogger(LocalOfficeUtils.class);
/**
* This class is required in order to create a default office home only on demand, as explained by
* the Initialization-on-demand holder idiom: <a
* href="https://www.wikiwand.com/en/Initialization-on-demand_holder_idiom">Initialization-on-demand
* holder idiom</a>
*/
private static class DefaultOfficeHomeHolder {
/* default */ static final File INSTANCE;
static {
if (StringUtils.isNotBlank(System.getProperty("office.home"))) {
INSTANCE = new File(System.getProperty("office.home"));
} else if (OSUtils.IS_OS_WINDOWS) {
// Try to find the most recent version of LibreOffice or OpenOffice,
// starting with the 64-bit version. %ProgramFiles(x86)% on 64-bit
// machines; %ProgramFiles% on 32-bit ones
final String programFiles64 = System.getenv("ProgramFiles");
final String programFiles32 = System.getenv("ProgramFiles(x86)");
INSTANCE =
findOfficeHome(
EXECUTABLE_WINDOWS,
programFiles64 + File.separator + "LibreOffice",
programFiles32 + File.separator + "LibreOffice",
programFiles64 + File.separator + "LibreOffice 5",
programFiles32 + File.separator + "LibreOffice 5",
programFiles64 + File.separator + "LibreOffice 4",
programFiles32 + File.separator + "LibreOffice 4",
programFiles32 + File.separator + "OpenOffice 4",
programFiles64 + File.separator + "LibreOffice 3",
programFiles32 + File.separator + "LibreOffice 3",
programFiles32 + File.separator + "OpenOffice.org 3");
} else if (OSUtils.IS_OS_MAC) {
File homeDir =
findOfficeHome(
EXECUTABLE_MAC_41,
"/Applications/LibreOffice.app/Contents",
"/Applications/OpenOffice.app/Contents",
"/Applications/OpenOffice.org.app/Contents");
if (homeDir == null) {
homeDir =
findOfficeHome(
EXECUTABLE_MAC,
"/Applications/LibreOffice.app/Contents",
"/Applications/OpenOffice.app/Contents",
"/Applications/OpenOffice.org.app/Contents");
}
INSTANCE = homeDir;
} else {
// UNIX
// Linux or other *nix variants
INSTANCE =
findOfficeHome(
EXECUTABLE_DEFAULT,
"/usr/lib64/libreoffice",
"/usr/lib/libreoffice",
"/usr/local/lib64/libreoffice",
"/usr/local/lib/libreoffice",
"/opt/libreoffice",
"/usr/lib64/openoffice",
"/usr/lib64/openoffice.org3",
"/usr/lib64/openoffice.org",
"/usr/lib/openoffice",
"/usr/lib/openoffice.org3",
"/usr/lib/openoffice.org",
"/opt/openoffice4",
"/opt/openoffice.org3");
}
LOGGER.debug("Default office home set to {}", INSTANCE);
}
private static File findOfficeHome(final String executablePath, final String... homePaths) {
return Stream.of(homePaths)
.filter(homePath -> Files.isRegularFile(Paths.get(homePath, executablePath)))
.findFirst()
.map(File::new)
.orElse(null);
}
}
/**
* Find the best process manager that will be used to retrieve a process PID and to kill a process
* by PID.
*
* @return The best process manager according to the current OS.
*/
public static @NonNull ProcessManager findBestProcessManager() {
if (OSUtils.IS_OS_MAC) {
return MacProcessManager.getDefault();
} else if (OSUtils.IS_OS_FREE_BSD) {
return FreeBSDProcessManager.getDefault();
} else if (OSUtils.IS_OS_UNIX) {
return UnixProcessManager.getDefault();
} else if (OSUtils.IS_OS_WINDOWS) {
final WindowsProcessManager windowsProcessManager = WindowsProcessManager.getDefault();
return windowsProcessManager.isUsable()
? windowsProcessManager
: PureJavaProcessManager.getDefault();
} else {
// NOTE: UnixProcessManager can't be trusted to work on Solaris
// because of the 80-char limit on ps output there
return PureJavaProcessManager.getDefault();
}
}
/**
* Builds an array of {@link OfficeUrl} from an array of port numbers and an array of pipe names.
*
* @param portNumbers The port numbers from which office URLs will be created, may be null.
* @param pipeNames The pipe names from which office URLs will be created, may be null.
* @return an list of office URL. If both arguments are null, then an array is returned with a
* single office URL, using the default port number 2002.
*/
static @NonNull List<@NonNull OfficeUrl> buildOfficeUrls(
final @Nullable List<@NonNull Integer> portNumbers,
final @Nullable List<@NonNull String> pipeNames) {
return buildOfficeUrls(null, portNumbers, pipeNames, null);
}
/**
* Builds an array of {@link OfficeUrl} from an array of port numbers and an array of pipe names.
*
* @param host The host to which open ports belong, may be null.
* @param portNumbers The port numbers from which office URLs will be created, may be null.
* @param pipeNames The pipe names from which office URLs will be created, may be null.
* @param websocketUrls The websocket urls from which office URLs will be created, may be null.
* @return a list of office URL. If both arguments are null, then an array is returned with a
* single office URL, using the default port number 2002.
*/
/* default */ static @NonNull List<@NonNull OfficeUrl> buildOfficeUrls(
final @Nullable String host,
final @Nullable List<@NonNull Integer> portNumbers,
final @Nullable List<@NonNull String> pipeNames,
final @Nullable List<@NonNull String> websocketUrls) {
// Assign default value if no pipe names, port numbers or websocketUrls have been specified.
if ((portNumbers == null || portNumbers.isEmpty())
&& (pipeNames == null || pipeNames.isEmpty())
&& (websocketUrls == null || websocketUrls.isEmpty())) {
return Collections.singletonList(new OfficeUrl(host, DEFAULT_PORT));
}
// Build the office URL list and return it
final List<OfficeUrl> officeUrls = new ArrayList<>();
if (portNumbers != null) {
portNumbers.stream().map(p -> new OfficeUrl(host, p)).forEach(officeUrls::add);
}
if (pipeNames != null) {
pipeNames.stream().map(OfficeUrl::new).forEach(officeUrls::add);
}
if (websocketUrls != null) {
websocketUrls.stream().map(OfficeUrl::createForWebsocket).forEach(officeUrls::add);
}
return officeUrls;
}
/**
* Gets the default office home directory, which is auto-detected.
*
* @return A {@code File} instance that is the directory where lives the first detected office
* installation.
*/
public static @NonNull File getDefaultOfficeHome() {
return DefaultOfficeHomeHolder.INSTANCE;
}
/**
* Gets the {@link DocumentFamily} of the specified document, without throwing an exception if not
* found.
*
* @param document The document whose family will be returned. Must not be null.
* @return The {@link DocumentFamily} for the specified document, or {@code null} if the document
* does not represent any supported document family.
*/
public static @Nullable DocumentFamily getDocumentFamilySilently(
final @NonNull XComponent document) {
AssertUtils.notNull(document, "document must not be null");
final XServiceInfo serviceInfo = Lo.qi(XServiceInfo.class, document);
// NOTE: a GenericTextDocument is either a TextDocument, a WebDocument, or a GlobalDocument.
// So we must test for WebDocument first.
if (serviceInfo.supportsService(Lo.WEB_SERVICE)) {
return DocumentFamily.WEB;
} else if (serviceInfo.supportsService(Lo.WRITER_SERVICE)) {
return DocumentFamily.TEXT;
} else if (serviceInfo.supportsService(Lo.CALC_SERVICE)) {
return DocumentFamily.SPREADSHEET;
} else if (serviceInfo.supportsService(Lo.IMPRESS_SERVICE)) {
return DocumentFamily.PRESENTATION;
} else if (serviceInfo.supportsService(Lo.DRAW_SERVICE)) {
return DocumentFamily.DRAWING;
}
return null;
}
/**
* Gets the {@link DocumentFamily} of the specified document.
*
* @param document The document whose family will be returned. Must not be null.
* @return The {@link DocumentFamily} for the specified document.
* @throws OfficeException If the document family cannot be retrieved.
*/
public static @NonNull DocumentFamily getDocumentFamily(final @NonNull XComponent document)
throws OfficeException {
final DocumentFamily family = getDocumentFamilySilently(document);
if (family == null) {
throw new OfficeException("Document of unknown family: " + document.getClass().getName());
}
return family;
}
/**
* Gets the office executable within an office installation.
*
* @param officeHome The root (home) directory of the office installation.
* @return Aninstance of the executable file.
*/
public static @NonNull File getOfficeExecutable(final @NonNull File officeHome) {
// Mac
if (OSUtils.IS_OS_MAC) {
// Starting with LibreOffice 4.1 the location of the executable has changed on Mac.
// It's now in program/soffice. Handle both cases!
File executableFile = new File(officeHome, EXECUTABLE_MAC_41);
if (!executableFile.isFile()) {
executableFile = new File(officeHome, EXECUTABLE_MAC);
}
return executableFile;
}
// Windows
if (OSUtils.IS_OS_WINDOWS) {
return new File(officeHome, EXECUTABLE_WINDOWS);
}
// Everything else
return new File(officeHome, EXECUTABLE_DEFAULT);
}
/**
* Converts a regular java map to an array of {@code PropertyValue}, usable as arguments with UNO
* interface types.
*
* @param properties The map to convert.
* @return An array of {@code PropertyValue}.
*/
public static @NonNull PropertyValue[] toUnoProperties(
final @NonNull Map<@NonNull String, @NonNull Object> properties) {
final List<PropertyValue> propertyValues = new ArrayList<>(properties.size());
for (final Map.Entry<String, Object> entry : properties.entrySet()) {
Object value = entry.getValue();
if (value instanceof Map) {
@SuppressWarnings("unchecked")
final Map<String, Object> subProperties = (Map<String, Object>) value;
value = toUnoProperties(subProperties);
}
propertyValues.add(Props.makeProperty(entry.getKey(), value));
}
return propertyValues.toArray(new PropertyValue[0]);
}
/**
* Constructs a URL from the specified file as expected by office.
*
* @param file The file for which a URL will be constructed.
* @return A valid office URL.
*/
public static @NonNull String toUrl(final @NonNull File file) {
final String path = file.toURI().getRawPath();
final String url = path.startsWith("//") ? "file:" + path : "file://" + path;
return url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
}
/**
* Validates that the specified File instance is a valid office home directory.
*
* @param officeHome The home to validate.
* @exception IllegalStateException If the specified directory if not a valid office home
* directory.
*/
public static void validateOfficeHome(final @NonNull File officeHome) {
AssertUtils.notNull(officeHome, "officeHome must not be null");
if (!officeHome.isDirectory()) {
throw new IllegalStateException(
"officeHome doesn't exist or is not a directory: " + officeHome);
}
if (!getOfficeExecutable(officeHome).isFile()) {
throw new IllegalStateException(
"Invalid officeHome: it doesn't contain soffice.bin: " + officeHome);
}
}
/**
* Validates that the specified File instance is a valid office template profile directory.
*
* @param templateProfileDir The directory to validate.
* @exception IllegalStateException If the specified directory if not a valid office template
* profile directory.
*/
public static void validateOfficeTemplateProfileDirectory(
final @Nullable File templateProfileDir) {
// Template profile directory is not required.
if (templateProfileDir == null || new File(templateProfileDir, "user").isDirectory()) {
return;
}
throw new IllegalStateException(
"templateProfileDir doesn't appear to contain a user profile: " + templateProfileDir);
}
// Suppresses default constructor, ensuring non-instantiability.
private LocalOfficeUtils() {
throw new AssertionError("Utility class must not be instantiated");
}
}