1/*
2 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.xml.internal.org.jvnet.mimepull;
27
28import java.io.File;
29import java.io.IOException;
30import java.lang.reflect.Array;
31import java.lang.reflect.InvocationTargetException;
32import java.lang.reflect.Method;
33import java.util.logging.Level;
34import java.util.logging.Logger;
35
36/**
37 * Helper utility to support jdk <= jdk1.6. After jdk1.6 EOL reflection can be removed and API can be used directly.
38 */
39class TempFiles {
40
41    private static final Logger LOGGER = Logger.getLogger(TempFiles.class.getName());
42
43    private static final Class<?> CLASS_FILES;
44    private static final Class<?> CLASS_PATH;
45    private static final Class<?> CLASS_FILE_ATTRIBUTE;
46    private static final Class<?> CLASS_FILE_ATTRIBUTES;
47    private static final Method METHOD_FILE_TO_PATH;
48    private static final Method METHOD_FILES_CREATE_TEMP_FILE;
49    private static final Method METHOD_FILES_CREATE_TEMP_FILE_WITHPATH;
50
51    private static final Method METHOD_PATH_TO_FILE;
52
53    private static boolean useJdk6API;
54
55    static {
56        useJdk6API = isJdk6();
57
58        CLASS_FILES = safeGetClass("java.nio.file.Files");
59        CLASS_PATH = safeGetClass("java.nio.file.Path");
60        CLASS_FILE_ATTRIBUTE = safeGetClass("java.nio.file.attribute.FileAttribute");
61        CLASS_FILE_ATTRIBUTES = safeGetClass("[Ljava.nio.file.attribute.FileAttribute;");
62        METHOD_FILE_TO_PATH = safeGetMethod(File.class, "toPath");
63        METHOD_FILES_CREATE_TEMP_FILE = safeGetMethod(CLASS_FILES, "createTempFile", String.class, String.class, CLASS_FILE_ATTRIBUTES);
64        METHOD_FILES_CREATE_TEMP_FILE_WITHPATH = safeGetMethod(CLASS_FILES, "createTempFile", CLASS_PATH, String.class, String.class, CLASS_FILE_ATTRIBUTES);
65        METHOD_PATH_TO_FILE = safeGetMethod(CLASS_PATH, "toFile");
66    }
67
68    private static boolean isJdk6() {
69        String javaVersion = System.getProperty("java.version");
70        LOGGER.log(Level.FINEST, "Detected java version = {0}", javaVersion);
71        return javaVersion.startsWith("1.6.");
72    }
73
74    private static Class<?> safeGetClass(String className) {
75        // it is jdk 6 or something failed already before
76        if (useJdk6API) return null;
77        try {
78            return Class.forName(className);
79        } catch (ClassNotFoundException e) {
80            LOGGER.log(Level.SEVERE, "Exception cought", e);
81            LOGGER.log(Level.WARNING, "Class {0} not found. Temp files will be created using old java.io API.", className);
82            useJdk6API = true;
83            return null;
84        }
85    }
86
87    private static Method safeGetMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
88        // it is jdk 6 or something failed already before
89        if (useJdk6API) return null;
90        try {
91            return clazz.getMethod(methodName, parameterTypes);
92        } catch (NoSuchMethodException e) {
93            LOGGER.log(Level.SEVERE, "Exception cought", e);
94            LOGGER.log(Level.WARNING, "Method {0} not found. Temp files will be created using old java.io API.", methodName);
95            useJdk6API = true;
96            return null;
97        }
98    }
99
100
101    static Object toPath(File f) throws InvocationTargetException, IllegalAccessException {
102        return METHOD_FILE_TO_PATH.invoke(f);
103    }
104
105    static File toFile(Object path) throws InvocationTargetException, IllegalAccessException {
106        return (File) METHOD_PATH_TO_FILE.invoke(path);
107    }
108
109    static File createTempFile(String prefix, String suffix, File dir) throws IOException {
110
111        if (useJdk6API) {
112            LOGGER.log(Level.FINEST, "Jdk6 detected, temp file (prefix:{0}, suffix:{1}) being created using old java.io API.", new Object[]{prefix, suffix});
113            return File.createTempFile(prefix, suffix, dir);
114
115        } else {
116
117            try {
118                if (dir != null) {
119                    Object path = toPath(dir);
120                    LOGGER.log(Level.FINEST, "Temp file (path: {0}, prefix:{1}, suffix:{2}) being created using NIO API.", new Object[]{dir.getAbsolutePath(), prefix, suffix});
121                    return toFile(METHOD_FILES_CREATE_TEMP_FILE_WITHPATH.invoke(null, path, prefix, suffix, Array.newInstance(CLASS_FILE_ATTRIBUTE, 0)));
122                } else {
123                    LOGGER.log(Level.FINEST, "Temp file (prefix:{0}, suffix:{1}) being created using NIO API.", new Object[]{prefix, suffix});
124                    return toFile(METHOD_FILES_CREATE_TEMP_FILE.invoke(null, prefix, suffix, Array.newInstance(CLASS_FILE_ATTRIBUTE, 0)));
125                }
126
127            } catch (IllegalAccessException e) {
128                LOGGER.log(Level.SEVERE, "Exception caught", e);
129                LOGGER.log(Level.WARNING, "Error invoking java.nio API, temp file (path: {0}, prefix:{1}, suffix:{2}) being created using old java.io API.",
130                        new Object[]{dir != null ? dir.getAbsolutePath() : null, prefix, suffix});
131                return File.createTempFile(prefix, suffix, dir);
132
133            } catch (InvocationTargetException e) {
134                LOGGER.log(Level.SEVERE, "Exception caught", e);
135                LOGGER.log(Level.WARNING, "Error invoking java.nio API, temp file (path: {0}, prefix:{1}, suffix:{2}) being created using old java.io API.",
136                        new Object[]{dir != null ? dir.getAbsolutePath() : null, prefix, suffix});
137                return File.createTempFile(prefix, suffix, dir);
138            }
139        }
140
141    }
142
143
144}
145