file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
PreferencesFacade.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/facades/PreferencesFacade.java
package org.hvdw.jexiftoolgui.facades; import org.hvdw.jexiftoolgui.Application; import java.util.prefs.Preferences; public class PreferencesFacade implements IPreferencesFacade { static final IPreferencesFacade thisFacade = new PreferencesFacade(); private Preferences rootNode; private PreferencesFacade() { this.rootNode = Preferences.userNodeForPackage(Application.class); } @Override public String getByKey(PreferenceKey key, int i) { return rootNode.get(key.key, null); } @Override public String getByKey(PreferenceKey key, String defaultValue) { return rootNode.get(key.key, defaultValue); } public boolean keyIsSet(PreferenceKey key) { return getByKey(key, 1360) != null; } @Override public boolean getByKey(PreferenceKey key, boolean defaultValue) { return rootNode.getBoolean(key.key, defaultValue); } @Override public void storeByKey(PreferenceKey key, String value) { rootNode.put(key.key, value); } @Override public void storeByKey(PreferenceKey key, boolean value) { rootNode.putBoolean(key.key, value); } }
1,174
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
SystemPropertyFacade.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/facades/SystemPropertyFacade.java
package org.hvdw.jexiftoolgui.facades; public class SystemPropertyFacade { public enum SystemPropertyKey { LINE_SEPARATOR("line.separator"), FILE_SEPARATOR("file.separator"), OS_NAME("os.name"), OS_ARCH("os.arch"), OS_VERSION("os.version"), USER_DIR("user.dir"), USER_HOME("user.home"), USER_NAME("user.name"), JAVA_HOME("java.home"), JAVA_VERSION("java.version"); public final String key; SystemPropertyKey(String key) { this.key = key; } } private SystemPropertyFacade() {} public static String getPropertyByKey(SystemPropertyKey key) { return getPropertyByKey(key, null); } public static String getPropertyByKey(SystemPropertyKey key, String defaultValue) { return System.getProperty(key.key, defaultValue); } }
881
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
CommandLineArguments.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/CommandLineArguments.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.MyVariables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class CommandLineArguments { private final static Logger logger = (Logger) LoggerFactory.getLogger(CommandLineArguments.class); public static File[] ProcessArguments(List<File> filesList) { String[] args = MyVariables.getcommandLineArgs(); if (args.length > 0) { // Work this out logger.debug("args.length {}", args.length); //logger.info("The command-line arguments are:"); for (String arg : args) { Path path = Paths.get(arg); File file = new File(arg); //logger.info("arg: {}", arg); if (file.exists()) { if (file.isFile()) { filesList.add(file); logger.debug("adding file {}", file.toString()); } else if (file.isDirectory()) { logger.debug("arg {} detected as directory", file.toString()); File[] listOfFiles = file.listFiles(); for (File filecontent : listOfFiles) { if (filecontent.isFile()) { logger.debug("parsing folder, adding file {} ", filecontent.toString()); filesList.add(filecontent); } // We are currently not going to recursively parse subfolders. We might end up with tens of thousands of files } } } } } //finally convert possible relative paths to canonical paths logger.debug("filesList.size() {}", filesList.size()); File[] files = new File[filesList.size()]; int counter = 0; for (File workfile : filesList) { try { String canonicalpath = workfile.getCanonicalPath(); files[counter] = new File(canonicalpath); } catch (IOException e) { logger.error("workfile.getCanonicalPath() error {}", e); e.printStackTrace(); } counter++; } logger.debug("commandline files: {}", files.toString()); return files; } }
2,517
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
ExifToolCommands.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/ExifToolCommands.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.view.Favorites; import org.slf4j.LoggerFactory; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class ExifToolCommands { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ExifToolCommands.class); private Favorites Favs = new Favorites(); public void executeCommands(String Commands, JEditorPane Output, JRadioButton UseNonPropFontradioButton, JProgressBar progressBar, String ETCommandsFoldertextField, boolean IncludeSubFolders) { int[] selectedIndices = null; File[] files = null; int counter = 0; if ("".equals(ETCommandsFoldertextField)) { selectedIndices = MyVariables.getSelectedFilenamesIndices(); files = MyVariables.getLoadedFiles(); } String fpath =""; String Result = ""; int firstIndexOf = 0; StringBuilder commandOutput = new StringBuilder(""); boolean htmlOutput = false; boolean htmlDump = false; List<String> cmdparams = new ArrayList<String>(); List<String> newCommands = new ArrayList<>(); if (UseNonPropFontradioButton.isSelected()) { Output.setFont(new Font("monospaced", Font.PLAIN, 12)); } else { Output.setFont(new Font("SansSerif", Font.PLAIN, 12)); } Commands = Commands.trim(); String orgCommands = Commands; logger.debug(" Commands \"{}\"", Commands); String exiftool = Utils.platformExiftool(); if (Commands.contains("-t ") || Commands.contains("-tab ")) { logger.debug("tabbed output requested, overrule font setting"); Output.setFont(new Font("SansSerif", Font.PLAIN, 12)); } else if (Commands.contains("-htmlDump ")) { logger.debug("htmlDump requested"); htmlDump = true; } else if (Commands.contains("-h ") || Commands.contains("-htmlFormat ")) { logger.debug("html output requested"); htmlOutput = true; } cmdparams.clear(); StringBuilder tmpcmpstring = new StringBuilder(); if (Utils.isOsFromMicrosoft()) { cmdparams.add("\"" + Utils.platformExiftool().replace("\\", "/") + "\"" ); String[] splitCommands = orgCommands.split(" "); List<String> listCommands = Arrays.asList(splitCommands); cmdparams.addAll(listCommands); } else { //Linux & MacOS cmdparams.add("/bin/sh"); cmdparams.add("-c"); tmpcmpstring = new StringBuilder(Utils.platformExiftool().replaceAll(" ", "\\ ") + " " + orgCommands + " "); } if ( !("".equals(ETCommandsFoldertextField)) ) { // The folder line is used if (IncludeSubFolders) { if (Utils.isOsFromMicrosoft()) { cmdparams.add("-r"); } else { tmpcmpstring.append(" ").append("-r"); } } if (Utils.isOsFromMicrosoft()) { cmdparams.add("\"" + ETCommandsFoldertextField + "\""); } else { //tmpcmpstring.append(" ").append("\"" + ETCommandsFoldertextField.replaceAll(" ", "\\ ") + "\""); tmpcmpstring.append(" \"" + ETCommandsFoldertextField + "\" "); } } else { counter = 1; for (int index : selectedIndices) { int finalIMG = selectedIndices.length; logger.debug("finalIMG {}", finalIMG); if (Utils.isOsFromMicrosoft()) { cmdparams.add("\"" + files[index].getPath() + "\""); } else { tmpcmpstring.append(" \"" + files[index].getPath() + "\" "); } //try } } if (!Utils.isOsFromMicrosoft()) { // Do this on linux and MacOS due to bash command cmdparams.add(tmpcmpstring.toString()); } logger.info("cmdparams {}", cmdparams.toString()); Executor executor = Executors.newSingleThreadExecutor(); boolean finalHtmlOutput = htmlOutput; boolean finalHtmlDump = htmlDump; executor.execute(() -> { try { String res = CommandRunner.runCommand(cmdparams); if (finalHtmlOutput) { Output.setContentType("text/html"); commandOutput.append("<html><body><font face=\"Helvetica\">"); commandOutput.append(res); commandOutput.append("<br><br>"); progressBar.setVisible(false); commandOutput.append("</body></html>"); Output.setText(commandOutput.toString()); } else if (finalHtmlDump) { Output.setContentType("text/html"); commandOutput.append(res); Output.setText(commandOutput.toString()); } else { Output.setContentType("text/plain"); commandOutput.append(res); commandOutput.append("\n\n"); Output.setText(commandOutput.toString()); progressBar.setVisible(false); } } catch (IOException | InterruptedException ex) { logger.error("Error executing command", ex); } }); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setVisible(true); } }); counter++; } }
5,973
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
StandardFileIO.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/StandardFileIO.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.*; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileSystemView; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.*; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.List; import org.apache.commons.io.FileUtils; import static org.hvdw.jexiftoolgui.Application.OS_NAMES.APPLE; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.*; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.LAST_OPENED_FOLDER; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.USER_HOME; public class StandardFileIO { private static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(StandardFileIO.class); public static String extract_resource_to_jexiftoolguiFolder(String resourcePath, String strjexiftoolguifolder, String targetSubFolder){ String copyresult = ""; Path resourceFile = Paths.get(strjexiftoolguifolder + File.separator); try { InputStream fileStream = StandardFileIO.getResourceAsStream(resourcePath); if(fileStream == null) return null; // Grab the file name String[] chopped = resourcePath.split("\\/"); String fileName = chopped[chopped.length-1]; if ("".equals(targetSubFolder)) { resourceFile = Paths.get(strjexiftoolguifolder + File.separator + fileName); } else { resourceFile = Paths.get(strjexiftoolguifolder + File.separator + targetSubFolder + File.separator + fileName); } // Create an output stream OutputStream out = new FileOutputStream(String.valueOf(resourceFile)); // Write the file byte[] buffer = new byte[1024]; int len = fileStream.read(buffer); while (len != -1) { out.write(buffer, 0, len); len = fileStream.read(buffer); } // Close the streams fileStream.close(); out.close(); } catch (IOException e) { copyresult = "Error creating file " + resourcePath; logger.error("Error creating file " + resourcePath); return null; } if ("".equals(copyresult)) { copyresult = "success"; logger.debug("success copying {}", resourcePath); } return copyresult; } public static String readTextFileAsString (String fileName) { // This will reference one line at a time String line = null; StringBuilder totalText = new StringBuilder(""); try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(fileName); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { logger.debug(line); totalText.append(line); } // Always close files. bufferedReader.close(); } catch(FileNotFoundException ex) { logger.debug("Unable to open file '{}'", fileName); } catch(IOException ex) { logger.debug("Error reading file '{}'", fileName); } return totalText.toString(); } public static InputStream getResourceAsStream(String path) { return Utils.class.getClassLoader().getResourceAsStream(path); } // Reads a text file from resources public static String readTextFileAsStringFromResource(String fileName) { String strCurrentLine; String strFileContents = ""; try { InputStream is = getResourceAsStream(fileName); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); strFileContents = ""; while ((strCurrentLine = reader.readLine()) != null) { strFileContents += strCurrentLine + "\r\n"; } } catch(FileNotFoundException ex) { logger.debug("Unable to open file '{}'", fileName); } catch(IOException ex) { logger.debug("Error reading file '{}'", fileName); } return strFileContents; } /* General check method which folder to open * Based on preference default folder, "always Use Last used folder" or home folder */ public static String getFolderPathToOpenBasedOnPreferences() { boolean useLastOpenedFolder = prefs.getByKey(USE_LAST_OPENED_FOLDER, false); String lastOpenedFolder = prefs.getByKey(LAST_OPENED_FOLDER, ""); String userHome = SystemPropertyFacade.getPropertyByKey(USER_HOME); String defaultStartFolder = prefs.getByKey(DEFAULT_START_FOLDER, ""); //java_11 String startFolder = !defaultStartFolder.isBlank() ? defaultStartFolder : userHome; //java_11 if (useLastOpenedFolder && !lastOpenedFolder.isBlank()) { startFolder = lastOpenedFolder; } return startFolder; } /** * When use folder loading we sometimes encounter a folder with images, but also containing one or more folders * We only want the images. * @param files * @return */ public static File[] stripFoldersFromFiles (File[] files) { //File[] realFiles = null; List<File> tmpFiles = new ArrayList<File>(); for (File file : files) { if (file.isFile()) { tmpFiles.add(file); } } File[] realFiles = tmpFiles.toArray(new File[tmpFiles.size()]); logger.debug("realFiles {}", Arrays.toString(realFiles)); return realFiles; } /* * Get the files from the "Load images" command via JFilechooser */ public static File[] getFileNames(JPanel myComponent) { File[] files = null; javax.swing.filechooser.FileFilter imgFilter; FileFilter imageFormats = null; FileSystemView fsv = FileSystemView.getFileSystemView(); String userDefinedFilefilter = prefs.getByKey(USER_DEFINED_FILE_FILTER, ""); String startFolder = getFolderPathToOpenBasedOnPreferences(); logger.debug("startfolder for load images via JFilechooser {}", startFolder); final JFileChooser jchooser = new JFileChooser(startFolder, fsv); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); jchooser.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); if (!"".equals(userDefinedFilefilter)) { String[] uDefFilefilter = userDefinedFilefilter.split(","); for (int i = 0; i < uDefFilefilter.length; i++) uDefFilefilter[i] = uDefFilefilter[i].trim(); logger.trace("String userDefinedFilefilter {} ; String[] uDefFilefilter {}", userDefinedFilefilter, Arrays.toString(uDefFilefilter)); imgFilter = new FileNameExtensionFilter(ResourceBundle.getBundle("translations/program_strings").getString("stfio.userdefinedfilter"), uDefFilefilter); imageFormats = new FileNameExtensionFilter(ResourceBundle.getBundle("translations/program_strings").getString("stfio.images"), MyConstants.SUPPORTED_IMAGES); } else { imgFilter = new FileNameExtensionFilter(ResourceBundle.getBundle("translations/program_strings").getString("stfio.images"), MyConstants.SUPPORTED_IMAGES); } FileFilter audioFormats = new FileNameExtensionFilter(ResourceBundle.getBundle("translations/program_strings").getString("stfio.audioformats"), MyConstants.SUPPORTED_AUDIOS); FileFilter videoFormats = new FileNameExtensionFilter(ResourceBundle.getBundle("translations/program_strings").getString("stfio.videoformats"), MyConstants.SUPPORTED_VIDEOS); FileFilter supFormats = new FileNameExtensionFilter(ResourceBundle.getBundle("translations/program_strings").getString("stfio.allformats"), MyConstants.SUPPORTED_FORMATS); jchooser.setMultiSelectionEnabled(true); jchooser.setDialogTitle(ResourceBundle.getBundle("translations/program_strings").getString("stfio.loadimages")); jchooser.setFileFilter(imgFilter); if (!"".equals(userDefinedFilefilter)) { jchooser.addChoosableFileFilter(imageFormats); } jchooser.addChoosableFileFilter(audioFormats); jchooser.addChoosableFileFilter(videoFormats); jchooser.addChoosableFileFilter(supFormats); int status = jchooser.showOpenDialog(myComponent); if (status == JFileChooser.APPROVE_OPTION) { files = jchooser.getSelectedFiles(); MyVariables.setLoadedFiles(files); prefs.storeByKey(LAST_OPENED_FOLDER, jchooser.getCurrentDirectory().getAbsolutePath()); logger.debug("jchooser.getCurrentDirectory().getAbsolutePath() {}", jchooser.getCurrentDirectory().getAbsolutePath()); return files; } else { files = null; } return files; } /* * Get the files from the "Load images" command via Awt Filedialog */ public static File[] getFileNamesAwt(JPanel myComponent) { Frame dialogframe = new Frame(); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); dialogframe.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); String startFolder = getFolderPathToOpenBasedOnPreferences(); String userDefinedFilefilter = prefs.getByKey(USER_DEFINED_FILE_FILTER, ""); logger.debug("startfolder for load images via Awt {}", startFolder); //logger.info("startfolder {}", startFolder); FileDialog fdchooser = new FileDialog(dialogframe, ResourceBundle.getBundle("translations/program_strings").getString("stfio.loadimages"), FileDialog.LOAD); //Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); fdchooser.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); Application.OS_NAMES os = Utils.getCurrentOsName(); if (os == APPLE) { System.setProperty("apple.awt.fileDialogForDirectories", "false"); System.setProperty("apple.awt.use-file-dialog-packages", "true"); } fdchooser.setDirectory(startFolder); fdchooser.setMultipleMode(true); fdchooser.setFilenameFilter(new FilenameFilter() { @Override public boolean accept(File file, String ext) { if (!"".equals(userDefinedFilefilter)) { String[] uDefFilefilter = userDefinedFilefilter.split(","); for (int i = 0; i < uDefFilefilter.length; i++) uDefFilefilter[i] = uDefFilefilter[i].trim(); for (int i = 0; i < uDefFilefilter.length; i++) { if (ext.toLowerCase().endsWith(uDefFilefilter[i])) { return true; } } return false; } else { for (int i = 0; i < MyConstants.SUPPORTED_FORMATS.length; i++) { if (ext.toLowerCase().endsWith(MyConstants.SUPPORTED_FORMATS[i])) { return true; } } return false; } } }); fdchooser.setVisible(true); File[] files = fdchooser.getFiles(); if ( files.length == 0) { // no selection return files = null; } MyVariables.setLoadedFiles(files); prefs.storeByKey(LAST_OPENED_FOLDER, fdchooser.getDirectory()); return files; } /* * Get the files from a folder via the "Load Directory" via JFilechooser */ public static File[] getFolderFiles(JPanel myComponent) { File[] files = null; File[] realFiles = null; String SelectedFolder; FileSystemView fsv = FileSystemView.getFileSystemView(); File startFolder = new File(getFolderPathToOpenBasedOnPreferences()); logger.debug("startFolder for Opening folder with Jfilechooser {}", getFolderPathToOpenBasedOnPreferences()); Application.OS_NAMES os = Utils.getCurrentOsName(); if (os == APPLE) { Path tmp = Paths.get(getFolderPathToOpenBasedOnPreferences()); tmp = tmp.getParent(); startFolder = tmp.toFile(); } final JFileChooser jchooser = new JFileChooser(startFolder, fsv); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); jchooser.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); jchooser.setDialogTitle(ResourceBundle.getBundle("translations/program_strings").getString("stfio.loadfolder")); jchooser.resetChoosableFileFilters(); jchooser.setAcceptAllFileFilterUsed(false); jchooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int status = jchooser.showOpenDialog(myComponent); if (status == JFileChooser.APPROVE_OPTION) { SelectedFolder = jchooser.getSelectedFile().getAbsolutePath(); File folder = new File(SelectedFolder); //files = listFiles(SelectedFolder); files = folder.listFiles(); realFiles = stripFoldersFromFiles(files); MyVariables.setLoadedFiles(realFiles); prefs.storeByKey(LAST_OPENED_FOLDER, jchooser.getCurrentDirectory().getAbsolutePath()); logger.debug("jchooser.getCurrentDirectory().getAbsolutePath() {}", jchooser.getCurrentDirectory().getAbsolutePath()); return realFiles; } else { return files = null; } //return files; } /* * Get the files from a folder via the "Load Directory" via Awt Filedialog */ public static File[] getFolderFilesAwt(JPanel myComponent) { File[] files = null; File[] realFiles = null; String SelectedFolder; Frame dialogframe = new Frame(); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); dialogframe.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); String startFolder = getFolderPathToOpenBasedOnPreferences(); logger.debug("startFolder for Opening folder with Awt {}", getFolderPathToOpenBasedOnPreferences()); Application.OS_NAMES os = Utils.getCurrentOsName(); if (os == APPLE) { Path tmp = Paths.get(getFolderPathToOpenBasedOnPreferences()); tmp = tmp.getParent(); startFolder = tmp.toFile().toString(); System.setProperty("apple.awt.fileDialogForDirectories", "true"); System.setProperty("apple.awt.use-file-dialog-packages", "false"); } FileDialog fdchooser = new FileDialog(dialogframe, ResourceBundle.getBundle("translations/program_strings").getString("stfio.loadfolder"), FileDialog.LOAD); fdchooser.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); fdchooser.setDirectory(startFolder); fdchooser.setMultipleMode(false); fdchooser.setVisible(true); SelectedFolder = fdchooser.getDirectory(); if (SelectedFolder == null) { files = null; } File folder = new File(SelectedFolder); files = folder.listFiles(); realFiles = stripFoldersFromFiles(files); MyVariables.setLoadedFiles(realFiles); prefs.storeByKey(LAST_OPENED_FOLDER, fdchooser.getDirectory()); return realFiles; } /* / This method is called from the MetDataViewPanel and copies, when relevant, the custom config file to the "user home"/jexiftoolgui_data */ public static String CopyCustomConfigFile(String fileName, String configFilePath) { String userHome = SystemPropertyFacade.getPropertyByKey(USER_HOME); String strjexiftoolguifolder = userHome + File.separator + MyConstants.MY_DATA_FOLDER; String strfileToBe = strjexiftoolguifolder + File.separator + fileName; String copyResult = ""; //NIO copy with replace existing Path copyFrom = Paths.get(configFilePath); Path copyTo = Paths.get(strfileToBe); //logger.info("copyFrom {} copyTo {}", configFilePath, strfileToBe); File testFile = new File(strfileToBe); if (testFile.exists()) { testFile.delete(); } try { Path path = Files.copy(copyFrom, copyTo, StandardCopyOption.REPLACE_EXISTING); copyResult = "successfully copied config file"; } catch (IOException e) { e.printStackTrace(); logger.error("copy of \"{}\" to \"{}\" failed with {}", configFilePath, strfileToBe, e.toString()); copyResult = e.toString(); } return copyResult; } /* / This method is called from the MetDataViewPanel and exports, when relevant, the custom config file to the "user home" */ public static String ExportCustomConfigFile(String fileName) { String userHome = SystemPropertyFacade.getPropertyByKey(USER_HOME); String strCopyTo = userHome + File.separator + fileName; String strCopyFrom = userHome + File.separator + MyConstants.MY_DATA_FOLDER + File.separator + fileName; String copyResult = ""; //NIO copy with replace existing Path copyTo = Paths.get(strCopyTo); Path copyFrom = Paths.get(strCopyFrom); //logger.info("copyFrom {} copyTo {}", configFilePath, strfileToBe); File testFile = new File(userHome + File.separator + fileName); if (testFile.exists()) { testFile.delete(); } try { Path path = Files.copy(copyFrom, copyTo, StandardCopyOption.REPLACE_EXISTING); copyResult = "successfully copied config file"; } catch (IOException e) { e.printStackTrace(); logger.error("copy of \"{}\" to \"{}\" failed with {}", strCopyFrom , strCopyTo, e.toString()); copyResult = e.toString(); } return copyResult; } /* / This method is used to import a custom config file from the path where the user also specified / the csv file for import */ public static String ImportCustomConfigFile(String fileName) { String userHome = SystemPropertyFacade.getPropertyByKey(USER_HOME); //String strjexiftoolguifolder = userHome + File.separator + MyConstants.MY_DATA_FOLDER; String strCopyTo = userHome + File.separator + MyConstants.MY_DATA_FOLDER + File.separator + fileName; String strCopyFrom = fileName; String copyResult = ""; //NIO copy with replace existing Path copyTo = Paths.get(strCopyTo); Path copyFrom = Paths.get(strCopyFrom); //logger.info("copyFrom {} copyTo {}", configFilePath, strfileToBe); File testFile = new File(strCopyTo); if (testFile.exists()) { testFile.delete(); } try { Path path = Files.copy(copyFrom, copyTo, StandardCopyOption.REPLACE_EXISTING); copyResult = "successfully copied config file"; } catch (IOException e) { e.printStackTrace(); logger.error("copy of \"{}\" to \"{}\" failed with {}", strCopyFrom , strCopyTo, e.toString()); copyResult = e.toString(); } return copyResult; } static void moveFiles(File source, File destination) { try { FileUtils.copyDirectory(source, destination); } catch (IOException e) { e.printStackTrace(); } } // Create subfolders inside our jexiftoolgui data folder // We do this from our below checkforjexiftoolguiFolder() public static String checkforJTGsubfolder(String subFolderName) { String result = ""; File newsubFolder = new File(subFolderName); if (!newsubFolder.exists()) { // the cache folder does not exist yet try { Files.createDirectories(Paths.get(subFolderName)); } catch (IOException e) { logger.error("Error creating cache directory " + subFolderName); e.printStackTrace(); result = "Error creating subfolder " + subFolderName; } } result = subFolderName; return result; } // Check if we have a jexiftoolgui_custom folder in $HOME with defaults public static String checkforjexiftoolguiFolder() { String method_result = ""; String fileToBecopied = ""; File copyFile = null; Path dataFolder, cacheFolder, logsFolder; dataFolder = cacheFolder = logsFolder = null; File fdataFolder, fcacheFolder, flogsFolder; fdataFolder = fcacheFolder = flogsFolder = null; String userHome = SystemPropertyFacade.getPropertyByKey(USER_HOME); // Check if folder exists String strjexiftoolguifolder = userHome + File.separator + MyConstants.MY_DATA_FOLDER; /* Do this for later if we are really going to move our jexiftoolgui_data folder if (Utils.isOsFromMicrosoft()) { dataFolder = Paths.get(userHome, "AppData", "Roaming", MyConstants.MY_BASE_FOLDER); cacheFolder = Paths.get(userHome, "AppData", "Local", MyConstants.MY_BASE_FOLDER, "cache"); logsFolder = Paths.get(userHome, "AppData", "Local", MyConstants.MY_BASE_FOLDER, "logs"); } else { dataFolder = Paths.get(userHome, ".local", "share", MyConstants.MY_BASE_FOLDER, "data"); cacheFolder = Paths.get(userHome, ".cache", MyConstants.MY_BASE_FOLDER); logsFolder = Paths.get(userHome, ".local", "share", MyConstants.MY_BASE_FOLDER, "logs"); } */ File jexiftoolguifolder = new File(strjexiftoolguifolder); /* Do this for later if we are really going to move our jexiftoolgui_data folder if (jexiftoolguifolder.exists()) { fcacheFolder = cacheFolder.toFile(); if (!fcacheFolder.exists()) { // no cachefolder yet try { Files.createDirectories(cacheFolder); File oldCacheFolder = new File(strjexiftoolguifolder + File.separator + "cache"); moveFiles(new File(strjexiftoolguifolder + File.separator + "cache"), fcacheFolder); oldCacheFolder.delete(); } catch (IOException ioe) { ioe.printStackTrace(); method_result = "Error creating directory " + cacheFolder; logger.error("Error creating directory " + cacheFolder); } } fdataFolder = dataFolder.toFile(); if (!fdataFolder.exists()) { // no datafolder yet } } flogsFolder = logsFolder.toFile(); File jexiftoolguifolder = new File(strjexiftoolguifolder); */ if (!jexiftoolguifolder.exists()) { // no folder yet // First create jexiftoolgui_custom in userHome try { Files.createDirectories(Paths.get(strjexiftoolguifolder)); } catch (IOException ioe) { ioe.printStackTrace(); method_result = "Error creating directory " + strjexiftoolguifolder; logger.error("Error creating directory " + strjexiftoolguifolder); } } else { //folder exists method_result = "exists"; } // Check on our cache directory and if it doesn't exist: create it! String strsubfolder = checkforJTGsubfolder(strjexiftoolguifolder + File.separator + "cache"); // Save this much used to a getter/setter MyVariables.setjexiftoolguiCacheFolder(strsubfolder); // Check on our lenses directory and if it doesn't exist: create it! strsubfolder = checkforJTGsubfolder(strjexiftoolguifolder + File.separator + "lenses"); String result = extract_resource_to_jexiftoolguiFolder("example_lens.hashmap", strjexiftoolguifolder, "lenses"); MyVariables.setlensFolder(strsubfolder); // Check on our custommetadataset directory and if it doesn't exist: create it! strsubfolder = checkforJTGsubfolder(strjexiftoolguifolder + File.separator + "custommetadatasets"); MyVariables.setcustommetadatasetFolder(strsubfolder); // Check on our args directory and if it doesn't exist: create it! strsubfolder = checkforJTGsubfolder(strjexiftoolguifolder + File.separator + "args"); String argsfolder = strjexiftoolguifolder + File.separator + "args"; String args_files[] = {"exif2iptc.args","gps2xmp.args","iptc2xmp.args","pdf2xmp.args","xmp2gps.args","xmp2pdf.args","exif2xmp.args","iptc2exif.args","iptcCore.args","xmp2exif.args","xmp2iptc.args"}; for (String args_file : args_files) { File tst_arg_file = new File(argsfolder + File.separator + args_file); if (!tst_arg_file.exists()) { result = extract_resource_to_jexiftoolguiFolder("args" + File.separator + args_file, strjexiftoolguifolder, "args"); } } // Now check if our database exists fileToBecopied = strjexiftoolguifolder + File.separator + "jexiftoolgui.db"; copyFile = new File(fileToBecopied); if (!copyFile.exists()) { logger.debug("no database yet; trying to create it"); method_result = extract_resource_to_jexiftoolguiFolder("jexiftoolgui.db", strjexiftoolguifolder, ""); if ("success".equals(method_result)) { MyVariables.setjexiftoolguiDBPath(fileToBecopied); logger.info("copied the initial database"); } } else { // the DB already exists method_result = "exists"; logger.debug("the database already exists."); MyVariables.setjexiftoolguiDBPath(fileToBecopied); } // Check if we have our (default) favorites.hashmap file fileToBecopied = strjexiftoolguifolder + File.separator + "favorites.hashmap"; copyFile = new File(fileToBecopied); if (!copyFile.exists()) { logger.debug("no favorites.hashmap yet; trying to create it"); method_result = extract_resource_to_jexiftoolguiFolder("favorites.hashmap", strjexiftoolguifolder, ""); if ("success".equals(method_result)) { logger.info("copied the initial favorites.hashmap yet"); } } //logger.info("string for DB: " + MyVariables.getjexiftoolguiDBPath()); return method_result; } public static boolean deleteDirectory(File directoryToBeDeleted) { File[] allContents = directoryToBeDeleted.listFiles(); if (allContents != null) { for (File file : allContents) { deleteDirectory(file); } } return directoryToBeDeleted.delete(); } public static String RecreateOurTempFolder () { String result = "Success"; boolean successfully_erased = true; // Get the temporary directory String tempWorkDir = System.getProperty("java.io.tmpdir") + File.separator + "jexiftoolgui"; File tmpfolder = new File (tempWorkDir); MyVariables.settmpWorkFolder(tempWorkDir); if (tmpfolder.exists()) { boolean successfully_deleted = deleteDirectory(tmpfolder); if (!successfully_deleted) { successfully_erased = false; result = "Failed to erase " + tempWorkDir + File.separator + "jexiftoolgui"; logger.error(result); } } // Now (re)create our tmpfolder try { //Files.createDirectories(Paths.get(tempWorkDir + File.separator + "jexiftoolgui")); Files.createDirectories(Paths.get(tempWorkDir)); } catch (IOException ioe) { ioe.printStackTrace(); result = "Creating folder \"" + tempWorkDir + File.separator + "jexiftoolgui failed"; logger.error(result); } // delete our tmp workfolder including contents on program exit tmpfolder.deleteOnExit(); return result; } public static String noSpacePath () throws IOException { FileChannel sourceChannel = null; FileChannel destChannel = null; String checkPath = MyVariables.getSelectedImagePath(); if (checkPath.contains(" ")) { //Only checks for first space in string, but that's enough. Even one space is too much logger.debug("path contains spaces {}", checkPath); File imgfile = new File(MyVariables.getSelectedImagePath()); String filename = imgfile.getName(); File targetfile = new File(MyVariables.gettmpWorkFolder() + File.separator + filename); if (targetfile.exists()) { return MyVariables.gettmpWorkFolder() + File.separator + filename; } else { try { //Files.copy(imgfile, targetfile); sourceChannel = new FileInputStream(imgfile).getChannel(); destChannel = new FileOutputStream(targetfile).getChannel(); destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); }finally { sourceChannel.close(); destChannel.close(); } return targetfile.getPath(); } } else { // simply return original path. Nothing to do logger.debug("No spaces in {}", checkPath); return checkPath; } } /* * This method delivers a folder path containing images to the several screens */ public String getImagePath(JPanel myComponent) { String SelectedFolder; String prefFileDialog = prefs.getByKey(PREFERRED_FILEDIALOG, "jfilechooser"); String startFolder = StandardFileIO.getFolderPathToOpenBasedOnPreferences(); if ("jfilechooser".equals(prefFileDialog)) { final JFileChooser chooser = new JFileChooser(startFolder); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); chooser.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); chooser.setDialogTitle(ResourceBundle.getBundle("translations/program_strings").getString("stfio.loadfolder")); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int status = chooser.showOpenDialog(myComponent); if (status == JFileChooser.APPROVE_OPTION) { SelectedFolder = chooser.getSelectedFile().getAbsolutePath(); return SelectedFolder; } else { return ""; } } else { JFrame dialogframe = new JFrame(""); FileDialog chooser = new FileDialog(dialogframe, ResourceBundle.getBundle("translations/program_strings").getString("stfio.loadfolder"), FileDialog.LOAD); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); dialogframe.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); chooser.setDirectory(startFolder); chooser.setMultipleMode(false); chooser.setVisible(true); SelectedFolder = chooser.getDirectory(); if (SelectedFolder == null) { return ""; } else { return SelectedFolder; } } } /* / This method copies the thumb files from the tmp folder to the cache folder / It does this in a swingworker background process */ public static void copyThumbsToCache() { // use with *ThumbnailImage.jpg and *PhotoshopThumbnail.jpg SwingWorker sw = new SwingWorker<Void, Void>() { public Void doInBackground() { String tmpWorkDir = MyVariables.gettmpWorkFolder(); Path tmpworkDirPath = Paths.get(tmpWorkDir); File tmpWorkDirFile = new File(tmpWorkDir); String userHome = SystemPropertyFacade.getPropertyByKey(USER_HOME); File[] allExtractedThumbs = tmpWorkDirFile.listFiles(); for (File thumb : allExtractedThumbs) { String thumbName = thumb.getName(); logger.debug("tmp thumb file {} in listing", thumb.getName()); if ( (thumbName.contains("ThumbnailImage.jpg")) || (thumbName.contains("PhotoshopThumbnail.jpg")) ) { logger.debug("copy thumb file {}", thumbName); String strCopyTo = MyVariables.getjexiftoolguiCacheFolder() + File.separator; String copyResult = ""; //NIO copy with replace existing Path copyTo = Paths.get(strCopyTo + thumbName); Path copyFrom = Paths.get(tmpWorkDir + File.separator + thumbName); logger.debug("thumbs copy to cache: From {} To {}", copyFrom.toString(), copyTo.toString()); File testFile = new File(strCopyTo + thumbName); if (testFile.exists()) { testFile.delete(); } try { Path path = Files.copy(copyFrom, copyTo, StandardCopyOption.REPLACE_EXISTING); copyResult = "successfully copied config file"; } catch (IOException e) { e.printStackTrace(); logger.error("copy of \"{}\" to \"{}\" failed with {}", (tmpWorkDir + File.separator + thumbName) , strCopyTo, e.toString()); copyResult = e.toString(); } // Now delete from our /tmp folder File delThumb = new File(tmpWorkDir + File.separator + thumbName); delThumb.delete(); } } return null; } }; sw.execute(); } /* / This method saves.copies a single icon to cache after having created this from an image without preview / It does this in a swingworker background process */ public static void saveIconToCache(String fileName, BufferedImage bi) { // use with *ThumbnailImage.jpg and *PhotoshopThumbnail.jpg String userHome = SystemPropertyFacade.getPropertyByKey(USER_HOME); String thumbFileName = fileName.substring(0, fileName.lastIndexOf('.')) + "_ThumbnailImage.jpg"; SwingWorker sw = new SwingWorker<Void, Void>() { public Void doInBackground() { logger.info("thumb to save {}", thumbFileName); logger.info("outputfile {}", MyVariables.getjexiftoolguiCacheFolder() + File.separator + thumbFileName.replaceAll(" ", "\\ ")); File outputfile = new File(MyVariables.getjexiftoolguiCacheFolder() + File.separator + thumbFileName.replaceAll(" ", "\\ ")); try { ImageIO.write(bi, "JPEG", outputfile); } catch (IOException e) { logger.error("saving icon to cache errors out with {}", e.toString()); e.printStackTrace(); } return null; } }; sw.execute(); } // Write Hashmap file public static String writeHashMapToFile(File hashmapfile, HashMap<String, String> myHashMap) { String result = ""; BufferedWriter bf = null; try { // create new BufferedWriter for the output file bf = new BufferedWriter(new FileWriter(hashmapfile)); // BufferedWriter overwites if exists, otherwise creates // iterate map entries for (Map.Entry<String, String> key_value : myHashMap.entrySet()) { // put key and value separated by a colon bf.write(key_value.getKey() + "::" + key_value.getValue()); // new line bf.newLine(); } bf.flush(); result = "successfully saved"; } catch (IOException e) { logger.error("Saving hashmap to file {} gives error {}", hashmapfile.toString(), e.toString()); e.printStackTrace(); result = "Error saving hashmap to file " + hashmapfile.toString(); } finally { try { // always close the writer bf.close(); } catch (Exception e) { } } return result; } public static HashMap<String, String> readHashMapFromFile(File hashmapfile) { HashMap<String, String> myHashmap = new HashMap<String, String>(); BufferedReader br = null; try { // create BufferedReader object from the File br = new BufferedReader(new FileReader(hashmapfile)); String line = null; // read file line by line while ((line = br.readLine()) != null) { // split the line by the separator: String[] parts = line.split("::"); // first part is name, second is number String key = parts[0].trim(); String value = parts[1].trim(); if (!key.equals("") && !value.equals("")) myHashmap.put(key, value); } } catch (Exception e) { logger.error("Loading hashmap from file {} failed with error {}", hashmapfile.getName(), e.toString()); e.printStackTrace(); } finally { // Always close the BufferedReader if (br != null) { try { br.close(); } catch (Exception e) { }; } } return myHashmap; } }
39,293
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
UpdateActions.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/UpdateActions.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.MyConstants; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.hvdw.jexiftoolgui.controllers.StandardFileIO.extract_resource_to_jexiftoolguiFolder; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.USER_HOME; public class UpdateActions { private IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(UpdateActions.class); static void do_Update( String sql, String Comments) { String qr = SQLiteJDBC.insertUpdateQuery(sql, "disk"); if (!"".equals(qr)) { //means we have an error JOptionPane.showMessageDialog(null, "Encountered an error " + Comments); logger.error("Encountered an error: {}", Comments); } else { // we were successful logger.debug("Successfully did: " + Comments); } } static void fill_UserMetadataCustomSet_Tables( String sql_file) { String sqlFile = StandardFileIO.readTextFileAsStringFromResource(sql_file); String[] sqlCommands = sqlFile.split("\\r?\\n"); // split on new lines for (String sqlCommand : sqlCommands) { if (!sqlCommand.startsWith("--") && !sqlCommand.equals("")) { do_Update(sqlCommand, sqlCommand); } } } static void update_1_4() { String queryresult = ""; // Version 1.4 // Add the userFavorites table and functionality for "Own commands" and "SQL queries" String sql = "Create table if not exists userFavorites (\n" +"id integer primary key autoincrement,\n" +"favorite_type text NOT NULL,\n" +"favorite_name text NOT NULL,\n" +"command_query text NOT NULL,\n" +"UNIQUE (favorite_type, favorite_name));"; do_Update(sql, "creating the table userFavorites (1.4)"); // => Add table ApplicationVersion to also check on database options. //sql = "create table if not exists ApplicationVersion ( version text );"; //do_Update(sql, "creating table ApplicationVersion (1.4"); //do_Update("delete from table ApplicationVersion;", "deleting (all) versions(s)"); //do_Update("insert into ApplicationVersion(version) values('1.4.0');", "inserting version into table ApplicationVersion"); } static void update_1_6() { String queryresult = ""; // version 1.6 // First drop some unused tables do_Update("drop table if exists CustomView","drop table CustomView"); do_Update("drop table if exists CustomViewLines","drop table CustomViewLines"); do_Update("drop table if exists CustomEdit","drop table CustomEdit"); do_Update("drop table if exists CustomEditLines","drop table CustomEditLines"); // Add the User defined custom metadata set combinations tables String sql = "Create table if not exists CustomMetadataset (\n" + " id integer primary key autoincrement,\n" + " customset_name text NOT NULL UNIQUE,\n" + " custom_config text,\n" + " unique (id, customset_name))"; do_Update(sql, "creating the table CustomMetadataset (1.6)"); sql = "Create table if not exists CustomMetadatasetLines (\n" + " id integer primary key autoincrement,\n" + " customset_name text NOT NULL,\n" + " rowcount integer,\n" + " screen_label text NOT NULL,\n" + " tag text NOT NULL,\n" + " default_value text,\n" + " UNIQUE (customset_name, tag),\n" + " foreign key(customset_name) references CustomMetadataset(customset_name))"; do_Update(sql, "creating the table CustomMetadatasetLines (1.6)"); // pre-fill both tables if necessary with isadg data queryresult = SQLiteJDBC.generalQuery("select count(customset_name) from custommetadatasetLines where customset_name='isadg'", "disk"); logger.debug("isadg test {}", queryresult.trim()); if (!"26".equals(queryresult.trim())) { fill_UserMetadataCustomSet_Tables("sql/fill_isadg.sql"); } // our data folder String strjexiftoolguifolder = SystemPropertyFacade.getPropertyByKey(USER_HOME) + File.separator + MyConstants.MY_DATA_FOLDER; // Check if isadg-struct.cfg exists File isadg = new File(strjexiftoolguifolder + File.separator + "isadg-struct.cfg"); if (isadg.exists()) { isadg.delete(); } String method_result = extract_resource_to_jexiftoolguiFolder("isadg-struct.cfg", strjexiftoolguifolder, ""); // pre-fill both tables if necessary with gps_location data queryresult = SQLiteJDBC.generalQuery("select count(customset_name) from custommetadatasetLines where customset_name='gps_location'", "disk"); logger.debug("gps_location test {}", queryresult.trim()); if (!"19".equals(queryresult.trim())) { fill_UserMetadataCustomSet_Tables("sql/fill_location.sql"); } // pre-fill both tables if necessary with gps_location data queryresult = SQLiteJDBC.generalQuery("select count(customset_name) from custommetadatasetLines where customset_name='Google Photos'", "disk"); logger.debug("Google Photos test {}", queryresult.trim()); if (!"38".equals(queryresult.trim())) { fill_UserMetadataCustomSet_Tables("sql/fill_gphotos.sql"); } } /* static void update_1_7() { // our data folder String strjexiftoolguifolder = SystemPropertyFacade.getPropertyByKey(USER_HOME) + File.separator + MyConstants.MY_DATA_FOLDER; String args_files[] = {"exif2iptc.args","gps2xmp.args","iptc2xmp.args","pdf2xmp.args","xmp2gps.args","xmp2pdf.args","exif2xmp.args","iptc2exif.args","iptcCore.args","xmp2exif.args","xmp2iptc.args"}; String str_args_folder = strjexiftoolguifolder + File.separator + "args"; File args_folder = new File(str_args_folder); if (!args_folder.exists()) { try { Files.createDirectories(Paths.get(str_args_folder)); } catch (IOException ioe) { ioe.printStackTrace(); logger.error("Error creating directory " + str_args_folder); } } for (String args_file : args_files) { String method_result = extract_resource_to_jexiftoolguiFolder("args" + File.separator + args_file, strjexiftoolguifolder, "args"); } } */ static void update_1_9() { String queryresult = ""; // our data folder String strjexiftoolguifolder = SystemPropertyFacade.getPropertyByKey(USER_HOME) + File.separator + MyConstants.MY_DATA_FOLDER; // Check if vrae.config exists File vrae = new File(strjexiftoolguifolder + File.separator + "vrae.config"); if (!vrae.exists()) { //vrae.delete(); String method_result = extract_resource_to_jexiftoolguiFolder("vrae.config", strjexiftoolguifolder, ""); // add vrae data to both tables if necessary queryresult = SQLiteJDBC.generalQuery("select count(customset_name) from custommetadatasetLines where customset_name='vrae-display'", "disk"); logger.debug("VRAE data test {}", queryresult.trim()); if (queryresult.isEmpty()) { fill_UserMetadataCustomSet_Tables("sql/fill_vrae-display.sql"); } } } static void update_2_0() { String queryresult = ""; // our data folder String strjexiftoolguifolder = SystemPropertyFacade.getPropertyByKey(USER_HOME) + File.separator + MyConstants.MY_DATA_FOLDER; // Check if extra_functions.config exists File vrae = new File(strjexiftoolguifolder + File.separator + "extra_functions.config"); if (!vrae.exists()) { //vrae.delete(); String method_result = extract_resource_to_jexiftoolguiFolder("extra_functions.config", strjexiftoolguifolder, ""); } } // ################## Start of the update stuff #################### // This is where we add extra tables or table data after an update that added extra functionality // This can also be to alter table commands // // This can also mean that we update/alter settings // This is run as background task using a swingworker public static void Updates() { SwingWorker sw = new SwingWorker<Void, Void>() { public Void doInBackground() { update_1_4(); update_1_6(); //update_1_7(); update_1_9(); update_2_0(); // Actually 2.0.2 //logger.debug("Checked and when necessary did the updates"); return null; } @Override public void done() { // maybe some time this needs to do something as well } }; sw.execute(); } }
9,510
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
ButtonsActionListener.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/ButtonsActionListener.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.editpane.EditGeotaggingdata; import org.hvdw.jexiftoolgui.view.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import static org.slf4j.LoggerFactory.getLogger; public class ButtonsActionListener implements ActionListener { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) getLogger(ButtonsActionListener.class); private ExifToolReferencePanel ETRP = new ExifToolReferencePanel(); private SimpleWebView WV = new SimpleWebView(); private Favorites Favs = new Favorites(); private ExifToolCommands YourCmnds = new ExifToolCommands(); private EditGeotaggingdata EGd = new EditGeotaggingdata(); private MetadataUserCombinations MD = new MetadataUserCombinations(); private StandardFileIO SFIO = new StandardFileIO(); public JLabel OutputLabel; public JPanel rootPanel; public JTextField CommandsParameterstextField; public JTextField geotaggingImgFoldertextField; public JTextField geotaggingGPSLogtextField; public JTextField sqlQuerytextField; public JComboBox UserCombiscomboBox; public JTextField ExpImgFoldertextField; public JTextField ETCommandsFoldertextField; private String[] params; public ButtonsActionListener(JPanel rootPanel, JLabel OutputLabel, JTextField CommandsParameterstextField, JTextField geotaggingImgFoldertextField, JTextField geotaggingGPSLogtextField, JComboBox UserCombiscomboBox, JTextField ExpImgFoldertextField, JTextField ETCommandsFoldertextField) { this.rootPanel = rootPanel; this.OutputLabel = OutputLabel; this.CommandsParameterstextField = CommandsParameterstextField; this.geotaggingImgFoldertextField = geotaggingImgFoldertextField; this.geotaggingGPSLogtextField = geotaggingGPSLogtextField; this.sqlQuerytextField = sqlQuerytextField; this.UserCombiscomboBox = UserCombiscomboBox; this.ExpImgFoldertextField = ExpImgFoldertextField; this.ETCommandsFoldertextField = ETCommandsFoldertextField; } @Override public void actionPerformed(ActionEvent gav) { // gav = gui ActionEvent List<Integer> selectedIndicesList = new ArrayList<Integer>(); OutputLabel.setText(""); // This is not nice object oriented programming but gives a nice clear structured overview switch (gav.getActionCommand()) { case "bSI": logger.debug("button buttonShowImage pressed"); Utils.displaySelectedImageInExternalViewer(); break; case "CommandshB": logger.debug("button CommandshelpButton pressed"); WV.HTMLView(ResourceBundle.getBundle("translations/program_help_texts").getString("exiftoolcommandstitle"), ResourceBundle.getBundle("translations/program_help_texts").getString("exiftoolcommands"), 700, 550); break; case "ExifhB": case "xmpHB": logger.debug("button Exifhelp or xmpHelp pressed"); JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 700, ResourceBundle.getBundle("translations/program_help_texts").getString("exifandxmphelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("exifhelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "lCBBHB": logger.debug("button leftCheckBoxBarHelpButton pressed"); JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 700, ResourceBundle.getBundle("translations/program_help_texts").getString("leftcheckboxbarhelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("leftcheckboxbartitle"), JOptionPane.INFORMATION_MESSAGE); break; case "geotHb": logger.debug("button geotagginghelpButton pressed"); JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 700, ResourceBundle.getBundle("translations/program_help_texts").getString("geotagginghelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("geotagginghelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "gpsMcb": logger.debug("button gpsMapcoordinatesButton pressed"); Utils.openBrowser("https://www.mapcoordinates.net/en"); break; case "gpsHb": logger.debug("button gpsHelpbutton pressed"); JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 600, ResourceBundle.getBundle("translations/program_help_texts").getString("gpshelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("gpshelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "CopyHb": logger.debug("button CopyHelpbutton pressed"); JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_help_texts").getString("copymetadatatext")), ResourceBundle.getBundle("translations/program_help_texts").getString("copymetadatatitle"), JOptionPane.INFORMATION_MESSAGE); break; case "gpanoHb": logger.debug("button gpanoHelpbutton pressed"); JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_help_texts").getString("gpanohelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("gpanohelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "lensHb": logger.debug("button lensHelpbutton pressed"); JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_help_texts").getString("lenshelptext")), ResourceBundle.getBundle("translations/program_help_texts").getString("lenshelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "sPHb": logger.debug("button stringPlusHelpbutton pressed"); break; case "CommandsclearPSFB": logger.debug("button CommandsclearParameterSFieldButton pressed"); CommandsParameterstextField.setText(""); break; case "ACommFavorb": logger.debug("button AddCommandFavoritebutton pressed"); if (CommandsParameterstextField.getText().length()>0) { Favs.showDialog(rootPanel, "AddFavorite", "Exiftool_Command", CommandsParameterstextField.getText()); } else { JOptionPane.showMessageDialog(rootPanel, ResourceBundle.getBundle("translations/program_strings").getString("msd.nocommandparams"), ResourceBundle.getBundle("translations/program_strings").getString("msd.nocommandparams"), JOptionPane.WARNING_MESSAGE); } break; case "LCommFavb": logger.debug("button LoadCommandFavoritebutton pressed"); //YourCmnds.LoadCommandFavorite(rootPanel, CommandsParameterstextField); CommandsParameterstextField.setText(Favs.showDialog(rootPanel, "SelectFavorite", "Exiftool_Command", "")); break; case "geoIFb": logger.debug("button geotaggingImgFolderbutton pressed"); //String ImgPath = EGd.getImagePath(rootPanel); String ImgPath = SFIO.getImagePath(rootPanel); if (!"".equals(ImgPath)) { geotaggingImgFoldertextField.setText(ImgPath); } break; case "geoGPSLb": logger.debug("button geotaggingGPSLogbutton pressed"); String TrackFile = EGd.gpsLogFile(rootPanel); if (!"".equals(TrackFile)) { geotaggingGPSLogtextField.setText(TrackFile); } break; case "udcCNB": logger.debug("button udcCreateNewButton pressed"); MD.showDialog(rootPanel); MetadataUserCombinations MUC = new MetadataUserCombinations(); String[] views = MUC.loadCustomSets("fill_combo"); UserCombiscomboBox.setModel(new DefaultComboBoxModel(views)); break; case "udcHb": logger.debug("button udcHelpbutton pressed"); //Utils.openBrowser(ProgramTexts.ProjectWebSite + "/manual/jexiftoolgui_usercombis.html"); Utils.openBrowser(ProgramTexts.ProjectWebSite + "/manual/index.html#userdefinedmetadatacombinations"); break; case "sidecarhelp": Utils.openBrowser(ProgramTexts.ProjectWebSite + "/manual/index.html#sidecar"); break; case "expIFb": logger.debug("button ExpBrowseButton pressed"); ImgPath = SFIO.getImagePath(rootPanel); if (!"".equals(ImgPath)) { ExpImgFoldertextField.setText(ImgPath); } break; case "etCmdBtn": logger.debug("button ETCBrowseButton pressed"); ImgPath = SFIO.getImagePath(rootPanel); if (!"".equals(ImgPath)) { ETCommandsFoldertextField.setText(ImgPath); } break; } } }
9,835
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
LeftPanePopupMenuListener.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/LeftPanePopupMenuListener.java
package org.hvdw.jexiftoolgui.controllers; import org.slf4j.LoggerFactory; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ResourceBundle; public class LeftPanePopupMenuListener { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LeftPanePopupMenuListener.class); public JTable tableListfiles; public JPopupMenu myPopupMenu = new JPopupMenu(); public LeftPanePopupMenuListener( JTable tableListfiles, JPopupMenu myPopupMenu) { this.tableListfiles = tableListfiles; this.myPopupMenu = myPopupMenu; //addPopupMenu(); } /** * Insert one or more rows into the table at the clicked row. * * @param e */ // just an example to further work out private void loadDirectory(ActionEvent e) { // something here } /** * Add a popup menu to the left tablelistfiles table to handle insertion and * deletion of rows. */ public void addPopupMenu() { myPopupMenu = new JPopupMenu(); // Menu items. JMenuItem menuItem = new JMenuItem(ResourceBundle.getBundle("translations/program_strings").getString("fmenu.loaddirectory")); // index 0 menuItem.addActionListener(new MyMenuHandler()); myPopupMenu.add(menuItem); menuItem = new JMenuItem(ResourceBundle.getBundle("translations/program_strings").getString("fmenu.loadimages")); // index 1 menuItem.addActionListener(new MyMenuHandler()); myPopupMenu.add(menuItem); menuItem = new JMenuItem(ResourceBundle.getBundle("translations/program_strings").getString("btn.displayimages")); // index 2 menuItem.addActionListener(new MyMenuHandler()); myPopupMenu.add(menuItem); menuItem = new JMenuItem(ResourceBundle.getBundle("translations/program_strings").getString("btn.compareimgs")); // index 3 menuItem.addActionListener(new MyMenuHandler()); myPopupMenu.add(menuItem); menuItem = new JMenuItem(ResourceBundle.getBundle("translations/program_strings").getString("btn.slideshow")); // index 4 menuItem.addActionListener(new MyMenuHandler()); myPopupMenu.add(menuItem); tableListfiles.addMouseListener(new MyPopupListener()); } /** * Listen for popup menu invocation. * Need both mousePressed and mouseReleased for cross platform support. */ public class MyPopupListener extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { showPopup(e); } @Override public void mouseReleased(MouseEvent e) { showPopup(e); } private void showPopup(MouseEvent e) { if (e.isPopupTrigger()) { // Enable or disable the "Display Image" and "Sildeshow" menu item // depending on whether a row is selected. myPopupMenu.getComponent(2).setEnabled( tableListfiles.getSelectedRowCount() > 0); myPopupMenu.getComponent(4).setEnabled( tableListfiles.getSelectedRowCount() > 0); // Enable or disable "Compare images" >= 2 rows selected myPopupMenu.getComponent(3).setEnabled( tableListfiles.getSelectedRowCount() > 1); myPopupMenu.show(e.getComponent(), e.getX(), e.getY()); } } } /** * Handle popup menu commands. */ class MyMenuHandler implements ActionListener { /** * Popup menu actions. * * @param e the menu event. */ @Override public void actionPerformed(ActionEvent e) { JMenuItem item = (JMenuItem) e.getSource(); if (item.getText().equals(ResourceBundle.getBundle("translations/program_strings").getString("fmenu.loaddirectory"))) { //loadDirectory(e); //mainScreen.loadImages("images"); } else if (item.getText().equals(ResourceBundle.getBundle("translations/program_strings").getString("fmenu.loadimages"))) { //loadImages(e); } else if (item.getText().equals(ResourceBundle.getBundle("translations/program_strings").getString("btn.displayimages"))) { //loadImages(e); } else if (item.getText().equals(ResourceBundle.getBundle("translations/program_strings").getString("btn.compareimgs"))) { //loadImages(e); } else if (item.getText().equals(ResourceBundle.getBundle("translations/program_strings").getString("btn.slideshow"))) { //loadImages(e); } } } }
4,896
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
SingletonEnum.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/SingletonEnum.java
package org.hvdw.jexiftoolgui.controllers; import ch.qos.logback.classic.Logger; import org.slf4j.LoggerFactory; public enum SingletonEnum { INSTANCE; private final static Logger logger = (Logger) LoggerFactory.getLogger(SingletonEnum.class); private SingletonEnum() { System.out.println("Singleton call"); } }
339
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
SQLiteJDBC.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/SQLiteJDBC.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import java.sql.*; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; public class SQLiteJDBC { private static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(SQLiteJDBC.class); static public Connection connect() { // ######################### The basic necessary stuff ###################3 Connection conn = null; String url; try { // db parameters boolean isWindows = Utils.isOsFromMicrosoft(); if (isWindows) { url = "jdbc:sqlite:" + MyVariables.getjexiftoolguiDBPath(); } else { url = "jdbc:sqlite:" + MyVariables.getjexiftoolguiDBPath().replace(" ", "\\ "); } // create a connection to the database conn = DriverManager.getConnection(url); logger.debug("Connection to SQLite DB has been established."); } catch (SQLException e) { System.out.println(e.getMessage()); } return conn; } static public Connection connect(String dbType) { // ######################### The basic necessary stuff ###################3 Connection conn = null; String url; try { // db parameters boolean isWindows = Utils.isOsFromMicrosoft(); if ("inmemory".equals(dbType)) { url = "jdbc:sqlite::memory:"; } else { if (isWindows) { url = "jdbc:sqlite:" + MyVariables.getjexiftoolguiDBPath(); } else { url = "jdbc:sqlite:" + MyVariables.getjexiftoolguiDBPath().replace(" ", "\\ "); } } // create a connection to the database conn = DriverManager.getConnection(url); if ("inmemory".equals(dbType)) { logger.debug("Connection to in Memeory SQLite DB has been established."); } else { logger.debug("Connection to SQLite DB has been established."); } } catch (SQLException e) { System.out.println(e.getMessage()); } return conn; } static public String generalQuery(String sql, String dbType) { String DBresult = ""; String queryFields; StringBuilder sbresult = new StringBuilder(); // get the fields that are being queried on and immediately remove spaces if (sql.contains("distinct")) { queryFields = Utils.stringBetween(sql.toLowerCase(), "select distinct", "from").replaceAll("\\s+", ""); // regex "\s" is space, extra \ to escape the first \; } else { queryFields = Utils.stringBetween(sql.toLowerCase(), "select", "from").replaceAll("\\s+", ""); // regex "\s" is space, extra \ to escape the first \; } logger.debug("the general query queryfields returned string: " + queryFields); String[] dbFields = queryFields.split(","); try (Connection conn = connect(dbType); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)){ int noOfFields = dbFields.length; //logger.debug("nooffields: " + String.valueOf(noOfFields)); int counter = 1; while (rs.next()) { for (String dbfield : dbFields) { if ( (noOfFields) > counter) { sbresult.append(rs.getString(dbfield) + "\t"); counter ++; } else { sbresult.append(rs.getString(dbfield) + SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); counter = 1; } } } } catch (SQLException e) { logger.error("sql error: " + e.getMessage()); sbresult.append(e.getMessage()); } return sbresult.toString(); } static public String singleFieldQuery(String sql, String field) { String DBresult = ""; StringBuilder sbresult = new StringBuilder(); String typeDB = "inmemory"; try ( Connection conn = connect(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)){ // loop through the result set while (rs.next()) { sbresult.append(rs.getString(field) + "\n"); } } catch (SQLException e) { logger.error(e.getMessage()); } logger.trace("singlefieldQuery result {}", sbresult.toString()); return sbresult.toString(); } static public String countQuery(String sql) { String DBresult = ""; try (Connection conn = connect(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)){ rs.next(); // You always have a row, with the count int count = rs.getInt(1); DBresult = String.valueOf(count).trim(); } catch (SQLException e) { logger.error(e.getMessage()); } return DBresult; } static public String insertUpdateQuery(String sql, String dbType) { String queryresult = ""; try { Connection conn = connect(dbType); Statement stmt = conn.createStatement(); stmt.executeUpdate(sql); } catch (SQLException e) { logger.error(e.getMessage()); queryresult = e.getMessage(); } logger.trace("insertUpdateQueryResult {}", queryresult); return queryresult; } static public String bulkInsertUpdateQuery(String[] sqls, String dbType) { String queryresult = ""; try { Connection conn = connect(dbType); Statement stmt = conn.createStatement(); for (String sql : sqls) { stmt.executeUpdate(sql); } } catch (SQLException e) { logger.error(e.getMessage()); queryresult = e.getMessage(); } logger.trace("insertUpdateQueryResult {}", queryresult); return queryresult; } // ################### End of the basic necessary stuff ################### }
6,734
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
MenuActionListener.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/MenuActionListener.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.*; import org.hvdw.jexiftoolgui.datetime.DateTime; import org.hvdw.jexiftoolgui.datetime.ModifyAllDateTime; import org.hvdw.jexiftoolgui.datetime.ModifyDateTime; import org.hvdw.jexiftoolgui.datetime.ShiftDateTime; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.hvdw.jexiftoolgui.metadata.CreateArgsFile; import org.hvdw.jexiftoolgui.metadata.ExportMetadata; import org.hvdw.jexiftoolgui.metadata.MetaData; import org.hvdw.jexiftoolgui.metadata.RemoveMetadata; import org.hvdw.jexiftoolgui.model.CompareImages; import org.hvdw.jexiftoolgui.model.GuiConfig; import org.hvdw.jexiftoolgui.renaming.RenamePhotos; import org.hvdw.jexiftoolgui.view.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.OS_NAME; import static org.slf4j.LoggerFactory.getLogger; public class MenuActionListener implements ActionListener { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) getLogger(MenuActionListener.class); PreferencesDialog prefsDialog = new PreferencesDialog(); private DateTime dateTime = new DateTime(); private MetadataUserCombinations MD = new MetadataUserCombinations(); private MetaData metaData = new MetaData(); private ExportMetadata ExpMD = new ExportMetadata(); private SimpleWebView WV = new SimpleWebView(); public int[] selectedIndices; public List<Integer> selectedIndicesList = new ArrayList<>(); public JFrame frame; public JPanel rootPanel; public JSplitPane splitPanel; public JLabel OutputLabel; public JMenuBar menuBar; public JProgressBar progressBar; public JComboBox UserCombiscomboBox; public MenuActionListener(JFrame frame, JPanel rootPanel, JSplitPane splitPanel, JMenuBar menuBar, JLabel OutputLabel, JProgressBar progressBar, JComboBox UserCombiscomboBox) { this.frame = frame; this.rootPanel = rootPanel; this.splitPanel = splitPanel; this.menuBar = menuBar; this.OutputLabel = OutputLabel; this.progressBar = progressBar; this.UserCombiscomboBox = UserCombiscomboBox; } // menuListener public void actionPerformed(ActionEvent mev) { String[] dummy = null; logger.info("Selected: {}", mev.getActionCommand()); selectedIndicesList = MyVariables.getselectedIndicesList(); if (selectedIndicesList == null) { selectedIndicesList = new ArrayList<>(); } OutputLabel.setText(""); switch (mev.getActionCommand()) { case "Preferences": prefsDialog.showDialog(); break; case "Exit": StandardFileIO.deleteDirectory(new File(MyVariables.gettmpWorkFolder()) ); CompareImages.CleanUp(); GuiConfig.SaveGuiConfig(frame, rootPanel, splitPanel); System.exit(0); break; case "Rename photos": RenamePhotos renPhotos = new RenamePhotos(); if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { renPhotos.showDialog(true); } else { renPhotos.showDialog(false); } break; case "Copy all metadata to xmp format": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { metaData.copyToXmp(OutputLabel); OutputLabel.setText(""); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "Repair JPGs with corrupted metadata": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.repairjpgs")); metaData.repairJPGMetadata( progressBar); OutputLabel.setText(""); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "Remove metadata": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { RemoveMetadata rmMetadata = new RemoveMetadata(); rmMetadata.showDialog(progressBar); OutputLabel.setText(""); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "Shift Date/time": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { ShiftDateTime SDT = new ShiftDateTime(); SDT.showDialog(progressBar); OutputLabel.setText(""); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "Modify Date/time": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { ModifyDateTime MDT = new ModifyDateTime(); MDT.showDialog(progressBar); OutputLabel.setText(""); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "Modify all dates and times": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { ModifyAllDateTime MADT = new ModifyAllDateTime(); MADT.showDialog(progressBar); OutputLabel.setText(""); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "Set file date to DateTimeOriginal": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { dateTime.setFileDateTimeToDateTimeOriginal(progressBar, "image"); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "Set movie date to CreateDate": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { dateTime.setFileDateTimeToDateTimeOriginal(progressBar, "movie"); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "Create args file(s)": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { CreateArgsFile CAF = new CreateArgsFile(); CAF.showDialog(selectedIndices, MyVariables.getLoadedFiles(), progressBar); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "Export all previews/thumbs from selected": if ( !(selectedIndicesList == null) && (selectedIndicesList.size() > 0) ) { OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.extractpreviewsthumbs")); Utils.ExportPreviewsThumbnails(progressBar); OutputLabel.setText(""); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgslong")), ResourceBundle.getBundle("translations/program_strings").getString("msd.noimgs"), JOptionPane.WARNING_MESSAGE); } break; case "UserMetadata": MD.showDialog(rootPanel); MetadataUserCombinations MUC = new MetadataUserCombinations(); String[] views = MUC.loadCustomSets("fill_combo"); UserCombiscomboBox.setModel(new DefaultComboBoxModel(views)); break; case "DeleteFavorites": Favorites Favs = new Favorites(); Favs.showDialog(rootPanel, "DeleteFavorite", "Exiftool_Command", ""); break; case "DeleteLenses": SelectmyLens SmL = new SelectmyLens(); SmL.showDialog(rootPanel, "delete lens"); break; case "ExiftoolDatabase": ExiftoolReference.showDialog(); break; case "About jExifToolGUI": WV.HTMLView(ResourceBundle.getBundle("translations/program_help_texts").getString("abouttitle"), ResourceBundle.getBundle("translations/program_help_texts").getString("abouttext"), 500, 450); break; case "About ExifTool": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_help_texts").getString("aboutexiftool")), ResourceBundle.getBundle("translations/program_help_texts").getString("aboutexiftooltitle"), JOptionPane.INFORMATION_MESSAGE); break; case "jExifToolGUI homepage": Utils.openBrowser(ProgramTexts.ProjectWebSite); break; case "ExifTool homepage": Utils.openBrowser("https://exiftool.org/"); break; case "Online manual": Utils.openBrowser(ProgramTexts.ProjectWebSite + "/manual/index.html"); break; case "onlinemanuales": Utils.openBrowser("https://docs.museosabiertos.org/jexiftoolgui"); break; case "Youtube channel": Utils.openBrowser("https://www.youtube.com/playlist?list=PLAHD8RNkeuGdyRH7BKFefc7p72Dp6jVjW"); break; case "Credits": String Credits = StandardFileIO.readTextFileAsStringFromResource("texts/credits.html"); WV.HTMLView(ResourceBundle.getBundle("translations/program_strings").getString("hmenu.credits"), String.format(ProgramTexts.HTML, 600, Credits), 700, 600); break; case "System/Program info": String os = SystemPropertyFacade.getPropertyByKey(OS_NAME); if (os.contains("APPLE") || os.contains("Mac") ) { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 650, Utils.systemProgramInfo()), ResourceBundle.getBundle("translations/program_strings").getString("sys.title"), JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 500, Utils.systemProgramInfo()), ResourceBundle.getBundle("translations/program_strings").getString("sys.title"), JOptionPane.INFORMATION_MESSAGE); } break; case "License": Utils.showLicense(rootPanel); break; case "Check for new version": Utils.checkForNewVersion("menu"); break; case "Translate": //Utils.openBrowser("https://github.com/hvdwolf/jExifToolGUI/blob/master/translations/Readme.md"); Utils.openBrowser("https://hosted.weblate.org/projects/jexiftoolgui/"); break; case "Changelog": Utils.openBrowser("https://github.com/hvdwolf/jExifToolGUI/blob/master/Changelog.md"); break; case "Donate": Utils.openBrowser("https://hvdwolf.github.io/jExifToolGUI/donate.html"); // Disable for the time being //WebPageInPanel WPIP = new WebPageInPanel(); //WPIP.WebPageInPanel(rootPanel,"https://hvdwolf.github.io/jExifToolGUI/donate.html", 700,300); break; // Below this line we will add our Help sub menu containing the helptexts topics in this program case "editdataexif": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 700, ResourceBundle.getBundle("translations/program_help_texts").getString("exifandxmphelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("exifhelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "editdataxmp": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 700, ResourceBundle.getBundle("translations/program_help_texts").getString("exifandxmphelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("xmphelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "editdatagps": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 600, ResourceBundle.getBundle("translations/program_help_texts").getString("gpshelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("gpshelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "editdatageotag": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 700, ResourceBundle.getBundle("translations/program_help_texts").getString("geotagginghelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("geotagginghelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "editdatagpano": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_help_texts").getString("gpanohelp")), ResourceBundle.getBundle("translations/program_help_texts").getString("gpanohelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "editdatalens": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_help_texts").getString("lenshelptext")), ResourceBundle.getBundle("translations/program_help_texts").getString("lenshelptitle"), JOptionPane.INFORMATION_MESSAGE); break; case "copydata": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_help_texts").getString("copymetadatatext")), ResourceBundle.getBundle("translations/program_help_texts").getString("copymetadatatitle"), JOptionPane.INFORMATION_MESSAGE); break; case "exiftoolcommands": WV.HTMLView(ResourceBundle.getBundle("translations/program_help_texts").getString("exiftoolcommandstitle"), ResourceBundle.getBundle("translations/program_help_texts").getString("exiftoolcommands"), 700, 500); break; case "exiftooldb": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 700, ResourceBundle.getBundle("translations/program_help_texts").getString("exiftooldbhelptext")), ResourceBundle.getBundle("translations/program_help_texts").getString("exiftooldbtitle"), JOptionPane.INFORMATION_MESSAGE); break; case "menurenaminginfo": JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 700, ResourceBundle.getBundle("translations/program_help_texts").getString("renamingtext")), ResourceBundle.getBundle("translations/program_help_texts").getString("renamingtitle"), JOptionPane.INFORMATION_MESSAGE); break; default: break; } } }
18,044
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
ExifTool.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/ExifTool.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.Application; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; import static org.hvdw.jexiftoolgui.Utils.getCurrentOsName; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.EXIFTOOL_PATH; public class ExifTool { private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ExifTool.class); /* * This method tries to find exiftool in the path on the several OSes */ public static String getExiftoolInPath() { String res; List<String> cmdparams; Application.OS_NAMES currentOs = getCurrentOsName(); if (currentOs == Application.OS_NAMES.MICROSOFT) { //String[] params = {"c:\\Windows\\System32\\where.exe", "exiftool.exe"}; String[] params = {"c:\\Windows\\System32\\cmd.exe", "/c", "where", "exiftool"}; //String[] params = {"where", "exiftool"}; cmdparams = Arrays.asList(params); } else { String[] params = {"which", "exiftool"}; cmdparams = Arrays.asList(params); } try { res = CommandRunner.runCommand(cmdparams); // res returns path to exiftool; on error on windows "INFO: Could not ...", on linux returns nothing } catch (IOException | InterruptedException ex) { logger.debug("Error executing command. error {}", ex.toString()); //res = ex.getMessage(); res = "Error executing find command."; } return res; } /** * This method checkWindowPaths checks if: * the string does not contain multiple paths * and if exiftool is not in c:\windows or in c:\windows\System32 * @param pathResult * @return String res with PATH or message */ public static String checkWindowPaths (String pathResult) { String res = ""; // First check whether we have multiple exiftool versions in our path String[] lines = pathResult.split(System.getProperty("line.separator")); logger.debug("lines is {}", Arrays.toString(lines)); logger.info("line 0 is {}", lines[0]); logger.info("number of lines {}", Integer.toString(lines.length)); for ( int i = 0; i<= lines.length; i++) { if ( (lines[i].toLowerCase()).contains("c:\\windows\\exiftool.exe") || (lines[i].toLowerCase()).contains("c:\\windows\\system32\\exiftool.exe") ) { res = "not allowed windows PATH"; } else if ( (lines[i].toLowerCase()).contains("exiftool(-k).exe") ) { res = "exiftool -k version"; } else { res = lines[i]; } } return res; } /////////////////// Locate exiftool ////////////// /* * File chooser to locate exiftool when user comes from checkExifTool * and selected "Specify Location" */ public static String whereIsExiftool(JPanel myComponent) { String exiftool = ""; String selectedBinary = ""; boolean isWindows = Utils.isOsFromMicrosoft(); final JFileChooser chooser = new JFileChooser(); if (isWindows) { FileFilter filter = new FileNameExtensionFilter("(*.exe)", "exe"); chooser.setFileFilter(filter); } chooser.setMultiSelectionEnabled(false); chooser.setDialogTitle(ResourceBundle.getBundle("translations/program_strings").getString("exift.dlgtitle")); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int status = chooser.showOpenDialog(myComponent); if (status == JFileChooser.APPROVE_OPTION) { selectedBinary = chooser.getSelectedFile().getPath(); String tmpstr = selectedBinary.toLowerCase(); if (isWindows) { if (tmpstr.contains("exiftool.exe")) { exiftool = selectedBinary; } else if (tmpstr.contains("exiftool(-k).exe")) { logger.info("User tries to use exiftool(-k).exe. Ask to rename and try again"); //JOptionPane.showMessageDialog(myComponent, ProgramTexts.wrongETbinaryfromStartup, ResourceBundle.getBundle("translations/program_strings").getString("exift.wrongexebin"), JOptionPane.WARNING_MESSAGE); exiftool = "exiftool(-k).exe"; } else { exiftool = "no exiftool binary"; } } else if ( (tmpstr.contains("exiftool")) && (!(tmpstr.contains("jexiftoolgui.db"))) ) { exiftool = selectedBinary; } else { exiftool = "no exiftool binary"; } } else if (status == JFileChooser.CANCEL_OPTION) { exiftool = "cancelled"; } //logger.info("what is given back from whereisexiftool: {}", exiftool); return exiftool; } /* * If no exiftool found in the path and neither in the preferences, ask the user * where he/she installed it or offer to download it. * Otherwise simply exit the program */ static public void checkExifTool(JPanel myComponent) { String returnValue = ""; String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("exift.optlocation"), ResourceBundle.getBundle("translations/program_strings").getString("exift.optdownload"), ResourceBundle.getBundle("translations/program_strings").getString("exift.optstop")}; //JOptionPane.showOptionDialog(null,"I can not find exiftool in the preferences or I can not find exiftool at all","exiftool missing",JOptionPane.ERROR_MESSAGE); int choice = JOptionPane.showOptionDialog(null, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_help_texts").getString("noexiftool")), ResourceBundle.getBundle("translations/program_help_texts").getString("noexiftooltitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); if (choice == 0) { // open file chooser // Do this from the PreferencesDialog class as it actually belongs there returnValue = whereIsExiftool(myComponent); logger.info("returnValue is: {}", returnValue); if (returnValue.equals("cancelled")) { JOptionPane.showMessageDialog(myComponent, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_strings").getString("exift.cancelledetlocatefromstartup")), ResourceBundle.getBundle("translations/program_strings").getString("exift.lookupcancelled"), JOptionPane.WARNING_MESSAGE); System.exit(0); } else if (returnValue.equals("no exiftool binary")) { JOptionPane.showMessageDialog(myComponent, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_strings").getString("exift.wrongetbinaryfromstartup")), ResourceBundle.getBundle("translations/program_strings").getString("exift.wrongexebin"), JOptionPane.WARNING_MESSAGE); System.exit(0); } else if ( returnValue.contains("exiftool(-k).exe") || returnValue.contains("-k")) { JOptionPane.showMessageDialog(myComponent, String.format(ProgramTexts.HTML, 600, ResourceBundle.getBundle("translations/program_strings").getString("exift.exifktxt")), ResourceBundle.getBundle("translations/program_strings").getString("exift.exifktitle"), JOptionPane.WARNING_MESSAGE); System.exit(0); } else { // Yes. It looks like we have a correct exiftool selected // remove all possible line breaks returnValue = returnValue.replace("\n", "").replace("\r", ""); prefs.storeByKey(EXIFTOOL_PATH, returnValue); } } else if (choice == 1) { JOptionPane.showMessageDialog(myComponent, String.format(ProgramTexts.HTML, 450, ProgramTexts.downloadInstallET), ResourceBundle.getBundle("translations/program_strings").getString("exift.download"), JOptionPane.INFORMATION_MESSAGE); // open exiftool site Utils.openBrowser("https://exiftool.org/"); System.exit(0); } else { // exit program System.exit(0); } } public static String showVersion(JLabel OutputLabel) { boolean isWindows = Utils.isOsFromMicrosoft(); List<String> cmdparams = new ArrayList<>(); String exv = ""; String exiftool_path = prefs.getByKey(EXIFTOOL_PATH, ""); if (isWindows) { cmdparams.add("\"" + exiftool_path + "\""); } else { cmdparams.add(exiftool_path); } cmdparams.add("-ver"); try { exv = CommandRunner.runCommand(cmdparams).replace("\n", "").replace("\r", ""); OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.exiftoolavailable") + exv); MyVariables.setExiftoolVersion(exv); logger.debug("version from isExecutable check {}", exv); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command"); exv = "Error executing command"; } return exv; } }
9,857
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
ImageFunctions.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/ImageFunctions.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.*; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.imageio.IIOException; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.FileImageInputStream; import javax.imageio.stream.ImageInputStream; import javax.swing.*; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.*; import java.util.List; import static org.hvdw.jexiftoolgui.Application.OS_NAMES.APPLE; import static org.hvdw.jexiftoolgui.Utils.*; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.USER_HOME; public class ImageFunctions { // A big deal was copied from Dennis Damico's FastPhotoTagger // And he copied it almost 100% from Wyat Olsons original ImageTagger Imagefunctions (2005) // Extended with additional functionality private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ImageFunctions.class); /* / This gets all image data using exiftool, but only returns the basic image data / The total tag data is put into a hashmap via a getter/setter */ public static int[] getImageMetaData (File file) { // BASIC_IMG_DATA = {"-n", "-S", "-imagewidth", "-imageheight", "-orientation", "-iso", "-fnumber", "-exposuretime", "-focallength", "-focallengthin35mmformat"} int[] basicdata = {0, 0, 999, 0, 0, 0, 0, 0}; long tmpvalue; String tmpValue; HashMap<String, String> imgBasicData = new HashMap<String, String>(); //Directory metadata = null; String filename = file.getName().replace("\\", "/"); String exiftool = Utils.platformExiftool(); List<String> cmdparams = new ArrayList<String>(); cmdparams.add(exiftool.trim()); //cmdparams.addAll(Arrays.asList(MyConstants.BASIC_IMG_DATA)); cmdparams.add("-n"); cmdparams.add("-S"); cmdparams.add("-a"); cmdparams.add(file.getPath()); int counter = 0; String who =""; try { who = CommandRunner.runCommand(cmdparams); logger.debug("res is {}", who); } catch (IOException | InterruptedException ex) { logger.error("Error executing command", ex.toString()); } if (who.length() > 0) { String[] lines = who.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); for (String line : lines) { String[] parts = line.split(":", 2); imgBasicData.put(parts[0].trim(), parts[1].trim()); try { if (parts[0].contains("ImageWidth")) { basicdata[0] = Integer.parseInt(parts[1].trim()); } else if (parts[0].contains("ImageHeight")) { basicdata[1] = Integer.parseInt(parts[1].trim()); } else if (parts[0].contains("Orientation")) { basicdata[2] = Integer.parseInt(parts[1].trim()); } } catch (NumberFormatException e) { e.printStackTrace(); logger.info("error Integer.parseInt {}", e); } //} counter++; } MyVariables.setimgBasicData(imgBasicData); logger.trace("imgBasicData {}", imgBasicData); HashMap<String, HashMap<String, String> > imagesData = MyVariables.getimagesData(); imagesData.put(filename, imgBasicData); MyVariables.setimagesData(imagesData); // Note: 100 images will create 300~600 Kb in the total imagesData hashmap. } return basicdata; } /* / This only gets width, height and rotation for an image. Although exiftool is slower than java for jpeg, it is faster for other file formats * and gives better results for orientation. See also below the getImageDimension method: same performance */ public static int[] getWidthHeightOrientation (File file) { int[] basicdata = {0, 0, 999, 0, 0, 0, 0, 0}; /* // Standard java imageIO //BufferedImage bimg = ImageIO.read(new File(filename)); //int width = bimg.getWidth(); //int height = bimg.getHeight(); //Or public static int getOrientation(File imageFile){ int result = 0; ImageIcon image = new ImageIcon(imageFile.getPath()); if (image.getIconWidth() > image.getIconHeight()) { result = 0; } else { result = 1; } image = null; return result; } */ String exiftool = Utils.platformExiftool(); List<String> cmdparams = new ArrayList<String>(); cmdparams.add(exiftool.trim()); cmdparams.add("-n"); cmdparams.add("-S"); cmdparams.add("-imagewidth"); cmdparams.add("-imageheight"); cmdparams.add("-orientation"); cmdparams.add(file.getPath()); String w_h_o =""; try { w_h_o = CommandRunner.runCommand(cmdparams); logger.debug("res is {}", w_h_o); } catch (IOException | InterruptedException ex) { logger.error("Error executing command", ex.toString()); } if (w_h_o.length() > 0) { String[] lines = w_h_o.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); for (String line : lines) { String[] parts = line.split(":", 2); try { if (parts[0].contains("ImageWidth")) { basicdata[0] = Integer.parseInt(parts[1].trim()); } else if (parts[0].contains("ImageHeight")) { basicdata[1] = Integer.parseInt(parts[1].trim()); } else if (parts[0].contains("Orientation")) { basicdata[2] = Integer.parseInt(parts[1].trim()); } } catch (NumberFormatException e) { e.printStackTrace(); logger.info("error Integer.parseInt {}", e); } } } return basicdata; } /** * Gets image dimensions for given file * @param imgFile image file * @return dimensions of image * @throws IOException if the file is not a known image * * This is one of the fastest, if not the fastest, java method to get this data * for png files is is between 50~100ms * but average operation is around 700 ms for jpegs * while exiftool does it in ~235ms */ public static Dimension getImageDimension(File imgFile) throws IOException { int pos = imgFile.getName().lastIndexOf("."); if (pos == -1) throw new IOException("No extension for file: " + imgFile.getAbsolutePath()); String suffix = imgFile.getName().substring(pos + 1); Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix); while(iter.hasNext()) { ImageReader reader = iter.next(); try { ImageInputStream stream = new FileImageInputStream(imgFile); reader.setInput(stream); int width = reader.getWidth(reader.getMinIndex()); int height = reader.getHeight(reader.getMinIndex()); return new Dimension(width, height); } catch (IOException e) { logger.error("Error reading: " + imgFile.getAbsolutePath(), e); } finally { reader.dispose(); } } throw new IOException("Not a known image file: " + imgFile.getAbsolutePath()); } /* / This one is used to get all metadata in the background for further use */ public static void getImageData (JLabel[] mainScreenLabels, JProgressBar progressBar, JButton buttonSearchMetadata) { HashMap<String, String> imgBasicData = new HashMap<String, String>(); String exiftool = Utils.platformExiftool(); List<String> basiccmdparams = new ArrayList<String>(); basiccmdparams.add(exiftool.trim()); basiccmdparams.add("-n"); basiccmdparams.add("-S"); basiccmdparams.add("-a"); boolean files_null = false; File[] files = MyVariables.getLoadedFiles(); SwingWorker sw = new SwingWorker<Void, Void>() { public Void doInBackground() { List<String> cmdparams = new ArrayList<String>(); cmdparams.addAll(basiccmdparams); for (File file : files) { cmdparams.add(file.getPath()); } logger.debug("Show getBulkImageData command string: {}", String.join(" ", cmdparams)); String imgTags = ""; try { imgTags = CommandRunner.runCommand(cmdparams); logger.debug("complete images metadata is {}", imgTags); } catch (IOException | InterruptedException ex) { logger.error("Error executing command", ex.toString()); } int counter = 0; if (imgTags.length() > 0) { String filename = ""; String prev_filename = ""; String[] lines = imgTags.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); boolean initialized = true; HashMap<String, String> imgBasicData = new HashMap<String, String>(); MyVariables.setimgBasicData(imgBasicData); HashMap<String, HashMap<String, String>> imagesData = new HashMap<String, HashMap<String, String>>(); MyVariables.setimagesData(imagesData); for (String line : lines) { if (line.startsWith("======== ")) { String[] arrfilename = line.split(" ",2); //logger.info("filename : {}", filename); filename = arrfilename[1].trim(); //logger.info("\n\n\nfile no. : {} filename: {}\n\n", String.valueOf(counter), filename); if (counter == 0) { prev_filename = filename; //imgBasicData.clear(); imgBasicData = new HashMap<String, String>(); //imagesData.clear(); } else { MyVariables.setimgBasicData(imgBasicData); logger.debug("\n\n prev_filename {} imgBasicData {}\n\n", prev_filename, imgBasicData.toString()); //logger.debug("\n\n prev_filename {}\n\n", prev_filename); imagesData = MyVariables.getimagesData(); imagesData.put(prev_filename, imgBasicData); MyVariables.setimagesData(imagesData); prev_filename = filename; //imgBasicData.clear(); imgBasicData = new HashMap<String, String>(); } counter++; } else { if (line.contains(":")) { String[] parts = line.split(":", 2); imgBasicData.put(parts[0].trim(), parts[1].trim()); } else { imgBasicData.put("Error in tag", "Error in value"); logger.info("Error in tag or value for file {}", filename); } } } // And the last image data logger.debug("\n\n prev_filename {}\n\n", prev_filename); imagesData = MyVariables.getimagesData(); imagesData.put(prev_filename, imgBasicData); MyVariables.setimagesData(imagesData); //logger.info("imagesData\n {}", imagesData.toString()); imgBasicData.clear(); MyVariables.setimgBasicData(imgBasicData); } //logger.info("MyVariables.getimagesData().toString() \n{}",MyVariables.getimagesData().toString()); //logger.debug("\n\n\n\ncounter : {}", String.valueOf(counter)); return null; } @Override public void done() { logger.debug("Finished reading all the metadata in the background"); progressBar.setVisible(false); mainScreenLabels[0].setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.finishedreadingmetadabackground")); buttonSearchMetadata.setEnabled(true); } }; sw.execute(); } /* / This method is used to mass extract thumbnails from images, either by load folder, load images or "dropped" images. */ public static void extractThumbnails() { String exiftool = Utils.platformExiftool(); List<String> cmdparams = new ArrayList<String>(); cmdparams.add(exiftool.trim()); String filename = ""; boolean isWindows = Utils.isOsFromMicrosoft(); File[] files = MyVariables.getLoadedFiles(); List<File> createthumbs = new ArrayList<File>(); // Get the temporary directory String tempWorkDir = MyVariables.gettmpWorkFolder(); String userHome = SystemPropertyFacade.getPropertyByKey(USER_HOME); String strjexiftoolguicachefolder = userHome + File.separator + MyConstants.MY_DATA_FOLDER + File.separator + "cache"; cmdparams.add("-a"); cmdparams.add("-m"); cmdparams.add("-b"); cmdparams.add("-W"); cmdparams.add(tempWorkDir + File.separator + "%f_%t%-c.%s"); cmdparams.add("-preview:all"); for (File file : files) { // First check for existing thumbnails filename = file.getName().replace("\\", "/"); String thumbfilename = filename.substring(0, filename.lastIndexOf('.')) + "_ThumbnailImage.jpg"; String photoshopThumbfilename = filename.substring(0, filename.lastIndexOf('.')) + "_PhotoshopThumbnail.jpg"; File thumbfile = new File(MyVariables.gettmpWorkFolder() + File.separator + thumbfilename); File psthumbfile = new File (MyVariables.gettmpWorkFolder() + File.separator + photoshopThumbfilename); if (!thumbfile.exists()) { // If the thumbfile doesn't exist if (!psthumbfile.exists()) { // and the photoshop thumbfile doesn't exist // then we need to try to create one of them if (isWindows) { cmdparams.add(file.getPath().replace("\\", "/")); } else { cmdparams.add(file.getPath()); } } } } try { String cmdResult = CommandRunner.runCommand(cmdparams); logger.debug("cmd result after export previews " + cmdResult); } catch (IOException | InterruptedException ex) { logger.error("Error executing command to export thumbnails and previews for selected images"); //exportResult = (" " + ResourceBundle.getBundle("translations/program_strings").getString("ept.exporterror")); } StandardFileIO.copyThumbsToCache(); } /* * This method is used to try to get a preview image for those (RAW) images that can't be converted directly to be displayed in the left images column * We will try to extract a jpg from the RAW to the tempdir and resize/display that one */ public static String ExportPreviewsThumbnailsForIconDisplay(File file, boolean bSimpleExtension, String filenameExt) { List<String> cmdparams = new ArrayList<String>(); String exportResult = "Success"; cmdparams.add(Utils.platformExiftool()); boolean isWindows = Utils.isOsFromMicrosoft(); // Get the temporary directory String tempWorkDir = MyVariables.gettmpWorkFolder(); cmdparams.add("-a"); cmdparams.add("-m"); cmdparams.add("-b"); cmdparams.add("-W"); cmdparams.add(tempWorkDir + File.separator + "%f_%t%-c.%s"); cmdparams.add("-preview:all"); if (isWindows) { cmdparams.add(file.getPath().replace("\\", "/")); } else { cmdparams.add(file.getPath()); } try { String cmdResult = CommandRunner.runCommand(cmdparams); //logger.info("cmd result from export previews for single RAW" + cmdResult); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command to export previews for one RAW"); exportResult = (" " + ResourceBundle.getBundle("translations/program_strings").getString("ept.exporterror")); } return exportResult; } /** * This method extract previews for PDF export and likewise exports * @param file * @return */ public static String ExtractPreviews(File file) { List<String> cmdparams = new ArrayList<String>(); String exportResult = "Success"; cmdparams.add(Utils.platformExiftool()); boolean isWindows = Utils.isOsFromMicrosoft(); // Get the temporary directory String tempWorkDir = MyVariables.gettmpWorkFolder(); cmdparams.add("-a"); cmdparams.add("-m"); cmdparams.add("-b"); cmdparams.add("-W"); cmdparams.add(tempWorkDir + File.separator + "%f_%t%-c.%s"); cmdparams.add("-preview:JpgFromRaw"); cmdparams.add("-preview:PreviewImage"); if (isWindows) { cmdparams.add(file.getPath().replace("\\", "/")); } else { cmdparams.add(file.getPath()); } try { String cmdResult = CommandRunner.runCommand(cmdparams); //logger.info("cmd result from export previews for single RAW" + cmdResult); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command to export previews for one RAW"); exportResult = (" " + ResourceBundle.getBundle("translations/program_strings").getString("ept.exporterror")); } return exportResult; } public static ImageIcon useCachedOrCreateIcon (File file) { ImageIcon icon = null; String filename = file.getName().replace("\\", "/"); String thumbfilename = MyVariables.getjexiftoolguiCacheFolder() + File.separator + filename.substring(0, filename.lastIndexOf('.')) + "_ThumbnailImage.jpg"; String photoshopThumbfilename = MyVariables.getjexiftoolguiCacheFolder() + File.separator + filename.substring(0, filename.lastIndexOf('.')) + "_PhotoshopThumbnail.jpg"; File thumbfile = new File(thumbfilename); File psthumbfile = new File(photoshopThumbfilename); if (thumbfile.exists()) { icon = new ImageIcon(thumbfilename); } else if (psthumbfile.exists()) { icon = new ImageIcon(photoshopThumbfilename); } else { icon = ImageFunctions.analyzeImageAndCreateIcon(file); } return icon; } /** * This method AnalyzeImageAndCreateIcon will check if a thumbnail already exists, created by the extract thumbnails method * If not, like in the case for images without any preview, it will resize the image to thumbnail * This function is also called by useCachedOrCreateThumbNail * @param file * @return */ public static ImageIcon analyzeImageAndCreateIcon (File file) { boolean heicextension = false; String[] SimpleExtensions = MyConstants.JAVA_SUP_EXTENSIONS; boolean bSimpleExtension = false; ImageIcon icon = null; ImageIcon finalIcon = null; Application.OS_NAMES currentOsName = getCurrentOsName(); String filename = file.getName().replace("\\", "/"); String filenameExt = getFileExtension(filename); // Define our possible previews String thumbfilename = filename.substring(0, filename.lastIndexOf('.')) + "_ThumbnailImage.jpg"; String photoshopThumbfilename = filename.substring(0, filename.lastIndexOf('.')) + "_PhotoshopThumbnail.jpg"; String previewThumbfilename = filename.substring(0, filename.lastIndexOf('.')) + "_PreviewImage.jpg"; File thumbfile = new File (MyVariables.gettmpWorkFolder() + File.separator + thumbfilename); File psthumbfile = new File (MyVariables.gettmpWorkFolder() + File.separator + photoshopThumbfilename); File prevthumbfile = new File (MyVariables.gettmpWorkFolder() + File.separator + previewThumbfilename); File cachedthumbfile = new File (MyVariables.getjexiftoolguiCacheFolder() + File.separator + thumbfilename); File cachedpsthumbfile = new File (MyVariables.getjexiftoolguiCacheFolder() + File.separator + photoshopThumbfilename); if ( (filenameExt.toLowerCase().equals("heic")) || ((filenameExt.toLowerCase().equals("heif"))) ) { heicextension = true; } for (String ext : SimpleExtensions) { if (filenameExt.toLowerCase().equals(ext)) { // it is either bmp, gif, jp(e)g, png or tif(f) bSimpleExtension = true; break; } } if ( (heicextension) && currentOsName == APPLE) { // For Apple we deviate logger.info("do sipsConvertToJPG for {}", filename); String exportResult = ImageFunctions.sipsConvertToJPG(file, "thumb"); if ("Success".equals(exportResult)) { logger.info("back from sipsconvert: result {}", exportResult); //Hoping we have a thumbnail thumbfilename = filename.substring(0, filename.lastIndexOf('.')) + ".jpg"; thumbfile = new File(MyVariables.gettmpWorkFolder() + File.separator + thumbfilename); if (thumbfile.exists()) { // Create icon of this thumbnail (thumbnail is 90% 160x120 already, but resize it anyway logger.debug("create thumb nr1"); //icon = ImageFunctions.createIcon(thumbfile); icon = ImageFunctions.createIcon(thumbfile); if (icon != null) { // display our created icon from the thumbnail return icon; } } } //reset our heic flag heicextension = false; } else if ( (filenameExt.toLowerCase().equals("jpg")) || (filenameExt.toLowerCase().equals("jpeg") || filenameExt.toLowerCase().equals("tif")) || (filenameExt.toLowerCase().equals("tiff")) ) { if (cachedthumbfile.exists()) { icon = ImageFunctions.createIcon(file); return icon; } else if (cachedpsthumbfile.exists()) { icon = ImageFunctions.createIcon(cachedpsthumbfile); return icon; } else { BufferedImage img = null; try { img = ImageIO.read(file); } catch (IOException e) { logger.error("error reading buffered image to scale it to icon {}", e.toString()); e.printStackTrace(); } BufferedImage resizedImg = ImageFunctions.scaleImageToContainer(img, 160, 160); icon = new ImageIcon(resizedImg); // Save our created icon if ( (filenameExt.toLowerCase().equals("jpg")) || (filenameExt.toLowerCase().equals("jpeg")) ) { //BufferedImage thumbImg = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),BufferedImage.TYPE_INT_RGB); BufferedImage thumbImg = (BufferedImage) icon.getImage(); StandardFileIO.saveIconToCache(filename, thumbImg); } else { //tiff //BufferedImage thumbImg = new BufferedImage(icon); BufferedImage thumbImg = new BufferedImage(resizedImg.getWidth(), resizedImg.getHeight(), BufferedImage.OPAQUE); thumbImg.createGraphics().drawImage(resizedImg, 0, 0, Color.WHITE, null); StandardFileIO.saveIconToCache(filename, thumbImg); } return icon; } } else if ( (filenameExt.toLowerCase().equals("bmp")) || (filenameExt.toLowerCase().equals("png")) ) { if (cachedthumbfile.exists()) { icon = ImageFunctions.createIcon(file); } else { BufferedImage img = null; try { img = ImageIO.read(file); } catch (IOException e) { logger.error("error reading buffered image to scale it to icon {}", e.toString()); e.printStackTrace(); } BufferedImage resizedImg = ImageFunctions.scaleImageToContainer(img, 160, 160); icon = new ImageIcon(resizedImg); BufferedImage thumbImg = (BufferedImage) icon.getImage(); // Save our created icon StandardFileIO.saveIconToCache(filename, thumbImg); //logger.info("Saving file {} to cache", filename); } return icon; } else { //We have a RAW image extension or something else like audio/video String exportResult = ""; exportResult = "Success"; if ("Success".equals(exportResult)) { //Hoping we have a thumbnail logger.debug("thumb nr1:" + MyVariables.gettmpWorkFolder() + File.separator + thumbfilename); if (cachedthumbfile.exists()) { // Create icon of this thumbnail (thumbnail is 90% 160x120 already, but resize it anyway logger.trace("create thumb nr1"); icon = ImageFunctions.createIcon(file); if (icon != null) { // display our created icon from the thumbnail return icon; } } else { //thumbnail image probably doesn't exist, move to 2nd option // We do not cache PreviewImage as they are way too big, so check the tmp folder instead of the cache folder thumbfilename = filename.substring(0, filename.lastIndexOf('.')) + "_PreviewImage.jpg"; thumbfile = new File(MyVariables.gettmpWorkFolder() + File.separator + thumbfilename); logger.debug("PreviewImage option {}", MyVariables.gettmpWorkFolder() + File.separator + thumbfilename); if (thumbfile.exists()) { // Create icon of this Preview logger.trace("create thumb nr2"); //icon = ImageFunctions.createIcon(file); icon = ImageFunctions.createIcon(thumbfile); if (icon != null) { BufferedImage thumbImg = (BufferedImage) icon.getImage(); // Save our created icon StandardFileIO.saveIconToCache(filename, thumbImg); // display our created icon from the preview return icon; } } else { // So thumbnail and previewImage don't exist. Try 3rd option // We do not cache JpgFromRaw as they are way too big, so check the tmp folder instead of the cache folder thumbfilename = filename.substring(0, filename.lastIndexOf('.')) + "_JpgFromRaw.jpg"; thumbfile = new File(MyVariables.gettmpWorkFolder() + File.separator + thumbfilename); logger.debug("JpgFromRaw option {}", MyVariables.gettmpWorkFolder() + File.separator + thumbfilename); if (thumbfile.exists()) { // Create icon of this Preview //icon = ImageFunctions.createIcon(file); icon = ImageFunctions.createIcon(thumbfile); if (icon != null) { BufferedImage thumbImg = (BufferedImage) icon.getImage(); // Save our created icon StandardFileIO.saveIconToCache(filename, thumbImg); // display our created icon from the preview return icon; } } else { // So thumbnail and previewImage don't exist. Try 4th option for photoshop thumbnail if (cachedpsthumbfile.exists()) { // Create icon of this Preview icon = ImageFunctions.createIcon(file); //icon = ImageFunctions.createIcon(thumbfile); if (icon != null) { BufferedImage thumbImg = (BufferedImage) icon.getImage(); // Save our created icon StandardFileIO.saveIconToCache(filename, thumbImg); // display our created icon from the preview return icon; } } else { // Load he cantdisplay.png from our resources try { BufferedImage img = ImageIO.read(mainScreen.class.getResource("/cantdisplay.png")); icon = new ImageIcon(img); } catch (IOException e) { logger.error("Error loading image", e); icon = null; } //ImageFunctions.getbasicImageData(file); if (icon != null) { // display our created icon from the preview return icon; } } // end of 3nd option creation ("else if") and 4rd option creation (else) } // end of 4th option creation ("else if") and cantdisplaypng option (else) } // end of 2nd option creation ("else if") and 3rd option creation (else) } // end of 1st option creation ("else if") and 2nd option creation (else) } else { // Our "String exportResult = ExportPreviewsThumbnailsForIconDisplay(file);" either failed due to some weird RAW format try { BufferedImage img = ImageIO.read(mainScreen.class.getResource("/cantdisplay.png")); icon = new ImageIcon(img); } catch (IOException e) { logger.error("Error loading image", e); icon = null; } //ImageFunctions.getbasicImageData(file); if (icon != null) { // display our created icon from the preview return icon; } } } return icon; } /* * Create the icon after having determined what kind of image we have * This is only necessary if we do not have a thumbnail, previewimage, etc from our "big" image */ public static ImageIcon createIcon(File file) { ImageIcon icon = null; int[] basicdata = {0, 0, 999, 0, 0, 0, 0, 0};; boolean bde = false; String thumbfilename = ""; String photoshopThumbfilename = ""; File thumbfile = null; File psthumbfile = null; String filename = ""; BufferedImage img = null; BufferedImage resizedImg = null; filename = file.getName().replace("\\", "/"); logger.debug("Now working on image: " +filename); String filenameExt = getFileExtension(filename); try { try { // We use exiftool to get width, height and orientation from the ORIGINAL image // (as it is not always available in the thumbnail or preview) basicdata = getWidthHeightOrientation(file); logger.debug("Width {} Height {} Orientation {}", String.valueOf(basicdata[0]), String.valueOf(basicdata[1]), String.valueOf(basicdata[2])); } catch (NullPointerException npe) { npe.printStackTrace(); bde = true; } logger.trace("after getbasicdata"); if ((bde) || (basicdata[2] == 999)) { // We had some error. Mostly this is the orientation basicdata[2]= 1; } // Check whether we have a thumbnail thumbfilename = filename.substring(0, filename.lastIndexOf('.')) + "_ThumbnailImage.jpg"; photoshopThumbfilename = filename.substring(0, filename.lastIndexOf('.')) + "_PhotoshopThumbnail.jpg"; thumbfile = new File (MyVariables.gettmpWorkFolder() + File.separator + thumbfilename); psthumbfile = new File (MyVariables.gettmpWorkFolder() + File.separator + photoshopThumbfilename); if (thumbfile.exists()) { logger.debug("precreated thumbnail found: {}", thumbfile.toString()); img = ImageIO.read(new File(thumbfile.getPath().replace("\\", "/"))); } else if (psthumbfile.exists()) { logger.debug("precreated photoshop thumbnail found: {}", psthumbfile.toString()); img = ImageIO.read(new File(psthumbfile.getPath().replace("\\", "/"))); } else { logger.debug("precreated thumbnail NOT found: {}", thumbfile.toString()); img = ImageIO.read(new File(file.getPath().replace("\\", "/"))); } if (basicdata[0] > 160) { resizedImg = ImageFunctions.scaleImageToContainer(img, 160, 160); logger.trace("after scaleImageToContainer"); } else { // In some circumstances we even have images < 160 width resizedImg = img; } if ( basicdata[2] > 1 ) { //We use 999 if we can' t find an orientation resizedImg = ImageFunctions.rotate(resizedImg, basicdata[2]); } logger.trace("after rotate"); icon = new ImageIcon(resizedImg); return icon; } catch (IIOException iex) { icon = null; } catch (IOException ex) { logger.error("Error loading image", ex); icon = null; } return icon; } /* / On Mac we let sips do the conversion of tif and heic images to previews / like "sips -s format JPEG -Z 160 test.heic --out test.jpg" */ public static String sipsConvertToJPG(File file, String size) { List<String> cmdparams = new ArrayList<String>(); String exportResult = "Success"; cmdparams.add("/usr/bin/sips"); cmdparams.add("-s"); cmdparams.add("format"); cmdparams.add("jpeg"); if (size.toLowerCase().equals("thumb")) { cmdparams.add("-Z"); cmdparams.add("160"); } else if (size.toLowerCase().equals("pdfexport")) { cmdparams.add("-Z"); cmdparams.add("1600"); } // Get the file cmdparams.add(file.getPath().replaceAll(" ", "\\ ")); //cmdparams.add("\"" + file.getPath() + "\""); cmdparams.add("--out"); // Get the temporary directory String tempWorkDir = MyVariables.gettmpWorkFolder(); // Get the file name without extension String fileName = file.getName(); int pos = fileName.lastIndexOf("."); if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character. fileName = fileName.substring(0, pos); } cmdparams.add(tempWorkDir + File.separator + fileName + ".jpg"); logger.info("final sips command: " + cmdparams.toString()); try { String cmdResult = CommandRunner.runCommand(cmdparams); logger.trace("cmd result from export previews for single RAW" + cmdResult); } catch (IOException | InterruptedException ex) { logger.debug("Error executing sipd command to convert to jpg"); } return exportResult; } /** * Resizes an image using a Graphics2D object backed by a BufferedImage. * @param src - source image to scale * @param w - desired width * @param h - desired height * @return - the new resized image */ public static BufferedImage scaleImage(BufferedImage src, int w, int h) { BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImg.createGraphics(); g2.drawImage(src, 0, 0, w, h, null); g2.dispose(); return resizedImg; } /** * Scale an image. * @param img the image to be scaled. * @param conWidth the maximum width after scaling. * @param conHeight the maximum height after scaling. * @return the scaled image. */ public static BufferedImage scaleImageToContainer(BufferedImage img, int conWidth, int conHeight) { if (img == null) return null; // Original image size: int width = img.getWidth(); int height = img.getHeight(); // If the image is already the right size then there is nothing to do. if ((width == conWidth && height <= conHeight) || (height == conHeight && width <= conWidth)) { return img; } // Scaled image size: int scaledWidth = conWidth; int scaledHeight = conHeight; float cAspect = ((float) conWidth) / conHeight; float fileAspect = ((float) width) / height; if (fileAspect >= cAspect) { scaledHeight = (int) (scaledWidth / fileAspect); } else { scaledWidth = (int) (scaledHeight * fileAspect); } // Prevent scaling to 0 size. if (scaledWidth <= 0 || scaledHeight <= 0) { scaledWidth = 1; scaledHeight = 1; } Image newScaledImg = img.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_FAST); BufferedImage scaledImg = new BufferedImage(newScaledImg.getWidth(null), newScaledImg.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = scaledImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); // Draw the scaled image. g2.drawImage(img, 0, 0, scaledWidth, scaledHeight, Color.WHITE, null); g2.dispose(); return scaledImg; } /** * Rotate an image. * @param image The image to rotate. * @param rotation The rotation constant. * @return The rotated image. */ public static BufferedImage rotate(BufferedImage image, int rotation) { // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html tag 0x0112 Orientation // "exiftool -exif:orientation" gives for example Rotate 90 CW // "exiftool -n -exif:orientation" gives for example 6 // rotation values: // 1 = Horizontal (normal) // 2 = Mirror horizontal // 3 = Rotate 180 // 4 = Mirror vertical // 5 = Mirror horizontal and rotate 270 CW // 6 = Rotate 90 CW // 7 = Mirror horizontal and rotate 90 CW // 8 = Rotate 270 CW AffineTransform tx = null; AffineTransformOp op = null; if (image == null) return null; switch (rotation) { default: case 1: // No rotation break; case 2: // Mirror horizontal tx = AffineTransform.getScaleInstance(-1, 1); tx.translate(-image.getWidth(null), 0); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); break; case 3: // Rotate 180 // Relocate the center of the image to the origin. // Rotate about the origin. Then move image back. // (This avoids black bars on rotated images.) tx = new AffineTransform(); tx.translate(image.getWidth() / 2.0, image.getHeight() / 2.0); tx.rotate(Math.toRadians(180)); tx.translate( - image.getWidth() / 2.0, - image.getHeight() / 2.0); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); break; case 4: // Mirror vertical tx = AffineTransform.getScaleInstance(1, -1); tx.translate(0, -image.getHeight(null)); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); break; case 5: // Mirror horizontal and rotate 270 CW tx = AffineTransform.getScaleInstance(-1, 1); tx.translate(-image.getWidth(null), 0); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); // Fall thru to case 8. case 8: // Rotate 270 CW tx = new AffineTransform(); tx.translate(image.getHeight() / 2.0, image.getWidth() / 2.0); tx.rotate(Math.toRadians(270)); tx.translate( - image.getWidth() / 2.0, - image.getHeight() / 2.0); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); break; case 7: // Mirror horizontal and rotate 90 CW tx = AffineTransform.getScaleInstance(-1, 1); tx.translate(-image.getWidth(null), 0); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); // Fall through to case 6. case 6: // Rotate 90 CW tx = new AffineTransform(); tx.translate(image.getHeight() / 2.0, image.getWidth() / 2.0); tx.rotate(Math.toRadians(90)); tx.translate( - image.getWidth() / 2.0, - image.getHeight() / 2.0); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); break; } return image; } /** * Adjust an image aspect ratio depending on the image rotation. * @param oldAspectRatio The original aspect ratio. * @param rotation The rotation constant. * @return The adjusted aspect ratio. */ public static float fixAspectRatio(float oldAspectRatio, int rotation) { switch (rotation) { default: case 0: case 1: case 2: case 3: case 4: return oldAspectRatio; case 5: case 6: case 7: case 8: return 1 / oldAspectRatio; } } }
44,810
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
CSVUtils.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/CSVUtils.java
package org.hvdw.jexiftoolgui.controllers; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBaseBuilder; import com.opencsv.CSVReaderBuilder; import com.opencsv.CSVWriter; import com.opencsv.enums.CSVReaderNullFieldIndicator; import com.opencsv.exceptions.CsvValidationException; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static org.hvdw.jexiftoolgui.controllers.StandardFileIO.getResourceAsStream; import static org.slf4j.LoggerFactory.getLogger; /** * This class is using the opencsv library * * website & manual: http://opencsv.sourceforge.net/index.html * Download: https://sourceforge.net/projects/opencsv/ */ public class CSVUtils { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) getLogger(CSVUtils.class); public static List<String[]> ReadCSV(Path csvFile, String separator) throws IOException { String[] line; // CSVReader reader = new CSVReaderBuilder(inputStreamReader) // .withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS) // // Skip the header // .withSkipLines(1) // .build(); // try (Reader reader = Files.newBufferedReader(csvFile)) { // try (CSVReader csvReader = new CSVReader(reader)) { List<String[]> csvList = new ArrayList<>(); try (Reader reader = Files.newBufferedReader(csvFile)) { //try (CSVReader csvReader = new CSVReader(reader, "\t")){ try (CSVReader csvReader = new CSVReaderBuilder(reader).withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS).withSkipLines(1).build()) { while ((line = csvReader.readNext()) != null) { csvList.add(line); } } catch (CsvValidationException e) { logger.error("CsvValidationException {}", e); e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } //logger.info("the list {}", csvList); return csvList; } public static List<String[]> ReadCSVfromResources(String csvFile) throws IOException { String[] line; List<String[]> csvList = new ArrayList<>(); InputStream is = getResourceAsStream(csvFile); //try (Reader reader = Files.newBufferedReader(Paths.get(csvFile))) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) { try (CSVReader csvReader = new CSVReaderBuilder(reader).withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS).withSkipLines(1).build()) { //String[] line; while ((line = csvReader.readNext()) != null) { csvList.add(line); } } catch (CsvValidationException e) { logger.error("CsvValidationException {}", e); e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } return csvList; } public static void WriteCSV(String csvFile, String[] csvData) throws IOException { //CSVWriter writer = new CSVWriter(new FileWriter(csvFile), '\t'); CSVWriter writer = new CSVWriter(new FileWriter(csvFile)); writer.writeNext(csvData); writer.close(); } public static void WriteCSVList(String csvFile, List<String[]> csvData) throws IOException { //using custom delimiter and quote character //CSVWriter csvWriter = new CSVWriter(writer, '#', '\''); FileWriter fw = new FileWriter(new File(csvFile)); try (CSVWriter writer = new CSVWriter(fw)) { for (String[] line : csvData) { writer.writeNext(line); } } } }
3,956
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
MouseListeners.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/MouseListeners.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.List; import java.util.ArrayList; import static org.slf4j.LoggerFactory.getLogger; public class MouseListeners { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) getLogger(MouseListeners.class); public static void FileNamesTableMouseListener(JTable tableListfiles, JTable ListexiftoolInfotable, String[] params, JLabel OutputLabel) { // Use the mouse listener for the single cell double-click selection for the left table to be able to // display the image in the default viewer tableListfiles.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent mouseEvent) { JTable table =(JTable) mouseEvent.getSource(); Point point = mouseEvent.getPoint(); int trow = table.rowAtPoint(point); int tcolumn = table.columnAtPoint(point); if (mouseEvent.getClickCount() == 2 && table.getSelectedRow() != -1) { Utils.displaySelectedImageInExternalViewer(); logger.debug("double-click registered from thumbstable from row {} and column {}", String.valueOf(trow), String.valueOf(tcolumn)); } OutputLabel.setText(""); logger.debug("mouselistener: selected cell in row {} and column {}", String.valueOf(trow), String.valueOf(tcolumn)); } }); } public static void filesJListListener(JList iconViewList, JTable ListexiftoolInfotable, JLabel[] mainScreenLabels) { iconViewList.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent mouseEvent) { int[] selectedIndices; List<Integer> selectedIndicesList = new ArrayList<Integer>(); List<Integer> tmpselectedIndices = new ArrayList<>(); JList list =(JList) mouseEvent.getSource(); Point point = mouseEvent.getPoint(); int listCell = list.getSelectedIndex(); MyVariables.setSelectedRowOrIndex(listCell); if (mouseEvent.getClickCount() == 2 && list.getSelectedIndex() != -1) { logger.debug("double-click registered from filesJlist from index {}", String.valueOf(listCell)); Utils.displaySelectedImageInExternalViewer(); } mainScreenLabels[0].setText(""); logger.debug("single-click mouselistener: selected cell in index {}", String.valueOf(listCell)); String[] params = MyVariables.getmainScreenParams(); String res = Utils.getImageInfoFromSelectedFile(params); Utils.displayInfoForSelectedImage(res, ListexiftoolInfotable); int selectedRowOrIndex = MyVariables.getSelectedRowOrIndex(); File[] files = MyVariables.getLoadedFiles(); if (res.startsWith("jExifToolGUI")) { mainScreenLabels[3].setText(" "); } else { mainScreenLabels[3].setText(files[selectedRowOrIndex].getPath()); } } }); } public static class iconViewListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { // Perfectly working row selection method of first program List<Integer> tmpselectedIndices = new ArrayList<>(); ListSelectionModel lsm = (ListSelectionModel) e.getSource(); List<Integer> selectedIndicesList = new ArrayList<>(); int[] selectedIndices = null; if (lsm.isSelectionEmpty()) { logger.debug("no grid view index selected"); } else { // Find out which indexes are selected. int minIndex = lsm.getMinSelectionIndex(); int maxIndex = lsm.getMaxSelectionIndex(); for (int i = minIndex; i <= maxIndex; i++) { if (lsm.isSelectedIndex(i)) { tmpselectedIndices.add(i); int SelectedRowOrIndex = i; MyVariables.setSelectedRowOrIndex(i); //logger.info("MyVariables.getSelectedRowOrIndex() {}", MyVariables.getSelectedRowOrIndex()); } } String[] params = MyVariables.getmainScreenParams(); String res = Utils.getImageInfoFromSelectedFile(params); //Utils.displayInfoForSelectedImage(res, ListexiftoolInfotable); int selectedRowOrIndex = MyVariables.getSelectedRowOrIndex(); File[] files = MyVariables.getLoadedFiles(); /*if (res.startsWith("jExifToolGUI")) { lblFileNamePath.setText(" "); } else { lblFileNamePath.setText(files[selectedRowOrIndex].getPath()); }*/ selectedIndices = tmpselectedIndices.stream().mapToInt(Integer::intValue).toArray(); logger.debug("Selected grid indices: {}", tmpselectedIndices); //logger.info("Save indices {}", Arrays.toString(selectedIndices)); selectedIndicesList = tmpselectedIndices; MyVariables.setselectedIndicesList(selectedIndicesList); MyVariables.setSelectedFilenamesIndices(selectedIndices); } } } }
5,838
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
CheckPreferences.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/CheckPreferences.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.Application; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import static org.hvdw.jexiftoolgui.Utils.getCurrentOsName; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.EXIFTOOL_PATH; /** * This class checks preferences that need to be checked. * Currently that is only exiftool */ public class CheckPreferences { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Utils.class); private IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; /** * Checks all possible incorrect entries of provided exiftool paths * @param exiftool_path * @return */ private boolean check_ET_correctness( String exiftool_path) { boolean correctET = false; if ( (exiftool_path != null) && !(exiftool_path.isEmpty()) ) { switch (exiftool_path) { case "": break; case "jexiftoolgui.db": break; case "exiftool(-k).exe": break; case "-k version": break; default: correctET = true; } } return correctET; } public String isExifToolExecutable(String etPath , JLabel OutputLabel) { String res = ""; List<String> cmdparams = new ArrayList<>(); boolean isWindows = Utils.isOsFromMicrosoft(); if (isWindows) { cmdparams.add("\"" + res + "\""); } else { cmdparams.add(res); } cmdparams.add("-ver"); try { String exv = CommandRunner.runCommand(cmdparams).replace("\n", "").replace("\r", ""); OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.exiftoolavailable") + exv); MyVariables.setExiftoolVersion(exv); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command"); res = "Error executing command"; } return res; } public String checkExifToolPreference() { boolean exiftool_preference_exists = false; String res = ""; exiftool_preference_exists = prefs.keyIsSet(EXIFTOOL_PATH); logger.debug("preference check exiftool_exists reports: {}",exiftool_preference_exists); if (exiftool_preference_exists) { // Yes, our preference setting exists String exiftool_path = prefs.getByKey(EXIFTOOL_PATH, ""); logger.info("exiftoolpath contains {}", exiftool_path); File tmpFile = new File(exiftool_path); boolean file_exists = tmpFile.exists(); if (exiftool_path == null || exiftool_path.isEmpty() || !file_exists) { res = "Preference null_empty_notexisting"; logger.debug("result from getExiftoolInPath() for null/empty/nonexisting value: {}", res); } else { // Yes, our preference exists and has a value for which the file can be found (doesn't mean it is correct) res = exiftool_path; } } else { res = "No exiftool preference yet"; } return res; } //check preferences (a.o. exiftool) public boolean checkPreferences(JPanel rootPanel, JLabel OutputLabel) { boolean exiftool_preference_exists = false; boolean exiftool_found = false; boolean correctET =false; String res = null; List<String> cmdparams = new ArrayList<>(); boolean isWindows = Utils.isOsFromMicrosoft(); exiftool_preference_exists = prefs.keyIsSet(EXIFTOOL_PATH); logger.debug("preference check exiftool_exists reports: {}",exiftool_preference_exists); if (exiftool_preference_exists) { String exiftool_path = prefs.getByKey(EXIFTOOL_PATH, ""); logger.debug("prefs.getByKey exiftoolpath contains {}", exiftool_path); if ( !(exiftool_path.contains("jexiftoolgui.db")) && !(exiftool_path.contains("exiftool(-k).exe")) && !(exiftool_path.contains("-k version")) ) { File tmpFile = new File(exiftool_path); boolean file_exists = tmpFile.exists(); if (!file_exists) { logger.debug("the exiftool path in the preferences being \"{} \" isn't found", exiftool_path); exiftool_path = null; JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 300, ResourceBundle.getBundle("translations/program_strings").getString("prefs.etprefincorrecttext")), ResourceBundle.getBundle("translations/program_strings").getString("prefs.etprefincorrecttitle"), JOptionPane.WARNING_MESSAGE); } if (exiftool_path == null || exiftool_path.isEmpty() || !file_exists) { // Try to find exiftool in the path res = ExifTool.getExiftoolInPath(); // logger.debug("result from getExiftoolInPath() after null/empty/not_exist: {}", res); } else { res = exiftool_path; logger.debug("preference exists and not empty/null/non_existent: {}", res); } } else { //user has selected jexiftoolgui.db as exiftool (it happens) or from a windows internal path. res = ExifTool.getExiftoolInPath(); } } else { // exiftool preference does not exist res = ExifTool.getExiftoolInPath(); } //////////////////////// old /////////////////////////////////// if ((res != null) && !res.isEmpty() && !res.toLowerCase().startsWith("info") && !(res.toLowerCase()).equals("c:\\windows\\exiftool.exe") ) { exiftool_found = true; // We already checked that the node did not exist and that it is empty or null // remove all possible line breaks res = res.replace("\n", "").replace("\r", ""); if (exiftool_found) { prefs.storeByKey(EXIFTOOL_PATH, res); MyVariables.setExifToolPath(res); } } else if ("c:\\windows\\exiftool.exe".equals(res.toLowerCase())) { exiftool_found = true; MyVariables.setExifToolPath(res); } logger.info("exiftool_found mentions: {}", exiftool_found); logger.info("exiftool path: {}", res); return exiftool_found; } }
6,945
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
CommandRunner.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/controllers/CommandRunner.java
package org.hvdw.jexiftoolgui.controllers; import org.hvdw.jexiftoolgui.MyConstants; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.slf4j.LoggerFactory; import javax.swing.*; import java.awt.*; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Executor; public class CommandRunner { public final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(CommandRunner.class); /* * All exiftool commands go through this method */ public static String runCommand(List<String> cmdparams) throws InterruptedException, IOException { StringBuilder res = new StringBuilder(); List<String> newParams = new ArrayList<String>(); List<String> imgList = new ArrayList<String>(); List<String> postArgParams = new ArrayList<String>(); byte[] myBytes = null; boolean bUTF8 = true; boolean versionCall = false; boolean winWhere = false; String[] supportedImages = MyConstants.SUPPORTED_IMAGES; List<String> supImgList = Arrays.asList(supportedImages); StringBuilder argsString = new StringBuilder();; // try with apache commons String platformCharset = Charset.defaultCharset().displayName(); logger.debug("platformCharset: {}", platformCharset); logger.debug("cmdparams on entering runCommand: {}", cmdparams.toString().replaceAll(",", " ")); //Always read/write exif data as utf8 if (Utils.isOsFromMicrosoft()) { for (String subString : cmdparams) { if (subString.contains("preview")) { bUTF8 = false; } if (subString.contains("jExifToolGUI")) { bUTF8 = false; } if ((subString.toLowerCase()).contains("-ver")) { bUTF8 = false; } if ((subString.toLowerCase()).contains("where")) { bUTF8 = false; } } for (String subString : cmdparams) { // && !(subString.contains("exiftool.exe")) if (bUTF8) { if ((subString.toLowerCase().contains("exiftool"))) { //if ( (subString.toLowerCase().contains("exiftool")) && !(subString.contains("jExifToolGUI")) && !(subString.contains("preview")) ) { newParams.add(subString); newParams.add("-charset"); newParams.add("utf8"); newParams.add("-charset"); newParams.add("iptc=utf8"); newParams.add("-charset"); newParams.add("exif=utf8"); //newParams.add("-@"); //} else if ( (subString.toLowerCase().contains("jpg")) || (subString.toLowerCase().contains("tif")) || (subString.toLowerCase().contains("png")) ) } else if ((supImgList.stream().anyMatch(subString.toLowerCase()::endsWith)) && !(subString.toLowerCase().startsWith("-"))) { // These are the images imgList.add("\"" + subString + "\""); logger.info("img subString {}", subString); } else if (subString.contains("=") ) { //These are strings that set tag values argsString.append(subString + " \n"); } else { postArgParams.add(subString); } } } // Now write our argsString as Args file to tmp folder if (argsString.length() != 0) { // we need our argsfile @ newParams.add("-@"); File argsFile = new File(MyVariables.gettmpWorkFolder() + File.separator + "argfile.txt"); // Use java 11 functionality for writing try (FileWriter fw = new FileWriter(argsFile, StandardCharsets.UTF_8); BufferedWriter writer = new BufferedWriter(fw)) { writer.append(argsString); logger.info("argsString contains {}", argsString); } catch (IOException e) { e.printStackTrace(); logger.error("error creating tmp argsfile on Windows {}", e.toString()); } newParams.add(argsFile.toString()); } //Now combine it all newParams.addAll(postArgParams); newParams.addAll(imgList); } logger.debug("total newParams {}\n", newParams.toString()); // end try with apache commons ProcessBuilder builder = null; if ((Utils.isOsFromMicrosoft())) { if ( !(bUTF8) ) { builder = new ProcessBuilder(cmdparams); } else { builder = new ProcessBuilder(newParams); logger.info("newParams in processbuilder {}", newParams); } } else { builder = new ProcessBuilder(cmdparams); logger.debug("cmdparams in processbuilder {}", cmdparams); } logger.debug("Did ProcessBuilder builder = new ProcessBuilder(cmdparams);"); try { builder.redirectErrorStream(true); Process process = builder.start(); //Use a buffered reader to prevent hangs on Windows BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { res.append(line).append(System.lineSeparator()); logger.trace("tasklist: " + line); } process.waitFor(); } catch (IOException e) { logger.error("IOException error {}", e.toString()); res.append("IOException error") .append(System.lineSeparator()) .append(e.getMessage()); } return res.toString(); } /* * This shows the output of exiftool after it has run */ public static void outputAfterCommand(String output) { JTextArea textArea = new JTextArea(output); JScrollPane scrollPane = new JScrollPane(textArea); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); scrollPane.setPreferredSize(new Dimension(500, 500)); JOptionPane.showMessageDialog(null, scrollPane, "Output from the given command", JOptionPane.INFORMATION_MESSAGE); } /* * This executes the commands via runCommand and shows/hides the progress bar * This one is special for the output windows and has 2 parameters */ public static void runCommandWithProgressBar(List<String> cmdparams, JProgressBar progressBar) { // Create executor thread to be able to update my gui when longer methods run Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor(); executor.execute(new Runnable() { @Override public void run() { try { String res = runCommand(cmdparams); logger.debug("res is\n{}", res); progressBar.setVisible(false); outputAfterCommand(res); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command"); } } }); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setVisible(true); } }); } /* * This executes the commands via runCommand and shows/hides the progress bar * This one has a 3rd parameter to enable/disable output. It should replace the above one (when I find the time) */ public static void runCommandWithProgressBar(List<String> cmdparams, JProgressBar progressBar, String output) { // Create executor thread to be able to update my gui when longer methods run Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor(); executor.execute(new Runnable() { @Override public void run() { try { String res = runCommand(cmdparams); logger.debug("res is\n {}", res); progressBar.setVisible(false); if ("delayed".equals(output.toLowerCase())) { String tmp = MyVariables.getdelayedOutput(); MyVariables.setdelayedOutput(tmp + "\n\n" + res); //outputAfterCommand(res); } } catch (IOException | InterruptedException ex) { logger.debug("Error executing command"); } } }); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setVisible(true); } }); } }
9,333
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
ModifyDateTime.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/datetime/ModifyDateTime.java
package org.hvdw.jexiftoolgui.datetime; import ch.qos.logback.classic.Logger; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.plaf.FontUIResource; import javax.swing.text.StyleContext; import java.awt.*; import java.awt.event.*; import java.io.File; import java.lang.reflect.Method; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; public class ModifyDateTime extends JDialog { private JPanel rootModifyDateTimePane; private JButton buttonOK; private JButton buttonCancel; private JLabel ModifyDateTimeLabel; private JCheckBox UseRefDateTimecheckBox; private JTextField ModifyDatetextField; private JCheckBox ModifyDatecheckBox; private JTextField DateTimeOriginaltextField; private JCheckBox DateTimeOriginalcheckBox; private JTextField CreateDatetextField; private JCheckBox CreateDatecheckBox; private JCheckBox ShiftAboveDateTimecheckBox; private JTextField shiftDateTimetextField; private JCheckBox UpdateXmpcheckBox; private JCheckBox BackupOfOriginalscheckBox; public int[] selectedFilenamesIndices; public File[] files; private JProgressBar progBar; private final static Logger logger = (Logger) LoggerFactory.getLogger(ModifyDateTime.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; public ModifyDateTime() { setContentPane(rootModifyDateTimePane); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); rootModifyDateTimePane.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); setModal(true); getRootPane().setDefaultButton(buttonOK); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE rootModifyDateTimePane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } public void initDialog() { ModifyDateTimeLabel.setText(String.format(ProgramTexts.HTML, 370, ResourceBundle.getBundle("translations/program_strings").getString("mdt.toptext"))); DateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); Date date = new Date(); ModifyDatetextField.setText(dateFormat.format(date)); DateTimeOriginaltextField.setText(dateFormat.format(date)); CreateDatetextField.setText(dateFormat.format(date)); } private void writeInfo() { String shiftOption; List<String> cmdparams = new LinkedList<>(); String exiftool = Utils.platformExiftool(); cmdparams.add(exiftool); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!BackupOfOriginalscheckBox.isSelected()) { cmdparams.add("-overwrite_original"); } if (ModifyDatecheckBox.isSelected()) { cmdparams.add("-exif:ModifyDate=" + ModifyDatetextField.getText().trim()); if (UpdateXmpcheckBox.isSelected()) { cmdparams.add("-xmp:ModifyDate=" + ModifyDatetextField.getText().trim()); } } if (DateTimeOriginalcheckBox.isSelected()) { cmdparams.add("-exif:DateTimeOriginal=" + DateTimeOriginaltextField.getText().trim()); if (UpdateXmpcheckBox.isSelected()) { cmdparams.add("-xmp:DateTimeOriginal=" + DateTimeOriginaltextField.getText().trim()); } } if (CreateDatecheckBox.isSelected()) { cmdparams.add("-exif:CreateDate=" + CreateDatetextField.getText().trim()); if (UpdateXmpcheckBox.isSelected()) { cmdparams.add("-xmp:DateTimeDigitized=" + CreateDatetextField.getText().trim()); } } for (int index : selectedFilenamesIndices) { if (Utils.isOsFromMicrosoft()) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } logger.info(cmdparams.toString()); CommandRunner.runCommandWithProgressBar(cmdparams, progBar); } private void onOK() { // add your code here writeInfo(); dispose(); } private void onCancel() { // add your code here if necessary dispose(); } public void showDialog(JProgressBar progressBar) { selectedFilenamesIndices = MyVariables.getSelectedFilenamesIndices(); files = MyVariables.getLoadedFiles(); progBar = progressBar; pack(); setLocationByPlatform(true); setTitle(ResourceBundle.getBundle("translations/program_strings").getString("mdt.title")); initDialog(); setVisible(true); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { rootModifyDateTimePane = new JPanel(); rootModifyDateTimePane.setLayout(new GridLayoutManager(4, 1, new Insets(10, 10, 10, 10), -1, -1)); rootModifyDateTimePane.setPreferredSize(new Dimension(500, 300)); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); rootModifyDateTimePane.add(panel1, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false)); panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); buttonOK = new JButton(); this.$$$loadButtonText$$$(buttonOK, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.ok")); panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); buttonCancel = new JButton(); this.$$$loadButtonText$$$(buttonCancel, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.cancel")); panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new GridLayoutManager(4, 1, new Insets(0, 0, 0, 0), -1, -1)); rootModifyDateTimePane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); ModifyDateTimeLabel = new JLabel(); ModifyDateTimeLabel.setText("ModifyDateTimeLabel"); panel3.add(ModifyDateTimeLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); UseRefDateTimecheckBox = new JCheckBox(); UseRefDateTimecheckBox.setText("Use date and time from reference image"); UseRefDateTimecheckBox.setVisible(false); panel3.add(UseRefDateTimecheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel4 = new JPanel(); panel4.setLayout(new GridLayoutManager(4, 3, new Insets(5, 5, 5, 5), -1, -1)); panel3.add(panel4, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); final JLabel label1 = new JLabel(); this.$$$loadLabelText$$$(label1, this.$$$getMessageFromBundle$$$("translations/program_strings", "mdt.timeformat")); panel4.add(label1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label2 = new JLabel(); Font label2Font = this.$$$getFont$$$(null, Font.BOLD, -1, label2.getFont()); if (label2Font != null) label2.setFont(label2Font); this.$$$loadLabelText$$$(label2, this.$$$getMessageFromBundle$$$("translations/program_strings", "label.save")); panel4.add(label2, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label3 = new JLabel(); this.$$$loadLabelText$$$(label3, this.$$$getMessageFromBundle$$$("translations/program_strings", "mdt.modifydate")); panel4.add(label3, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); ModifyDatetextField = new JTextField(); panel4.add(ModifyDatetextField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); ModifyDatecheckBox = new JCheckBox(); ModifyDatecheckBox.setSelected(true); ModifyDatecheckBox.setText(""); panel4.add(ModifyDatecheckBox, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label4 = new JLabel(); this.$$$loadLabelText$$$(label4, this.$$$getMessageFromBundle$$$("translations/program_strings", "mdt.datetimeoriginal")); panel4.add(label4, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); DateTimeOriginaltextField = new JTextField(); panel4.add(DateTimeOriginaltextField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); DateTimeOriginalcheckBox = new JCheckBox(); DateTimeOriginalcheckBox.setSelected(true); DateTimeOriginalcheckBox.setText(""); panel4.add(DateTimeOriginalcheckBox, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label5 = new JLabel(); this.$$$loadLabelText$$$(label5, this.$$$getMessageFromBundle$$$("translations/program_strings", "mdt.createdate")); panel4.add(label5, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); CreateDatetextField = new JTextField(); panel4.add(CreateDatetextField, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); CreateDatecheckBox = new JCheckBox(); CreateDatecheckBox.setSelected(true); CreateDatecheckBox.setText(""); panel4.add(CreateDatecheckBox, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer2 = new Spacer(); panel3.add(spacer2, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); UpdateXmpcheckBox = new JCheckBox(); UpdateXmpcheckBox.setSelected(true); this.$$$loadButtonText$$$(UpdateXmpcheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "mdt.updatexmp")); rootModifyDateTimePane.add(UpdateXmpcheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); BackupOfOriginalscheckBox = new JCheckBox(); this.$$$loadButtonText$$$(BackupOfOriginalscheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "chkbox.makebackup")); rootModifyDateTimePane.add(BackupOfOriginalscheckBox, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); } /** * @noinspection ALL */ private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) { if (currentFont == null) return null; String resultName; if (fontName == null) { resultName = currentFont.getName(); } else { Font testFont = new Font(fontName, Font.PLAIN, 10); if (testFont.canDisplay('a') && testFont.canDisplay('1')) { resultName = fontName; } else { resultName = currentFont.getName(); } } Font font = new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize()); boolean isMac = System.getProperty("os.name", "").toLowerCase(Locale.ENGLISH).startsWith("mac"); Font fontWithFallback = isMac ? new Font(font.getFamily(), font.getStyle(), font.getSize()) : new StyleContext().getFont(font.getFamily(), font.getStyle(), font.getSize()); return fontWithFallback instanceof FontUIResource ? fontWithFallback : new FontUIResource(fontWithFallback); } private static Method $$$cachedGetBundleMethod$$$ = null; private String $$$getMessageFromBundle$$$(String path, String key) { ResourceBundle bundle; try { Class<?> thisClass = this.getClass(); if ($$$cachedGetBundleMethod$$$ == null) { Class<?> dynamicBundleClass = thisClass.getClassLoader().loadClass("com.intellij.DynamicBundle"); $$$cachedGetBundleMethod$$$ = dynamicBundleClass.getMethod("getBundle", String.class, Class.class); } bundle = (ResourceBundle) $$$cachedGetBundleMethod$$$.invoke(null, path, thisClass); } catch (Exception e) { bundle = ResourceBundle.getBundle(path); } return bundle.getString(key); } /** * @noinspection ALL */ private void $$$loadLabelText$$$(JLabel component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setDisplayedMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ private void $$$loadButtonText$$$(AbstractButton component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return rootModifyDateTimePane; } }
19,811
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
ShiftDateTime.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/datetime/ShiftDateTime.java
package org.hvdw.jexiftoolgui.datetime; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.USE_G1_GROUP; public class ShiftDateTime extends JDialog { private JPanel shiftDateTimePane; private JButton buttonOK; private JButton buttonCancel; private JCheckBox shiftForwardCheckBox; private JTextField ShiftDateTimetextField; private JLabel ShiftDateTimeLabel; private JCheckBox ShiftDateTimeOriginalcheckBox; private JCheckBox ShiftCreateDatecheckBox; private JCheckBox ShiftModifyDatecheckBox; private JCheckBox BackupOfOriginalscheckBox; private JCheckBox UpdatexmpcheckBox; private int[] selectedFilenamesIndices; public File[] files; private JProgressBar progBar; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ShiftDateTime.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; public ShiftDateTime() { setContentPane(shiftDateTimePane); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); shiftDateTimePane.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); setModal(true); getRootPane().setDefaultButton(buttonOK); buttonOK.addActionListener(e -> onOK()); buttonCancel.addActionListener(e -> onCancel()); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE shiftDateTimePane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } private void initDialog() { ShiftDateTimeLabel.setText(String.format(ProgramTexts.HTML, 320, ResourceBundle.getBundle("translations/program_strings").getString("sdt.toptext"))); } private void writeInfo() { String shiftOption; List<String> cmdparams = new LinkedList<>(); String exiftool = Utils.platformExiftool(); cmdparams.add(exiftool); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!BackupOfOriginalscheckBox.isSelected()) { cmdparams.add("-overwrite_original"); } if (shiftForwardCheckBox.isSelected()) { shiftOption = "+="; } else { shiftOption = "-="; } if (ShiftDateTimeOriginalcheckBox.isSelected()) { cmdparams.add("-exif:DateTimeOriginal" + shiftOption + ShiftDateTimetextField.getText().trim()); if (UpdatexmpcheckBox.isSelected()) { cmdparams.add("-xmp:DateTimeOriginal" + shiftOption + ShiftDateTimetextField.getText().trim()); } } if (ShiftModifyDatecheckBox.isSelected()) { cmdparams.add("-exif:ModifyDate" + shiftOption + ShiftDateTimetextField.getText().trim()); if (UpdatexmpcheckBox.isSelected()) { cmdparams.add("-xmp:ModifyDate" + shiftOption + ShiftDateTimetextField.getText().trim()); } } if (ShiftCreateDatecheckBox.isSelected()) { cmdparams.add("-exif:CreateDate" + shiftOption + ShiftDateTimetextField.getText().trim()); if (UpdatexmpcheckBox.isSelected()) { cmdparams.add("-xmp:DateTimeDigitized" + shiftOption + ShiftDateTimetextField.getText().trim()); } } for (int index : selectedFilenamesIndices) { if (Utils.isOsFromMicrosoft()) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } logger.info(cmdparams.toString()); CommandRunner.runCommandWithProgressBar(cmdparams, progBar); } private void onOK() { if ("0000:00:00 00:00:00".equals(ShiftDateTimetextField.getText())) { JOptionPane.showMessageDialog(shiftDateTimePane, String.format(ProgramTexts.HTML, 400, ResourceBundle.getBundle("translations/program_strings").getString("sdt.dlgshiftzero")), ResourceBundle.getBundle("translations/program_strings").getString("sdt.dlgnoshift"), JOptionPane.ERROR_MESSAGE); } else if ((!ShiftDateTimeOriginalcheckBox.isSelected()) && (!ShiftModifyDatecheckBox.isSelected()) && (!ShiftCreateDatecheckBox.isSelected())) { // You did not select any date option JOptionPane.showMessageDialog(shiftDateTimePane, String.format(ProgramTexts.HTML, 400, ResourceBundle.getBundle("translations/program_strings").getString("sdt.dlgshiftzero")), ResourceBundle.getBundle("translations/program_strings").getString("sdt.dlgnoshift"), JOptionPane.ERROR_MESSAGE); } else { writeInfo(); dispose(); } } private void onCancel() { // add your code here if necessary dispose(); } public void showDialog(JProgressBar progressBar) { selectedFilenamesIndices = MyVariables.getSelectedFilenamesIndices(); files = MyVariables.getLoadedFiles(); progBar = progressBar; pack(); setLocationByPlatform(true); setTitle(ResourceBundle.getBundle("translations/program_strings").getString("sdt.dlgtitle")); initDialog(); setVisible(true); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { shiftDateTimePane = new JPanel(); shiftDateTimePane.setLayout(new GridLayoutManager(7, 1, new Insets(10, 10, 10, 10), 1, 1)); shiftDateTimePane.setPreferredSize(new Dimension(450, 500)); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); shiftDateTimePane.add(panel1, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false)); panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); buttonOK = new JButton(); this.$$$loadButtonText$$$(buttonOK, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.ok")); panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); buttonCancel = new JButton(); this.$$$loadButtonText$$$(buttonCancel, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.cancel")); panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new GridLayoutManager(4, 2, new Insets(0, 0, 0, 0), -1, -1)); shiftDateTimePane.add(panel3, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel3.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); shiftForwardCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(shiftForwardCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "sdt.forward")); panel3.add(shiftForwardCheckBox, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer2 = new Spacer(); panel3.add(spacer2, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); final JLabel label1 = new JLabel(); this.$$$loadLabelText$$$(label1, this.$$$getMessageFromBundle$$$("translations/program_strings", "sdt.shifttext")); panel3.add(label1, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); ShiftDateTimetextField = new JTextField(); ShiftDateTimetextField.setText("0000:00:00 00:00:00"); panel3.add(ShiftDateTimetextField, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(120, -1), null, 0, false)); final JLabel label2 = new JLabel(); this.$$$loadLabelText$$$(label2, this.$$$getMessageFromBundle$$$("translations/program_strings", "sdt.format")); panel3.add(label2, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); ShiftDateTimeLabel = new JLabel(); ShiftDateTimeLabel.setText("ShiftDateTimeLabel"); shiftDateTimePane.add(ShiftDateTimeLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel4 = new JPanel(); panel4.setLayout(new GridLayoutManager(3, 1, new Insets(0, 0, 0, 0), -1, -1)); shiftDateTimePane.add(panel4, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); ShiftDateTimeOriginalcheckBox = new JCheckBox(); this.$$$loadButtonText$$$(ShiftDateTimeOriginalcheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "sdt.shiftdatetimeoriginal")); panel4.add(ShiftDateTimeOriginalcheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); ShiftCreateDatecheckBox = new JCheckBox(); this.$$$loadButtonText$$$(ShiftCreateDatecheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "sdt.shiftcreatedate")); panel4.add(ShiftCreateDatecheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); ShiftModifyDatecheckBox = new JCheckBox(); this.$$$loadButtonText$$$(ShiftModifyDatecheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "sdt.shiftmodifydate")); panel4.add(ShiftModifyDatecheckBox, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); BackupOfOriginalscheckBox = new JCheckBox(); this.$$$loadButtonText$$$(BackupOfOriginalscheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "chkbox.makebackup")); shiftDateTimePane.add(BackupOfOriginalscheckBox, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); UpdatexmpcheckBox = new JCheckBox(); UpdatexmpcheckBox.setSelected(true); this.$$$loadButtonText$$$(UpdatexmpcheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "sdt.updatexmp")); shiftDateTimePane.add(UpdatexmpcheckBox, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); } private static Method $$$cachedGetBundleMethod$$$ = null; private String $$$getMessageFromBundle$$$(String path, String key) { ResourceBundle bundle; try { Class<?> thisClass = this.getClass(); if ($$$cachedGetBundleMethod$$$ == null) { Class<?> dynamicBundleClass = thisClass.getClassLoader().loadClass("com.intellij.DynamicBundle"); $$$cachedGetBundleMethod$$$ = dynamicBundleClass.getMethod("getBundle", String.class, Class.class); } bundle = (ResourceBundle) $$$cachedGetBundleMethod$$$.invoke(null, path, thisClass); } catch (Exception e) { bundle = ResourceBundle.getBundle(path); } return bundle.getString(key); } /** * @noinspection ALL */ private void $$$loadLabelText$$$(JLabel component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setDisplayedMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ private void $$$loadButtonText$$$(AbstractButton component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return shiftDateTimePane; } }
17,687
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
ModifyAllDateTime.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/datetime/ModifyAllDateTime.java
package org.hvdw.jexiftoolgui.datetime; import ch.qos.logback.classic.Logger; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.*; import java.io.File; import java.lang.reflect.Method; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; public class ModifyAllDateTime extends JDialog { private JPanel rootModifyAllDateTimePane; private JButton buttonOK; private JButton buttonCancel; private JLabel ModifyAllDateTimeLabel; private JCheckBox UseRefDateTimecheckBox; private JTextField DatetextField; private JCheckBox BackupOfOriginalscheckBox; public int[] selectedFilenamesIndices; public File[] files; private JProgressBar progBar; private final static Logger logger = (Logger) LoggerFactory.getLogger(ModifyDateTime.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; public ModifyAllDateTime() { setContentPane(rootModifyAllDateTimePane); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); rootModifyAllDateTimePane.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); setModal(true); getRootPane().setDefaultButton(buttonOK); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE rootModifyAllDateTimePane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } public void initDialog() { ModifyAllDateTimeLabel.setText(String.format(ProgramTexts.HTML, 370, ResourceBundle.getBundle("translations/program_strings").getString("madt.toptext"))); DateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); Date date = new Date(); DatetextField.setText(dateFormat.format(date)); } private void writeInfo() { String shiftOption; List<String> cmdparams = new LinkedList<>(); String exiftool = Utils.platformExiftool(); cmdparams.add(exiftool); //cmdparams.add("-v"); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!BackupOfOriginalscheckBox.isSelected()) { cmdparams.add("-overwrite_original"); } cmdparams.add("-AllDates=" + DatetextField.getText().trim()); cmdparams.add("-track1:trackcreatedate=" + DatetextField.getText().trim()); cmdparams.add("-track1:trackmodifydate=" + DatetextField.getText().trim()); cmdparams.add("-track2:mediacreatedate=" + DatetextField.getText().trim()); cmdparams.add("-track2:mediamodifydate=" + DatetextField.getText().trim()); for (int index : selectedFilenamesIndices) { if (Utils.isOsFromMicrosoft()) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } logger.info(cmdparams.toString()); CommandRunner.runCommandWithProgressBar(cmdparams, progBar); } private void onOK() { // add your code here writeInfo(); dispose(); } private void onCancel() { // add your code here if necessary dispose(); } public void showDialog(JProgressBar progressBar) { selectedFilenamesIndices = MyVariables.getSelectedFilenamesIndices(); files = MyVariables.getLoadedFiles(); progBar = progressBar; pack(); setLocationByPlatform(true); setTitle(ResourceBundle.getBundle("translations/program_strings").getString("madt.title")); initDialog(); setVisible(true); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { rootModifyAllDateTimePane = new JPanel(); rootModifyAllDateTimePane.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1)); rootModifyAllDateTimePane.setPreferredSize(new Dimension(500, 300)); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); rootModifyAllDateTimePane.add(panel1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false)); panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); buttonOK = new JButton(); this.$$$loadButtonText$$$(buttonOK, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.ok")); panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); buttonCancel = new JButton(); this.$$$loadButtonText$$$(buttonCancel, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.cancel")); panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new GridLayoutManager(3, 1, new Insets(0, 0, 0, 0), -1, -1)); rootModifyAllDateTimePane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); ModifyAllDateTimeLabel = new JLabel(); ModifyAllDateTimeLabel.setText("ModifyDateTimeLabel"); panel3.add(ModifyAllDateTimeLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); UseRefDateTimecheckBox = new JCheckBox(); UseRefDateTimecheckBox.setText("Use date and time from reference image"); UseRefDateTimecheckBox.setVisible(false); panel3.add(UseRefDateTimecheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel4 = new JPanel(); panel4.setLayout(new GridLayoutManager(2, 2, new Insets(5, 5, 5, 5), -1, -1)); panel3.add(panel4, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); final JLabel label1 = new JLabel(); this.$$$loadLabelText$$$(label1, this.$$$getMessageFromBundle$$$("translations/program_strings", "madt.timeformat")); panel4.add(label1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label2 = new JLabel(); this.$$$loadLabelText$$$(label2, this.$$$getMessageFromBundle$$$("translations/program_strings", "madt.newdate")); panel4.add(label2, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); DatetextField = new JTextField(); panel4.add(DatetextField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); BackupOfOriginalscheckBox = new JCheckBox(); this.$$$loadButtonText$$$(BackupOfOriginalscheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "chkbox.makebackup")); rootModifyAllDateTimePane.add(BackupOfOriginalscheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); } private static Method $$$cachedGetBundleMethod$$$ = null; private String $$$getMessageFromBundle$$$(String path, String key) { ResourceBundle bundle; try { Class<?> thisClass = this.getClass(); if ($$$cachedGetBundleMethod$$$ == null) { Class<?> dynamicBundleClass = thisClass.getClassLoader().loadClass("com.intellij.DynamicBundle"); $$$cachedGetBundleMethod$$$ = dynamicBundleClass.getMethod("getBundle", String.class, Class.class); } bundle = (ResourceBundle) $$$cachedGetBundleMethod$$$.invoke(null, path, thisClass); } catch (Exception e) { bundle = ResourceBundle.getBundle(path); } return bundle.getString(key); } /** * @noinspection ALL */ private void $$$loadLabelText$$$(JLabel component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setDisplayedMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ private void $$$loadButtonText$$$(AbstractButton component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return rootModifyAllDateTimePane; } }
13,785
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
DateTime.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/datetime/DateTime.java
package org.hvdw.jexiftoolgui.datetime; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; public class DateTime { private static final ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(DateTime.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; public static void setFileDateTimeToDateTimeOriginal( JProgressBar progressBar, String fileType) { int counter = 0; //Used in loop for first time initialization; can't do that outside the loop String action = ""; int[] selectedIndices = MyVariables.getSelectedFilenamesIndices(); File[] files = MyVariables.getLoadedFiles(); List<String> cmdparams = new ArrayList<>(); StringBuilder tmpcmpstring = new StringBuilder(); String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("dlg.no"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.yes")}; logger.trace("Set file date/time to DateTimeOriginal?"); int choice = JOptionPane.showOptionDialog(null, String.format(ProgramTexts.HTML, 600, ResourceBundle.getBundle("translations/program_strings").getString("sfdt.text")),ResourceBundle.getBundle("translations/program_strings").getString("sfdt.title"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (choice == 1) { //Yes // Do something boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); boolean isWindows = Utils.isOsFromMicrosoft(); if (isWindows) { cmdparams.add("\"" + Utils.platformExiftool().replace("\\", "/") + "\"" ); if (preserveModifyDate) { cmdparams.add("-preserve"); } cmdparams.add("-overwrite_original"); if ("image".equals(fileType)) { cmdparams.add("\"-FileModifyDate<DateTimeOriginal\""); } else { cmdparams.add("\"-CreateDate<DateTimeOriginal\""); } } else { // The < or > redirect options cannot directly be used within a single param on unixes/linuxes cmdparams.add("/bin/sh"); cmdparams.add("-c"); if ("image".equals(fileType)) { action = "-FileModifyDate<DateTimeOriginal"; } else { action = "-CreateDate<DateTimeOriginal"; } if (preserveModifyDate) { tmpcmpstring = new StringBuilder(Utils.platformExiftool().replaceAll(" ", "\\ ") + " -overwrite_original -preserve '" + action + "' "); } else { tmpcmpstring = new StringBuilder(Utils.platformExiftool().replaceAll(" ", "\\ ") + " -overwrite_original '\" + action + \"' "); } } for (int index: selectedIndices) { logger.trace("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { cmdparams.add("\"" + files[index].getPath().replace("\\", "/") + "\""); } else { //tmpcmpstring.append(" ").append(files[index].getPath().replaceAll(" ", "\\ ")); tmpcmpstring.append(" ").append("'" + files[index].getPath() + "'"); } } if (!isWindows) { cmdparams.add(tmpcmpstring.toString()); } CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } } }
4,133
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
MetaData.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/metadata/MetaData.java
package org.hvdw.jexiftoolgui.metadata; import org.hvdw.jexiftoolgui.*; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.USER_HOME; public class MetaData { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(MetaData.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; public void copyToXmp(JLabel OutputLabel) { String fpath = ""; StringBuilder TotalOutput = new StringBuilder(); int[] selectedIndices = MyVariables.getSelectedFilenamesIndices(); File[] files = MyVariables.getLoadedFiles(); List<String> cmdparams = new ArrayList<String>(); String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("dlg.no"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.yes")}; logger.info("Copy all metadata to xmp format"); int choice = JOptionPane.showOptionDialog(null, String.format(ProgramTexts.HTML, 500, ResourceBundle.getBundle("translations/program_strings").getString("cmd.dlgtext")), ResourceBundle.getBundle("translations/program_strings").getString("cmd.dlgtitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (choice == 1) { //Yes // Do something OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.copyallxmpdata")); boolean isWindows = Utils.isOsFromMicrosoft(); String exiftool = Utils.platformExiftool(); for (int index : selectedIndices) { // Unfortunately we need to do this file by file. It also means we need to initialize everything again and again cmdparams.clear(); if (isWindows) { cmdparams.add(exiftool); cmdparams.add("-TagsFromfile"); cmdparams.add(files[index].getPath().replace("\\", "/")); cmdparams.add("\"-all>xmp:all\""); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } cmdparams.add("-overwrite_original"); cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add("/bin/sh"); cmdparams.add("-c"); cmdparams.add(exiftool + " -TagsFromfile " + files[index].getPath().replaceAll(" ", "\\ ") + " '-all:all>xmp:all' -overwrite_original " + files[index].getPath().replaceAll(" ", "\\ ")); } try { String res = CommandRunner.runCommand(cmdparams); logger.debug("res is\n{}", res); TotalOutput.append(res); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command"); } } CommandRunner.outputAfterCommand(TotalOutput.toString()); } } public void repairJPGMetadata(JProgressBar progressBar) { List<String> cmdparams = new ArrayList<String>(); String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("dlg.no"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.yes")}; int[] selectedIndices = MyVariables.getSelectedFilenamesIndices(); File[] files = MyVariables.getLoadedFiles(); logger.info("Repair corrupted metadata in JPG(s)"); int choice = JOptionPane.showOptionDialog(null, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_strings").getString("rjpg.dialogtext")), ResourceBundle.getBundle("translations/program_strings").getString("rjpg.dialogtitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (choice == 1) { //Yes cmdparams.add(Utils.platformExiftool()); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } cmdparams.add("-overwrite_original"); for (String s : MyConstants.REPAIR_JPG_METADATA) { cmdparams.add(s); } boolean isWindows = Utils.isOsFromMicrosoft(); for (int index : selectedIndices) { if (isWindows) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } // export metadata CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } } public void copyMetaData(JPanel rootpanel, JRadioButton[] CopyMetaDataRadiobuttons, JCheckBox[] CopyMetaDataCheckBoxes, int selectedRow, JProgressBar progressBar) { int selectedIndices[] = MyVariables.getSelectedFilenamesIndices(); File[] files = MyVariables.getLoadedFiles(); boolean atLeastOneSelected = false; boolean copyAllToXMP = false; String fpath = ""; List<String> params = new ArrayList<String>(); params.add(Utils.platformExiftool()); params.add("-TagsFromfile"); boolean isWindows = Utils.isOsFromMicrosoft(); if (isWindows) { fpath = files[selectedRow].getPath().replace("\\", "/"); } else { fpath = files[selectedRow].getPath(); } params.add(fpath); // which options selected? StringBuilder Message = new StringBuilder("<html>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.dlgyouhaveselected")); if (CopyMetaDataRadiobuttons[0].isSelected()) { Message.append(ResourceBundle.getBundle("translations/program_strings").getString("copyd.alltopreferred") + "<br><br>"); atLeastOneSelected = true; } else if (CopyMetaDataRadiobuttons[1].isSelected()) { Message.append(ResourceBundle.getBundle("translations/program_strings").getString("copyd.alltoorggroup") + "<br><br>"); params.add("-all:all"); atLeastOneSelected = true; } else { // The copySelectiveMetadataradioButton Message.append("<ul>"); if (CopyMetaDataCheckBoxes[0].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.copyexifcheckbox") + "</li>"); params.add("-exif:all"); atLeastOneSelected = true; } if (CopyMetaDataCheckBoxes[1].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.copyxmpcheckbox") + "</li>"); params.add("-xmp:all"); atLeastOneSelected = true; } if (CopyMetaDataCheckBoxes[2].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.copyiptccheckbox") + "</li>"); params.add("-iptc:all"); atLeastOneSelected = true; } if (CopyMetaDataCheckBoxes[3].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.copyicc_profilecheckbox") + "</li>"); params.add("-icc_profile:all"); atLeastOneSelected = true; } if (CopyMetaDataCheckBoxes[4].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.copygpscheckbox") + "</li>"); params.add("-gps:all"); atLeastOneSelected = true; } if (CopyMetaDataCheckBoxes[5].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.copyjfifcheckbox") + "</li>"); params.add("-jfif:all"); atLeastOneSelected = true; } if (CopyMetaDataCheckBoxes[6].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.copymakernotescheckbox") + "</li>"); params.add("-makernotes:all"); atLeastOneSelected = true; } Message.append("</ul><br><br>"); } //if (!copyAllToXMP) { // This is actually a dirty way of starting the copyalltoxmp and bypassing the rest in this method boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { params.add("-preserve"); } if (!CopyMetaDataCheckBoxes[7].isSelected()) { params.add("-overwrite_original"); } Message.append(ResourceBundle.getBundle("translations/program_strings").getString("copyd.dlgisthiscorrect") + "</html>"); if (atLeastOneSelected) { String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("dlg.cancel"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.continue")}; int choice = JOptionPane.showOptionDialog(null, Message, ResourceBundle.getBundle("translations/program_strings").getString("copyd.dlgtitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (choice == 1) { //Yes // Copy metadata String[] etparams = params.toArray(new String[0]); for (int index : selectedIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { params.add(files[index].getPath().replace("\\", "/")); } else { params.add(files[index].getPath()); } } // export metadata CommandRunner.runCommandWithProgressBar(params, progressBar); } } else { JOptionPane.showMessageDialog(rootpanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_strings").getString("copyd.nooptionsselectedtxt")), ResourceBundle.getBundle("translations/program_strings").getString("copyd.nooptionsselectedtitle"), JOptionPane.WARNING_MESSAGE); } //} } public void copyInsideMetaData(JPanel rootpanel, JRadioButton[] InsideCopyMetaDataRadiobuttons, JRadioButton[] InsideSubCopyMetaDataRadiobuttons, JCheckBox[] InsideCopyMetaDataCheckBoxes, JLabel OutputLabel) { StringBuilder TotalOutput = new StringBuilder(); int selectedIndices[] = MyVariables.getSelectedFilenamesIndices(); File[] files = MyVariables.getLoadedFiles(); String strjexiftoolguiARGSfolder = SystemPropertyFacade.getPropertyByKey(USER_HOME) + File.separator + MyConstants.MY_DATA_FOLDER + File.separator + "args"; boolean atLeastOneSelected = false; boolean copyAllToXMP = false; String fpath = ""; List<String> params = new ArrayList<String>(); // which options selected? StringBuilder Message = new StringBuilder("<html>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.dlgyouhaveselected")); if (InsideCopyMetaDataRadiobuttons[0].isSelected()) { copyToXmp(OutputLabel); atLeastOneSelected = true; copyAllToXMP= true; } else if (InsideCopyMetaDataRadiobuttons[1].isSelected()) { // we have the following checkboxes if (InsideSubCopyMetaDataRadiobuttons[0].isSelected()) { // To XMP // to xmp (0, 1, 2, 3): exif2xmpCheckBox, gps2xmpCheckBox, iptc2xmpCheckBox, pdf2xmpCheckBox, Message.append("<br>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.tagstoxmp") + "<ul>"); if (InsideCopyMetaDataCheckBoxes[0].isSelected()) { Message.append("<li>exif2xmp</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "exif2xmp.args"); atLeastOneSelected = true; } if (InsideCopyMetaDataCheckBoxes[1].isSelected()) { Message.append("<li>gps2xmp</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "gps2xmp.args"); atLeastOneSelected = true; } if (InsideCopyMetaDataCheckBoxes[2].isSelected()) { Message.append("<li>iptc2xmp</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "iptc2xmp.args"); atLeastOneSelected = true; } if (InsideCopyMetaDataCheckBoxes[3].isSelected()) { Message.append("<li>pdf2xmp</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "pdf2xmp.args"); atLeastOneSelected = true; } } if (InsideSubCopyMetaDataRadiobuttons[1].isSelected()) { // To Exif // to exif (4, 5): iptc2exifCheckBox, xmp2exifCheckBox, Message.append("<br>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.tagstoexif") + "<ul>"); if (InsideCopyMetaDataCheckBoxes[4].isSelected()) { Message.append("<li>iptc2exif</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "iptc2exif.args"); atLeastOneSelected = true; } if (InsideCopyMetaDataCheckBoxes[5].isSelected()) { Message.append("<li>xmp2exif</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "xmp2exif.args"); atLeastOneSelected = true; } } if (InsideSubCopyMetaDataRadiobuttons[2].isSelected()) { // To IPTC // to iptc (6, 7): exif2iptcCheckBox, xmp2iptcCheckBox, Message.append("<br>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.tagstoiptc") + "<ul>"); if (InsideCopyMetaDataCheckBoxes[6].isSelected()) { Message.append("<li>exif2iptc</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "exif2iptc.args"); atLeastOneSelected = true; } if (InsideCopyMetaDataCheckBoxes[7].isSelected()) { Message.append("<li>xmp2iptc</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "xmp2iptc.args"); atLeastOneSelected = true; } } if (InsideSubCopyMetaDataRadiobuttons[3].isSelected()) { // To Gps // to gps (8): xmp2gpsCheckBox, Message.append("<br>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.tagstogps") + "<ul>"); if (InsideCopyMetaDataCheckBoxes[8].isSelected()) { Message.append("<li>xmp2gps</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "xmp2gps.args"); atLeastOneSelected = true; } } if (InsideSubCopyMetaDataRadiobuttons[4].isSelected()) { //To PDF // to pdf (9): xmp2pdfCheckBox, Message.append("<br>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.tagstopdf") + "<ul>"); if (InsideCopyMetaDataCheckBoxes[9].isSelected()) { Message.append("<li>xmp2pdf</li>"); params.add("-@"); params.add(strjexiftoolguiARGSfolder + File.separator + "xmp2pdf.args"); atLeastOneSelected = true; } } Message.append("</ul><br><br>"); } if (!copyAllToXMP) { // This is actually a dirty way of bypassing the copyalltoxmp which has been called earlier boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { params.add("-preserve"); } // and of course (10): CopyInsideImageMakeCopyOfOriginalscheckBox if (!InsideCopyMetaDataCheckBoxes[10].isSelected()) { params.add("-overwrite_original"); } Message.append(ResourceBundle.getBundle("translations/program_strings").getString("copyd.dlgisthiscorrect") + "</html>"); if (atLeastOneSelected) { String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("dlg.cancel"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.continue")}; int choice = JOptionPane.showOptionDialog(null, Message, ResourceBundle.getBundle("translations/program_strings").getString("copyd.dlgtitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (choice == 1) { //Yes OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.inscopytagtotag")); // Copy metadata String[] etparams = params.toArray(new String[0]); for (int index : selectedIndices) { List<String> cmdparams = new ArrayList<String>(); boolean isWindows = Utils.isOsFromMicrosoft(); cmdparams.add(Utils.platformExiftool()); cmdparams.add("-Tagsfromfile"); //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { cmdparams.add(files[index].getPath().replace("\\", "/")); cmdparams.addAll(params); cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); cmdparams.addAll(params); cmdparams.add(files[index].getPath().replace("\\", "/")); } logger.debug("insidecopy command {}", cmdparams.toString()); try { String res = CommandRunner.runCommand(cmdparams); logger.debug("res is\n{}", res); TotalOutput.append(res); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command"); } } } CommandRunner.outputAfterCommand(TotalOutput.toString()); } else { JOptionPane.showMessageDialog(rootpanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_strings").getString("copyd.nooptionsselectedtxt")), ResourceBundle.getBundle("translations/program_strings").getString("copyd.nooptionsselectedtitle"), JOptionPane.WARNING_MESSAGE); } } } }
20,729
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
SearchMetaData.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/metadata/SearchMetaData.java
package org.hvdw.jexiftoolgui.metadata; import org.hvdw.jexiftoolgui.MyVariables; import javax.swing.*; import java.util.*; import java.util.List; import java.util.stream.Collectors; import static org.slf4j.LoggerFactory.getLogger; /** This class will be used to search through metadata on both tag and value for loaded images * Maybe later I might implement a background process to store metadata also in the database (and then create a special metadata database?) */ public class SearchMetaData { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) getLogger(SearchMetaData.class); HashMap<String, HashMap<String, String>> imagesData = MyVariables.getimagesData(); public static List<String> searchMetaData(JPanel rootPanel, String searchPhrase) { List<String> result = new ArrayList<>(); HashMap <String, HashMap<String, String> > imagesData = MyVariables.getimagesData(); //logger.info("in searchmetada \n\n{}", imagesData.toString()); for (Map.Entry<String, HashMap<String, String>> outerEntry: imagesData.entrySet()) { String imageName = outerEntry.getKey(); HashMap<String, String> singleImageMetaData = outerEntry.getValue(); //now loop through the single image hashmap with the tag & value Set<Map.Entry<String, String>> entrySet = singleImageMetaData.entrySet(); searchPhrase = searchPhrase.toLowerCase(); for (Map.Entry<String, String> entry: entrySet) { //logger.info("imageName {}", imageName); if (entry.getKey().toLowerCase().contains(searchPhrase)) { result.add(imageName + "\tkey-value\t" + entry.getKey() + "\t" + entry.getValue()); logger.debug("imageName {}: found key {} with value {}", imageName, entry.getKey(), entry.getValue()); } if (entry.getValue().toLowerCase().contains(searchPhrase)) { result.add(imageName + "\tvalue-key\t" + entry.getValue() + "\t" + entry.getKey()); logger.debug("imageName {}: found value {} with corresponding key {}", imageName, entry.getValue(), entry.getKey()); } } // Now sort the list of results, if not empty if ((result != null) && !(result.isEmpty())) { result = result.stream().sorted().collect(Collectors.toList()); } } return result; } }
2,513
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
CreateArgsFile.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/metadata/CreateArgsFile.java
package org.hvdw.jexiftoolgui.metadata; import ch.qos.logback.classic.Logger; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.MyConstants; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.*; import java.io.File; import java.lang.reflect.Method; import java.util.*; import java.util.List; public class CreateArgsFile extends JDialog { private final static Logger logger = (Logger) LoggerFactory.getLogger(CreateArgsFile.class); private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JLabel CreateArgsMetaDataUiText; private JCheckBox exportAllMetadataCheckBox; private JCheckBox exportExifDataCheckBox; private JCheckBox exportXmpDataCheckBox; private JCheckBox exportGpsDataCheckBox; private JCheckBox exportIptcDataCheckBox; private JCheckBox exportICCDataCheckBox; private JCheckBox makeBackupOfOriginalsCheckBox; public int[] selectedFilenamesIndices; public File[] files; public JProgressBar progBar; public CreateArgsFile() { setContentPane(contentPane); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); contentPane.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); setModal(true); getRootPane().setDefaultButton(buttonOK); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); exportAllMetadataCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (exportAllMetadataCheckBox.isSelected()) { exportExifDataCheckBox.setSelected(true); exportXmpDataCheckBox.setSelected(true); exportGpsDataCheckBox.setSelected(true); exportIptcDataCheckBox.setSelected(true); exportICCDataCheckBox.setSelected(true); } else { exportExifDataCheckBox.setSelected(false); exportXmpDataCheckBox.setSelected(false); exportGpsDataCheckBox.setSelected(false); exportIptcDataCheckBox.setSelected(false); exportICCDataCheckBox.setSelected(false); } } }); } private void initDialog() { CreateArgsMetaDataUiText.setText(String.format(ProgramTexts.HTML, 270, ResourceBundle.getBundle("translations/program_strings").getString("args.toptext"))); } private void onOK() { // add your code here writeFile(); dispose(); } private void onCancel() { // add your code here if necessary dispose(); } //public void createfile(int[] selectedFilenamesIndices, File[] files){ private void writeFile() { boolean atLeastOneSelected = false; String[] CAparams = MyConstants.CREATE_ARGS_FILE_STRINGS; List<String> params = new ArrayList<String>(); params.add(Utils.platformExiftool()); // which options selected? StringBuilder Message = new StringBuilder("<html>" + ResourceBundle.getBundle("translations/program_strings").getString("args.dlgtext")); if (exportAllMetadataCheckBox.isSelected()) { Message.append(ResourceBundle.getBundle("translations/program_strings").getString("args.all") + "<br>"); params.add("-all"); atLeastOneSelected = true; } else { Message.append("<ul>"); if (exportExifDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("args.exif") + "</li>"); params.add("-exif:all"); atLeastOneSelected = true; } if (exportXmpDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("args.xmp") + "</li>"); params.add("-xmp:all"); atLeastOneSelected = true; } if (exportGpsDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("args.gps") + "</li>"); params.add("-gps:all"); atLeastOneSelected = true; } if (exportIptcDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("args.iptc") + "</li>"); params.add("-iptc:all"); atLeastOneSelected = true; } if (exportICCDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("args.icc") + "</li>"); params.add("-icc_profile:all"); atLeastOneSelected = true; } Message.append("</ul><br><br>"); } Message.append(ResourceBundle.getBundle("translations/program_strings").getString("args.dlgcorrect") + "</html>"); if (atLeastOneSelected) { String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("dlg.cancel"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.continue")}; int choice = JOptionPane.showOptionDialog(null, Message, ResourceBundle.getBundle("translations/program_strings").getString("args.dlgtext"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (choice == 1) { //Yes params.addAll(Arrays.asList(MyConstants.CREATE_ARGS_FILE_STRINGS)); // images selected boolean isWindows = Utils.isOsFromMicrosoft(); for (int index : selectedFilenamesIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { params.add(files[index].getPath().replace("\\", "/")); } else { params.add(files[index].getPath()); } } // export metadata CommandRunner.runCommandWithProgressBar(params, progBar); } } else { JOptionPane.showMessageDialog(contentPane, ResourceBundle.getBundle("translations/program_strings").getString("args.nothingselected"), ResourceBundle.getBundle("translations/program_strings").getString("args.nothingselected"), JOptionPane.WARNING_MESSAGE); } } public void showDialog(int[] selectedIndices, File[] openedfiles, JProgressBar progressBar) { //ExportMetadata dialog = new ExportMetadata(); //setSize(400, 250); // first set the public variables I need selectedFilenamesIndices = selectedIndices; files = openedfiles; progBar = progressBar; //Now do the gui pack(); //setLocationRelativeTo(null); setLocationByPlatform(true); setTitle(ResourceBundle.getBundle("translations/program_strings").getString("createargsfile.title")); initDialog(); setVisible(true); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { contentPane = new JPanel(); contentPane.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1)); contentPane.setPreferredSize(new Dimension(400, 400)); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false)); panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); buttonOK = new JButton(); this.$$$loadButtonText$$$(buttonOK, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.ok")); panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); buttonCancel = new JButton(); this.$$$loadButtonText$$$(buttonCancel, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.cancel")); panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); CreateArgsMetaDataUiText = new JLabel(); CreateArgsMetaDataUiText.setEnabled(true); CreateArgsMetaDataUiText.setRequestFocusEnabled(false); CreateArgsMetaDataUiText.setText(""); CreateArgsMetaDataUiText.setVerifyInputWhenFocusTarget(false); panel3.add(CreateArgsMetaDataUiText, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 1, false)); final JPanel panel4 = new JPanel(); panel4.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel4, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); exportAllMetadataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(exportAllMetadataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "args.all")); panel4.add(exportAllMetadataCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel5 = new JPanel(); panel5.setLayout(new GridLayoutManager(5, 1, new Insets(0, 30, 0, 0), -1, -1)); panel4.add(panel5, new GridConstraints(1, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 2, false)); exportExifDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(exportExifDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "args.exif")); panel5.add(exportExifDataCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); exportXmpDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(exportXmpDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "args.xmp")); panel5.add(exportXmpDataCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); exportGpsDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(exportGpsDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "args.gps")); panel5.add(exportGpsDataCheckBox, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); exportIptcDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(exportIptcDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "args.iptc")); panel5.add(exportIptcDataCheckBox, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); exportICCDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(exportICCDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "args.icc")); panel5.add(exportICCDataCheckBox, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer2 = new Spacer(); panel4.add(spacer2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); } private static Method $$$cachedGetBundleMethod$$$ = null; private String $$$getMessageFromBundle$$$(String path, String key) { ResourceBundle bundle; try { Class<?> thisClass = this.getClass(); if ($$$cachedGetBundleMethod$$$ == null) { Class<?> dynamicBundleClass = thisClass.getClassLoader().loadClass("com.intellij.DynamicBundle"); $$$cachedGetBundleMethod$$$ = dynamicBundleClass.getMethod("getBundle", String.class, Class.class); } bundle = (ResourceBundle) $$$cachedGetBundleMethod$$$.invoke(null, path, thisClass); } catch (Exception e) { bundle = ResourceBundle.getBundle(path); } return bundle.getString(key); } /** * @noinspection ALL */ private void $$$loadButtonText$$$(AbstractButton component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return contentPane; } }
17,853
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
RemoveMetadata.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/metadata/RemoveMetadata.java
package org.hvdw.jexiftoolgui.metadata; import ch.qos.logback.classic.Logger; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.StandardFileIO; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.*; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; public class RemoveMetadata extends JDialog { private final static Logger logger = (Logger) LoggerFactory.getLogger(RemoveMetadata.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JLabel RemoveMetaDataUiText; private JCheckBox removeAllMetadataCheckBox; private JCheckBox removeExifDataCheckBox; private JCheckBox removeXmpDataCheckBox; private JCheckBox removeGpsDataCheckBox; private JCheckBox removeIptcDataCheckBox; private JCheckBox removeICCDataCheckBox; private JCheckBox makeBackupOfOriginalsCheckBox; private JCheckBox removegeotagDataCheckbox; private JCheckBox removexmpgeotagDataCheckbox; private JRadioButton rempgroupradioButtonExpByTagName; private JComboBox remcomboBoxExpByTagName; private JRadioButton remUsedCategeriesRadioButton; private JLabel lblWarning; public int[] selectedFilenamesIndices; public File[] files; public JProgressBar progBar; //private final HyperlinkListener linkListener = new LinkListener(); public RemoveMetadata() { setContentPane(contentPane); Locale currentLocale = new Locale.Builder().setLocale(MyVariables.getCurrentLocale()).build(); contentPane.applyComponentOrientation(ComponentOrientation.getOrientation(currentLocale)); setModal(true); getRootPane().setDefaultButton(buttonOK); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); removeAllMetadataCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (removeAllMetadataCheckBox.isSelected()) { removeExifDataCheckBox.setSelected(true); removeXmpDataCheckBox.setSelected(true); removeGpsDataCheckBox.setSelected(true); removeIptcDataCheckBox.setSelected(true); removeICCDataCheckBox.setSelected(true); removegeotagDataCheckbox.setSelected(true); removexmpgeotagDataCheckbox.setSelected(true); } else { removeExifDataCheckBox.setSelected(false); removeXmpDataCheckBox.setSelected(false); removeGpsDataCheckBox.setSelected(false); removeIptcDataCheckBox.setSelected(false); removeICCDataCheckBox.setSelected(false); removegeotagDataCheckbox.setSelected(false); removexmpgeotagDataCheckbox.setSelected(false); } } }); remUsedCategeriesRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (remUsedCategeriesRadioButton.isSelected()) { remcomboBoxExpByTagName.setEnabled(false); removeAllMetadataCheckBox.setEnabled(true); removeExifDataCheckBox.setEnabled(true); removeXmpDataCheckBox.setEnabled(true); removeGpsDataCheckBox.setEnabled(true); removeIptcDataCheckBox.setEnabled(true); removeICCDataCheckBox.setEnabled(true); removegeotagDataCheckbox.setEnabled(true); removexmpgeotagDataCheckbox.setEnabled(true); } } }); rempgroupradioButtonExpByTagName.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (rempgroupradioButtonExpByTagName.isSelected()) { remcomboBoxExpByTagName.setEnabled(true); removeAllMetadataCheckBox.setEnabled(false); removeExifDataCheckBox.setEnabled(false); removeXmpDataCheckBox.setEnabled(false); removeGpsDataCheckBox.setEnabled(false); removeIptcDataCheckBox.setEnabled(false); removeICCDataCheckBox.setEnabled(false); removegeotagDataCheckbox.setEnabled(false); removexmpgeotagDataCheckbox.setEnabled(false); } } }); lblWarning.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // the user clicks on the label Utils.openBrowser("https://exiftool.org/exiftool_pod.html#DESCRIPTION"); } @Override public void mouseEntered(MouseEvent e) { // the mouse has entered the label } @Override public void mouseExited(MouseEvent e) { // the mouse has exited the label } }); } private void initDialog() { //RemoveMetaDataUiText.setContentType("text/html"); RemoveMetaDataUiText.setText(String.format(ProgramTexts.HTML, 620, (ResourceBundle.getBundle("translations/program_strings").getString("rmd.toptext") + "<br><br>"))); String TagGroups = StandardFileIO.readTextFileAsStringFromResource("texts/g1.txt"); String[] Tags = TagGroups.split("\\r?\\n"); // split on new lines remcomboBoxExpByTagName.setModel(new DefaultComboBoxModel(Tags)); remcomboBoxExpByTagName.setEnabled(false); } private void onOK() { // add your code here removeMetadatafromImage(); dispose(); } private void onCancel() { // add your code here if necessary dispose(); } private void removeMetadatafromImage() { boolean atLeastOneSelected = false; List<String> params = new ArrayList<String>(); params.add(Utils.platformExiftool()); // which options selected? StringBuilder Message = new StringBuilder("<html>" + ResourceBundle.getBundle("translations/program_strings").getString("rmd.youhaveselected")); ///////////////////////////////////// if (remUsedCategeriesRadioButton.isSelected()) { if (removeAllMetadataCheckBox.isSelected()) { Message.append(ResourceBundle.getBundle("translations/program_strings").getString("rmd.allmetadata") + "<br><br>"); params.add("-all="); atLeastOneSelected = true; } else { Message.append("<ul>"); if (removeExifDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("rmd.removeexif") + "</li>"); params.add("-exif:all="); atLeastOneSelected = true; } if (removeXmpDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("rmd.removexmp") + "</li>"); params.add("-xmp:all="); atLeastOneSelected = true; } if (removeGpsDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("rmd.removegps") + "</li>"); params.add("-gps:all="); atLeastOneSelected = true; } if (removeIptcDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("rmd.removeiptc") + "</li>"); params.add("-iptc:all="); atLeastOneSelected = true; } if (removeICCDataCheckBox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("rmd.removeicc") + "</li>"); params.add("-icc_profile:all="); atLeastOneSelected = true; } if (removegeotagDataCheckbox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("rmd.removegeotag") + "</li>"); params.add("-geotag="); atLeastOneSelected = true; } if (removexmpgeotagDataCheckbox.isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("rmd.removegexmp") + "</li>"); params.add("-xmp:geotag="); atLeastOneSelected = true; } Message.append("</ul><br><br>"); } } else { //remove by group String selectedCategory = String.valueOf(remcomboBoxExpByTagName.getSelectedItem()); Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("rmd.remcategory") + ": " + selectedCategory + "</li>"); params.add("-" + selectedCategory + ":all="); atLeastOneSelected = true; logger.info("String.valueOf(remcomboBoxExpByTagName.getSelectedItem()) {}", "-" + selectedCategory + ":all="); } //////////////////////////////////////////////////// Message.append("Is this correct?</html>"); if (atLeastOneSelected) { String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("dlg.cancel"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.continue")}; int choice = JOptionPane.showOptionDialog(null, Message, ResourceBundle.getBundle("translations/program_strings").getString("rmd.dlgyouwantto"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (choice == 1) { //Yes boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { params.add("-preserve"); } if (!makeBackupOfOriginalsCheckBox.isSelected()) { params.add("-overwrite_original"); } boolean isWindows = Utils.isOsFromMicrosoft(); for (int index : selectedFilenamesIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { params.add(files[index].getPath().replace("\\", "/")); } else { params.add(files[index].getPath()); } } // remove metadata CommandRunner.runCommandWithProgressBar(params, progBar); } } else { JOptionPane.showMessageDialog(contentPane, ResourceBundle.getBundle("translations/program_strings").getString("rmd.dlgnooptiontext"), ResourceBundle.getBundle("translations/program_strings").getString("rmd.dlgnooptiontitle"), JOptionPane.WARNING_MESSAGE); } } public void showDialog(JProgressBar progressBar) { selectedFilenamesIndices = MyVariables.getSelectedFilenamesIndices(); files = MyVariables.getLoadedFiles(); progBar = progressBar; lblWarning.setText(String.format(ProgramTexts.HTML, 200, ResourceBundle.getBundle("translations/program_strings").getString("rmd.warning") + "<a href=\"https://exiftool.org/exiftool_pod.html#DESCRIPTION\">https://exiftool.org/exiftool_pod.html#DESCRIPTION</a>")); pack(); //setLocationRelativeTo(null); setLocationByPlatform(true); setTitle(ResourceBundle.getBundle("translations/program_strings").getString("removemetadata.title")); initDialog(); setVisible(true); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { contentPane = new JPanel(); contentPane.setLayout(new GridLayoutManager(4, 1, new Insets(10, 10, 10, 10), -1, -1)); contentPane.setPreferredSize(new Dimension(850, 500)); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel1, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false)); panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); buttonOK = new JButton(); this.$$$loadButtonText$$$(buttonOK, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.ok")); panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); buttonCancel = new JButton(); this.$$$loadButtonText$$$(buttonCancel, this.$$$getMessageFromBundle$$$("translations/program_strings", "dlg.cancel")); panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); RemoveMetaDataUiText = new JLabel(); RemoveMetaDataUiText.setEnabled(true); RemoveMetaDataUiText.setRequestFocusEnabled(false); RemoveMetaDataUiText.setText(""); RemoveMetaDataUiText.setVerifyInputWhenFocusTarget(false); panel3.add(RemoveMetaDataUiText, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 1, false)); final JPanel panel4 = new JPanel(); panel4.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel4, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); makeBackupOfOriginalsCheckBox = new JCheckBox(); makeBackupOfOriginalsCheckBox.setSelected(true); this.$$$loadButtonText$$$(makeBackupOfOriginalsCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "chkbox.makebackup")); panel4.add(makeBackupOfOriginalsCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel5 = new JPanel(); panel5.setLayout(new GridLayoutManager(4, 3, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel5, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel5.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); removeAllMetadataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(removeAllMetadataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "rmd.removeall")); panel5.add(removeAllMetadataCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel6 = new JPanel(); panel6.setLayout(new GridLayoutManager(7, 1, new Insets(0, 30, 0, 0), -1, -1)); panel5.add(panel6, new GridConstraints(2, 0, 2, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 2, false)); removeExifDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(removeExifDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "rmd.removeexif")); panel6.add(removeExifDataCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); removeXmpDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(removeXmpDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "rmd.removexmp")); panel6.add(removeXmpDataCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); removeGpsDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(removeGpsDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "rmd.removegps")); panel6.add(removeGpsDataCheckBox, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); removeIptcDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(removeIptcDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "rmd.removeiptc")); panel6.add(removeIptcDataCheckBox, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); removeICCDataCheckBox = new JCheckBox(); this.$$$loadButtonText$$$(removeICCDataCheckBox, this.$$$getMessageFromBundle$$$("translations/program_strings", "rmd.removeicc")); panel6.add(removeICCDataCheckBox, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); removegeotagDataCheckbox = new JCheckBox(); this.$$$loadButtonText$$$(removegeotagDataCheckbox, this.$$$getMessageFromBundle$$$("translations/program_strings", "rmd.removegeotag")); panel6.add(removegeotagDataCheckbox, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); removexmpgeotagDataCheckbox = new JCheckBox(); this.$$$loadButtonText$$$(removexmpgeotagDataCheckbox, this.$$$getMessageFromBundle$$$("translations/program_strings", "rmd.removegexmp")); panel6.add(removexmpgeotagDataCheckbox, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer2 = new Spacer(); panel5.add(spacer2, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel7 = new JPanel(); panel7.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 30), -1, -1)); panel5.add(panel7, new GridConstraints(1, 2, 2, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); remcomboBoxExpByTagName = new JComboBox(); panel7.add(remcomboBoxExpByTagName, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final Spacer spacer3 = new Spacer(); panel7.add(spacer3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); lblWarning = new JLabel(); lblWarning.setText(""); panel7.add(lblWarning, new GridConstraints(1, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); remUsedCategeriesRadioButton = new JRadioButton(); remUsedCategeriesRadioButton.setSelected(true); this.$$$loadButtonText$$$(remUsedCategeriesRadioButton, this.$$$getMessageFromBundle$$$("translations/program_strings", "rmd.mostused")); panel5.add(remUsedCategeriesRadioButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); rempgroupradioButtonExpByTagName = new JRadioButton(); this.$$$loadButtonText$$$(rempgroupradioButtonExpByTagName, this.$$$getMessageFromBundle$$$("translations/program_strings", "vdtab.bygroup")); panel5.add(rempgroupradioButtonExpByTagName, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); ButtonGroup buttonGroup; buttonGroup = new ButtonGroup(); buttonGroup.add(remUsedCategeriesRadioButton); buttonGroup.add(rempgroupradioButtonExpByTagName); } private static Method $$$cachedGetBundleMethod$$$ = null; private String $$$getMessageFromBundle$$$(String path, String key) { ResourceBundle bundle; try { Class<?> thisClass = this.getClass(); if ($$$cachedGetBundleMethod$$$ == null) { Class<?> dynamicBundleClass = thisClass.getClassLoader().loadClass("com.intellij.DynamicBundle"); $$$cachedGetBundleMethod$$$ = dynamicBundleClass.getMethod("getBundle", String.class, Class.class); } bundle = (ResourceBundle) $$$cachedGetBundleMethod$$$.invoke(null, path, thisClass); } catch (Exception e) { bundle = ResourceBundle.getBundle(path); } return bundle.getString(key); } /** * @noinspection ALL */ private void $$$loadButtonText$$$(AbstractButton component, String text) { StringBuffer result = new StringBuffer(); boolean haveMnemonic = false; char mnemonic = '\0'; int mnemonicIndex = -1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '&') { i++; if (i == text.length()) break; if (!haveMnemonic && text.charAt(i) != '&') { haveMnemonic = true; mnemonic = text.charAt(i); mnemonicIndex = result.length(); } } result.append(text.charAt(i)); } component.setText(result.toString()); if (haveMnemonic) { component.setMnemonic(mnemonic); component.setDisplayedMnemonicIndex(mnemonicIndex); } } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return contentPane; } }
27,603
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
ExportMetadata.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/metadata/ExportMetadata.java
package org.hvdw.jexiftoolgui.metadata; import ch.qos.logback.classic.Logger; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.SQLiteJDBC; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.view.SimpleWebView; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; public class ExportMetadata { private final static Logger logger = (Logger) LoggerFactory.getLogger(ExportMetadata.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; public static void writeExport(JPanel rootPanel, JRadioButton[] GeneralExportRadiobuttons, JCheckBox[] GeneralExportCheckButtons, JComboBox exportUserCombicomboBox, JProgressBar progressBar, String ExpImgFoldertextField, boolean includeSubFolders) { boolean atLeastOneSelected = false; final BufferedWriter[] writer = new BufferedWriter[1]; List<String> params = new ArrayList<String>(); List<String> cmdparams = new ArrayList<String>(); // We need this for the csv option String filepath = ""; // Again: we need this for the csv option int[] selectedIndices = null; File[] files = null; if (ExpImgFoldertextField.isBlank()) { //if the foldertextfield is empty; we need to have selected images selectedIndices = MyVariables.getSelectedFilenamesIndices(); files = MyVariables.getLoadedFiles(); logger.info("passed the if field"); } String createdExportFiles = ""; String createdExportFileExtension = ""; int counter = 1; // checkboxes: exportAllMetadataCheckBox, exportExifDataCheckBox, exportXmpDataCheckBox, exportGpsDataCheckBox, exportIptcDataCheckBox, exportICCDataCheckBox, GenExpuseMetadataTagLanguageCheckBoxport // translate to clarify // catmetadataradioButton, exportFromUserCombisradioButton, txtRadioButton, tabRadioButton, xmlRadioButton, htmlRadioButton, csvRadioButton JRadioButton catmetadataradioButton = GeneralExportRadiobuttons[0]; JRadioButton exportFromUserCombisradioButton = GeneralExportRadiobuttons[1]; JRadioButton txtRadioButton = GeneralExportRadiobuttons[2]; JRadioButton tabRadioButton = GeneralExportRadiobuttons[3]; JRadioButton xmlRadioButton = GeneralExportRadiobuttons[4]; JRadioButton htmlRadioButton = GeneralExportRadiobuttons[5]; JRadioButton csvRadioButton = GeneralExportRadiobuttons[6]; boolean isWindows = Utils.isOsFromMicrosoft(); params.add(Utils.platformExiftool()); if (GeneralExportCheckButtons[6].isSelected()) { // Check for chosen metadata language if (!"".equals(Utils.getmetadataLanguage())) { params.add("-lang"); params.add(Utils.getmetadataLanguage()); logger.debug("Export in specific metadata language requested lang= {}", Utils.getmetadataLanguage()); } } params.add("-a"); StringBuilder Message = new StringBuilder(); if (catmetadataradioButton.isSelected()) { // which options are selected from the checkboxes? Message.append("<html>" + ResourceBundle.getBundle("translations/program_strings").getString("copyd.dlgyouhaveselected")); if (GeneralExportCheckButtons[0].isSelected()) { Message.append(ResourceBundle.getBundle("translations/program_strings").getString("emd.exportall")); params.add("-all"); Message.append("<br><br>"); atLeastOneSelected = true; } else { Message.append("<ul>"); if (GeneralExportCheckButtons[1].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("emd.exportexif") + "</li>"); params.add("-exif:all"); atLeastOneSelected = true; } if (GeneralExportCheckButtons[2].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("emd.extportxmp") + "</li>"); params.add("-xmp:all"); atLeastOneSelected = true; } if (GeneralExportCheckButtons[3].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("emd.exportgps") + "</li>"); params.add("-gps:all"); atLeastOneSelected = true; } if (GeneralExportCheckButtons[4].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("emd.exportiptc") + "</li>"); params.add("-iptc:all"); atLeastOneSelected = true; } if (GeneralExportCheckButtons[5].isSelected()) { Message.append("<li>" + ResourceBundle.getBundle("translations/program_strings").getString("emd.exporticc") + "</li>"); params.add("-icc_profile:all"); atLeastOneSelected = true; } Message.append("</ul><br><br>"); } } else { // This is when the user has selected to export from a user combination atLeastOneSelected = true; // if we use the drop-down always one item is selected String SelectedCombi = exportUserCombicomboBox.getSelectedItem().toString(); logger.debug("selected metadata set for export {}", SelectedCombi); String sql = "select tag from custommetadatasetLines where customset_name='" + SelectedCombi + "' order by rowcount"; String queryResult = SQLiteJDBC.singleFieldQuery(sql, "tag"); if (queryResult.length() > 0) { String[] customTags = queryResult.split("\\r?\\n"); logger.debug("queryResult {}", queryResult); List<String> tmpparams = new ArrayList<String>(); for (String customTag : customTags) { logger.trace("customTag {}", customTag); if (customTag.startsWith("-")) { params.add(customTag); } else { params.add("-" + customTag); } } logger.debug("custom tags for export: {}", params.toString()); } Message.append("<html>" + ResourceBundle.getBundle("translations/program_strings").getString("emd.askusercombi") + "<br>"); Message.append(SelectedCombi); Message.append("<br><br>"); } Message.append(ResourceBundle.getBundle("translations/program_strings").getString("copyd.dlgisthiscorrect") + "</html>"); if (atLeastOneSelected) { String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("dlg.cancel"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.continue")}; int choice = JOptionPane.showOptionDialog(null, Message, ResourceBundle.getBundle("translations/program_strings").getString("emd.dlgtitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (choice == 1) { //Yes // Check with export file format has been chosen if (txtRadioButton.isSelected()) { params.add("-w!"); params.add("txt"); createdExportFileExtension = ".txt"; } else if (tabRadioButton.isSelected()) { params.add("-t"); params.add("-w!"); params.add("txt"); createdExportFileExtension = ".txt"; } else if (xmlRadioButton.isSelected()) { params.add("-X"); params.add("-w!"); params.add("xml"); createdExportFileExtension = ".xml"; } else if (htmlRadioButton.isSelected()) { params.add("-h"); params.add("-w!"); params.add("html"); createdExportFileExtension = ".html"; /*} else if (xmpRadioButton.isSelected()) { params.add("xmpexport"); */ } else if (csvRadioButton.isSelected()) { params.add("-csv"); } // Use files from previews or a folder if (!(ExpImgFoldertextField.isBlank())) { // if the foldertextfield is not empty; folder takes precedence over preview files logger.debug("exporting from folder {}", ExpImgFoldertextField ); createdExportFiles = "<a href=\"file://" + ExpImgFoldertextField + "\">" + ExpImgFoldertextField + "</a><br>"; logger.debug("includesubfolder {}", includeSubFolders); if (includeSubFolders) { params.add("-r"); } if (isWindows) { if (csvRadioButton.isSelected()) { params.add("\"" + ExpImgFoldertextField.replace("\\", "/") + "\""); } else { params.add(ExpImgFoldertextField.replace("\\", "/")); } } else { params.add(ExpImgFoldertextField); } } else { // use the selected previews for (int index : selectedIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { if (csvRadioButton.isSelected()) { params.add("\"" + files[index].getPath().replace("\\", "/") + "\""); } else { params.add(files[index].getPath().replace("\\", "/")); //createdExportFiles += files[index].getParent() + File.separator + files[index].getName() + "<br>"; createdExportFiles += files[index].getParent() + File.separator + Utils.getFileNameWithoutExtension(files[index].getName()) + createdExportFileExtension + "<br>"; } } else { params.add(files[index].getPath()); //createdExportFiles += files[index].getParent() + File.separator + files[index].getName() + "<br>"; //createdExportFiles += files[index].getParent() + File.separator + Utils.getFileNameWithoutExtension(files[index].getName()) + createdExportFileExtension + "<br>"; String file = files[index].getParent() + File.separator + Utils.getFileNameWithoutExtension(files[index].getName()) + createdExportFileExtension; String link = "file://" + file; String complete = "<a href=\"" + link + "\">" + file + "</a><br>"; createdExportFiles += complete; } // Again necessary for csv filepath = files[index].getParent(); counter++; } } // Originally for csv we needed the > character to redirect output to a csv file, which we need to treat specially and differently on unixes and windows. // We also really needed the shell for it otherwise the > is seen as a file // We now read the output into a string and write that string to file with a bufferedwriter if (csvRadioButton.isSelected()) { if (isWindows) { cmdparams.add(params.toString().substring(1, params.toString().length() - 1).replaceAll(", ", " ")); } else { cmdparams.add(params.toString().substring(1, params.toString().length() - 1).replaceAll(", ", " ")); } } else { cmdparams = params; } logger.info("cmdparams : {}", cmdparams.toString()); // Export metadata if (!csvRadioButton.isSelected()) { //CommandRunner.runCommandWithProgressBar(params, progressBar); Executor executor = Executors.newSingleThreadExecutor(); String finalCreatedExportFiles = createdExportFiles; int finalCounter = counter; executor.execute(new Runnable() { @Override public void run() { try { try { CommandRunner.runCommand(params); progressBar.setVisible(false); SimpleWebView WV = new SimpleWebView(); if (!(ExpImgFoldertextField.isBlank())) { //folder specified WV.HTMLView(ResourceBundle.getBundle("translations/program_strings").getString("emd.expfolder"), String.format(ProgramTexts.HTML, 600, (ResourceBundle.getBundle("translations/program_strings").getString("emd.expfolder") + ":<br><br>" + finalCreatedExportFiles)), 700, (int) (100 + (finalCounter * 15))); } else { WV.HTMLView(ResourceBundle.getBundle("translations/program_strings").getString("emd.expfiles"), String.format(ProgramTexts.HTML, 600, (ResourceBundle.getBundle("translations/program_strings").getString("emd.expfiles") + ":<br><br>" + finalCreatedExportFiles)), 700, (int) (100 + (finalCounter * 15))); } //JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 400, (ResourceBundle.getBundle("translations/program_strings").getString("emd.expfiles") + ":<br><br>" + createdExportFiles), ResourceBundle.getBundle("translations/program_strings").getString("emd.expfiles"), JOptionPane.INFORMATION_MESSAGE)); } catch (InterruptedException | IOException e) { logger.error("Error creating your export files {}", e.toString()); e.printStackTrace(); } } catch (Exception ex) { logger.debug("Error executing command"); } } }); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setVisible(true); //outputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.exppdf")); } }); } else { logger.debug("CSV export requested"); final String[] outcsv = new String[1]; Executor executor = Executors.newSingleThreadExecutor(); String finalCreatedExportFiles = createdExportFiles; int finalCounter = counter; String finalFilepath = filepath; executor.execute(new Runnable() { @Override public void run() { try { try { String result = CommandRunner.runCommand(params); progressBar.setVisible(false); logger.trace("\n\n\nresult {}", result); if (!(ExpImgFoldertextField.isBlank())) { // folder takes precedence over preview files // do something if (isWindows) { writer[0] = new BufferedWriter(new FileWriter(ExpImgFoldertextField.replace("\\", "/") + File.separator + "out.csv")); outcsv[0] = ExpImgFoldertextField.replace("\\", "/") + File.separator + "out.csv"; } else { writer[0] = new BufferedWriter(new FileWriter(ExpImgFoldertextField + File.separator + "out.csv")); outcsv[0] = ExpImgFoldertextField + File.separator + "out.csv"; } writer[0].write(result); writer[0].close(); } else { if (isWindows) { writer[0] = new BufferedWriter(new FileWriter(finalFilepath.replace("\\", "/") + File.separator + "out.csv")); outcsv[0] = finalFilepath.replace("\\", "/") + File.separator + "out.csv"; } else { writer[0] = new BufferedWriter(new FileWriter(finalFilepath + File.separator + "out.csv")); outcsv[0] = finalFilepath + File.separator + "out.csv"; } writer[0].write(result); writer[0].close(); } JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 400, (ResourceBundle.getBundle("translations/program_strings").getString("emd.expfiles") + ":<br><br>" + outcsv[0]), ResourceBundle.getBundle("translations/program_strings").getString("emd.expfiles"), JOptionPane.INFORMATION_MESSAGE)); } catch (InterruptedException | IOException e) { e.printStackTrace(); logger.error("metadata export failed with error {}", e); } } catch (Exception ex) { logger.debug("Error executing command"); } } }); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setVisible(true); //outputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.exppdf")); } }); } } } else { JOptionPane.showMessageDialog(rootPanel, ResourceBundle.getBundle("translations/program_strings").getString("emd.dlgnoexporttext"), ResourceBundle.getBundle("translations/program_strings").getString("emd.dlgnoexporttitle"), JOptionPane.WARNING_MESSAGE); } } /** * This method is indirectly called from the "Compare images" screen. That screens opens a popup request the format to export to * @param allMetadata * @param ciwRootPanel * @param output ==> onecsvperimage or onecombinedcsv */ public static void WriteCSVFromImgComp(List<String[]> allMetadata, JPanel ciwRootPanel, String output) { List<String[]> imageMetadata = new ArrayList<String[]>(); File[] files = MyVariables.getLoadedFiles(); int[] selectedIndices = MyVariables.getSelectedFilenamesIndices(); File tmpfile; String filename; String csvnamepath = ""; String csvdata = ""; String producedDocs = ""; if ("onecsvperimage".equals(output)) { for (int index : selectedIndices) { String[] csv; filename = files[index].getName(); csvdata = ""; tmpfile = files[index]; csvnamepath = tmpfile.getParent() + File.separator + Utils.getFileNameWithoutExtension(filename) + ".csv"; File csvfile = new File(csvnamepath); logger.debug("csvnamepath {}", csvnamepath); // Get the data belonging to this file (index) for (String[] row : allMetadata) { if (Integer.valueOf(row[1]) == index) { csvdata = csvdata + "\"" + row[2] + "\",\"" + row[3] + "\",\"" + row[4] + "\"\r\n"; //logger.trace("index {} rowdata {}", index, Arrays.toString(row)); } } try { //FileWriter fw = new FileWriter(csvfile, Charset.forName("UTF8")); FileWriter fw = new FileWriter(csvnamepath); fw.write(csvdata); fw.close(); producedDocs += csvnamepath + "<br>"; } catch (IOException e) { logger.error("error writing csv {}", e); e.printStackTrace(); } } // use the setpdfDocs variable for it. No use to create another variable MyVariables.setpdfDocs(producedDocs); logger.debug("produced csv Docs {}", producedDocs); } else { //onecombinedcsv producedDocs = ""; List<String> csvrows = new ArrayList<String>(); filename = files[0].getName(); tmpfile = files[0]; csvnamepath = tmpfile.getParent() + File.separator + "Output.csv"; csvdata = "\"Category name\",\"Tag name\""; for (int index : selectedIndices) { tmpfile = files[index]; filename = files[index].getName(); csvdata = csvdata + ",\"" + filename + "\""; } csvrows.add(csvdata); // The allMetadata is in this case tableMetadata for (String[] row : allMetadata) { int columns = row.length; csvdata= "\"" + row[0] + "\""; for (int i = 1; i < columns; i++) { csvdata = csvdata + ",\"" + row[i] + "\""; } //csvdata = csvdata; csvrows.add(csvdata); } // Sort the arraylist Collections.sort(csvrows); csvdata = ""; for (String row : csvrows) { csvdata = csvdata + row + "\n"; } try { FileWriter fw = new FileWriter(csvnamepath); fw.write(csvdata); fw.close(); producedDocs += csvnamepath + "<br>"; } catch (IOException e) { logger.error("error writing csv {}", e); e.printStackTrace(); } MyVariables.setpdfDocs(producedDocs); } } /////////////////////// Below the Sidecar exports public static void SidecarChoices(JRadioButton[] SCradiobuttons, JPanel rootPanel, JProgressBar progressBar, JLabel OutputLabel, String ExpImgFoldertextField, boolean includeSubFolders) { logger.debug("include subfolders {}", includeSubFolders); if (SCradiobuttons[0].isSelected()) { OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.exifsidecar")); exportExifMieExvSidecar(rootPanel, progressBar, "exif", ExpImgFoldertextField, includeSubFolders); OutputLabel.setText(""); } else if (SCradiobuttons[1].isSelected()) { OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.xmpsidecar")); exportXMPSidecar(rootPanel, progressBar, ExpImgFoldertextField, includeSubFolders); OutputLabel.setText(""); } else if (SCradiobuttons[2].isSelected()) { OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.miesidecar")); exportExifMieExvSidecar(rootPanel, progressBar, "mie", ExpImgFoldertextField, includeSubFolders); OutputLabel.setText(""); } else { OutputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.exvsidecar")); exportExifMieExvSidecar(rootPanel, progressBar, "exv", ExpImgFoldertextField, includeSubFolders); OutputLabel.setText(""); } } public static void exportExifMieExvSidecar(JPanel rootpanel, JProgressBar progressBar, String exportoption, String ExpImgFoldertextField, boolean includeSubFolders) { String commandstring = ""; String pathwithoutextension = ""; List<String> cmdparams = new ArrayList<String>(); int[] selectedIndices = null; File[] files = null; String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("dlg.continue"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.cancel")}; if (ExpImgFoldertextField.isBlank()) { // foldertexfield empty; otherwise folder takes precedence over preview files selectedIndices = MyVariables.getSelectedFilenamesIndices(); files = MyVariables.getLoadedFiles(); } int choice = 999; String logstring = ""; String export_extension = exportoption.toLowerCase().trim(); switch (exportoption.toLowerCase()) { case "mie": logger.info("Create MIE sidecar"); logstring = "export mie sidecar cmdparams: {}"; choice = JOptionPane.showOptionDialog(rootpanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_strings").getString("esc.mietext")), ResourceBundle.getBundle("translations/program_strings").getString("esc.mietitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); break; case "exv": logger.info("Create EXV sidecar"); logstring = "export exv sidecar cmdparams: {}"; choice = JOptionPane.showOptionDialog(rootpanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_strings").getString("esc.exvtext")), ResourceBundle.getBundle("translations/program_strings").getString("esc.exvtitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); break; case "exif": logger.info("Create EXIF sidecar"); logstring = "export exif sidecar cmdparams: {}"; choice = JOptionPane.showOptionDialog(rootpanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_strings").getString("esc.exiftext")), ResourceBundle.getBundle("translations/program_strings").getString("esc.exiftitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); break; } if ((choice == 0)) { // choice 0: exiftool -tagsfromfile a.jpg -all:all -icc_profile a.mie // exiftool -tagsfromfile a.jpg -all:all -icc_profile a.exv // exiftool -tagsfromfile a.jpg -all:all -icc_profile a.exif // choice 1: Cancel boolean isWindows = Utils.isOsFromMicrosoft(); if (ExpImgFoldertextField.isBlank()) { // folder takes precedence over preview files // exiftool -o %d%f.exif -all -unsafe DIR ; exiftool -o %d%f.exif -all -unsafe -r DIR cmdparams = new ArrayList<String>(); cmdparams.add(Utils.platformExiftool()); cmdparams.add("-o"); cmdparams.add("%d%f." + exportoption.toLowerCase()); cmdparams.add("-all:all"); if ("exif".equals(exportoption.toLowerCase())) { cmdparams.add("-unsafe"); } if (includeSubFolders) { cmdparams.add("-r"); } if (isWindows) { cmdparams.add(ExpImgFoldertextField.replace("\\", "/")); } else { cmdparams.add(ExpImgFoldertextField.replaceAll(" ", "\\ ")); } // export metadata logger.info(logstring, cmdparams); CommandRunner.runCommandWithProgressBar(cmdparams, progressBar, "off"); JOptionPane.showMessageDialog(rootpanel, ResourceBundle.getBundle("translations/program_strings").getString("esc.fintext"), ResourceBundle.getBundle("translations/program_strings").getString("esc.fintitle"), JOptionPane.INFORMATION_MESSAGE); } else { // Work on the selected previews for (int index : selectedIndices) { cmdparams = new ArrayList<String>(); ; // initialize on every file cmdparams.add(Utils.platformExiftool()); cmdparams.add("-tagsfromfile"); if (isWindows) { pathwithoutextension = Utils.getFilePathWithoutExtension(files[index].getPath().replace("\\", "/")); cmdparams.add(files[index].getPath().replace("\\", "/")); cmdparams.add("-all:all"); if (!"exif".equals(export_extension)) { cmdparams.add("-icc_profile"); } cmdparams.add(pathwithoutextension + "." + export_extension); } else { pathwithoutextension = Utils.getFilePathWithoutExtension(files[index].getPath()); cmdparams.add(files[index].getPath()); commandstring += files[index].getPath().replaceAll(" ", "\\ "); cmdparams.add("-all:all"); if (!"exif".equals(export_extension)) { cmdparams.add("-icc_profile"); } cmdparams.add((pathwithoutextension + "." + export_extension)); } // export metadata logger.info(logstring, cmdparams); CommandRunner.runCommandWithProgressBar(cmdparams, progressBar, "off"); } JOptionPane.showMessageDialog(rootpanel, ResourceBundle.getBundle("translations/program_strings").getString("esc.fintext"), ResourceBundle.getBundle("translations/program_strings").getString("esc.fintitle"), JOptionPane.INFORMATION_MESSAGE); } } } public static void exportXMPSidecar(JPanel rootpanel, JProgressBar progressBar, String ExpImgFoldertextField, boolean includeSubFolders) { String commandstring = ""; String pathwithoutextension = ""; List<String> cmdparams = new ArrayList<String>(); String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("esc.all"), ResourceBundle.getBundle("translations/program_strings").getString("esc.xmp"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.cancel")}; //String[] options = {ResourceBundle.getBundle("translations/program_strings").getString("esc.all"), ResourceBundle.getBundle("translations/program_strings").getString("dlg.cancel")}; int[] selectedIndices = null; File[] files = null; if (ExpImgFoldertextField.isBlank()) { // folder takes precedence over preview files selectedIndices = MyVariables.getSelectedFilenamesIndices(); files = MyVariables.getLoadedFiles(); } logger.info("Create xmp sidecar"); int choice = JOptionPane.showOptionDialog(rootpanel, String.format(ProgramTexts.HTML, 450, ResourceBundle.getBundle("translations/program_strings").getString("esc.xmptext")), ResourceBundle.getBundle("translations/program_strings").getString("esc.xmptitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (!(choice == 2)) { // choice 0: exiftool -tagsfromfile SRC.EXT DST.xmp // choice 1: exiftool -tagsfromfile SRC.EXT -xmp DST.xmp // choice 2: Cancel boolean isWindows = Utils.isOsFromMicrosoft(); if (!(ExpImgFoldertextField.isBlank())) { // folder takes precedence over preview files cmdparams = new ArrayList<String>(); cmdparams.add(Utils.platformExiftool()); cmdparams.add("-o"); cmdparams.add("%d%f.xmp"); if (choice == 0) { cmdparams.add("-all:all"); } else { cmdparams.add("-xmp:all"); } if (includeSubFolders) { cmdparams.add("-r"); } if (isWindows) { cmdparams.add(ExpImgFoldertextField.replace("\\", "/")); } else { cmdparams.add(ExpImgFoldertextField.replaceAll(" ", "\\ ")); } // export metadata logger.info("exportxmpsidecar cmdparams {}", cmdparams); CommandRunner.runCommandWithProgressBar(cmdparams, progressBar, "off"); JOptionPane.showMessageDialog(rootpanel, ResourceBundle.getBundle("translations/program_strings").getString("esc.fintext"), ResourceBundle.getBundle("translations/program_strings").getString("esc.fintitle"), JOptionPane.INFORMATION_MESSAGE); } else { for (int index : selectedIndices) { commandstring = ""; cmdparams = new ArrayList<String>(); ; // initialize on every file cmdparams.add(Utils.platformExiftool()); commandstring += Utils.platformExiftool(); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } cmdparams.add("-tagsfromfile"); commandstring += " -tagsfromfile "; if (isWindows) { pathwithoutextension = Utils.getFilePathWithoutExtension(files[index].getPath().replace("\\", "/")); cmdparams.add(files[index].getPath().replace("\\", "/")); commandstring += files[index].getPath().replace("\\", "/"); if (choice == 1) { cmdparams.add("-xmp"); commandstring += " -xmp "; } cmdparams.add(pathwithoutextension + ".xmp"); commandstring += pathwithoutextension + ".xmp"; } else { pathwithoutextension = Utils.getFilePathWithoutExtension(files[index].getPath()); cmdparams.add(files[index].getPath()); commandstring += files[index].getPath().replaceAll(" ", "\\ "); if (choice == 1) { cmdparams.add("-xmp"); commandstring += " -xmp "; } cmdparams.add(pathwithoutextension + ".xmp"); commandstring += (pathwithoutextension + ".xmp").replaceAll(" ", "\\ "); } // export metadata logger.info("exportxmpsidecar cmdparams: {}", cmdparams); CommandRunner.runCommandWithProgressBar(cmdparams, progressBar, "off"); JOptionPane.showMessageDialog(rootpanel, ResourceBundle.getBundle("translations/program_strings").getString("esc.fintext"), ResourceBundle.getBundle("translations/program_strings").getString("esc.fintitle"), JOptionPane.INFORMATION_MESSAGE); } } } } }
37,144
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
EditGeotaggingdata.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/editpane/EditGeotaggingdata.java
package org.hvdw.jexiftoolgui.editpane; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.controllers.StandardFileIO; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.PreferencesFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import java.io.File; import java.util.ArrayList; import java.util.List; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.*; public class EditGeotaggingdata { private String ImageFolder; private IPreferencesFacade prefs = PreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(EditGeotaggingdata.class); public String gpsLogFile(JPanel myComponent) { String startFolder = StandardFileIO.getFolderPathToOpenBasedOnPreferences(); final JFileChooser chooser = new JFileChooser(startFolder); chooser.setMultiSelectionEnabled(false); String[] filexts = {"gpx", "gps", "log"}; FileFilter filter = new FileNameExtensionFilter("(*.gpx)", filexts); chooser.setFileFilter(filter); chooser.setDialogTitle("Locate GPS log file ..."); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int status = chooser.showOpenDialog(myComponent); if (status == JFileChooser.APPROVE_OPTION) { String selectedLogFile = chooser.getSelectedFile().getPath(); return selectedLogFile; } else { return ""; } } public void writeInfo(boolean images_selected, JTextField[] geotaggingFields, JCheckBox[] geotaggingBoxes, boolean OverwiteOriginals, JProgressBar progressBar) { int[] selectedFilenamesIndices = null; File[] files = null; if (images_selected) { selectedFilenamesIndices = MyVariables.getSelectedFilenamesIndices(); files = MyVariables.getLoadedFiles(); } String fpath = ""; List<String> cmdparams = new ArrayList<String>(); String onFolder = geotaggingFields[0].getText().trim(); String gpslogfile = geotaggingFields[1].getText().trim(); String geosync = geotaggingFields[2].getText().trim(); logger.info("onFolder: {} gpslogfile: {} geosync {}", onFolder, gpslogfile, geosync); boolean isWindows = Utils.isOsFromMicrosoft(); if (isWindows) { cmdparams.add(" " + Utils.platformExiftool() + " "); } else { cmdparams.add(Utils.platformExiftool()); } boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!OverwiteOriginals) { cmdparams.add("-overwrite_original"); } cmdparams.add("-geotag"); cmdparams.add(gpslogfile); if (!"".equals(geosync)) { cmdparams.add("-geosync=" + geosync); } // Check if also the location is to be added if (geotaggingBoxes[0].isSelected()) { cmdparams.add("-xmp:Location=" + geotaggingFields[3].getText().trim()); cmdparams.add("-iptc:Sub-location=" + geotaggingFields[3].getText().trim()); } if (geotaggingBoxes[1].isSelected()) { cmdparams.add("-xmp:Country=" + geotaggingFields[4].getText().trim()); cmdparams.add("-iptc:Country-PrimaryLocationName=" + geotaggingFields[4].getText().trim()); } if (geotaggingBoxes[2].isSelected()) { cmdparams.add("-xmp:State=" + geotaggingFields[5].getText().trim()); cmdparams.add("-iptc:Province-State=" + geotaggingFields[5].getText().trim()); } if (geotaggingBoxes[3].isSelected()) { cmdparams.add("-xmp:City=" + geotaggingFields[6].getText().trim()); cmdparams.add("-iptc:City=" + geotaggingFields[6].getText().trim()); } logger.info("onfolder {}", onFolder); if ("".equals(onFolder)) { // Empty folder string which means we use selected files for (int index : selectedFilenamesIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } } else { // We do have a non-empty folder string //cmdparams.addAll( Arrays.asList(params) ); if (isWindows) { cmdparams.add(onFolder.replace("\\", "/")); } else { cmdparams.add(onFolder.replace(" ", "\\ ")); } } logger.info("cmdparams {}", cmdparams.toString()); CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } public void ResetFields(JTextField[] geotaggingFields, JCheckBox[] geotaggingBoxes) { for (JTextField field: geotaggingFields) { field.setText(""); } for (JCheckBox checkBox: geotaggingBoxes) { checkBox.setSelected(false); } } }
5,680
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
EditXmpdata.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/editpane/EditXmpdata.java
package org.hvdw.jexiftoolgui.editpane; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; public class EditXmpdata { private IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(EditXmpdata.class); // I had specified for the arrays: //JTextField[] xmpFields = {xmpCreatortextField, xmpRightstextField,xmpLabeltextField, xmpSubjecttextField, xmpTitletextField, xmpPersontextField, xmpRegionNametextField, xmpRegionTypetextField}; // JTextArea[] xmpAreas = {xmpDescriptiontextArea}; // JCheckBox[] xmpBoxes = {xmpCreatorcheckBox, xmpRightscheckBox, xmpDescriptioncheckBox, xmpLabelcheckBox, xmpSubjectcheckBox, xmpTitlecheckBox, xmpPersoncheckBox}; public void resetFields(JTextField[] xmpFields, JTextArea Description) { for (JTextField field: xmpFields) { field.setText(""); } Description.setText(""); } public void copyXmpFromSelected(JTextField[] xmpFields, JTextArea Description) { File[] files = MyVariables.getLoadedFiles(); int SelectedRow = MyVariables.getSelectedRowOrIndex(); String[] xmpcopyparams = {"-e", "-n", "-xmp:Creator", "-xmp:Credit", "-xmp:Rights", "-xmp:Label", "-xmp-pdf:Keywords", "-xmp:Subject", "-xmp:Title", "-xmp:Description", "-xmp:Person", "-xmp:PersonInImage"}; String fpath = ""; String res = ""; List<String> cmdparams = new ArrayList<String>(); //First clean the fields resetFields(xmpFields, Description); if (Utils.isOsFromMicrosoft()) { fpath = files[SelectedRow].getPath().replace("\\", "/"); } else { fpath = files[SelectedRow].getPath(); } logger.info(fpath); cmdparams.add(Utils.platformExiftool()); cmdparams.addAll(Arrays.asList(xmpcopyparams)); cmdparams.add(fpath); try { res = CommandRunner.runCommand(cmdparams); logger.info("res is\n{}", res); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command"); } if (res.length() > 0) { displayCopiedInfo(xmpFields, Description, res); } } public void displayCopiedInfo(JTextField[] xmpFields, JTextArea Description, String exiftoolInfo) { String[] lines = exiftoolInfo.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); for (String line : lines) { String[] cells = line.split(":", 2); // Only split on first : as some tags also contain (multiple) : String SpaceStripped = cells[0].replaceAll("\\s+",""); // regex "\s" is space, extra \ to escape the first \ //With ALL spaces removed from the tag we als need to use identiefiers without spaces //xmpCreatortextField, xmpRightstextField,xmpLabeltextField, xmpSubjecttextField, xmpTitletextField, xmpPersontextField, xmpRegionNametextField, xmpRegionTypetextField if (SpaceStripped.contains("Creator")) { xmpFields[0].setText(cells[1].trim()); } if (SpaceStripped.contains("Credit")) { xmpFields[1].setText(cells[1].trim()); } if (SpaceStripped.contains("Rights")) { xmpFields[2].setText(cells[1].trim()); } if (SpaceStripped.contains("Label")) { xmpFields[3].setText(cells[1].trim()); } if (SpaceStripped.contains("Title")) { xmpFields[4].setText(cells[1].trim()); } if (SpaceStripped.contains("Keywords")) { xmpFields[5].setText(cells[1].trim()); } if (SpaceStripped.contains("Subject")) { xmpFields[6].setText(cells[1].trim()); } if (SpaceStripped.contains("PersonInImage")) { xmpFields[7].setText(cells[1].trim()); } /*if (SpaceStripped.contains("RegionName")) { xmpFields[7].setText(cells[1].trim()); } if (SpaceStripped.contains("RegionType")) { xmpFields[8].setText(cells[1].trim()); }*/ if (SpaceStripped.contains("Description")) { // Our text area Description.setText(cells[1].trim()); } } } public void writeXmpTags(JTextField[] xmpFields, JTextArea Description, JCheckBox[] xmpBoxes, JProgressBar progressBar) { List<String> cmdparams = new ArrayList<String>(); int selectedIndices[] = MyVariables.getSelectedFilenamesIndices(); File[] files = MyVariables.getLoadedFiles(); cmdparams.add(Utils.platformExiftool()); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!xmpBoxes[9].isSelected()) { // default overwrite originals, when set do not cmdparams.add("-overwrite_original"); } cmdparams.addAll(Utils.AlwaysAdd()); if (xmpBoxes[0].isSelected()) { cmdparams.add("-xmp:Creator=" + xmpFields[0].getText().trim()); } if (xmpBoxes[1].isSelected()) { cmdparams.add("-xmp:Credit=" + xmpFields[1].getText().trim()); } if (xmpBoxes[2].isSelected()) { cmdparams.add("-xmp:Rights=" + xmpFields[2].getText().trim()); } if (xmpBoxes[3].isSelected()) { cmdparams.add("-xmp:Label=" + xmpFields[3].getText().trim()); } if (xmpBoxes[4].isSelected()) { cmdparams.add("-xmp:Title=" + xmpFields[4].getText().trim()); } if (xmpBoxes[5].isSelected()) { cmdparams.add("-xmp-pdf:Keywords=" + xmpFields[5].getText().trim()); } if (xmpBoxes[6].isSelected()) { String[] subjects = xmpFields[6].getText().trim().split(","); for (String subject : subjects) { cmdparams.add("-xmp:Subject=" + subject.trim()); } //cmdparams.add("-xmp:Subject=" + xmpFields[4].getText().trim()); } /*if (xmpBoxes[5.isSelected()) { if self.xmp_rating1.isSelected()) { rating = 1 elif self.xmp_rating2.isSelected()) { rating = 2 elif self.xmp_rating3.isSelected()) { rating = 3 elif self.xmp_rating4.isSelected()) { rating = 4 else) { rating = 5 cmdparams.add("-xmp:Rating=" + rating); */ if (xmpBoxes[7].isSelected()) { //cmdparams.add("-xmp:Person=" + xmpFields[6].getText()); String[] persons = xmpFields[7].getText().trim().split(","); for (String person : persons) { cmdparams.add("-xmp:PersonInImage=" + person.trim()); } //cmdparams.add("-xmp:PersonInImage=" + xmpFields[6].getText().trim()); } /*if (xmpBoxes[7].isSelected()) { cmdparams.add("-xmp:RegionName=\"" + xmpFields[7].getText().trim() + "\""); } if (xmpBoxes[8].isSelected()) { cmdparams.add("-xmp:RegionType=\"" + xmpFields[8].getText().trim() + "\""); }*/ if (xmpBoxes[8].isSelected()) { cmdparams.add("-xmp:Description=" + Description.getText().trim()); } boolean isWindows = Utils.isOsFromMicrosoft(); for (int index: selectedIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } }
8,965
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
EditGpanodata.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/editpane/EditGpanodata.java
package org.hvdw.jexiftoolgui.editpane; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.text.DefaultFormatterFactory; import javax.swing.text.NumberFormatter; import java.io.File; import java.io.IOException; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; public class EditGpanodata { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(EditGpanodata.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; public void setFormattedFieldFormats(JFormattedTextField[] theFields) { Locale currentLocale = Locale.getDefault(); NumberFormat formatter = NumberFormat.getNumberInstance(currentLocale ); formatter.setMaximumFractionDigits(4); for (JFormattedTextField field : theFields) { field.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(formatter))); } } public void resetFields(JFormattedTextField[] gpanoFields, JTextField gpanoStitchingSoftwaretextField, JCheckBox[] gpanoBoxes) { for (JFormattedTextField field: gpanoFields) { field.setText(""); } for (JCheckBox checkbox: gpanoBoxes) { checkbox.setSelected(false); } gpanoStitchingSoftwaretextField.setText(""); } public boolean checkFieldsOnNotBeingEmpty(JFormattedTextField[] gpanoFields, JComboBox gpanoPTcomboBox) { boolean complete = true; // Only first 6 are mandatory so we now use a for loop for (int index = 0; index < 6; index++) { if (gpanoFields[index].getText().trim().isEmpty()) { complete = false; } } return complete; } public void copyGpanoFromSelected(JFormattedTextField[] gpanoFields, JTextField gpanoStitchingSoftwaretextField, JComboBox gpanoPTCombobox, JCheckBox[] gpanoBoxes) { File[] files = MyVariables.getLoadedFiles(); int SelectedRow = MyVariables.getSelectedRowOrIndex(); String[] gpano_params = {"-xmp:StitchingSoftware","-xmp:CroppedAreaImageHeightPixels","-xmp:CroppedAreaImageWidthPixels","-xmp:CroppedAreaLeftPixels","-xmp:CroppedAreaTopPixels","-xmp:FullPanoHeightPixels","-xmp:FullPanoWidthPixels","-xmp:ProjectionType","-xmp:UsePanoramaViewer","-xmp:PoseHeadingDegrees","-xmp:InitialViewHeadingDegrees","-xmp:InitialViewPitchDegrees","-xmp:InitialViewRollDegrees","-xmp:InitialHorizontalFOVDegrees"}; String fpath =""; String res = ""; List<String> cmdparams = new ArrayList<String>(); //First clean the fields resetFields(gpanoFields, gpanoStitchingSoftwaretextField, gpanoBoxes); if (Utils.isOsFromMicrosoft()) { fpath = files[SelectedRow].getPath().replace("\\", "/"); } else { fpath = files[SelectedRow].getPath(); } cmdparams.add(Utils.platformExiftool()); cmdparams.add("-e"); cmdparams.add("-n"); cmdparams.addAll( Arrays.asList(gpano_params)); cmdparams.add(fpath); try { res = CommandRunner.runCommand(cmdparams); logger.info("res is\n{}", res); } catch(IOException | InterruptedException ex) { logger.debug("Error executing command"); } if (res.length() > 0) { displayCopiedInfo(gpanoFields, gpanoStitchingSoftwaretextField, gpanoPTCombobox, res); } } private void displayCopiedInfo(JFormattedTextField[] gpanoFields, JTextField gpanoStitchingSoftwaretextField, JComboBox gpanoPTCombobox, String exiftoolInfo) { String[] lines = exiftoolInfo.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); //for(int i = 0; i < lines.length; i++) { for (String line : lines) { String[] cells = line.split(":", 2); // Only split on first : as some tags also contain (multiple) : String SpaceStripped = cells[0].replaceAll("\\s+",""); // regex "\s" is space, extra \ to escape the first \ //Wit ALL spaces removed from the tag we als need to use identiefiers without spaces logger.info(SpaceStripped, " ; value: ", cells[1], "\n"); if (SpaceStripped.contains("CroppedAreaImageHeightPixels")) { gpanoFields[0].setText(cells[1].trim()); } if (SpaceStripped.contains("CroppedAreaImageWidthPixels")) { gpanoFields[1].setText(cells[1].trim()); } if (SpaceStripped.contains("CroppedAreaLeftPixels")) { gpanoFields[2].setText(cells[1].trim()); } if (SpaceStripped.contains("CroppedAreaTopPixels")) { gpanoFields[3].setText(cells[1].trim()); } if (SpaceStripped.contains("FullPanoHeightPixels")) { gpanoFields[4].setText(cells[1].trim()); } if (SpaceStripped.contains("FullPanoWidthPixels")) { gpanoFields[5].setText(cells[1].trim()); } if (SpaceStripped.contains("ProjectionType")) { gpanoPTCombobox.setSelectedItem(cells[1].trim()); logger.info("projection type", cells[1].trim()); //gpanoFields[6].setText(cells[1]); } if (SpaceStripped.contains("PoseHeadingDegrees")) { gpanoFields[6].setText(cells[1].trim()); } if (SpaceStripped.contains("StitchingSoftware")) { gpanoStitchingSoftwaretextField.setText(cells[1].trim()); } if (SpaceStripped.contains("InitialViewHeadingDegrees")) { gpanoFields[7].setText(cells[1].trim()); } if (SpaceStripped.contains("InitialViewPitchDegrees")) { gpanoFields[8].setText(cells[1].trim()); } if (SpaceStripped.contains("InitialViewRollDegrees")) { gpanoFields[9].setText(cells[1].trim()); } if (SpaceStripped.contains("InitialHorizontalFOVDegrees")) { gpanoFields[10].setText(cells[1].trim()); } } } public void writeGpanoTags(JFormattedTextField[] gpanoFields, JCheckBox[] gpanoBoxes, JTextField gpanoStitchingSoftwaretextField, JComboBox gpanoPTcomboBox, JProgressBar progressBar) { List<String> cmdparams = new ArrayList<String>(); File[] files = MyVariables.getLoadedFiles(); int selectedIndices[] = MyVariables.getSelectedFilenamesIndices(); cmdparams.add(Utils.platformExiftool()); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!gpanoBoxes[6].isSelected()) { // default overwrite originals, when set do not cmdparams.add("-overwrite_original"); } cmdparams.addAll(Utils.AlwaysAdd()); // These are manadatory anyway and do not need a checkbox. They need to be controlled first if they are not empty cmdparams.add("-xmp:CroppedAreaImageHeightPixels=" + gpanoFields[0].getText().trim()); cmdparams.add("-xmp:CroppedAreaImageWidthPixels=" + gpanoFields[1].getText().trim()); cmdparams.add("-xmp:CroppedAreaLeftPixels=" + gpanoFields[2].getText().trim()); cmdparams.add("-xmp:CroppedAreaTopPixels=" + gpanoFields[3].getText().trim()); cmdparams.add("-xmp:FullPanoHeightPixels=" + gpanoFields[4].getText().trim()); cmdparams.add("-xmp:FullPanoWidthPixels=" + gpanoFields[5].getText().trim()); // Get combobox value cmdparams.add("-xmp:ProjectionType=" + gpanoPTcomboBox.getSelectedItem()); cmdparams.add("-xmp:UsePanoramaViewer=1"); if (gpanoBoxes[0].isSelected()) { cmdparams.add("-xmp:PoseHeadingDegrees=" + gpanoFields[6].getText().trim()); } if (gpanoBoxes[1].isSelected()) { cmdparams.add("-xmp:StitchingSoftware=" + gpanoStitchingSoftwaretextField.getText().trim()); } if (gpanoBoxes[2].isSelected()) { cmdparams.add("-xmp:InitialViewHeadingDegrees=" + gpanoFields[7].getText().trim()); } if (gpanoBoxes[3].isSelected()) { cmdparams.add("-xmp:InitialViewPitchDegrees=" + gpanoFields[8].getText().trim()); } if (gpanoBoxes[4].isSelected()) { cmdparams.add("-xmp:InitialViewRollDegrees=" + gpanoFields[9].getText().trim()); } if (gpanoBoxes[5].isSelected()) { cmdparams.add("-xmp:InitialHorizontalFOVDegrees=" + gpanoFields[10].getText().trim()); } for (int index: selectedIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (Utils.isOsFromMicrosoft()) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } }
9,672
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
EditLensdata.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/editpane/EditLensdata.java
package org.hvdw.jexiftoolgui.editpane; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.controllers.StandardFileIO; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.hvdw.jexiftoolgui.view.CreateUpdatemyLens; import org.hvdw.jexiftoolgui.view.SelectmyLens; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.*; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; public class EditLensdata { private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(EditLensdata.class); private SelectmyLens SmL = new SelectmyLens(); private CreateUpdatemyLens CUL = new CreateUpdatemyLens(); public void resetFields(JTextField[] lensFields, JCheckBox[] lensBoxes, JComboBox meteringmodecomboBox) { for (JTextField field: lensFields) { field.setText(""); } for (JCheckBox checkbox: lensBoxes) { checkbox.setSelected(true); } meteringmodecomboBox.setSelectedItem("Unknown"); } public void copyLensDataFromSelected(JTextField[] lensFields, JComboBox meteringmodecomboBox, JCheckBox[] lensBoxes) { String[] lenscopyparams = {"-exif:lensmake","-exif:lensmodel","-exif:lensserialnumber","-makernotes:lensserialnumber","-exif:focallength","-exif:focallengthin35mmformat","-exif:fnumber","-exif:maxaperturevalue","-exif:meteringmode","-makernotes:focusdistance","-composite:lensid","-composite:lens","-makernotes:focusdistance","-makernotes:conversionlens","-makernotes:lenstype","-makernotes:lensfirmwareversion"}; File[] files = MyVariables.getLoadedFiles(); int SelectedRow = MyVariables.getSelectedRowOrIndex(); String fpath = ""; String res = ""; List<String> cmdparams = new ArrayList<String>(); //First clean the fields resetFields(lensFields, lensBoxes, meteringmodecomboBox); if (Utils.isOsFromMicrosoft()) { fpath = files[SelectedRow].getPath().replace("\\", "/"); } else { fpath = files[SelectedRow].getPath(); } logger.info(fpath); cmdparams.add(Utils.platformExiftool()); cmdparams.addAll(Arrays.asList(lenscopyparams)); cmdparams.add(fpath); try { res = CommandRunner.runCommand(cmdparams); logger.info("res is\n{}", res); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command"); } if (res.length() > 0) { displayCopiedInfo(lensFields, lensBoxes, meteringmodecomboBox, res); } } public void displayCopiedInfo(JTextField[] lensFields, JCheckBox[] lensBoxes, JComboBox meteringmodecomboBox, String exiftoolInfo) { String[] lines = exiftoolInfo.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); for (String line : lines) { String[] cells = line.split(":", 2); // Only split on first : as some tags also contain (multiple) : String SpaceStripped = cells[0].replaceAll("\\s+",""); // regex "\s" is space, extra \ to escape the first \ //With ALL spaces removed from the tag we als need to use identifiers without spaces //logger.info("SpaceStripped: " + SpaceStripped); if (SpaceStripped.contains("Make")) { lensFields[0].setText(cells[1].trim()); } if (SpaceStripped.contains("Model")) { lensFields[1].setText(cells[1].trim()); } if (SpaceStripped.toLowerCase().contains("serialnumber")) { lensFields[2].setText(cells[1].trim()); } if ("FocalLength".equals(SpaceStripped)) { lensFields[3].setText(cells[1].replace(" mm","").trim()); } if (SpaceStripped.toLowerCase().contains("focallengthin35mmformat")) { // FocalLengthIn35mmFormat lensFields[4].setText(cells[1].replace(" mm","").trim()); } if (SpaceStripped.contains("FNumber")) { lensFields[5].setText(cells[1].trim()); } if (SpaceStripped.contains("MaxApertureValue")) { lensFields[6].setText(cells[1].trim()); } if (SpaceStripped.contains("FocusDistance")) { lensFields[7].setText(cells[1].trim()); } if (SpaceStripped.toLowerCase().contains("id")) { lensFields[8].setText(cells[1].trim()); } if (SpaceStripped.contains("ConversionLens")) { lensFields[9].setText(cells[1].trim()); } if (SpaceStripped.contains("LensType")) { lensFields[10].setText(cells[1].trim()); } if (SpaceStripped.contains("LensFirmwareVersion")) { lensFields[11].setText(cells[1].trim()); } if (SpaceStripped.contains("MeteringMode")) { // simple set of if statements. somehow the direct cells[1] option does not work if (cells[1].toLowerCase().contains("unknown")) { meteringmodecomboBox.setSelectedItem("Unknown"); } if (cells[1].toLowerCase().equals("average")) { meteringmodecomboBox.setSelectedItem("Average"); } if (cells[1].toLowerCase().equals("Spot")) { meteringmodecomboBox.setSelectedItem("Spot"); } if (cells[1].toLowerCase().contains("multi-spot")) { meteringmodecomboBox.setSelectedItem("Multi-spot"); } if (cells[1].toLowerCase().contains("weighted")) { meteringmodecomboBox.setSelectedItem("Center-weighted average"); } if (cells[1].toLowerCase().contains("segment")) { meteringmodecomboBox.setSelectedItem("Multi-segment"); } if (cells[1].toLowerCase().contains("partial")) { meteringmodecomboBox.setSelectedItem("Partial"); } if (cells[1].toLowerCase().contains("other")) { meteringmodecomboBox.setSelectedItem("Other"); } //meteringmodecomboBox.setSelectedItem(cells[1].trim()); //logger.info("metering mode (SpaceStripped, cells[1].trim()) " + SpaceStripped + " " + cells[1].trim()); } } } public void writeLensTags(JTextField[] lensFields, JCheckBox[] lensBoxes, JComboBox meteringmodecomboBox, JProgressBar progressBar) { List<String> cmdparams = new ArrayList<String>(); int selectedIndices[] = MyVariables.getSelectedFilenamesIndices(); File[] files = MyVariables.getLoadedFiles(); cmdparams.add(Utils.platformExiftool()); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!lensBoxes[13].isSelected()) { // default overwrite originals, when set do not cmdparams.add("-overwrite_original"); } cmdparams.addAll(Utils.AlwaysAdd()); if (lensBoxes[0].isSelected()) { cmdparams.add("-exif:lensmake=" + lensFields[0].getText().trim()); } if (lensBoxes[1].isSelected()) { cmdparams.add("-exif:lensmodel=" + lensFields[1].getText().trim()); } if (lensBoxes[2].isSelected()) { cmdparams.add("-exif:lensserialnumber=" + lensFields[2].getText().trim()); cmdparams.add("-makernotes:lensserialnumber=" + lensFields[2].getText().trim()); } if (lensBoxes[3].isSelected()) { cmdparams.add("-exif:focallength=" + lensFields[3].getText().trim()); } if (lensBoxes[4].isSelected()) { cmdparams.add("-exif:focallengthIn35mmformat=" + lensFields[4].getText().trim()); } if (lensBoxes[5].isSelected()) { cmdparams.add("-exif:fnumber=" + lensFields[5].getText().trim()); } if (lensBoxes[6].isSelected()) { cmdparams.add("-exif:maxaperturevalue=" + lensFields[6].getText()); } if (lensBoxes[7].isSelected()) { cmdparams.add("-makernotes:focusdistance=" + lensFields[7].getText().trim()); } if (lensBoxes[8].isSelected()) { cmdparams.add("-composite:lensid=" + lensFields[8].getText().trim()); } if (lensBoxes[9].isSelected()) { cmdparams.add("-makernotes:conversionlens=" + lensFields[9].getText().trim()); } if (lensBoxes[10].isSelected()) { cmdparams.add("-makernotes:lenstype=" + lensFields[10].getText().trim()); } if (lensBoxes[11].isSelected()) { cmdparams.add("-makernotes:lensfirmwareversion=" + lensFields[11].getText().trim()); } if (lensBoxes[12].isSelected()) { cmdparams.add("-exif:meteringmode=" + meteringmodecomboBox.getSelectedItem()); } boolean isWindows = Utils.isOsFromMicrosoft(); for (int index: selectedIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } // Only add a value to the hashmap if the value really contains a value HashMap<String, String> CheckValue(HashMap<String, String> tmplens, String lens_key, String checkValue) { if ( !(checkValue == null) && !("".equals(checkValue)) ) { tmplens.put(lens_key, checkValue); } return tmplens; } public void saveLensconfig(JTextField[] LensFields, JComboBox meteringmodecomboBox, JPanel rootpanel) { // lensfields lensmaketextField, lensmodeltextField, lensserialnumbertextField, focallengthtextField, focallengthIn35mmformattextField, fnumbertextField (5), // maxaperturevaluetextField, focusdistancetextField, lensidtextField (8), conversionlenstextField, lenstypetextField, lensfirmwareversiontextField String writeresult = ""; HashMap<String, String> lens = new HashMap<String, String>(); String str_lens_file = ""; // Check if (!(setName == null) && !("".equals(setName))) { String[] chosenValues = CUL.showDialog(rootpanel); // Put all our values into a HashMap, but check if we really have a vlaue //lens.put("lens_name", chosenValues[0]); lens = CheckValue(lens, "lens_name", chosenValues[0]); lens = CheckValue(lens, "lens_description", chosenValues[1]); lens = CheckValue(lens, "exif_lensmake", LensFields[0].getText()); lens = CheckValue(lens, "exif_lensmodel", LensFields[1].getText()); lens = CheckValue(lens, "exif_lensserialnumber", LensFields[2].getText()); lens = CheckValue(lens, "exif_focallength", LensFields[3].getText()); lens = CheckValue(lens, "exif_focallengthIn35mmformat", LensFields[4].getText()); lens = CheckValue(lens, "exif_fnumber", LensFields[5].getText()); lens = CheckValue(lens, "exif_maxaperturevalue", LensFields[6].getText()); lens = CheckValue(lens, "makernotes_focusdistance", LensFields[7].getText()); lens = CheckValue(lens, "composite_lensid", LensFields[8].getText()); lens = CheckValue(lens, "makernotes_conversionlens", LensFields[9].getText()); lens = CheckValue(lens, "makernotes_lenstype", LensFields[10].getText()); lens = CheckValue(lens, "makernotes_lensfirmwareversion", LensFields[11].getText()); lens.put("exif_meteringmode", (String) meteringmodecomboBox.getSelectedItem()); logger.debug("chosen name/description: " + chosenValues[0] + " + " + chosenValues[1]); if (!"".equals(chosenValues[0])) { // So the user provided a name and not an empty string // Check if already exists if (chosenValues[0].contains(".hashmap")) { str_lens_file = MyVariables.getlensFolder() + File.separator + chosenValues[0]; } else { str_lens_file = MyVariables.getlensFolder() + File.separator + chosenValues[0] + ".hashmap"; } logger.info("str_lens_file {}", str_lens_file); File lens_file = new File(str_lens_file); if (lens_file.exists()) { // so we have a existing lens file but do we want to overwite it? int result = JOptionPane.showConfirmDialog(rootpanel, String.format(ProgramTexts.HTML, 400, ResourceBundle.getBundle("translations/program_strings").getString("addlens.overwrite") + " " + chosenValues[0] + "?"), ResourceBundle.getBundle("translations/program_strings").getString("addlens.overwriteshort"), JOptionPane.OK_CANCEL_OPTION); if (result == 0) { //OK // user wants us to overwrite logger.info("user wants to overwrite the lens file with name: " + chosenValues[0]); writeresult = StandardFileIO.writeHashMapToFile(lens_file, lens); if ("Error saving".contains(writeresult)) { //means we have an error saving the hashmap file JOptionPane.showMessageDialog(rootpanel, String.format(ProgramTexts.HTML, 400, ResourceBundle.getBundle("translations/program_strings").getString("addlens.updateerror") + chosenValues[0]) , ResourceBundle.getBundle("translations/program_strings").getString("addlens.updateerrorshort"), JOptionPane.ERROR_MESSAGE); } else { //success JOptionPane.showMessageDialog(rootpanel, String.format(ProgramTexts.HTML, 400, ResourceBundle.getBundle("translations/program_strings").getString("addlens.saved") + " " + chosenValues[0]), ResourceBundle.getBundle("translations/program_strings").getString("addlens.savedshort"), JOptionPane.INFORMATION_MESSAGE); } } // result 2 means cancel; do nothing } else {// lens file does not exist yet, so we can simply write it out. logger.info("save new lens file named: " + chosenValues[0]); writeresult = StandardFileIO.writeHashMapToFile(lens_file, lens); if ("Error saving".contains(writeresult)) { //means we have an error JOptionPane.showMessageDialog(rootpanel, String.format(ProgramTexts.HTML, 400, ResourceBundle.getBundle("translations/program_strings").getString("addlens.inserterror") + " " + chosenValues[0]), ResourceBundle.getBundle("translations/program_strings").getString("addlens.inserterrorshort"), JOptionPane.ERROR_MESSAGE); } else { //success JOptionPane.showMessageDialog(rootpanel, String.format(ProgramTexts.HTML, 400, ResourceBundle.getBundle("translations/program_strings").getString("addlens.saved") + " " + chosenValues[0]), ResourceBundle.getBundle("translations/program_strings").getString("addlens.savedshort"), JOptionPane.INFORMATION_MESSAGE); } } } else { // user did not provide a lensname to insert/update JOptionPane.showMessageDialog(rootpanel, String.format(ProgramTexts.HTML, 400, ResourceBundle.getBundle("translations/program_strings").getString("addlens.noname")), ResourceBundle.getBundle("translations/program_strings").getString("addlens.nonameshort"), JOptionPane.ERROR_MESSAGE); } } public void loadLensconfig(JTextField[] lensFields, JComboBox meteringmodecomboBox, JPanel rootpanel) { String lensname = SmL.showDialog(rootpanel, "load lens"); logger.debug("returned selected lensname: " + lensname); String str_lens_file = MyVariables.getlensFolder() + File.separator + lensname; logger.info("str_lens_file {}", str_lens_file); File lens_file = new File(str_lens_file); if (lens_file.exists()) { // Is actually a must otherwise the user could not have selected it HashMap<String, String> lens; lens = StandardFileIO.readHashMapFromFile(lens_file); if (lens.size() > 0) { for (JTextField field: lensFields) { field.setText(""); } if (lens.containsKey("exif_lensmake")) { lensFields[0].setText(lens.get("exif_lensmake")); } if (lens.containsKey("exif_lensmodel")) { lensFields[1].setText(lens.get("exif_lensmodel")); } if (lens.containsKey("exif_lensserialnumber")) { lensFields[2].setText(lens.get("exif_lensserialnumber")); } if (lens.containsKey("exif_focallength")) { lensFields[3].setText(lens.get("exif_focallength")); } if (lens.containsKey("exif_focallengthIn35mmformat")) { lensFields[4].setText(lens.get("exif_focallengthIn35mmformat")); } if (lens.containsKey("exif_fnumber")) { lensFields[5].setText(lens.get("exif_fnumber")); } if (lens.containsKey("exif_maxaperturevalue")) { lensFields[6].setText(lens.get("exif_maxaperturevalue")); } if (lens.containsKey("makernotes_focusdistance")) { lensFields[7].setText(lens.get("makernotes_focusdistance")); } if (lens.containsKey("composite_lensid")) { lensFields[8].setText(lens.get("composite_lensid")); } if (lens.containsKey("makernotes_conversionlens")) { lensFields[9].setText(lens.get("makernotes_conversionlens")); } if (lens.containsKey("makernotes_lenstype")) { lensFields[10].setText(lens.get("makernotes_lenstype")); } if (lens.containsKey("makernotes_lensfirmwareversion")) { lensFields[11].setText(lens.get("makernotes_lensfirmwareversion")); } if (lens.containsKey("exif_meteringmode")) { meteringmodecomboBox.setSelectedItem("exif_meteringmode"); } } } } public void deletelensconfig(JPanel SMLcontentPane, String lensname) { String str_lens_file = ""; if (lensname.contains(".hashmap")) { str_lens_file = MyVariables.getlensFolder() + File.separator + lensname; } else { str_lens_file = MyVariables.getlensFolder() + File.separator + lensname + ".hashmap"; } File lens_file = new File(str_lens_file); if (lens_file.exists()) { lens_file.delete(); JOptionPane.showMessageDialog(SMLcontentPane, String.format(ProgramTexts.HTML, 400, ResourceBundle.getBundle("translations/program_strings").getString("sellens.deleted") + " " + lensname), ResourceBundle.getBundle("translations/program_strings").getString("sellens.deletedshort"), JOptionPane.INFORMATION_MESSAGE); } } }
20,029
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
EditExifdata.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/editpane/EditExifdata.java
package org.hvdw.jexiftoolgui.editpane; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.commons.codec.binary.StringUtils; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; public class EditExifdata { private IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(EditExifdata.class); // I had specified for the arrays: //JTextField[] exifFields = {ExifMaketextField, ExifModeltextField, ExifModifyDatetextField, ExifDateTimeOriginaltextField,ExifCreateDatetextField, // ExifArtistCreatortextField, ExifCopyrighttextField, ExifUsercommenttextField}; // JCheckBox[] exifBoxes = {ExifMakecheckBox, ExifModelcheckBox, ExifModifyDatecheckBox, ExifDateTimeOriginalcheckBox,ExifCreateDatecheckBox, // ExifArtistCreatorcheckBox, ExifCopyrightcheckBox, ExifUsercommentcheckBox, ExifDescriptioncheckBox}; public void resetFields(JTextField[] exifFields, JTextArea exiftextArea) { for (JTextField field: exifFields) { field.setText(""); } exiftextArea.setText(""); } public void copyExifFromSelected(JTextField[] exifFields, JTextArea exiftextArea) { String[] exifcopyparams = {"-e","-n","-exif:Make","-exif:Model","-exif:ModifyDate","-exif:DateTimeOriginal","-exif:CreateDate","-exif:Artist","-exif:Copyright","-exif:UserComment","-exif:ImageDescription"}; File[] files = MyVariables.getLoadedFiles(); int SelectedRow = MyVariables.getSelectedRowOrIndex(); String fpath; String res = ""; List<String> cmdparams = new LinkedList<>(); //First clean the fields resetFields(exifFields, exiftextArea); if (Utils.isOsFromMicrosoft()) { fpath = files[SelectedRow].getPath().replace("\\", "/"); } else { fpath = files[SelectedRow].getPath(); } cmdparams.add(Utils.platformExiftool()); cmdparams.addAll( Arrays.asList(exifcopyparams)); cmdparams.add(fpath); try { res = CommandRunner.runCommand(cmdparams); logger.debug("res is\n{}", res); } catch(IOException | InterruptedException ex) { logger.debug("Error executing command"); } if (res.length() > 0) { displayCopiedInfo(exifFields, exiftextArea, res); } } private void displayCopiedInfo(JTextField[] exifFields, JTextArea exiftextArea, String exiftoolInfo) { String[] lines = exiftoolInfo.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); //for(int i = 0; i < lines.length; i++) { for (String line : lines) { String[] cells = line.split(":", 2); // Only split on first : as some tags also contain (multiple) : String SpaceStripped = cells[0].replaceAll("\\s+",""); // regex "\s" is space, extra \ to escape the first \ //Wit ALL spaces removed from the tag we als need to use identiefiers without spaces logger.debug(SpaceStripped, " ; value: ", cells[1], "\n"); if (SpaceStripped.contains("Make")) { exifFields[0].setText(cells[1].trim()); } if (SpaceStripped.contains("CameraModelName")) { exifFields[1].setText(cells[1].trim()); } if (SpaceStripped.contains("ModifyDate")) { exifFields[2].setText(cells[1].trim()); } if (SpaceStripped.contains("Date/TimeOriginal")) { /// Date/timeOriginal: / gives issues with contains???? exifFields[3].setText(cells[1].trim()); } if (SpaceStripped.contains("CreateDate")) { exifFields[4].setText(cells[1].trim()); } if (SpaceStripped.contains("Artist")) { exifFields[5].setText(cells[1].trim()); } if (SpaceStripped.contains("Copyright")) { exifFields[6].setText(cells[1].trim()); } if (SpaceStripped.contains("UserComment")) { exifFields[7].setText(cells[1].trim()); } if (SpaceStripped.contains("ImageDescription")) { exiftextArea.setText(cells[1].trim()); } } } /* * */ public static String fromCPtoUnicode( String value) { byte[] myBytes = null; String newValue = null; String platformCharset = Charset.defaultCharset().displayName(); logger.debug("Writing exif data, converting from codepage {} text {}", platformCharset, value); myBytes = StringUtils.getBytesUnchecked(value, platformCharset); newValue = StringUtils.newStringUtf8(myBytes); logger.debug("Writing exif data, converted string {}", newValue); return newValue; } public void writeExifTags(JTextField[] exifFields, JTextArea Description, JCheckBox[] exifBoxes, JProgressBar progressBar) { List<String> cmdparams = new LinkedList<>(); File[] files = MyVariables.getLoadedFiles(); int[] selectedIndices = MyVariables.getSelectedFilenamesIndices(); cmdparams.add(Utils.platformExiftool()); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!exifBoxes[9].isSelected()) { // default overwrite originals, when set do not cmdparams.add("-overwrite_original"); } cmdparams.addAll(Utils.AlwaysAdd()); if (exifBoxes[0].isSelected()) { cmdparams.add("-exif:Make=" + exifFields[0].getText().trim()); } if (exifBoxes[1].isSelected()) { cmdparams.add("-exif:Model=" + exifFields[1].getText().trim()); } if (exifBoxes[2].isSelected()) { cmdparams.add("-exif:ModifyDate=" + exifFields[2].getText().trim()); } if (exifBoxes[3].isSelected()) { cmdparams.add("-exif:DateTimeOriginal=" + exifFields[3].getText().trim()); } if (exifBoxes[4].isSelected()) { cmdparams.add("-exif:CreateDate=" + exifFields[4].getText().trim()); } if (exifBoxes[5].isSelected()) { cmdparams.add("-exif:Artist=" + exifFields[5].getText().trim()); } if (exifBoxes[6].isSelected()) { cmdparams.add("-exif:Copyright=" + exifFields[6].getText().trim()); } if (exifBoxes[7].isSelected()) { cmdparams.add("-exif:UserComment=" + exifFields[7].getText().trim()); } if (exifBoxes[8].isSelected()) { cmdparams.add("-exif:ImageDescription=" + Description.getText().trim()); } for (int index: selectedIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (Utils.isOsFromMicrosoft()) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } }
7,838
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
EditStringdata.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/editpane/EditStringdata.java
package org.hvdw.jexiftoolgui.editpane; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; public class EditStringdata { private IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(EditStringdata.class); public void resetFields(JTextField[] stringPlusFields, JCheckBox stringPlusOverwriteOriginalscheckBox) { for (JTextField field: stringPlusFields) { field.setText(""); } stringPlusOverwriteOriginalscheckBox.setSelected(false); } public void copyStringPlusFromSelected(JTextField[] stringPlusFields, JCheckBox stringPlusOverwriteOriginalscheckBox) { File[] files = MyVariables.getLoadedFiles(); int SelectedRow = MyVariables.getSelectedRowOrIndex(); String[] copyparams = {"-e", "-n", "-iptc:keywords","-xmp:Subject", "-xmp:PersonInImage"}; String fpath = ""; String res = ""; List<String> cmdparams = new ArrayList<String>(); //First clean the fields resetFields(stringPlusFields, stringPlusOverwriteOriginalscheckBox); if (Utils.isOsFromMicrosoft()) { fpath = files[SelectedRow].getPath().replace("\\", "/"); } else { fpath = files[SelectedRow].getPath(); } logger.info(fpath); cmdparams.add(Utils.platformExiftool()); cmdparams.addAll(Arrays.asList(copyparams)); cmdparams.add(fpath); try { res = CommandRunner.runCommand(cmdparams); logger.info("res is\n{}", res); } catch (IOException | InterruptedException ex) { logger.debug("Error executing command"); } if (res.length() > 0) { displayCopiedInfo(stringPlusFields, res); } } public void displayCopiedInfo(JTextField[] stringPlusFields, String exiftoolInfo) { String[] lines = exiftoolInfo.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); for (String line : lines) { String[] cells = line.split(":", 2); // Only split on first : as some tags also contain (multiple) : String SpaceStripped = cells[0].replaceAll("\\s+",""); // regex "\s" is space, extra \ to escape the first \ if (SpaceStripped.contains("Keywords")) { stringPlusFields[0].setText(cells[1].trim()); } if (SpaceStripped.contains("Subject")) { stringPlusFields[1].setText(cells[1].trim()); } if (SpaceStripped.contains("PersonInImage")) { stringPlusFields[2].setText(cells[1].trim()); } } } public List<String> fillcmdparams (List<String> cmdparams, String textField, String action, String tag, String separator) { String[] words = textField.trim().split(separator); for (String word : words) { cmdparams.add(tag + action + word.trim()); } return cmdparams; } /* / This method returns the selected separator */ private String getStringSeparator() { String separator = ";"; return separator; } public void writeStringPlusTags(JTextField[] stringPlusFields, JCheckBox stringPlusOverwriteOriginalscheckBox, String[] selectedRadioButtons, String separator, JProgressBar progressBar) { List<String> cmdparams = new ArrayList<String>(); int selectedIndices[] = MyVariables.getSelectedFilenamesIndices(); File[] files = MyVariables.getLoadedFiles(); logger.debug("separator: {}", separator); cmdparams.add(Utils.platformExiftool()); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!stringPlusOverwriteOriginalscheckBox.isSelected()) { // default overwrite originals, when set do not cmdparams.add("-overwrite_original"); } cmdparams.addAll(Utils.AlwaysAdd()); //keywords -> xmp keywords /*if ( (stringPlusFields[0].getText().length() > 0) && (!"".equals(selectedRadioButtons[0])) && (stringPlusBoxes[0].isSelected()) ) { cmdparams = fillcmdparams(cmdparams, stringPlusFields[0].getText(), selectedRadioButtons[0], "-xmp-acdsee:keywords", separator); } // keywords -> IPTC if ( (stringPlusFields[0].getText().length() > 0) && (!"".equals(selectedRadioButtons[0])) && (stringPlusBoxes[1].isSelected()) ) { cmdparams = fillcmdparams(cmdparams, stringPlusFields[0].getText(), selectedRadioButtons[0], "-iptc:keywords", separator); }*/ // keywords -> IPTC if ( (stringPlusFields[0].getText().length() > 0) && (!"".equals(selectedRadioButtons[0])) ) { cmdparams = fillcmdparams(cmdparams, stringPlusFields[0].getText(), selectedRadioButtons[0], "-iptc:keywords", separator); } // Subject -> only XMP if ( (stringPlusFields[1].getText().length() > 0) && (!"".equals(selectedRadioButtons[1])) ) { cmdparams = fillcmdparams(cmdparams, stringPlusFields[1].getText(), selectedRadioButtons[1], "-xmp:subject", separator); } // PersonInImage -> only xmp if ( (stringPlusFields[2].getText().length() > 0) && (!"".equals(selectedRadioButtons[2])) ) { cmdparams = fillcmdparams(cmdparams, stringPlusFields[2].getText(), selectedRadioButtons[2], "-xmp:personinimage", separator); } boolean isWindows = Utils.isOsFromMicrosoft(); for (int index: selectedIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } logger.info("params for string+ " + cmdparams.toString()); CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } }
6,695
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
EditGPSdata.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/editpane/EditGPSdata.java
package org.hvdw.jexiftoolgui.editpane; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.ProgramTexts; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.text.DefaultFormatterFactory; import javax.swing.text.NumberFormatter; import java.io.File; import java.io.IOException; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; import static org.hvdw.jexiftoolgui.Utils.in_Range; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; public class EditGPSdata { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(EditGPSdata.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; // I had specified for the arrays: //textfields: gpsLatDecimaltextField, gpsLonDecimaltextField, gpsAltDecimaltextField, gpsLocationtextField, gpsCountrytextField, gpsStateProvincetextField, gpsCitytextField //checkboxes: SaveLatLonAltcheckBox, gpsAboveSealevelcheckBox, gpsLocationcheckBox, gpsCountrycheckBox, gpsStateProvincecheckBox, gpsCitycheckBox, gpsBackupOriginalscheckBox public void setFormattedFieldMasks(JFormattedTextField[] gpsNumdecFields, JFormattedTextField[] gpsCalcFields) { //Always use the US decimal formtter . NumberFormat latformatter = NumberFormat.getNumberInstance(Locale.US ); // Latitude 0-90 latformatter.setMaximumIntegerDigits(2); latformatter.setMaximumFractionDigits(8); gpsNumdecFields[0].setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(latformatter))); NumberFormat lonformatter = NumberFormat.getNumberInstance(Locale.US ); // Longitude 0-180 lonformatter.setMaximumIntegerDigits(3); lonformatter.setMaximumFractionDigits(8); gpsNumdecFields[1].setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(lonformatter))); //Altitude NumberFormat altformatter = NumberFormat.getNumberInstance(Locale.US ); altformatter.setMaximumIntegerDigits(5); altformatter.setMaximumFractionDigits(2); gpsNumdecFields[2].setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(altformatter))); //GPS GMS fields // Deg (lat) and min are 2 digits integer NumberFormat degminformatter = NumberFormat.getNumberInstance(Locale.US ); degminformatter.setMaximumIntegerDigits(2); degminformatter.setMaximumFractionDigits(0); //{CalcLatDegtextField, CalcLatMintextField, CalcLatSectextField, CalcLonDegtextField, CalcLonMintextField, CalcLonSectextField}; gpsCalcFields[0].setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(degminformatter))); gpsCalcFields[1].setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(degminformatter))); gpsCalcFields[4].setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(degminformatter))); // Deg lon is 3 digit integer NumberFormat londegformatter = NumberFormat.getNumberInstance(Locale.US ); londegformatter.setMaximumIntegerDigits(3); londegformatter.setMaximumFractionDigits(0); gpsCalcFields[3].setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(londegformatter))); // secs we make 2 digit, 3 decimals floats NumberFormat secformatter = NumberFormat.getNumberInstance(Locale.US ); secformatter.setMaximumIntegerDigits(2); secformatter.setMaximumFractionDigits(3); gpsCalcFields[2].setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(secformatter))); gpsCalcFields[5].setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(secformatter))); } public void resetFields(JFormattedTextField[] gpsNumdecFields, JTextField[] gpsLocationFields, JFormattedTextField[] GPSdmsFields) { for (JFormattedTextField field: gpsNumdecFields) { field.setText(""); } for (JTextField field: gpsLocationFields) { field.setText(""); } for (JFormattedTextField field: GPSdmsFields) { field.setText(""); } } public void copyGPSFromSelected(JFormattedTextField[] gpsNumdecFields, JTextField[] gpsLocationFields, JCheckBox[] gpsBoxes, JFormattedTextField[] GPSdmsFields, JRadioButton[] GPSdmsradiobuttons) { File[] files = MyVariables.getLoadedFiles(); int SelectedRow = MyVariables.getSelectedRowOrIndex(); // Use "-n" for numerical values, like GPSAltitudeRef 0/1, instead of Above Sea Level/Below Sea Level String[] gpscopyparams = {"-e","-n","-s","-exif:GPSLatitude","-exif:GPSLatitudeRef","-exif:GPSLongitude","-exif:GPSLongitudeRef","-exif:GPSAltitude","-exif:GPSAltitudeRef","-xmp:Location","-xmp:Country","-xmp:State","-xmp:City"}; String fpath =""; String res = ""; List<String> cmdparams = new ArrayList<String>(); //First clean the fields resetFields(gpsNumdecFields, gpsLocationFields, GPSdmsFields); if (Utils.isOsFromMicrosoft()) { fpath = files[SelectedRow].getPath().replace("\\", "/"); } else { fpath = files[SelectedRow].getPath(); } cmdparams.add(Utils.platformExiftool()); cmdparams.addAll( Arrays.asList(gpscopyparams)); cmdparams.add(fpath); try { res = CommandRunner.runCommand(cmdparams); logger.info("res is\n{}", res); } catch(IOException | InterruptedException ex) { logger.debug("Error executing command"); } if (res.length() > 0) { displayCopiedInfo(gpsNumdecFields, gpsLocationFields, gpsBoxes, GPSdmsFields, GPSdmsradiobuttons, res); } } public void displayCopiedInfo(JFormattedTextField[] gpsNumdecFields, JTextField[] gpsLocationFields, JCheckBox[] gpsBoxes, JFormattedTextField[] GPSdmsFields, JRadioButton[] GPSdmsradiobuttons, String exiftoolInfo) { String[] lines = exiftoolInfo.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); boolean latMin = false; boolean lonMin = false; for (String line : lines) { String[] cells = line.split(":", 2); // Only split on first : as some tags also contain (multiple) : String SpaceStripped = cells[0].replaceAll("\\s+",""); // regex "\s" is space, extra \ to escape the first \ //With ALL spaces removed from the tag we als need to use identifiers without spaces logger.info(SpaceStripped + "; value: " + cells[1], "\n"); if ("GPSLatitude".equals(SpaceStripped)) { gpsNumdecFields[0].setText(cells[1].trim()); String[] dmsFields = decDegToDegMinSec(cells[1].trim()); GPSdmsFields[0].setText(dmsFields[0]); GPSdmsFields[1].setText(dmsFields[1]); GPSdmsFields[2].setText(dmsFields[2]); } if (SpaceStripped.contains("GPSLatitudeRef")) { if ("S".equals(cells[1].trim())) { // South means Negative latMin = true; } } if ("GPSLongitude".equals(SpaceStripped)) { gpsNumdecFields[1].setText(cells[1].trim()); String[] dmsFields = decDegToDegMinSec(cells[1].trim()); GPSdmsFields[3].setText(dmsFields[0]); GPSdmsFields[4].setText(dmsFields[1]); GPSdmsFields[5].setText(dmsFields[2]); } if (SpaceStripped.contains("GPSLongitudeRef")) { if ("W".equals(cells[1].trim())) { // West means Negative lonMin = true; } } if ("GPSAltitude".equals(SpaceStripped)) { gpsNumdecFields[2].setText(cells[1].trim()); } if (SpaceStripped.contains("AltitudeRef")) { if (cells[1].contains("0")) { gpsBoxes[1].setSelected(true); } else { gpsBoxes[1].setSelected(false); } } if (SpaceStripped.contains("Location")) { gpsLocationFields[0].setText(cells[1].trim()); } if (SpaceStripped.contains("Country")) { gpsLocationFields[1].setText(cells[1].trim()); } if (SpaceStripped.contains("State")) { gpsLocationFields[2].setText(cells[1].trim()); } if (SpaceStripped.contains("City")) { gpsLocationFields[3].setText(cells[1].trim()); } } // Do the final updates if (latMin) { gpsNumdecFields[0].setText("-" + gpsNumdecFields[0].getText()); GPSdmsradiobuttons[1].setSelected(true); } if (lonMin) { gpsNumdecFields[1].setText("-" + gpsNumdecFields[1].getText()); GPSdmsradiobuttons[3].setSelected(true); } } public void writeGPSTags(JFormattedTextField[] gpsNumdecFields, JTextField[] gpsLocationFields, JCheckBox[] gpsBoxes, JFormattedTextField[] gpsDMSFields, JRadioButton[] gpSdmsradiobuttons, JProgressBar progressBar, int selectedTabIndex, JPanel rootPanel) { int selectedIndices[] = MyVariables.getSelectedFilenamesIndices(); File[] files = MyVariables.getLoadedFiles(); List<String> cmdparams = new ArrayList<String>(); boolean valuescorrect = true; cmdparams.add(Utils.platformExiftool()); boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!gpsBoxes[6].isSelected()) { // default overwrite originals, when set do not cmdparams.add("-overwrite_original"); } if (gpsBoxes[7].isSelected()) { // Use "-m" parameter to allow for longer than 32 char IPTC fields cmdparams.add("-m"); } cmdparams.addAll(Utils.AlwaysAdd()); if (gpsBoxes[0].isSelected()) { // LatLonAlt if (selectedTabIndex == 0) { // This means the decimal format tab // Exiftool prefers to only set one tag (exif or xmp) and retrieve with composite, // but I prefer to set both to satisfy every user //check for correct numbers, no trimming in case of empty field. trim in method String checklat = checkValue(gpsNumdecFields[0].getText(), "double", 90); String checklon = checkValue(gpsNumdecFields[1].getText(), "double", 180); if ("incorrect".equals(checklat) || "incorrect".equals(checklon)) { // Values to high or too low JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 350, ResourceBundle.getBundle("translations/program_strings").getString("gps.declatlon")), ResourceBundle.getBundle("translations/program_strings").getString("gps.inputval"), JOptionPane.ERROR_MESSAGE); valuescorrect = false; } else { cmdparams.add("-exif:GPSLatitude=" + checklat); if (Float.parseFloat(checklat) > 0) { cmdparams.add("-exif:GPSLatitudeREF=N"); } else { cmdparams.add("-exif:GPSLatitudeREF=S"); } cmdparams.add("-exif:GPSLongitude=" + checklon); if (Float.parseFloat(checklon) > 0) { cmdparams.add("-exif:GPSLongitudeREF=E"); } else { cmdparams.add("-exif:GPSLongitudeREF=W"); } if ( !(gpsNumdecFields[2].getText() == null) && !gpsNumdecFields[2].getText().trim().isEmpty()) { String alt = checkValue(gpsNumdecFields[2].getText(), "double", 100000); if ("incorrect".equals(alt)) { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 350, ResourceBundle.getBundle("translations/program_strings").getString("gps.alterror")), ResourceBundle.getBundle("translations/program_strings").getString("gps.inputval"), JOptionPane.ERROR_MESSAGE); valuescorrect = false; } else { cmdparams.add("-exif:GPSAltitude=" + gpsNumdecFields[2].getText().trim()); cmdparams.add("-xmp:GPSLatitude=" + checklat); cmdparams.add("-xmp:GPSLongitude=" + checklon); cmdparams.add("-xmp:GPSAltitude=" + gpsNumdecFields[2].getText().trim()); if (gpsBoxes[1].isSelected()) { //Altitude positive cmdparams.add("-exif:GPSAltitudeREF=above"); } else { cmdparams.add("-exif:GPSAltitudeREF=below"); } } } } } else { //This means the deg-min-sec format tab // First check values String latdeg = checkValue(gpsDMSFields[0].getText().trim(), "int", 90); String latmin = checkValue(gpsDMSFields[1].getText().trim(), "int", 60); String latsec = checkValue(gpsDMSFields[2].getText().trim(), "double", 60); String londeg = checkValue(gpsDMSFields[3].getText().trim(), "int", 180); String lonmin = checkValue(gpsDMSFields[4].getText().trim(), "int", 60); String lonsec = checkValue(gpsDMSFields[5].getText().trim(), "double", 60); String NorS = ""; String EorW = ""; if (gpSdmsradiobuttons[0].isSelected()) { NorS = "N"; } else { NorS = "S"; } if (gpSdmsradiobuttons[2].isSelected()) { EorW = "E"; } else { EorW = "W"; } if ("incorrect".equals(latdeg) || "incorrect".equals(latmin) || "incorrect".equals(latsec) || "incorrect".equals(londeg) || "incorrect".equals(lonmin) || "incorrect".equals(lonsec)) { // Values to high or too low JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 350, ResourceBundle.getBundle("translations/program_strings").getString("gps.dmserror")), ResourceBundle.getBundle("translations/program_strings").getString("gps.inputval"), JOptionPane.ERROR_MESSAGE); valuescorrect = false; } else { // all values correct String[] lat_lon = null; // For xmp values we still need the decimal version as we can't easily save it using the exiftool advised formats for xmp try { lat_lon = Utils.gpsCalculator(rootPanel, new String[]{latdeg, latmin, latsec, NorS, londeg, lonmin, lonsec, EorW}); } catch (ParseException e) { logger.error("error converting deg-min-sec to decimal degrees {}", e.toString()); e.printStackTrace(); } cmdparams.add("-exif:GPSLatitude=" + lat_lon[0]); if (Float.parseFloat(lat_lon[0]) > 0) { cmdparams.add("-exif:GPSLatitudeREF=N"); } else { cmdparams.add("-exif:GPSLatitudeREF=S"); } cmdparams.add("-exif:GPSLongitude=" + lat_lon[1]); if (Float.parseFloat(lat_lon[1]) > 0) { cmdparams.add("-exif:GPSLongitudeREF=E"); } else { cmdparams.add("-exif:GPSLongitudeREF=W"); } if ( !(gpsNumdecFields[2].getText() == null) && !gpsNumdecFields[2].getText().trim().isEmpty()) { String alt = checkValue(gpsNumdecFields[2].getText(), "double", 100000); if ("incorrect".equals(alt)) { JOptionPane.showMessageDialog(rootPanel, String.format(ProgramTexts.HTML, 350, ResourceBundle.getBundle("translations/program_strings").getString("gps.alterror")), ResourceBundle.getBundle("translations/program_strings").getString("gps.inputval"), JOptionPane.ERROR_MESSAGE); valuescorrect = false; } else { cmdparams.add("-exif:GPSAltitude=" + gpsNumdecFields[2].getText().trim()); cmdparams.add("-xmp:GPSLatitude=" + lat_lon[0]); cmdparams.add("-xmp:GPSLongitude=" + lat_lon[1]); cmdparams.add("-xmp:GPSAltitude=" + gpsNumdecFields[2].getText().trim()); if (gpsBoxes[1].isSelected()) { //Altitude positive cmdparams.add("-exif:GPSAltitudeREF=above"); } else { cmdparams.add("-exif:GPSAltitudeREF=below"); } } } } } } // Again: exiftool prefers to only set one tag, but I set both if (gpsBoxes[2].isSelected()) { cmdparams.add("-xmp:Location=" + gpsLocationFields[0].getText().trim()); cmdparams.add("-iptc:Sub-location=" + gpsLocationFields[0].getText().trim()); if (gpsBoxes[8].isSelected()) { // Add Location to makernotes cmdparams.add("-makernotes:Location=" + gpsLocationFields[0].getText().trim()); } } if (gpsBoxes[3].isSelected()) { cmdparams.add("-xmp:Country=" + gpsLocationFields[1].getText().trim()); cmdparams.add("-iptc:Country-PrimaryLocationName=" + gpsLocationFields[1].getText().trim()); if (gpsBoxes[8].isSelected()) { // Add Location to makernotes cmdparams.add("-makernotes:Country=" + gpsLocationFields[1].getText().trim()); } } if (gpsBoxes[4].isSelected()) { cmdparams.add("-xmp:State=" + gpsLocationFields[2].getText().trim()); cmdparams.add("-iptc:Province-State=" + gpsLocationFields[2].getText().trim()); if (gpsBoxes[8].isSelected()) { // Add Location to makernotes cmdparams.add("-makernotes:State=" + gpsLocationFields[2].getText().trim()); } } if (gpsBoxes[5].isSelected()) { cmdparams.add("-xmp:City=" + gpsLocationFields[3].getText().trim()); cmdparams.add("-iptc:City=" + gpsLocationFields[3].getText().trim()); if (gpsBoxes[8].isSelected()) { // Add Location to makernotes cmdparams.add("-makernotes:City=" + gpsLocationFields[3].getText().trim()); } } boolean isWindows = Utils.isOsFromMicrosoft(); for (int index: selectedIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (isWindows) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } logger.debug("total cmdparams from GPS {}", cmdparams); if (valuescorrect) { CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } } private String checkValue (String value, String int_or_double, int maxvalue) { String checked_value = "incorrect"; if ("int".equals(int_or_double)) { // deg-min-sec integers are always positive if ( in_Range(Integer.parseInt(value), 0, maxvalue)) { checked_value = value; } } else if ( "float".equals(int_or_double) || "double".equals(int_or_double) ) { int minvalue = -maxvalue; double dbl = Double.parseDouble(value); int intvalue = (int) dbl; if ( in_Range(intvalue, minvalue, maxvalue)) { checked_value = value; } } return checked_value; } /** * Convert a decimal coordiante back to deg-min-sec for the deg-min-sec textfields * @param coordinate * @return */ public static String[] decDegToDegMinSec(String coordinate) { String deg; double decdegrees = 0.0; double decminutes = 0.0; double decseconds = 0.0; //int intDeg = Integer.parseInt(coordinate); if (coordinate.startsWith("-")) { coordinate = coordinate.substring(1); } decdegrees = Double.parseDouble(coordinate); int intDeg = (int) decdegrees; decminutes = (decdegrees - intDeg) * 60; int intMin = (int) decminutes; decseconds = (decminutes - intMin) * 60; //logger.info("decdegrees {} intDeg {} decminutes {} intMin {} decseconds {}", String.valueOf(decdegrees), String.valueOf(intDeg), String.valueOf(decminutes), String.valueOf(intMin), String.valueOf(decseconds)); NumberFormat numsecs = NumberFormat.getInstance(new Locale("en", "US" )); numsecs.setMaximumFractionDigits(2); String strSeconds = numsecs.format(decseconds); //logger.info("strSeconds {}", strSeconds); String[] dmscoordinate = { String.valueOf(intDeg), String.valueOf(intMin), strSeconds}; return dmscoordinate; } }
22,213
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
EditUserDefinedCombis.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/editpane/EditUserDefinedCombis.java
package org.hvdw.jexiftoolgui.editpane; import org.hvdw.jexiftoolgui.MyConstants; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.CommandRunner; import org.hvdw.jexiftoolgui.controllers.SQLiteJDBC; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.PRESERVE_MODIFY_DATE; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.USER_HOME; public class EditUserDefinedCombis { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(EditUserDefinedCombis.class); private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; JTable usercombiTable; MyTableModel model; TableModelListener modelListener; List<String> tablerowdata = new ArrayList<String>(); List<String> defaultValues = new ArrayList<String>(); String strcustomconfigfile = ""; /* / This option makes only the 3rd (tag value) and 4th (Save checkbox) columns (2, 3) editable / column 1 (no. 0) & 2 (no. 1) are ready-only. / Also override getColumnClass to allow for the Save checkbox in 4th column. */ public class MyTableModel extends DefaultTableModel { public boolean isCellEditable(int row, int column){ return column == 2 || column == 3; } public Class getColumnClass(int column) { if (column == 3) return Boolean.class; else return String.class; } } /* / This method updates the table in case we have selected another combi from the JCombobox */ public void UpdateTable(JPanel rootpanel, JComboBox combicombobox, JScrollPane userCombiPane) { if (model != null && modelListener != null) model.removeTableModelListener(modelListener); tablerowdata.clear(); defaultValues.clear(); if (model == null) { model = new MyTableModel(); model.setColumnIdentifiers(new String[]{ResourceBundle.getBundle("translations/program_strings").getString("mduc.columnlabel"), ResourceBundle.getBundle("translations/program_strings").getString("mduc.columntag"), ResourceBundle.getBundle("translations/program_strings").getString("mduc.columndefault"), ResourceBundle.getBundle("translations/program_strings").getString("label.save")}); } else model.setRowCount(0); if (usercombiTable == null) usercombiTable = new JTable(model); String setName = combicombobox.getSelectedItem().toString(); String sql = "select screen_label, tag, default_value from custommetadatasetLines where customset_name='" + setName.trim() + "' order by rowcount"; String queryResult = SQLiteJDBC.generalQuery(sql, "disk"); if (queryResult.length() > 0) { String[] lines = queryResult.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); for (String line : lines) { String[] cells = line.split("\\t", 4); String defVal = cells[2].trim(); model.addRow(new Object[]{cells[0], cells[1], defVal, defVal.length() == 0 ? Boolean.FALSE : Boolean.TRUE}); tablerowdata.add(""); defaultValues.add(defVal); // We'll use the default values again during a copy operation } MyVariables.setuserCombiTableValues(tablerowdata); } userCombiPane.setViewportView(usercombiTable); // Make the Save column narrower. usercombiTable.getColumnModel().getColumn(3).setMinWidth(50); usercombiTable.getColumnModel().getColumn(3).setMaxWidth(110); usercombiTable.getColumnModel().getColumn(3).setPreferredWidth(70); if (modelListener == null) { modelListener = new TableModelListener() { // React to edits of tag values. If value is different to original value then tick the Save checkbox public void tableChanged(TableModelEvent e) { int col = e.getColumn(); if (col == 3) // No need to react to checkboxes return; int row = e.getFirstRow(); Object originalValue = tablerowdata.get(row); Object modifiedValue = model.getValueAt(row, col); logger.debug("source {}; firstRow {}; lastRow {}, column{}", e.getSource(), row, e.getLastRow(), col); logger.debug("tag {}; original value {}; modified tablecell value {}", model.getValueAt(row, 1), originalValue, modifiedValue); if (originalValue.equals(modifiedValue)) model.setValueAt(Boolean.FALSE, row, 3); else model.setValueAt(Boolean.TRUE, row, 3); } }; } model.addTableModelListener(modelListener); } public void UpdateCustomConfigLabel(JComboBox combicombobox, JLabel customconfiglabel) { String setName = combicombobox.getSelectedItem().toString(); String sql = "select custom_config from custommetadataset where customset_name='" + setName.trim() + "'"; String queryResult = SQLiteJDBC.singleFieldQuery(sql, "custom_config").trim(); if ("".equals(queryResult) || queryResult.isEmpty() || "null".equals(queryResult)) { customconfiglabel.setText(""); strcustomconfigfile = ""; customconfiglabel.setVisible(false); } else { strcustomconfigfile = queryResult.trim(); customconfiglabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("udc.thisset") + " " + queryResult); customconfiglabel.setVisible(true); } } public void ResetFields(JScrollPane userCombiPane) { // Not used here: if user wants to reset, he/she simply selects the dropdown again. } public void SaveTableValues(JCheckBox udcOverwriteOriginalscheckBox, JProgressBar progressBar) { // if Save checkedbox ticked => save File[] files = MyVariables.getLoadedFiles(); int[] selectedIndices = MyVariables.getSelectedFilenamesIndices(); tablerowdata = MyVariables.getuserCombiTableValues(); int rowcounter = 0; List<String> cmdparams = new ArrayList<String>(); cmdparams.add(Utils.platformExiftool()); // -config parameter for custom config file has to be first parameter on command line if (!strcustomconfigfile.equals("")) { String userHome = SystemPropertyFacade.getPropertyByKey(USER_HOME); String strjexiftoolguifolder = userHome + File.separator + MyConstants.MY_DATA_FOLDER; cmdparams.add("-config"); cmdparams.add(strjexiftoolguifolder + File.separator + strcustomconfigfile); } boolean preserveModifyDate = prefs.getByKey(PRESERVE_MODIFY_DATE, true); if (preserveModifyDate) { cmdparams.add("-preserve"); } if (!udcOverwriteOriginalscheckBox.isSelected()) { // default not select ->overwrite originals cmdparams.add("-overwrite_original"); } cmdparams.addAll(Utils.AlwaysAdd()); cmdparams.add("-n"); // Need this for some tags, eg Orientation boolean hasChanged = false; model.removeTableModelListener(modelListener); // Temporarily remove listener to avoid triggering unnecessary events for (String value : tablerowdata) { if ((Boolean) model.getValueAt(rowcounter, 3)) { hasChanged = true; String cellValue = model.getValueAt(rowcounter,2).toString().trim(); logger.info("tag {}; original value {}; modified tablecell value {}", model.getValueAt(rowcounter,1), tablerowdata.get(rowcounter), cellValue); if (model.getValueAt(rowcounter,1).toString().startsWith("-")) { cmdparams.add(model.getValueAt(rowcounter,1).toString() + "=" + cellValue); } else { //tag without - (minus sign/hyphen) as prefix cmdparams.add("-" + model.getValueAt(rowcounter,1).toString() + "=" + cellValue); } tablerowdata.set(rowcounter, cellValue); model.setValueAt(cellValue, rowcounter, 2); } rowcounter++; } model.addTableModelListener(modelListener); // Add back listener for (int index: selectedIndices) { //logger.info("index: {} image path: {}", index, files[index].getPath()); if (Utils.isOsFromMicrosoft()) { cmdparams.add(files[index].getPath().replace("\\", "/")); } else { cmdparams.add(files[index].getPath()); } } if (hasChanged) { logger.info("Save user combi parameter command {}", cmdparams); CommandRunner.runCommandWithProgressBar(cmdparams, progressBar); } else { logger.info("Nothing to save -- no edits made"); } } public void CopyFromSelectedImage() { File[] files = MyVariables.getLoadedFiles(); int SelectedRow = MyVariables.getSelectedRowOrIndex(); tablerowdata = MyVariables.getuserCombiTableValues(); int rowcounter = 0; String fpath =""; String res = ""; List<String> cmdparams = new ArrayList<String>(); List<String> tagnames = new ArrayList<String>(); if (Utils.isOsFromMicrosoft()) { fpath = files[SelectedRow].getPath().replace("\\", "/"); } else { fpath = files[SelectedRow].getPath(); } cmdparams.add(Utils.platformExiftool()); cmdparams.add("-e"); cmdparams.add("-n"); // Now get the tags from table for (String value : tablerowdata) { logger.debug("tag derived from table {}", model.getValueAt(rowcounter,1)); String tname = model.getValueAt(rowcounter,1).toString(); if (tname.startsWith("-")) { tname = tname.substring(1); } // Format the output using exiftool -p option rather than relying on the default output. // The format used is: TAGNAME::VALUE. CANNOT USE "=" for the delimiter due to handling of args in runCommand under Windows cmdparams.add("-p"); cmdparams.add(tname + "::${" + tname + "}"); tagnames.add(tname); rowcounter++; } cmdparams.add(fpath); try { res = CommandRunner.runCommand(cmdparams); logger.debug("res from copyfrom is\n{}", res); } catch(IOException | InterruptedException ex) { logger.debug("Error executing command"); } if (res.length() > 0) { String[] strTagnames = tagnames.stream().toArray(String[]::new); model.removeTableModelListener(modelListener); // Temporarily remove listener to avoid triggering unnecessary events displayCopiedInfo( res, strTagnames); model.addTableModelListener(modelListener); // Add back listener } } private void displayCopiedInfo(String exiftoolInfo, String[] tagNames) { int rowcounter = 0; String[] lines = exiftoolInfo.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); tablerowdata = MyVariables.getuserCombiTableValues(); // Clear previous values and set defaults for (int row = 0; row < model.getRowCount(); row++) { tablerowdata.set(row, ""); model.setValueAt(defaultValues.get(row), row, 2); } for (String line : lines) { String[] returnedValuesRow = line.split("::", 2); // Only split on first :: as some tags also contain (multiple) :: if (returnedValuesRow.length < 2) // line does not contain "TAGNAME::VALUE" so skip it, eg warning messages continue; String SpaceStrippedTag = returnedValuesRow[0]; logger.debug("returnedValuesRow tag {}; returnedValuesRow value {}; SpaceStrippedTag {}", returnedValuesRow[0], returnedValuesRow[1], SpaceStrippedTag); rowcounter =0; for (String tagname: tablerowdata) { if (model.getValueAt(rowcounter,1).toString().equals(SpaceStrippedTag)) { // The model data and tablerowdata values are the same when first retrieved. // Later, during save, each row is checked if it was changed. tablerowdata.set(rowcounter, returnedValuesRow[1].trim()); model.setValueAt(returnedValuesRow[1].trim(),rowcounter,2); } rowcounter++; } } // Tick the Save checkbox for any tags which have defaults still remaining for (int row = 0; row < model.getRowCount(); row++) { if (model.getValueAt(row, 2).equals(tablerowdata.get(row))) model.setValueAt(Boolean.FALSE, row, 3); else model.setValueAt(Boolean.TRUE, row, 3); } } }
13,881
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
SQLiteModel.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/model/SQLiteModel.java
package org.hvdw.jexiftoolgui.model; import org.slf4j.LoggerFactory; import static org.hvdw.jexiftoolgui.controllers.SQLiteJDBC.*; public class SQLiteModel { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.hvdw.jexiftoolgui.controllers.SQLiteJDBC.class); /* static public String getDBversion() { String sql = "select version from ExiftoolVersion limit 1"; return singleFieldQuery(sql, "version"); } static public String getGroups() { String sql = "SELECT taggroup FROM Groups order by taggroup"; return singleFieldQuery(sql, "taggroup"); } */ static public String getdefinedlensnames() { String sql = "select lens_name from myLenses order by lens_Name"; return singleFieldQuery(sql, "lens_name"); } static public String getdefinedCustomSets() { String sql = "select customset_name from CustomMetadataset order by customset_name"; return singleFieldQuery(sql, "customset_name"); } static public String deleteCustomSetRows( String setName) { String sql = "delete from CustomMetadatasetLines where customset_name='" + setName + "'"; return insertUpdateQuery(sql, "disk"); } static public String queryByTagname(String searchString, boolean likequery) { String sqlresult = ""; String sql = ""; logger.debug("search string is: " + searchString); if (likequery) { sql = "select taggroup,tagname,tagtype,writable from Groups,Tags,tagsingroups where tagsingroups.groupid=Groups.id and tagsingroups.tagid=tags.id and tagname like '%" + searchString + "%' order by taggroup"; // use our view //sql = "select taggroup,tagname,tagtype,writable from v_tags_groups where tagname like '%" + searchString + "%'"; } else { sql = "select taggroup,tagname,tagtype,writable from Groups,Tags,tagsingroups where tagsingroups.groupid=Groups.id and tagsingroups.tagid=tags.id and taggroup='" + searchString + "'"; // use our view //sql = "select taggroup,tagname,tagtype,writable from v_tags_groups where taggroup='" + searchString + "'"; } sqlresult = generalQuery(sql, "disk"); return sqlresult; } static public String ownQuery(String sql) { String sqlresult = ""; sqlresult = generalQuery(sql, "disk"); return sqlresult; } }
2,496
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
NominatimResult.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/model/NominatimResult.java
package org.hvdw.jexiftoolgui.model; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class NominatimResult { private String[] geoPosition; //display_Name, latitude,longitude; private String[] boundingbox; // contains X1, X2, Y1, Y2 private Map address = new HashMap(); public NominatimResult(String[] geoPosition, String[] boundingbox, Map address) { this.geoPosition = geoPosition; this.boundingbox = boundingbox; this.address = address; } public String[] getGeoPosition() { return geoPosition; } public String[] setGeoPosition(String[] geoPosition) { this.geoPosition = geoPosition; return geoPosition; } public String[] getBoundingbox() { return boundingbox; } public String[] setBoundingbox(String[] boundingbox) { this.boundingbox = boundingbox; return boundingbox; } public Map getAddress() { return address; } public Map setAddress(Map address) { this.address = address; return address; } }
1,101
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
CompareImages.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/model/CompareImages.java
package org.hvdw.jexiftoolgui.model; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.controllers.SQLiteJDBC; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.hvdw.jexiftoolgui.view.CompareImagesWindow; import javax.swing.*; import java.io.File; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; import static org.slf4j.LoggerFactory.getLogger; public class CompareImages { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) getLogger(CompareImages.class); public final static class ArrayListHolder { private ArrayList<String[]> tmpMetadata = new ArrayList<String[]>(); private ArrayList<String> Cat_Tag_List = new ArrayList<String>(); public ArrayList<String[]> getTmpMetadata() { return tmpMetadata; } public void setTmpMetadata(ArrayList<String[]> tmpMdata) { tmpMetadata = tmpMdata; } public ArrayList<String> getCat_Tag_List() { return Cat_Tag_List; } public void setCat_Tag_List(ArrayList<String> CT_List) { Cat_Tag_List = CT_List; } } private static void dbAction(String sql, String comment) { String qr = SQLiteJDBC.insertUpdateQuery(sql, "disk"); if (!"".equals(qr)) { //means we have an error JOptionPane.showMessageDialog(null, "Encountered an error creating " + comment); logger.error("Encountered an error creating {}", comment); } else { // we were successful logger.debug("Successfully did {}", comment); } } private static void dbBulkAction(String[] sql, String comment) { String qr = SQLiteJDBC.bulkInsertUpdateQuery(sql, "disk"); if (!"".equals(qr)) { //means we have an error JOptionPane.showMessageDialog(null, "Encountered an error creating " + comment); logger.error("Encountered an error creating {}", comment); } else { // we were successful logger.debug("Successfully did {}", comment); } } private static void Initialize() { // On every start of this Function CleanUp(); String sql = "Create table if not exists ImageInfoRows (\n" + " id integer primary key autoincrement,\n" + " imgindex int NOT NULL,\n" + " filename text NOT NULL,\n" + " category text NOT NULL,\n" + " tagname text NOT NULL,\n" + " value text)"; dbAction(sql, "create ImageInfoRows"); sql = "create view if not exists category_tagname as select distinct category, tagname from imageinforows"; //dbAction(sql, "Create view category_tagname"); } /** * Used on every new compare and when closing the app */ public static void CleanUp() { //dbAction("drop view if exists category_tagname", "drop view if exists category_tagname"); dbAction("drop table if exists ImageInfoRows","drop table if exists ImageInfoRows"); } /** * Method that stores all metadat into a table for later retrieval * @param index * @param filename * @param exiftoolInfo */ private static void AddToImageInfoRows(Integer index, String filename, String exiftoolInfo) { String sql; if (exiftoolInfo.length() > 0) { if (exiftoolInfo.trim().startsWith("Warning")) { sql = "Insert into ImageInfoRows(imgindex,filename,category,tagname,value) values(" + index + ",\"" + filename + "\",\"ExifTool Warning\",\"Invalid Metadata data\",\"Error\")"; dbAction(sql, "Add warning row for " + filename); } else if (exiftoolInfo.trim().startsWith("Error")) { sql = "Insert into ImageInfoRows(imgindex,filename,category,tagname,value) values(" + index + ",\"" + filename + "\",\"ExifTool Error\",\"Invalid Metadata data\",\"Error\")"; dbAction(sql, "Add error row for " + filename); } else { String[] lines = exiftoolInfo.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); String[] sqls = new String[lines.length]; int counter = 0; for (String line : lines) { String[] imgInfoRow = line.split("\\t", 3); sql = "Insert into ImageInfoRows(imgindex,filename,category,tagname,value) values(" + index + ",\"" + filename + "\",\"" + imgInfoRow[0].trim() + "\",\"" + imgInfoRow[1].trim() + "\",\"" +imgInfoRow[2].trim() + "\")"; sqls[counter] = sql; counter++; } dbBulkAction(sqls, "bulk sql"); } } } /** * Method that stores all infodata in multiple Lists * @param index * @param exiftoolInfo */ private static List<String[]> AddToInfoRows(Integer index, String exiftoolInfo) { //String sql; ArrayListHolder arrayListData = new ArrayListHolder(); List<String[]> tmpMetadata = new ArrayList<String[]>(); ArrayList<String> Cat_Tag_List = new ArrayList<String>(); //String[] oneRow; // getter Cat_Tag_List => Cat_Tag_List = MyVariables.getCat_Tag_List Cat_Tag_List = MyVariables.getcategory_tag(); if (exiftoolInfo.length() > 0) { if (exiftoolInfo.trim().startsWith("Warning")) { String[] oneRow = { "ExifTool Warning||Invalid Metadata data", String.valueOf(index), "ExifTool Warning", "Invalid Metadata data", "Error" }; tmpMetadata.add(oneRow); } else if (exiftoolInfo.trim().startsWith("Error")) { String[] oneRow = { "ExifTool Error||Invalid Metadata data", String.valueOf(index), "ExifTool Error", "Invalid Metadata data", "Error" }; tmpMetadata.add(oneRow); } else { String[] lines = exiftoolInfo.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); for (String line : lines) { String[] imgInfoRow = line.split("\\t", 3); String[] oneRow = { imgInfoRow[0].trim() + "||" + imgInfoRow[1].trim(), String.valueOf(index), imgInfoRow[0].trim(), imgInfoRow[1].trim(), imgInfoRow[2].trim()}; tmpMetadata.add(oneRow); String tmp = imgInfoRow[0].trim() + "||" + imgInfoRow[1].trim(); //Cat_Tag_List.add( tmp ); } } } //MyVariables.setcategory_tag(Cat_Tag_List); //setCat_Tag_List(Cat_Tag_List); return tmpMetadata; } //public static List<String[]> CompareImages(List<Integer> selectedIndices, String[] params, JProgressBar progressBar, JLabel outputLabel) { public static void CompareImages(List<Integer> selectedIndices, String[] params, JProgressBar progressBar, JLabel outputLabel) { List<String> cmdparams = new ArrayList<String>(); File[] files = MyVariables.getLoadedFiles(); List<String> category_tagname = new ArrayList<String>(); List<String[]> allMetadata = new ArrayList<String[]>(); List<String[]> tableMetadata = new ArrayList<String[]>(); String sql; final String[][] values = new String[1][1]; ArrayListHolder arrayListData = new ArrayListHolder(); Initialize(); logger.debug("params for exiftool {}", String.join(",", params)); // Use background thread to prepare everything Executor executor = Executors.newSingleThreadExecutor(); executor.execute(new Runnable() { @Override public void run() { try { boolean isWindows = Utils.isOsFromMicrosoft(); cmdparams.add(Utils.platformExiftool()); // we want short tags to prevent issues with tagnames with spaces, colons and commas. And it makes our column slightly smaller. cmdparams.add("-s"); cmdparams.addAll(Arrays.asList(params)); long start = System.currentTimeMillis(); for (int index : selectedIndices) { List<String[]> tmpMetadata = new ArrayList<String[]>(); long astart = System.currentTimeMillis(); String res = Utils.getImageInfoFromSelectedFile(params, index); long aend = System.currentTimeMillis(); long bstart = System.currentTimeMillis(); //AddToImageInfoRows(index, filename, res); tmpMetadata = AddToInfoRows(index, res); allMetadata.addAll(tmpMetadata); long bend = System.currentTimeMillis(); logger.debug("exiftool {} ms; addtoListArray {} ms", (astart - aend), (bstart - bend)); logger.debug("allMetadata {}", allMetadata.size()); } long end = System.currentTimeMillis(); logger.debug("Reading exiftool info and adding to List {} ms", (end - start)); logger.debug("final allMetadata {}", allMetadata.size()); start = System.currentTimeMillis(); for (String[] oneRow : allMetadata) { //logger.info(Arrays.toString(oneRow)); category_tagname.add(oneRow[0]); } Set<String> unique_cat_tag_set = new HashSet<String>(category_tagname); List<String> unique_cat_tag = new ArrayList<>(unique_cat_tag_set); Collections.sort(unique_cat_tag); end = System.currentTimeMillis(); logger.debug("Creating category_tagname list + hashset {} ms", (end - start)); start = System.currentTimeMillis(); for (String cat_tag : unique_cat_tag) { String[] values = new String[selectedIndices.size() + 2]; // Create list with 27 values: more than we will ever process on files: 2 for category and tgname, 25 for images List<String> listvalues = new ArrayList<String>(); for (int i = 0; i < 27; i++) { listvalues.add("9999"); } for (String[] metadata : allMetadata) { //logger.info("cat_tag {} metadata {}", cat_tag, metadata); int counter = 2; for (int index : selectedIndices) { if ((cat_tag.equals(metadata[0])) && (Integer.valueOf(metadata[1]) == index)) { listvalues.set(0, metadata[2]); listvalues.set(1, metadata[3]); //listvalues.set((Integer.valueOf(index) + 2), metadata[4]); listvalues.set(counter, metadata[4]); } counter++; } } //logger.info("list values {}", listvalues); for (int i = 0; i < (selectedIndices.size() + 2); i++) { if ((listvalues.get(i)).equals("9999")) { values[i] = ""; } else { values[i] = listvalues.get(i); } } //logger.info("values {}", Arrays.toString(values)); tableMetadata.add(values); } end = System.currentTimeMillis(); logger.debug("raw data to table data {}", (end - start)); //Now display our data CompareImagesWindow.Initialize(tableMetadata, allMetadata); logger.debug("Now starting CompareImagesWindow to show the data"); progressBar.setVisible(false); outputLabel.setText(""); //CompareImagesWindow.Initialize(allMetadata); } catch (Exception ex) { logger.debug("Error executing command"); } } }); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setVisible(true); outputLabel.setText(ResourceBundle.getBundle("translations/program_strings").getString("pt.compare")); } }); //return allMetadata; ////////////////////////////////////// } }
13,177
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
Lenses.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/model/Lenses.java
package org.hvdw.jexiftoolgui.model; import org.hvdw.jexiftoolgui.MyVariables; import org.hvdw.jexiftoolgui.controllers.SQLiteJDBC; import org.hvdw.jexiftoolgui.facades.SystemPropertyFacade; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import static org.hvdw.jexiftoolgui.facades.SystemPropertyFacade.SystemPropertyKey.LINE_SEPARATOR; public class Lenses { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Lenses.class); public static List<File> loadlensnames() { File lensFolder = new File(MyVariables.getlensFolder()); File[] listOfFiles = lensFolder.listFiles(); List<File> listOfCheckedFileNames = new ArrayList<File>(); for (File file : listOfFiles) { if (file.isFile()) { //System.out.println(file.getName()); listOfCheckedFileNames.add(file); } } return listOfCheckedFileNames; } public static void displaylensnames(List<File> lensnames, JTable lensnametable) { DefaultTableModel model = (DefaultTableModel) lensnametable.getModel(); model.setColumnIdentifiers(new String[]{ResourceBundle.getBundle("translations/program_strings").getString("sellens.name")}); lensnametable.getColumnModel().getColumn(0).setPreferredWidth(250); model.setRowCount(0); Object[] row = new Object[1]; if (lensnames.size() > 0) { //String[] lines = lensnames.split(SystemPropertyFacade.getPropertyByKey(LINE_SEPARATOR)); //logger.debug("String[] lines {}", Arrays.toString(lines)); for (File lensname : lensnames) { logger.debug("lensname {}", lensname.getName()); model.addRow(new Object[]{lensname.getName()}); } } } }
2,003
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
FileTreeModel.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/model/FileTreeModel.java
package org.hvdw.jexiftoolgui.model; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.io.File; /** * The methods in this class allow the JTree component to traverse * the file system tree, and display the files and directories. * Copied from http://www.java2s.com/Code/Java/Swing-JFC/implementsTreeModeltodisplayFileinaTree.htm **/ public class FileTreeModel implements TreeModel { // We specify the root directory when we create the model. protected File root; public FileTreeModel(File root) { this.root = root; } // The model knows how to return the root object of the tree public Object getRoot() { return root; } // Tell JTree whether an object in the tree is a leaf or not public boolean isLeaf(Object node) { return ((File)node).isFile(); } // Tell JTree how many children a node has public int getChildCount(Object parent) { String[] children = ((File)parent).list(); if (children == null) return 0; return children.length; } // Fetch any numbered child of a node for the JTree. // Our model returns File objects for all nodes in the tree. The // JTree displays these by calling the File.toString() method. public Object getChild(Object parent, int index) { String[] children = ((File)parent).list(); /*for (String child : children) { System.out.println(child); }*/ //System.out.println(("parent: " + (File)parent).toString() + " + children " + children.toString()); if ((children == null) || (index >= children.length)) return null; return new File((File) parent, children[index]); } // Figure out a child's position in its parent node. public int getIndexOfChild(Object parent, Object child) { String[] children = ((File)parent).list(); if (children == null) return -1; String childname = ((File)child).getName(); for(int i = 0; i < children.length; i++) { if (childname.equals(children[i])) return i; } return -1; } // This method is only invoked by the JTree for editable trees. // This TreeModel does not allow editing, so we do not implement // this method. The JTree editable property is false by default. public void valueForPathChanged(TreePath path, Object newvalue) {} // Since this is not an editable tree model, we never fire any events, // so we don't actually have to keep track of interested listeners. public void addTreeModelListener(TreeModelListener l) {} public void removeTreeModelListener(TreeModelListener l) {} }
2,687
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
Nominatim.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/model/Nominatim.java
package org.hvdw.jexiftoolgui.model; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonValue; import org.hvdw.jexiftoolgui.controllers.ButtonsActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import static org.slf4j.LoggerFactory.getLogger; public class Nominatim { private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) getLogger(ButtonsActionListener.class); /** * This is the standard search routine for Nominatim * @param searchphrase * @return * @throws IOException */ public static String SearchLocation(String searchphrase) throws IOException { String getResponse = ""; final String baseurl = "https://nominatim.openstreetmap.org/search?addressdetails=1&q="; String geturl = baseurl + searchphrase.replace(" ", "+") + "&format=json"; logger.debug("geturl {}", geturl); URL urlObj = new URL(geturl); HttpsURLConnection connection = (HttpsURLConnection) urlObj.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestProperty("Accept-Charset", "UTF-8"); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine + "\n"); } in.close(); logger.debug(response.toString()); getResponse = response.toString(); } else { logger.error("The GET request to Nominatim {} did not work", geturl); } return getResponse; } /** * This method does a reverse search whe na user has right-clicked the map * @param lat * @param lon * @return * @throws IOException */ public static String ReverseSearch(double lat, double lon) throws IOException { String getResponse = ""; final String baseurl = "https://nominatim.openstreetmap.org/reverse?"; String geturl = baseurl + "lat=" + lat + "&lon=" + lon + "&format=json"; logger.debug("geturl {}", geturl); URL urlObj = new URL(geturl); HttpsURLConnection connection = (HttpsURLConnection) urlObj.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestProperty("Accept-Charset", "UTF-8"); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine + "\n"); } in.close(); logger.debug(response.toString()); getResponse = response.toString(); } else { logger.error("The GET request to Nominatim {} did not work", geturl); } return getResponse; } /** * Get list of strings containing (display_)name, latitude, longitude using simple-json * @param input * @return */ public static List<Map> parseLocationJson(String input) { List<NominatimResult> NRList = new ArrayList<>(); List<Map> placesList = new ArrayList<>(); JsonArray places = Json.parse(input).asArray(); logger.debug("places {}", places.toString()); for (JsonValue place : places) { Map hmplace = new HashMap(); hmplace.put("display_Name", place.asObject().getString("display_name", "Unknown display_name")); hmplace.put("geoLatitude", place.asObject().getString("lat", "Unknown latitude")); hmplace.put("geoLongitude", place.asObject().getString("lon", "Unknown longitude")); //boundingbox JsonArray boundingbox = (JsonArray) place.asObject().get("boundingbox"); hmplace.put("bbX1", boundingbox.get(0).asString()); hmplace.put("bbX2", boundingbox.get(1).asString()); hmplace.put("bbY1", boundingbox.get(2).asString()); hmplace.put("bbY2", boundingbox.get(3).asString()); //Address JsonValue value = place.asObject().get("address"); String addressstring = value.toString().replace("\"", "").replace("{", "").replace("}",""); logger.debug("addresstring {}", addressstring); String[] addressArray = addressstring.split(","); for (String addresspart : addressArray) { String[] splitaddresspart = addresspart.split(":"); hmplace.put(splitaddresspart[0].trim(), splitaddresspart[1].trim()); } placesList.add(hmplace); } return placesList; } public static Map<String, String> parseReverseLocationJson(String input) { JsonValue place = Json.parse(input); Map hmplace = new HashMap(); hmplace.put("display_Name", place.asObject().getString("display_name", "Unknown display_name")); hmplace.put("geoLatitude", place.asObject().getString("lat", "Unknown latitude")); hmplace.put("geoLongitude", place.asObject().getString("lon", "Unknown longitude")); //boundingbox JsonArray boundingbox = (JsonArray) place.asObject().get("boundingbox"); hmplace.put("bbX1", boundingbox.get(0).asString()); hmplace.put("bbX2", boundingbox.get(1).asString()); hmplace.put("bbY1", boundingbox.get(2).asString()); hmplace.put("bbY2", boundingbox.get(3).asString()); //Address JsonValue value = place.asObject().get("address"); String addressstring = value.toString().replace("\"", "").replace("{", "").replace("}",""); logger.debug("addresstring {}", addressstring); String[] addressArray = addressstring.split(","); for (String addresspart : addressArray) { String[] splitaddresspart = addresspart.split(":"); hmplace.put(splitaddresspart[0].trim(), splitaddresspart[1].trim()); } return hmplace; } }
6,871
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
GuiConfig.java
/FileExtraction/Java_unseen/hvdwolf_jExifToolGUI/src/main/java/org/hvdw/jexiftoolgui/model/GuiConfig.java
package org.hvdw.jexiftoolgui.model; import org.hvdw.jexiftoolgui.Application; import org.hvdw.jexiftoolgui.Utils; import org.hvdw.jexiftoolgui.facades.IPreferencesFacade; import javax.swing.*; import java.awt.*; import static org.hvdw.jexiftoolgui.facades.IPreferencesFacade.PreferenceKey.*; import static org.slf4j.LoggerFactory.getLogger; public class GuiConfig { public static int guiWidth; public static int guiHeight; private final static IPreferencesFacade prefs = IPreferencesFacade.defaultInstance; private final static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) getLogger(GuiConfig.class); /** * Gets the current width and height from the rootPanel (not the frame) * @param rootPanel */ public static void GuiSize(JPanel rootPanel){ guiWidth = rootPanel.getWidth(); guiHeight = rootPanel.getHeight(); logger.debug("rootPanel size {} x {}", guiWidth, guiHeight); } public static void GuiSize(JFrame frame){ guiWidth = frame.getWidth(); guiHeight = frame.getHeight(); logger.debug("frame size {} x {}", guiWidth, guiHeight); } /** * SplitPaneDividerPercentage returns the position as a value like 0.33 (450/1350) or so * @param splitpane */ private static double SplitPaneDividerPercentage( JSplitPane splitpane) { double SplitPositionPercentage; // getDividerLocation is int, setDividerLocation is double double splitposition = splitpane.getDividerLocation() / (double) (splitpane.getWidth() - splitpane.getDividerSize()); return SplitPositionPercentage = ((int) (100 * (splitposition + 0.005))) / (double) 100; } /** * SaveGuiConfig saves Width, Height and JSplitpane position to Preferences * This method is called when the user nicely uses the File -> Exit method * @param rootPanel * @param splitpanel */ public static void SaveGuiConfig(JFrame frame, JPanel rootPanel, JSplitPane splitpanel) { //GuiSize(rootPanel); GuiSize(frame); double SPP = SplitPaneDividerPercentage(splitpanel); prefs.storeByKey(GUI_WIDTH, String.valueOf(guiWidth)); prefs.storeByKey(GUI_HEIGHT, String.valueOf(guiHeight)); prefs.storeByKey(SPLITPANEL_POSITION, String.valueOf(SPP)); logger.debug("Save Gui Settings: Width x Height {}x{}; splitpanel postion {}", guiWidth, guiHeight, String.valueOf(SPP)); } /** * This SaveGuiConfig method saves only the frame size and is invoked when the user presses the exit button in the menubar * @param frame */ public static void SaveGuiConfig(JFrame frame) { //GuiSize(rootPanel); GuiSize(frame); prefs.storeByKey(GUI_WIDTH, String.valueOf(guiWidth)); prefs.storeByKey(GUI_HEIGHT, String.valueOf(guiHeight)); } /** * LoadGuiConfig loads Width, Height and JSplitpane postion from Preferences and restores the Gui * to the state when the user exited the application * @param rootPanel * @param splitpanel */ public static void LoadGuiConfig(JPanel rootPanel, JSplitPane splitpanel) { String strWidth; String strHeight; int Width; int Height; strWidth = prefs.getByKey(GUI_WIDTH, "1"); // 1450 Apple, 1360 others strHeight = prefs.getByKey(GUI_HEIGHT, "1"); //850 Application.OS_NAMES os = Utils.getCurrentOsName(); if ("1".equals(strWidth)) { if (os == Application.OS_NAMES.APPLE) { Width = 1450; } else { Width = 850; } } else { Width = Integer.parseInt(strWidth); } if ("1".equals(strHeight)) { Height = 850; } else { Height = Integer.parseInt(strHeight); } logger.debug("rootPanel.setSize {} x {}", Width, Height); rootPanel.setPreferredSize(new Dimension(Width, Height)); } /** * * @param splitpanel */ public static void SetSplitPaneDivider(JSplitPane splitpanel) { String strSplitPanePosition = prefs.getByKey(SPLITPANEL_POSITION, "1"); if ("1".equals(strSplitPanePosition)) { splitpanel.setDividerLocation(0.33); } else { splitpanel.setDividerLocation(Double.parseDouble(strSplitPanePosition)); } } /** * This version of the LoadGuiConfig sets the total frame size * @param frame */ public static void LoadGuiConfig(JFrame frame) { String strWidth; String strHeight; int Width; int Height; strWidth = prefs.getByKey(GUI_WIDTH, "1"); // 1450 Apple, 1360 others strHeight = prefs.getByKey(GUI_HEIGHT, "1"); //850 Application.OS_NAMES os = Utils.getCurrentOsName(); if ("1".equals(strWidth)) { if (os == Application.OS_NAMES.APPLE) { Width = 1450; } else { Width = 850; } } else { Width = Integer.parseInt(strWidth); } if ("1".equals(strHeight)) { Height = 850; } else { Height = Integer.parseInt(strHeight); } logger.debug("frame.setSize {} x {}", Width, Height); frame.setSize(Width, Height); } }
5,398
Java
.java
hvdwolf/jExifToolGUI
421
35
33
2019-05-17T13:36:07Z
2023-12-11T23:08:29Z
DictionaryBuilder.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/dictionary/src/main/java/com/frank0631/SemanticWebScraper/DictionaryBuilder.java
package com.frank0631.SemanticWebScraper; //import com.entopix.maui.main.MauiWrapper; //import com.entopix.maui.util.Topic; import com.entopix.maui.filters.MauiFilter; import com.entopix.maui.main.MauiModelBuilder; import com.entopix.maui.main.MauiTopicExtractor; import com.entopix.maui.util.MauiDocument; import com.entopix.maui.util.MauiTopics; import com.entopix.maui.util.Topic; import java.io.File; import java.util.List; public class DictionaryBuilder { public DictionaryBuilder(){ String modelname = "SemEval2010"; File modelfile = new File(modelname); if(!modelfile.exists()) { /* -l directory (directory with the data) -m model (model file) -v vocabulary (vocabulary name) -f {skos|text} (vocabulary format) -w database@server (wikipedia location) */ String[] trainOptions = new String[]{ "-l", "SemEval2010-Maui/maui-semeval2010-train", "-v", "lcsh.rdf.gz", "-f", "skos", "-x", "2", "-o", "2", "-m", modelname}; try { MauiModelBuilder mauiModelBuilder = new MauiModelBuilder(); mauiModelBuilder.setBasicFeatures(true); mauiModelBuilder.setOptions(trainOptions); System.out.println(mauiModelBuilder.getOptions()); MauiFilter frankModel = mauiModelBuilder.buildModel(); mauiModelBuilder.saveModel(frankModel); } catch (Exception ex) { ex.printStackTrace(); } } String[] testOptions = new String[]{"-l", "SemEval2010-Maui/maui-semeval2010-test", "-v", "lcsh.rdf.gz", "-f", "skos", "-m", modelname}; try { MauiTopicExtractor mauiTopicExtractor = new MauiTopicExtractor(); mauiTopicExtractor.setOptions(testOptions); mauiTopicExtractor.loadModel(); List<MauiDocument> testFiles = mauiTopicExtractor.loadDocuments(); List<MauiTopics> testTopics = mauiTopicExtractor.extractTopics(testFiles); for (MauiTopics tts : testTopics) { System.out.println(tts.getFilePath()); for (Topic topic : tts.getTopics()) System.out.print(topic.getTitle()+":"+topic.getProbability()+", "); } } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args){ new DictionaryBuilder(); } }
2,650
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
ArticleFetcher.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/ArticleFetcher.java
package com.frank0631.SemanticWebScraper; import de.l3s.boilerpipe.BoilerpipeProcessingException; import de.l3s.boilerpipe.extractors.ArticleExtractor; import de.l3s.boilerpipe.sax.HTMLHighlighter; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; /** * Created by frank on 1/18/15. */ public class ArticleFetcher implements Runnable { public static String regexURL = "[^A-Za-z0-9()]"; public static int reachTimeoutSec = 3; public static int readTimeoutSec = 6; public static String[] skipExt = (new String[]{".pdf", ".doc", ".ppt"}); public static ArticleExtractor article_extractor; public static HTMLHighlighter html_highlighter; public String urlstr; public String storePath; public ArticleFetcher(String storePath, String urlstr) { //TODO pass in these two objects when threadsafe article_extractor = new ArticleExtractor(); html_highlighter = HTMLHighlighter.newHighlightingInstance(); this.storePath = storePath; this.urlstr = urlstr; } @Override public void run() { fetch(); } private void fetch() { try { htmlHilight(urlstr, true); extractorArticle(urlstr, true, false, storePath); System.out.println("cached " + urlstr); } catch (IOException ioe) { System.out.println("could not cache " + urlstr); //ioe.printStackTrace(); } catch (UnsupportedExtension ioe) { System.out.println("could not cache " + urlstr); //ioe.printStackTrace(); } } public String htmlHilight(String url_str, boolean write) throws IOException, UnsupportedExtension { for (String skip : skipExt) { if (url_str.toLowerCase().endsWith(skip)) throw new UnsupportedExtension("UnsupportedExtension " + skip); } String url_path = url_str.replaceAll(regexURL, "").toLowerCase(); String article_html_file = storePath + url_path + "/highlighted.html"; String article_html = null; URL url = new URL(url_str); File html_file = new File(article_html_file); if (html_file.exists())//read article_html = fileToString(html_file); else { if (URLFetcher.ping(url)) { try { article_html = html_highlighter.process(url, article_extractor); } catch (BoilerpipeProcessingException bpe) { article_html = ""; bpe.printStackTrace(); } catch (SAXException saxe) { article_html = ""; saxe.printStackTrace(); } if (write) { new File(storePath + url_path).mkdir(); PrintWriter out_html = new PrintWriter(article_html_file, "UTF-8"); out_html.println("<base href=\"" + url + "\" >"); out_html.println("<meta http-equiv=\"Content-Type\" content=\"text-html; charset=utf-8\" />"); out_html.println(article_html); out_html.close(); } } else return ""; } return article_html; } public static String extractorArticle(String url_str, boolean write, boolean cachedArticle, String storePath) throws IOException, UnsupportedExtension { for (String skip : skipExt) { if (url_str.toLowerCase().endsWith(skip)) throw new UnsupportedExtension("UnsupportedExtension " + skip); } String url_path = url_str.replaceAll(regexURL, "").toLowerCase(); String article_html_file = storePath + url_path + "/highlighted.html"; String article_html = null; File html_file; String article_text_file = storePath + url_path + "/text.txt"; String article_text; File text_file = new File(article_text_file); if (text_file.exists())//read article_text = fileToString(text_file); else { html_file = new File(article_html_file); if (html_file.exists()) { //read if html exist article_html = fileToString(html_file); try { article_text = article_extractor.getText(article_html); } catch (BoilerpipeProcessingException bpe) { article_text = ""; bpe.printStackTrace(); } } else if (cachedArticle == false) { //read if no html exist URL url = new URL(url_str); if (URLFetcher.ping(url)) try { article_text = article_extractor.getText(url); } catch (BoilerpipeProcessingException bpe) { article_text = ""; bpe.printStackTrace(); } else article_text = ""; //if no html exist set to blank } else article_text = ""; if (write) { new File(storePath + url_path).mkdir(); PrintWriter out_text = new PrintWriter(article_text_file, "US-ASCII"); out_text.println(article_text); out_text.close(); } } return article_text; } public static class UnsupportedExtension extends Exception { public UnsupportedExtension(String msg) { super(msg); } } public static String fileToString(File in) throws IOException { FileInputStream is = new FileInputStream(in); byte[] b = new byte[(int) in.length()]; is.read(b, 0, (int) in.length()); String contents = new String(b); return contents; } public static int countWords(String summery) { String trimmed = summery.trim(); if (trimmed.isEmpty()) return 0; return trimmed.split("\\s+").length; } }
6,146
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
KeywordHandeler.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/KeywordHandeler.java
package com.frank0631.SemanticWebScraper; //import com.entopix.maui.main.MauiWrapper; //import com.entopix.maui.util.Topic; import com.entopix.maui.main.MauiWrapper; import com.entopix.maui.util.Topic; import java.io.File; import java.io.PrintWriter; import java.util.*; public class KeywordHandeler { String vocabularyName = "lcsh.rdf.gz"; String modelName = "SemEval2010"; MauiWrapper keywordsExtractor; int keywordsLimit = 30; public KeywordHandeler(){ //setup keywords extractor keywordsExtractor = new MauiWrapper(modelName,vocabularyName,"skos"); keywordsExtractor.setModelParameters(vocabularyName,null,null,null); } public Map ExtractKeywords(Map urlSummeries){ Map urlKeywords = new LinkedHashMap(); int i=0; //loop urls text Iterator text_itt = urlSummeries.entrySet().iterator(); while (text_itt.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry)text_itt.next(); String url = pairs.getKey(); String txtSummery = pairs.getValue(); try{ if(txtSummery!=null && !txtSummery.isEmpty()) { ArrayList<Topic> keytopics = keywordsExtractor.extractTopicsFromText(txtSummery, keywordsLimit); ArrayList<String> keywords = new ArrayList<String>(); for (Topic topic : keytopics) keywords.add(topic.getTitle()); //ArrayList<String> keywords = keywordsExtractor.extractTopicsFromText(txtSummery, keywordsLimit); urlKeywords.put(url, keywords); } else urlKeywords.put(url, new ArrayList<String>()); i=i++; //System.out.println(i); } catch(Exception e){ e.printStackTrace(); } } return urlKeywords; } public ArrayList<String> ListKeywords(Map urlKeywords){ //pool all keywords ArrayList<String> keywordsList= new ArrayList<String>(); Iterator keywords_itt = urlKeywords.entrySet().iterator(); while (keywords_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry)keywords_itt.next(); ArrayList<String> keywords = pairs.getValue(); for(String keyword : keywords){ if(!keywordsList.contains(keyword)) keywordsList.add(keyword); } } return keywordsList; } public Map KeywordDistribution(Map urlKeywords, ArrayList<String> keywordsList){ Map<String,Integer> keywords_distribution = new TreeMap<String,Integer>(); //String keyword_distribution_file = "testURLs_mega_distribution.csv"; //setup keyword map for(String keyword : keywordsList) keywords_distribution.put(keyword, 0); //get keyword distribution Iterator keywords_itt = urlKeywords.entrySet().iterator(); keywords_itt = urlKeywords.entrySet().iterator(); while (keywords_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry)keywords_itt.next(); ArrayList<String> keywords = pairs.getValue(); for(String keyword : keywords){ int count = (int)keywords_distribution.get(keyword) +1; keywords_distribution.put(keyword,count); } } //Sorted Treemap ValueComparator distoCompare = new ValueComparator(keywords_distribution); TreeMap<String,Integer> keywords_distribution_sorted = new TreeMap<String,Integer>(distoCompare); keywords_distribution_sorted.putAll(keywords_distribution); return keywords_distribution_sorted; } //largest to smallest class ValueComparator implements Comparator<String> { Map<String, Integer> base; public ValueComparator(Map<String, Integer> base) { this.base = base; } // Note: this comparator imposes orderings that are inconsistent with equals. public int compare(String a, String b) { if (base.get(a) >= base.get(b)) { return -1; } else { return 1; } // returning 0 would merge keys } } public Map KeywordMatricMap(Map urlKeywords, ArrayList<String> keywordsList){ Map keywordMatrixMap = new TreeMap(); //for all urls Iterator keywords_itt = urlKeywords.entrySet().iterator(); keywords_itt = urlKeywords.entrySet().iterator(); while (keywords_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry)keywords_itt.next(); String url = pairs.getKey(); ArrayList<String> urlkeywords = pairs.getValue(); ArrayList<Integer> keywordVector= new ArrayList<Integer>(); //for all keywords for(String keyword : keywordsList) if(urlkeywords.contains(keyword)) keywordVector.add(1); else keywordVector.add(0); int[] keywordArray = new int[keywordsList.size()]; for (int i=0; i < keywordsList.size(); i++) keywordArray[i] = keywordVector.get(i).intValue(); //place array in Map keywordMatrixMap.put(url,keywordArray); } return keywordMatrixMap; } public int[][] MaptoMatrix(Map keywordMatrixMap){ return null; } public void BuildTrainingDir(String dirPath, Map urlSummeries){ new File(dirPath).mkdir(); Iterator text_itt = urlSummeries.entrySet().iterator(); while (text_itt.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry)text_itt.next(); String url = pairs.getKey(); String summery = pairs.getValue(); long urlHash = foldingHash(url,2147483647); String urlHashStr = String.format("%10d", urlHash)+".txt"; try{ String hashName = dirPath+File.separator+urlHashStr; if(new File(hashName).exists()) System.out.println("collosion deteccted "+hashName); PrintWriter train_text = new PrintWriter(hashName, "US-ASCII"); train_text.println(summery); train_text.close(); } catch(Exception e){ e.printStackTrace(); } } } long foldingHash(String s, int M) { int intLength = s.length() / 4; long sum = 0; for (int j = 0; j < intLength; j++) { char c[] = s.substring(j * 4, (j * 4) + 4).toCharArray(); long mult = 1; for (int k = 0; k < c.length; k++) { sum += c[k] * mult; mult *= 256; } } char c[] = s.substring(intLength * 4).toCharArray(); long mult = 1; for (int k = 0; k < c.length; k++) { sum += c[k] * mult; mult *= 256; } return(Math.abs(sum) % M); } }
7,120
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
ArticleHandeler.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/ArticleHandeler.java
package com.frank0631.SemanticWebScraper; import de.l3s.boilerpipe.extractors.ArticleExtractor; import de.l3s.boilerpipe.sax.HTMLHighlighter; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //Scrapes articles from URLs public class ArticleHandeler { String storePath; public ArticleHandeler(String storePath){ System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); this.storePath=storePath; new File(storePath).mkdir(); ArticleExtractor articleExtractor = new ArticleExtractor(); HTMLHighlighter htmlHighlighter = HTMLHighlighter.newHighlightingInstance(); } public Map summeryMap(List<String> urls, int wordCountLimit, boolean cacheOnly) { Map url_text_map = new LinkedHashMap(); //loop urls Iterator<String> url_itt = urls.iterator(); while (url_itt.hasNext()) { String url = url_itt.next(); System.out.println("extracting " + url); try { String txt_summery = ArticleFetcher.extractorArticle(url, false, cacheOnly, storePath); if (txt_summery != null) { int summery_words = ArticleFetcher.countWords(txt_summery); if (summery_words >= wordCountLimit) url_text_map.put(url, txt_summery); else { System.out.print("Not enough words in " + url); url_text_map.put(url, null); } } } //ioe.printStackTrace(); catch (IOException ioe) { System.out.print("Could not reach " + url); url_text_map.put(url, null); //ioe.printStackTrace(); } catch (ArticleFetcher.UnsupportedExtension ioe) { System.out.print("Could not read " + url); url_text_map.put(url, null); } } return url_text_map; } public void cacheArticles(List<String> urls, int nThreads){ try { //FIXME multiple threads writing to disk seems like a bad idea ExecutorService executor = Executors.newFixedThreadPool(nThreads); Iterator<String> url_itt = urls.iterator(); while (url_itt.hasNext()) { String urlstr = url_itt.next(); Runnable urlFetcher = new ArticleFetcher(storePath,urlstr); executor.execute(urlFetcher); } executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(100); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Finished caching URLs"); } }
2,869
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLHandeler.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/URLHandeler.java
package com.frank0631.SemanticWebScraper; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; //Scrapes list of URLs public class URLHandeler { public URLHandeler() { } //TODO make this return URLCouples instead of writing to file public void readURLsFromBookmarks(String bookmarks_filename, String urlout_filename, boolean inHREF) { ArrayList<String> url_array = new ArrayList<String>(); File bookmarks_file = new File(bookmarks_filename); try { Scanner scanner = new Scanner(bookmarks_file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); Pattern p; if (inHREF) p = Pattern.compile("HREF=\"(.*?)\""); else p = Pattern.compile("http(.*)"); Matcher m = p.matcher(line); while (m.find()) { if (inHREF) url_array.add(m.group(1)); else url_array.add("http" + m.group(1)); } scanner.close(); } } catch (Exception e) { e.printStackTrace(); } try { PrintWriter extracted_urls = new PrintWriter(urlout_filename, "US-ASCII"); for (String url : url_array) extracted_urls.println(url); extracted_urls.close(); } catch (Exception e) { e.printStackTrace(); } } public URLCouples readURLFromFiles(String validfilename, String invalidfilename) { File validfile = new File(validfilename); File invalidfile = new File(invalidfilename); URLCouples urlCouples = new URLCouples(); try { BufferedReader validFileBufferedReader = new BufferedReader(new FileReader(validfile)); BufferedReader invalidFileBufferedReader = new BufferedReader(new FileReader(invalidfile)); for (String line; (line = validFileBufferedReader.readLine()) != null; ) urlCouples.ValidURLs.add(line); for (String line; (line = invalidFileBufferedReader.readLine()) != null; ) urlCouples.inValidURLs.add(line); } catch (Exception e) { e.printStackTrace(); } return urlCouples; } public URLCouples readURLrows(String readfilename, int nThreads) { File readfile = new File(readfilename); URLCouples urlCouples = new URLCouples(); if (readfile.exists()) try { BufferedReader br = new BufferedReader(new FileReader(readfilename)); ExecutorService executor = Executors.newFixedThreadPool(nThreads); //Multi Threaded URL Fetching for (String line; (line = br.readLine()) != null; ) { Runnable urlFetcher = new URLFetcher(urlCouples, line); executor.execute(urlFetcher); } executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(100); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Finished pinging URLs"); return urlCouples; } }
3,477
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLFetcher.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/URLFetcher.java
package com.frank0631.SemanticWebScraper; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; /** * Created by frank on 1/18/15. */ public class URLFetcher implements Runnable { public static int reachTimeoutSec = 3; public static int readTimeoutSec = 6; public static ArrayList<String> urlSchemas; static { urlSchemas = new ArrayList<String>(); urlSchemas.add("http://"); urlSchemas.add("http://www."); urlSchemas.add("https://"); urlSchemas.add("https://www."); } public URLCouples urlCouples; public String line; public URLFetcher(URLCouples urlCouples, String line){ this.urlCouples=urlCouples; this.line=line; } @Override public void run() { fetch(); } private void fetch() { try { String url_str= valid(line); if(url_str!=null && !urlCouples.ValidURLs.contains(url_str)) { urlCouples.ValidURLs.add(url_str); System.out.println("added to URL list: "+url_str); }else { urlCouples.inValidURLs.add(line); System.out.println("URL not valid: " + line); } } catch (Exception e) { e.printStackTrace(); } } public String valid(String url_str){ if (ping(url_str)) return url_str; for (String prefix : urlSchemas) if (ping(prefix + url_str)) return prefix + url_str; return null; } static public boolean ping(String url_str){ //false if malformed URL try { URL url = new URL(url_str); return ping(url); } catch (IOException ex){ return false; } } static public boolean ping(URL url){ //ping url, false if not responding or no connection try { final HttpURLConnection urlping = (HttpURLConnection) url.openConnection(); urlping.setConnectTimeout(1000 * reachTimeoutSec); urlping.setRequestMethod("GET"); urlping.setReadTimeout(1000 * readTimeoutSec); urlping.setInstanceFollowRedirects(false); urlping.connect(); urlping.disconnect(); if (urlping.getResponseCode() == HttpURLConnection.HTTP_OK) return true; return false; }catch (Exception ex){ return false; } } }
2,536
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
PrincipleComponentAnalysis.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/PrincipleComponentAnalysis.java
package com.frank0631.SemanticWebScraper;// @author Peter Abeles import org.ejml.interfaces.decomposition.*; import org.ejml.alg.dense.decomposition.*; import org.ejml.factory.DecompositionFactory; import org.ejml.data.DenseMatrix64F; import org.ejml.ops.CommonOps; import org.ejml.ops.NormOps; import org.ejml.ops.SingularOps; public class PrincipleComponentAnalysis { // principle component subspace is stored in the rows private DenseMatrix64F V_t; // how many principle components are used private int numComponents; // where the data is stored private DenseMatrix64F A = new DenseMatrix64F(1,1); private int sampleIndex; // mean values of each element across all the samples double mean[]; public PrincipleComponentAnalysis() { } /** * Must be called before any other functions. Declares and sets up internal data structures. * * @param numSamples Number of samples that will be processed. * @param sampleSize Number of elements in each sample. */ public void setup( int numSamples , int sampleSize ) { mean = new double[ sampleSize ]; A.reshape(numSamples,sampleSize,false); sampleIndex = 0; numComponents = -1; } /** * Adds a new sample of the raw data to internal data structure for later processing. All the samples * must be added before computeBasis is called. * * @param sampleData Sample from original raw data. */ public void addSample( double[] sampleData ) { if( A.getNumCols() != sampleData.length ) throw new IllegalArgumentException("Unexpected sample size"); if( sampleIndex >= A.getNumRows() ) throw new IllegalArgumentException("Too many samples"); for( int i = 0; i < sampleData.length; i++ ) { A.set(sampleIndex,i,sampleData[i]); } sampleIndex++; } /** * Computes a basis (the principle components) from the most dominant eigenvectors. * * @param numComponents Number of vectors it will use to describe the data. Typically much * smaller than the number of elements in the input vector. */ public void computeBasis( int numComponents ) { if( numComponents > A.getNumCols() ) throw new IllegalArgumentException("More components requested that the data's length."); if( sampleIndex != A.getNumRows() ) throw new IllegalArgumentException("Not all the data has been added"); if( numComponents > sampleIndex ) throw new IllegalArgumentException("More data needed to compute the desired number of components"); this.numComponents = numComponents; // compute the mean of all the samples for( int i = 0; i < A.getNumRows(); i++ ) { for( int j = 0; j < mean.length; j++ ) { mean[j] += A.get(i,j); } } for( int j = 0; j < mean.length; j++ ) { mean[j] /= A.getNumRows(); } // subtract the mean from the original data for( int i = 0; i < A.getNumRows(); i++ ) { for( int j = 0; j < mean.length; j++ ) { A.set(i,j,A.get(i,j)-mean[j]); } } // Compute SVD and save time by not computing U SingularValueDecomposition<DenseMatrix64F> svd = DecompositionFactory.svd(A.numRows, A.numCols, false, true, false); if( !svd.decompose(A) ) throw new RuntimeException("SVD failed"); V_t = svd.getV(null,true); DenseMatrix64F W = svd.getW(null); // Singular values are in an arbitrary order initially SingularOps.descendingOrder(null,false,W,V_t,true); // strip off unneeded components and find the basis V_t.reshape(numComponents,mean.length,true); } /** * Returns a vector from the PCA's basis. * * @param which Which component's vector is to be returned. * @return Vector from the PCA basis. */ public double[] getBasisVector( int which ) { if( which < 0 || which >= numComponents ) throw new IllegalArgumentException("Invalid component"); DenseMatrix64F v = new DenseMatrix64F(1,A.numCols); CommonOps.extract(V_t,which,which+1,0,A.numCols,v,0,0); return v.data; } /** * Converts a vector from sample space into eigen space. * * @param sampleData Sample space data. * @return Eigen space projection. */ public double[] sampleToEigenSpace( double[] sampleData ) { if( sampleData.length != A.getNumCols() ) throw new IllegalArgumentException("Unexpected sample length"); DenseMatrix64F mean = DenseMatrix64F.wrap(A.getNumCols(),1,this.mean); DenseMatrix64F s = new DenseMatrix64F(A.getNumCols(),1,true,sampleData); DenseMatrix64F r = new DenseMatrix64F(numComponents,1); CommonOps.sub(s,mean,s); CommonOps.mult(V_t,s,r); return r.data; } /** * Converts a vector from eigen space into sample space. * * @param eigenData Eigen space data. * @return Sample space projection. */ public double[] eigenToSampleSpace( double[] eigenData ) { if( eigenData.length != numComponents ) throw new IllegalArgumentException("Unexpected sample length"); DenseMatrix64F s = new DenseMatrix64F(A.getNumCols(),1); DenseMatrix64F r = DenseMatrix64F.wrap(numComponents,1,eigenData); CommonOps.multTransA(V_t,r,s); DenseMatrix64F mean = DenseMatrix64F.wrap(A.getNumCols(),1,this.mean); CommonOps.add(s,mean,s); return s.data; } /** * <p> * The membership error for a sample. If the error is less than a threshold then * it can be considered a member. The threshold's value depends on the data set. * </p> * <p> * The error is computed by projecting the sample into eigenspace then projecting * it back into sample space and * </p> * * @param sampleA The sample whose membership status is being considered. * @return Its membership error. */ public double errorMembership( double[] sampleA ) { double[] eig = sampleToEigenSpace(sampleA); double[] reproj = eigenToSampleSpace(eig); double total = 0; for( int i = 0; i < reproj.length; i++ ) { double d = sampleA[i] - reproj[i]; total += d*d; } return Math.sqrt(total); } /** * Computes the dot product of each basis vector against the sample. Can be used as a measure * for membership in the training sample set. High values correspond to a better fit. * * @param sample Sample of original data. * @return Higher value indicates it is more likely to be a member of input dataset. */ public double response( double[] sample ) { if( sample.length != A.numCols ) throw new IllegalArgumentException("Expected input vector to be in sample space"); DenseMatrix64F dots = new DenseMatrix64F(numComponents,1); DenseMatrix64F s = DenseMatrix64F.wrap(A.numCols,1,sample); CommonOps.mult(V_t,s,dots); return NormOps.normF(dots); } }
7,327
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLCouples.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/URLCouples.java
package com.frank0631.SemanticWebScraper; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by frank on 1/18/15. */ public class URLCouples{ public List<String> ValidURLs; public List<String> inValidURLs; public URLCouples(){ ValidURLs = Collections.synchronizedList(new ArrayList<String>()); inValidURLs = Collections.synchronizedList(new ArrayList<String>()); } }
447
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
semanticWebScraper.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/semanticWebScraper.java
package com.frank0631.SemanticWebScraper; import jgibblda.Estimator; import jgibblda.LDACmdOption; import weka.core.Instances; import weka.core.converters.ArffSaver; import weka.core.converters.CSVLoader; import java.io.File; import java.io.PrintWriter; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class semanticWebScraper { public static String regexCSV = "[^A-Za-z0-9() ]"; //hardcode for now String base_file_name = "frank_mega"; String url_file_name = base_file_name + "_urls.txt"; String valid_file_name = base_file_name + "_valid.txt"; String invalid_file_name = base_file_name + "_invalid.txt"; String distribution_file_name = base_file_name + "_distribution.csv"; String matrix_file_name = base_file_name + "_matrix.csv"; String arff_file_name = base_file_name + "_matrix.arff"; String LDADir = System.getProperty("user.dir")+File.separator+"LDA"; String JGIDDLDA_file_name = base_file_name + "_JGIDDLDA.txt"; ArrayList<String> URLs; ArrayList<String> Bad_URLs; Map url_text_map; int numClusters = 50; boolean cachedArticle = true; int wordCountLimit = 50; ArrayList<String> keywords_list; public semanticWebScraper() { try { URLCouples URLs; Map summeryMap; //get URLs URLHandeler urlHandel = new URLHandeler(); //URLs = urlHandel.readURLrows(url_file_name, 20); URLs = urlHandel.readURLFromFiles(valid_file_name, invalid_file_name); PrintWriter valid_file_writer = new PrintWriter(valid_file_name, "US-ASCII"); PrintWriter invalid_file_writer = new PrintWriter(invalid_file_name, "US-ASCII"); printArrayString(URLs.ValidURLs, valid_file_writer); printArrayString(URLs.inValidURLs, invalid_file_writer); valid_file_writer.close(); invalid_file_writer.close(); //get Summeries ArticleHandeler articleHandeler = new ArticleHandeler("URLs/"); if (!cachedArticle) articleHandeler.cacheArticles(URLs.ValidURLs, 10); summeryMap = articleHandeler.summeryMap(URLs.ValidURLs, wordCountLimit, cachedArticle); System.out.println("Number of URL Summeries " + summeryMap.size()); Map keywordMap; Map keywordDistro; Map keywordMatrixMap; ArrayList<String> keywords; ArrayList<String> keywords_sorted; KeywordHandeler keywordHandeler = new KeywordHandeler(); //keywordHandeler.BuildTrainingDir("frank_train",summeryMap); keywordHandeler.keywordsLimit = 40; keywordMap = keywordHandeler.ExtractKeywords(summeryMap); keywords = keywordHandeler.ListKeywords(keywordMap); keywordDistro = keywordHandeler.KeywordDistribution(keywordMap, keywords); keywords_sorted = new ArrayList<String>(keywordDistro.keySet()); keywordMatrixMap = keywordHandeler.KeywordMatricMap(keywordMap, keywords_sorted); PrintWriter distribution_file_writer = new PrintWriter(distribution_file_name, "US-ASCII"); PrintWriter matrix_file_writer = new PrintWriter(matrix_file_name, "US-ASCII"); PrintWriter JGIDDLDA_file_writer = new PrintWriter(LDADir+File.separator+JGIDDLDA_file_name, "US-ASCII"); printKeywordDistribution(keywordDistro, distribution_file_writer); printMatrixMap(keywords_sorted,keywordMatrixMap, matrix_file_writer, true, true); printKeywordJGIDDLDA(keywordMap,JGIDDLDA_file_writer); distribution_file_writer.close(); matrix_file_writer.close(); JGIDDLDA_file_writer.close(); CSVtoARFF(matrix_file_name, arff_file_name); //LDA File LDAFile = new File(LDADir); if(!LDAFile.exists() || !LDAFile.isDirectory()) LDAFile.mkdir(); LDACmdOption ldaOption = new LDACmdOption(); // ldaOption.inf = true; ldaOption.modelName = base_file_name+"model"; ldaOption.est = true; ldaOption.K = numClusters; ldaOption.dfile = JGIDDLDA_file_name; ldaOption.dir = LDADir; ldaOption.twords = keywords_sorted.size(); ldaOption.niters = 500; ldaOption.savestep = 500 + 1; Estimator e = new Estimator(); e.init(ldaOption); e.estimate(); // Inferencer inferencer = new Inferencer(); // inferencer.init(ldaOption); // // String [] test = {"politics bill clinton", "law court", "football match"}; // Model newModel = inferencer.inference(test); //LDADataset.readDataSet(matrix_file_name); } catch (Exception e) { e.printStackTrace(); } //build feature matrix //loop urls //plot in point cloud //k_means //graph representation } public static void main(String[] args) { semanticWebScraper sws = new semanticWebScraper(); } private static void printKeywordDistribution(Map<String, Integer> keywords_distribution, PrintWriter distribution_file_writer) { //print keyword distribution for (Map.Entry<String, Integer> keyword_entry : keywords_distribution.entrySet()) { String keyword_str = keyword_entry.getKey(); int keyword_count = keyword_entry.getValue(); distribution_file_writer.print(keyword_str.replaceAll(regexCSV, "") + ","); distribution_file_writer.print( keyword_count+ ","); for (int i = 0; i < keyword_count; i++) distribution_file_writer.print("|"); distribution_file_writer.println(); } } private static void printKeywordJGIDDLDA(Map<String, List<String>> keywordMap, PrintWriter printWriter) { int blankrows = 0; Iterator keywordsMap_itt = keywordMap.entrySet().iterator(); while (keywordsMap_itt .hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry) keywordsMap_itt.next(); if(pairs.getValue().size()==0) blankrows++; } printWriter.println(keywordMap.size()-blankrows); keywordsMap_itt = keywordMap.entrySet().iterator(); while (keywordsMap_itt .hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry) keywordsMap_itt .next(); String document = pairs.getKey(); ArrayList<String> keywords = pairs.getValue(); if(keywords.size()>0) { printWriter.print("\t"); for (String word : keywords) printWriter.print(word.replaceAll(regexCSV, "").replaceAll(" ","_")+" "); printWriter.println(); } } } private static void printMatrixMap(ArrayList<String> keywordsList, Map keywordMatrixMap, PrintWriter keyword_matrix_writer, boolean printHeader, boolean printURLs) { //print keyword distribution if (printHeader) { keyword_matrix_writer.print("Keywords header,hostname,"); for (int i = 0; i < keywordsList.size(); ++i) { String keyword = keywordsList.get(i); if (i + 1 == keywordsList.size()) keyword_matrix_writer.println(keyword); else keyword_matrix_writer.print("\"" + keyword + "\"" + ","); } } Iterator keywordsMatrix_itt = keywordMatrixMap.entrySet().iterator(); while (keywordsMatrix_itt.hasNext()) { Map.Entry<String, int[]> pairs = (Map.Entry) keywordsMatrix_itt.next(); String urlstr = pairs.getKey(); int[] keywordsArray = pairs.getValue(); if (printURLs) { String hostname = ""; try { URL url = new URL(urlstr); hostname = url.getHost(); } catch (Exception e) { e.printStackTrace(); } keyword_matrix_writer.print("\"" + urlstr + "\"" + "," + hostname + ","); } for (int i = 0; i < keywordsArray.length; ++i) { if (i + 1 == keywordsArray.length) keyword_matrix_writer.println(keywordsArray[i]); else keyword_matrix_writer.print(keywordsArray[i] + ","); } } } public static void printMapString(Map<String, String> stringMap, PrintWriter printWriter) { Iterator text_itt = stringMap.entrySet().iterator(); while (text_itt.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry) text_itt.next(); String key = pairs.getKey(); String txt = pairs.getValue(); printWriter.println(key + "," + txt); } } public static void printArrayString(List<String> arryStr, PrintWriter printWriter) { for (String str : arryStr) { printWriter.println(str); } } public static void printMapArray(Map<String, List<String>> arrayMap, PrintWriter printWriter) { Iterator text_itt = arrayMap.entrySet().iterator(); while (text_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry) text_itt.next(); String key = pairs.getKey(); printWriter.print(key + ","); ArrayList<String> strings = pairs.getValue(); for (String str : strings) { printWriter.print(str + ","); } printWriter.println(); } } public static void CSVtoARFF(String csvfilename, String arfffilename) { try { // load CSV CSVLoader loader = new CSVLoader(); loader.setSource(new File(csvfilename)); Instances data = loader.getDataSet(); // save ARFF ArffSaver saver = new ArffSaver(); saver.setInstances(data); saver.setFile(new File(arfffilename)); saver.setDestination(new File(arfffilename)); saver.writeBatch(); } catch (Exception e) { e.printStackTrace(); } } }
10,719
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLsFromBookmarks.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/URLsFromBookmarks.java
package com.frank0631.SemanticWebScraper; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; public class URLsFromBookmarks { public static void main(String[] args) { boolean inHREF = false; boolean plainText = true; String bookmarks_name = "bookmarks_frank_mega"; File file; if(plainText) file = new File(bookmarks_name+".txt"); else file = new File(bookmarks_name+".html"); try { PrintWriter extracted_urls = new PrintWriter(bookmarks_name+"_url_out.txt", "US-ASCII"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); Pattern p; if(inHREF) p = Pattern.compile("HREF=\"(.*?)\""); else p = Pattern.compile("http(.*)"); Matcher m = p.matcher(line); if (m.find()) for (int i = 1; i <= m.groupCount(); i++) { if(inHREF) extracted_urls.println(m.group(1)); else extracted_urls.println("http"+m.group(1)); } } scanner.close(); extracted_urls.close(); } catch (Exception e) { e.printStackTrace(); } } }
1,484
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
HelloPCA.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/HelloPCA.java
package com.frank0631.SemanticWebScraper; public class HelloPCA { public static void main(String[] args) { PrincipleComponentAnalysis pcsTest = new PrincipleComponentAnalysis(); double [ ] [ ] pc = { {-0.0971,-0.0178,0.0636 }, {1.3591,1.5820,-1.5266 }, {0.0149,-0.0178,0.0636 }, {1.1351,1.0487,-0.8905 }, {-0.0971,-0.0178,0.0636 }, {-0.0971,-0.0178,0.0636 }, {-0.9932,-0.8177,-0.8905 }, {-0.9932,-0.8177,1.0178 }, {-1.6653,-1.8842,1.9719 }, {-1.2173,-1.3509,1.6539 }, {2.0312,1.8486,-1.5266 }, {0.6870,0.5155,-0.2544 }, {-0.0971,-0.0178,0.0636 }, {0.0149,-0.0178,0.0636 }, {0.0149,-0.0178,0.0636}}; System.out.println(pc.length); //Print matrix for(int i=0;i<pc.length;i++){ for(int j=0;j<pc[i].length;j++) System.out.print(String.format("%f8", pc[i][j])+"\t"); System.out.println(); } System.out.println(); pcsTest.setup( 15 , 3 ); for(int i=0;i<pc.length;i++) pcsTest.addSample(pc[i]); pcsTest.computeBasis( 2); for(int i=0;i<2;i++){ double[] vec = pcsTest.getBasisVector(i); for(int j=0;j<vec.length;j++) System.out.print(String.format("%f8", vec[j])+"\t"); System.out.println(); } System.out.println("Hello, World"); } }
1,541
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
Printer.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/utils/Printer.java
package com.frank0631.SemanticWebScraper.utils; import java.io.PrintWriter; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Created by frank0631 on 2/21/15. */ public class Printer { public static String regexCSV = "[^A-Za-z0-9() ]"; public static void printKeywordDistribution(Map<String, Integer> keywords_distribution, PrintWriter distribution_file_writer) { //print keyword distribution for (Map.Entry<String, Integer> keyword_entry : keywords_distribution.entrySet()) { String keyword_str = keyword_entry.getKey(); int keyword_count = keyword_entry.getValue(); distribution_file_writer.print(keyword_str.replaceAll(regexCSV, "") + ","); distribution_file_writer.print(keyword_count + ","); for (int i = 0; i < keyword_count; i++) distribution_file_writer.print("|"); distribution_file_writer.println(); } } public static void printKeywordJGIDDLDA(Map<String, List<String>> keywordMap, PrintWriter printWriter) { int blankrows = 0; Iterator keywordsMap_itt = keywordMap.entrySet().iterator(); while (keywordsMap_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry) keywordsMap_itt.next(); if (pairs.getValue().size() == 0) blankrows++; } printWriter.println(keywordMap.size() - blankrows); keywordsMap_itt = keywordMap.entrySet().iterator(); while (keywordsMap_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry) keywordsMap_itt.next(); String document = pairs.getKey(); ArrayList<String> keywords = pairs.getValue(); if (keywords.size() > 0) { printWriter.print("\t"); for (String word : keywords) printWriter.print(word.replaceAll(regexCSV, "").replaceAll(" ", "_") + " "); printWriter.println(); } } } public static void printMatrixMap(ArrayList<String> keywordsList, Map keywordMatrixMap, PrintWriter keyword_matrix_writer, boolean printHeader, boolean printURLs) { //print keyword distribution if (printHeader) { keyword_matrix_writer.print("Keywords header,hostname,"); for (int i = 0; i < keywordsList.size(); ++i) { String keyword = keywordsList.get(i); if (i + 1 == keywordsList.size()) keyword_matrix_writer.println(keyword); else keyword_matrix_writer.print("\"" + keyword + "\"" + ","); } } Iterator keywordsMatrix_itt = keywordMatrixMap.entrySet().iterator(); while (keywordsMatrix_itt.hasNext()) { Map.Entry<String, int[]> pairs = (Map.Entry) keywordsMatrix_itt.next(); String urlstr = pairs.getKey(); int[] keywordsArray = pairs.getValue(); if (printURLs) { String hostname = ""; try { URL url = new URL(urlstr); hostname = url.getHost(); } catch (Exception e) { e.printStackTrace(); } keyword_matrix_writer.print("\"" + urlstr + "\"" + "," + hostname + ","); } for (int i = 0; i < keywordsArray.length; ++i) { if (i + 1 == keywordsArray.length) keyword_matrix_writer.println(keywordsArray[i]); else keyword_matrix_writer.print(keywordsArray[i] + ","); } } } public static void printMapString(Map<String, String> stringMap, PrintWriter printWriter) { Iterator text_itt = stringMap.entrySet().iterator(); while (text_itt.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry) text_itt.next(); String key = pairs.getKey(); String txt = pairs.getValue(); printWriter.println(key + "," + txt); } } public static void printArrayString(List<String> arryStr, PrintWriter printWriter) { for (String str : arryStr) { printWriter.println(str); } } public static void printMapArray(Map<String, List<String>> arrayMap, PrintWriter printWriter) { Iterator text_itt = arrayMap.entrySet().iterator(); while (text_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry) text_itt.next(); String key = pairs.getKey(); printWriter.print(key + ","); ArrayList<String> strings = pairs.getValue(); for (String str : strings) { printWriter.print(str + ","); } printWriter.println(); } } }
4,941
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLCouples.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/utils/URLCouples.java
package com.frank0631.SemanticWebScraper.utils; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by frank on 1/18/15. */ public class URLCouples { public List<String> ValidURLs; public List<String> inValidURLs; public URLCouples() { ValidURLs = Collections.synchronizedList(new ArrayList<String>()); inValidURLs = Collections.synchronizedList(new ArrayList<String>()); } }
455
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLNode.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/utils/URLNode.java
package com.frank0631.SemanticWebScraper.utils; import java.net.URL; import java.util.List; /** * Created by frank0631 on 2/21/15. */ public class URLNode { URL url; String hostname; String title; String url_str; List<String> topics; String summery; boolean valid; int[] keyword_vector; }
327
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLNodeSet.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/utils/URLNodeSet.java
package com.frank0631.SemanticWebScraper.utils; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class URLNodeSet { Map<String, URLNode> urlNodes; public URLNodeSet() { urlNodes = new LinkedHashMap<String, URLNode>(); } public int size() { return urlNodes.size(); } public void setURLCouples(URLCouples urls) { for (String validURL : urls.ValidURLs) { URLNode tmpNode = new URLNode(); //url_str as key tmpNode.url_str = validURL; try { URL url_tmp = new URL(validURL); tmpNode.url = url_tmp; tmpNode.hostname = url_tmp.getHost(); tmpNode.valid = true; urlNodes.put(validURL, tmpNode); } catch (MalformedURLException e) { e.printStackTrace(); } } } public void setSummeries(Map<String, String> summeryMap) { for (Map.Entry<String, String> entry : summeryMap.entrySet()) if (urlNodes.containsKey(entry.getKey())) urlNodes.get(entry.getKey()).summery = entry.getValue(); } public void setKeywords(Map<String, List<String>> keywordDistro) { for (Map.Entry<String, List<String>> entry : keywordDistro.entrySet()) if (urlNodes.containsKey(entry.getKey())) urlNodes.get(entry.getKey()).topics = entry.getValue(); } public void setKeywordVector(Map<String, int[]> keywordMatrixMap) { for (Map.Entry<String, int[]> entry : keywordMatrixMap.entrySet()) if (urlNodes.containsKey(entry.getKey())) urlNodes.get(entry.getKey()).keyword_vector = entry.getValue(); } }
1,821
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
ArticleFetcher.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/extractors/ArticleFetcher.java
package com.frank0631.SemanticWebScraper.extractors; import de.l3s.boilerpipe.BoilerpipeProcessingException; import de.l3s.boilerpipe.extractors.ArticleExtractor; import de.l3s.boilerpipe.sax.HTMLHighlighter; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; /** * Created by frank on 1/18/15. */ public class ArticleFetcher implements Runnable { public static String regexURL = "[^A-Za-z0-9()]"; public static int reachTimeoutSec = 3; public static int readTimeoutSec = 6; public static String[] skipExt = (new String[]{".pdf", ".doc", ".ppt"}); public static ArticleExtractor article_extractor; public static HTMLHighlighter html_highlighter; public String urlstr; public String storePath; public ArticleFetcher(String storePath, String urlstr) { //TODO pass in these two objects when threadsafe article_extractor = new ArticleExtractor(); html_highlighter = HTMLHighlighter.newHighlightingInstance(); this.storePath = storePath; this.urlstr = urlstr; } @Override public void run() { fetch(); } private void fetch() { try { htmlHilight(urlstr, true); extractorArticle(urlstr, true, false, storePath); System.out.println("cached " + urlstr); } catch (IOException ioe) { System.out.println("could not cache " + urlstr); //ioe.printStackTrace(); } catch (UnsupportedExtension ioe) { System.out.println("could not cache " + urlstr); //ioe.printStackTrace(); } } public String htmlHilight(String url_str, boolean write) throws IOException, UnsupportedExtension { for (String skip : skipExt) { if (url_str.toLowerCase().endsWith(skip)) throw new UnsupportedExtension("UnsupportedExtension " + skip); } String url_path = url_str.replaceAll(regexURL, "").toLowerCase(); String article_html_file = storePath + url_path + "/highlighted.html"; String article_html = null; URL url = new URL(url_str); File html_file = new File(article_html_file); if (html_file.exists())//read article_html = fileToString(html_file); else { if (URLFetcher.ping(url)) { try { article_html = html_highlighter.process(url, article_extractor); } catch (BoilerpipeProcessingException bpe) { article_html = ""; bpe.printStackTrace(); } catch (SAXException saxe) { article_html = ""; saxe.printStackTrace(); } if (write) { new File(storePath + url_path).mkdir(); PrintWriter out_html = new PrintWriter(article_html_file, "UTF-8"); out_html.println("<base href=\"" + url + "\" >"); out_html.println("<meta http-equiv=\"Content-Type\" content=\"text-html; charset=utf-8\" />"); out_html.println(article_html); out_html.close(); } } else return ""; } return article_html; } public static String extractorArticle(String url_str, boolean write, boolean cachedArticle, String storePath) throws IOException, UnsupportedExtension { for (String skip : skipExt) { if (url_str.toLowerCase().endsWith(skip)) throw new UnsupportedExtension("UnsupportedExtension " + skip); } String url_path = url_str.replaceAll(regexURL, "").toLowerCase(); String article_html_file = storePath + url_path + "/highlighted.html"; String article_html = null; File html_file; String article_text_file = storePath + url_path + "/text.txt"; String article_text; File text_file = new File(article_text_file); if (text_file.exists())//read article_text = fileToString(text_file); else { html_file = new File(article_html_file); if (html_file.exists()) { //read if html exist article_html = fileToString(html_file); try { article_text = article_extractor.getText(article_html); } catch (BoilerpipeProcessingException bpe) { article_text = ""; bpe.printStackTrace(); } } else if (cachedArticle == false) { //read if no html exist URL url = new URL(url_str); if (URLFetcher.ping(url)) try { article_text = article_extractor.getText(url); } catch (BoilerpipeProcessingException bpe) { article_text = ""; bpe.printStackTrace(); } else article_text = ""; //if no html exist set to blank } else article_text = ""; if (write) { new File(storePath + url_path).mkdir(); PrintWriter out_text = new PrintWriter(article_text_file, "US-ASCII"); out_text.println(article_text); out_text.close(); } } return article_text; } public static class UnsupportedExtension extends Exception { public UnsupportedExtension(String msg) { super(msg); } } public static String fileToString(File in) throws IOException { FileInputStream is = new FileInputStream(in); byte[] b = new byte[(int) in.length()]; is.read(b, 0, (int) in.length()); String contents = new String(b); is.close(); return contents; } public static int countWords(String summery) { String trimmed = summery.trim(); if (trimmed.isEmpty()) return 0; return trimmed.split("\\s+").length; } }
6,177
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
KeywordHandeler.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/extractors/KeywordHandeler.java
package com.frank0631.SemanticWebScraper.extractors; //import com.entopix.maui.main.MauiWrapper; //import com.entopix.maui.util.Topic; import com.entopix.maui.main.MauiWrapper; import com.entopix.maui.util.Topic; import java.io.File; import java.io.PrintWriter; import java.util.*; public class KeywordHandeler { String vocabularyName = "lcsh.rdf.gz"; String modelName = "SemEval2010"; //String modelName = "indexing_model"; //String vocabularyName = "wikipedia"; MauiWrapper keywordsExtractor; public int keywordsLimit = 30; public KeywordHandeler(){ //setup keywords extractor keywordsExtractor = new MauiWrapper(modelName,vocabularyName,"skos"); keywordsExtractor.setModelParameters(vocabularyName,null,null,null); } public Map ExtractKeywords(Map urlSummeries){ Map urlKeywords = new LinkedHashMap(); int i=0; //loop urls text Iterator text_itt = urlSummeries.entrySet().iterator(); while (text_itt.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry)text_itt.next(); String url = pairs.getKey(); String txtSummery = pairs.getValue(); try{ if(txtSummery!=null && !txtSummery.isEmpty()) { ArrayList<Topic> keytopics = keywordsExtractor.extractTopicsFromText(txtSummery, keywordsLimit); ArrayList<String> keywords = new ArrayList<String>(); for (Topic topic : keytopics) keywords.add(topic.getTitle()); //ArrayList<String> keywords = keywordsExtractor.extractTopicsFromText(txtSummery, keywordsLimit); urlKeywords.put(url, keywords); } else urlKeywords.put(url, new ArrayList<String>()); i=i++; //System.out.println(i); } catch(Exception e){ e.printStackTrace(); } } return urlKeywords; } public ArrayList<String> ListKeywords(Map urlKeywords){ //pool all keywords ArrayList<String> keywordsList= new ArrayList<String>(); Iterator keywords_itt = urlKeywords.entrySet().iterator(); while (keywords_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry)keywords_itt.next(); ArrayList<String> keywords = pairs.getValue(); for(String keyword : keywords){ if(!keywordsList.contains(keyword)) keywordsList.add(keyword); } } return keywordsList; } public Map KeywordDistribution(Map urlKeywords, ArrayList<String> keywordsList){ Map<String,Integer> keywords_distribution = new TreeMap<String,Integer>(); //String keyword_distribution_file = "testURLs_mega_distribution.csv"; //setup keyword map for(String keyword : keywordsList) keywords_distribution.put(keyword, 0); //get keyword distribution Iterator keywords_itt = urlKeywords.entrySet().iterator(); keywords_itt = urlKeywords.entrySet().iterator(); while (keywords_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry)keywords_itt.next(); ArrayList<String> keywords = pairs.getValue(); for(String keyword : keywords){ int count = (int)keywords_distribution.get(keyword) +1; keywords_distribution.put(keyword,count); } } //Sorted Treemap ValueComparator distoCompare = new ValueComparator(keywords_distribution); TreeMap<String,Integer> keywords_distribution_sorted = new TreeMap<String,Integer>(distoCompare); keywords_distribution_sorted.putAll(keywords_distribution); return keywords_distribution_sorted; } //largest to smallest class ValueComparator implements Comparator<String> { Map<String, Integer> base; public ValueComparator(Map<String, Integer> base) { this.base = base; } // Note: this comparator imposes orderings that are inconsistent with equals. public int compare(String a, String b) { if (base.get(a) >= base.get(b)) { return -1; } else { return 1; } // returning 0 would merge keys } } public Map KeywordMatricMap(Map urlKeywords, ArrayList<String> keywordsList){ Map keywordMatrixMap = new TreeMap(); //for all urls Iterator keywords_itt = urlKeywords.entrySet().iterator(); keywords_itt = urlKeywords.entrySet().iterator(); while (keywords_itt.hasNext()) { Map.Entry<String, ArrayList<String>> pairs = (Map.Entry)keywords_itt.next(); String url = pairs.getKey(); ArrayList<String> urlkeywords = pairs.getValue(); ArrayList<Integer> keywordVector= new ArrayList<Integer>(); //for all keywords for(String keyword : keywordsList) if(urlkeywords.contains(keyword)) keywordVector.add(1); else keywordVector.add(0); int[] keywordArray = new int[keywordsList.size()]; for (int i=0; i < keywordsList.size(); i++) keywordArray[i] = keywordVector.get(i).intValue(); //place array in Map keywordMatrixMap.put(url,keywordArray); } return keywordMatrixMap; } public int[][] MaptoMatrix(Map keywordMatrixMap){ return null; } public void BuildTrainingDir(String dirPath, Map urlSummeries){ new File(dirPath).mkdir(); Iterator text_itt = urlSummeries.entrySet().iterator(); while (text_itt.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry)text_itt.next(); String url = pairs.getKey(); String summery = pairs.getValue(); long urlHash = foldingHash(url,2147483647); String urlHashStr = String.format("%10d", urlHash)+".txt"; try{ String hashName = dirPath+File.separator+urlHashStr; if(new File(hashName).exists()) System.out.println("collosion deteccted "+hashName); PrintWriter train_text = new PrintWriter(hashName, "US-ASCII"); train_text.println(summery); train_text.close(); } catch(Exception e){ e.printStackTrace(); } } } long foldingHash(String s, int M) { int intLength = s.length() / 4; long sum = 0; for (int j = 0; j < intLength; j++) { char c[] = s.substring(j * 4, (j * 4) + 4).toCharArray(); long mult = 1; for (int k = 0; k < c.length; k++) { sum += c[k] * mult; mult *= 256; } } char c[] = s.substring(intLength * 4).toCharArray(); long mult = 1; for (int k = 0; k < c.length; k++) { sum += c[k] * mult; mult *= 256; } return(Math.abs(sum) % M); } }
7,224
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
ArticleHandeler.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/extractors/ArticleHandeler.java
package com.frank0631.SemanticWebScraper.extractors; import de.l3s.boilerpipe.extractors.ArticleExtractor; import de.l3s.boilerpipe.sax.HTMLHighlighter; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //Scrapes articles from URLs public class ArticleHandeler { String storePath; public ArticleHandeler(String storePath){ System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); this.storePath=storePath; new File(storePath).mkdir(); ArticleExtractor articleExtractor = new ArticleExtractor(); HTMLHighlighter htmlHighlighter = HTMLHighlighter.newHighlightingInstance(); } public Map<String,String> summeryMap(List<String> urls, int wordCountLimit, boolean cacheOnly) { Map url_text_map = new LinkedHashMap<String,String>(); //loop urls Iterator<String> url_itt = urls.iterator(); while (url_itt.hasNext()) { String url = url_itt.next(); System.out.println("extracting " + url); try { String txt_summery = ArticleFetcher.extractorArticle(url, false, cacheOnly, storePath); if (txt_summery != null) { int summery_words = ArticleFetcher.countWords(txt_summery); if (summery_words >= wordCountLimit) url_text_map.put(url, txt_summery); else { System.out.print("Not enough words in " + url); url_text_map.put(url, null); } } } //ioe.printStackTrace(); catch (IOException ioe) { System.out.print("Could not reach " + url); url_text_map.put(url, null); //ioe.printStackTrace(); } catch (ArticleFetcher.UnsupportedExtension ioe) { System.out.print("Could not read " + url); url_text_map.put(url, null); } } return url_text_map; } public void cacheArticles(List<String> urls, int nThreads){ try { //FIXME multiple threads writing to disk seems like a bad idea ExecutorService executor = Executors.newFixedThreadPool(nThreads); Iterator<String> url_itt = urls.iterator(); while (url_itt.hasNext()) { String urlstr = url_itt.next(); Runnable urlFetcher = new ArticleFetcher(storePath,urlstr); executor.execute(urlFetcher); } executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(100); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Finished caching URLs"); } }
2,910
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLHandeler.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/extractors/URLHandeler.java
package com.frank0631.SemanticWebScraper.extractors; import com.frank0631.SemanticWebScraper.utils.URLCouples; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; //Scrapes list of URLs public class URLHandeler { public URLHandeler() { } //TODO make this return URLCouples instead of writing to file public void readURLsFromBookmarks(String bookmarks_filename, String urlout_filename, boolean inHREF) { ArrayList<String> url_array = new ArrayList<String>(); File bookmarks_file = new File(bookmarks_filename); try { Scanner scanner = new Scanner(bookmarks_file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); Pattern p; if (inHREF) p = Pattern.compile("HREF=\"(.*?)\""); else p = Pattern.compile("http(.*)"); Matcher m = p.matcher(line); while (m.find()) { if (inHREF) url_array.add(m.group(1)); else url_array.add("http" + m.group(1)); } scanner.close(); } } catch (Exception e) { e.printStackTrace(); } try { PrintWriter extracted_urls = new PrintWriter(urlout_filename, "US-ASCII"); for (String url : url_array) extracted_urls.println(url); extracted_urls.close(); } catch (Exception e) { e.printStackTrace(); } } public URLCouples readURLFromFiles(String validfilename, String invalidfilename) { File validfile = new File(validfilename); File invalidfile = new File(invalidfilename); URLCouples urlCouples = new URLCouples(); try { BufferedReader validFileBufferedReader = new BufferedReader(new FileReader(validfile)); BufferedReader invalidFileBufferedReader = new BufferedReader(new FileReader(invalidfile)); for (String line; (line = validFileBufferedReader.readLine()) != null; ) urlCouples.ValidURLs.add(line); for (String line; (line = invalidFileBufferedReader.readLine()) != null; ) urlCouples.inValidURLs.add(line); } catch (Exception e) { e.printStackTrace(); } return urlCouples; } public URLCouples readURLrows(String readfilename, int nThreads) { File readfile = new File(readfilename); URLCouples urlCouples = new URLCouples(); if (readfile.exists()) try { BufferedReader br = new BufferedReader(new FileReader(readfilename)); ExecutorService executor = Executors.newFixedThreadPool(nThreads); //Multi Threaded URL Fetching for (String line; (line = br.readLine()) != null; ) { Runnable urlFetcher = new URLFetcher(urlCouples, line); executor.execute(urlFetcher); } executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(100); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Finished pinging URLs"); return urlCouples; } }
3,549
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLFetcher.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/extractors/URLFetcher.java
package com.frank0631.SemanticWebScraper.extractors; import com.frank0631.SemanticWebScraper.utils.URLCouples; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; /** * Created by frank on 1/18/15. */ public class URLFetcher implements Runnable { public static int reachTimeoutSec = 3; public static int readTimeoutSec = 6; public static ArrayList<String> urlSchemas; static { urlSchemas = new ArrayList<String>(); urlSchemas.add("http://"); urlSchemas.add("http://www."); urlSchemas.add("https://"); urlSchemas.add("https://www."); } public URLCouples urlCouples; public String line; public URLFetcher(URLCouples urlCouples, String line){ this.urlCouples=urlCouples; this.line=line; } @Override public void run() { fetch(); } private void fetch() { try { String url_str= valid(line); if(url_str!=null && !urlCouples.ValidURLs.contains(url_str)) { urlCouples.ValidURLs.add(url_str); System.out.println("added to URL list: "+url_str); }else { urlCouples.inValidURLs.add(line); System.out.println("URL not valid: " + line); } } catch (Exception e) { e.printStackTrace(); } } public String valid(String url_str){ if (ping(url_str)) return url_str; for (String prefix : urlSchemas) if (ping(prefix + url_str)) return prefix + url_str; return null; } static public boolean ping(String url_str){ //false if malformed URL try { URL url = new URL(url_str); return ping(url); } catch (IOException ex){ return false; } } static public boolean ping(URL url){ //ping url, false if not responding or no connection try { final HttpURLConnection urlping = (HttpURLConnection) url.openConnection(); urlping.setConnectTimeout(1000 * reachTimeoutSec); urlping.setRequestMethod("GET"); urlping.setReadTimeout(1000 * readTimeoutSec); urlping.setInstanceFollowRedirects(false); urlping.connect(); urlping.disconnect(); if (urlping.getResponseCode() == HttpURLConnection.HTTP_OK) return true; return false; }catch (Exception ex){ return false; } } }
2,606
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
PrincipleComponentAnalysis.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/extractors/PrincipleComponentAnalysis.java
package com.frank0631.SemanticWebScraper.extractors;// @author Peter Abeles import org.ejml.interfaces.decomposition.*; import org.ejml.alg.dense.decomposition.*; import org.ejml.factory.DecompositionFactory; import org.ejml.data.DenseMatrix64F; import org.ejml.ops.CommonOps; import org.ejml.ops.NormOps; import org.ejml.ops.SingularOps; public class PrincipleComponentAnalysis { // principle component subspace is stored in the rows private DenseMatrix64F V_t; // how many principle components are used private int numComponents; // where the data is stored private DenseMatrix64F A = new DenseMatrix64F(1,1); private int sampleIndex; // mean values of each element across all the samples double mean[]; public PrincipleComponentAnalysis() { } /** * Must be called before any other functions. Declares and sets up internal data structures. * * @param numSamples Number of samples that will be processed. * @param sampleSize Number of elements in each sample. */ public void setup( int numSamples , int sampleSize ) { mean = new double[ sampleSize ]; A.reshape(numSamples,sampleSize,false); sampleIndex = 0; numComponents = -1; } /** * Adds a new sample of the raw data to internal data structure for later processing. All the samples * must be added before computeBasis is called. * * @param sampleData Sample from original raw data. */ public void addSample( double[] sampleData ) { if( A.getNumCols() != sampleData.length ) throw new IllegalArgumentException("Unexpected sample size"); if( sampleIndex >= A.getNumRows() ) throw new IllegalArgumentException("Too many samples"); for( int i = 0; i < sampleData.length; i++ ) { A.set(sampleIndex,i,sampleData[i]); } sampleIndex++; } /** * Computes a basis (the principle components) from the most dominant eigenvectors. * * @param numComponents Number of vectors it will use to describe the data. Typically much * smaller than the number of elements in the input vector. */ public void computeBasis( int numComponents ) { if( numComponents > A.getNumCols() ) throw new IllegalArgumentException("More components requested that the data's length."); if( sampleIndex != A.getNumRows() ) throw new IllegalArgumentException("Not all the data has been added"); if( numComponents > sampleIndex ) throw new IllegalArgumentException("More data needed to compute the desired number of components"); this.numComponents = numComponents; // compute the mean of all the samples for( int i = 0; i < A.getNumRows(); i++ ) { for( int j = 0; j < mean.length; j++ ) { mean[j] += A.get(i,j); } } for( int j = 0; j < mean.length; j++ ) { mean[j] /= A.getNumRows(); } // subtract the mean from the original data for( int i = 0; i < A.getNumRows(); i++ ) { for( int j = 0; j < mean.length; j++ ) { A.set(i,j,A.get(i,j)-mean[j]); } } // Compute SVD and save time by not computing U SingularValueDecomposition<DenseMatrix64F> svd = DecompositionFactory.svd(A.numRows, A.numCols, false, true, false); if( !svd.decompose(A) ) throw new RuntimeException("SVD failed"); V_t = svd.getV(null,true); DenseMatrix64F W = svd.getW(null); // Singular values are in an arbitrary order initially SingularOps.descendingOrder(null,false,W,V_t,true); // strip off unneeded components and find the basis V_t.reshape(numComponents,mean.length,true); } /** * Returns a vector from the PCA's basis. * * @param which Which component's vector is to be returned. * @return Vector from the PCA basis. */ public double[] getBasisVector( int which ) { if( which < 0 || which >= numComponents ) throw new IllegalArgumentException("Invalid component"); DenseMatrix64F v = new DenseMatrix64F(1,A.numCols); CommonOps.extract(V_t,which,which+1,0,A.numCols,v,0,0); return v.data; } /** * Converts a vector from sample space into eigen space. * * @param sampleData Sample space data. * @return Eigen space projection. */ public double[] sampleToEigenSpace( double[] sampleData ) { if( sampleData.length != A.getNumCols() ) throw new IllegalArgumentException("Unexpected sample length"); DenseMatrix64F mean = DenseMatrix64F.wrap(A.getNumCols(),1,this.mean); DenseMatrix64F s = new DenseMatrix64F(A.getNumCols(),1,true,sampleData); DenseMatrix64F r = new DenseMatrix64F(numComponents,1); CommonOps.sub(s,mean,s); CommonOps.mult(V_t,s,r); return r.data; } /** * Converts a vector from eigen space into sample space. * * @param eigenData Eigen space data. * @return Sample space projection. */ public double[] eigenToSampleSpace( double[] eigenData ) { if( eigenData.length != numComponents ) throw new IllegalArgumentException("Unexpected sample length"); DenseMatrix64F s = new DenseMatrix64F(A.getNumCols(),1); DenseMatrix64F r = DenseMatrix64F.wrap(numComponents,1,eigenData); CommonOps.multTransA(V_t,r,s); DenseMatrix64F mean = DenseMatrix64F.wrap(A.getNumCols(),1,this.mean); CommonOps.add(s,mean,s); return s.data; } /** * <p> * The membership error for a sample. If the error is less than a threshold then * it can be considered a member. The threshold's value depends on the data set. * </p> * <p> * The error is computed by projecting the sample into eigenspace then projecting * it back into sample space and * </p> * * @param sampleA The sample whose membership status is being considered. * @return Its membership error. */ public double errorMembership( double[] sampleA ) { double[] eig = sampleToEigenSpace(sampleA); double[] reproj = eigenToSampleSpace(eig); double total = 0; for( int i = 0; i < reproj.length; i++ ) { double d = sampleA[i] - reproj[i]; total += d*d; } return Math.sqrt(total); } /** * Computes the dot product of each basis vector against the sample. Can be used as a measure * for membership in the training sample set. High values correspond to a better fit. * * @param sample Sample of original data. * @return Higher value indicates it is more likely to be a member of input dataset. */ public double response( double[] sample ) { if( sample.length != A.numCols ) throw new IllegalArgumentException("Expected input vector to be in sample space"); DenseMatrix64F dots = new DenseMatrix64F(numComponents,1); DenseMatrix64F s = DenseMatrix64F.wrap(A.numCols,1,sample); CommonOps.mult(V_t,s,dots); return NormOps.normF(dots); } }
7,338
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
URLsFromBookmarks.java
/FileExtraction/Java_unseen/frank0631_semantic-web-scraper/app/src/main/java/com/frank0631/SemanticWebScraper/extractors/URLsFromBookmarks.java
package com.frank0631.SemanticWebScraper.extractors; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; public class URLsFromBookmarks { public static void main(String[] args) { boolean inHREF = false; boolean plainText = true; String bookmarks_name = "bookmarks_frank_mega"; File file; if(plainText) file = new File(bookmarks_name+".txt"); else file = new File(bookmarks_name+".html"); try { PrintWriter extracted_urls = new PrintWriter(bookmarks_name+"_url_out.txt", "US-ASCII"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); Pattern p; if(inHREF) p = Pattern.compile("HREF=\"(.*?)\""); else p = Pattern.compile("http(.*)"); Matcher m = p.matcher(line); if (m.find()) for (int i = 1; i <= m.groupCount(); i++) { if(inHREF) extracted_urls.println(m.group(1)); else extracted_urls.println("http"+m.group(1)); } } scanner.close(); extracted_urls.close(); } catch (Exception e) { e.printStackTrace(); } } }
1,495
Java
.java
frank0631/semantic-web-scraper
9
9
0
2014-10-17T05:10:02Z
2015-03-21T12:57:34Z
InstrProxy.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/lib/InstrProxy.java
/* * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.lib; import com.sun.tdk.jcov.Instr; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import static java.io.File.pathSeparator; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; public class InstrProxy { private final Path outputDir; public InstrProxy(Path outputDir) { this.outputDir = outputDir; } public void copyBytecode(String... classes) throws IOException { byte[] buf = new byte[1024]; for(String c : classes) { String classFile = classFile(c); try(InputStream in = InstrProxy.class.getClassLoader().getResourceAsStream(classFile)) { Path o = outputDir.resolve(classFile); if(!Files.exists(o.getParent())) Files.createDirectories(o.getParent()); try(OutputStream out = Files.newOutputStream(o)) { int read; while((read = in.read(buf)) > 0) out.write(buf, 0, read); } } }; } public int instr(String[] options, Consumer<String> outConsumer, Consumer<String> errConsumer, String... classes) throws IOException, InterruptedException { if(!Files.exists(outputDir) || !Files.isDirectory(outputDir)) { Files.createDirectories(outputDir); } //this does not work because //Warning: Add input source(s) to the classpath: -cp jcov.jar:... // List<String> params = new ArrayList<>(); // params.addAll(List.of(options)); // params.addAll(Arrays.stream(classes).map(c -> outputDir.resolve(classFile(c)).toString()).collect(toList())); // System.out.println(params.stream().collect(Collectors.joining(" "))); // new Instr().run(params.toArray(new String[0])); List<String> files = Arrays.stream(classes).map(this::classFile) .map(outputDir::resolve) .map(Path::toString) .collect(toList()); List<String> command = new ArrayList<>(); command.add(System.getProperty("java.home") + "/bin/java"); command.add("-Djcov.selftest=true"); command.add("-Djcov.stacktrace=true"); command.add("-cp"); command.add(System.getProperty("java.class.path") + pathSeparator + files.stream() .collect(joining(pathSeparator))); command.add(Instr.class.getName()); command.addAll(Arrays.asList(options)); command.addAll(files); System.out.println(command.stream().collect(joining(" "))); ProcessBuilder pb = new ProcessBuilder().command(command.toArray(new String[0])); if(outConsumer == null) pb = pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); if(errConsumer == null) pb = pb.redirectError(ProcessBuilder.Redirect.INHERIT); Process p = pb.start(); if(outConsumer != null) { try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while((line = in.readLine()) != null) outConsumer.accept(line); } } if(errConsumer != null) { try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream()))) { String line; while((line = in.readLine()) != null) errConsumer.accept(line); } } return p.waitFor(); } public String classFile(String className) { return className.replace('.', '/') + ".class"; } public Class runClass(String className, String[] argv) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { ClassLoader offOutputDir = new InstrumentedClassLoader(); Class cls = offOutputDir.loadClass(className); Method m = cls.getMethod("main", new String[0].getClass()); m.invoke(null, (Object)argv); return cls; } private class InstrumentedClassLoader extends ClassLoader { protected InstrumentedClassLoader() { super(InstrProxy.class.getClassLoader()); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { Path classFile = outputDir.resolve(classFile(name)); if(Files.exists(classFile)) { byte[] buf = new byte[1024]; try(InputStream in = Files.newInputStream(classFile)) { try(ByteArrayOutputStream out = new ByteArrayOutputStream()) { int read; while((read = in.read(buf)) > 0) out.write(buf, 0, read); return defineClass(name, out.toByteArray(), 0, out.size()); } } catch (IOException e) { throw new RuntimeException(e); } } return super.loadClass(name); } } }
6,822
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
PrivacyTest.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/report/dataprocessor/privacy/PrivacyTest.java
/* * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.dataprocessor.privacy; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.DataPackage; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.processing.DefaultDataProcessorSPI; import com.sun.tdk.jcov.processing.ProcessingException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class PrivacyTest { static DataRoot data; static String template; @BeforeClass public static void setup() { template = PrivacyTest.class.getPackageName() .replace(".", "/") + "/privacy_template.xml"; } @Test public void load() throws FileFormatException { data = Reader.readXML(ClassLoader.getSystemResourceAsStream(template)); DataPackage p = data.findPackage("pkg"); DataClass tc1 = p.findClass("TestCode$1"); assertTrue(tc1.findMethod("publicMethod").getModifiers().isPublic()); DataClass tc2 = p.findClass("TestCode$1"); assertTrue(tc2.findMethod("publicMethod").getModifiers().isPublic()); DataClass tcInner = p.findClass("TestCode$Inner"); assertTrue(tcInner.findMethod("publicMethod").getModifiers().isPublic()); } @Test(dependsOnMethods = "load") public void transform() throws ProcessingException { data = new DefaultDataProcessorSPI().getDataProcessor().process(data); DataPackage p = data.findPackage("pkg"); DataClass tc = p.findClass("TestCode"); assertTrue(tc.findMethod("$1.publicMethod").getModifiers().isPublic()); assertTrue(tc.findMethod("$2.publicMethod").getModifiers().isPublic()); assertTrue(tc.findMethod("$Inner.publicMethod").getModifiers().isPublic()); } }
3,192
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
SyntheticityTest.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/report/dataprocessor/syntheticity/SyntheticityTest.java
/* * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.dataprocessor.syntheticity; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataPackage; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.processing.DefaultDataProcessorSPI; import com.sun.tdk.jcov.processing.ProcessingException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class SyntheticityTest { static DataRoot data; static String template; @BeforeClass public static void setup() { template = SyntheticityTest.class.getPackageName() .replace(".", "/") + "/synthetic_template.xml"; } @Test public void load() throws FileFormatException { data = Reader.readXML(ClassLoader.getSystemResourceAsStream(template)); DataPackage p = data.findPackage("package"); DataClass sc1 = p.findClass("SyntheticityClass$SyntheticClass"); assertTrue(sc1.findMethod("syntheticMethod").getModifiers().isSynthetic()); assertFalse(sc1.findMethod("nonSyntheticMethod").getModifiers().isSynthetic()); DataClass sc2 = p.findClass("SyntheticityClass$NonSyntheticClass"); assertTrue(sc2.findMethod("syntheticMethod").getModifiers().isSynthetic()); assertFalse(sc2.findMethod("nonSyntheticMethod").getModifiers().isSynthetic()); } @Test(dependsOnMethods = "load") public void transform() throws ProcessingException { data = new DefaultDataProcessorSPI().getDataProcessor().process(data); DataPackage p = data.findPackage("package"); DataClass sc = p.findClass("SyntheticityClass"); assertTrue(sc.findMethod("$SyntheticClass.syntheticMethod").getModifiers().isSynthetic()); assertFalse(sc.findMethod("$SyntheticClass.nonSyntheticMethod").getModifiers().isSynthetic()); assertTrue(sc.findMethod("$NonSyntheticClass.syntheticMethod").getModifiers().isSynthetic()); assertFalse(sc.findMethod("$NonSyntheticClass.nonSyntheticMethod").getModifiers().isSynthetic()); } }
3,439
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
BuiltInAncFiltersTest.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/report/ancfilters/BuiltInAncFiltersTest.java
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.report.AncFilter; import com.sun.tdk.jcov.report.AncFilterFactory; import org.testng.annotations.Test; import java.util.Collection; import static org.testng.Assert.assertTrue; public class BuiltInAncFiltersTest { static final AncFilterFactory factory = new BuiltInAncFilters(); @Test public void testInstantiate() { assertTrue(factory.instantiate("setter") instanceof SetterANCFilter); assertTrue(factory.instantiate("getter") instanceof GetterANCFilter); } @Test public void testInstantiateAll() { Collection<AncFilter> filters = factory.instantiateAll(); assertTrue(filters.stream().anyMatch(f -> f instanceof CatchANCFilter)); assertTrue(filters.stream().anyMatch(f -> f instanceof DeprecatedANCFilter)); assertTrue(filters.stream().noneMatch(f -> f instanceof ListANCFilter)); } }
2,140
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ListANCFilterTest.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/report/ancfilters/ListANCFilterTest.java
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethodEntryOnly; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertFalse; public class ListANCFilterTest { private String createListFile(String[] lines) throws IOException { Path file = Files.createTempFile("ListANCFilterTest", ".lst"); BufferedWriter out = Files.newBufferedWriter(file, Charset.defaultCharset()); for(String ln : lines) { out.write(ln);out.newLine(); } out.close(); file.toFile().deleteOnExit(); return file.toAbsolutePath().toString(); } @Test public void testNormal() throws IOException { ListANCFilter filter = new ListANCFilter(); String[] data = { "#normal", //a method "java/lang/String#indexOf(I)I", //a constructor "java/lang/Math#<init>()V", }; filter.setParameter(createListFile(data)); assertEquals(filter.getAncReason(), "normal"); DataClass stringDataClass = new DataClass(0, "java/lang/String", "java.base", 0, false); assertFalse(filter.accept(stringDataClass)); assertTrue(filter.accept(stringDataClass, new DataMethodEntryOnly(stringDataClass, 0, "indexOf", "(I)I", "", new String[0], 0))); DataClass mathDataClass = new DataClass(2, "java/lang/Math", "java.base", 0, false); assertTrue(filter.accept(mathDataClass, new DataMethodEntryOnly(mathDataClass, 0, "<init>", "()V", "", new String[0], 0))); } @Test public void testNested() throws IOException { ListANCFilter filter = new ListANCFilter(); String[] data = { "#nested", //a nested class "java/lang/System$LoggerFinder#checkPermission()Ljava/lang/Void;" }; filter.setParameter(createListFile(data)); assertEquals(filter.getAncReason(), "nested"); DataClass systemDataClass = new DataClass(2, "java/lang/System", "java.base", 0, false); assertTrue(filter.accept(systemDataClass, new DataMethodEntryOnly(systemDataClass, 0, "$LoggerFinder.checkPermission", "()Ljava/lang/Void;", "", new String[0], 0))); } @DataProvider(name="unreadable") public Object[][] unreadableLists() { return new Object[][] { {new String[] {"java/lang/String#indexOf(I)I"}}, {new String[] {"data", "java/lang/String#indexOf(I)I"}}, {new String[] {"#data", "java/lang/String/indexOf(I)I"}}, {null} }; } @Test(dataProvider = "unreadable", expectedExceptions = {IllegalStateException.class, IllegalArgumentException.class}) public void testNotRead(String[] data) throws IllegalStateException, IOException { String file; if(data == null) file = null; else file = createListFile(data); new ListANCFilter().setParameter(file); } @DataProvider(name="readable") public Object[][] readableLists() { String indexOfLine = "java/lang/String#indexOf(I)I"; String[] indexOfElements = {"java/lang/String", "indexOf", "(I)I"}; String constructorLine = "java/lang/Math#<init>()V"; String[] constructorElements = {"java/lang/Math", "<init>", "()V"}; return new Object[][] { {new String[] {"#data0", indexOfLine}, "data0", new String[][] {indexOfElements}}, {new String[] {"#data1", "", constructorLine}, "data1", new String[][] {constructorElements}}, {new String[] {"#data2", indexOfLine, constructorLine, ""}, "data2", new String[][] {indexOfElements, constructorElements}}, {new String[] {"#data3"}, "data3", new String[][] {}} }; } @Test(dataProvider = "readable") public void testRead(String[] data, String reason, String[][] elements) throws IllegalStateException, IOException { ListANCFilter filter = new ListANCFilter(); filter.setParameter(createListFile(data)); assertEquals(filter.getAncReason(), reason); for(String[] el : elements) { DataClass dataClass = new DataClass(2, el[0], "java.base", 0, false); assertTrue(filter.accept(dataClass, new DataMethodEntryOnly(dataClass, 0, el[1], el[2], "", new String[0], 0))); } } @Test(expectedExceptions = IllegalStateException.class) public void testUninitiated() { new ListANCFilter().accept(new DataClass(0, "java/lang/String", "java.base", 0, false)); } @Test(expectedExceptions = IllegalStateException.class) public void testReasonUninitiated() { new ListANCFilter().getAncReason(); } }
6,491
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Util.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/Util.java
/* * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; public class Util { private final Path outputDir; public Util(Path dir) { outputDir = dir; } public List<Path> copyBytecode(String... classes) throws IOException { byte[] buf = new byte[1024]; List<Path> result = new ArrayList<>(); for(String c : classes) { String classFile = classFile(c); try(InputStream in = getClass().getClassLoader().getResourceAsStream(classFile)) { Path o = outputDir.resolve(classFile); result.add(o); if(!Files.exists(o.getParent())) Files.createDirectories(o.getParent()); try(OutputStream out = Files.newOutputStream(o)) { int read; while((read = in.read(buf)) > 0) out.write(buf, 0, read); } } }; return result; } public static Path copyJRE(Path src) throws IOException { Path dest = Files.createTempDirectory("JDK"); System.out.println("Copying a JDK from " + src + " to " + dest); Files.walk(src).forEach(s -> { try { Files.copy(s, dest.resolve(src.relativize(s)), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new UncheckedIOException(e); } }); return dest; } public static Path createRtJar(String prefix, Class collect) throws IOException { Path dest = Files.createTempFile(prefix, ".jar"); System.out.println(prefix + " jar: " + dest); try(JarOutputStream jar = new JarOutputStream(Files.newOutputStream(dest))) { jar.putNextEntry(new JarEntry(collect.getName().replace(".", File.separator) + ".class")); try (InputStream ci = collect.getClassLoader() .getResourceAsStream(collect.getName().replace('.', '/') + ".class")) { byte[] buffer = new byte[1024]; int read; while((read = ci.read(buffer)) > 0) { jar.write(buffer, 0, read); } } } return dest; } public static String classFile(String className) { return className.replace('.', '/') + ".class"; } public Class runClass(Class className, String[] argv) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { return runClass(className.getName(), argv); } public Class runClass(String className, String[] argv) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { ClassLoader offOutputDir = new InstrumentedClassLoader(); Class cls = offOutputDir.loadClass(className); Method m = cls.getMethod("main", new String[0].getClass()); m.invoke(null, (Object)argv); return cls; } private class InstrumentedClassLoader extends ClassLoader { protected InstrumentedClassLoader() { super(Util.class.getClassLoader()); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { Path classFile = outputDir.resolve(classFile(name)); if(Files.exists(classFile)) { byte[] buf = new byte[1024]; try(InputStream in = Files.newInputStream(classFile)) { try(ByteArrayOutputStream out = new ByteArrayOutputStream()) { int read; while((read = in.read(buf)) > 0) out.write(buf, 0, read); return defineClass(name, out.toByteArray(), 0, out.size()); } } catch (IOException e) { throw new RuntimeException(e); } } return super.loadClass(name); } } public static void rmRF(Path jre) throws IOException { System.out.println("Removing " + jre); if(Files.isRegularFile(jre)) Files.deleteIfExists(jre); else Files.walkFileTree(jre, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } }
7,049
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
IntrumentNestHostTest.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/IntrumentNestHostTest.java
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument; import java.io.OutputStream; import java.lang.reflect.Method; import java.math.BigDecimal; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import com.sun.tdk.jcov.Instr; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.runtime.Collect; import org.testng.Assert; import org.testng.annotations.Test; public class IntrumentNestHostTest { @Test public void testNestHostMembers() throws Exception { Path temp = Files.createTempDirectory("jcov"); Path template = temp.resolve("template.xml"); Path classes = temp.resolve("classes"); Files.createDirectories(classes); try (OutputStream out = Files.newOutputStream(classes.resolve("Simple.class"))) { out.write(SIMPLE_CLASS); } try (OutputStream out = Files.newOutputStream(classes.resolve("Simple$I.class"))) { out.write(SIMPLE$I_CLASS); } Path outDir = temp.resolve("out"); Files.createDirectories(outDir); Instr instr = new Instr(); instr.setTemplate(template.toFile().getAbsolutePath()); instr.instrumentFile(classes.toFile(), outDir.toFile(), null); instr.finishWork(); Assert.assertNotEquals(Files.size(outDir.resolve("Simple.class")), Files.size(classes.resolve("Simple.class")), "File size should differ."); Assert.assertNotEquals(Files.size(outDir.resolve("Simple$I.class")), Files.size(classes.resolve("Simple$I.class")), "File size should differ."); Collect.enableCounts(); //reset if (new BigDecimal(System.getProperty("java.class.version")).compareTo(new BigDecimal("55.0")) >= 0) { //run the code, and check coverage outcome: ClassLoader cl = new URLClassLoader(new URL[] {outDir.toUri().toURL()}); Class<?> simple = Class.forName("Simple", false, cl); Method run = simple.getMethod("run"); run.invoke(null); DataRoot root = Reader.readXML(template.toFile().getAbsolutePath(), true, null); int blocks = 0; for (DataClass dc : root.getClasses()) { for (DataMethod dm : dc.getMethods()) { if ("<init>".equals(dm.name)) continue; for (DataBlock db : dm.getBlocks()) { Assert.assertEquals(Collect.countFor(db.slot), 1); blocks++; } } } Assert.assertEquals(blocks, 3); } else { System.err.println("Warning: skipping run of the test sample, as the runtime JDK cannot handle classfiles version 55."); } } //classfiles based on: //public class Simple { // public static void run() { // I.run(); // } // private static class I { // public static void run() { // d(); // } // private static void d() {} // } //} private static final byte[] SIMPLE_CLASS = new byte[] { (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x37, (byte) 0x00, (byte) 0x15, (byte) 0x0A, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x10, (byte) 0x0A, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x11, (byte) 0x07, (byte) 0x00, (byte) 0x12, (byte) 0x07, (byte) 0x00, (byte) 0x13, (byte) 0x07, (byte) 0x00, (byte) 0x14, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x49, (byte) 0x01, (byte) 0x00, (byte) 0x0C, (byte) 0x49, (byte) 0x6E, (byte) 0x6E, (byte) 0x65, (byte) 0x72, (byte) 0x43, (byte) 0x6C, (byte) 0x61, (byte) 0x73, (byte) 0x73, (byte) 0x65, (byte) 0x73, (byte) 0x01, (byte) 0x00, (byte) 0x06, (byte) 0x3C, (byte) 0x69, (byte) 0x6E, (byte) 0x69, (byte) 0x74, (byte) 0x3E, (byte) 0x01, (byte) 0x00, (byte) 0x03, (byte) 0x28, (byte) 0x29, (byte) 0x56, (byte) 0x01, (byte) 0x00, (byte) 0x04, (byte) 0x43, (byte) 0x6F, (byte) 0x64, (byte) 0x65, (byte) 0x01, (byte) 0x00, (byte) 0x0F, (byte) 0x4C, (byte) 0x69, (byte) 0x6E, (byte) 0x65, (byte) 0x4E, (byte) 0x75, (byte) 0x6D, (byte) 0x62, (byte) 0x65, (byte) 0x72, (byte) 0x54, (byte) 0x61, (byte) 0x62, (byte) 0x6C, (byte) 0x65, (byte) 0x01, (byte) 0x00, (byte) 0x03, (byte) 0x72, (byte) 0x75, (byte) 0x6E, (byte) 0x01, (byte) 0x00, (byte) 0x0A, (byte) 0x53, (byte) 0x6F, (byte) 0x75, (byte) 0x72, (byte) 0x63, (byte) 0x65, (byte) 0x46, (byte) 0x69, (byte) 0x6C, (byte) 0x65, (byte) 0x01, (byte) 0x00, (byte) 0x0B, (byte) 0x53, (byte) 0x69, (byte) 0x6D, (byte) 0x70, (byte) 0x6C, (byte) 0x65, (byte) 0x2E, (byte) 0x6A, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x01, (byte) 0x00, (byte) 0x0B, (byte) 0x4E, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x4D, (byte) 0x65, (byte) 0x6D, (byte) 0x62, (byte) 0x65, (byte) 0x72, (byte) 0x73, (byte) 0x0C, (byte) 0x00, (byte) 0x08, (byte) 0x00, (byte) 0x09, (byte) 0x0C, (byte) 0x00, (byte) 0x0C, (byte) 0x00, (byte) 0x09, (byte) 0x01, (byte) 0x00, (byte) 0x06, (byte) 0x53, (byte) 0x69, (byte) 0x6D, (byte) 0x70, (byte) 0x6C, (byte) 0x65, (byte) 0x01, (byte) 0x00, (byte) 0x10, (byte) 0x6A, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2F, (byte) 0x6C, (byte) 0x61, (byte) 0x6E, (byte) 0x67, (byte) 0x2F, (byte) 0x4F, (byte) 0x62, (byte) 0x6A, (byte) 0x65, (byte) 0x63, (byte) 0x74, (byte) 0x01, (byte) 0x00, (byte) 0x08, (byte) 0x53, (byte) 0x69, (byte) 0x6D, (byte) 0x70, (byte) 0x6C, (byte) 0x65, (byte) 0x24, (byte) 0x49, (byte) 0x00, (byte) 0x21, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x08, (byte) 0x00, (byte) 0x09, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1D, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, (byte) 0x2A, (byte) 0xB7, (byte) 0x00, (byte) 0x01, (byte) 0xB1, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x0B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x09, (byte) 0x00, (byte) 0x0C, (byte) 0x00, (byte) 0x09, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0xB8, (byte) 0x00, (byte) 0x02, (byte) 0xB1, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x0B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x0E, (byte) 0x00, (byte) 0x0F, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x0A }; private static final byte[] SIMPLE$I_CLASS = new byte[] { (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x37, (byte) 0x00, (byte) 0x16, (byte) 0x0A, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x0F, (byte) 0x0A, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x10, (byte) 0x07, (byte) 0x00, (byte) 0x11, (byte) 0x07, (byte) 0x00, (byte) 0x14, (byte) 0x01, (byte) 0x00, (byte) 0x06, (byte) 0x3C, (byte) 0x69, (byte) 0x6E, (byte) 0x69, (byte) 0x74, (byte) 0x3E, (byte) 0x01, (byte) 0x00, (byte) 0x03, (byte) 0x28, (byte) 0x29, (byte) 0x56, (byte) 0x01, (byte) 0x00, (byte) 0x04, (byte) 0x43, (byte) 0x6F, (byte) 0x64, (byte) 0x65, (byte) 0x01, (byte) 0x00, (byte) 0x0F, (byte) 0x4C, (byte) 0x69, (byte) 0x6E, (byte) 0x65, (byte) 0x4E, (byte) 0x75, (byte) 0x6D, (byte) 0x62, (byte) 0x65, (byte) 0x72, (byte) 0x54, (byte) 0x61, (byte) 0x62, (byte) 0x6C, (byte) 0x65, (byte) 0x01, (byte) 0x00, (byte) 0x03, (byte) 0x72, (byte) 0x75, (byte) 0x6E, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x64, (byte) 0x01, (byte) 0x00, (byte) 0x0A, (byte) 0x53, (byte) 0x6F, (byte) 0x75, (byte) 0x72, (byte) 0x63, (byte) 0x65, (byte) 0x46, (byte) 0x69, (byte) 0x6C, (byte) 0x65, (byte) 0x01, (byte) 0x00, (byte) 0x0B, (byte) 0x53, (byte) 0x69, (byte) 0x6D, (byte) 0x70, (byte) 0x6C, (byte) 0x65, (byte) 0x2E, (byte) 0x6A, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x01, (byte) 0x00, (byte) 0x08, (byte) 0x4E, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x48, (byte) 0x6F, (byte) 0x73, (byte) 0x74, (byte) 0x07, (byte) 0x00, (byte) 0x15, (byte) 0x0C, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x06, (byte) 0x0C, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x06, (byte) 0x01, (byte) 0x00, (byte) 0x08, (byte) 0x53, (byte) 0x69, (byte) 0x6D, (byte) 0x70, (byte) 0x6C, (byte) 0x65, (byte) 0x24, (byte) 0x49, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x49, (byte) 0x01, (byte) 0x00, (byte) 0x0C, (byte) 0x49, (byte) 0x6E, (byte) 0x6E, (byte) 0x65, (byte) 0x72, (byte) 0x43, (byte) 0x6C, (byte) 0x61, (byte) 0x73, (byte) 0x73, (byte) 0x65, (byte) 0x73, (byte) 0x01, (byte) 0x00, (byte) 0x10, (byte) 0x6A, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2F, (byte) 0x6C, (byte) 0x61, (byte) 0x6E, (byte) 0x67, (byte) 0x2F, (byte) 0x4F, (byte) 0x62, (byte) 0x6A, (byte) 0x65, (byte) 0x63, (byte) 0x74, (byte) 0x01, (byte) 0x00, (byte) 0x06, (byte) 0x53, (byte) 0x69, (byte) 0x6D, (byte) 0x70, (byte) 0x6C, (byte) 0x65, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1D, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, (byte) 0x2A, (byte) 0xB7, (byte) 0x00, (byte) 0x01, (byte) 0xB1, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x09, (byte) 0x00, (byte) 0x09, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0xB8, (byte) 0x00, (byte) 0x02, (byte) 0xB1, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x07, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x08, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x19, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xB1, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x09, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x0B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x0C, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x0E, (byte) 0x00, (byte) 0x13, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x0E, (byte) 0x00, (byte) 0x12, (byte) 0x00, (byte) 0x0A }; }
14,153
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JREInstrTest.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/jreinstr/JREInstrTest.java
/* * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.jreinstr; import com.sun.tdk.jcov.JREInstr; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.DataPackage; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.instrument.Util; import com.sun.tdk.jcov.io.Reader; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class JREInstrTest { Path jre; Path userCode; static void createUserCode(Path location, Class code) throws IOException { String fileName = code.getName().replace('.', '/') + ".class"; Path classFile = location.resolve(fileName); Files.createDirectories(classFile.getParent()); try (InputStream ci = code.getClassLoader().getResourceAsStream(fileName); OutputStream out = Files.newOutputStream(classFile)) { byte[] buffer = new byte[1024]; int read; while ((read = ci.read(buffer)) > 0) { out.write(buffer, 0, read); } } } @BeforeClass public void setup() throws IOException, InterruptedException { String testJRE = System.getProperty("test.jre"); if(testJRE == null) { testJRE = System.getProperty("java.home"); } jre = Util.copyJRE(Paths.get(testJRE)); userCode = Paths.get("user_code"); createUserCode(userCode, Code.class); } @Test public void testJREInstr() throws IOException, InterruptedException { String runtime = Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator)) .peek(System.out::println) .filter(s -> s.endsWith("jcov_file_saver.jar")).findAny().get(); String[] params = new String[] { "-implantrt", runtime, "-im", "java.base", jre.toString()}; System.out.println("Running JREInstr with " + Arrays.stream(params).collect(Collectors.joining(" "))); long start = System.currentTimeMillis(); assertEquals(new JREInstr().run(params), 0); //track instrumentation time for the TODO in copyJRE System.out.println("Took " + (System.currentTimeMillis() - start) + " to instrument."); } @Test(dependsOnMethods = "testJREInstr") public void testInstrumentation() throws IOException, InterruptedException { List<String> command = List.of( jre.toString() + File.separator + "bin" + File.separator + "java", "-cp", userCode.toAbsolutePath().toString(), Code.class.getName()); System.out.println(command.stream().collect(Collectors.joining(" "))); new ProcessBuilder() .command(command) .redirectError(ProcessBuilder.Redirect.INHERIT) .start().waitFor(); assertTrue(Files.exists(Paths.get("result.xml"))); } @Test(dependsOnMethods = "testInstrumentation") public void testCoverage() throws IOException, InterruptedException, FileFormatException { DataRoot data = Reader.readXML(Files.newInputStream(Paths.get("result.xml"))); DataPackage pkg = data.getPackages().stream().filter(p -> p.getName().equals("javax/swing")).findAny().get(); DataClass cls = pkg.getClasses().stream().filter(c -> c.getName().equals("JFrame")) .findAny().get(); DataMethod method = cls.getMethods().stream().filter(m -> m.getName().equals("<init>") && m.getVmSignature().equals("()V") ).findFirst().get(); assertEquals(method.getCount(), 1); } @AfterClass public void tearDown() throws IOException { if(jre != null && Files.exists(jre)) Util.rmRF(jre); if(userCode != null && Files.exists(userCode)) Util.rmRF(userCode); Files.deleteIfExists(Paths.get("result.xml")); } }
5,580
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Code.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/jreinstr/Code.java
/* * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.jreinstr; import javax.swing.JFrame; public class Code { public static void main(String[] args) { new JFrame(); System.out.println("User code has been executed."); } }
1,437
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
FieldsClass.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/plugin/FieldsClass.java
/* * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.plugin; /** * This is a test class which is instrumented during the test. */ public class FieldsClass { int field1; String field2 = ""; public void setField1(int field1) { this.field1 = field1; } public void setField2(String field2) { this.field2 = field2; } public static void main(String[] args) { FieldsClass ac = new FieldsClass(); ac.field1 = 1; ac.field2 = "one"; ac.setField1(2); ac.setField2("two"); } }
1,749
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
FieldsTest.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/plugin/FieldsTest.java
/* * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.plugin; import com.sun.tdk.jcov.lib.InstrProxy; import org.testng.annotations.Test; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static com.sun.tdk.jcov.instrument.plugin.FieldsPlugin.INSTRUMENTATION_COMPLETE; import static java.lang.Integer.parseInt; import static java.util.stream.Collectors.joining; import static org.testng.Assert.*; /** * Tests that it is possible to use instrumentation plugin and a corresponding data saver. */ public class FieldsTest { Path test_dir; InstrProxy instr; /** * Perform the instrumentation. */ @Test public void instrument() throws IOException, InterruptedException { test_dir = Paths.get(System.getProperty("user.dir")).resolve("plugin_test"); instr = new InstrProxy(test_dir); instr.copyBytecode(FieldsClass.class.getName()); System.getProperties().setProperty("jcov.selftest", "true"); int[] instrumentationCompleteTimes = new int[1]; instr.instr(new String[]{"-instr_plugin", FieldsPlugin.class.getName()}, line -> { if(line.startsWith(INSTRUMENTATION_COMPLETE)) instrumentationCompleteTimes[0] = parseInt(line.substring(INSTRUMENTATION_COMPLETE.length())); }, null, FieldsClass.class.getName()); assertEquals(instrumentationCompleteTimes[0], 1); //this does not work because //Warning: Add input source(s) to the classpath: -cp jcov.jar:... //see InstrProxy class for more info //assertEquals(FieldsPlugin.completeCount.intValue(), 1); } /** * Check collected field values at runtime in the same VM. */ @Test(dependsOnMethods = "instrument") public void fields() throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { instr.runClass(FieldsClass.class.getName(), new String[0]); Set<Object> set = new HashSet<Object>(){{ add(1); add(2); }}; testFieldValuesSameVM("field1", set); set = new HashSet<Object>(){{ add(""); add("two"); add("one"); }}; testFieldValuesSameVM("field2", set); } private void testFieldValuesSameVM(String field, Set<Object> values) { String fullName = FieldsClass.class.getName().replace('.','/') + "." + field; testFieldValues(fullName, field, values, FieldsPlugin.values.get(fullName)); } /** * Test that data saver is called. */ @Test(dependsOnMethods = "instrument") public void testSaver() throws IOException, InterruptedException { List<String> command = new ArrayList<>(); command.add(System.getProperty("java.home") + "/bin/java"); command.add("-Djcov.data-saver="+FieldsPlugin.class.getName()); command.add("-cp"); command.add(test_dir + File.pathSeparator + System.getProperty("java.class.path")); command.add(FieldsClass.class.getName()); System.out.println(command.stream().collect(joining(" "))); Process p = new ProcessBuilder().command(command.toArray(new String[0])) .redirectError(ProcessBuilder.Redirect.INHERIT) .start(); try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) { List<String> lines = in.lines().collect(Collectors.toList()); Set<Object> set = new HashSet<Object>(){{ add(1); add(2); }}; testFieldValuesOtherVM("field1", set, lines); set = new HashSet<Object>(){{ add(""); add("two"); add("one"); }}; testFieldValuesOtherVM("field2", set, lines); } assertEquals(p.waitFor(), 0); } private void testFieldValuesOtherVM(String field, Set<Object> values, List<String> lines) { String fullName = FieldsClass.class.getName().replace('.','/') + "." + field; testFieldValues(fullName, field, values.stream().map(Object::toString).collect(Collectors.toSet()), lines.stream().filter(l -> l.startsWith(fullName + "=")) .map(l -> l.substring(fullName.length() + 1)) .collect(Collectors.toSet())); } private void testFieldValues(String fullName, String field, Set<Object> values, Set<Object> actual) { if(values.size() == 0) { assertFalse(FieldsPlugin.values.containsKey(fullName), "No values for field " + fullName); } else { assertNotNull(actual); System.out.printf("Comparing [%s] with [%s]\n", values.stream().map(Object::toString).collect(joining(",")), actual.stream().map(Object::toString).collect(joining(","))); assertEquals(values.size(), actual.size(), "size"); assertTrue(values.stream().allMatch(actual::contains), "content is the same"); } } }
6,509
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
FieldsPlugin.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/plugin/FieldsPlugin.java
/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.plugin; import com.sun.tdk.jcov.instrument.asm.ASMInstrumentationPlugin; import com.sun.tdk.jcov.runtime.JCovSaver; import org.objectweb.asm.MethodVisitor; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.String.format; import static org.objectweb.asm.Opcodes.*; /** * An instrumentation plugin which saves some information about fields and methods used during execution. * This plugin inserts calls to specific mathod after every PUTFIELD bytecode instruction. * This plugin only supports Object and int data types. * This class also defines the logic to be used at runtime to save the collected data by printing it into the output. */ public class FieldsPlugin implements ASMInstrumentationPlugin, JCovSaver { public static final Map<String, Set<Object>> values = new HashMap<>(); public static final String INSTRUMENTATION_COMPLETE = "Instrumentation complete: "; public static void recordFieldValue(Object value, String field) { Set<Object> fieldValues = values.getOrDefault(field, new HashSet<>()); if(values.containsKey(field)) { fieldValues = values.get(field); } else { fieldValues = new HashSet<>(); values.put(field, fieldValues); } fieldValues.add(value); } // @Override public MethodVisitor methodVisitor(int access, String owner, String name, String desc, MethodVisitor visitor) { return new MethodVisitor(ASM6, visitor) { @Override public void visitFieldInsn(int opcode, String owner, String name, String descriptor) { if(opcode == PUTFIELD) { super.visitInsn(DUP); if(!descriptor.startsWith("L")) { switch (descriptor) { case "I": super.visitMethodInsn(INVOKESTATIC, Integer.class.getName().replace(".", "/"), "valueOf", "(I)Ljava/lang/Integer;", false); break; } } super.visitLdcInsn(format("%s.%s", owner, name)); super.visitMethodInsn(INVOKESTATIC, FieldsPlugin.class.getName().replace('.', '/'), "recordFieldValue", "(Ljava/lang/Object;Ljava/lang/String;)V", false); } super.visitFieldInsn(opcode, owner, name, descriptor); } }; } final static AtomicInteger completeCount = new AtomicInteger(0); @Override public void instrumentationComplete() throws Exception { completeCount.incrementAndGet(); System.out.println(INSTRUMENTATION_COMPLETE + completeCount); } @Override public Path runtime() { return null; } @Override public String collectorPackage() { return null; } @Override public void saveResults() { values.entrySet().forEach(e -> e.getValue().forEach(v -> System.out.println(e.getKey() + "=" + v))); } }
4,514
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JREInstrTest.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/plugin/jreinstr/JREInstrTest.java
/* * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.plugin.jreinstr; import com.sun.tdk.jcov.JREInstr; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.Arrays; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.stream.Collectors; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class JREInstrTest { public static final String TIMES_SAVED = "TIMES SAVED "; public static final String TIMES_CALLED = "TIMES CALLED "; Path rtJar; Path jre; private Path copyJRE(Path src) throws IOException, InterruptedException { Path dest = Files.createTempDirectory("JDK"); System.out.println("Copying " + src + " to " + dest); Files.walk(src).forEach(s -> { try { Files.copy(s, dest.resolve(src.relativize(s)), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new UncheckedIOException(e); } }); return dest; //TODO make this to work, as it would be a whole lot faster //a JDK created by jimage can not be used, it fails with //Command line error: bootmodules.jimage was not found in modules directory //see CODETOOLS-7903016 // Path dest = Files.createTempDirectory("test_data"); // Path res = dest.resolve("jdk"); // List<String> command = List.of( // src.toString() + File.separator + "bin" + File.separator + "jlink", // "--add-modules", "java.base,java.compiler", // "--output", res.toString() // ); // System.out.println(command.stream().collect(Collectors.joining(" "))); // assertEquals(new ProcessBuilder(command) // .redirectError(ProcessBuilder.Redirect.INHERIT) // .redirectInput(ProcessBuilder.Redirect.INHERIT) // .start().waitFor(), 0); // return res; } private void removeJRE(Path jre) throws IOException { System.out.println("Removing " + jre); Files.walkFileTree(jre, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } static Path createRtJar(String prefix, Class collect) throws IOException { Path dest = Files.createTempFile(prefix, ".jar"); System.out.println(prefix + " jar: " + dest); try(JarOutputStream jar = new JarOutputStream(Files.newOutputStream(dest))) { jar.putNextEntry(new JarEntry(collect.getName().replace(".", File.separator) + ".class")); try (InputStream ci = collect.getClassLoader() .getResourceAsStream(collect.getName().replace('.', '/') + ".class")) { byte[] buffer = new byte[1024]; int read; while((read = ci.read(buffer)) > 0) { jar.write(buffer, 0, read); } } } return dest; } @BeforeClass public void setup() throws IOException, InterruptedException { String testJRE = System.getProperty("test.jre"); if(testJRE == null) { testJRE = System.getProperty("java.home"); } rtJar = createRtJar("jcov-rt-", Collect.class); jre = copyJRE(Paths.get(testJRE)); } @Test public void testJREInstr() throws IOException, InterruptedException { TestPlugin.reset(); String runtime = Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator)) .peek(System.out::println) .filter(s -> s.endsWith("jcov_network_saver.jar")).findAny().get(); String[] params = new String[] { "-implantrt", runtime, "-instr_plugin", TestPlugin.class.getName(), "-im", "java.base", jre.toString()}; System.out.println("Running JREInstr with " + Arrays.stream(params).collect(Collectors.joining(" "))); long start = System.currentTimeMillis(); assertEquals(new JREInstr().run(params), 0); //track instrumentation time for the TODO in copyJRE System.out.println("Took " + (System.currentTimeMillis() - start) + " to instrument."); assertEquals(TestPlugin.savedTimes.intValue(), 1); assertTrue(TestPlugin.calledTimes.get() > 0); } @Test(dependsOnMethods = "testJREInstr") public void testInstrumentation() throws IOException, InterruptedException { //no classpath necessary for the next call because the class is implanted List<String> command = List.of( jre.toString() + File.separator + "bin" + File.separator + "java", Collect.class.getName()); System.out.println(command.stream().collect(Collectors.joining(" "))); Process p = new ProcessBuilder() .command(command) .redirectError(ProcessBuilder.Redirect.INHERIT) .start(); boolean jcovExported = false; boolean pluginExported = false; try(BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while((line = in.readLine()) != null && !(jcovExported && pluginExported)) { System.out.println(line); if(line.equals(Collect.class.getPackage().getName())) pluginExported = true; if(line.equals(com.sun.tdk.jcov.runtime.Collect.class.getPackage().getName())) jcovExported = true; } } p.waitFor(); assertTrue(pluginExported && jcovExported); } @AfterClass public void tearDown() throws IOException { if(jre != null && Files.exists(jre)) removeJRE(jre); if(rtJar != null && Files.exists(rtJar)) Files.delete(rtJar); } }
8,335
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
TestPlugin.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/plugin/jreinstr/TestPlugin.java
/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.plugin.jreinstr; import com.sun.tdk.jcov.instrument.asm.ASMInstrumentationPlugin; import org.objectweb.asm.MethodVisitor; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Path; import java.util.concurrent.atomic.AtomicInteger; public class TestPlugin implements ASMInstrumentationPlugin { public static AtomicInteger calledTimes = new AtomicInteger(0); public static AtomicInteger savedTimes = new AtomicInteger(0); public static Path rt; static { try { rt = JREInstrTest.createRtJar("plugin-rt-", Collect.class); } catch (IOException e) { throw new UncheckedIOException(e); } } public static void reset() { calledTimes.set(0); savedTimes.set(0); } @Override public MethodVisitor methodVisitor(int access, String owner, String name, String desc, MethodVisitor visitor) { calledTimes.incrementAndGet(); return visitor; } @Override public void instrumentationComplete() throws Exception { savedTimes.incrementAndGet(); } @Override public Path runtime() { return rt; } @Override public String collectorPackage() { return Collect.class.getPackage().getName(); } }
2,535
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Collect.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/plugin/jreinstr/Collect.java
/* * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.plugin.jreinstr; import java.lang.module.ModuleDescriptor; public class Collect { //this is called from the test to test that the necessary changes has been done by the instarumentation public static void main(String[] args) { Object.class.getModule().getDescriptor().exports().stream().filter(e -> !e.isQualified()) .map(ModuleDescriptor.Exports::source) .forEach(System.out::println); } }
1,688
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
UserCode.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/instr/UserCode.java
/* * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.instr; public class UserCode { private static int count = 0; public static void main(String[] args) { if(args[0].equals("-")) count--; else if(args[0].equals("+")) count++; System.out.println("User code is running."); } }
1,502
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
InstrTest.java
/FileExtraction/Java_unseen/openjdk_jcov/test/unit/com/sun/tdk/jcov/instrument/instr/InstrTest.java
/* * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument.instr; import com.sun.tdk.jcov.Instr; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.instrument.Util; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.runtime.Collect; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static org.testng.Assert.assertTrue; public class InstrTest { Path test_dir; Path template; int method_slot = -1; @BeforeClass public void clean() throws IOException { System.setProperty("jcov.selftest", "true"); Path data_dir = Paths.get(System.getProperty("user.dir")); test_dir = data_dir.resolve("instr_test"); System.out.println("test dir = " + test_dir); Util.rmRF(test_dir); template = test_dir.resolve("template.lst"); } @Test public void instrument() throws IOException, InterruptedException, FileFormatException { List<String> params = new ArrayList<>(); params.add("-t"); params.add(template.toString()); params.add(new Util(test_dir).copyBytecode(UserCode.class.getName()).get(0).toString()); new Instr().run(params.toArray(new String[0])); DataRoot data = Reader.readXML(template.toString()); DataMethod dm = data.getPackages().stream().filter(p -> p.getName().equals("com/sun/tdk/jcov/instrument/instr")).findAny().get() .getClasses().stream().filter(c -> c.getName().equals("UserCode")).findAny().get() .getMethods().stream().filter(m -> m.getName().equals("main")).findAny().get(); method_slot = dm.getSlot(); assertTrue(method_slot > 0); } @Test(dependsOnMethods = "instrument") public void run() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException, InstantiationException { new Util(test_dir).runClass(UserCode.class, new String[] {"+"}); assertTrue(Collect.wasHit(method_slot)); } @AfterClass public void tearDown() throws IOException { Util.rmRF(test_dir); } }
3,670
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
TestDemoApp2.java
/FileExtraction/Java_unseen/openjdk_jcov/examples/tutorial/test/TestDemoApp2.java
import com.oracle.demoapp.Plane; public class TestDemoApp2{ public static void main(String[] args){ Plane plane = new Plane(); if (plane.countGreenFiguresArea() != 0) { throw new RuntimeException("TestDemoApp2 test failed!"); } else { System.out.println("TestDemoApp2 test passed"); } } }
357
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
TestDemoApp1.java
/FileExtraction/Java_unseen/openjdk_jcov/examples/tutorial/test/TestDemoApp1.java
import com.oracle.demoapp.Plane; import com.oracle.demoapp.figures.Disk; import com.oracle.demoapp.figures.Square; public class TestDemoApp1{ public static void main(String[] args){ Plane plane = new Plane(); Square square = new Square(2, "Red"); Disk disc = new Disk(3, "Green"); plane.addFigure(square); plane.addFigure(disc); if (plane.countRedFiguresArea() != 4) { throw new RuntimeException("TestDemoApp1 test failed!"); } else { System.out.println("TestDemoApp1 test passed"); } } }
589
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Plane.java
/FileExtraction/Java_unseen/openjdk_jcov/examples/tutorial/src/com/oracle/demoapp/Plane.java
package com.oracle.demoapp; import com.oracle.demoapp.figures.abstractpack.Figure; import java.util.ArrayList; public class Plane { ArrayList<Figure> figures; public Plane(){ figures = new ArrayList<Figure>(); } public void addFigure(Figure figure){ figures.add(figure); } public double countRedFiguresArea(){ double result = 0; for (Figure figure : figures){ if ("red".equals(figure.getColorName().toLowerCase())){ result+=figure.getArea(); } } return result; } public double countGreenFiguresArea(){ double result = 0; for (Figure figure : figures){ if ("green".equals(figure.getColorName().toLowerCase())){ result+=figure.getArea(); } } return result; } }
864
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Square.java
/FileExtraction/Java_unseen/openjdk_jcov/examples/tutorial/src/com/oracle/demoapp/figures/Square.java
package com.oracle.demoapp.figures; import com.oracle.demoapp.figures.abstractpack.Figure; public class Square extends Figure { private int length; public Square(int l, String color){ length = l; setColorName(color); } @Override public double getArea() { return length * length; } }
335
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Disk.java
/FileExtraction/Java_unseen/openjdk_jcov/examples/tutorial/src/com/oracle/demoapp/figures/Disk.java
package com.oracle.demoapp.figures; import com.oracle.demoapp.figures.abstractpack.Figure; public class Disk extends Figure { private int length; public Disk(int l, String color){ length = l; setColorName(color); } @Override public double getArea() { return Math.PI*length*length; } }
337
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Figure.java
/FileExtraction/Java_unseen/openjdk_jcov/examples/tutorial/src/com/oracle/demoapp/figures/abstractpack/Figure.java
package com.oracle.demoapp.figures.abstractpack; public abstract class Figure{ private String colorName; public Figure(){ } public String getColorName(){ return colorName; } public void setColorName(String colorName){ this.colorName = colorName; } public abstract double getArea(); }
338
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JTObserver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/jcov/JTObserver.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jcov; import com.sun.javatest.Harness; import com.sun.javatest.Parameters; import com.sun.javatest.TestResult; import com.sun.javatest.TestResult.Section; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; /** * * @author Andrey Titov */ public class JTObserver implements Harness.Observer { private static int port = 3337; public static final int SAVE = 0; public static final int NAME = 1; private static final HashSet<ClientData> clientsData = new HashSet<ClientData>(); private static volatile String currentname = null; private static volatile boolean saving = false; private static volatile boolean naming = false; public JTObserver() { new Thread(new Runnable() { @Override public void run() { try { ServerSocket listener = new ServerSocket(port); try { while (true) { new Handler(listener.accept()).start(); } } finally { listener.close(); } } catch (Exception e){ log("Socket server exception: "+e); } } }).start(); } public void startingTestRun(Parameters prmtrs) { log("Starting test run"); } public void startingTest(TestResult tr) { send(tr.getTestName(), NAME); tr.addObserver(new TestResult.Observer() { public void createdSection(TestResult tr, Section sctn) { } public void completedSection(TestResult tr, Section sctn) { } public void createdOutput(TestResult tr, Section sctn, String string) { } public void completedOutput(TestResult tr, Section sctn, String string) { } public void updatedOutput(TestResult tr, Section sctn, String string, int i, int i1, String string1) { } public void updatedProperty(TestResult tr, String string, String string1) { } public void completed(TestResult tr) { send(tr.getTestName(), SAVE); } }); log("Starting test " + tr.getTestName()); } public void finishedTest(TestResult tr) { log("Finished test " + tr.getTestName()); } public void stoppingTestRun() { log("Stopping testrun"); } public void finishedTesting() { log("Finished testing"); } public void finishedTestRun(boolean bln) { log("Finished testrun"); } public void error(String string) { log("error"); } private static void log(String str) { //System.out.println(str); } private void send(String name, int command) { log("send name="+name + " command = "+command); log("clientsData.size() ="+clientsData.size()); if (command == JTObserver.NAME) { currentname = name; naming = true; while (!nameClientsData()){ try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized (clientsData){ for (ClientData clientData :clientsData){ clientData.setNamed(false); } } } if (command == JTObserver.SAVE) { saving = true; currentname = name; while (!saveClientsData()){ try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized (clientsData){ for (ClientData clientData :clientsData){ clientData.setSaved(false); } } } log("end send"); } private boolean nameClientsData(){ synchronized (clientsData){ for (ClientData clientData : clientsData){ if (!clientData.isNamed()) return false; } if (clientsData.size() != 0) naming = false; return true; } } private boolean saveClientsData(){ synchronized (clientsData){ for (ClientData clientData :clientsData){ if (!clientData.isSaved()) return false; } if (clientsData.size() != 0) saving = false; return true; } } private class Handler extends Thread { private Socket socket; private BufferedReader in; private PrintWriter out; public Handler(Socket socket) { this.socket = socket; } public void run() { try { in = new BufferedReader(new InputStreamReader( socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); ClientData clientData = null; synchronized (clientsData) { clientData = new ClientData(out, in); clientsData.add(clientData); } while (true) { try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (clientData) { if (naming && !clientData.isNamed()){ try { clientData.getWriter().println("NAME" + currentname); String answer = clientData.getReader().readLine(); log("name answer = " + answer); } catch(Exception e){ //we do not close clients connections } clientData.setNamed(true); } if (saving && !clientData.isSaved()){ try { clientData.getWriter().println("SAVE" + currentname); String answer = clientData.getReader().readLine(); log("save answer = " + answer); } catch(Exception e){ //we do not close clients connections } clientData.setSaved(true); } if (currentname!=null && !naming && !saving && !clientData.isNamed()){ try { clientData.getWriter().println("NAME" + currentname); String answer = clientData.getReader().readLine(); log("name answer = " + answer); } catch(Exception e){ //we do not close clients connections } clientData.setNamed(true); } } } } catch (IOException e) { log("JTObserver: " + e); } } } private static class ClientData { private PrintWriter writer; private BufferedReader reader; private boolean named = false; private boolean saved = false; public ClientData(PrintWriter writer, BufferedReader reader){ this.writer = writer; this.reader = reader; } public PrintWriter getWriter(){ return writer; } public BufferedReader getReader(){ return reader; } public boolean isNamed() { return named; } public void setNamed(boolean named) { this.named = named; } public boolean isSaved() { return saved; } public void setSaved(boolean saved) { this.saved = saved; } } }
9,740
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JCov.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/JCov.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.constants.MiscConstants; import com.sun.tdk.jcov.data.Result; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; /** * One command to get coverage on product by running user command. * * @author Alexey Fedorchenko */ public class JCov extends JCovCMDTool { private String userOutput; private String srcRootPath; private String command; private String template = MiscConstants.JcovTemplateFileNameXML; private String result = "result.xml"; private String reportDirName = "report"; private int commandsPort = MiscConstants.JcovGrabberCommandPort; private int testsPort = MiscConstants.JcovPortNumber; private final String JCOV_NETWORK_JAR_NAME = "jcov_network_saver.jar"; // logger initialization static { Utils.initLogger(); logger = Logger.getLogger(JCov.class.getName()); } private final static Logger logger; private final Object lock = new Object(); @Override protected int run() throws Exception { //instr ProductInstr instr = new ProductInstr(); File productDir = new File(srcRootPath); if (!productDir.exists()) { logger.log(Level.SEVERE, "No product to get coverage"); return 1; } if (productDir.isFile()) { logger.log(Level.SEVERE, "Set product directory, not file"); return 1; } File jcovJar = new File(JCov.class.getProtectionDomain().getCodeSource().getLocation().getPath()); File networkJar = new File(jcovJar.getParent() + File.separator + JCOV_NETWORK_JAR_NAME); if (!networkJar.exists()) { logger.log(Level.SEVERE, "Can not find " + JCOV_NETWORK_JAR_NAME + " in the jcov.jar location"); logger.log(Level.SEVERE, networkJar.getAbsolutePath()); return 1; } File parentProductDir = productDir.getCanonicalFile().getParentFile(); //zip product try { Utils.zipFolder(productDir.getAbsolutePath(), parentProductDir.getAbsolutePath() + File.separator + productDir.getName() + ".zip"); } catch (Exception e) { logger.log(Level.SEVERE, "Can not zip product", e); return 1; } Utils.addToClasspath(new String[]{srcRootPath}); try { instr.run(new String[]{"-product", srcRootPath, "-productOutput", parentProductDir.getAbsolutePath() + File.separator + "instr", "-rt", networkJar.getAbsolutePath()}); } catch (Exception ex) { logger.log(Level.SEVERE, "Error while instrument product", ex); return 1; } //reeplace product by instrumented one Utils.deleteDirectory(productDir); productDir = new File(productDir.getAbsolutePath()); productDir.mkdir(); File instrFiles = new File(parentProductDir.getAbsolutePath() + File.separator + "instr"); for (File file : instrFiles.listFiles()) { if (file.isDirectory()) { Utils.copyDirectory(file, new File(productDir, file.getName())); } else { Utils.copyFile(file, new File(productDir, file.getName())); } } Utils.deleteDirectory(new File(parentProductDir.getAbsolutePath() + File.separator + "instr")); GrabberThread grabberThread = new GrabberThread(); grabberThread.start(); synchronized (lock) { while (!grabberThread.isStarted()) { lock.wait(); } } //runcommand try { Process process = Runtime.getRuntime().exec(command); process.waitFor(); if (process.exitValue() != 0) { logger.log(Level.SEVERE, "wrong command for running tests."); } } catch (Exception e) { logger.log(Level.SEVERE, "exception in process", e); } //stop grabber GrabberManager grabberManager = new GrabberManager(); grabberManager.setPort(commandsPort); grabberManager.sendKillCommand(); //repgen RepGen rg = new RepGen(); File outputFile = networkJar.getParentFile(); if (userOutput != null && !userOutput.isEmpty()) { outputFile = new File(userOutput); if (!outputFile.exists()) { outputFile.mkdirs(); } } try { Result res = new Result(result); rg.generateReport(rg.getDefaultReportGenerator(), outputFile.getAbsolutePath() + File.separator + reportDirName, res, srcRootPath); } catch (Exception e) { logger.log(Level.SEVERE, "error in report generation", e); } System.out.println("coverage report for product: " + outputFile.getAbsolutePath() + File.separator + reportDirName); return SUCCESS_EXIT_CODE; } public static void main(String args[]) { JCov tool = new JCov(); try { int res = tool.run(args); System.exit(res); } catch (Exception ex) { System.exit(1); } } @Override protected EnvHandler defineHandler() { EnvHandler envHandler = new EnvHandler(new OptionDescr[]{ DSC_PRODUCT, DSC_RUN_COMMAND, DSC_OUTPUT,}, this); return envHandler; } @Override protected int handleEnv(EnvHandler opts) throws EnvHandlingException { if (opts.isSet(DSC_PRODUCT)) { srcRootPath = opts.getValue(DSC_PRODUCT); } if (opts.isSet(DSC_RUN_COMMAND)) { command = opts.getValue(DSC_RUN_COMMAND); } else { throw new EnvHandlingException("command to run tests is not specified"); } if (opts.isSet(DSC_OUTPUT)) { userOutput = opts.getValue(DSC_OUTPUT); } return SUCCESS_EXIT_CODE; } @Override protected String getDescr() { return "gets product coverage with one command"; } @Override protected String usageString() { return "java -jar jcov.jar JCov -pro productDirPath -command \"java -jar tests.jar\""; } @Override protected String exampleString() { return "java -jar jcov.jar JCov -pro productDirPath -command \"java -jar tests.jar\""; } public final static OptionDescr DSC_PRODUCT = new OptionDescr("product", new String[]{"product", "pro"}, "Product files.", OptionDescr.VAL_SINGLE, ""); public final static OptionDescr DSC_RUN_COMMAND = new OptionDescr("command", new String[]{"command", "cmd"}, "Command to run on product and get coverage", OptionDescr.VAL_SINGLE, ""); public final static OptionDescr DSC_OUTPUT = new OptionDescr("output", new String[]{"output", "out", "o"}, "Output dir to create the result report directory", OptionDescr.VAL_SINGLE, ""); private class GrabberThread extends Thread { private boolean started = false; public GrabberThread() { super(); } public boolean isStarted() { return started; } @Override public void run() { try { //grabber Grabber grabber = new Grabber(); grabber.setCommandPort(commandsPort); grabber.setPort(testsPort); grabber.setSaveOnReceive(false); grabber.setTemplate(template); grabber.setOutputFilename(result); grabber.start(true); synchronized (lock) { started = true; lock.notifyAll(); } grabber.waitForStopping(); } catch (Exception e) { logger.log(Level.SEVERE, "grabber exception", e); } } } }
9,316
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
package-info.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/package-info.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * <p> JCov tools accessible from CLI and by API. </p> <p> JCov consists of a * number of tools used to prepare classes for coverage collection, collection * itself and post-collection proccessign. Every tool can be accessed from the * command line ("java -jar <toolname>") as well as from API. </p> <p> It's * possible to create custom tools extending JCovCMDTool class. </p> */ package com.sun.tdk.jcov;
1,621
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Agent.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/Agent.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.constants.MiscConstants; import com.sun.tdk.jcov.instrument.*; import com.sun.tdk.jcov.instrument.asm.ClassMorph; import com.sun.tdk.jcov.runtime.AgentSocketSaver; import com.sun.tdk.jcov.runtime.Collect; import com.sun.tdk.jcov.runtime.CollectDetect; import com.sun.tdk.jcov.runtime.FileSaver; import com.sun.tdk.jcov.runtime.JCovSaver; import com.sun.tdk.jcov.runtime.PropertyFinder; import com.sun.tdk.jcov.runtime.SaverDecorator; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.Utils; import java.io.*; import java.lang.instrument.*; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.Charset; import java.security.ProtectionDomain; import java.util.Arrays; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class Agent extends JCovTool { private boolean detectInternal; private boolean classesReload; private boolean instrumentField; private boolean instrumentAbstract; private boolean instrumentNative; private boolean instrumentAnonymous = true; private boolean instrumentSynthetic = true; private String[] include; private String[] exclude; private String[] m_include; private String[] m_exclude; private String[] callerInclude; private String[] callerExclude; private String[] fm; private String[] saveBegin; private String[] saveEnd; private String template; private String filename; private String flushPath; private InstrumentationOptions.InstrumentationMode mode; private InstrumentationOptions.MERGE merge; private boolean grabberSaver = false; static { Utils.initLogger(); logger = Logger.getLogger(Agent.class.getName()); } private final static Logger logger; private static ClassMorph classMorph; private String host; private int port; private static final Object LOCK = new Object(); private static class SynchronizedSaverDecorator implements SaverDecorator { private JCovSaver wrap; public SynchronizedSaverDecorator(JCovSaver wrap) { init(wrap); } @Override public final void init(JCovSaver saver) { this.wrap = saver; } public void saveResults() { synchronized (LOCK) { wrap.saveResults(); } } } /** * ClassFileTransformer implementation. Gets classfile binary data from VM * and runs ClassMorph.morph method. */ private static class Tr implements ClassFileTransformer { /** * Path to flush instrumented classfiles to. Null means that * instrumented classfiles should not be flushed. */ private final String flushpath; /** * Transformer name. Is not used. */ private final String trname; /** * Can turn off agent instrumentation */ private boolean ignoreLoads = true; /** * Creates new Tr instance * * @param trname Transformer name. Is not used. * @param flushpath Path to flush instrumented classfiles to. Null means * that instrumented classfiles should not be flushed. */ public Tr(String trname, String flushpath) { this.trname = trname; this.flushpath = flushpath; } /** * transform method implementation * * @param loader * @param className * @param classBeingRedefined * @param protectionDomain * @param classfileBuffer * @return instrumented classfile binary data (if ignoreLoads is not set * to true, classfileBuffer will be returned otherwise). If collect is * not enabled - null is returned. */ public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { synchronized (LOCK) { if (Collect.enabled == false) { return null; // signals to the VM that no changes were done } // no need to enter when Collect is disabled CollectDetect.enterInstrumentationCode(); // ensuring that instrumenting will not influence on coverage data try { if (ignoreLoads) { logger.log(Level.INFO, "Ignore for now {0}", className); } else { logger.log(Level.INFO, "Try to transform {0}", className); byte[] newBuff = classMorph.morph(classfileBuffer, loader, flushpath); return newBuff; } } catch (Throwable e) { logger.log(Level.SEVERE, "Adaption failed for {0} with :{1}", new Object[]{className, e}); e.printStackTrace(); } finally { CollectDetect.leaveInstrumentationCode(); // release instrumentation lock } return null; } } } /** * Class for listening agent commands */ private static class CommandThread extends Thread { /** * Agent commands */ public static enum COMMAND { SAVE { String cmd() { return "save"; } }, SAVED { String cmd() { return "saved"; } }, EXIT { String cmd() { return "exit"; } }, EXIT_WITHOUT_SAVE { String cmd() { return "exitWithoutSave".toLowerCase(); } }, AUTOSAVE_DISABLED { String cmd() { return "autosave disabled"; } }; abstract String cmd(); } /** * Port to listen incoming messages */ private int port; /** * Instrumentation params */ private InstrumentationParams params; /** * Creates CommandThread instance * * @param port Port to listen incoming messages * @param params Instrumentation params */ public CommandThread(int port, InstrumentationParams params) { this.port = port; this.params = params; setDaemon(true); } @Override public void run() { while (true) { try { ServerSocket sock = new ServerSocket(port); Socket s = sock.accept(); // System.out.println("Accepted"); InputStream is = s.getInputStream(); byte[] buff = new byte[1024]; int l; String rest = ""; while ((l = is.read(buff)) > 0) { String msg = rest + new String(buff, 0, l, Charset.defaultCharset()); // System.out.println("Message: " + msg); rest = performTask(msg, s); } sock.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Network IOException", ex); } } } /** * Parse and execute incoming message * * @param msg message * @param sock socket * @return exit code * @throws IOException */ private String performTask(String msg, Socket sock) throws IOException { Pattern p = Pattern.compile("\\p{Space}*(\\p{Digit}+).*"); msg = msg.toLowerCase(Locale.getDefault()); PrintStream ps = new PrintStream(sock.getOutputStream(), false, "UTF-8"); while (msg.length() > 0) { msg = msg.trim(); COMMAND cmd = nextCommand(msg); if (cmd == null) { break; } else { switch (cmd) { case SAVE: msg = msg.substring(cmd.cmd().length()); if (Collect.enabled) { Collect.disable(); Collect.saveResults(); params.enable(); } ps.print(COMMAND.SAVED.cmd()); ps.flush(); break; case EXIT: msg = msg.substring(cmd.cmd().length()); Matcher m = p.matcher(msg); int exitCode = 0; if (m.matches()) { exitCode = Integer.parseInt(m.group(1)); } System.exit(exitCode); break; case EXIT_WITHOUT_SAVE: msg = msg.substring(cmd.cmd().length()); m = p.matcher(msg); exitCode = 0; if (m.matches()) { exitCode = Integer.parseInt(m.group(1)); } FileSaver.setDisableAutoSave(true); ps.print(COMMAND.AUTOSAVE_DISABLED.cmd()); ps.flush(); System.exit(exitCode); break; } } } return msg; } /** * Parse incomming message and return COMMAND value * * @param msg message to parse * @return associated COMMAND value */ private COMMAND nextCommand(String msg) { String foundPref = ""; COMMAND found = null; for (COMMAND c : COMMAND.values()) { if (msg.startsWith(c.cmd()) && foundPref.length() < c.cmd().length()) { found = c; foundPref = c.cmd(); } } return found; } } /** * javaagent entry point * * @param agentArgs * @param instArg * @throws Exception */ public static void premain(String agentArgs, Instrumentation instArg) { // handling JCovTool // This method manages CLI handling for Agent tool. // If any change is performed here - check JCovCMDTool CLI handling logic. Agent tool = new Agent(); EnvHandler handler = tool.defineHandler(); try { // proccess cmd options if (agentArgs == null) { agentArgs = ""; } handler.parseCLIArgs(EnvHandler.parseAgentString(agentArgs)); tool.handleEnv(handler); if (handler.isSet(EnvHandler.PRINT_ENV)) { handler.printEnv(); } } catch (EnvHandler.CLParsingException ex) { if (handler.isSet(EnvHandler.HELP)) { handler.usage(); handler.getOut().println("\n JCov Agent command line error: " + ex.getMessage() + "\n"); System.exit(ERROR_CMDLINE_EXIT_CODE); } if (handler.isSet(EnvHandler.HELP_VERBOSE)) { handler.usage(true); handler.getOut().println("\n JCov Agent command line error: " + ex.getMessage() + "\n"); System.exit(ERROR_CMDLINE_EXIT_CODE); } handler.getOut().println(" JCov Agent command line error: " + ex.getMessage() + "\n"); handler.getOut().println("Use \"java -jar jcov.jar Agent -h\" for command-line help or \"java -jar jcov.jar Agent -hv\" for wider description"); System.exit(ERROR_CMDLINE_EXIT_CODE); } catch (EnvHandlingException ex) { handler.getOut().println("JCov Agent command line error: " + ex.getMessage() + "\n"); handler.getOut().println("Use \"java -jar jcov.jar Agent -h\" for command-line help or \"java -jar jcov.jar Agent -hv\" for wider description"); if (handler.isSet(EnvHandler.PRINT_ENV)) { handler.printEnv(); } System.exit(ERROR_CMDLINE_EXIT_CODE); } catch (Throwable ex) { handler.getOut().println("JCov Agent command line error: " + ex.getMessage()); System.exit(ERROR_CMDLINE_EXIT_CODE); } if (handler.isSet(EnvHandler.PRINT_ENV)) { handler.printEnv(); System.exit(SUCCESS_EXIT_CODE); } try { if (Utils.getJavaVersion() >= Utils.VER1_6) { tool.premainV50(agentArgs, instArg); } else { tool.premainV49(agentArgs, instArg); } } catch (Exception ex) { System.out.println("Agent execution error: " + ex.getMessage()); ex.printStackTrace(); System.exit(ERROR_EXEC_EXIT_CODE); } } /** * premain chain for classfiles V50+ * * @param agentArgs * @param inst * @throws Exception */ public void premainV50(String agentArgs, Instrumentation inst) throws Exception { InstrumentationParams params = new InstrumentationParams(true, classesReload, true, instrumentNative, instrumentField, detectInternal, instrumentAbstract ? InstrumentationOptions.ABSTRACTMODE.DIRECT : InstrumentationOptions.ABSTRACTMODE.NONE, include, exclude, callerInclude, callerExclude, m_include, m_exclude, mode, saveBegin, saveEnd) .setInstrumentAnonymous(instrumentAnonymous) .setInstrumentSynthetic(instrumentSynthetic); params.enable(); CollectDetect.enterInstrumentationCode(); Tr transformer = new Tr("RetransformApp", flushPath); inst.addTransformer(transformer, true); if (params.isInstrumentNative()) { inst.setNativeMethodPrefix(transformer, InstrumentationOptions.nativePrefix); } DataRoot root = new DataRoot(agentArgs, params); classMorph = new ClassMorph(filename, root, params); Class[] classes = inst.getAllLoadedClasses(); Set<Class> examinedClasses = new HashSet<Class>(Arrays.asList(classes)); int keep = 0; for (Class c : classes) { if (inst.isModifiableClass(c) && classMorph.shouldTransform(c.getName().replace('.', '/')) && !c.getName().replace('.', '/').equals("jdk/internal/reflect/Reflection") && !c.getName().replace('.', '/').equals("sun/reflect/Reflection")) { classes[keep++] = c; } } transformer.ignoreLoads = false; if (keep > 0) { classes = Utils.copyOf(classes, keep); logger.log(Level.INFO, "About to retransform {0} classes {1}", new Object[]{keep, classes[0]}); try { inst.retransformClasses(classes); } catch (UnmodifiableClassException e) { System.err.println("Should not happen: " + e); e.printStackTrace(System.err); } catch (Throwable e) { System.err.println("During retransform: " + e); e.printStackTrace(System.err); } } logger.log(Level.INFO, "Retransformed {0} classes", keep); Class[] allClasses = inst.getAllLoadedClasses(); keep = 0; for (Class c : allClasses) { if (!examinedClasses.contains(c) && inst.isModifiableClass(c) && classMorph.shouldTransform(c.getName().replace('.', '/'))) { allClasses[keep++] = c; } } if (keep > 0) { logger.log(Level.INFO, "New not transformed: {0} classes {1}", new Object[]{keep, allClasses[0]}); classes = Utils.copyOf(classes, keep); try { inst.retransformClasses(classes); } catch (UnmodifiableClassException e) { logger.log(Level.SEVERE, "retransformClasses: Should not happen: ", e); //log.log(.printStackTrace(System.err); } catch (Throwable e) { logger.log(Level.SEVERE, "Error during retransform: ", e); } } if (!grabberSaver) { // File saver should perform full merge here, not only insert new classes. JCovSaver saver = FileSaver.getFileSaver(root, filename, template, merge, true); loadFileSaverClasses(); Collect.setSaver(Collect.decorateSaver(new SynchronizedSaverDecorator(saver))); } else { AgentSocketSaver saver = new AgentSocketSaver(root, filename, host, port); Collect.setSaver(Collect.decorateSaver(new SynchronizedSaverDecorator(saver))); } CollectDetect.leaveInstrumentationCode(); PropertyFinder.addAutoShutdownSave(); } private void loadFileSaverClasses() throws IOException{ File file = new File(filename + "_load"); new FileOutputStream(file).close(); file.delete(); } /** * premain chain for classfiles V49+ * * @param agentArgs * @param inst * @throws Exception */ public void premainV49(String agentArgs, Instrumentation inst) throws Exception { InstrumentationParams params = new InstrumentationParams(true, instrumentNative, instrumentField, detectInternal, instrumentAbstract ? InstrumentationOptions.ABSTRACTMODE.DIRECT : InstrumentationOptions.ABSTRACTMODE.NONE, include, exclude, callerInclude, callerExclude, mode, saveBegin, saveEnd) .setInstrumentAnonymous(instrumentAnonymous) .setInstrumentSynthetic(instrumentSynthetic); params.enable(); CollectDetect.enterInstrumentationCode(); Tr transformer = new Tr("RetransformApp", flushPath); inst.addTransformer(transformer); /* if (Options.isInstrumentNative()) { inst.setNativeMethodPrefix(transformer, Options.nativePrefix); } */ DataRoot root = new DataRoot(agentArgs, params); classMorph = new ClassMorph(filename, root, params); Class[] classes = inst.getAllLoadedClasses(); Set<Class> examinedClasses = new HashSet<Class>(Arrays.asList(classes)); int keep = 0; for (Class c : classes) { if (/*inst.isModifiableClass(c) &&*/classMorph.shouldTransform(c.getName().replace('.', '/'))) { classes[keep++] = c; } } if (keep > 0) { classes = Utils.copyOf(classes, keep); logger.log(Level.INFO, "About to retransform {0} classes {1}", new Object[]{keep, classes[0]}); } logger.log(Level.INFO, "Retransformed {0} classes", keep); transformer.ignoreLoads = false; Class[] allClasses = inst.getAllLoadedClasses(); keep = 0; for (Class c : allClasses) { if (!examinedClasses.contains(c) && // inst.isModifiableClass(c) && classMorph.shouldTransform(c.getName().replace('.', '/'))) { allClasses[keep++] = c; } } if (keep > 0) { classes = Utils.copyOf(allClasses, keep); } if (!grabberSaver) { // File saver should perform full merge here, not only insert new classes. JCovSaver saver = FileSaver.getFileSaver(root, filename, template, merge, true); loadFileSaverClasses(); Collect.setSaver(Collect.decorateSaver(new SynchronizedSaverDecorator(saver))); } else { AgentSocketSaver saver = new AgentSocketSaver(root, filename, host, port); Collect.setSaver(Collect.decorateSaver(new SynchronizedSaverDecorator(saver))); } CollectDetect.leaveInstrumentationCode(); PropertyFinder.addAutoShutdownSave(); } public String usageString() { return "java -javaagent:jcov.jar=[=option=value[,option=value]*] ..."; } public String exampleString() { return "java -javaagent:jcov.jar=include=java\\.lang\\.String,native=on,type=branch,abstract=off -jar MyApp.jar"; } public String getDescr() { return "print help on usage jcov in dynamic mode"; } @Override public boolean isMainClassProvided() { return false; } ///////// JCovTool implementation ///////// @Override public EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{ DSC_OUTPUT, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MERGE, // Verbosity DSC_VERBOSE, DSC_TIMEOUT, DSC_PORT, // Instrumentation parameters. com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_TEMPLATE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_TYPE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_CALLER_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_CALLER_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_ABSTRACT, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_NATIVE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FIELD, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_SYNTHETIC, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_ANONYM, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_CLASSESRELOAD, // Data save points com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_SAVE_BEGIN, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_SAVE_AT_END, ClassMorph.DSC_FLUSH_CLASSES, DSC_GRABBER, DSC_PORT_GRABBER, DSC_HOST_GRABBER, DSC_LOG }, this); } @Override public int handleEnv(EnvHandler opts) throws EnvHandlingException { String internal = "default"; if (internal.equals("detect")) { detectInternal = true; } else if (internal.equals("show")) { detectInternal = true; } else if (internal.equals("include")) { detectInternal = false; } else if (internal.equals("default")) { detectInternal = true; } else { throw new Error("Parameter error"); } mode = InstrumentationOptions.InstrumentationMode.fromString(opts.getValue(InstrumentationOptions.DSC_TYPE)); if (opts.isSet(InstrumentationOptions.DSC_TEMPLATE)) { template = opts.getValue(InstrumentationOptions.DSC_TEMPLATE); } include = InstrumentationOptions.handleInclude(opts); exclude = InstrumentationOptions.handleExclude(opts); m_include = InstrumentationOptions.handleMInclude(opts); m_exclude = InstrumentationOptions.handleMExclude(opts); fm = InstrumentationOptions.handleFM(opts); callerInclude = opts.getValues(InstrumentationOptions.DSC_CALLER_INCLUDE); // System.out.println("Setup callerInclude " + Arrays.toString(callerInclude)); callerExclude = opts.getValues(InstrumentationOptions.DSC_CALLER_EXCLUDE); // System.out.println("Setup callerExclude " + Arrays.toString(callerExclude)); String abstractValue = opts.getValue(InstrumentationOptions.DSC_ABSTRACT); if (abstractValue.equals("off")) { instrumentAbstract = false; } else if (abstractValue.equals("on")) { instrumentAbstract = true; } else { // will not happen - checking inside EnvHandler throw new EnvHandlingException("'" + InstrumentationOptions.DSC_ABSTRACT.name + "' parameter value error: expected 'on' or 'off'; found: '" + abstractValue + "'"); } String classesReloadValue = opts.getValue(InstrumentationOptions.DSC_CLASSESRELOAD); if (classesReloadValue.equals("on")) { classesReload = true; } else { classesReload = false; } String nativeValue = opts.getValue(InstrumentationOptions.DSC_NATIVE); if (nativeValue.equals("on")) { instrumentNative = true; } else if (nativeValue.equals("off")) { instrumentNative = false; } else { // will not happen - checking inside EnvHandler throw new EnvHandlingException("'" + InstrumentationOptions.DSC_NATIVE.name + "' parameter value error: expected 'on' or 'off'; found: '" + nativeValue + "'"); } String fieldValue = opts.getValue(InstrumentationOptions.DSC_FIELD); if (fieldValue.equals("on")) { instrumentField = true; } else if (fieldValue.equals("off")) { instrumentField = false; } else { // will not happen - checking inside EnvHandler throw new EnvHandlingException("'" + InstrumentationOptions.DSC_FIELD.name + "' parameter value error: expected 'on' or 'off'; found: '" + fieldValue + "'"); } String anonym = opts.getValue(InstrumentationOptions.DSC_ANONYM); if (anonym.equals("on")) { instrumentAnonymous = true; } else { // off instrumentAnonymous = false; } String synthetic = opts.getValue(InstrumentationOptions.DSC_SYNTHETIC); if (synthetic.equals("on")) { instrumentSynthetic = true; } else { // off instrumentSynthetic = false; } String mergeValue = opts.getValue(InstrumentationOptions.DSC_MERGE); if (mergeValue.equals("merge")) { merge = InstrumentationOptions.MERGE.MERGE; } else if (mergeValue.equals("scale")) { merge = InstrumentationOptions.MERGE.SCALE; } else if (mergeValue.equals("overwrite")) { merge = InstrumentationOptions.MERGE.OVERWRITE; } else if (mergeValue.equals("gensuff")) { merge = InstrumentationOptions.MERGE.GEN_SUFF; } else { // will never happen as this is checked in EnvHandler throw new EnvHandlingException("'" + InstrumentationOptions.DSC_MERGE.name + "' parameter value error: expected 'merge', 'scale', 'overwrite' or 'gensuff'; found: '" + mergeValue + "'"); } saveBegin = opts.getValues(InstrumentationOptions.DSC_SAVE_BEGIN); saveEnd = opts.getValues(InstrumentationOptions.DSC_SAVE_AT_END); flushPath = opts.getValue(ClassMorph.DSC_FLUSH_CLASSES); if ("none".equals(flushPath)) { flushPath = null; } String logfile = opts.getValue(EnvHandler.LOGFILE); if (opts.isSet(DSC_LOG) || logfile != null) { if (logfile == null) { logfile = "jcov.log"; } try { Utils.setLoggerHandler(new FileHandler(logfile)); } catch (Exception ex) { throw new EnvHandlingException("Can't open file '" + logfile + "' for writing the log", ex); } if (opts.isSet(EnvHandler.LOGLEVEL)) { Utils.setLoggingLevel(opts.getValue(EnvHandler.LOGLEVEL)); } else if (opts.isSet(DSC_VERBOSE)) { int verbositylevel = Utils.checkedToInt(opts.getValue(DSC_VERBOSE), "verbosity level", Utils.CheckOptions.INT_NONNEGATIVE); switch (verbositylevel) { case 0: logger.setLevel(Level.SEVERE); Utils.setLoggingLevel(Level.SEVERE); break; case 1: logger.setLevel(Level.CONFIG); Utils.setLoggingLevel(Level.CONFIG); break; case 2: logger.setLevel(Level.INFO); Utils.setLoggingLevel(Level.INFO); break; case 3: logger.setLevel(Level.ALL); Utils.setLoggingLevel(Level.ALL); break; default: throw new EnvHandlingException("Incorrect verbosity level (" + opts.getValue(DSC_VERBOSE) + ") - should be 0..3"); } } } else { Utils.setLoggingLevel(Level.OFF); } if (opts.isSet(DSC_TIMEOUT)) { long timeout = Utils.checkedToInt(opts.getValue(DSC_TIMEOUT), "timeout value"); if (timeout > 0) { Timer timer = new Timer(true); timer.schedule(new TimerTask() { @Override public void run() { logger.log(Level.INFO, "Agent has been timed out."); if (Collect.enabled) { Collect.disable(); Collect.saveResults(); } Runtime.getRuntime().halt(0); } }, timeout); } } grabberSaver = opts.isSet(DSC_GRABBER); if (grabberSaver) { host = opts.getValue(DSC_HOST_GRABBER); Utils.checkHostCanBeNull(host, "grabber host"); this.port = Utils.checkedToInt(opts.getValue(DSC_PORT_GRABBER), "grabber port number", Utils.CheckOptions.INT_POSITIVE); } filename = opts.getValue(DSC_OUTPUT); if (!grabberSaver) { Utils.checkFileNotNull(filename, "output filename", Utils.CheckOptions.FILE_NOTISDIR, Utils.CheckOptions.FILE_PARENTEXISTS); } if (opts.isSet(DSC_PORT)) { CommandThread cmdThread = new CommandThread(Utils.checkedToInt(opts.getValue(DSC_PORT), "command listener port number", Utils.CheckOptions.INT_POSITIVE), new InstrumentationParams(true, instrumentNative, instrumentField, detectInternal, instrumentAbstract ? InstrumentationOptions.ABSTRACTMODE.DIRECT : InstrumentationOptions.ABSTRACTMODE.NONE, include, exclude, callerInclude, callerExclude, mode, saveBegin, saveEnd) .setInstrumentAnonymous(instrumentAnonymous) .setInstrumentSynthetic(instrumentSynthetic)); cmdThread.start(); } return SUCCESS_EXIT_CODE; } public static final OptionDescr DSC_OUTPUT = new OptionDescr("file", new String[]{"url", "o"}, "Output path definition.", OptionDescr.VAL_SINGLE, "Specifies output data file. \n" + "If specified file already exists, collected data will be merged with data from file", "result.xml"); public final static OptionDescr DSC_VERBOSE = new OptionDescr("verbose", "Verbosity level.", new String[][]{ {"0", "minimal, only fatal failure diagnostic is printed"}, {"1", "moderate, non-fatal errors are included in log"}, {"2", "high, all warnings are included in log"}, {"3", "highest, all messages are included in log"} }, "Set verbosity level.", "0"); public static final OptionDescr DSC_TIMEOUT = new OptionDescr("timeout", "Agent process timeout.", OptionDescr.VAL_SINGLE, "Specifies timeout for agent process in milliseconds.\n" + "0 means there is no timeout specified. Default is 0.\n", "0"); // port now can be set only as "agent.port" via VM properties and env variables. "Port" is used only for grabber and socket saver. public static final OptionDescr DSC_PORT = new OptionDescr("agent.port", new String[]{"portcl"}, "Agent command listening port", OptionDescr.VAL_SINGLE, "Specifies port number to listen for driving commands.\n" + "Commands are executed sequentially, some may send messages in response. " + "Valid commands to send are: \n" + " \"save\" - to save already collected data. It will respond with \"saved\" message\n" + " \"exit\" - to perform System.exit() immediately. Exit code number may be sent with this command.\n" + " It's chars should follow \"exit\""); public static final OptionDescr DSC_PORT_GRABBER = new OptionDescr("port", new String[]{"grabberport"}, "", OptionDescr.VAL_SINGLE, "Specifies port number to send data to the grabber", MiscConstants.JcovPortNumber + ""); public static final OptionDescr DSC_HOST_GRABBER = new OptionDescr("host", new String[]{"grabberhost"}, "", OptionDescr.VAL_SINGLE, "Specifies host name to send data to the grabber", "localhost"); public final static OptionDescr DSC_LOG = new OptionDescr("log", "logging", OptionDescr.VAL_NONE, "Turns on JCov's agent logging.\n" + "Log records saved in jcov.log file"); public final static OptionDescr DSC_GRABBER = new OptionDescr("grabber", "use grabber saver", OptionDescr.VAL_NONE, "Use grabber saver instead of file saver. jcov.port " + "and jcov.host VM properties could be used to control the saver as well as JCOV_PORT and JCOV_HOST env variable"); }
36,438
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
RepMerge.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/RepMerge.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.OptionDescr; /** * * @author Andrey Titov */ public class RepMerge extends Merger { @Override protected int run() throws Exception { System.out.println("Warning, this tool is depricated and would be removed soon"); return super.run(); } @Override protected EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{DSC_OUTPUT, DSC_NONEW}, this); } @Override protected int handleEnv(EnvHandler opts) throws EnvHandlingException { int res = super.handleEnv(opts); if (opts.isSet(DSC_NONEW)) { setAddMissing(false); } setSigmerge(true); return res; } @Override protected String usageString() { return "java com.sun.tdk.jcov.RepMerge [-output <filename>] [-nonew] <filenames>"; } @Override protected String exampleString() { return "java -cp jcov.jar com.sun.tdk.jcov.RepMerge -output merged.xml test1.xml test2.xml"; } @Override protected String getDescr() { return "merges jcov data files at method level not caring of blocks <deprecated>"; } public static void main(String[] args) { try { System.exit(new RepMerge().run(args)); } catch (Exception e) { System.exit(ERROR_EXEC_EXIT_CODE); } } static OptionDescr DSC_NONEW = new OptionDescr("nonew", "", OptionDescr.VAL_NONE, "Don't include any information that doesn't exist in the first merged file."); }
2,815
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Filter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/Filter.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.filter.ConveyerFilter; import com.sun.tdk.jcov.filter.FilterSpi; import com.sun.tdk.jcov.filter.MemberFilter; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.instrument.InstrumentationOptions.MERGE; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.io.ClassSignatureFilter; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.runtime.JCovXMLFileSaver; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.tools.SPIDescr; import com.sun.tdk.jcov.util.Utils; import java.util.ArrayList; import java.util.Arrays; /** * The class that applies a custom filter to coverage data file. It has a * command line entry point. It also can be used from other tools. * * Usage examples: * <pre> * Filter filter = new Filter("plugin.myFilterSpi"); * filter.applyFilter("result.xml", "new.xml"); * </pre> or from command line: * <pre> * # java com.sun.tdk.jcov.Filter -i com.sun.* -filter plugin.myFilterSpi result.xml new.xml * </pre> * * @author Dmitry Fazunenko * @author Sergey Borodin */ public class Filter extends JCovCMDTool { private String inFile = null; private String outFile = null; // primitive filter by class name include/exclude private ClassSignatureFilter readFilter; private MemberFilter filter; private String[] filterSpi = null; private boolean synthetic = false; /** * * Reads inFile, applies filter and writes result down to outFile. * * @param inFile - file to read * @param outFile - file to create (if null, System.out will be used) * @throws Exception */ public void applyFilter(String inFile, String outFile) throws Exception { DataRoot root = Reader.readXML(inFile, true, readFilter); if (synthetic) { root.applyFilter(new RepGen.ANC_FILTER()); } if (filter != null) { root.applyFilter(filter); } root.getParams().setIncludes(readFilter.getIncludes()); root.getParams().setExcludes(readFilter.getExcludes()); if (readFilter.getModifs() != null && readFilter.getModifs().length > 0) { root.getXMLHeadProperties().put("coverage.generator.modif", Arrays.toString(readFilter.getModifs())); } else { root.getXMLHeadProperties().remove("coverage.generator.modif"); } if (filterSpi != null) { String get = root.getXMLHeadProperties().get("coverage.filter.plugin"); root.getXMLHeadProperties().put("coverage.filter.plugin", Arrays.toString(filterSpi)); } else { root.getXMLHeadProperties().remove("coverage.filter.plugin"); } new JCovXMLFileSaver(root, MERGE.OVERWRITE).saveResults(outFile); root.destroy(); } /** * Entry point for command line. * * @param args */ public static void main(String args[]) { Filter tool = new Filter(); try { int res = tool.run(args); System.exit(res); } catch (Exception ex) { System.exit(1); } } protected String usageString() { return "java " + Filter.class.getCanonicalName() + " [options] inFile outFile"; } protected String exampleString() { return "java -cp jcov.jar:filter_classes " + Filter.class.getCanonicalName() + " -include java.lang.* " + "-filter java.xml lang.xml"; } protected String getDescr() { return "filters out result data"; } ///////// JCovTool implementation ///////// @Override protected EnvHandler defineHandler() { EnvHandler eh = new EnvHandler(new OptionDescr[]{ com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FM, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FM_LIST, InstrumentationOptions.DSC_MINCLUDE, InstrumentationOptions.DSC_MINCLUDE_LIST, InstrumentationOptions.DSC_MEXCLUDE, InstrumentationOptions.DSC_MEXCLUDE_LIST, DSC_FILTER_PLUGIN, DSC_SYNTHETIC }, this); eh.registerSPI(new SPIDescr("filter", FilterSpi.class)); return eh; } @Override protected int handleEnv(EnvHandler opts) throws EnvHandlingException { String[] files = opts.getTail(); if (files == null || files.length == 0) { throw new EnvHandlingException("no input file specified"); } else if (files.length == 1) { throw new EnvHandlingException("no output file specified"); } else if (files.length == 2) { inFile = files[0]; Utils.checkFileNotNull(inFile, "input JCov datafile", Utils.CheckOptions.FILE_ISFILE, Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_CANREAD); outFile = files[1]; Utils.checkFileNotNull(outFile, "output JCov datafile", Utils.CheckOptions.FILE_NOTEXISTS); } else if (files.length > 2) { throw new EnvHandlingException("too many files specified"); } synthetic = opts.isSet(DSC_SYNTHETIC); String[] exclude = InstrumentationOptions.handleExclude(opts); String[] include = InstrumentationOptions.handleInclude(opts); String[] fm = InstrumentationOptions.handleFM(opts); String[] m_exclude = InstrumentationOptions.handleMExclude(opts); String[] m_include = InstrumentationOptions.handleMInclude(opts); readFilter = new ClassSignatureFilter(include, exclude, m_include, m_exclude, fm); ArrayList<FilterSpi> filters = opts.getSPIs(FilterSpi.class); if (filters == null || filters.isEmpty()) { filter = null; } else if (filters.size() == 1) { filter = filters.get(0).getFilter(); } else { ConveyerFilter cf = new ConveyerFilter(); for (FilterSpi spi : filters) { cf.add(spi.getFilter()); } filter = cf; } return SUCCESS_EXIT_CODE; } @Override protected int run() throws Exception { try { applyFilter(inFile, outFile); } catch (Exception e) { if (filter != null) { if (e instanceof NullPointerException) { e.printStackTrace(); } throw new Exception("Cannot apply filter '" + filter + "' to " + inFile + " - exception occured: " + e.getMessage(), e); } else { throw new Exception("Mishap:", e); } } return SUCCESS_EXIT_CODE; } /** * @return ClassSignatureFilter used by this Filter to read the DataRoot */ public ClassSignatureFilter getReadingFilter() { return readFilter; } /** * Set the ClassSignatureFilter used by this Filter to read the DataRoot * * @param acceptor */ public void setReadingFilter(ClassSignatureFilter acceptor) { this.readFilter = acceptor; } /** * @return MemberFilter used by this Filter */ public MemberFilter getFilter() { return filter; } /** * Set MemberFilter used by this Filter * * @param filter */ public void setFilter(MemberFilter filter) { this.filter = filter; } final static OptionDescr DSC_FILTER_PLUGIN = new OptionDescr("filter", "", OptionDescr.VAL_MULTI, "Custom filtering plugin class"); public final static OptionDescr DSC_SYNTHETIC = new OptionDescr("synthetic", "Additional filtering", "Remove coverage for synthetic methods"); }
9,444
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Instr.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/Instr.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.insert.AbstractUniversalInstrumenter; import com.sun.tdk.jcov.instrument.InstrumentationParams; import com.sun.tdk.jcov.instrument.asm.ClassMorph; import com.sun.tdk.jcov.instrument.InstrumentationPlugin; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static com.sun.tdk.jcov.instrument.InstrumentationOptions.*; import static com.sun.tdk.jcov.util.Utils.CheckOptions.*; /** * <p> A tool to statically instrument class files to collect coverage. </p> <p> * There are 2 coverage collection modes: static and dynamic. In static mode * JCov reads and modifies classes bytecode inserting there some instructions * which will use JCov RT libraries. In dynamic mode (aka Agent mode) a VM agent * is used ("java -javaagent") that instruments bytecode just at loadtime. </p> * * @author Andrey Titov * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class Instr extends JCovCMDTool { private String[] include = new String[]{".*"}; private String[] exclude = new String[]{""}; private String[] m_include = new String[]{".*"}; private String[] m_exclude = new String[]{""}; private String[] callerInclude; private String[] callerExclude; private String[] innerInclude; private String[] innerExclude; private String[] save_beg = null; private String[] save_end = null; private boolean genAbstract = false; private boolean gennative = false; private boolean genfield = false; private boolean gensynthetic = true; private boolean genanonymous = true; private boolean innerinvocations = true; private String[] srcs; private File outDir; private String include_rt; private String template; private String flushPath; private boolean subsequentInstr = false; private boolean recurse; private InstrumentationMode mode = InstrumentationMode.BRANCH; private AbstractUniversalInstrumenter instrumenter; private ClassMorph morph; private ClassLoader cl = null; private static final Logger logger; private InstrumentationPlugin plugin; static { Utils.initLogger(); logger = Logger.getLogger(Instr.class.getName()); } private boolean needToFixJavaBase = false; public void fixJavaBase() { needToFixJavaBase = true; } /** * <p> Instrument specified files (directories with classfiles and jars) and * write template. Output template will be merged with input template (if * any) or will be written to specified path. Instrumented file will be * written to * <code>outDir</code>. </p> * * @param files Files to be instrumented. Can contain both directoried with * classfiles and jars * @param outDir Directory to write instrumented data to. Be careful - all * instrumented data will be written to the root of outDir. When null - * instrumented data will overwrite source binaries * @param includeRTJar Runtime jar path to be implanted into instrumented * data. For jar files - rt will be integrated into result jar. For * directories - rt will be unpacked into outDir. Null if nothing should be * implanted * @throws IOException * @see #setTemplate(java.lang.String) */ public void instrumentAll(File[] files, File outDir, String includeRTJar) throws IOException { instrumentFiles(files, outDir, includeRTJar); instrumenter.finishWork(); } /** * <p> Instrument several files (classfiles or jars) to some directory. * Instrumenter should be set. Instrumented file will be written to * <code>outDir</code>. </p> * * @param files files to instrument * @param outDir can be null. Initial file will be overwritten in such case. * @throws IOException * @see * #setInstrumenter(com.sun.tdk.jcov.insert.AbstractUniversalInstrumenter) * @see #setDefaultInstrumenter() */ public void instrumentAll(File[] files, File outDir) throws IOException { instrumentAll(files, outDir, null); } /** * <p> Instrument one file using default instrumenter. This method doesn't * write output template.xml - use * <code>finishWork()</code> method. Instrumented file will be written to * <code>outDir</code>. </p> * * @param file * @param outDir can be null. Initial file will be overwritten in such case. * @param includeRTJar * @throws IOException * @see * #setInstrumenter(com.sun.tdk.jcov.insert.AbstractUniversalInstrumenter) * @see #setDefaultInstrumenter() * @see #finishWork() */ public void instrumentFile(File file, File outDir, String includeRTJar) throws IOException { setDefaultInstrumenter(); instrumenter.instrument(file, outDir, includeRTJar, recurse); } /** * <p> Instrument one file using default instrumenter. This method doesn't * write output template.xml - use * <code>finishWork()</code> method. Instrumented file will be written to * <code>outDir</code>. </p> * * @param file * @param outDir can be null. Initial file will be overwritten in such case. * @param includeRTJar * @throws IOException * @see * #setInstrumenter(com.sun.tdk.jcov.insert.AbstractUniversalInstrumenter) * @see #setDefaultInstrumenter() * @see #finishWork() */ public void instrumentFile(String file, File outDir, String includeRTJar) throws IOException { instrumentFile(new File(file), outDir, includeRTJar); } public void instrumentFile(String file, File outDir, String includeRTJar, String moduleName) throws IOException { if (morph != null){ morph.setCurrentModuleName(moduleName); if(needToFixJavaBase && "java.base".equals(moduleName)) { File moduleInfo = new File(file + File.separator + "module-info.class"); if(!moduleInfo.exists()) throw new IllegalStateException(moduleInfo + " does not exist!"); try(FileInputStream fi = new FileInputStream(moduleInfo)) { byte[] noHashes = morph.clearHashes(fi.readAllBytes(), cl); List<String> packages = new ArrayList<>(); packages.add("com/sun/tdk/jcov/runtime"); if(plugin != null) { String pluginRuntimePackage = plugin.collectorPackage(); if (pluginRuntimePackage != null) { pluginRuntimePackage = pluginRuntimePackage.replace('.', '/'); packages.add(pluginRuntimePackage); } } byte[] withExports = morph.addExports(noHashes, packages, cl); try (FileOutputStream fo = new FileOutputStream(((outDir == null) ? file : outDir) + File.separator + "module-info.class")) { fo.write(withExports); } } } instrumentFile(new File(file), outDir, includeRTJar); } } /** * <p> This method instruments a bunch of files using default instrumenter. * This method doesn't write output template.xml - use * <code>finishWork()</code> method. Instrumented file will be written to * <code>outDir</code>. </p> * * @param files * @param outDir can be null. Initial file will be overwritten in such case. * @param implantRT */ public void instrumentFiles(File[] files, File outDir, String implantRT) throws IOException { setDefaultInstrumenter(); for (File file : files) { instrumenter.instrument(file, outDir, implantRT, recurse); } } /** * <p> This method instruments a bunch of files using default instrumenter. * This method doesn't write output template.xml - use * <code>finishWork()</code> method. Instrumented file will be written to * <code>outDir</code>. </p> * * @param files * @param outDir can be null. Initial file will be overwritten in such case. * @param implantRT */ public void instrumentFiles(String[] files, File outDir, String implantRT) throws IOException { setDefaultInstrumenter(); for (String file : files) { instrumenter.instrument(new File(file), outDir, implantRT, recurse); } } public void instrumentTests(String[] files, File outDir, String implantRT) throws IOException { if (gennative || genAbstract) { morph.fillIntrMethodsIDs(morph.getRoot()); } setDefaultInstrumenter(); for (String file : files) { instrumenter.instrument(new File(file), outDir, implantRT, recurse); } } /** * Begin instrumentation in semi-automatic mode * * @see Instr#finishWork() */ public void startWorking() { setDefaultInstrumenter(); } /** * Set default instrumenter */ private void setDefaultInstrumenter() { if (morph == null) { InstrumentationParams params = new InstrumentationParams(innerinvocations, false, false, gennative, genfield, false, genAbstract ? ABSTRACTMODE.DIRECT : ABSTRACTMODE.NONE, include, exclude, callerInclude, callerExclude, m_include, m_exclude, mode, save_beg, save_end) .setInstrumentSynthetic(gensynthetic) .setInstrumentAnonymous(genanonymous) .setInnerInvocations(innerinvocations) .setInnerIncludes(innerInclude) .setInnerExcludes(innerExclude) .setInstrumentationPlugin(plugin); if (subsequentInstr) { morph = new ClassMorph(params, template); } else { morph = new ClassMorph(params, null); } } if (instrumenter == null) { instrumenter = new AbstractUniversalInstrumenter(true) { protected byte[] instrument(byte[] classData, int classLen) throws IOException { return morph.morph(classData, cl, flushPath); } public void finishWork() { if (subsequentInstr) { morph.saveData(MERGE.MERGE); // template should be initialized } else { morph.saveData(template, null, MERGE.OVERWRITE); // template should be initialized } } public void processClassFileInModules(Path filePath, File outDir){ if (morph != null){ if (filePath != null){ String mpath = filePath.toAbsolutePath().toString(); mpath = mpath.substring("/modules/".length()); if (mpath.contains("/")){ String module_name = mpath.substring(0, mpath.indexOf("/")); morph.setCurrentModuleName(module_name); } } super.processClassFileInModules(filePath, outDir); } } }; } } /** * Set instrumenter * * @param instrumenter instrumenter used to instrument data */ public void setInstrumenter(AbstractUniversalInstrumenter instrumenter) { this.instrumenter = instrumenter; } /** * Finish instrumentation and write template. If template already exists - * it will be merged. <p> Template is written to the place Instrumenter was * created with */ public void finishWork() throws Exception { if (instrumenter != null) { instrumenter.finishWork(); // destroy instrumenter & morph? } if(plugin != null) plugin.instrumentationComplete(); } /** * Finish instrumentation and write template. If template already exists - * it will be merged. * * @param outTemplate template path */ public void finishWork(String outTemplate) throws Exception { if (instrumenter != null) { if (subsequentInstr) { morph.saveData(outTemplate, MERGE.MERGE); // template should be initialized } else { morph.saveData(outTemplate, null, MERGE.OVERWRITE); // template should be initialized } } if(plugin != null) plugin.instrumentationComplete(); } /** * Legacy CLI entry point. */ public static void main(String[] args) { Instr tool = new Instr(); try { int res = tool.run(args); System.exit(res); } catch (Exception ex) { System.exit(1); } } protected String usageString() { return "java -cp jcov.jar:source1:sourceN com.sun.tdk.jcov.Instr [-option value] source1 sourceN"; } /** * @return Command note * @see com.sun.tdk.jcov.tools.JCovTool#noteString() */ @Override protected String noteString() { return " Note: Starting from JDK 9, the sources: source1,sourceN should be added to the class path of the command line."; } protected String exampleString() { return "java -cp jcov.jar:source1:sourceN com.sun.tdk.jcov.Instr -include java.lang.* " + "-type block -output instrumented_classes source1 sourceN"; } protected String getDescr() { return "instruments class files and creates template.xml"; } /** * public configuration interface * * @param b true when logger should be verbose */ public void setVerbose(boolean b) { if (b) { logger.setLevel(Level.INFO); } else { logger.setLevel(Level.WARNING); } } public void resetDefaults() { try { handleEnv_(defineHandler()); } catch (EnvHandlingException ex) { // should not happen } } public boolean isGenAbstract() { return genAbstract; } public void setGenAbstract(boolean genAbstract) { this.genAbstract = genAbstract; } public String[] getExclude() { return exclude; } public void setExclude(String[] exclude) { this.exclude = exclude; } public String[] getMExclude() { return m_exclude; } public void setMExclude(String[] m_exclude) { this.m_exclude = m_exclude; } public boolean isGenField() { return genfield; } public void setGenField(boolean field) { this.genfield = field; } public boolean isGenNative() { return gennative; } public void setGenNative(boolean gennative) { this.gennative = gennative; } public String[] getInclude() { return include; } public void setInclude(String[] include) { this.include = include; } public String[] getMInclude() { return m_include; } public void setMInclude(String[] m_include) { this.m_include = m_include; } public void setCallerInclude(String[] callerInclude) { this.callerInclude = callerInclude; } public void setCallerExclude(String[] callerExclude) { this.callerExclude = callerExclude; } public void setInnerInclude(String[] include) { this.innerInclude = include; } public void setInnerExclude(String[] exclude) { this.innerExclude = exclude; } public void setFilter(String[] include, String exclude[]) { this.include = include; this.exclude = exclude; } public void setPlugin(InstrumentationPlugin plugin) { this.plugin = plugin; } public InstrumentationPlugin getPlugin() { return plugin; } public String[] getSave_beg() { return save_beg; } public void setSave_beg(String[] save_beg) { this.save_beg = save_beg; } public String[] getSave_end() { return save_end; } public void setSave_end(String[] save_end) { this.save_end = save_end; } public void setMode(InstrumentationMode mode) { this.mode = mode; } public InstrumentationMode getMode() { return mode; } public void config(boolean genabstract, boolean genfield, boolean gennative, String[] saveBegin, String saveEnd[]) { setGenNative(gennative); setGenAbstract(genabstract); setGenField(genfield); setSave_beg(save_beg); setSave_end(save_end); } public void setTemplate(String template) { this.template = template; } public String getTemplate() { return template; } public boolean isSubsequentInstr() { return subsequentInstr; } public void setSubsequentInstr(boolean subsequentInstr) { this.subsequentInstr = subsequentInstr; } public void setFlushPath(String flushPath) { this.flushPath = flushPath; } public String getFlushPath() { return flushPath; } public void setClassLoader(ClassLoader cl) { this.cl = cl; } @Override protected int run() throws Exception { Utils.addToClasspath(srcs); try { instrumentFiles(srcs, outDir, include_rt); finishWork(template); } catch (IOException ex) { throw new EnvHandlingException("Critical exception: " + ex); } return SUCCESS_EXIT_CODE; } @Override protected EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{ DSC_OUTPUT, DSC_VERBOSE, DSC_TYPE, DSC_INCLUDE, DSC_INCLUDE_LIST, DSC_EXCLUDE, DSC_CALLER_INCLUDE, DSC_CALLER_EXCLUDE, DSC_EXCLUDE_LIST, DSC_MINCLUDE, DSC_MEXCLUDE, DSC_SAVE_BEGIN, DSC_SAVE_AT_END, DSC_TEMPLATE, DSC_SUBSEQUENT, DSC_ABSTRACT, DSC_NATIVE, DSC_FIELD, DSC_SYNTHETIC, DSC_ANONYM, DSC_INNERINVOCATION, DSC_INSTR_PLUGIN, ClassMorph.DSC_FLUSH_CLASSES, DSC_INCLUDE_RT, DSC_RECURSE,}, this); } private int handleEnv_(EnvHandler opts) throws EnvHandlingException { if (opts.isSet(DSC_VERBOSE)) { setVerbose(true); } outDir = null; if (opts.isSet(DSC_OUTPUT)) { // compatibility outDir = new File(opts.getValue(DSC_OUTPUT)); Utils.checkFile(outDir, "output directory", FILE_NOTISFILE); if (!outDir.exists()) { outDir.mkdirs(); logger.log(Level.INFO, "The directory {0} was created.", outDir.getAbsolutePath()); } } save_beg = opts.getValues(DSC_SAVE_BEGIN); save_end = opts.getValues(DSC_SAVE_AT_END); String abstractValue = opts.getValue(DSC_ABSTRACT); if (abstractValue.equals("off")) { genAbstract = false; } else if (abstractValue.equals("on")) { genAbstract = true; } else { throw new EnvHandlingException("'" + DSC_ABSTRACT.name + "' parameter value error: expected 'on' or 'off'; found: '" + abstractValue + "'"); } String nativeValue = opts.getValue(DSC_NATIVE); if (nativeValue.equals("on")) { gennative = true; } else if (nativeValue.equals("off")) { gennative = false; } else { throw new EnvHandlingException("'" + DSC_NATIVE.name + "' parameter value error: expected 'on' or 'off'; found: '" + nativeValue + "'"); } String fieldValue = opts.getValue(DSC_FIELD); if (fieldValue.equals("on")) { genfield = true; } else if (fieldValue.equals("off")) { genfield = false; } else { // can't happen - check is in EnvHandler throw new EnvHandlingException("'" + DSC_FIELD.name + "' parameter value error: expected 'on' or 'off'; found: '" + fieldValue + "'"); } String anonym = opts.getValue(DSC_ANONYM); genanonymous = anonym.equals("on"); String synthetic = opts.getValue(DSC_SYNTHETIC); gensynthetic = synthetic.equals("on"); String innerInvocation = opts.getValue(DSC_INNERINVOCATION); innerinvocations = ! "off".equals(innerInvocation); callerInclude = opts.getValues(DSC_CALLER_INCLUDE); callerExclude = opts.getValues(DSC_CALLER_EXCLUDE); recurse = opts.isSet(DSC_RECURSE); mode = InstrumentationMode.fromString(opts.getValue(DSC_TYPE)); template = opts.getValue(DSC_TEMPLATE); Utils.checkFileNotNull(template, "template filename", FILE_NOTISDIR, FILE_PARENTEXISTS); subsequentInstr = opts.isSet(DSC_SUBSEQUENT); include = handleInclude(opts); exclude = handleExclude(opts); m_include = handleMInclude(opts); m_exclude = handleMExclude(opts); flushPath = opts.getValue(ClassMorph.DSC_FLUSH_CLASSES); if ("none".equals(flushPath)) { flushPath = null; } include_rt = opts.getValue(DSC_INCLUDE_RT); Utils.checkFileCanBeNull(include_rt, "JCovRT library jarfile", FILE_EXISTS, FILE_ISFILE, FILE_CANREAD); try { String pluginClass = opts.getValue(DSC_INSTR_PLUGIN); if(pluginClass != null && !pluginClass.isEmpty()) plugin = (InstrumentationPlugin) Class.forName(pluginClass) .getDeclaredConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) { throw new EnvHandlingException("'" + DSC_INSTR_PLUGIN.name + "' parameter error: '" + e + "'"); } return SUCCESS_EXIT_CODE; } @Override protected int handleEnv(EnvHandler opts) throws EnvHandlingException { srcs = opts.getTail(); if (srcs == null || srcs.length == 0) { throw new EnvHandlingException("No sources specified"); } return handleEnv_(opts); } final static OptionDescr DSC_OUTPUT = new OptionDescr("instr.output", new String[]{"output", "o"}, "Output directory for instrumented classes", OptionDescr.VAL_SINGLE, "Specifies output directory, default directory is current. " + "Instr command could process different dirs and different jars: \n " + "all classes from input dirs and all jars will be placed in output directory."); final static OptionDescr DSC_VERBOSE = new OptionDescr("verbose", "Verbose mode", "Enable verbose mode."); final static OptionDescr DSC_INCLUDE_RT = new OptionDescr("implantrt", new String[]{"rt"}, "Runtime management", OptionDescr.VAL_SINGLE, "Allows to implant needed for runtime files into instrumented data: -includert jcov_rt.jar"); final static OptionDescr DSC_SUBSEQUENT = new OptionDescr("subsequent", "", OptionDescr.VAL_NONE, "Template would be used to decide what should not be instrumented - " + "all existing in template would be treated as already instrumented"); final static OptionDescr DSC_RECURSE = new OptionDescr("recursive", "", OptionDescr.VAL_NONE, "Recurse through specified directories instrumenting everything inside. " + "With -flush option it will be able to instrument duplicate classes"); }
26,116
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Helper.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/Helper.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.JCovTool; import com.sun.tdk.jcov.tools.JcovVersion; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class Helper { public static void main(String[] args) { if (args.length > 0) { String arg = args[0]; if ("-version".equals(arg)) { System.out.println(String.format("JCov %s-%s", JcovVersion.jcovVersion, JcovVersion.jcovBuildNumber, JcovVersion.jcovMilestone) + ("beta".equals(JcovVersion.jcovMilestone) ? " beta" : "")); System.exit(0); } else { for (int i = 0; i < JCovTool.allToolsList.size(); i++) { // 17 = "com.sun.tdk.jcov." if (JCovTool.allToolsList.get(i).toLowerCase().substring(17).equals(arg.toLowerCase())) { try { Class c = Class.forName(JCovTool.allToolsList.get(i)); if (JCovCMDTool.class.isAssignableFrom(c)) { JCovCMDTool tool = (JCovCMDTool) c.newInstance(); // String[] newArgs = Arrays.copyOfRange(args, 1, args.length); String[] newArgs = new String[args.length - 1]; System.arraycopy(args, 1, newArgs, 0, args.length - 1); // jdk1.5 support System.exit(tool.run(newArgs)); } else if (JCovTool.class.isAssignableFrom(c)) { JCovTool.printHelp((JCovTool) c.newInstance(), args); System.exit(1); } else { System.out.println("INTERNAL ERROR! Specified tool ('" + arg + "') is not a jcovtool. "); System.exit(1); } } catch (ClassNotFoundException e) { System.out.println("INTERNAL ERROR! Specified tool was not found in classpath. "); System.exit(1); } catch (Exception e) { System.out.println("INTERNAL ERROR! " + e.getMessage()); e.printStackTrace(); System.exit(1); } } } } } JCovTool.printHelp(); } }
3,724
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
IssueCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/IssueCoverage.java
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.source.tree.*; import com.sun.source.util.JavacTask; import com.sun.source.util.SourcePositions; import com.sun.source.util.TreeScanner; import com.sun.source.util.Trees; import com.sun.tdk.jcov.filter.MemberFilter; import com.sun.tdk.jcov.instrument.*; import com.sun.tdk.jcov.processing.DataProcessorSPI; import com.sun.tdk.jcov.processing.DefaultDataProcessorSPI; import com.sun.tdk.jcov.processing.StubSpi; import com.sun.tdk.jcov.report.*; import com.sun.tdk.jcov.tools.*; import com.sun.tdk.jcov.util.Utils; import javax.tools.*; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; /** * @author Alexey Fedorchenko */ public class IssueCoverage extends JCovCMDTool { final static String DATA_PROCESSOR_SPI = "dataprocessor.spi"; private String hg_path = "hg"; private String hg_repo_dir = "jdk"; private String output = "report"; private String hg_comment = ""; private DataProcessorSPI dataProcessorSPIs[]; private static final Logger logger; private String resultFile; private String replaceDiff = ""; private HashMap<String, DiffCoverage.SourceLine[]> sources; static { Utils.initLogger(); logger = Logger.getLogger(IssueCoverage.class.getName()); } @Override protected int run() throws Exception { String[] command = new String[]{hg_path, "log", "-k", hg_comment}; ProcessBuilder pb = new ProcessBuilder(command) .directory(new File(hg_repo_dir)); Process proc = pb.start(); InputStream inputStream = proc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String logline; ArrayList<Integer> changesets = new ArrayList<Integer>(); while ((logline = br.readLine()) != null) { if (logline.contains("changeset:")) { try { changesets.add(Integer.parseInt(logline.split(":")[1].trim())); } catch (Exception e) { e.printStackTrace(); } } } if (changesets.size() == 0) { logger.log(Level.SEVERE, "No changes found in the repository for " + hg_comment); return ERROR_EXEC_EXIT_CODE; } String[] change_command = new String[changesets.size() + 2]; change_command[0] = hg_path; change_command[1] = "diff"; for (int i = 0; i < changesets.size(); i++) { change_command[i + 2] = "-c " + changesets.get(i); } ProcessBuilder pb1 = new ProcessBuilder(change_command) .directory(new File(hg_repo_dir)); Process proc1 = pb1.start(); InputStream patchInputStream = proc1.getInputStream(); try { BufferedReader in = new BufferedReader(new InputStreamReader(patchInputStream, "UTF-8")); DiffCoverage.DiffHandler handler = new DiffCoverage.HGDiffHandler(in); sources = new HashMap<String, DiffCoverage.SourceLine[]>(); String sourceName; while ((sourceName = handler.getNextSource()) != null) { LinkedList<DiffCoverage.SourceLine> lines = new LinkedList<DiffCoverage.SourceLine>(); DiffCoverage.SourceLine line; while ((line = handler.getNextSourceLine()) != null) { lines.add(line); } if (lines.size() > 0) { logger.log(Level.INFO, "File {0} has {1} new lines", new Object[]{sourceName, lines.size()}); sources.put(sourceName, lines.toArray(new DiffCoverage.SourceLine[lines.size()])); } else { logger.log(Level.INFO, "File {0} doesn't have new lines", sourceName); } } } catch (Exception ex) { logger.log(Level.SEVERE, "Error while parsing diff", ex); return ERROR_EXEC_EXIT_CODE; } final HashMap<String, ArrayList<MethodWithParams>> changed = new HashMap<String, ArrayList<MethodWithParams>>(); processChangedClasses(changesets, changed); DataRoot data = com.sun.tdk.jcov.io.Reader.readXML(resultFile, false, new MemberFilter() { public boolean accept(DataClass clz) { String className; if (replaceDiff != null && replaceDiff.contains("#module")) { className = replaceDiff.replaceAll("\\#module", clz.getModuleName()) + clz.getFullname().substring(0, clz.getFullname().lastIndexOf('/') + 1) + clz.getSource(); } else { className = replaceDiff + clz.getFullname().substring(0, clz.getFullname().lastIndexOf('/') + 1) + clz.getSource(); } return (changed.get(className) != null); } public boolean accept(DataClass clz, DataMethod m) { return true; } public boolean accept(DataClass clz, DataField f) { return true; } }); if (dataProcessorSPIs != null) { for (DataProcessorSPI spi : dataProcessorSPIs) { data = spi.getDataProcessor().process(data); } } AncFilter notChanged = new AncFilter() { @Override public boolean accept(DataClass clz) { return false; } @Override public boolean accept(DataClass clz, DataMethod m) { String className; if (replaceDiff != null && replaceDiff.contains("#module")) { className = replaceDiff.replaceAll("\\#module", clz.getModuleName()) + clz.getFullname().substring(0, clz.getFullname().lastIndexOf('/') + 1) + clz.getSource(); } else { className = replaceDiff + clz.getFullname().substring(0, clz.getFullname().lastIndexOf('/') + 1) + clz.getSource(); } if (changed.get(className) != null) { for (MethodWithParams method : changed.get(className)) { if (m.getName().equals(method.getMethodName()) || (m.getName().contains("$") && m.getName().endsWith(method.getMethodName()))) { if (method.getMethodParams().size() == 0 || m.getFormattedSignature().split(",").length == method.getMethodParams().size() && m.getFormattedSignature().matches(".*" + method.getParamsRegex())) { method.setFound(true); return false; } } } } return true; } @Override public boolean accept(DataMethod m, DataBlock b) { return false; } @Override public String getAncReason() { return "No changes"; } }; RepGen rr = new RepGen(); ReportGenerator rg = rr.getDefaultReportGenerator(); try { ReportGenerator.Options options = new ReportGenerator.Options(new File(hg_repo_dir + "/" + replaceDiff).getAbsolutePath(), null, null, false, false); ProductCoverage coverage = new ProductCoverage(data, options.getSrcRootPaths(), options.getJavapClasses(), false, false, false, new AncFilter[]{notChanged}); for (String classFile : changed.keySet()) { for (MethodWithParams method : changed.get(classFile)) { if (!method.isFound()) { logger.log(Level.WARNING, "Could not find changed method {0} from classfile {1}", new String[]{method.toString(), classFile}); } } } rg.init(output); rg.generateReport(coverage, options); } catch (Exception e) { logger.log(Level.SEVERE, "Error in report generation:", e); } return 0; } private void processChangedClasses(ArrayList<Integer> changesets, HashMap<String, ArrayList<MethodWithParams>> changed) { try { ArrayList<String> files = new ArrayList<String>(); String[] command = new String[]{hg_path, "log", "-k", hg_comment, "--stat"}; ProcessBuilder pb = new ProcessBuilder(command) .directory(new File(hg_repo_dir)); Process proc = pb.start(); InputStream inputStream = proc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String classline; while ((classline = br.readLine()) != null) { if (classline.contains("|") && (classline.contains("+") || classline.contains("-"))) { try { files.add(classline.split(" ")[1]); } catch (Exception e) { e.printStackTrace(); } } } parseClassFiles(files, changesets.get(0), changed); } catch (Exception e) { logger.log(Level.SEVERE, "Error in parsing changed files:", e); } } private void parseClassFiles(ArrayList<String> files, int changeset, HashMap<String, ArrayList<MethodWithParams>> changed) { try { for (String file : files) { String[] command = new String[]{hg_path, "cat", file, "-r", String.valueOf(changeset)}; ProcessBuilder pb = new ProcessBuilder(command) .directory(new File(hg_repo_dir)); Process proc = pb.start(); InputStream inputStream = proc.getInputStream(); final Path destination = Paths.get(new File(hg_repo_dir).getAbsolutePath() + File.pathSeparator + "temp" + File.pathSeparator + ".java"); Files.copy(inputStream, destination); DiffCoverage.SourceLine lines[] = sources.get(file); parseClassFile(destination.toFile(), lines, file, changed); destination.toFile().delete(); } } catch (Exception e) { logger.log(Level.SEVERE, "Error in parsing changed files:", e); } } private void parseClassFile(File c, DiffCoverage.SourceLine lines[], String classFile, HashMap<String, ArrayList<MethodWithParams>> changed) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, null, null); Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(c); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, fileObjects); JavacTask javacTask = (JavacTask) task; SourcePositions sourcePositions = Trees.instance(javacTask).getSourcePositions(); Iterable<? extends CompilationUnitTree> parseResult = null; try { parseResult = javacTask.parse(); } catch (IOException e) { logger.log(Level.SEVERE, "Error in parsing source file:", e); } if (parseResult != null) { for (CompilationUnitTree compilationUnitTree : parseResult) { compilationUnitTree.accept(new MethodParser(compilationUnitTree, sourcePositions, lines, classFile, changed), null); } } } private class MethodParser extends TreeScanner<Void, Void> { private final CompilationUnitTree compilationUnitTree; private final SourcePositions sourcePositions; private final LineMap lineMap; private final DiffCoverage.SourceLine lines[]; private HashMap<String, ArrayList<MethodWithParams>> changed; private String classFile; private List<ClassTree> classes; private MethodParser(CompilationUnitTree compilationUnitTree, SourcePositions sourcePositions, DiffCoverage.SourceLine lines[], String classFile, HashMap<String, ArrayList<MethodWithParams>> changed) { this.compilationUnitTree = compilationUnitTree; this.sourcePositions = sourcePositions; this.lineMap = compilationUnitTree.getLineMap(); this.lines = lines; this.changed = changed; this.classFile = classFile; classes = new ArrayList<ClassTree>(); } @Override public Void visitClass(ClassTree paramClassTree, Void paramP) { classes.add(paramClassTree); return super.visitClass(paramClassTree, paramP); } private String findClassName(MethodTree method) { String simpleName = ""; String className = ""; HashMap<String, Integer> annonym = new HashMap<String, Integer>(); for (ClassTree classTree : classes) { simpleName = classTree.getSimpleName().toString(); if (simpleName.isEmpty()) { if (annonym.get(className) == null) { annonym.put(className, 1); } else { annonym.put(className, annonym.get(className) + 1); } } else { className = String.valueOf(simpleName); } for (Tree tree : classTree.getMembers()) { if (method.equals(tree)) { if (simpleName.isEmpty()) { simpleName = className + "$" + annonym.get(className); } return simpleName; } } } return simpleName; } @Override public Void visitMethod(final MethodTree arg0, Void arg1) { long startPosition = sourcePositions.getStartPosition(compilationUnitTree, arg0); long startLine = lineMap.getLineNumber(startPosition); long endPosition = sourcePositions.getEndPosition(compilationUnitTree, arg0); long endLine = lineMap.getLineNumber(endPosition); if (lines != null) { for (DiffCoverage.SourceLine line : lines) { if (line.line >= startLine && line.line <= endLine) { if (changed.get(classFile) == null) { changed.put(classFile, new ArrayList<MethodWithParams>()); } String simpleClassName = findClassName(arg0); String methodName = classFile.endsWith(simpleClassName + ".java") ? arg0.getName().toString() : "$" + simpleClassName + "." + arg0.getName(); List<String> params = new ArrayList<String>(); for (VariableTree vt : arg0.getParameters()) { params.add(vt.getType().toString()); } changed.get(classFile).add(new MethodWithParams(methodName, params)); return super.visitMethod(arg0, arg1); } } } return super.visitMethod(arg0, arg1); } } @Override protected EnvHandler defineHandler() { EnvHandler envHandler = new EnvHandler(new OptionDescr[]{ DSC_REPLACE_DIFF, DSC_ISSUE_TO_FIND, DSC_REPO_DIR, DSC_OUTPUT, DSC_HG_PATH }, this); SPIDescr spiDescr = new SPIDescr(DATA_PROCESSOR_SPI, DataProcessorSPI.class); spiDescr.addPreset("none", new StubSpi()); spiDescr.setDefaultSPI(new DefaultDataProcessorSPI()); envHandler.registerSPI(spiDescr); return envHandler; } @Override protected int handleEnv(EnvHandler envHandler) throws EnvHandlingException { String[] tail = envHandler.getTail(); if (tail == null) { throw new EnvHandlingException("No input files. Please specify JCov data file and diff (mercurial) file."); } ArrayList<DataProcessorSPI> dataProcessors = envHandler.getSPIs(DataProcessorSPI.class); if (dataProcessors != null) { dataProcessorSPIs = dataProcessors.toArray(new DataProcessorSPI[dataProcessors.size()]); } replaceDiff = envHandler.getValue(DSC_REPLACE_DIFF); hg_path = envHandler.getValue(DSC_HG_PATH); hg_comment = envHandler.getValue(DSC_ISSUE_TO_FIND); hg_repo_dir = envHandler.getValue(DSC_REPO_DIR); output = envHandler.getValue(DSC_OUTPUT); resultFile = tail[0]; Utils.checkFileNotNull(tail[0], "JCov datafile", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_ISFILE, Utils.CheckOptions.FILE_CANREAD); return SUCCESS_EXIT_CODE; } @Override protected String getDescr() { return null; } @Override protected String usageString() { return null; } @Override protected String exampleString() { return null; } class MethodWithParams { private String methodName; private List<String> methodParams; private boolean found = false; MethodWithParams(String methodName, List<String> methodParams) { this.methodName = methodName; this.methodParams = methodParams; } public List<String> getMethodParams() { return methodParams; } public void setMethodParams(List<String> methodParams) { this.methodParams = methodParams; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public String getParamsRegex() { if (methodParams.size() == 0) { return "\\(\\)"; } StringBuilder sb = new StringBuilder(); sb.append("\\("); for (int i = 0; i < methodParams.size(); i++) { String param = methodParams.get(i); if (param.equals("K") || param.equals("V")) { param = "Object"; } if (param.contains("<")) { param = param.substring(0, param.indexOf("<")); } param = Pattern.quote(param); if (i < methodParams.size() - 1) { sb.append(".*").append(param).append(","); } else { sb.append(".*").append(param).append("\\)"); } } return sb.toString(); } public boolean isFound() { return found; } public void setFound(boolean found) { this.found = found; } public String toString() { StringBuilder result = new StringBuilder(); result.append(methodName).append("( "); for (String param : methodParams) { result.append(param).append(" "); } result.append(")"); return result.toString(); } } static OptionDescr DSC_HG_PATH = new OptionDescr("hgPath", new String[]{"hgPath", "hg"}, "", OptionDescr.VAL_SINGLE, "Path to the hg", "hg"); static OptionDescr DSC_REPLACE_DIFF = new OptionDescr("replaceDiff", "Manage replacing", OptionDescr.VAL_SINGLE, "Set replacement pattern for diff filenames (e.g. to cut out \"src/classes\" you can specify -replaceDiff src/classes:)"); static OptionDescr DSC_ISSUE_TO_FIND = new OptionDescr("issueToFind", new String[]{"issueToFind","if"}, "", OptionDescr.VAL_SINGLE, "Set issue identifier to find in repository history"); static OptionDescr DSC_REPO_DIR = new OptionDescr("localRepo", new String[]{"localRepo", "lr"}, "", OptionDescr.VAL_SINGLE, "Path to the local repository"); static OptionDescr DSC_OUTPUT = new OptionDescr("output", new String[]{"output", "o"}, "", OptionDescr.VAL_SINGLE, "Output directory for generating HTML report.", "report"); }
21,985
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Grabber.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/Grabber.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.constants.MiscConstants; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.data.Result; import com.sun.tdk.jcov.instrument.*; import com.sun.tdk.jcov.instrument.DataRoot.CompatibilityCheckResult; import com.sun.tdk.jcov.instrument.InstrumentationOptions.MERGE; import com.sun.tdk.jcov.runtime.Collect; import com.sun.tdk.jcov.runtime.FileSaver; import com.sun.tdk.jcov.runtime.PropertyFinder; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.JcovVersion; import com.sun.tdk.jcov.tools.LoggingFormatter; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.RuntimeUtils; import com.sun.tdk.jcov.util.Utils; import com.sun.tdk.jcov.util.Utils.Pair; import java.io.*; import java.net.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.LinkedList; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; /** * Class Client serves to collect data from remote client. isWorking() should * return true until all data is processed by Server. * * @author Dmitry Fazunenko * @author Alexey Fedorchenko * * @see #isWorking() */ class Client extends Thread { private final Socket socket; // socket private final Server server; // server private final int clientNumber; // number of this client private boolean working = true; // set to false when data is read public static int unknownTestNumber = 0; // number of unknown tests got from clients // runtime data - got from client side private String testName; // test name private String testerName; // tester name private String productName; // product name private int slotNumber; // slots number (in static mode) private static final int MAX_SLOTS = Collect.MAX_SLOTS; public static final String UNKNOWN = "<unknown>"; /** * Constructor for Client class Sets "Client{clientNumber}Thread" as the * name of the thread * * @param server Server object this client is connected to * @param socket Remote clients socket * @param clientNumber ID of this client */ public Client(Server server, Socket socket, int clientNumber) { super(); setName("Client" + clientNumber + "Thread"); setDaemon(false); this.socket = socket; this.server = server; this.clientNumber = clientNumber; } /** * <p> Main method. Use start() to launch in new thread. </p> <p> Reads data * as long[] or as DataRoot and forwards it to the Server </p> <p> Sets * accepted test name, tester name and product name. Use getTestName(), * getTesterName() and getProductName() to read them. </p> */ @Override public void run() { executeClient(); } public void executeClient() { DataInputStream IN = null; byte buff[]; boolean legacy = false, dynamic = false; int version; long reserve = 0L; try { // synchronized (Server.STOP_THE_WORLD_LOCK) { // server.checkFreeMemory(30000000L); // 30mb for a client seems to be OK /* while (server.isDumping()) { // locks the thread when is dumping Server.STOP_THE_WORLD_LOCK.wait(); }*/ IN = new DataInputStream(new BufferedInputStream(socket.getInputStream())); buff = new byte[4]; for (int i = 0; i < buff.length; ++i) { buff[i] = IN.readByte(); } if (!new String(buff, "UTF-8").equals("JCOV")) { reserve = 10000000L; // 10mb legacy = true; } else { version = IN.read(); testerName = IN.readUTF(); testName = IN.readUTF(); productName = IN.readUTF(); if ("".equals(testName)) { testName = testName + " " + testerName + " " + productName + "_test" + ++unknownTestNumber; } Grabber.logger.log(Level.FINE, "Got test data: name {0}, tester {1}, product {2}", new Object[]{testName, testerName, productName}); dynamic = IN.readBoolean(); if (dynamic) { reserve = 50000000L; // 50mb } else { reserve = Collect.SLOTS * 10; } } //server.increaseReserved(reserve); //} // release synchronized (Server.STOP_THE_WORLD_LOCK) if (legacy) { Grabber.logger.log(Level.FINE, "Header missmatch from client N{0}: '{1}'. Reading as legacy", new Object[]{clientNumber + "", new String(buff, "UTF-8")}); // reading in old format - not to forget include first 8 bytes // in old format we can't get less or more than 1bill longs - so reading them all in long[1000000] testerName = UNKNOWN; testName = "test" + ++unknownTestNumber; productName = UNKNOWN; long ids[] = new long[1000000]; // copying the first long to the result array for (int j = 0; j < 4; ++j) { ids[0] += ((long) buff[j] & 0xffL) << (8 * j); } int i = 1; try { for (; i < 1000000; ++i) { ids[i] = IN.readLong(); } } catch (EOFException e) { Grabber.logger.log(Level.SEVERE, "Got incorrect number of longs from legacy-format client N{0}: {1}, expected 1 000 000", new Object[]{clientNumber + "", i}); return; } IN.close(); IN = null; Grabber.logger.log(Level.FINER, "Got legacy-format static data from client N{0}", clientNumber + ""); saveResults(ids); return; } else { if (dynamic) { DataRoot root = new DataRoot(IN); slotNumber = root.getCount(); IN.close(); IN = null; saveResults(root); } else { String templateHash = IN.readUTF(); slotNumber = IN.readInt(); int lastIndex = IN.readInt(); long ids[] = new long[lastIndex + 1]; int i = 0; try { for (; i < slotNumber; ++i) { int index = IN.readInt(); ids[index] = IN.readLong(); } } catch (EOFException e) { Grabber.logger.log(Level.SEVERE, "Got incorrect number of longs from static client N{0}: found {1}, expected {2}", new Object[]{clientNumber + "", i, slotNumber}); } catch (IOException ioe) { Grabber.logger.log(Level.WARNING, "Got incorrect number of longs from static client N{0}: found {1}, expected {2}", new Object[]{clientNumber + "", i, slotNumber}); } IN.close(); IN = null; socket.close(); Grabber.logger.log(Level.FINER, "Got new-format static data from client N{0}", clientNumber + ""); saveResults(ids); } } } catch (Exception e) { Grabber.logger.log(Level.SEVERE, "e =" + e); Grabber.logger.log(Level.SEVERE, "Error while receiving data from client N" + clientNumber, e); // e.printStackTrace(); } finally { server.decreaseReserved(reserve); // java7+try-with-resources rules if (IN != null) { try { IN.close(); } catch (IOException ex) { } } if (!socket.isClosed()) { try { socket.close(); } catch (IOException ex) { } } --server.aliveClients; working = false; // all is done Grabber.logger.log(Level.FINE, "Client N{0} done", clientNumber + ""); } } /** * Handle got data. Translates data to the Server. * * @param ids Data in long[] form transferred from client */ private void saveResults(long[] ids) { server.handleData(ids, this); } /** * Handle got data. Translates data to the Server. * * @param root Data in DataRoot transferred from client */ private void saveResults(DataRoot root) { server.handleData(root, this); } /** * Returns client address * * @return Client address formatted as 'host:port' * @see #Client(com.sun.tdk.jcov.Server, java.net.Socket, int) */ public String getClientAddress() { return socket.getInetAddress().getHostName() + ":" + socket.getLocalPort(); } /** * Returns ID assigned to this Client * * @return ID assigned to this Client * @see #Client(com.sun.tdk.jcov.Server, java.net.Socket, int) */ public int getClientNumber() { return clientNumber; } /** * Answers whether Client have finished transactions. * * @return false when all transactions are finished (data received and * translated to Server or Exception occurred) */ public boolean isWorking() { return working; } /** * @return test name accepted from client side or generated test name */ public String getTestName() { return testName; } /** * @return tester name accepted from client side or &lt;unknown&gt; */ public String getTesterName() { return testerName; } /** * @return product name accepted from client side or &lt;unknown&gt; */ public String getProductName() { return productName; } } // ############# Client /** * Server class manages incoming client connections and handles coverage data * coming from them. * * @see #handleData(long[], com.sun.tdk.jcov.Client) */ class Server extends Thread { // config data private String fileName; // output file private final String templateName; // template file private final int port; // port to listen for client connections private int saveCount; // maximum connections to manage. Infinite if 0 private boolean saveAtReceive; // true = save data when it's coming from Client private final String hostName; // host to connect in 'once' mode private final boolean once; // enables 'once' mode private String outTestList; // output testlist file private boolean genscale; // allows to generate scales without outtestlist private String saveBadData; // path to save bad agent data to // status data private boolean working = true; // thread is working (not dead). Set to false at kill() method and when exiting main loop. private boolean listening = true; // thread is listening for new connections. Set to false when exiting main loop. private boolean dataSaved = false; // no notsaved data. Set to true when accepting new data, set to false when writing data. private boolean started = false; // set to true when all initialization is done. // runtime data private ServerSocket ss = null; // socket listener private long[] data = null; // data got from clients. Not used in SaveAtReceive mode private DataRoot dataRoot = null; // data got from clients. Not used in SaveAtReceive mode private int totalConnections; // connections occurred int aliveClients = 0; // increased on client.start(), decreased in client private LinkedList<String> tests; // accepted testnames static int MAX_TIMEOUT = 90000; // maximum time to wait for Client working static boolean showMemoryChecks = false; // show memory checks final static Runtime rt = Runtime.getRuntime(); // runtime private long reservedMemory = 0; // memory reserved by alive clients - not used yet private int dumpCount = 0; // number of dumped files private boolean dumping = false; // dumping proccess is going on static final Object STOP_THE_WORLD_LOCK = new Object(); // LOCK private boolean veryLowMemoryRun = false; // very low memory mode - minimal memory lock, no merge private boolean lowMemoryRun = false; // low memory mode - minimal memory lock, merge private boolean normalMemoryRun = false; // normal memory mode - 45% memory lock, merge private boolean mergeByTestNames = false;// generate scales based on test names (test name identifies test) private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); /** * <p> Constructor for Server class. Warning: ServerSocket will be opened in * constructor so port will be binded. </p> <p> Sets "ServerThread" as the * name of the thread. </p> * * @param port port to listen for client connections * @param once enables 'once' mode - Server connects to hname:port and * receives data from there * @param template template file * @param host host to connect in 'once' mode * @param saveAtRecieve true = save data when it's coming from Client * @param genscale allows to generate scales without outtestlist * @throws BindException * @throws IOException */ public Server(int port, boolean once, String template, String host, boolean saveAtRecieve, boolean genscale, boolean mergeByTestNames) throws BindException, IOException { super(); setName("ServerThread"); setDaemon(false); totalConnections = 0; this.once = once; this.templateName = template; this.hostName = host; this.saveAtReceive = saveAtRecieve; this.genscale = genscale; this.mergeByTestNames = mergeByTestNames; if (this.genscale) { tests = new LinkedList<String>(); } if (this.once) { this.port = port; if (this.port == 0) { throw new IllegalArgumentException("Port should be specified in 'once' mode"); } } else { try { initDataRoot(); // checking available memory if (genscale) { rt.gc(); if (rt.totalMemory() > rt.maxMemory() / 1.2) { Grabber.logger.log(Level.WARNING, "Server started with very low memory: it''s recomended at least {0}M max memory for this template. Server will not write data dumps on low memory and can fail in OutOfMemoryError.", rt.totalMemory() * 3 / 1000000); veryLowMemoryRun = true; } else if (rt.totalMemory() > rt.maxMemory() / 2.5) { if (showMemoryChecks) { Grabber.logger.log(Level.WARNING, "Server started with low memory: it''s recomended at least {0}M max memory for this template. Server will write data dumps on low memory and will try to merge them on exit.", rt.totalMemory() * 2.5 / 1000000); } lowMemoryRun = true; } else { if (showMemoryChecks) { Grabber.logger.log(Level.INFO, "Server will write data dumps on 45% free memory and will try to merge them on exit."); } normalMemoryRun = true; } } } catch (FileFormatException ex) { throw new IllegalArgumentException("Bad template: " + templateName, ex); } this.ss = new ServerSocket(port); this.port = ss.getLocalPort(); // updating port number - when port == 0 ServerSocket will take any free port } } /** * <p> Constructor for Server class. Warning: ServerSocket will be opened in * constructor so port will be binded. </p> <p> Sets "ServerThread" as the * name of the thread </p> * * @param port port to listen for client connections * @param once enables 'once' mode - Server connects to hname:port and * receives data from there * @param template template file * @param output output file * @param outTestList file to write testlist to * @param host host to connect in 'once' mode * @param maxCount maximum connections to manage. Infinite if 0 * @param saveAtReceive true = save data when it's coming from Client * @param genscale allows to generate scales without outtestlist * @throws BindException * @throws IOException */ Server(int port, boolean once, String template, String output, String outTestList, String host, int maxCount, boolean saveAtReceive, boolean genscale, boolean mergeByTestNames) throws BindException, IOException { this(port, once, template, host, saveAtReceive, genscale || outTestList != null, mergeByTestNames); this.fileName = output; this.outTestList = outTestList; this.saveCount = maxCount; } @Override public synchronized void start() { super.start(); } /** * Main method. Use start() to launch in new thread. 1. In 'once' mode * Server opens Socket to hostName:port, creates a Client object for this * Socket and receives data from it (all in one thread). Then it dies. 2. In * other case Server starts accepting client connections by ServerSocket. * For every connected client Server creates Client object and starts it in * new thread waiting for next connection. Client receives data and * translates it back to Server. Server will stop when maxCount connections * will be received or at system shutdown (eg Ctrl-C) or when kill() method * will be called (eg by CommandListener) */ @Override public void run() { if (once) { // 'client' mode - single data connection to hostName:port started = true; InetAddress adr; try { if (hostName == null) { adr = InetAddress.getLocalHost(); } else { adr = InetAddress.getByName(hostName); } Socket s = new Socket(adr, port); Grabber.logger.log(Level.INFO, "Connection established with {0}:{1}", new Object[]{adr, port}); ++aliveClients; new Client(this, s, 0).executeClient(); // running client in local thread saveData(); Grabber.logger.log(Level.FINE, "Server stopped"); } catch (Exception e) { Grabber.logger.log(Level.SEVERE, "Jcov grabber failed", e); } finally { working = false; } } else { // server mode - receive data saveCount times (or any if 0) started = true; try { int n = 0; do { Grabber.logger.log(Level.FINE, "Waiting for new connection"); Socket s = ss.accept(); Client c = new Client(this, s, ++n); Grabber.logger.log(Level.INFO, "Connection N{0} received from {1}:{2}", new Object[]{n + "", s.getInetAddress(), s.getLocalPort() + ""}); // s.getLocalPort() + "" - to avoid int formatting Grabber.logger.log(Level.FINE, "Alive connections: {0}; total connections: {1}", new Object[]{aliveClients + 1 + "", totalConnections + 1 + ""}); ++aliveClients; executor.execute(c); //c.start(); ++totalConnections; } while (--saveCount != 0 && listening); // kill() sets listening to false to break the loop if (saveCount == 0 && listening) { // normal exit kill(false); // ServerSocket will not produce exception on ss.close() as accept() is not waiting } } catch (Throwable e) { if (listening) { // loop was broken without kill() -> real exception. When kill() is called - ServerSocket.close() is called so IOException is thrown LoggingFormatter.printStackTrace = true; Grabber.logger.log(Level.SEVERE, "JCov grabber failed", e); working = false; } } finally { int timeout = 0; while (working && timeout < MAX_TIMEOUT * 2) { // if working == true -> kill(false) was called when some client are still alive. Server waits for their ending. try { Thread.sleep(500); timeout += 500; } catch (InterruptedException ex) { } } ss = null; working = false; listening = false; Grabber.logger.log(Level.FINE, "Server stopped"); } } } /** * Stop listening socket for new client connections and close socket * listener. IOException will be thrown in run() method from ServerSocket as * it will be closed. * * @param force when false - server will wait till all alive clients will * end transmitting data */ public void kill(boolean force) { listening = false; if (ss != null && !ss.isClosed()) { try { ss.close(); // killing socket listener } catch (Exception ex) { Grabber.logger.log(Level.SEVERE, "Error while closing socket", ex); } } if (!force && clientsAlive()) { Grabber.logger.log(Level.INFO, "Awaiting for finishing data transmission from {0} clients. Max timeout time: {1}ms", new Object[]{getAliveConnectionCount() + "", MAX_TIMEOUT}); waitForAliveClients(); // getting data from alive connected clients } if (!force) { if (!dataSaved) { saveData(); if (dataRoot != null) { // started without template dataRoot.destroy(); } if (dumpCount > 0) { if (veryLowMemoryRun) { // not merging at very low - it's not possible } else { Grabber.logger.log(Level.WARNING, "Server is merging dumped data: {0} files should be merged", dumpCount + ""); // merge datafiles Merger merger = new Merger(); Result res[] = new Result[dumpCount + 1]; try { res[0] = new Result(fileName, outTestList); for (int i = 0; i < dumpCount; ++i) { if (outTestList != null) { res[i + 1] = new Result(fileName, outTestList + i); } } } catch (IOException ignore) { } System.out.println("Server.this.templateName = " + Server.this.templateName); Merger.Merge m = new Merger.Merge(res, Server.this.templateName); try { merger.mergeAndWrite(m, outTestList, fileName, null); } catch (OutOfMemoryError e) { Grabber.logger.log(Level.SEVERE, "OutOfMemoryError while merging dumped files. Please merge them manually: 'java -jar jcov.jar merger -o {0} -outTestList {1} {0}%{1} {0}0%{1}) {0}1%{1}1 ...'.", new Object[]{fileName, outTestList}); } catch (Throwable ignore) { } for (int i = 0; i < dumpCount; ++i) { new File(fileName + dumpCount).delete(); new File(outTestList + dumpCount).delete(); } Grabber.logger.log(Level.INFO, "Merging done"); } } } } executor.shutdown(); working = false; } /** * Read template from templateName and initializes template * * @throws FileFormatException */ private void initDataRoot() throws FileFormatException { if (templateName != null) { Grabber.logger.log(Level.FINE, "Server is reading template {0}", templateName); this.dataRoot = DataRoot.read(templateName, false, null); this.dataRoot.makeAttached(); Collect.SLOTS = this.dataRoot.getCount(); Collect.enableCounts(); this.data = Collect.counts(); if (genscale) { // creating empty scales this.dataRoot.getScaleOpts().setReadScales(true); if (outTestList != null) { this.dataRoot.getScaleOpts().setOutTestList(outTestList); } this.dataRoot.cleanScales(); // making zero scales } Grabber.logger.log(Level.FINER, "Server finished reading template", templateName); } else { // DataRoot will be created at first data accept } } /** * Receives data from Client and handles it. In SaveAtReceive mode Server * saves data instantly by calling saveData(data) method. In SaveAtExit mode * Server stores clients data and merges it in memory. Real saving will * occur as saveData() method calls. Sets dataSaved to false * * @param data received clients data to handle * @param client client received the data (used for logging) * @see #saveData() */ public synchronized void handleData(long[] data, Client client) { if (!working) { return; } if (templateName == null) { Grabber.logger.log(Level.SEVERE, "Server can't accept static data - started without template"); return; } dataSaved = false; Grabber.logger.log(Level.INFO, "Server got data from client N{0}", client.getClientNumber() + ""); if (saveAtReceive) { Grabber.logger.log(Level.FINE, "Server is saving data from client N{0}", client.getClientNumber() + ""); for (int i = 0; i < data.length && i < dataRoot.getCount(); ++i) { this.data[i] += data[i]; } saveData(data); } else { if (this.data == null) { // no need for Collect.enableCounts as it's performed in Collect.clinit this.data = Collect.counts(); } for (int i = 0; i < data.length && i < dataRoot.getCount(); ++i) { this.data[i] += data[i]; } if (genscale) { dataRoot.addScales(); dataRoot.update(); boolean merged = false; if (mergeByTestNames) { for (int i = 0; i < tests.size(); i++) { if (tests.get(i).equals(client.getTestName())) { ArrayList<Pair> list = new ArrayList<Pair>(); list.add(new Utils.Pair(i, tests.size())); this.dataRoot.illuminateDuplicatesInScales(list); merged = true; break; } } } if (!merged) { tests.add(client.getTestName()); } } } Grabber.logger.log(Level.FINEST, "Data from client N{0} saved", client.getClientNumber() + ""); } /** * Receives data from Client and handles it. In SaveAtReceive mode Server * saves data instantly by calling saveData(data) method. In SaveAtExit mode * Server stores clients data and merges it in memory. Real saving will * occur as saveData() method calls. Sets dataSaved to false * * @param root received clients data to handle * @param client client received the data (used for logging) * @see #saveData() */ public synchronized void handleData(DataRoot root, Client client) { boolean merged = false; try { if (!working) { return; } dataSaved = false; Grabber.logger.log(Level.FINER, "Server got dynamic data from client N{0}", client.getClientNumber() + ""); if (saveAtReceive) { try { root.write(fileName, MERGE.MERGE); } catch (Exception ex) { Grabber.logger.log(Level.SEVERE, "Server can't save data from client N{0} to file '{1}' on recieve: {2}", new Object[]{client.getClientNumber() + "", fileName, ex.getMessage()}); } } else { Grabber.logger.log(Level.FINE, "Server is merging dynamic data from client N{0}", client.getClientNumber() + ""); root.getScaleOpts().setScaleSize(root.getScaleOpts().getScaleSize() + 1); // dynamic data mode only - template == null. In this mode should save first data got as dataRoot if (templateName == null && dataRoot == null) { dataRoot = root; dataRoot.attach(); if (genscale && (dataRoot.getScaleOpts() == null || !dataRoot.getScaleOpts().needReadScales())) { dataRoot.getScaleOpts().setReadScales(true); dataRoot.getScaleOpts().setOutTestList(outTestList); dataRoot.getScaleOpts().setScaleSize(1); tests.add(client.getTestName()); } } else { // merging. First of all - checking compatibility. int severity = 0; // merge with template - different data is allowed - only template data will be merged if (templateName != null) { severity = 3; } CompatibilityCheckResult cc = this.dataRoot.checkCompatibility(root, severity, true); if (cc.errors == 0) { // merge + scale if needed if (genscale && mergeByTestNames) { for (int i = 0; i < tests.size(); i++) { if (tests.get(i).equals(client.getTestName())) { this.dataRoot.merge(root, templateName == null); ArrayList<Pair> list = new ArrayList<Pair>(); list.add(new Utils.Pair(i, tests.size())); this.dataRoot.illuminateDuplicatesInScales(list); merged = true; break; } } } if (genscale && !merged) { this.dataRoot.merge(root, templateName == null); tests.add(client.getTestName()); merged = true; } if (!genscale) { this.dataRoot.merge(root, templateName == null); merged = true; } Grabber.logger.log(Level.FINER, "Server finished merging dynamic data from client N{0}", client.getClientNumber() + ""); } else { // data not compatible - flushing to file if selected if (saveBadData != null) { String filename = saveBadData + "_" + client.getTestName() + ".xml"; Grabber.logger.log(Level.INFO, "Malformed data from client N{0}: saving data to '{1}'", new Object[]{client.getClientNumber() + "", filename}); try { root.write(filename, MERGE.GEN_SUFF); } catch (Exception ex) { Grabber.logger.log(Level.SEVERE, "Can't save malformed data from client N{0} to file '{1}': {2}", new Object[]{client.getClientNumber() + "", filename, ex.getMessage()}); } } else { Grabber.logger.log(Level.SEVERE, "Malformed data from client N{0}: not saving", client.getClientNumber() + ""); } } } } } finally { if (dataRoot != root && !merged) { // destroy not needed if already merged - "root" was destroyed in DataRoot.merge root.destroy(); } } } /** * Save data to file if it's needed (if dataSaved == false) */ public synchronized void saveData() { if (dataSaved == true) { Grabber.logger.log(Level.FINE, "No new data received - nothing to save"); return; // nothing to do - received data is already saved } Grabber.logger.log(Level.INFO, "Server is saving cached data to {0}", fileName); saveData(data); Grabber.logger.log(Level.FINE, "Saving done"); } /** * Save data to file. In SaveAtExit mode file will always be rewritten. Sets * dataSaved to true * * @param data data to save */ private synchronized void saveData(long[] data) { try { if (!saveAtReceive) { File file = new File(fileName); if (file.exists()) { if (!file.delete()) { File nfile = getUnexistingFile(file); Grabber.logger.log(Level.SEVERE, "Error: given file '{0}' exists, cannot overwrite it. Data saved to '{1}'", new Object[]{file.getPath(), nfile.getPath()}); file = nfile; fileName = nfile.getPath(); } } } if (dataRoot != null) { if (templateName != null) { //do not need it at all dataRoot.update(); if (dataRoot.getParams().isInstrumentAbstract() || dataRoot.getParams().isInstrumentNative()) { for (DataPackage dp : dataRoot.getPackages()) { for (DataClass dc : dp.getClasses()) { for (DataMethod dm : dc.getMethods()) { if ((dm.getModifiers().isAbstract() || dm.getModifiers().isNative()) && data.length > dm.getSlot() && dm.getCount() < data[dm.getSlot()]) { dm.setCount(data[dm.getSlot()]); } } } } } } FileSaver fs = FileSaver.getFileSaver(dataRoot, fileName, templateName, MERGE.OVERWRITE, false, true); fs.saveResults(fileName); } else if (templateName != null) { Utils.copyFile(new File(templateName), new File(fileName)); } if (outTestList != null) { Utils.writeLines(outTestList, tests.toArray(new String[tests.size()])); } dataSaved = true; } catch (Exception ex) { Grabber.logger.log(Level.SEVERE, "Error while saving data", ex); // ex.printStackTrace(); } } void increaseReserved(long reserve) { reservedMemory += reserve; } void decreaseReserved(long reserve) { reservedMemory -= reserve; } synchronized boolean checkFreeMemory(long minMemory) throws Exception { if (genscale) { long mem = rt.freeMemory() + (rt.maxMemory() - rt.totalMemory()); // mem - current total free memory (free + non-allocated) if (showMemoryChecks) { Grabber.logger.log(Level.FINER, "Memory check routine. Total: {0}; max: {1}; free: {2}; max-total {3}", new Object[]{rt.totalMemory(), rt.maxMemory(), rt.freeMemory(), rt.maxMemory() - rt.totalMemory()}); } if (((veryLowMemoryRun || lowMemoryRun) && mem < minMemory) || (normalMemoryRun && (rt.totalMemory() - rt.freeMemory()) > rt.maxMemory() / 3)) { // if (rt.totalMemory() > rt.maxMemory() / 2.1) { Grabber.logger.log(Level.INFO, "Server is at low memory: trying to clean memory..."); rt.gc(); Thread.yield(); mem = rt.freeMemory() + (rt.maxMemory() - rt.totalMemory()); if ((lowMemoryRun && mem < minMemory && !dumping) || (normalMemoryRun && (rt.totalMemory() - rt.freeMemory()) > rt.maxMemory() * 0.45)) { // if (rt.totalMemory() > rt.maxMemory() / 1.5 && totalConnections > 10 && !dumping) { Grabber.logger.log(Level.WARNING, "Server is at low memory: cleaning memory didn''t help - {0}mb free memory left. Dumping data to the file...", mem); dumpAndResetData(); return true; } } } return false; } boolean isDumping() { synchronized (STOP_THE_WORLD_LOCK) { return dumping; } } private synchronized void dumpAndResetData() throws Exception { dumping = true; Thread t = new Thread() { @Override public void run() { synchronized (STOP_THE_WORLD_LOCK) { try { dataRoot.update(); FileSaver fs = FileSaver.getFileSaver(dataRoot, fileName + dumpCount, templateName, MERGE.OVERWRITE, false, true); fs.saveResults(fileName + dumpCount); if (outTestList != null) { Utils.writeLines(outTestList + dumpCount, tests.toArray(new String[tests.size()])); tests.clear(); } dataRoot.cleanScales(); for (int i = 0; i < data.length; ++i) { data[i] = 0; } dataRoot.update(); // needed? } catch (Exception ex) { throw new RuntimeException(ex); } finally { ++dumpCount; dumping = false; STOP_THE_WORLD_LOCK.notifyAll(); } } } }; t.setName("DumpingThread" + dumpCount); t.setPriority(Thread.MAX_PRIORITY); t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { } }); t.start(); } private static File getUnexistingFile(File file) { File temp = null; do { String suffix = RuntimeUtils.genSuffix(); temp = new File(file.getPath() + suffix); } while (temp.exists()); return temp; } /** * Wait until all alive clients will finish working */ private void waitForAliveClients() { int timeout = 0; while (timeout < MAX_TIMEOUT && clientsAlive()) { try { Thread.sleep(100); timeout += 100; } catch (InterruptedException e) { return; } } } /** * Checks that all clients have finish working Removes dead Client objects * from clients list * * @return false when all clients have finish working */ private boolean clientsAlive() { return aliveClients > 0; } /** * Server is working * * @return server is working */ public boolean isWorking() { return working; } public boolean isStarted() { return started; } /** * Returns count of all connections occurred * * @return count of all connections occurred */ public int getConnectionsCount() { return totalConnections; } /** * Returns count of connections that are alive at the moment The number can * change fastly * * @return count of connections that are alive at the moment */ public int getAliveConnectionCount() { return aliveClients; } /** * Checks that there is no unsaved data * * @return true when all data is saved to file (or no data comed) */ public boolean isDataSaved() { return dataSaved; } /** * Get output file name * * @return output file name */ public String getFileName() { return fileName; } /** * Get data template file name * * @return data template file name */ public String getTemplateName() { return templateName; } /** * Get listening port * * @return listening port, assigned to ServerSocket. If server was created * with port == 0, then real listening port will be returned. -1 is returned * if server is not working anymore of port is not binded. */ public int getPort() { if (port == 0) { if (ss != null) { return ss.getLocalPort(); } else { if (!working) { return -1; } } } return port; } /** * Check whether server is saving data on receive * * @return true if server is saving data on receive */ public boolean isSaveOnReceive() { return saveAtReceive; } /** * Get maximum connections count * * @return maximum connections count */ public int getMaxCount() { return saveCount; } /** * Set the maximum connection count that this Server will collect * * @param saveCount */ public void setMaxCount(int saveCount) { this.saveCount = saveCount; } /** * Set maximum time in milliseconds to wait for alive clients when closing * Server * * @param MAX_TIMEOUT */ public static void setMaxTimeout(int MAX_TIMEOUT) { Server.MAX_TIMEOUT = MAX_TIMEOUT; } /** * Set output testlist file * * @param outTestList */ public void setOutTestList(String outTestList) { this.outTestList = outTestList; } /** * Set output file * * @param fileName */ public void setFileName(String fileName) { this.fileName = fileName; } public String getSaveBadData() { return saveBadData; } public void setSaveBadData(String saveBadData) { this.saveBadData = saveBadData; } } // ############# Server /** * Class for server command listener. Receives commands from commandPort and * controls the Server */ class CommandListener extends Thread { private final int commandPort; // port to listen for commands private final Server server; // server to control private String runCommand; // command the Server was started with private ServerSocket serverSocket = null; // socket listener private String hostName; // name of the host running the Server // runtime data private boolean working = true; // thread is working /** * Constructor for CommandListener class Sets "CommandListener" as the name * of the thread * * @param commandPort port to listen for commands * @param server Server to control */ public CommandListener(int commandPort, Server server) throws BindException, IOException { this(commandPort, server, "<unknown>", "<localhost>"); } /** * Constructor for CommandListener class Sets "CommandListener" as the name * of the thread * * @param commandPort port to listen for commands * @param server Server to control * @param runCommand command this Server was runned with */ public CommandListener(int commandPort, Server server, String runCommand, String hostName) throws BindException, IOException { super(); setDaemon(false); setName("CommandListener"); this.server = server; this.runCommand = runCommand; serverSocket = new ServerSocket(commandPort); this.commandPort = serverSocket.getLocalPort(); this.hostName = hostName; } /** * Main method. Use start() to launch in new thread. CommandListener listens * commandPort with ServerSocket and receives commands from it. Every 5 * seconds ServerSocket is getting TimeoutException so ServerSocket.accept() * releases the thread to check whether Server is still alive. */ @Override public void run() { try { Grabber.logger.log(Level.CONFIG, "Server is waiting for commands at port {0}", Integer.toString(commandPort)); outer: while (working && server.isWorking() && serverSocket != null) { Socket socket = null; try { serverSocket.setSoTimeout(5000); socket = serverSocket.accept(); InputStream in = socket.getInputStream(); int command = in.read(); Grabber.logger.log(Level.FINE, "Server received command {0} from {1}", new Object[]{Integer.toString(command), socket.getInetAddress().getHostAddress()}); switch (command) { case MiscConstants.GRABBER_KILL_COMMAND: Grabber.logger.log(Level.INFO, "Server received kill command."); BufferedReader inReader = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset())); int killtimeout = Integer.valueOf(inReader.readLine()); if (killtimeout > 0){ server.setMaxTimeout(killtimeout*1000); } server.kill(false); // server.saveData(); socket.getOutputStream().write(1); socket.getOutputStream().close(); inReader.close(); break outer; case MiscConstants.GRABBER_FORCE_KILL_COMMAND: socket.getOutputStream().write(1); socket.getOutputStream().close(); in.close(); Grabber.logger.log(Level.SEVERE, "Server received forced kill command. Exiting."); server.kill(true); break outer; case MiscConstants.GRABBER_SAVE_COMMAND: socket.getOutputStream().write(1); socket.getOutputStream().close(); in.close(); Grabber.logger.log(Level.FINE, "Server received save command."); server.saveData(); break; case MiscConstants.GRABBER_STATUS_COMMAND: OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8")); String message = String.format("%b;%d;%d;%b;%s;%s;%s;%s", server.isWorking(), server.getConnectionsCount(), server.getAliveConnectionCount(), server.isDataSaved(), runCommand, new File(".").getCanonicalPath(), server.getTemplateName(), server.getFileName()); Grabber.logger.log(Level.FINEST, "Sending status '{0}'", message); out.write(message, 0, message.length()); out.flush(); in.close(); out.close(); break; case MiscConstants.GRABBER_WAIT_COMMAND: out = new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8")); if (server.isStarted()) { message = String.format("%b;%s;%d;%s", true, hostName, server.getPort(), server.getTemplateName()); Grabber.logger.log(Level.FINEST, "Sending started status: {0}", message); } else { message = String.format("%b;%s;%d;%s", false, hostName, server.getPort(), server.getTemplateName()); } out.write(message, 0, message.length()); out.flush(); in.close(); out.close(); break; default: Grabber.logger.log(Level.WARNING, "Unknown message '{0}' came from {0}", new Object[]{Integer.toString(command), socket.getInetAddress().getHostAddress()}); break; } } catch (SocketTimeoutException ex) { if (!server.isWorking()) { break; } } catch (IOException ex) { if (serverSocket != null && !serverSocket.isClosed()) { // means that kill() was called Grabber.logger.log(Level.SEVERE, "Exception occurred while processing command", ex); } } finally { if (socket != null && !socket.isClosed()) { try { socket.close(); } catch (IOException ex) { } } } } } finally { if (serverSocket != null && !serverSocket.isClosed()) { try { serverSocket.close(); } catch (IOException ex) { } } serverSocket = null; working = false; } } /** * Stop listening port for commands IOException will be thrown in run() * method from ServerSocket as it will be closed. */ public void kill() { working = false; if (serverSocket != null) { try { serverSocket.close(); } catch (IOException ex) { } } serverSocket = null; } /** * Sets the command used for running the Grabber * * @param runCommand the command used for running the Grabber */ public void setRunCommand(String runCommand) { if (runCommand == null || runCommand.trim().equals("")) { this.runCommand = "<empty>"; } else { this.runCommand = runCommand; } } /** * Get command the server was runned with * * @return command the server was runned with */ public String getRunCommand() { return runCommand; } /** * Get port Command Listener is listening * * @return port Command Listener is listening */ public int getPort() { if (commandPort == 0) { if (serverSocket != null) { return serverSocket.getLocalPort(); } else { if (!working) { return -1; } } } return commandPort; } } // ############# CommandListener // ############################################################################## // ############################################################################## // ############################################################################## // ################################# MAIN CLASS ################################# // ############################################################################## // ############################################################################## // ############################################################################## /** * <p> Grabber is a class that collects coverage data in both static and dynamic * formats from remote clients. RT clients send their data through * JCovSocketSavers or Grabber connects to ServerSocketSavers set up by RT * clients. </p> <p> Grabber class manages 2 classes: Server and * CommandListener. First is listening for client connections and the second is * listening for commands sent from GrabberManager tool. </p> * * @see GrabberManager * @author andrey */ public class Grabber extends JCovCMDTool { static final Logger logger; static { Utils.initLogger(); logger = Logger.getLogger(Grabber.class.getName()); } public static final String COMMAND_PORT_PORPERTY = "jcov.grabber.commandPort"; public static final String MAX_COUNT_PROPERTY = "jcov.grabber.maxCount"; public static final String OUTPUTFILE_PROPERTY = "jcov.grabber.outputfile"; public static final String PORT_PROPERTY = "jcov.grabber.port"; public static final String RUN_LINE_PROPERTY = "jcov.grabber.runLine"; public static final String SAVE_ON_RECEIVE_PROPERTY = "jcov.grabber.saveOnReceive"; public static final String SAVE_IN_SHUTDOWN_HOOK_PROPERTY = "jcov.grabber.shutdownHookInstalled"; public static final String TEMPLATE_PROPERTY = "jcov.grabber.template"; public static final String SERVER_VERSION_PROPERTY = "jcov.grabber.version"; public static final String SERVER_LOCAL_HOSTNAME_PROPERTY = "jcov.grabber.localhostname"; private boolean saveInShutdownHook = false; // true -> data would be automatically saved in shutdown hook private String propfile; // propfile to write private String hostName; // host running the Server private int maxCount; // maximum connections that would be processed by Server private Thread shutdownHook = null; // shutdown hook which will save data if saveInShutdownHook is set to true // CommandListener configuration private boolean noCommand; // do not start CommandListener private CommandListener commandListener = null; // commandListener instance private int commandPort; // port to listen for commands from GrabberManager private String runCommand; // command this Grabber was started with // Server configuration private int port; // port to launch Server and listen for clients connections private Server server = null; // server instance private boolean once; // "once" mode when Server connects to the client private String template; // template to read (is passed to Server) private String filename; // output filename private boolean saveOnReceive; // save data on recieve (true) or on exit (false) private String onceHostToConnect; // host to connect in "once" mode private String outTestList; // file to write testlist to private boolean genscale; // allows to generate scales without outtestlist private String baddata; // directory to write bad data to private String messageFormat; private boolean mergeByTestNames = false; // generate scales based on test names (test name identifies test) /** * Get Properties object initialized with info about Server, Command * Listener and shutdown hook Properties object is initialized with: * jcov.grabber.port - Server's port jcov.grabber.commandPort - Command * Listener's port if set (otherwise this property is not set) * jcov.grabber.saveOnReceive - is the Server saving data on receive * jcov.grabber.shutdownHookInstalled - is the shutdown hook installed * jcov.grabber.maxCount - maximum Server connections allowed * jcov.grabber.template - template file jcov.grabber.outputfile - output * file jcov.grabber.runLine - line the Server is runned with (<unknown> * when not set and <empty> when there are no arguments) * * @return initialized Properties object */ public Properties getProperties() { Properties ps = new Properties(); ps.setProperty(PORT_PROPERTY, Integer.toString(server.getPort())); if (commandListener != null) { ps.setProperty(COMMAND_PORT_PORPERTY, Integer.toString(commandListener.getPort())); ps.setProperty(RUN_LINE_PROPERTY, commandListener.getRunCommand()); } ps.setProperty(SAVE_ON_RECEIVE_PROPERTY, Boolean.toString(server.isSaveOnReceive())); ps.setProperty(SAVE_IN_SHUTDOWN_HOOK_PROPERTY, Boolean.toString(saveInShutdownHook)); ps.setProperty(MAX_COUNT_PROPERTY, Integer.toString(server.getMaxCount())); if (server != null) { ps.setProperty(TEMPLATE_PROPERTY, server.getTemplateName()); ps.setProperty(OUTPUTFILE_PROPERTY, server.getFileName()); } ps.setProperty(SERVER_VERSION_PROPERTY, JcovVersion.jcovVersion + "-" + JcovVersion.jcovBuildNumber); try { ps.setProperty(SERVER_LOCAL_HOSTNAME_PROPERTY, InetAddress.getLocalHost().toString()); } catch (UnknownHostException ex) { } return ps; } /** * Write properties to a file. Properties.store() is used so * Properties.load() can be used to retrieve data * * @param file file to write properites */ public void writePropfile(String file) throws IOException { Properties ps = getProperties(); FileOutputStream out = null; try { out = new FileOutputStream(file); ps.store(out, null); } finally { if (out != null) { out.close(); } } } /** * Wait untill Server and CommandListener will stop * * @throws InterruptedException */ public void waitForStopping() throws InterruptedException { if (server != null) { server.join(); } if (commandListener != null) { commandListener.kill(); commandListener.join(); } } /** * * @throws BindException * @throws IOException */ public void start(boolean startCommandListener) throws BindException, IOException { this.saveInShutdownHook = true; createServer(); if (startCommandListener) { startCommandListener(commandPort); } installShutdownHook(); startServer(); } public void createServer() throws BindException, IOException { server = new Server(port, once, template, filename, outTestList, hostName, maxCount, saveOnReceive, genscale, mergeByTestNames); server.setSaveBadData(baddata); } /** * Start Server object */ public void startServer() { server.start(); } /** * Start CommandListener object * * @param commandPort */ public void startCommandListener(int commandPort) throws BindException, IOException { if (server == null) { throw new IllegalStateException("Server is not created"); } if (commandListener != null && commandListener.isAlive()) { return; } commandListener = new CommandListener(commandPort, server); commandListener.start(); } /** * Start CommandListener object * * @param commandPort * @param runCommand command this Serever was runned with (used to send * 'info' command responce) */ public void startCommandListener(int commandPort, String runCommand) throws BindException, IOException { if (server == null) { throw new IllegalStateException("Server is not created"); } if (commandListener != null && commandListener.isAlive()) { return; } commandListener = new CommandListener(commandPort, server, runCommand, hostName); commandListener.start(); } /** * Install shutdown hook that will save data and stop CommandListener and * Server */ public void installShutdownHook() { if (shutdownHook == null) { // do this only when hook is not installed shutdownHook = new Thread() { @Override public void run() { logger.log(Level.CONFIG, "Shutdownhook fired"); if (commandListener != null) { commandListener.kill(); } if (server != null && server.isWorking()) { // in normal exit server should return false if (saveInShutdownHook) { server.saveData(); } server.kill(false); } logger.log(Level.FINE, "Shutdownhook done"); } }; Runtime.getRuntime().addShutdownHook(shutdownHook); logger.log(Level.FINE, "Shutdownhook installed"); } } /** * Stop the Server. CommandListener will also be stopped. * * @param force when false - server will wait till all alive clients will * end transmitting data */ public void stopServer(boolean force) { if (server != null) { server.kill(force); server = null; } if (commandListener != null) { stopCommandListener(); } } /** * Stop the CommandListener */ public void stopCommandListener() { commandListener.kill(); commandListener = null; } /** * Set run command to the Command Listener (wrapper method) * * @param command run command * @return true if runcommand was set, false otherwise (when Command * Listener is not created) */ public boolean setRunCommand(String command) { if (commandListener != null) { commandListener.setRunCommand(command); return true; } return false; } /** * main */ public static void main(String args[]) { Grabber tool = new Grabber(); try { int res = tool.run(args); System.exit(res); } catch (Exception ex) { System.exit(1); } } public String usageString() { return "java com.sun.tdk.jcov.Grabber [-option value]"; } public String exampleString() { return "java -cp jcov.jar com.sun.tdk.jcov.Grabber -output grabbed.xml -port 3000 -once -merge"; } protected String getDescr() { return "gathers information from JCov runtime via sockets"; } public int getServerPort() { if (server != null) { return server.getPort(); } return -1; } public int getCommandListenerPort() { if (commandListener != null) { return commandListener.getPort(); } return -1; } @Override public EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{ DSC_OUTPUT, DSC_VERBOSE, DSC_VERBOSEST, DSC_SHOW_MEMORY_CHECKS, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_TEMPLATE, DSC_HOSTNAME, DSC_ONCE, DSC_PORT, DSC_COUNT, DSC_SAVE_MODE, DSC_COMMAND_PORT, DSC_PROPFILE, Merger.DSC_OUTPUT_TEST_LIST, Merger.DSC_SCALE, DSC_BADDATA, DSC_MESSAGE_FORMAT, DSC_SCALE_BY_NAME }, this); } @Override public int handleEnv(EnvHandler opts) throws EnvHandlingException { template = opts.getValue(InstrumentationOptions.DSC_TEMPLATE); try { File t = Utils.checkFileNotNull(template, "template filename", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_ISFILE, Utils.CheckOptions.FILE_CANREAD); long recomendedMemory = Math.max(1000000000, t.length() * 16 + 150000000); // 12 = 4 (template in memory) * 4; 150000000 = 10mb (for each client) * 15 (number of concurrent/agent clients) long minMemory = Math.max(468000000, t.length() * 6 + 50000000); // 6 = 4 * 1.5; 50000000 = 10mb * 5 if (Runtime.getRuntime().maxMemory() < minMemory) { // < 0.8gb logger.log(Level.WARNING, "Grabber started with {0}M max memory. Minimal requirement for this template is {1}M, recomended {2}M. ", new Object[]{Runtime.getRuntime().maxMemory() / 1000000, minMemory / 1000000, recomendedMemory / 1000000}); } else if (Runtime.getRuntime().maxMemory() < recomendedMemory) { logger.log(Level.WARNING, "Grabber started with {0}M max memory. It''s recomended to have at least {1}M max memory. ", new Object[]{Runtime.getRuntime().maxMemory() / 1000000, recomendedMemory / 1000000}); } } catch (EnvHandlingException ex) { if (opts.isSet(InstrumentationOptions.DSC_TEMPLATE)) { throw ex; } logger.log(Level.WARNING, "Grabber started without template, accepting only dynamic data"); template = null; } try { InetAddress adr = InetAddress.getLocalHost(); hostName = adr.getHostName(); } catch (Exception ee) { logger.log(Level.WARNING, "Can't get real local host name, using '<localhost>'"); hostName = "<localhost>"; } if (opts.isSet(DSC_VERBOSE)) { Utils.setLoggingLevel(Level.INFO); } if (opts.isSet(DSC_VERBOSEST)) { Utils.setLoggingLevel(Level.ALL); } if (opts.isSet(DSC_SHOW_MEMORY_CHECKS)) { Server.showMemoryChecks = true; } once = opts.isSet(DSC_ONCE); port = opts.isSet(DSC_PORT) ? Utils.checkedToInt(opts.getValue(DSC_PORT), "port number", Utils.CheckOptions.INT_NONNEGATIVE) : (once ? MiscConstants.JcovOncePortNumber : MiscConstants.JcovPortNumber); maxCount = Utils.checkedToInt(opts.getValue(DSC_COUNT), "max connections count"); filename = opts.isSet(DSC_OUTPUT) ? opts.getValue(DSC_OUTPUT) : MiscConstants.JcovSaveFileNameXML; Utils.checkFileNotNull(filename, "output filename", Utils.CheckOptions.FILE_PARENTEXISTS, Utils.CheckOptions.FILE_NOTISDIR); saveOnReceive = "receive".equalsIgnoreCase(opts.getValue(DSC_SAVE_MODE)); if (once) { onceHostToConnect = opts.getValue(DSC_HOSTNAME); Utils.checkHostCanBeNull(onceHostToConnect, "testing host"); } String commandPortStr = opts.getValue(DSC_COMMAND_PORT); if (once) { commandPort = 0; } else if (commandPortStr == null) { commandPort = MiscConstants.JcovGrabberCommandPort; } else { commandPort = Utils.checkedToInt(commandPortStr, "command port number"); } noCommand = opts.isSet(DSC_NO_COMMAND); propfile = opts.getValue(DSC_PROPFILE); Utils.checkFileCanBeNull(propfile, "property filename", Utils.CheckOptions.FILE_NOTISDIR, Utils.CheckOptions.FILE_PARENTEXISTS); runCommand = opts.unParse(); outTestList = opts.getValue(Merger.DSC_OUTPUT_TEST_LIST); Utils.checkFileCanBeNull(outTestList, "output testlist filename", Utils.CheckOptions.FILE_NOTISDIR, Utils.CheckOptions.FILE_PARENTEXISTS); genscale = opts.isSet(Merger.DSC_SCALE); baddata = opts.getValue(DSC_BADDATA); Utils.checkFileCanBeNull(baddata, "directory for bad datafiles", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_ISDIR); messageFormat = opts.getCleanValue(DSC_MESSAGE_FORMAT); mergeByTestNames = opts.isSet(DSC_SCALE_BY_NAME); return SUCCESS_EXIT_CODE; } @Override public int run() throws Exception { if (!saveOnReceive) { logger.log(Level.INFO, "Installing shutdown hook"); } saveInShutdownHook = !saveOnReceive; // Trying to create server. It can fail in case port is incorrect or is already binded try { createServer(); int returnValue = 0; boolean shouldStartCL = !(once) || noCommand; if (shouldStartCL) { try { // Trying to create and start command listener. It can fail in case port is incorrect or is already binded startCommandListener(commandPort, runCommand); } catch (BindException ex) { Grabber.logger.log(Level.SEVERE, "Cannot bind CommandListener to {0}: {1}", new Object[]{ commandPort == 0 ? "any free port" : "port " + String.valueOf(commandPort), ex.getMessage()}); returnValue = 6; } catch (IOException ex) { Grabber.logger.log(Level.SEVERE, "Cannot create CommandListener", ex); returnValue = 6; } } if (!shouldStartCL || commandListener != null) { // run Server only if CommandListener was started or should not to be started installShutdownHook(); startServer(); char[] c = new char[]{'p', 'h', 'c', 't', 'C', 'o', 'O', 's', 'S'}; String[] s = new String[]{Integer.toString(server.getPort()), hostName, Integer.toString(commandListener.getPort()), template, Integer.toString(maxCount), filename, outTestList, Boolean.toString(genscale), saveOnReceive ? "receive" : "exit"}; System.out.println(PropertyFinder.processMacroString(messageFormat, c, s)); String file = propfile; if (file != null) { try { writePropfile(file); } catch (IOException ex) { logger.log(Level.SEVERE, "Error while trying to store properties file: ", ex); } } } else { server.kill(true); // CommandListener failed to start } logger.log(Level.INFO, "Waiting for closing all processes"); waitForStopping(); logger.log(Level.INFO, "Server is stopped"); return returnValue; } catch (BindException ex) { Grabber.logger.log(Level.SEVERE, "Cannot bind Server to {0}: {1}", new Object[]{ port == 0 ? "any free port" : "port " + String.valueOf(commandPort), ex.getMessage()}); return 5; } catch (IOException ex) { Grabber.logger.log(Level.SEVERE, "Cannot create Server", ex); return 5; } } public int getCommandPort() { return commandPort; } public void setCommandPort(int commandPort) { this.commandPort = commandPort; } public String getOutputFilename() { return filename; } public void setOutputFilename(String filename) { this.filename = filename; } public boolean isGenscale() { return genscale; } public void setGenscale(boolean genscale) { this.genscale = genscale; } public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public int getMaxCount() { return maxCount; } public void setMaxCount(int maxCount) { this.maxCount = maxCount; } public boolean isNoCommand() { return noCommand; } public void setNoCommand(boolean noCommand) { this.noCommand = noCommand; } public boolean isOnce() { return once; } public void setOnce(boolean once) { this.once = once; } public String getHostToConnect() { return onceHostToConnect; } public void setHostToConnect(String onceHostToConnect) { this.onceHostToConnect = onceHostToConnect; } public String getOutTestList() { return outTestList; } public void setOutTestList(String outTestList) { this.outTestList = outTestList; } public void setMergeByTestNames(boolean mergeByTestNames) { this.mergeByTestNames = mergeByTestNames; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public boolean isSaveInShutdownHook() { return saveInShutdownHook; } public void setSaveInShutdownHook(boolean saveInShutdownHook) { this.saveInShutdownHook = saveInShutdownHook; } public boolean isSaveOnReceive() { return saveOnReceive; } public void setSaveOnReceive(boolean saveOnReceive) { this.saveOnReceive = saveOnReceive; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } public String getMessageString() { return messageFormat; } public void setMessageString(String message) { this.messageFormat = message; } public final static OptionDescr DSC_SAVE_MODE = new OptionDescr("save", "", OptionDescr.VAL_SINGLE, new String[][]{ {"receive", "Save data to a file on receiving and then merge into it"}, {"exit", "Save data on exit merging it in memory (faster but more memory used)"} }, "Specify when incoming data should be merged and saved.", "exit"); public final static OptionDescr DSC_OUTPUT = new OptionDescr("grabber.output", new String[]{"output", "o"}, "Output parameters definition", OptionDescr.VAL_SINGLE, "Specifies output file.", "result.xml for xml format or java.jcov for legacy"); public final static OptionDescr DSC_VERBOSE = new OptionDescr("verbose", new String[]{"v"}, "Verbosity level", "Show more messages."); public final static OptionDescr DSC_VERBOSEST = new OptionDescr("verbosemore", new String[]{"vv"}, "", "Show all messages."); public final static OptionDescr DSC_SHOW_MEMORY_CHECKS = new OptionDescr("showmemory", "", "Show memory checks."); public final static OptionDescr DSC_HOSTNAME = new OptionDescr("hostname", "Connection parameters", OptionDescr.VAL_SINGLE, "Specify host to connect when client mode is used.", "localhost"); public final static OptionDescr DSC_ONCE = new OptionDescr("once", new String[]{"client"}, "", "Specify client mode."); //true - client, false - server public final static OptionDescr DSC_PORT = new OptionDescr("port", "", OptionDescr.VAL_SINGLE, "Specify port. Use -port 0 to use any free port for server (only for server mode)", MiscConstants.JcovPortNumber + " for server mode, or " + MiscConstants.JcovOncePortNumber + " for client mode."); public final static OptionDescr DSC_COUNT = new OptionDescr("count", "", OptionDescr.VAL_SINGLE, "Specify maximum times of receiving data. 0 corresponds to unlimited.", "0"); public final static OptionDescr DSC_COMMAND_PORT = new OptionDescr("command_port", new String[]{"command"}, "", OptionDescr.VAL_SINGLE, "Set port to listen commands. Use -command 0 to use any free port for command listener.", Integer.toString(MiscConstants.JcovGrabberCommandPort)); public final static OptionDescr DSC_NO_COMMAND = new OptionDescr("nocommand", new String[]{"nc"}, "", OptionDescr.VAL_NONE, "Use to not run command listener"); public final static OptionDescr DSC_PROPFILE = new OptionDescr("grabber.props", "Properties file", OptionDescr.VAL_SINGLE, "Write properties to a file to use them in the manager."); public final static OptionDescr DSC_BADDATA = new OptionDescr("baddatato", "manage bad data", OptionDescr.VAL_SINGLE, "Directory to write data that can't be merged with the template."); public final static OptionDescr DSC_MESSAGE_FORMAT = new OptionDescr("message", "welcome message format", OptionDescr.VAL_SINGLE, "Specify format for output welcome message. %p% - port, %c% - command port, %h% - running host, %t% - used template, %C% - maximum connection count (0 == unlimited), %o% - output file, %O% - output testlist file, %s% - generate scales, %S% - save at receive or exit", "Server started on %h%:%p%. Command listener at port %c%. Used template '%t%'."); public final static OptionDescr DSC_SCALE_BY_NAME = new OptionDescr("mergebyname", "process/generate test scales", "test name identifies the test. tests with same name will be automatically merged"); }
80,317
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Exec.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/Exec.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.constants.MiscConstants; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.data.Result; import com.sun.tdk.jcov.insert.AbstractUniversalInstrumenter; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.processing.ProcessingException; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.Utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.Arrays; import java.util.LinkedList; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; /** * <p> This tool is designed to simplify JCov Grabber usage. It starts a * grabber, then executes specified command and waits while command is active. * After finishing the command Exec will stop the grabber. </p> <p> Exec also * can instrument the product with -instr option. Instrumentation is performed * recursively so that entire product is copied to new location and every single * binary file (class or jar/zip/war) will be instrumented. </p> * * @author Andrey Titov */ public class Exec extends JCovCMDTool { static final Logger logger; static { Utils.initLogger(); logger = Logger.getLogger(Exec.class.getName()); } private String command[]; private Grabber grabber; private String outLogFile; private String errLogFile; private String grabberLogFile; private String template = MiscConstants.JcovTemplateFileNameXML; private String outTestList; private String outputFile = MiscConstants.JcovSaveFileNameXML; private File commandDir = null; // Product instrumentation private ProductInstr pInstr; // Report generation private File reportDir; private void instrumentProduct() throws Exception { pInstr.instrumentProduct(); } private void runCommand() throws IOException, Exception { if (pInstr != null || reportDir != null) { logger.log(Level.INFO, " - Starting command"); } logger.log(Level.CONFIG, "Command to run: ''{0}''", Arrays.toString(command)); OutputStream outStream = null; OutputStream errStream = null; Process proc = null; try { grabber.createServer(); logger.log(Level.INFO, "Starting the Grabber"); grabber.startServer(); if (outLogFile != null) { outStream = new FileOutputStream(outLogFile); } else { outStream = System.out; } if (errLogFile != null) { if (errLogFile.equals(outLogFile)) { errStream = outStream; } else { errStream = new FileOutputStream(errLogFile); } } else { if (outLogFile != null) { errStream = outStream; } else { errStream = System.err; } } ProcessBuilder pb = new ProcessBuilder(command) .redirectErrorStream(errStream == outStream) .directory(commandDir); pb.environment().put("JCOV_PORT", Integer.toString(grabber.getServerPort())); logger.log(Level.INFO, "Starting the command"); proc = pb.start(); InputStream inputStream = proc.getInputStream(); new Thread(new Redirector(inputStream, outStream)).start(); if (errStream != outStream) { new Thread(new Redirector(proc.getErrorStream(), errStream)).start(); } int exitStatus = proc.waitFor(); if (exitStatus == 0) { logger.log(Level.FINE, "Command finished with 0"); } else { logger.log(Level.WARNING, "Command finished with {0}", exitStatus); } proc = null; } catch (Throwable e) { e.printStackTrace(); } finally { if (proc != null) { logger.log(Level.INFO, "Destroying the process..."); proc.destroy(); } if (outLogFile != null) { outStream.close(); if (outStream != errStream) { errStream.close(); } } try { logger.log(Level.INFO, "Stopping the grabber (not forcely)..."); grabber.stopServer(false); } catch (Throwable e) { e.printStackTrace(); } if (!new File(outputFile).exists()) { throw new Exception("Output file " + outputFile + " was not created after grabber stop." + (reportDir != null ? " Can't write the report." : "")); } } } private void createReport() throws ProcessingException, FileFormatException, Exception { logger.log(Level.INFO, " - Generating report"); logger.log(Level.CONFIG, "Output report directory: ''{0}''", reportDir.getPath()); RepGen rg = new RepGen(); rg.configure(null, null, null, null, false, false, false, false, false, false, false, false); Result res; if (outTestList == null) { res = new Result(outputFile); } else { res = new Result(outputFile, outTestList); } rg.generateReport(reportDir.getAbsolutePath(), res); } @Override protected int run() throws Exception { if (pInstr != null) { instrumentProduct(); } runCommand(); if (reportDir != null) { createReport(); } return SUCCESS_EXIT_CODE; } @Override protected EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{ DSC_TEST_COMMAND, DSC_TEST_COMMANDS, DSC_COMMAND_DIR, Grabber.DSC_PORT, Grabber.DSC_OUTPUT, Merger.DSC_OUTPUT_TEST_LIST, DSC_REDIRECT_OUT, DSC_REDIRECT_ERR, DSC_GRABBER_REDIRECT, ProductInstr.DSC_INSTRUMENT, ProductInstr.DSC_INSTRUMENT_TO, ProductInstr.DSC_RT_TO, Instr.DSC_INCLUDE_RT, DSC_REPORT, InstrumentationOptions.DSC_TEMPLATE,}, this); } @Override protected int handleEnv(EnvHandler envHandler) throws EnvHandlingException { if (envHandler.isSet(DSC_TEST_COMMAND)) { command = splitNoQuotes(envHandler.getValue(DSC_TEST_COMMAND)); if (envHandler.isSet(DSC_TEST_COMMANDS)) { logger.log(Level.CONFIG, "'-commands' option ignored as '-command' option specified"); } } else if (envHandler.isSet(DSC_TEST_COMMANDS)) { command = envHandler.getValues(DSC_TEST_COMMANDS); } else { throw new EnvHandlingException("'-command' or '-commands' option needed"); } if (envHandler.isSet(DSC_COMMAND_DIR)) { commandDir = Utils.checkFileNotNull(envHandler.getValue(DSC_COMMAND_DIR), "command dir"); } if (envHandler.isSet(ProductInstr.DSC_INSTRUMENT)) { pInstr = new ProductInstr(); pInstr.handleEnv(envHandler); } reportDir = Utils.checkFileCanBeNull(envHandler.getValue(DSC_REPORT), "report directory", Utils.CheckOptions.FILE_NOTEXISTS, Utils.CheckOptions.FILE_CANWRITE); if (envHandler.isSet(DSC_GRABBER_REDIRECT)) { grabberLogFile = envHandler.getValue(DSC_GRABBER_REDIRECT); Logger grLogger = Logger.getLogger(Grabber.class.getName()); grLogger.setUseParentHandlers(false); try { grLogger.addHandler(new FileHandler(grabberLogFile)); } catch (Exception ex) { throw new EnvHandlingException("Error opening file for logging grabber: " + ex.getMessage(), ex); } } grabber = new Grabber(); grabber.handleEnv(envHandler); if (envHandler.isSet(DSC_REDIRECT_ERR)) { errLogFile = envHandler.getValue(DSC_REDIRECT_ERR); Utils.checkFileNotNull(errLogFile, "error log file", Utils.CheckOptions.FILE_CANWRITE, Utils.CheckOptions.FILE_NOTISDIR); } if (envHandler.isSet(DSC_REDIRECT_OUT)) { outLogFile = envHandler.getValue(DSC_REDIRECT_OUT); Utils.checkFileNotNull(outLogFile, "output log file", Utils.CheckOptions.FILE_CANWRITE, Utils.CheckOptions.FILE_NOTISDIR); } if (envHandler.isSet(InstrumentationOptions.DSC_TEMPLATE)) { template = envHandler.getValue(InstrumentationOptions.DSC_TEMPLATE); Utils.checkFileNotNull(template, "template file", Utils.CheckOptions.FILE_CANREAD, Utils.CheckOptions.FILE_ISFILE, Utils.CheckOptions.FILE_EXISTS); } if (envHandler.isSet(Merger.DSC_OUTPUT_TEST_LIST)) { outTestList = envHandler.getValue(Merger.DSC_OUTPUT_TEST_LIST); Utils.checkFileNotNull(outTestList, "output testlist file", Utils.CheckOptions.FILE_CANWRITE, Utils.CheckOptions.FILE_NOTISDIR, Utils.CheckOptions.FILE_NOTEXISTS); } if (envHandler.isSet(Grabber.DSC_OUTPUT)) { outputFile = envHandler.getValue(Grabber.DSC_OUTPUT); Utils.checkFileNotNull(outputFile, "output file", Utils.CheckOptions.FILE_CANWRITE, Utils.CheckOptions.FILE_NOTISDIR); } return 0; } @Override protected String getDescr() { return "Executes a command collecting coverage data in a grabber"; } @Override protected String usageString() { return "java -jar jcov.jar exec -command <command to run> [-option value]"; } @Override protected String exampleString() { return "java -jar jcov.jar exec -command \"./runtests.sh -testoptions:\\\"-javaagent:jcov.jar=grabber=\\\"\""; } /** * <p> Splits a string containing quotes ' and " by spaces. Everything * quoted is not splitted. Non-quoted quotes are removed. </p> * * @param str * @return */ public static String[] splitNoQuotes(String str) { Character quote = null; LinkedList<String> r = new LinkedList<String>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length(); ++i) { char charAt = str.charAt(i); if (quote == null) { switch (charAt) { case '\'': case '\"': quote = charAt; break; case ' ': case '\t': case '\n': case '\f': case '\r': case 0x0B: if (sb.length() > 0) { r.add(sb.toString()); sb = new StringBuilder(); } break; default: sb.append(charAt); } } else { if (charAt == quote) { quote = null; } else { sb.append(charAt); } } } if (sb.length() > 0) { r.add(sb.toString()); } return r.toArray(new String[r.size()]); } public static final OptionDescr DSC_TEST_COMMAND = new OptionDescr("command", new String[]{"comm", "cmd"}, "Exec commands", OptionDescr.VAL_SINGLE, "Command running tests over instrumented classes or using JCov agent. Use quotes for arguments: -command \"./tests.sh -arg1 -arg2 arg3\""); public static final OptionDescr DSC_COMMAND_DIR = new OptionDescr("command.dir", new String[]{"dir"}, "", OptionDescr.VAL_SINGLE, "Specify directory to run the command"); public static final OptionDescr DSC_TEST_COMMANDS = new OptionDescr("commands", new String[]{"comms", "cmds"}, "", OptionDescr.VAL_ALL, "Command running tests over instrumented classes or using JCov agent. Use quotes for arguments: -command \"./tests.sh -arg1 -arg2 arg3\""); public final static OptionDescr DSC_REDIRECT_OUT = new OptionDescr("out.file", new String[]{"out", "log.command"}, "", OptionDescr.VAL_SINGLE, "Redirect command output to a file"); public final static OptionDescr DSC_REDIRECT_ERR = new OptionDescr("err.file", new String[]{"err"}, "", OptionDescr.VAL_SINGLE, "Redirect command error output to a file"); public final static OptionDescr DSC_GRABBER_REDIRECT = new OptionDescr("log.grabber", "", OptionDescr.VAL_SINGLE, "Redirect grabber output to a file"); public final static OptionDescr DSC_REPORT = new OptionDescr("report", "", OptionDescr.VAL_SINGLE, ""); public static class Redirector implements Runnable { private final OutputStream out; private final BufferedReader rin; private final BufferedWriter rout; public Redirector(InputStream in, OutputStream out) { rin = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset())); this.out = out; rout = new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset())); } public void run() { String s; try { while ((s = rin.readLine()) != null) { // out stream can be used in 2 threads simultaneously synchronized (out) { rout.write(s); rout.newLine(); rout.flush(); } } } catch (Throwable ex) { ex.printStackTrace(); } } } }
15,600
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
DiffCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/DiffCoverage.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.filter.MemberFilter; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataField; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.DataPackage; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.report.ClassCoverage; import com.sun.tdk.jcov.report.LineCoverage; import com.sun.tdk.jcov.report.MethodCoverage; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * <p> Allows to get numbers of changed code lines that were not covered. </p> * <p> Uses a diff file and a JCov XML result file. </p> <p> Mercurial and * Subversion diff files formats are supported. </p> * * @author Andrey Titov */ public class DiffCoverage extends JCovCMDTool { /** * A line in the sources */ public static class SourceLine { public int line; public String source; boolean checked; boolean codeByDefault = true; public SourceLine(int line, String source) { this.line = line; this.source = source; } public SourceLine() { } public boolean hits(int start, int end) { return line > start && line < end; } public String toString() { return "[line = " + line + ", source = " + source + "]"; } } private String file; private File diffFile; private HashMap<String, SourceLine[]> sources; private HashMap<Integer, String> sourceLines; private static final Logger logger; private String replaceDiff; private String replaceClass; private boolean all; static { Utils.initLogger(); logger = Logger.getLogger(DiffCoverage.class.getName()); } @Override protected int run() throws Exception { final LinkedList<String> classNames = new LinkedList<String>(); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(diffFile), "UTF-8")); DiffHandler handler = new HGDiffHandler(in); sources = new HashMap<String, SourceLine[]>(); String sourceName; while ((sourceName = handler.getNextSource()) != null) { LinkedList<SourceLine> lines = new LinkedList<SourceLine>(); SourceLine line; while ((line = handler.getNextSourceLine()) != null) { lines.add(line); } if (lines.size() > 0) { classNames.add(sourceName.substring(sourceName.lastIndexOf('/') + 1)); // rough estimation of needed classes logger.log(Level.INFO, "File {0} has {1} new lines", new Object[]{sourceName, lines.size()}); if (replaceDiff != null) { String[] split = replaceDiff.split(":"); String patt = split[0]; String with; if (split.length == 1) { with = ""; } else { with = split[1]; } sourceName = sourceName.replaceAll(patt, with); } sources.put(sourceName, lines.toArray(new SourceLine[lines.size()])); } else { logger.log(Level.INFO, "File {0} doesn't have new lines", sourceName); } } } catch (Exception ex) { logger.log(Level.SEVERE, "Error while parsing diff file", ex); if (ex instanceof NullPointerException) { ex.printStackTrace(); } return ERROR_EXEC_EXIT_CODE; } DataRoot data = DataRoot.read(file, false, new MemberFilter() { public boolean accept(DataClass clz) { if (classNames.contains(clz.getSource())) { return true; } return false; } public boolean accept(DataClass clz, DataMethod m) { return true; } public boolean accept(DataClass clz, DataField f) { return true; } }); int notCovered = 0, covered = 0, nonCode = 0, noInformation = 0; for (DataPackage p : data.getPackages()) { HashMap<String, ArrayList<ClassCoveragePair>> classesMap = new HashMap<String, ArrayList<ClassCoveragePair>>(); for (DataClass c : p.getClasses()) { String packageName = c.getPackageName(); String className = !packageName.isEmpty() ? packageName + "/" + c.getSource() : c.getSource(); if (replaceClass != null) { String[] split = replaceClass.split(":"); String patt = split[0]; String with; if (split.length == 1) { with = ""; } else { with = split[1]; } className = className.replaceAll(patt, with); } if (classesMap.get(className) == null){ classesMap.put(className, new ArrayList<ClassCoveragePair>()); } classesMap.get(className).add(new ClassCoveragePair(c)); } for (String cln:classesMap.keySet()) { SourceLine lines[] = sources.get(cln); if (lines != null) { ArrayList<DataMethod> methods = new ArrayList<DataMethod>(); String sourceClassName = ""; for (int i=0; i<classesMap.get(cln).size(); i++){ DataClass dc = classesMap.get(cln).get(i).getDataClass(); methods.addAll(dc.getMethods()); if (!dc.getFullname().contains("$")){ sourceClassName = dc.getName(); } } for (DataMethod m : methods) { boolean changed = false; LineCoverage lc = new MethodCoverage(m, false).getLineCoverage(); // false is not used for (SourceLine line : lines) { if (line.checked) { continue; } if (line.line >= lc.firstLine() && line.line <= lc.lastLine()) { line.checked = true; if (!changed && all) { System.out.println(String.format(" %s: %s.%s", cln, sourceClassName, m.getFormattedSignature())); changed = true; } if (isLineCovered(classesMap.get(cln), line.line)) { ++covered; if (all) { System.out.println(String.format("+ %6d |%s", line.line, line.source)); } } else { if (isCode(classesMap.get(cln), line.line)) { if (!changed && !all) { System.out.println(String.format(" %s> %s: %s", cln, sourceClassName, m.getFormattedSignature())); changed = true; } ++notCovered; System.out.println(String.format("- %6d |%s", line.line, line.source)); } else { ++nonCode; if (all) { System.out.println(String.format(" %6d |%s", line.line, line.source)); } } } } } } for (SourceLine line : lines) { if (!line.checked) { line.codeByDefault = false; ++nonCode; } } } } } for (String diffClasses : sources.keySet()){ for (SourceLine line: sources.get(diffClasses)){ if (!line.checked && line.codeByDefault){ noInformation++; if (all) { System.out.println(String.format("? %6d |%s", line.line, line.source)); } } } } System.out.println(String.format("lines: %d new; %d covered; %d not covered; %d not code; %d no information", nonCode + notCovered + covered + noInformation, covered, notCovered, nonCode, noInformation)); return SUCCESS_EXIT_CODE; } private boolean isLineCovered(ArrayList<ClassCoveragePair> classes, int line){ for (int i=0; i<classes.size(); i++){ ClassCoverage cc = classes.get(i).getClassCoverage(); if (cc.isLineCovered(line)){ return true; } } return false; } private boolean isCode(ArrayList<ClassCoveragePair> classes, int line){ for (int i=0; i<classes.size(); i++){ ClassCoverage cc = classes.get(i).getClassCoverage(); if (cc.isCode(line)){ return true; } } return false; } @Override protected EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{DSC_REPLACE_DIFF, DSC_REPLACE_CLASS, DSC_ALL}, this); } @Override protected int handleEnv(EnvHandler envHandler) throws EnvHandlingException { String[] tail = envHandler.getTail(); if (tail == null) { throw new EnvHandlingException("No input files. Please specify JCov data file and diff (mercurial) file."); } if (tail.length < 2) { throw new EnvHandlingException("Not enough input files. Please specify JCov data file and diff (mercurial) file."); } file = tail[0]; Utils.checkFileNotNull(tail[0], "JCov datafile", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_ISFILE, Utils.CheckOptions.FILE_CANREAD); diffFile = new File(tail[1]); Utils.checkFile(diffFile, "diff file", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_ISFILE, Utils.CheckOptions.FILE_CANREAD); replaceDiff = envHandler.getValue(DSC_REPLACE_DIFF); replaceClass = envHandler.getValue(DSC_REPLACE_CLASS); all = envHandler.isSet(DSC_ALL); return SUCCESS_EXIT_CODE; } @Override protected String getDescr() { return "check whether changed lines were covered"; } @Override protected String usageString() { return "java -jar jcov.jar diffcoverage result.xml diff"; } @Override protected String exampleString() { return "java -jar jcov.jar diffcoverage -replace src/classes/: result.xml diff"; } static interface DiffHandler { public String getNextSource() throws IOException; public SourceLine getNextSourceLine() throws IOException; } static class HGDiffHandler implements DiffHandler { BufferedReader in; String current; int startLines = -1; int endLines = -1; public HGDiffHandler(BufferedReader in) { this.in = in; } public String getNextSource() throws IOException { if (current == null || !current.startsWith("+++")) { current = in.readLine(); } while (current != null && !(current.startsWith("+++") && current.contains(".java") && !current.contains("package-info.java") && !current.contains("module-info.java"))) { current = in.readLine(); } if (current != null) { String next = in.readLine(); if (next.startsWith("@@")) { // String filepath = current.substring(4, current.indexOf(".java") + 5); String filepath = current.substring(0, current.lastIndexOf(".java") + 5); filepath = filepath.replaceAll("\\+\\+\\+ ([a-zA-Z]/)?", ""); // !!! deleting _one_ symbol from the begining of the filename if current = next; return filepath; } current = null; } // else - EOF return null; } private static String LINES_NUMBERS_PATTERN = "@@ [-+][\\d]+,[\\d]+ [-+][\\d]+,[\\d]+ @@(?s).*"; public SourceLine getNextSourceLine() throws IOException { if (current != null && !current.startsWith("---")) { if (startLines == -1 && endLines == -1) { String linesNumbersLine = current; while (linesNumbersLine == null || !linesNumbersLine.matches(LINES_NUMBERS_PATTERN)) { // e.g. @@ +1,44 -4,8 @@ linesNumbersLine = in.readLine(); if (linesNumbersLine == null) { startLines = -1; endLines = -1; current = null; return null; } if (linesNumbersLine.matches("---")) { // end of file block startLines = -1; endLines = -1; current = null; return null; } } linesNumbersLine = linesNumbersLine.substring(0, linesNumbersLine.lastIndexOf("@@") + 2); linesNumbersLine = linesNumbersLine.replaceAll(" @@", ""); linesNumbersLine = linesNumbersLine.replaceAll("@@ .*\\+", ""); String[] split = linesNumbersLine.split(","); startLines = Integer.parseInt(split[0]); endLines = Integer.parseInt(split[1]) + startLines; } } else if (current != null) { return null; } String plusLine = null; while (plusLine == null || !(plusLine.startsWith("+"))) { plusLine = in.readLine(); // searching '+' statement if (plusLine == null) { startLines = -1; endLines = -1; current = null; return null; } if (!plusLine.startsWith("-")) { ++startLines; } if (plusLine.startsWith("---")) { startLines = -1; endLines = -1; current = plusLine; return null; } else if (plusLine.matches(LINES_NUMBERS_PATTERN)) { startLines = -1; endLines = -1; current = plusLine; return getNextSourceLine(); } } // plusLine is not null if we are here SourceLine line = new SourceLine(startLines - 1, plusLine.substring(1)); if (startLines > endLines) { startLines = -1; endLines = -1; current = null; } return line; } } private class ClassCoveragePair{ private DataClass dClass; private ClassCoverage cClass; public ClassCoveragePair(DataClass dClass){ this.dClass = dClass; this.cClass = new ClassCoverage(dClass, null, MemberFilter.ACCEPT_ALL); } public DataClass getDataClass(){ return dClass; } public ClassCoverage getClassCoverage(){ return cClass; } } static OptionDescr DSC_REPLACE_DIFF = new OptionDescr("replaceDiff", "Manage replacing", OptionDescr.VAL_SINGLE, "Set replacement pattern for diff filenames (e.g. to cut out \"src/classes\" you can specify -replaceDiff src/classes:)"); static OptionDescr DSC_REPLACE_CLASS = new OptionDescr("replaceClass", "", OptionDescr.VAL_SINGLE, "Set replacement pattern for class filenames (e.g. to cut out \"com/sun\" you can specify -replaceDiff com/sun:)"); static OptionDescr DSC_ALL = new OptionDescr("all", "Manage output", OptionDescr.VAL_NONE, "Show covered and non-code lines as well as not covered"); }
18,472
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
GrabberManager.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/GrabberManager.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.constants.MiscConstants; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.Utils; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.Iterator; import java.util.LinkedList; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * <p> Tool to control Grabber through socket requests </p> * * @author Andrey Titov */ public class GrabberManager extends JCovCMDTool { private LinkedList<ServerCommand> commands; private int waittime = 30; private int stoptimeout = 0; @Override protected int run() throws Exception { if (commands == null || commands.size() == 0) { throw new Exception("No commands specified"); } try { Iterator<ServerCommand> comm = commands.iterator(); while (comm.hasNext()) { ServerCommand command = comm.next(); if (command == COMM_WAIT) { String gotstatus = sendWaitCommand(); if (gotstatus == null) { throw new Exception("Server didn't respond"); } String[] split = gotstatus.split(";", -1); if (split.length != 4) { throw new Exception("Server sent malformed status: " + gotstatus); } String status = "Server started on " + split[1] + ":" + split[2] + ". Command listener at port " + port + ". Used template " + split[3] + "."; System.out.println(status); } else if (command == COMM_STATUS) { String gotstatus = sendStatusCommand(); String[] split = gotstatus.split(";", -1); if (split.length != 8) { throw new Exception("Got malformed status from the server: " + gotstatus); } String status = "Server " + (Boolean.parseBoolean(split[0]) ? "is working. Got " + Integer.parseInt(split[1]) + " connections, " + Integer.parseInt(split[2]) + " are alive. " + (Boolean.parseBoolean(split[3]) ? "No unsaved data. " : "Data is not saved. ") : "is not working. ") + "Server was started with options '" + split[4] + "' \n" + " working directory: " + split[5] + "\n" + " current template used: " + split[6] + "\n" + " output file to be created on exit: " + split[7] + "\n"; System.out.println("Status: " + status); } else if (command == COMM_SAVE) { sendSaveCommand(); System.out.println("Save: OK"); } else if (command == COMM_KILL_FORCE) { sendForceKillCommand(); System.out.println("Forced kill: OK"); } else if (command == COMM_KILL) { sendKillCommand(); System.out.println("Kill: OK"); } } } catch (UnknownHostException e) { throw new Exception("Can't resolve hostname '" + host + "'"); } catch (IOException e) { if (e.getMessage() != null && e.getMessage().startsWith("Connection refused")) { throw new Exception("Server not responding on command port " + port); } else { throw e; } } return SUCCESS_EXIT_CODE; } @Override protected EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{ DSC_HOSTNAME, DSC_PORT, DSC_FILE, DSC_WAITTIME, DSC_STOPTIMEOUT, COMM_KILL, COMM_KILL_FORCE, COMM_SAVE, COMM_STATUS, COMM_WAIT }, this); } @Override protected int handleEnv(EnvHandler opts) throws EnvHandlingException { String file = opts.getValue(DSC_FILE); Utils.checkFileCanBeNull(file, "properties filename", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_CANREAD); if (file != null) { try { initPortFromFile(file); } catch (IOException ex) { throw new EnvHandlingException("Error while reading properties file: ", ex); } } else { setPort(Utils.checkedToInt(opts.getValue(DSC_PORT), "port number")); } host = opts.getValue(DSC_HOSTNAME); Utils.checkHostCanBeNull(host, "grabber host"); commands = new LinkedList<ServerCommand>(); if (opts.isSet(COMM_WAIT)) { commands.add(COMM_WAIT); } if (opts.isSet(COMM_STATUS)) { commands.add(COMM_STATUS); } if (opts.isSet(COMM_SAVE)) { commands.add(COMM_SAVE); } if (opts.isSet(COMM_KILL_FORCE)) { commands.add(COMM_KILL_FORCE); } if (opts.isSet(COMM_KILL)) { commands.add(COMM_KILL); } if (commands.size() == 0) { throw new EnvHandlingException("Command was not specified"); } if (opts.isSet(DSC_WAITTIME)) { waittime = Utils.checkedToInt(opts.getValue(DSC_WAITTIME), "time to wait value in seconds"); } if (opts.isSet(DSC_STOPTIMEOUT)) { stoptimeout = Utils.checkedToInt(opts.getValue(DSC_STOPTIMEOUT), "time to wait before stop"); } return SUCCESS_EXIT_CODE; } static class ServerCommand extends OptionDescr { private int commandCode; ServerCommand(String name, String[] aliases, String titile, int values, String usage, int code) { super(name, aliases, titile, values, usage); this.commandCode = code; } public int getCommandCode() { return commandCode; } } final static OptionDescr DSC_HOSTNAME = new OptionDescr("host", new String[]{"hostname"}, "Connection parameters", OptionDescr.VAL_SINGLE, "Specify servers host to connect.", "localhost"); final static OptionDescr DSC_PORT = new OptionDescr("command_port", new String[]{"port"}, "", OptionDescr.VAL_SINGLE, "Specify servers command port.", Integer.toString(MiscConstants.JcovGrabberCommandPort)); final static OptionDescr DSC_STOPTIMEOUT = new OptionDescr("stoptimeout", new String[]{"stopt", "killt"}, "", OptionDescr.VAL_SINGLE, "Max time in seconds for Grabber to save all alive connections before stop.", Integer.toString(Server.MAX_TIMEOUT / 1000)); final static OptionDescr DSC_FILE = new OptionDescr("grabber.props", "", OptionDescr.VAL_SINGLE, "Read server properties from a file. Host should be specified explicitly."); final static OptionDescr DSC_WAITTIME = new OptionDescr("waittime", new String[]{"time", "t"}, "", OptionDescr.VAL_SINGLE, "Max time in seconds to wait for Grabber startup."); final static ServerCommand COMM_KILL = new ServerCommand("kill", new String[]{"stop"}, "Manage running server", OptionDescr.VAL_NONE, "Stop running server saving data and waining for all connections close.", MiscConstants.GRABBER_KILL_COMMAND); final static ServerCommand COMM_KILL_FORCE = new ServerCommand("fkill", new String[]{"fstop"}, "", OptionDescr.VAL_NONE, "Stop running server not saving data and not waining for all connections close.", MiscConstants.GRABBER_FORCE_KILL_COMMAND); final static ServerCommand COMM_SAVE = new ServerCommand("save", new String[]{"flush"}, "", OptionDescr.VAL_NONE, "Save data to file.", MiscConstants.GRABBER_SAVE_COMMAND); final static ServerCommand COMM_STATUS = new ServerCommand("status", null, "", OptionDescr.VAL_NONE, "Print server status.", MiscConstants.GRABBER_STATUS_COMMAND); final static ServerCommand COMM_WAIT = new ServerCommand("wait", null, "", OptionDescr.VAL_NONE, "Wait server for starting.", MiscConstants.GRABBER_WAIT_COMMAND); static final Logger logger; static { Utils.initLogger(); logger = Logger.getLogger(GrabberManager.class.getName()); } public static void main(String args[]) { GrabberManager tool = new GrabberManager(); try { int res = tool.run(args); System.exit(res); } catch (Exception ex) { System.exit(1); } } private int port; private String host; public GrabberManager() { this(MiscConstants.JcovGrabberCommandPort, "localhost"); } public GrabberManager(int port, String host) { this.port = port; this.host = host; } private void sendCode(int code) throws IOException { Socket socket = null; try { socket = new Socket(host, port); OutputStream out = socket.getOutputStream(); out.write(code); BufferedWriter outWriter = null; if (code == COMM_KILL.getCommandCode()){ outWriter = new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset())); outWriter.write(String.valueOf(stoptimeout)); outWriter.newLine(); outWriter.flush(); } socket.getInputStream().read(); socket.getInputStream().close(); if (outWriter != null) { outWriter.close(); } out.close(); } finally { if (socket != null && !socket.isClosed()) { socket.close(); } } } private String recieveCode(int code) throws IOException { String data = null; Socket socket = null; try { socket = new Socket(host, port); OutputStream out = socket.getOutputStream(); out.write(code); InputStream in = socket.getInputStream(); BufferedReader inReader = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset())); data = inReader.readLine(); out.close(); in.close(); } finally { if (socket != null) { socket.close(); } } return data; } /** * Send KILL command. Port and Host should be both set. * * @throws IOException */ public void sendKillCommand() throws IOException { sendCode(COMM_KILL.getCommandCode()); } /** * Send forced KILL command. Port and Host should be both set. * * @throws IOException */ public void sendForceKillCommand() throws IOException { sendCode(COMM_KILL_FORCE.getCommandCode()); } /** * Send SAVE command. Port and Host should be both set. * * @throws IOException */ public void sendSaveCommand() throws IOException { sendCode(COMM_SAVE.getCommandCode()); } /** * Send STATUS command and recieve responce. Port and Host should be both * set. * * @throws IOException */ public String sendStatusCommand() throws IOException { return recieveCode(COMM_STATUS.getCommandCode()); } /** * Send WAIT command and recieve responce. Port and Host should be both set. * * @throws IOException */ public String sendWaitCommand() throws IOException { String ret = null; for (int i = 0; i < waittime; ++i) { try { ret = recieveCode(COMM_WAIT.getCommandCode()); String[] split = ret.split(";"); if (Boolean.parseBoolean(split[0])) { break; } } catch (IOException e) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } } } return ret; } @Override protected String getDescr() { return "control commands to the Grabber server"; } @Override protected String usageString() { return "java -jar jcov.jar GrabberManager [-option value]"; } @Override protected String exampleString() { return "java -jar jcov.jar GrabberManager -port 3336 -status"; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public int initPortFromFile(String file) throws IOException { Properties ps = new Properties(); InputStream in = null; in = new FileInputStream(file); ps.load(in); in.close(); String portStr = ps.getProperty(Grabber.COMMAND_PORT_PORPERTY); if (portStr == null) { logger.log(Level.SEVERE, "Command Listeners port is not set in properties file '{0}'. Cannot work.", file); return 1; } port = 0; try { port = Integer.parseInt(portStr); } catch (NumberFormatException ex) { logger.log(Level.SEVERE, "Malformed port number '{0}' in properties file '{1}'. Cannot work.", new Object[]{portStr, file}); return 1; } if (port == 0) { String runLine = ps.getProperty(Grabber.RUN_LINE_PROPERTY); if (runLine != null) { logger.log(Level.SEVERE, "Command listener is not running on server (port = 0). Server was run with arguments '{0}'.", runLine); } else { logger.log(Level.SEVERE, "Command listener is not running on server (port = 0). Servers run line is unknown (not set in properties file)."); } return 1; } checkVersion(ps.getProperty(Grabber.SERVER_VERSION_PROPERTY)); return 0; } private void checkVersion(String version) { } }
15,815
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Merger.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/Merger.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.data.Result; import com.sun.tdk.jcov.data.ScaleOptions; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.instrument.InstrumentationOptions.MERGE; import com.sun.tdk.jcov.io.ClassSignatureFilter; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.runtime.FileSaver; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.tools.ScaleCompressor; import com.sun.tdk.jcov.tools.SimpleScaleCompressor; import com.sun.tdk.jcov.util.Utils; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * <p> This tool allows to create one merged XML file from many ones </p> <p> * Merger can create "scaled" coverage. </p> * * @author Andrey Titov */ public class Merger extends JCovCMDTool { /** * Do not ignore any error */ public final static String LOOSE_0 = "0"; /** * Ignore access and fields size errors */ public final static String LOOSE_1 = "1"; /** * Ignore signature and methods size errors (+ LOOSE_1) */ public final static String LOOSE_2 = "2"; /** * Ignore checksum mismatch (+ LOOSE_2) */ public final static String LOOSE_3 = "3"; public final static String LOOSE_BLOCKS = "blocks"; private String outTestList; private String output; private String skippedPath; private String template; private String[] srcs; private BreakOnError boe = BreakOnError.NONE; private boolean read_scales = false; private ClassSignatureFilter readFilter = null; private int loose_lvl = 0; private String[] include = new String[]{".*"}; private String[] exclude = new String[]{""}; private String[] m_include = new String[]{".*"}; private String[] m_exclude = new String[]{""}; private String[] fm = null; private boolean compress; private boolean sigmerge = false; private boolean addMissing = true; private boolean warningCritical = false; private static ScaleCompressor compressor = new SimpleScaleCompressor(); private final static Logger logger; static { Utils.initLogger(); logger = Logger.getLogger(Merger.class.getName()); } /** * <p> There could be a number of errors in XML which JCov Merger can not * resolve: * * <ul> <li>empty, malformed (non-XML) or damaged (not full) file </li> * <li>coverage type in a file is different from previous file (e.g. in * first it was Method coverage and in the second - Block) </li> <li>a file * contains coverage data of another product version or another product * </li> </ul> </p> <p> BreakOnError.FILE means than Merger will find all * the problems in the first malformed file and then will stop merging. </p> * <p> BreakOnError.ERROR means that Merger will stop at the very first * occurred error. </p> <p> BreakOnError.NONE means that Merger will stop * only when all files would be processed regardless on errors. </p> <p> * BreakOnError.SKIP means that merger will not stop on malformed data but * will skip such files. The list of skipped files would be saved in Merge * object. </p> * * @see Merge * @see #setBreakOnError(com.sun.tdk.jcov.Merger.BreakOnError) */ public static enum BreakOnError { FILE("file"), ERROR("error"), TEST("test"), NONE("none", "default"), SKIP("skip"); private String[] aliases; private BreakOnError(String... str) { this.aliases = str; } public static BreakOnError fromString(String name) { for (BreakOnError boe : values()) { for (String s : boe.aliases) { if (s.equalsIgnoreCase(name)) { return boe; } } } return null; } public static BreakOnError getDefault() { return NONE; } } /** * Merging info. Contains JCov results and template (if needed). After * merging contains result, skipped files list, error number and testlist */ public static class Merge { private final Result[] jcovFiles; private final String template; private DataRoot result; private List<String> skippedFiles; private int errors; private int warnings; private String[] resultTestList; public Merge(Result[] files, String template) { this.jcovFiles = files; this.template = template; } /** * <p> Creates Merge object from a number of XML files, their testlists * filenames and template. </p> * * @param files Files to merge * @param testlists Testlists assigned to each file. Can be null. Some * elements of the array can be null. Length of <b>testlists</b> can be * lesser than <b>files</b> * @param template Template to merge these files with. If template is * set - Merger will merge only those elements which exist in the * template. <p>Can be null.</p> * @throws IOException */ public Merge(String[] files, String[] testlists, String template) throws IOException { this.jcovFiles = new Result[files.length]; for (int i = 0; i < files.length; ++i) { if (testlists.length > i && testlists[i] != null) { jcovFiles[i] = new Result(files[i], testlists[i]); } else { jcovFiles[i] = new Result(files[i]); } } this.template = template; } /** * <p> When Merger finds a problem during merge (e.g. empty or damaged * file) it can skip it if BreakOnError is set to SKIP. Names of skipped * files are stored in a list and can be accessed after the merge * finishes. </p> * * @return List of files which were skipped during the merge routine. * Returns null if merge was not started yet or no files were skipped * @see BreakOnError * @see Merger#setBreakOnError(com.sun.tdk.jcov.Merger.BreakOnError) * */ public List<String> getSkippedFiles() { return skippedFiles; } /** * @return Result test list of merged data. Note that outTestList should * be passed to Merger in order to generate testlist. */ public String[] getResultTestList() { return resultTestList; } /** * <p> When Merger finds a problem during merge (e.g. empty or damaged * file) it can skip it if BreakOnError is set to SKIP. Names of skipped * files are stored in a list and can be accessed after the merge * finishes. </p> * * @return Count of files skipped during merge routine. * @see BreakOnError * @see Merger#setBreakOnError(com.sun.tdk.jcov.Merger.BreakOnError) * @see #getSkippedFiles() */ public int getSkippedCount() { if (skippedFiles == null) { return 0; } return skippedFiles.size(); } /** * <p> There could be a number of errors in XML which JCov Merger can * not resolve: * * <ul> <li>empty, malformed (non-XML) or damaged (not full) file </li> * <li>coverage type in a file is different from previous file (e.g. in * first it was Method coverage and in the second - Block) </li> <li>a * file contains coverage data of another product version or another * product </li> </ul> * * To control Merger behavior on error occurrence use BreakOnError </p> * * @return Number of critical errors found during the merge. * @see BreakOnError * @see Merger#setBreakOnError(com.sun.tdk.jcov.Merger.BreakOnError) */ public int getErrors() { return errors; } /** * <p> When Merger founds that a file contains coverage data collected * on another Java version it prints a warning. This warning can be * turned to error with <b>setWarningCritical()</b> method to prevent * JCov merge coverage collected on different Java platforms. </p> * * @return Number of warnings occurred during merge. * @see Merger#setWarningCritical(boolean) * @see BreakOnError * @see Merger#setBreakOnError(com.sun.tdk.jcov.Merger.BreakOnError) */ public int getWarnings() { return warnings; } void addSkippedFile(String file) { if (skippedFiles == null) { skippedFiles = new LinkedList(); } skippedFiles.add(file); } /** * @return Merge result as DataRoot object or null if Merger was not * started or failed (e.g. only one file found) */ public DataRoot getResult() { return result; } } /** * legacy entry point * * @param args * @param logStream * @throws Exception */ @Deprecated public static void innerMain(String args[], PrintStream logStream) throws Exception { Merger merger = new Merger(); merger.run(args); } /** * CLI entry point. Do not use it as API entry point - System.exit is called * here * * @param args */ public static void main(String args[]) { Merger merger = new Merger(); try { int res = merger.run(args); System.exit(res); } catch (Exception ex) { System.exit(1); } } ///////// BODY ///////// /** * Write merged data to a file * * @param merge merged data * @param outputPath path to write * @param outputTestList path to write testlist to * @param skippedPath path to write skipped files list to */ public void write(Merge merge, String outputPath, String outputTestList, String skippedPath) throws IOException { FileSaver saver = FileSaver.getFileSaver(merge.result, outputPath, template, MERGE.MERGE, false, read_scales); if (compress) { merge.result.getScaleOpts().setScalesCompressed(true); } try { logger.log(Level.INFO, "- Writing result to {0}", outputPath); saver.saveResults(outputPath); } catch (Exception ex) { throw new IOException("Can't write result file", ex); } try { if (merge.resultTestList != null) { Utils.writeLines(outputTestList, merge.resultTestList); } } catch (IOException ex) { throw new IOException("Cannot create resulting test list: " + outputTestList + ": ", ex); } try { if (skippedPath != null && merge.getSkippedCount() > 0) { Utils.writeLines(skippedPath, merge.getSkippedFiles().toArray(new String[merge.getSkippedFiles().size()])); } } catch (IOException ex) { throw new IOException("Cannot create skipped files list: " + skippedPath + ": ", ex); } } /** * Merge and write data (api entry point) * * @param jcovFiles files to merge * @param outTestList path to write testlist to * @param output path to write * @param template template to use for merging (golden data) * @param skippedPath path to write skipped files list to * @return merged and written data in Merge object * @throws IOException */ public Merge mergeAndWrite(String[] jcovFiles, String outTestList, String output, String template, String skippedPath) throws IOException { this.output = output; this.outTestList = outTestList; this.template = template; this.srcs = jcovFiles; this.skippedPath = skippedPath; logger.log(Level.INFO, "- Reading test lists"); Result results[]; try { results = initResults(jcovFiles, read_scales); } catch (IOException ex) { throw new IOException("Can't read test lists", ex); } Merge merge = new Merge(results, template); return mergeAndWrite(merge, outTestList, output, skippedPath); } /** * Merge and write data * * @param merge merging data * @param outTestList path to write testlist to * @param output to write * @param skippedPath path to write skipped files list to * @return merged data */ public Merge mergeAndWrite(Merge merge, String outTestList, String output, String skippedPath) throws IOException { merge(merge, outTestList, false); // merge.result == null when errors occurred or BOE.TEST is set if (merge.result != null && output != null && !"".equals(output)) { write(merge, output, outTestList, skippedPath); } return merge; } /** * Merge data * * @param merge merging data * @param outTestList path to write testlist to (testlist data will not be * collected if null, this method does NOT write the file) */ public void merge(Merge merge, String outTestList) { merge(merge, outTestList, false); } /** * Merge data * * @param merge merging data * @param outTestList path to write testlist to (testlist data will not be * collected if null, this method does NOT write the file) * @param ingoreOriginalScales files will be merged ignoring scales from * these files */ public void merge(Merge merge, String outTestList, boolean ignoreOriginalScales) { readFilter = new ClassSignatureFilter(include, exclude, m_include, m_exclude, fm); DataRoot merged = null; DataRoot rNext = null; logger.log(Level.INFO, "- Merging started"); int filesMerged = 0; String mergingRes; for (int i = 0; i < merge.jcovFiles.length; i++) { mergingRes = merge.jcovFiles[i].getResultPath(); try { if (i == 0 && merge.template != null) { logger.log(Level.INFO, "-- Reading jcov template {0}", merge.template); merged = Reader.readXML(merge.template, read_scales, readFilter); // template should not contain scales merged.getScaleOpts().setScaleSize(0); // template should not be counted in scales if (sigmerge) { merged.truncateToMethods(); // leaving only methods information in source XML } // scales are set to "0" 4 lines before // if (merged.getScaleOpts().getScaleSize() > 1) { // logger.log(Level.SEVERE, "Template {0} has not null scale size: found {1}; expected 1", new Object[]{merge.template, merged.getScaleOpts().getScaleSize()}); // merge.errors++; // break; // } if (merged.getParams().isDynamicCollect()) { logger.log(Level.SEVERE, "File {0} is dynamic collected coverage data and can't be used as template", merge.template); merge.errors++; break; } if (outTestList != null && read_scales && merged.getScaleOpts().getScaleSize() == 0) { merged.createScales(); } logger.log(Level.INFO, "-- Merging all with template {0}. Java version: {1}, generated {2}", new Object[]{merge.template, merged.getXMLHeadProperties().get("java.runtime.version"), merged.getXMLHeadProperties().get("coverage.created.date")}); filesMerged++; // allowing to merge 1 data file with template } logger.log(Level.FINE, "-- Reading jcov file {0}", mergingRes); rNext = Reader.readXML(mergingRes, read_scales, readFilter); if (outTestList != null) { logger.log(Level.FINE, "-- Reading testlist for jcov file {0}", mergingRes); if (ignoreOriginalScales) { rNext.cleanScales(); rNext.createScales(); } ScaleOptions scaleOpts = rNext.getScaleOpts(); String[] tlist = merge.jcovFiles[i].getTestList(); if (scaleOpts.getScaleSize() != tlist.length) { logger.log(Level.SEVERE, "Inconsistent scale sizes: in file {0}: {1}; expected: {2}", new Object[]{mergingRes, scaleOpts.getScaleSize(), tlist.length}); if (boe == BreakOnError.SKIP) { merge.addSkippedFile(mergingRes); continue; } merge.errors++; if (boe == BreakOnError.ERROR || boe == BreakOnError.FILE) { break; } } scaleOpts.setTestList(tlist); scaleOpts.setOutTestList(outTestList); } if (merged == null) { merged = rNext; logger.log(Level.INFO, "-- Merging all with {0}. Java version: {1}, generated {2}", new Object[]{mergingRes, merged.getXMLHeadProperties().get("java.runtime.version"), merged.getXMLHeadProperties().get("coverage.created.date")}); if (sigmerge) { merged.truncateToMethods(); // leaving only methods information in source XML } // we will lost fist test scales without creating them manually after reading file if (read_scales && merged.getScaleOpts().getScaleSize() == 0) { merged.createScales(); } filesMerged++; continue; } logger.log(Level.INFO, "-- Merging {0}", mergingRes); if (sigmerge) { merged.mergeOnSignatures(rNext, addMissing); } else { DataRoot.CompatibilityCheckResult localErrors; localErrors = merged.checkCompatibility(rNext, loose_lvl, boe == BreakOnError.ERROR); merge.errors += localErrors.errors; merge.warnings += localErrors.warnings; if (warningCritical) { localErrors.errors += localErrors.warnings; } if (localErrors.errors != 0) { if (boe == BreakOnError.SKIP) { logger.log(Level.INFO, "-- File {0} has {1} critical error(s) and will be skipped", new Object[]{mergingRes, localErrors.errors}); merge.addSkippedFile(mergingRes); continue; // just skip file without merging } if (boe == BreakOnError.FILE || boe == BreakOnError.ERROR) { logger.log(Level.SEVERE, "-- File {0} has {1} critical error(s). Stopping merging process (break on error set)", new Object[]{mergingRes, localErrors.errors}); break; } logger.log(Level.INFO, "-- File {0} has {1} critical errors", new Object[]{mergingRes, localErrors.errors}); } // all OK - merging merged.merge(rNext, addMissing); } filesMerged++; } catch (FileFormatException ex) { merge.errors++; if (boe == BreakOnError.SKIP) { logger.log(Level.SEVERE, "Skipping malformed xml file {0}: " + ex.getMessage(), new Object[]{mergingRes}); merge.addSkippedFile(mergingRes); continue; } if (boe == BreakOnError.FILE || boe == BreakOnError.ERROR) { if (i == 0 && merge.template != null) { logger.log(Level.SEVERE, "Stopping on malformed xml template {0}: {1}", new Object[]{merge.template, ex.getMessage()}); break; } else { logger.log(Level.SEVERE, "Stopping on malformed xml file {0}: {1}", new Object[]{mergingRes, ex.getMessage()}); break; } } logger.log(Level.SEVERE, "Malformed xml file: " + ex.getMessage(), mergingRes); } catch (Throwable th) { logger.log(Level.SEVERE, "Critical error while merging file " + mergingRes, th); th.printStackTrace(); merge.errors++; return; } } if (outTestList != null) { if (merge.errors == 0 || boe == BreakOnError.SKIP) { logger.log(Level.INFO, "- Generating result testlist"); if (merge.getSkippedCount() > 0) { Result[] newres = new Result[merge.jcovFiles.length - merge.getSkippedCount()]; int newresI = 0; outer: for (int i = 0; i < merge.jcovFiles.length; ++i) { for (int j = 0; j < merge.getSkippedCount(); ++j) { if (merge.jcovFiles[i].getResultPath().equals(merge.getSkippedFiles().get(j))) { continue outer; } } newres[newresI++] = merge.jcovFiles[i]; } merge.resultTestList = generateTestList(outTestList, newres, merged, merge.template != null); } else { merge.resultTestList = generateTestList(outTestList, merge.jcovFiles, merged, merge.template != null); } } else { logger.log(Level.SEVERE, "Don't generating result testlist - errors occurred"); } } if ((merge.errors > 0 && boe != BreakOnError.SKIP) || boe == BreakOnError.TEST) { logger.log(Level.SEVERE, "- Merging failed. Use \"-boe skip\" option to ignore bad files."); return; // DataRoot is not set to Merge } logger.log(Level.INFO, "- Merging complete"); if (merge.getSkippedCount() > 0) { logger.log(Level.SEVERE, "- {0} files were skipped: ", merge.getSkippedCount()); int i = 1; for (String skipped : merge.getSkippedFiles()) { logger.log(Level.SEVERE, "-- {0}", skipped); } } if (filesMerged < 2) { if (merge.getSkippedCount() > 0) { logger.log(Level.SEVERE, "- Not enough correct files to perform merging. Found {0} correct files and {1} were skipped due to errors while needed at least 2 correct files", new Object[]{filesMerged, merge.getSkippedCount()}); } else { logger.log(Level.SEVERE, "- Not enough correct files to perform merging. Found {0} correct files while needed at least 2", filesMerged); } return; } merge.result = merged; } protected int run() throws Exception { Result results[]; try { results = initResults(srcs, read_scales); } catch (IOException ex) { throw new IOException("Can't read test lists", ex); } Merge merge = new Merge(results, template); mergeAndWrite(merge, outTestList, output, skippedPath); if (boe == BreakOnError.TEST || warningCritical) { return merge.errors + merge.warnings; } else { return merge.errors; } } protected String usageString() { return "java com.sun.tdk.jcov.Merger [options] <filenames>"; } protected String exampleString() { return "java -cp jcov.jar com.sun.tdk.jcov.Merger -include java.lang.* -scale -output merged.xml test1.xml test2.xml"; } protected String getDescr() { return "merges several jcov data files"; } private String[] generateTestList(String outTestList, Result[] results, Object root, boolean cleanTmpl) { // list of unique test names to be written to output file ArrayList testList = new ArrayList(); // pairs of duplicate tests ArrayList pairs = new ArrayList(); int cur = 0; int length = cleanTmpl ? results.length + 1 : results.length; for (int i = 0; i < length; i++) { String[] tlist; if (cleanTmpl) { if (i == 0) { tlist = new String[]{results[0].getTestList()[0]}; } else { tlist = results[i - 1].getTestList(); } } else { tlist = results[i].getTestList(); } for (int j = 0; j < tlist.length; j++) { int found = testList.indexOf(tlist[j]); if (found < 0) { testList.add(tlist[j]); } else { pairs.add(new Utils.Pair(found, cur)); } cur++; } } if (root instanceof DataRoot) { ((DataRoot) root).illuminateDuplicatesInScales(pairs); } return (String[]) testList.toArray(new String[testList.size()]); } /** * Decodes list of jcov file names. File name may be in one of three forms: * <ul> <li> a.jcov#test_a - jcov for the test "test_a" </li> <li> * b.jcov%test.lst - jcov for the tests listed in the file "test.lst"</li> * <li> c.jcov - jcov for the test "c.jcov"</li> </ul> Method removes "#..." * and "%..." from the names of jcov files. Returned structure will contain * test list for each passed jcov file.<br> Example: <br> * <code> * initTestList({"a.jcov#test_a", "b.jcov%test.lst", "c.jcov"}) * will return: * { * {"test_a"}, * {"t1, t2, t3, t4"}, // lines of test.lst file * {"c.jcov"}, * } * passed array will be transformed to {"a.jcov", "b.jcov", "c.jcov"} * </code> * * @param jcov_files - jcov file lists * @return array of String arrays, where i-th row is comprised of tests for * jcov_files[i] */ public static Result[] initResults(String[] jcov_files, boolean initTestlists) throws IOException { Result[] results = new Result[jcov_files.length]; for (int i = 0; i < jcov_files.length; i++) { results[i] = new Result(); String str = jcov_files[i]; int k = str.indexOf('%'); if (k < 0) { k = str.indexOf('#'); if (k < 0) { results[i].setResultPath(str); if (initTestlists) { results[i].setDefaultName(); } } else { results[i].setResultPath(str.substring(0, k)); if (initTestlists) { results[i].setTestName(str.substring(k + 1)); } } } else { results[i].setResultPath(str.substring(0, k)); if (initTestlists) { results[i].readTestList(str.substring(k + 1)); } } } return results; } /** * * @param path Read testlist from file * @return read lines as array * @throws IOException */ public static String[] initTestList(String path) throws IOException { return Utils.readLines(path); } /** * Read testlist from file using first and last as borders in the files * * @param path file to read * @param first the first line to read * @param last the last line to read * @return read lines as array * @throws IOException */ public static String[] initTestList(String path, int first, int last) throws IOException { return Utils.readLines(path, first, last); } /** * JCov Merger allows to specify source files among with testlist (eg * result.xml%testlist) or testname (eg result.xml#test1). * * @param jcov_file filename to parse * @return Initialized Result object * @throws IOException * @see Result */ public static Result parseResultFromString(String jcov_file) throws IOException { Result res; int k = jcov_file.indexOf('%'); // testlist file separator if (k < 0) { k = jcov_file.indexOf('#'); // testname separator if (k > 0) { res = new Result(jcov_file.substring(0, k), new String[]{jcov_file.substring(k + 1)}); } else { res = new Result(jcov_file); } } else { res = new Result(jcov_file.substring(0, k), jcov_file.substring(k + 1)); } return res; } ///////// public API getters & setters ///////// /** * Sets default (ClassSignatureAcceptor) acceptor using include, exclude and * fm. * * @param include * @param exclude * @param fm */ public void setDefaultReadingFilter(String[] include, String[] exclude, String[] fm) { setDefaultReadingFilter(include, exclude, m_include, m_exclude, fm); } public void setDefaultReadingFilter(String[] include, String[] exclude, String[] m_include, String[] m_exclude, String[] fm) { this.include = include; this.exclude = exclude; this.m_include = m_include; this.m_exclude = m_exclude; this.fm = fm; this.readFilter = new ClassSignatureFilter(include, exclude, m_include, m_exclude, fm); } /** * Set ClassSignatureFilter used by this Merger to read the DataRoot * * @param filter */ public void setReadingFilter(ClassSignatureFilter filter) { this.readFilter = filter; } public BreakOnError getBreakOnError() { return boe; } public void setBreakOnError(BreakOnError boe) { this.boe = boe; } public static ScaleCompressor getCompressor() { return compressor; } public static void setCompressor(ScaleCompressor compressor) { Merger.compressor = compressor; } public int getLoose_lvl() { return loose_lvl; } public void setLoose_lvl(int loose_lvl) { this.loose_lvl = loose_lvl; } public boolean isRead_scales() { return read_scales; } public void setRead_scales(boolean read_scales) { this.read_scales = read_scales; } public boolean isCompress() { return compress; } public void setCompress(boolean compress) { this.compress = compress; } public void setFilters(String[] include, String[] exclude, String[] classModifiers) { if (include == null) { include = new String[]{".*"}; } this.include = include; if (exclude == null) { exclude = new String[]{""}; } this.exclude = exclude; this.fm = classModifiers; } public void setClassModifiers(String[] fm) { this.fm = fm; } public void resetDefaults() { try { handleEnv_(defineHandler()); setBreakOnError(BreakOnError.NONE); setRead_scales(false); setReadingFilter(null); setLoose_lvl(0); setCompress(false); warningCritical = false; } catch (EnvHandlingException ex) { // should not happen } } public String[] getExclude() { return exclude; } public String[] getInclude() { return include; } public String[] getFm() { return fm; } public boolean isAddMissing() { return addMissing; } public void setAddMissing(boolean addMissing) { this.addMissing = addMissing; } public void setSigmerge(boolean sigmerge) { this.sigmerge = sigmerge; } public boolean isSigmerge() { return sigmerge; } public boolean isWarningCritical() { return warningCritical; } public void setWarningCritical(boolean warningCritical) { this.warningCritical = warningCritical; } ///////// JCovTool implementation ///////// @Override protected EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{ DSC_OUTPUT, DSC_FILELIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FM, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FM_LIST, DSC_SCALE, DSC_OUTPUT_TEST_LIST, DSC_VERBOSE, DSC_LOOSE, DSC_COMPRESS, DSC_BREAKERR, DSC_WARNINGS, DSC_TEMPLATE, DSC_SKIPPED }, this); } private int handleEnv_(EnvHandler opts) throws EnvHandlingException { if (opts.isSet(DSC_FILELIST)) { String val = opts.getValue(DSC_FILELIST); int start = -1; int end = -1; String file = val; int ind = val.indexOf(","); if (ind != -1) { file = val.substring(0, ind); String rest = val.substring(ind + 1); int second_ind = rest.indexOf(","); if (second_ind == -1) { start = Integer.parseInt(rest); } else { start = Integer.parseInt(rest.substring(0, second_ind)); end = Integer.parseInt(rest.substring(second_ind + 1, rest.length())); } } Utils.checkFileNotNull(file, "filelist filename", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_CANREAD, Utils.CheckOptions.FILE_ISFILE); try { srcs = Utils.readLines(file, start, end); } catch (IOException ex) { throw new EnvHandlingException("Can't read filelist " + val, ex); } } include = InstrumentationOptions.handleInclude(opts); exclude = InstrumentationOptions.handleExclude(opts); m_include = InstrumentationOptions.handleMInclude(opts); m_exclude = InstrumentationOptions.handleMExclude(opts); fm = InstrumentationOptions.handleFM(opts); read_scales = opts.isSet(DSC_SCALE); if (opts.isSet(DSC_LOOSE)) { String loose = opts.getValue(DSC_LOOSE); if (LOOSE_BLOCKS.equals(loose)) { sigmerge = true; } else { try { loose_lvl = Utils.checkedToInt(loose, "loose level", Utils.CheckOptions.INT_POSITIVE); } catch (NumberFormatException nfe) { throw new EnvHandlingException("Can't parse loose level " + loose, nfe); } } } outTestList = null; if (opts.isSet(DSC_OUTPUT_TEST_LIST)) { outTestList = opts.getValue(DSC_OUTPUT_TEST_LIST); Utils.checkFileNotNull(outTestList, "output testlist filename", Utils.CheckOptions.FILE_CANWRITE, Utils.CheckOptions.FILE_NOTISDIR, Utils.CheckOptions.FILE_PARENTEXISTS); read_scales = true; } skippedPath = opts.getValue(DSC_SKIPPED); String boestr = opts.getValue(DSC_BREAKERR); if ("error".equalsIgnoreCase(boestr)) { boe = BreakOnError.ERROR; } else if ("test".equalsIgnoreCase(boestr)) { boe = BreakOnError.TEST; } else if ("file".equalsIgnoreCase(boestr)) { boe = BreakOnError.FILE; } else if ("skip".equalsIgnoreCase(boestr)) { boe = BreakOnError.SKIP; } else { boe = BreakOnError.NONE; } template = opts.getValue(DSC_TEMPLATE); Utils.checkFileCanBeNull(template, "template filename", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_ISFILE, Utils.CheckOptions.FILE_CANREAD); addMissing = template == null; output = opts.getValue(DSC_OUTPUT); Utils.checkFileNotNull(output, "output filename", Utils.CheckOptions.FILE_NOTISDIR, Utils.CheckOptions.FILE_PARENTEXISTS, Utils.CheckOptions.FILE_CANWRITE); compress = opts.isSet(DSC_COMPRESS); if (opts.isSet(DSC_VERBOSE)) { logger.setLevel(Level.INFO); } warningCritical = opts.isSet(DSC_WARNINGS); return SUCCESS_EXIT_CODE; } @Override protected int handleEnv(EnvHandler opts) throws EnvHandlingException { srcs = opts.getTail(); int code = handleEnv_(opts); if (srcs == null || srcs.length == 0) { // srcs could be set from filelist throw new EnvHandlingException("No input files specified"); } return code; } final static OptionDescr DSC_SKIPPED = new OptionDescr("outSkipped", "path for list of skipped files", OptionDescr.VAL_SINGLE, "Sets path to the list of files that were skipped during the merge by '-boe skip' option"); final static OptionDescr DSC_TEMPLATE = new OptionDescr("template", new String[]{"tmpl", "t"}, "template path", OptionDescr.VAL_SINGLE, "Sets path to the template used for merging. Only data in template will be merged"); final static OptionDescr DSC_BREAKERR = new OptionDescr("breakonerror", new String[]{"boe", "onerror"}, "break on error", new String[][]{{"file", "break when finished merging first file with errors"}, {"error", "break on the first occurred error"}, {"test", "don't break on any error and don't write result file"}, {"skip", "merge all correct files. Attention: first jcov file is always considered to be correct. Use '-template' option to ensure correct results."}, {"none", "don't break on any error and write result file if all passed. Neither result file neither testlist would be written if any error will occur."}}, "Sets type of handling errors in merging process. Can be 'none', 'test', 'error', 'skip' and 'file'", "file"); final static OptionDescr DSC_OUTPUT = new OptionDescr("merger.output", new String[]{"output", "o"}, "output file", OptionDescr.VAL_SINGLE, "Output file for generating new profiler data file.", "merged.xml"); final static OptionDescr DSC_FILELIST = new OptionDescr("filelist", "file to read jcov input files from", OptionDescr.VAL_SINGLE, "Text file to read jcov data files for merge from. One file name per line.\n" + "The option allows to specify a range of lines to be read:\n" + "-filelist=<file>,first_line,last_line"); final static OptionDescr DSC_SCALE = new OptionDescr("scale", "process/generate test scales", "Process/generate test scale that lets find tests covering specific\n" + "code sections (no scale by default)"); final static OptionDescr DSC_COMPRESS = new OptionDescr("compress", "compress test scales", "Compress test scales."); final static OptionDescr DSC_VERBOSE = new OptionDescr("verbose", new String[]{"v"}, "verbose mode", "Enables verbose mode"); final static OptionDescr DSC_OUTPUT_TEST_LIST = new OptionDescr("outTestList", "", OptionDescr.VAL_SINGLE, "Generate summary test list. Test names will be extracted from the filename\n" + "operands, which may be specified in one of the following ways:\n" + " a.jcov#test_a coverage file for 'test_a'\n" + " b.jcov%test.lst coverage file for tests listed in 'test.lst'\n" + " testC/c.jcov coverage file for 'testC/c.jcov'"); final static OptionDescr DSC_LOOSE = new OptionDescr("loose", "looseness level", new String[][]{ {LOOSE_0, "none (strict)"}, {LOOSE_1, "moderate"}, {LOOSE_2, "high"}, {LOOSE_3, "highest"}, {LOOSE_BLOCKS, "drop blocks"} }, "Sets the \"looseness\" level of merger operation.\n" + "0 - default strict mode. All errors are treated as fatal.\n" + "1 - warning instead of an error when merging two classes " + "with the same name and common timestamp, whose coverage " + "item counts don't match.\n" + "2 - warning instead of an error when merging two classes " + "with the same name and the same arbitrary timestamp, " + "whose coverage item counts don't match.\n" + "Also allows to merge without warning DATA: B and DATA: C classes\n" + "3 - warning instead of any error\n" + "blocks - all blocks information would be dropped. JCov data will be " + "truncated to method coverage without any checks in block structure and then merged by signatures", LOOSE_0); final static OptionDescr DSC_WARNINGS = new OptionDescr("critwarn", "", OptionDescr.VAL_NONE, "Count warnings as errors", "When set JCov will process warnings (e.g. java version missmatch) just as errors"); }
44,003
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z