Autopsy  4.14.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
JythonModuleLoader.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2014 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.python;
20 
21 import java.io.File;
22 import java.io.FileNotFoundException;
23 import java.io.FilenameFilter;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Scanner;
29 import java.util.Set;
30 import java.util.logging.Level;
31 import java.util.regex.Matcher;
32 import org.openide.DialogDisplayer;
33 import org.openide.NotifyDescriptor;
34 import org.openide.modules.InstalledFileLocator;
35 import org.openide.util.NbBundle;
36 import org.openide.util.NbBundle.Messages;
37 import org.python.util.PythonInterpreter;
44 
49 public final class JythonModuleLoader {
50 
51  private static final Logger logger = Logger.getLogger(JythonModuleLoader.class.getName());
52 
59  public static List<IngestModuleFactory> getIngestModuleFactories() {
61  }
62 
69  public static List<GeneralReportModule> getGeneralReportModules() {
71  }
72  @Messages({"JythonModuleLoader.pythonInterpreterError.title=Python Modules",
73  "JythonModuleLoader.pythonInterpreterError.msg=Failed to load python modules, See log for more details"})
74  private static <T> List<T> getInterfaceImplementations(LineFilter filter, Class<T> interfaceClass) {
75  List<T> objects = new ArrayList<>();
76  Set<File> pythonModuleDirs = new HashSet<>();
77  PythonInterpreter interpreter = null;
78  // This method has previously thrown unchecked exceptions when it could not load because of non-latin characters.
79  try {
80  interpreter = new PythonInterpreter();
81  } catch (Exception ex) {
82  logger.log(Level.SEVERE, "Failed to load python Intepreter. Cannot load python modules", ex);
84  MessageNotifyUtil.Notify.show(Bundle.JythonModuleLoader_pythonInterpreterError_title(),Bundle.JythonModuleLoader_pythonInterpreterError_msg(), MessageNotifyUtil.MessageType.ERROR);
85  }
86  return objects;
87  }
88  // add python modules from 'autospy/build/cluster/InternalPythonModules' folder
89  // which are copied from 'autopsy/*/release/InternalPythonModules' folders.
90  for (File f : InstalledFileLocator.getDefault().locateAll("InternalPythonModules", "org.sleuthkit.autopsy.core", false)) { //NON-NLS
91  Collections.addAll(pythonModuleDirs, f.listFiles());
92  }
93  // add python modules from 'testuserdir/python_modules' folder
94  Collections.addAll(pythonModuleDirs, new File(PlatformUtil.getUserPythonModulesPath()).listFiles());
95 
96  for (File file : pythonModuleDirs) {
97  if (file.isDirectory()) {
98  File[] pythonScripts = file.listFiles(new PythonScriptFileFilter());
99  for (File script : pythonScripts) {
100  try (Scanner fileScanner = new Scanner(script)) {
101  while (fileScanner.hasNextLine()) {
102  String line = fileScanner.nextLine();
103  if (line.startsWith("class ") && filter.accept(line)) { //NON-NLS
104  String className = line.substring(6, line.indexOf("("));
105  try {
106  objects.add(createObjectFromScript(interpreter, script, className, interfaceClass));
107  } catch (Exception ex) {
108  logger.log(Level.SEVERE, String.format("Failed to load %s from %s", className, script.getAbsolutePath()), ex); //NON-NLS
109  // NOTE: using ex.toString() because the current version is always returning null for ex.getMessage().
110  DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
111  NbBundle.getMessage(JythonModuleLoader.class, "JythonModuleLoader.errorMessages.failedToLoadModule", className, ex.toString()),
112  NotifyDescriptor.ERROR_MESSAGE));
113  }
114  }
115  }
116  } catch (FileNotFoundException ex) {
117  logger.log(Level.SEVERE, String.format("Failed to open %s", script.getAbsolutePath()), ex); //NON-NLS
118  DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
119  NbBundle.getMessage(JythonModuleLoader.class, "JythonModuleLoader.errorMessages.failedToOpenModule", script.getAbsolutePath()),
120  NotifyDescriptor.ERROR_MESSAGE));
121  }
122  }
123  }
124  }
125  return objects;
126  }
127 
128  private static <T> T createObjectFromScript(PythonInterpreter interpreter, File script, String className, Class<T> interfaceClass) {
129  // Add the directory where the Python script resides to the Python
130  // module search path to allow the script to use other scripts bundled
131  // with it.
132  interpreter.exec("import sys"); //NON-NLS
133  String path = Matcher.quoteReplacement(script.getParent());
134  interpreter.exec("sys.path.append('" + path + "')"); //NON-NLS
135  String moduleName = script.getName().replaceAll("\\.py$", ""); //NON-NLS
136 
137  // reload the module so that the changes made to it can be loaded.
138  interpreter.exec("import " + moduleName); //NON-NLS
139  interpreter.exec("reload(" + moduleName + ")"); //NON-NLS
140 
141  // Importing the appropriate class from the Py Script which contains multiple classes.
142  interpreter.exec("from " + moduleName + " import " + className); //NON-NLS
143  interpreter.exec("obj = " + className + "()"); //NON-NLS
144 
145  T obj = interpreter.get("obj", interfaceClass); //NON-NLS
146 
147  // Remove the directory where the Python script resides from the Python
148  // module search path.
149  interpreter.exec("sys.path.remove('" + path + "')"); //NON-NLS
150 
151  return obj;
152  }
153 
154  private static class PythonScriptFileFilter implements FilenameFilter {
155 
156  @Override
157  public boolean accept(File dir, String name) {
158  return name.endsWith(".py"); //NON-NLS
159  } //NON-NLS
160  }
161 
162  private static interface LineFilter {
163 
164  boolean accept(String line);
165  }
166 
167  private static class IngestModuleFactoryDefFilter implements LineFilter {
168 
169  @Override
170  public boolean accept(String line) {
171  return (line.contains("IngestModuleFactoryAdapter") || line.contains("IngestModuleFactory")); //NON-NLS
172  }
173  }
174 
175  private static class GeneralReportModuleDefFilter implements LineFilter {
176 
177  @Override
178  public boolean accept(String line) {
179  return (line.contains("GeneralReportModuleAdapter") || line.contains("GeneralReportModule")); //NON-NLS
180  }
181  }
182 }
static< T > List< T > getInterfaceImplementations(LineFilter filter, Class< T > interfaceClass)
static List< IngestModuleFactory > getIngestModuleFactories()
static List< GeneralReportModule > getGeneralReportModules()
static< T > T createObjectFromScript(PythonInterpreter interpreter, File script, String className, Class< T > interfaceClass)
synchronized static Logger getLogger(String name)
Definition: Logger.java:124
static void show(String title, String message, MessageType type, ActionListener actionListener)

Copyright © 2012-2020 Basis Technology. Generated on: Wed Apr 8 2020
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.