repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
jabref-main/src/main/java/org/jabref/logic/remote/server/RemoteListenerServerManager.java
package org.jabref.logic.remote.server; import java.io.IOException; import java.net.BindException; import org.jabref.gui.JabRefExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Manages the TeleServerThread through typical life cycle methods. * <p/> * open -> start -> stop * openAndStart -> stop * <p/> * Observer: isOpen, isNotStartedBefore */ public class RemoteListenerServerManager implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteListenerServerManager.class); private RemoteListenerServerThread remoteServerThread; public void stop() { if (isOpen()) { remoteServerThread.interrupt(); remoteServerThread = null; JabRefExecutorService.INSTANCE.stopRemoteThread(); } } /** * Acquire any resources needed for the server. */ public void open(RemoteMessageHandler messageHandler, int port) { if (isOpen()) { return; } try { remoteServerThread = new RemoteListenerServerThread(messageHandler, port); } catch (BindException e) { LOGGER.error("There was an error opening the configured network port {}. Please ensure there isn't another" + " application already using that port.", port); remoteServerThread = null; } catch (IOException e) { LOGGER.error("Unknown error while opening the network port.", e); remoteServerThread = null; } } public boolean isOpen() { return remoteServerThread != null; } public void start() { if (isOpen() && isNotStartedBefore()) { // threads can only be started when in state NEW JabRefExecutorService.INSTANCE.startRemoteThread(remoteServerThread); } } public boolean isNotStartedBefore() { // threads can only be started when in state NEW return (remoteServerThread == null) || (remoteServerThread.getState() == Thread.State.NEW); } public void openAndStart(RemoteMessageHandler messageHandler, int port) { open(messageHandler, port); start(); } @Override public void close() { stop(); } }
2,278
27.848101
121
java
null
jabref-main/src/main/java/org/jabref/logic/remote/server/RemoteListenerServerThread.java
package org.jabref.logic.remote.server; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This thread wrapper is required to be able to interrupt the remote listener server, e.g. when JabRef is closing down the server should shutdown as well. */ public class RemoteListenerServerThread extends Thread { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteListenerServerThread.class); private final RemoteListenerServer server; public RemoteListenerServerThread(RemoteMessageHandler messageHandler, int port) throws IOException { this.server = new RemoteListenerServer(messageHandler, port); this.setName("JabRef - Remote Listener Server on port " + port); } @Override public void interrupt() { LOGGER.debug("Interrupting " + this.getName()); this.server.closeServerSocket(); super.interrupt(); } @Override public void run() { this.server.run(); } }
1,003
28.529412
155
java
null
jabref-main/src/main/java/org/jabref/logic/remote/server/RemoteMessageHandler.java
package org.jabref.logic.remote.server; @FunctionalInterface public interface RemoteMessageHandler { void handleCommandLineArguments(String[] message); }
160
19.125
54
java
null
jabref-main/src/main/java/org/jabref/logic/search/DatabaseSearcher.java
package org.jabref.logic.search; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabases; import org.jabref.model.entry.BibEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DatabaseSearcher { private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseSearcher.class); private final SearchQuery query; private final BibDatabase database; public DatabaseSearcher(SearchQuery query, BibDatabase database) { this.query = Objects.requireNonNull(query); this.database = Objects.requireNonNull(database); } public List<BibEntry> getMatches() { LOGGER.debug("Search term: " + query); if (!query.isValid()) { LOGGER.warn("Search failed: illegal search expression"); return Collections.emptyList(); } List<BibEntry> matchEntries = database.getEntries().stream().filter(query::isMatch).collect(Collectors.toList()); return BibDatabases.purgeEmptyEntries(matchEntries); } }
1,168
28.974359
121
java
null
jabref-main/src/main/java/org/jabref/logic/search/SearchQuery.java
package org.jabref.logic.search; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.search.SearchMatcher; import org.jabref.model.search.rules.ContainsBasedSearchRule; import org.jabref.model.search.rules.GrammarBasedSearchRule; import org.jabref.model.search.rules.SearchRule; import org.jabref.model.search.rules.SearchRules; import org.jabref.model.search.rules.SentenceAnalyzer; public class SearchQuery implements SearchMatcher { /** * The mode of escaping special characters in regular expressions */ private enum EscapeMode { /** * using \Q and \E marks */ JAVA { @Override String format(String regex) { return Pattern.quote(regex); } }, /** * escaping all javascript regex special characters separately */ JAVASCRIPT { @Override String format(String regex) { return JAVASCRIPT_ESCAPED_CHARS_PATTERN.matcher(regex).replaceAll("\\\\$0"); } }; /** * Regex pattern for escaping special characters in javascript regular expressions */ private static final Pattern JAVASCRIPT_ESCAPED_CHARS_PATTERN = Pattern.compile("[.*+?^${}()|\\[\\]\\\\/]"); /** * Attempt to escape all regex special characters. * * @param regex a string containing a regex expression * @return a regex with all special characters escaped */ abstract String format(String regex); } private final String query; private EnumSet<SearchRules.SearchFlags> searchFlags; private final SearchRule rule; public SearchQuery(String query, EnumSet<SearchRules.SearchFlags> searchFlags) { this.query = Objects.requireNonNull(query); this.searchFlags = searchFlags; this.rule = SearchRules.getSearchRuleByQuery(query, searchFlags); } @Override public String toString() { return String.format("\"%s\" (%s, %s)", getQuery(), getCaseSensitiveDescription(), getRegularExpressionDescription()); } @Override public boolean isMatch(BibEntry entry) { return rule.applyRule(getQuery(), entry); } public boolean isValid() { return rule.validateSearchStrings(getQuery()); } public boolean isContainsBasedSearch() { return rule instanceof ContainsBasedSearchRule; } private String getCaseSensitiveDescription() { if (searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) { return "case sensitive"; } else { return "case insensitive"; } } private String getRegularExpressionDescription() { if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) { return "regular expression"; } else { return "plain text"; } } public String localize() { return String.format("\"%s\" (%s, %s)", getQuery(), getLocalizedCaseSensitiveDescription(), getLocalizedRegularExpressionDescription()); } private String getLocalizedCaseSensitiveDescription() { if (searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) { return Localization.lang("case sensitive"); } else { return Localization.lang("case insensitive"); } } private String getLocalizedRegularExpressionDescription() { if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) { return Localization.lang("regular expression"); } else { return Localization.lang("plain text"); } } /** * Tests if the query is an advanced search query described as described in the help * * @return true if the query is an advanced search query */ public boolean isGrammarBasedSearch() { return rule instanceof GrammarBasedSearchRule; } public String getQuery() { return query; } public EnumSet<SearchRules.SearchFlags> getSearchFlags() { return searchFlags; } /** * Returns a list of words this query searches for. The returned strings can be a regular expression. */ public List<String> getSearchWords() { if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) { return Collections.singletonList(getQuery()); } else { // Parses the search query for valid words and returns a list these words. // For example, "The great Vikinger" will give ["The","great","Vikinger"] return (new SentenceAnalyzer(getQuery())).getWords(); } } // Returns a regular expression pattern in the form (w1)|(w2)| ... wi are escaped if no regular expression search is enabled public Optional<Pattern> getPatternForWords() { return joinWordsToPattern(EscapeMode.JAVA); } // Returns a regular expression pattern in the form (w1)|(w2)| ... wi are escaped for javascript if no regular expression search is enabled public Optional<Pattern> getJavaScriptPatternForWords() { return joinWordsToPattern(EscapeMode.JAVASCRIPT); } /** * Returns a regular expression pattern in the form (w1)|(w2)| ... wi are escaped if no regular expression search is enabled * * @param escapeMode the mode of escaping special characters in wi */ private Optional<Pattern> joinWordsToPattern(EscapeMode escapeMode) { List<String> words = getSearchWords(); if ((words == null) || words.isEmpty() || words.get(0).isEmpty()) { return Optional.empty(); } // compile the words to a regular expression in the form (w1)|(w2)|(w3) Stream<String> joiner = words.stream(); if (!searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) { // Reformat string when we are looking for a literal match joiner = joiner.map(escapeMode::format); } String searchPattern = joiner.collect(Collectors.joining(")|(", "(", ")")); if (searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) { return Optional.of(Pattern.compile(searchPattern)); } else { return Optional.of(Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE)); } } public SearchRule getRule() { return rule; } }
6,767
33.181818
143
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DBMSConnection.java
package org.jabref.logic.shared; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.HashSet; import java.util.Set; import org.jabref.logic.l10n.Localization; import org.jabref.logic.shared.exception.InvalidDBMSConnectionPropertiesException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DBMSConnection implements DatabaseConnection { private static final Logger LOGGER = LoggerFactory.getLogger(DBMSConnection.class); private final Connection connection; private final DBMSConnectionProperties properties; public DBMSConnection(DBMSConnectionProperties connectionProperties) throws SQLException, InvalidDBMSConnectionPropertiesException { if (!connectionProperties.isValid()) { throw new InvalidDBMSConnectionPropertiesException(); } this.properties = connectionProperties; try { DriverManager.setLoginTimeout(3); // ensure that all SQL drivers are loaded - source: http://stackoverflow.com/a/22384826/873282 // we use the side effect of getAvailableDBMSTypes() - it loads all available drivers DBMSConnection.getAvailableDBMSTypes(); this.connection = DriverManager.getConnection(connectionProperties.getUrl(), connectionProperties.asProperties()); } catch (SQLException e) { // Some systems like PostgreSQL retrieves 0 to every exception. // Therefore a stable error determination is not possible. LOGGER.error("Could not connect to database: " + e.getMessage() + " - Error code: " + e.getErrorCode()); throw e; } } @Override public Connection getConnection() { return this.connection; } @Override public DBMSConnectionProperties getProperties() { return this.properties; } /** * Returns a Set of {@link DBMSType} which is supported by available drivers. */ public static Set<DBMSType> getAvailableDBMSTypes() { Set<DBMSType> dbmsTypes = new HashSet<>(); for (DBMSType dbms : DBMSType.values()) { try { Class.forName(dbms.getDriverClassPath()); dbmsTypes.add(dbms); } catch (ClassNotFoundException e) { // In case that the driver is not available do not perform tests for this system. LOGGER.info(Localization.lang("%0 driver not available.", dbms.toString())); } } return dbmsTypes; } }
2,563
35.628571
136
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DBMSConnectionProperties.java
package org.jabref.logic.shared; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Objects; import java.util.Optional; import java.util.Properties; import org.jabref.logic.shared.prefs.SharedDatabasePreferences; import org.jabref.logic.shared.security.Password; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Keeps all essential data for establishing a new connection to a DBMS using {@link DBMSConnection}. */ public class DBMSConnectionProperties implements DatabaseConnectionProperties { private static final Logger LOGGER = LoggerFactory.getLogger(DBMSConnectionProperties.class); private DBMSType type; private String host; private int port; private String database; private String user; private String password; private boolean allowPublicKeyRetrieval; private boolean useSSL; private String serverTimezone = ""; // Not needed for connection, but stored for future login private String keyStore; /** * Gets all required data from {@link SharedDatabasePreferences} and sets them if present. */ public DBMSConnectionProperties(SharedDatabasePreferences prefs) { if (prefs.getType().isPresent()) { Optional<DBMSType> dbmsType = DBMSType.fromString(prefs.getType().get()); if (dbmsType.isPresent()) { this.type = dbmsType.get(); } } prefs.getHost().ifPresent(theHost -> this.host = theHost); prefs.getPort().ifPresent(thePort -> this.port = Integer.parseInt(thePort)); prefs.getName().ifPresent(theDatabase -> this.database = theDatabase); prefs.getKeyStoreFile().ifPresent(theKeystore -> this.keyStore = theKeystore); prefs.getServerTimezone().ifPresent(theServerTimezone -> this.serverTimezone = theServerTimezone); this.useSSL = prefs.isUseSSL(); if (prefs.getUser().isPresent()) { this.user = prefs.getUser().get(); if (prefs.getPassword().isPresent()) { try { this.password = new Password(prefs.getPassword().get().toCharArray(), prefs.getUser().get()).decrypt(); } catch (UnsupportedEncodingException | GeneralSecurityException e) { LOGGER.error("Could not decrypt password", e); } } } if (!prefs.getPassword().isPresent()) { // Some DBMS require a non-null value as a password (in case of using an empty string). this.password = ""; } } DBMSConnectionProperties(DBMSType type, String host, int port, String database, String user, String password, boolean useSSL, boolean allowPublicKeyRetrieval, String serverTimezone, String keyStore) { this.type = type; this.host = host; this.port = port; this.database = database; this.user = user; this.password = password; this.useSSL = useSSL; this.allowPublicKeyRetrieval = allowPublicKeyRetrieval; this.serverTimezone = serverTimezone; this.keyStore = keyStore; } @Override public DBMSType getType() { return type; } @Override public String getHost() { return host; } @Override public int getPort() { return port; } @Override public String getDatabase() { return database; } @Override public String getUser() { return user; } @Override public String getPassword() { return password; } @Override public boolean isUseSSL() { return useSSL; } @Override public boolean isAllowPublicKeyRetrieval() { return allowPublicKeyRetrieval; } @Override public String getServerTimezone() { return serverTimezone; } public String getUrl() { String url = type.getUrl(host, port, database); return url; } /** * Returns username, password and ssl as Properties Object * * @return Properties with values for user, password and ssl */ public Properties asProperties() { Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", password); props.setProperty("serverTimezone", serverTimezone); if (useSSL) { props.setProperty("ssl", Boolean.toString(useSSL)); props.setProperty("useSSL", Boolean.toString(useSSL)); } if (allowPublicKeyRetrieval) { props.setProperty("allowPublicKeyRetrieval", Boolean.toString(allowPublicKeyRetrieval)); } return props; } @Override public String getKeyStore() { return keyStore; } /** * Compares all properties except the password. */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof DBMSConnectionProperties)) { return false; } DBMSConnectionProperties properties = (DBMSConnectionProperties) obj; return Objects.equals(type, properties.getType()) && this.host.equalsIgnoreCase(properties.getHost()) && Objects.equals(port, properties.getPort()) && Objects.equals(database, properties.getDatabase()) && Objects.equals(user, properties.getUser()) && Objects.equals(useSSL, properties.isUseSSL()) && Objects.equals(allowPublicKeyRetrieval, properties.isAllowPublicKeyRetrieval()) && Objects.equals(serverTimezone, properties.getServerTimezone()); } @Override public int hashCode() { return Objects.hash(type, host, port, database, user, useSSL); } @Override public boolean isValid() { return Objects.nonNull(type) && Objects.nonNull(host) && Objects.nonNull(port) && Objects.nonNull(database) && Objects.nonNull(user) && Objects.nonNull(password); } }
6,188
30.416244
136
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DBMSConnectionPropertiesBuilder.java
package org.jabref.logic.shared; public class DBMSConnectionPropertiesBuilder { private DBMSType type; private String host; private int port = -1; private String database; private String user; private String password; private boolean useSSL; private boolean allowPublicKeyRetrieval; private String serverTimezone = ""; private String keyStore; public DBMSConnectionPropertiesBuilder setType(DBMSType type) { this.type = type; return this; } public DBMSConnectionPropertiesBuilder setHost(String host) { this.host = host; return this; } public DBMSConnectionPropertiesBuilder setPort(int port) { this.port = port; return this; } public DBMSConnectionPropertiesBuilder setDatabase(String database) { this.database = database; return this; } public DBMSConnectionPropertiesBuilder setUser(String user) { this.user = user; return this; } public DBMSConnectionPropertiesBuilder setPassword(String password) { this.password = password; return this; } public DBMSConnectionPropertiesBuilder setUseSSL(boolean useSSL) { this.useSSL = useSSL; return this; } public DBMSConnectionPropertiesBuilder setAllowPublicKeyRetrieval(boolean allowPublicKeyRetrieval) { this.allowPublicKeyRetrieval = allowPublicKeyRetrieval; return this; } public DBMSConnectionPropertiesBuilder setServerTimezone(String serverTimezone) { this.serverTimezone = serverTimezone; return this; } public DBMSConnectionPropertiesBuilder setKeyStore(String keyStore) { this.keyStore = keyStore; return this; } public DBMSConnectionProperties createDBMSConnectionProperties() { if (port == -1) { port = type.getDefaultPort(); } return new DBMSConnectionProperties(type, host, port, database, user, password, useSSL, allowPublicKeyRetrieval, serverTimezone, keyStore); } }
2,064
27.680556
147
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DBMSProcessor.java
package org.jabref.logic.shared; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import org.jabref.logic.shared.exception.OfflineLockException; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.SharedBibEntryData; import org.jabref.model.entry.event.EntriesEventSource; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.model.metadata.MetaData; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Processes all incoming or outgoing bib data to external SQL Database and manages its structure. */ public abstract class DBMSProcessor { public static final String PROCESSOR_ID = UUID.randomUUID().toString(); protected static final Logger LOGGER = LoggerFactory.getLogger(DBMSProcessor.class); protected final Connection connection; protected DatabaseConnectionProperties connectionProperties; protected DBMSProcessor(DatabaseConnection dbmsConnection) { this.connection = dbmsConnection.getConnection(); this.connectionProperties = dbmsConnection.getProperties(); } /** * Scans the database for required tables. * * @return <code>true</code> if the structure matches the requirements, <code>false</code> if not. * @throws SQLException */ public boolean checkBaseIntegrity() throws SQLException { boolean databasePassesIntegrityCheck = false; DBMSType type = this.connectionProperties.getType(); Map<String, String> metadata = getSharedMetaData(); if (type == DBMSType.POSTGRESQL || type == DBMSType.MYSQL) { try { Integer VERSION_DB_STRUCT = Integer.valueOf(metadata.get(MetaData.VERSION_DB_STRUCT)); if (VERSION_DB_STRUCT == getCURRENT_VERSION_DB_STRUCT()) { databasePassesIntegrityCheck = true; } } catch (Exception e) { databasePassesIntegrityCheck = false; } } else { databasePassesIntegrityCheck = checkTableAvailability("ENTRY", "FIELD", "METADATA"); } return databasePassesIntegrityCheck; } /** * Determines whether the database is using an pre-3.6 structure. * * @return <code>true</code> if the structure is old, else <code>false</code>. */ public boolean databaseIsAtMostJabRef35() throws SQLException { return checkTableAvailability( "ENTRIES", "ENTRY_GROUP", "ENTRY_TYPES", "GROUPS", "GROUP_TYPES", "JABREF_DATABASE", "STRINGS"); // old tables } /** * Checks whether all given table names (<b>case insensitive</b>) exist in database. * * @param tableNames Table names to be checked * @return <code>true</code> if <b>all</b> given tables are present, else <code>false</code>. */ protected boolean checkTableAvailability(String... tableNames) throws SQLException { List<String> requiredTables = new ArrayList<>(); for (String name : tableNames) { requiredTables.add(name.toUpperCase(Locale.ENGLISH)); } DatabaseMetaData databaseMetaData = connection.getMetaData(); // ...getTables(null, ...): no restrictions try (ResultSet databaseMetaDataResultSet = databaseMetaData.getTables(null, null, null, null)) { while (databaseMetaDataResultSet.next()) { String tableName = databaseMetaDataResultSet.getString("TABLE_NAME").toUpperCase(Locale.ROOT); requiredTables.remove(tableName); // Remove matching tables to check requiredTables for emptiness } return requiredTables.isEmpty(); } } /** * Creates and sets up the needed tables and columns according to the database type and performs a check whether the * needed tables are present. * * @throws SQLException */ public void setupSharedDatabase() throws SQLException { setUp(); if (!checkBaseIntegrity()) { // can only happen with users direct intervention on shared database LOGGER.error("Corrupt_shared_database_structure."); } } /** * Creates and sets up the needed tables and columns according to the database type. * * @throws SQLException */ protected abstract void setUp() throws SQLException; /** * Escapes parts of SQL expressions such as a table name or a field name to match the conventions of the database * system using the current dbmsType. * <p> * This method is package private, because of DBMSProcessorTest * * @param expression Table or field name * @return Correctly escaped expression */ abstract String escape(String expression); abstract String escape_Table(String expression); abstract Integer getCURRENT_VERSION_DB_STRUCT(); /** * For use in test only. Inserts the BibEntry into the shared database. * * @param bibEntry {@link BibEntry} to be inserted. */ public void insertEntry(BibEntry bibEntry) { insertEntries(Collections.singletonList(bibEntry)); } /** * Inserts the List of BibEntry into the shared database. * * @param bibEntries List of {@link BibEntry} to be inserted */ public void insertEntries(List<BibEntry> bibEntries) { List<BibEntry> notYetExistingEntries = getNotYetExistingEntries(bibEntries); if (notYetExistingEntries.isEmpty()) { return; } insertIntoEntryTable(notYetExistingEntries); insertIntoFieldTable(notYetExistingEntries); } /** * Inserts the given List of BibEntry into the ENTRY table. * * @param bibEntries List of {@link BibEntry} to be inserted */ protected void insertIntoEntryTable(List<BibEntry> bibEntries) { StringBuilder insertIntoEntryQuery = new StringBuilder() .append("INSERT INTO ") .append(escape_Table("ENTRY")) .append("(") .append(escape("TYPE")) .append(") VALUES(?)"); // Number of commas is bibEntries.size() - 1 for (int i = 0; i < (bibEntries.size() - 1); i++) { insertIntoEntryQuery.append(", (?)"); } try (PreparedStatement preparedEntryStatement = connection.prepareStatement(insertIntoEntryQuery.toString(), new String[]{"SHARED_ID"})) { for (int i = 0; i < bibEntries.size(); i++) { preparedEntryStatement.setString(i + 1, bibEntries.get(i).getType().getName()); } preparedEntryStatement.executeUpdate(); try (ResultSet generatedKeys = preparedEntryStatement.getGeneratedKeys()) { // The following assumes that we get the generated keys in the order the entries were inserted // This should be the case for (BibEntry bibEntry : bibEntries) { generatedKeys.next(); bibEntry.getSharedBibEntryData().setSharedID(generatedKeys.getInt(1)); } if (generatedKeys.next()) { LOGGER.error("Error: Some shared IDs left unassigned"); } } } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } } /** * Filters a list of BibEntry to and returns those which do not exist in the database * * @param bibEntries {@link BibEntry} to be checked * @return <code>true</code> if existent, else <code>false</code> */ private List<BibEntry> getNotYetExistingEntries(List<BibEntry> bibEntries) { List<Integer> remoteIds = new ArrayList<>(); List<Integer> localIds = bibEntries.stream() .map(BibEntry::getSharedBibEntryData) .map(SharedBibEntryData::getSharedID) .filter(id -> id != -1) .collect(Collectors.toList()); if (localIds.isEmpty()) { return bibEntries; } try { StringBuilder selectQuery = new StringBuilder() .append("SELECT * FROM ") .append(escape_Table("ENTRY")); try (ResultSet resultSet = connection.createStatement().executeQuery(selectQuery.toString())) { while (resultSet.next()) { int id = resultSet.getInt("SHARED_ID"); remoteIds.add(id); } } } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } return bibEntries.stream().filter(entry -> !remoteIds.contains(entry.getSharedBibEntryData().getSharedID())) .collect(Collectors.toList()); } /** * Inserts the given list of BibEntry into FIELD table. * * @param bibEntries {@link BibEntry} to be inserted */ protected void insertIntoFieldTable(List<BibEntry> bibEntries) { try { // Inserting into FIELD table // Coerce to ArrayList in order to use List.get() List<List<Field>> fields = bibEntries.stream().map(bibEntry -> new ArrayList<>(bibEntry.getFields())) .collect(Collectors.toList()); StringBuilder insertFieldQuery = new StringBuilder() .append("INSERT INTO ") .append(escape_Table("FIELD")) .append("(") .append(escape("ENTRY_SHARED_ID")) .append(", ") .append(escape("NAME")) .append(", ") .append(escape("VALUE")) .append(") VALUES(?, ?, ?)"); int numFields = 0; for (List<Field> entryFields : fields) { numFields += entryFields.size(); } if (numFields == 0) { return; // Prevent SQL Exception } // Number of commas is fields.size() - 1 for (int i = 0; i < (numFields - 1); i++) { insertFieldQuery.append(", (?, ?, ?)"); } try (PreparedStatement preparedFieldStatement = connection.prepareStatement(insertFieldQuery.toString())) { int fieldsCompleted = 0; for (int entryIndex = 0; entryIndex < fields.size(); entryIndex++) { for (int entryFieldsIndex = 0; entryFieldsIndex < fields.get(entryIndex).size(); entryFieldsIndex++) { // columnIndex starts with 1 preparedFieldStatement.setInt((3 * fieldsCompleted) + 1, bibEntries.get(entryIndex).getSharedBibEntryData().getSharedID()); preparedFieldStatement.setString((3 * fieldsCompleted) + 2, fields.get(entryIndex).get(entryFieldsIndex).getName()); preparedFieldStatement.setString((3 * fieldsCompleted) + 3, bibEntries.get(entryIndex).getField(fields.get(entryIndex).get(entryFieldsIndex)).get()); fieldsCompleted += 1; } } preparedFieldStatement.executeUpdate(); } } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } } /** * Updates the whole {@link BibEntry} on shared database. * * @param localBibEntry {@link BibEntry} affected by changes * @throws SQLException */ public void updateEntry(BibEntry localBibEntry) throws OfflineLockException, SQLException { connection.setAutoCommit(false); // disable auto commit due to transaction try { Optional<BibEntry> sharedEntryOptional = getSharedEntry(localBibEntry.getSharedBibEntryData().getSharedID()); if (!sharedEntryOptional.isPresent()) { return; } BibEntry sharedBibEntry = sharedEntryOptional.get(); // remove shared fields which do not exist locally removeSharedFieldsByDifference(localBibEntry, sharedBibEntry); // update only if local version is higher or the entries are equal if ((localBibEntry.getSharedBibEntryData().getVersion() >= sharedBibEntry.getSharedBibEntryData() .getVersion()) || localBibEntry.equals(sharedBibEntry)) { insertOrUpdateFields(localBibEntry); // updating entry type StringBuilder updateEntryTypeQuery = new StringBuilder() .append("UPDATE ") .append(escape_Table("ENTRY")) .append(" SET ") .append(escape("TYPE")) .append(" = ?, ") .append(escape("VERSION")) .append(" = ") .append(escape("VERSION")) .append(" + 1 WHERE ") .append(escape("SHARED_ID")) .append(" = ?"); try (PreparedStatement preparedUpdateEntryTypeStatement = connection.prepareStatement(updateEntryTypeQuery.toString())) { preparedUpdateEntryTypeStatement.setString(1, localBibEntry.getType().getName()); preparedUpdateEntryTypeStatement.setInt(2, localBibEntry.getSharedBibEntryData().getSharedID()); preparedUpdateEntryTypeStatement.executeUpdate(); } connection.commit(); // apply all changes in current transaction } else { throw new OfflineLockException(localBibEntry, sharedBibEntry); } } catch (SQLException e) { LOGGER.error("SQL Error: ", e); connection.rollback(); // undo changes made in current transaction } finally { connection.setAutoCommit(true); // enable auto commit mode again } } /** * Helping method. Removes shared fields which do not exist locally */ private void removeSharedFieldsByDifference(BibEntry localBibEntry, BibEntry sharedBibEntry) throws SQLException { Set<Field> nullFields = new HashSet<>(sharedBibEntry.getFields()); nullFields.removeAll(localBibEntry.getFields()); for (Field nullField : nullFields) { StringBuilder deleteFieldQuery = new StringBuilder() .append("DELETE FROM ") .append(escape_Table("FIELD")) .append(" WHERE ") .append(escape("NAME")) .append(" = ? AND ") .append(escape("ENTRY_SHARED_ID")) .append(" = ?"); try (PreparedStatement preparedDeleteFieldStatement = connection .prepareStatement(deleteFieldQuery.toString())) { preparedDeleteFieldStatement.setString(1, nullField.getName()); preparedDeleteFieldStatement.setInt(2, localBibEntry.getSharedBibEntryData().getSharedID()); preparedDeleteFieldStatement.executeUpdate(); } } } /** * Helping method. Inserts a key-value pair into FIELD table for every field if not existing. Otherwise only an * update is performed. */ private void insertOrUpdateFields(BibEntry localBibEntry) throws SQLException { for (Field field : localBibEntry.getFields()) { // avoiding to use deprecated BibEntry.getField() method. null values are accepted by PreparedStatement! Optional<String> valueOptional = localBibEntry.getField(field); String value = null; if (valueOptional.isPresent()) { value = valueOptional.get(); } StringBuilder selectFieldQuery = new StringBuilder() .append("SELECT * FROM ") .append(escape_Table("FIELD")) .append(" WHERE ") .append(escape("NAME")) .append(" = ? AND ") .append(escape("ENTRY_SHARED_ID")) .append(" = ?"); try (PreparedStatement preparedSelectFieldStatement = connection .prepareStatement(selectFieldQuery.toString())) { preparedSelectFieldStatement.setString(1, field.getName()); preparedSelectFieldStatement.setInt(2, localBibEntry.getSharedBibEntryData().getSharedID()); try (ResultSet selectFieldResultSet = preparedSelectFieldStatement.executeQuery()) { if (selectFieldResultSet.next()) { // check if field already exists StringBuilder updateFieldQuery = new StringBuilder() .append("UPDATE ") .append(escape_Table("FIELD")) .append(" SET ") .append(escape("VALUE")) .append(" = ? WHERE ") .append(escape("NAME")) .append(" = ? AND ") .append(escape("ENTRY_SHARED_ID")) .append(" = ?"); try (PreparedStatement preparedUpdateFieldStatement = connection .prepareStatement(updateFieldQuery.toString())) { preparedUpdateFieldStatement.setString(1, value); preparedUpdateFieldStatement.setString(2, field.getName()); preparedUpdateFieldStatement.setInt(3, localBibEntry.getSharedBibEntryData().getSharedID()); preparedUpdateFieldStatement.executeUpdate(); } } else { StringBuilder insertFieldQuery = new StringBuilder() .append("INSERT INTO ") .append(escape_Table("FIELD")) .append("(") .append(escape("ENTRY_SHARED_ID")) .append(", ") .append(escape("NAME")) .append(", ") .append(escape("VALUE")) .append(") VALUES(?, ?, ?)"); try (PreparedStatement preparedFieldStatement = connection .prepareStatement(insertFieldQuery.toString())) { preparedFieldStatement.setInt(1, localBibEntry.getSharedBibEntryData().getSharedID()); preparedFieldStatement.setString(2, field.getName()); preparedFieldStatement.setString(3, value); preparedFieldStatement.executeUpdate(); } } } } } } /** * Removes the shared bibEntry. * * @param bibEntries {@link BibEntry} to be deleted */ public void removeEntries(List<BibEntry> bibEntries) { Objects.requireNonNull(bibEntries); if (bibEntries.isEmpty()) { return; } StringBuilder query = new StringBuilder() .append("DELETE FROM ") .append(escape_Table("ENTRY")) .append(" WHERE ") .append(escape("SHARED_ID")) .append(" IN ("); query.append("?, ".repeat(bibEntries.size() - 1)); query.append("?)"); try (PreparedStatement preparedStatement = connection.prepareStatement(query.toString())) { for (int j = 0; j < bibEntries.size(); j++) { preparedStatement.setInt(j + 1, bibEntries.get(j).getSharedBibEntryData().getSharedID()); } preparedStatement.executeUpdate(); } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } } /** * @param sharedID Entry ID * @return instance of {@link BibEntry} */ public Optional<BibEntry> getSharedEntry(int sharedID) { List<BibEntry> sharedEntries = getSharedEntries(Collections.singletonList(sharedID)); if (sharedEntries.isEmpty()) { return Optional.empty(); } else { return Optional.of(sharedEntries.get(0)); } } /** * Queries the database for shared entries in 500 element batches. * Optionally, they are filtered by the given list of sharedIds * * @param sharedIDs the list of Ids to filter. If list is empty, then no filter is applied */ public List<BibEntry> partitionAndGetSharedEntries(List<Integer> sharedIDs) { List<List<Integer>> partitions = Lists.partition(sharedIDs, 500); List<BibEntry> result = new ArrayList<>(); for (List<Integer> sublist : partitions) { result.addAll(getSharedEntries(sublist)); } return result; } /** * Queries the database for shared entries. Optionally, they are filtered by the given list of sharedIds * * @param sharedIDs the list of Ids to filter. If list is empty, then no filter is applied */ public List<BibEntry> getSharedEntries(List<Integer> sharedIDs) { Objects.requireNonNull(sharedIDs); List<BibEntry> sharedEntries = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT ") .append(escape_Table("ENTRY")).append(".").append(escape("SHARED_ID")).append(", ") .append(escape_Table("ENTRY")).append(".").append(escape("TYPE")).append(", ") .append(escape_Table("ENTRY")).append(".").append(escape("VERSION")).append(", ") .append("F.").append(escape("ENTRY_SHARED_ID")).append(", ") .append("F.").append(escape("NAME")).append(", ") .append("F.").append(escape("VALUE")) .append(" FROM ") .append(escape_Table("ENTRY")) // Handle special case if entry does not have any fields (yet) .append(" left outer join ") .append(escape_Table("FIELD")) .append(" F on ") .append(escape_Table("ENTRY")).append(".").append(escape("SHARED_ID")) .append(" = F.").append(escape("ENTRY_SHARED_ID")); if (!sharedIDs.isEmpty()) { query.append(" where ") .append(escape("SHARED_ID")).append(" in (") .append("?, ".repeat(sharedIDs.size() - 1)) .append("?)"); } query.append(" order by ") .append(escape("SHARED_ID")); try (PreparedStatement preparedStatement = connection.prepareStatement(query.toString())) { for (int i = 0; i < sharedIDs.size(); i++) { preparedStatement.setInt(i + 1, sharedIDs.get(i)); } try (ResultSet selectEntryResultSet = preparedStatement.executeQuery()) { BibEntry bibEntry = null; int lastId = -1; while (selectEntryResultSet.next()) { // We get a list of field values of bib entries "grouped" by bib entries // Thus, the first change in the shared id leads to a new BibEntry if (selectEntryResultSet.getInt("SHARED_ID") > lastId) { bibEntry = new BibEntry(); bibEntry.getSharedBibEntryData().setSharedID(selectEntryResultSet.getInt("SHARED_ID")); bibEntry.setType(EntryTypeFactory.parse(selectEntryResultSet.getString("TYPE"))); bibEntry.getSharedBibEntryData().setVersion(selectEntryResultSet.getInt("VERSION")); sharedEntries.add(bibEntry); lastId = selectEntryResultSet.getInt("SHARED_ID"); } // In all cases, we set the field value of the newly created BibEntry object String value = selectEntryResultSet.getString("VALUE"); if (value != null) { bibEntry.setField(FieldFactory.parseField(selectEntryResultSet.getString("NAME")), value, EntriesEventSource.SHARED); } } } } catch (SQLException e) { LOGGER.error("Executed >{}<", query.toString()); LOGGER.error("SQL Error", e); return Collections.emptyList(); } return sharedEntries; } public List<BibEntry> getSharedEntries() { return getSharedEntries(Collections.emptyList()); } /** * Retrieves a mapping between the columns SHARED_ID and VERSION. */ public Map<Integer, Integer> getSharedIDVersionMapping() { Map<Integer, Integer> sharedIDVersionMapping = new HashMap<>(); StringBuilder selectEntryQuery = new StringBuilder() .append("SELECT * FROM ") .append(escape_Table("ENTRY")) .append(" ORDER BY ") .append(escape("SHARED_ID")); try (ResultSet selectEntryResultSet = connection.createStatement().executeQuery(selectEntryQuery.toString())) { while (selectEntryResultSet.next()) { sharedIDVersionMapping.put(selectEntryResultSet.getInt("SHARED_ID"), selectEntryResultSet.getInt("VERSION")); } } catch (SQLException e) { LOGGER.error("SQL Error", e); } return sharedIDVersionMapping; } /** * Fetches and returns all shared meta data. */ public Map<String, String> getSharedMetaData() { Map<String, String> data = new HashMap<>(); try (ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM " + escape_Table("METADATA"))) { while (resultSet.next()) { data.put(resultSet.getString("KEY"), resultSet.getString("VALUE")); } } catch (SQLException e) { LOGGER.error("SQL Error", e); } return data; } /** * Clears and sets all shared meta data. * * @param data JabRef meta data as map */ public void setSharedMetaData(Map<String, String> data) throws SQLException { StringBuilder updateQuery = new StringBuilder() .append("UPDATE ") .append(escape_Table("METADATA")) .append(" SET ") .append(escape("VALUE")) .append(" = ? ") .append(" WHERE ") .append(escape("KEY")) .append(" = ?"); StringBuilder insertQuery = new StringBuilder() .append("INSERT INTO ") .append(escape_Table("METADATA")) .append("(") .append(escape("KEY")) .append(", ") .append(escape("VALUE")) .append(") VALUES(?, ?)"); for (Map.Entry<String, String> metaEntry : data.entrySet()) { try (PreparedStatement updateStatement = connection.prepareStatement(updateQuery.toString())) { updateStatement.setString(2, metaEntry.getKey()); updateStatement.setString(1, metaEntry.getValue()); if (updateStatement.executeUpdate() == 0) { // No rows updated -> insert data try (PreparedStatement insertStatement = connection.prepareStatement(insertQuery.toString())) { insertStatement.setString(1, metaEntry.getKey()); insertStatement.setString(2, metaEntry.getValue()); insertStatement.executeUpdate(); } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } } } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } } } /** * Returns a new instance of the abstract type {@link DBMSProcessor} */ public static DBMSProcessor getProcessorInstance(DatabaseConnection connection) { DBMSType type = connection.getProperties().getType(); if (type == DBMSType.MYSQL) { return new MySQLProcessor(connection); } else if (type == DBMSType.POSTGRESQL) { return new PostgreSQLProcessor(connection); } else if (type == DBMSType.ORACLE) { return new OracleProcessor(connection); } return null; // can never happen except new types were added without updating this method. } public DatabaseConnectionProperties getDBMSConnectionProperties() { return this.connectionProperties; } /** * Listens for notifications from DBMS. Needs to be implemented if LiveUpdate is supported by the DBMS * * @param dbmsSynchronizer {@link DBMSSynchronizer} which handles the notification. */ public void startNotificationListener(@SuppressWarnings("unused") DBMSSynchronizer dbmsSynchronizer) { // nothing to do } /** * Terminates the notification listener. Needs to be implemented if LiveUpdate is supported by the DBMS */ public void stopNotificationListener() { // nothing to do } /** * Notifies all clients ({@link DBMSSynchronizer}) which are connected to the same DBMS. Needs to be implemented if * LiveUpdate is supported by the DBMS */ public void notifyClients() { // nothing to do } }
30,493
41.352778
173
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DBMSSynchronizer.java
package org.jabref.logic.shared; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.logic.exporter.BibDatabaseWriter; import org.jabref.logic.exporter.MetaDataSerializer; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.util.MetaDataParser; import org.jabref.logic.shared.event.ConnectionLostEvent; import org.jabref.logic.shared.event.SharedEntriesNotPresentEvent; import org.jabref.logic.shared.event.UpdateRefusedEvent; import org.jabref.logic.shared.exception.OfflineLockException; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.event.EntriesAddedEvent; import org.jabref.model.database.event.EntriesRemovedEvent; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.event.EntriesEvent; import org.jabref.model.entry.event.EntriesEventSource; import org.jabref.model.entry.event.FieldChangedEvent; import org.jabref.model.metadata.MetaData; import org.jabref.model.metadata.event.MetaDataChangedEvent; import org.jabref.model.util.FileUpdateMonitor; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Synchronizes the shared or local databases with their opposite side. Local changes are pushed by {@link EntriesEvent} * using Google's Guava EventBus. */ public class DBMSSynchronizer implements DatabaseSynchronizer { private static final Logger LOGGER = LoggerFactory.getLogger(DBMSSynchronizer.class); private DBMSProcessor dbmsProcessor; private String dbName; private final BibDatabaseContext bibDatabaseContext; private MetaData metaData; private final BibDatabase bibDatabase; private final EventBus eventBus; private Connection currentConnection; private final Character keywordSeparator; private final GlobalCitationKeyPattern globalCiteKeyPattern; private final FileUpdateMonitor fileMonitor; private Optional<BibEntry> lastEntryChanged; public DBMSSynchronizer(BibDatabaseContext bibDatabaseContext, Character keywordSeparator, GlobalCitationKeyPattern globalCiteKeyPattern, FileUpdateMonitor fileMonitor) { this.bibDatabaseContext = Objects.requireNonNull(bibDatabaseContext); this.bibDatabase = bibDatabaseContext.getDatabase(); this.metaData = bibDatabaseContext.getMetaData(); this.fileMonitor = fileMonitor; this.eventBus = new EventBus(); this.keywordSeparator = keywordSeparator; this.globalCiteKeyPattern = Objects.requireNonNull(globalCiteKeyPattern); this.lastEntryChanged = Optional.empty(); } /** * Listening method. Inserts a new {@link BibEntry} into shared database. */ @Subscribe public void listen(EntriesAddedEvent event) { // While synchronizing the local database (see synchronizeLocalDatabase() below), some EntriesEvents may be posted. // In this case DBSynchronizer should not try to insert the bibEntry entry again (but it would not harm). if (isEventSourceAccepted(event) && checkCurrentConnection()) { synchronizeLocalMetaData(); pullWithLastEntry(); synchronizeLocalDatabase(); dbmsProcessor.insertEntries(event.getBibEntries()); // Reset last changed entry because it just has already been synchronized -> Why necessary? lastEntryChanged = Optional.empty(); } } /** * Listening method. Updates an existing shared {@link BibEntry}. */ @Subscribe public void listen(FieldChangedEvent event) { BibEntry bibEntry = event.getBibEntry(); // While synchronizing the local database (see synchronizeLocalDatabase() below), some EntriesEvents may be posted. // In this case DBSynchronizer should not try to update the bibEntry entry again (but it would not harm). if (isPresentLocalBibEntry(bibEntry) && isEventSourceAccepted(event) && checkCurrentConnection() && !event.isFilteredOut()) { synchronizeLocalMetaData(); pullWithLastEntry(); synchronizeSharedEntry(bibEntry); synchronizeLocalDatabase(); // Pull changes for the case that there were some } else { // Set new BibEntry that has been changed last lastEntryChanged = Optional.of(bibEntry); } } /** * Listening method. Deletes the given list of {@link BibEntry} from shared database. */ @Subscribe public void listen(EntriesRemovedEvent event) { // While synchronizing the local database (see synchronizeLocalDatabase() below), some EntriesEvents may be posted. // In this case DBSynchronizer should not try to delete the bibEntry entry again (but it would not harm). if (isEventSourceAccepted(event) && checkCurrentConnection()) { synchronizeLocalMetaData(); pullWithLastEntry(); dbmsProcessor.removeEntries(event.getBibEntries()); synchronizeLocalDatabase(); } } /** * Listening method. Synchronizes the shared {@link MetaData} and applies them locally. */ @Subscribe public void listen(MetaDataChangedEvent event) { if (checkCurrentConnection()) { synchronizeSharedMetaData(event.getMetaData(), globalCiteKeyPattern); synchronizeLocalDatabase(); applyMetaData(); dbmsProcessor.notifyClients(); } } /** * Sets the table structure of shared database if needed and pulls all shared entries to the new local database. * * @throws DatabaseNotSupportedException if the version of shared database does not match the version of current * shared database support ({@link DBMSProcessor}). */ public void initializeDatabases() throws DatabaseNotSupportedException { try { if (!dbmsProcessor.checkBaseIntegrity()) { LOGGER.info("Integrity check failed. Fixing..."); // This check should only be performed once on initial database setup. if (dbmsProcessor.databaseIsAtMostJabRef35()) { throw new DatabaseNotSupportedException(); } // Calling dbmsProcessor.setupSharedDatabase() lets dbmsProcessor.checkBaseIntegrity() be true. dbmsProcessor.setupSharedDatabase(); } } catch (SQLException e) { LOGGER.error("Could not check intergrity", e); throw new IllegalStateException(e); } dbmsProcessor.startNotificationListener(this); synchronizeLocalMetaData(); synchronizeLocalDatabase(); } /** * Synchronizes the local database with shared one. Possible update types are: removal, update, or insert of a * {@link BibEntry}. */ @Override public void synchronizeLocalDatabase() { if (!checkCurrentConnection()) { return; } List<BibEntry> localEntries = bibDatabase.getEntries(); Map<Integer, Integer> idVersionMap = dbmsProcessor.getSharedIDVersionMapping(); // remove old entries locally removeNotSharedEntries(localEntries, idVersionMap.keySet()); List<Integer> entriesToInsertIntoLocalDatabase = new ArrayList<>(); // compare versions and update local entry if needed for (Map.Entry<Integer, Integer> idVersionEntry : idVersionMap.entrySet()) { boolean remoteEntryMatchingOneLocalEntryFound = false; for (BibEntry localEntry : localEntries) { if (idVersionEntry.getKey().equals(localEntry.getSharedBibEntryData().getSharedID())) { remoteEntryMatchingOneLocalEntryFound = true; if (idVersionEntry.getValue() > localEntry.getSharedBibEntryData().getVersion()) { Optional<BibEntry> sharedEntry = dbmsProcessor.getSharedEntry(idVersionEntry.getKey()); if (sharedEntry.isPresent()) { // update fields localEntry.setType(sharedEntry.get().getType(), EntriesEventSource.SHARED); localEntry.getSharedBibEntryData() .setVersion(sharedEntry.get().getSharedBibEntryData().getVersion()); sharedEntry.get().getFieldMap().forEach( // copy remote values to local entry (field, value) -> localEntry.setField(field, value, EntriesEventSource.SHARED) ); // locally remove not existing fields localEntry.getFields().stream() .filter(field -> !sharedEntry.get().hasField(field)) .forEach( field -> localEntry.clearField(field, EntriesEventSource.SHARED) ); } } } } if (!remoteEntryMatchingOneLocalEntryFound) { entriesToInsertIntoLocalDatabase.add(idVersionEntry.getKey()); } } if (!entriesToInsertIntoLocalDatabase.isEmpty()) { // in case entries should be added into the local database, insert them bibDatabase.insertEntries(dbmsProcessor.partitionAndGetSharedEntries(entriesToInsertIntoLocalDatabase), EntriesEventSource.SHARED); } } /** * Removes all local entries which are not present on shared database. * * @param localEntries List of {@link BibEntry} the entries should be removed from * @param sharedIDs Set of all IDs which are present on shared database */ private void removeNotSharedEntries(List<BibEntry> localEntries, Set<Integer> sharedIDs) { List<BibEntry> entriesToRemove = localEntries.stream() .filter(localEntry -> !sharedIDs.contains(localEntry.getSharedBibEntryData().getSharedID())) .collect(Collectors.toList()); if (!entriesToRemove.isEmpty()) { eventBus.post(new SharedEntriesNotPresentEvent(entriesToRemove)); // remove all non-shared entries without triggering listeners bibDatabase.removeEntries(entriesToRemove, EntriesEventSource.SHARED); } } /** * Synchronizes the shared {@link BibEntry} with the local one. */ @Override public void synchronizeSharedEntry(BibEntry bibEntry) { if (!checkCurrentConnection()) { return; } try { BibDatabaseWriter.applySaveActions(bibEntry, metaData); // perform possibly existing save actions dbmsProcessor.updateEntry(bibEntry); } catch (OfflineLockException exception) { eventBus.post(new UpdateRefusedEvent(bibDatabaseContext, exception.getLocalBibEntry(), exception.getSharedBibEntry())); } catch (SQLException e) { LOGGER.error("SQL Error", e); } } /** * Synchronizes all meta data locally. */ public void synchronizeLocalMetaData() { if (!checkCurrentConnection()) { return; } try { metaData.setEventPropagation(false); MetaDataParser parser = new MetaDataParser(fileMonitor); parser.parse(metaData, dbmsProcessor.getSharedMetaData(), keywordSeparator); metaData.setEventPropagation(true); } catch (ParseException e) { LOGGER.error("Parse error", e); } } /** * Synchronizes all shared meta data. */ private void synchronizeSharedMetaData(MetaData data, GlobalCitationKeyPattern globalCiteKeyPattern) { if (!checkCurrentConnection()) { return; } try { dbmsProcessor.setSharedMetaData(MetaDataSerializer.getSerializedStringMap(data, globalCiteKeyPattern)); } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } } /** * Applies the {@link MetaData} on all local and shared BibEntries. */ public void applyMetaData() { if (!checkCurrentConnection()) { return; } for (BibEntry bibEntry : bibDatabase.getEntries()) { try { // synchronize only if changes were present if (!BibDatabaseWriter.applySaveActions(bibEntry, metaData).isEmpty()) { dbmsProcessor.updateEntry(bibEntry); } } catch (OfflineLockException exception) { eventBus.post(new UpdateRefusedEvent(bibDatabaseContext, exception.getLocalBibEntry(), exception.getSharedBibEntry())); } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } } } /** * Synchronizes the local BibEntries and applies the fetched MetaData on them. */ @Override public void pullChanges() { if (!checkCurrentConnection()) { return; } // First synchronize entry, then synchronize database pullWithLastEntry(); synchronizeLocalDatabase(); synchronizeLocalMetaData(); } /** * Synchronizes local BibEntries only if last entry changes still remain */ public void pullLastEntryChanges() { if (!lastEntryChanged.isEmpty()) { if (!checkCurrentConnection()) { return; } synchronizeLocalMetaData(); pullWithLastEntry(); // Pull changes for the case that there were some synchronizeLocalDatabase(); } } /** * Synchronizes local BibEntries and pulls remaining last entry changes */ private void pullWithLastEntry() { if (!lastEntryChanged.isEmpty() && isPresentLocalBibEntry(lastEntryChanged.get())) { synchronizeSharedEntry(lastEntryChanged.get()); } lastEntryChanged = Optional.empty(); } /** * Checks whether the current SQL connection is valid. In case that the connection is not valid a new {@link * ConnectionLostEvent} is going to be sent. * * @return <code>true</code> if the connection is valid, else <code>false</code>. */ public boolean checkCurrentConnection() { try { boolean isValid = currentConnection.isValid(0); if (!isValid) { LOGGER.warn("Lost SQL connection."); eventBus.post(new ConnectionLostEvent(bibDatabaseContext)); } return isValid; } catch (SQLException e) { LOGGER.error("SQL Error during connection check", e); return false; } } /** * Checks whether the {@link EntriesEventSource} of an {@link EntriesEvent} is crucial for this class. * * @param event An {@link EntriesEvent} * @return <code>true</code> if the event is able to trigger operations in {@link DBMSSynchronizer}, else * <code>false</code> */ public boolean isEventSourceAccepted(EntriesEvent event) { EntriesEventSource eventSource = event.getEntriesEventSource(); return (eventSource == EntriesEventSource.LOCAL) || (eventSource == EntriesEventSource.UNDO); } @Override public void openSharedDatabase(DatabaseConnection connection) throws DatabaseNotSupportedException { this.dbName = connection.getProperties().getDatabase(); this.currentConnection = connection.getConnection(); this.dbmsProcessor = DBMSProcessor.getProcessorInstance(connection); initializeDatabases(); } @Override public void closeSharedDatabase() { // Submit remaining entry changes pullLastEntryChanges(); try { dbmsProcessor.stopNotificationListener(); currentConnection.close(); } catch (SQLException e) { LOGGER.error("SQL Error:", e); } } private boolean isPresentLocalBibEntry(BibEntry bibEntry) { return bibDatabase.getEntries().contains(bibEntry); } @Override public String getDBName() { return dbName; } public DBMSProcessor getDBProcessor() { return dbmsProcessor; } @Override public DatabaseConnectionProperties getConnectionProperties() { return dbmsProcessor.getDBMSConnectionProperties(); } public void setMetaData(MetaData metaData) { this.metaData = metaData; } @Override public void registerListener(Object listener) { eventBus.register(listener); } }
17,206
39.392019
143
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DBMSType.java
package org.jabref.logic.shared; import java.util.Arrays; import java.util.Optional; /** * Enumerates all supported database systems (DBMS) by JabRef. */ public enum DBMSType { POSTGRESQL("PostgreSQL", "org.postgresql.Driver", "jdbc:postgresql://%s:%d/%s", 5432), MYSQL("MySQL", "org.mariadb.jdbc.Driver", "jdbc:mariadb://%s:%d/%s", 3306), ORACLE("Oracle", "oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@%s:%d/%s", 1521); private final String type; private final String driverPath; private final String urlPattern; private final int defaultPort; private DBMSType(String type, String driverPath, String urlPattern, int defaultPort) { this.type = type; this.driverPath = driverPath; this.urlPattern = urlPattern; this.defaultPort = defaultPort; } public static Optional<DBMSType> fromString(String typeName) { return Arrays.stream(DBMSType.values()).filter(dbmsType -> dbmsType.type.equalsIgnoreCase(typeName)).findAny(); } @Override public String toString() { return this.type; } /** * @return Java Class path for establishing JDBC connection. */ public String getDriverClassPath() throws Error { return this.driverPath; } /** * @return prepared connection URL for appropriate system. */ public String getUrl(String host, int port, String database) { return String.format(urlPattern, host, port, database); } /** * Retrieves the port number dependent on the type of the database system. */ public int getDefaultPort() { return this.defaultPort; } }
1,660
28.660714
119
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DatabaseConnection.java
package org.jabref.logic.shared; import java.sql.Connection; public interface DatabaseConnection { DatabaseConnectionProperties getProperties(); Connection getConnection(); }
187
16.090909
49
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DatabaseConnectionProperties.java
package org.jabref.logic.shared; public interface DatabaseConnectionProperties { DBMSType getType(); String getDatabase(); int getPort(); String getHost(); String getUser(); String getPassword(); boolean isValid(); String getKeyStore(); boolean isUseSSL(); boolean isAllowPublicKeyRetrieval(); String getServerTimezone(); }
380
13.111111
47
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DatabaseLocation.java
package org.jabref.logic.shared; import org.jabref.model.database.BibDatabaseContext; /** * This enum represents the location for {@link BibDatabaseContext}. */ public enum DatabaseLocation { LOCAL, SHARED }
220
17.416667
68
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DatabaseNotSupportedException.java
package org.jabref.logic.shared; /** * This exception is thrown in case that the SQL database structure is not compatible with the current shared database * support mechanisms. */ public class DatabaseNotSupportedException extends Exception { public DatabaseNotSupportedException() { super("The structure of the SQL database is not supported."); } }
371
27.615385
118
java
null
jabref-main/src/main/java/org/jabref/logic/shared/DatabaseSynchronizer.java
package org.jabref.logic.shared; import org.jabref.model.entry.BibEntry; public interface DatabaseSynchronizer { String getDBName(); void pullChanges(); void closeSharedDatabase(); void registerListener(Object listener); void openSharedDatabase(DatabaseConnection connection) throws DatabaseNotSupportedException; void synchronizeSharedEntry(BibEntry bibEntry); void synchronizeLocalDatabase(); DatabaseConnectionProperties getConnectionProperties(); }
495
20.565217
96
java
null
jabref-main/src/main/java/org/jabref/logic/shared/MySQLProcessor.java
package org.jabref.logic.shared; import java.sql.SQLException; import java.util.Map; import org.jabref.model.metadata.MetaData; /** * Processes all incoming or outgoing bib data to MySQL Database and manages its structure. */ public class MySQLProcessor extends DBMSProcessor { private Integer VERSION_DB_STRUCT_DEFAULT = -1; private Integer CURRENT_VERSION_DB_STRUCT = 1; public MySQLProcessor(DatabaseConnection connection) { super(connection); } /** * Creates and sets up the needed tables and columns according to the database type. * * @throws SQLException */ @Override public void setUp() throws SQLException { connection.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS `JABREF_ENTRY` (" + "`SHARED_ID` INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, " + "`TYPE` VARCHAR(255) NOT NULL, " + "`VERSION` INT(11) DEFAULT 1)"); connection.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS `JABREF_FIELD` (" + "`ENTRY_SHARED_ID` INT(11) NOT NULL, " + "`NAME` VARCHAR(255) NOT NULL, " + "`VALUE` TEXT DEFAULT NULL, " + "FOREIGN KEY (`ENTRY_SHARED_ID`) REFERENCES `JABREF_ENTRY`(`SHARED_ID`) ON DELETE CASCADE)"); connection.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS `JABREF_METADATA` (" + "`KEY` varchar(255) NOT NULL," + "`VALUE` text NOT NULL)"); Map<String, String> metadata = getSharedMetaData(); if (metadata.get(MetaData.VERSION_DB_STRUCT) != null) { try { VERSION_DB_STRUCT_DEFAULT = Integer.valueOf(metadata.get(MetaData.VERSION_DB_STRUCT)); } catch (Exception e) { LOGGER.warn("[VERSION_DB_STRUCT_DEFAULT] not Integer!"); } } else { LOGGER.warn("[VERSION_DB_STRUCT_DEFAULT] not Exist!"); } if (VERSION_DB_STRUCT_DEFAULT < CURRENT_VERSION_DB_STRUCT) { // We can to migrate from old table in new table if (CURRENT_VERSION_DB_STRUCT == 1 && checkTableAvailability("ENTRY", "FIELD", "METADATA")) { LOGGER.info("Migrating from VersionDBStructure == 0"); connection.createStatement().executeUpdate("INSERT INTO " + escape_Table("ENTRY") + " SELECT * FROM `ENTRY`"); connection.createStatement().executeUpdate("INSERT INTO " + escape_Table("FIELD") + " SELECT * FROM `FIELD`"); connection.createStatement().executeUpdate("INSERT INTO " + escape_Table("METADATA") + " SELECT * FROM `METADATA`"); metadata = getSharedMetaData(); } metadata.put(MetaData.VERSION_DB_STRUCT, CURRENT_VERSION_DB_STRUCT.toString()); setSharedMetaData(metadata); } } @Override String escape(String expression) { return "`" + expression + "`"; } @Override String escape_Table(String expression) { return escape("JABREF_" + expression); } @Override Integer getCURRENT_VERSION_DB_STRUCT() { return CURRENT_VERSION_DB_STRUCT; } }
3,335
37.344828
132
java
null
jabref-main/src/main/java/org/jabref/logic/shared/OracleProcessor.java
package org.jabref.logic.shared; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; import org.jabref.logic.shared.listener.OracleNotificationListener; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.metadata.MetaData; import oracle.jdbc.OracleConnection; import oracle.jdbc.OracleStatement; import oracle.jdbc.dcn.DatabaseChangeRegistration; /** * Processes all incoming or outgoing bib data to Oracle database and manages its structure. */ public class OracleProcessor extends DBMSProcessor { private OracleConnection oracleConnection; private OracleNotificationListener listener; private DatabaseChangeRegistration databaseChangeRegistration; private Integer VERSION_DB_STRUCT_DEFAULT = -1; private Integer CURRENT_VERSION_DB_STRUCT = 0; public OracleProcessor(DatabaseConnection connection) { super(connection); } /** * Creates and sets up the needed tables and columns according to the database type. * * @throws SQLException */ @Override public void setUp() throws SQLException { connection.createStatement().executeUpdate( "CREATE TABLE \"ENTRY\" (" + "\"SHARED_ID\" NUMBER NOT NULL, " + "\"TYPE\" VARCHAR2(255) NULL, " + "\"VERSION\" NUMBER DEFAULT 1, " + "CONSTRAINT \"ENTRY_PK\" PRIMARY KEY (\"SHARED_ID\"))"); connection.createStatement().executeUpdate("CREATE SEQUENCE \"ENTRY_SEQ\""); connection.createStatement().executeUpdate("CREATE TRIGGER \"ENTRY_T\" BEFORE INSERT ON \"ENTRY\" " + "FOR EACH ROW BEGIN SELECT \"ENTRY_SEQ\".NEXTVAL INTO :NEW.shared_id FROM DUAL; END;"); connection.createStatement().executeUpdate( "CREATE TABLE \"FIELD\" (" + "\"ENTRY_SHARED_ID\" NUMBER NOT NULL, " + "\"NAME\" VARCHAR2(255) NOT NULL, " + "\"VALUE\" CLOB NULL, " + "CONSTRAINT \"ENTRY_SHARED_ID_FK\" FOREIGN KEY (\"ENTRY_SHARED_ID\") " + "REFERENCES \"ENTRY\"(\"SHARED_ID\") ON DELETE CASCADE)"); connection.createStatement().executeUpdate( "CREATE TABLE \"METADATA\" (" + "\"KEY\" VARCHAR2(255) NULL," + "\"VALUE\" CLOB NOT NULL)"); Map<String, String> metadata = getSharedMetaData(); if (metadata.get(MetaData.VERSION_DB_STRUCT) != null) { try { VERSION_DB_STRUCT_DEFAULT = Integer.valueOf(metadata.get(MetaData.VERSION_DB_STRUCT)); } catch (Exception e) { LOGGER.warn("[VERSION_DB_STRUCT_DEFAULT] not Integer!"); } } else { LOGGER.warn("[VERSION_DB_STRUCT_DEFAULT] not Exist!"); } if (VERSION_DB_STRUCT_DEFAULT < CURRENT_VERSION_DB_STRUCT) { // We can to migrate from old table in new table metadata.put(MetaData.VERSION_DB_STRUCT, CURRENT_VERSION_DB_STRUCT.toString()); setSharedMetaData(metadata); } } @Override String escape(String expression) { return expression; } @Override String escape_Table(String expression) { return escape(expression); } @Override Integer getCURRENT_VERSION_DB_STRUCT() { return CURRENT_VERSION_DB_STRUCT; } @Override public void startNotificationListener(DBMSSynchronizer dbmsSynchronizer) { this.listener = new OracleNotificationListener(dbmsSynchronizer); try { oracleConnection = (OracleConnection) connection; Properties properties = new Properties(); properties.setProperty(OracleConnection.DCN_NOTIFY_ROWIDS, "true"); properties.setProperty(OracleConnection.DCN_QUERY_CHANGE_NOTIFICATION, "true"); databaseChangeRegistration = oracleConnection.registerDatabaseChangeNotification(properties); databaseChangeRegistration.addListener(listener); try (Statement statement = oracleConnection.createStatement()) { ((OracleStatement) statement).setDatabaseChangeRegistration(databaseChangeRegistration); StringBuilder selectQuery = new StringBuilder() .append("SELECT 1 FROM ") .append(escape_Table("ENTRY")) .append(", ") .append(escape_Table("METADATA")); // this execution registers all tables mentioned in selectQuery statement.executeQuery(selectQuery.toString()); } } catch (SQLException e) { LOGGER.error("SQL Error during starting the notification listener", e); } } @Override protected void insertIntoEntryTable(List<BibEntry> entries) { try { for (BibEntry entry : entries) { String insertIntoEntryQuery = "INSERT INTO " + escape_Table("ENTRY") + "(" + escape("TYPE") + ") VALUES(?)"; try (PreparedStatement preparedEntryStatement = connection.prepareStatement(insertIntoEntryQuery, new String[]{"SHARED_ID"})) { preparedEntryStatement.setString(1, entry.getType().getName()); preparedEntryStatement.executeUpdate(); try (ResultSet generatedKeys = preparedEntryStatement.getGeneratedKeys()) { if (generatedKeys.next()) { entry.getSharedBibEntryData().setSharedID(generatedKeys.getInt(1)); // set generated ID locally } } } } } catch (SQLException e) { LOGGER.error("SQL Error during entry insertion", e); } } @Override protected void insertIntoFieldTable(List<BibEntry> bibEntries) { try { // Inserting into FIELD table // Coerce to ArrayList in order to use List.get() List<List<Field>> fields = bibEntries.stream().map(entry -> new ArrayList<>(entry.getFields())) .collect(Collectors.toList()); StringBuilder insertFieldQuery = new StringBuilder() .append("INSERT ALL"); int numFields = 0; for (List<Field> entryFields : fields) { numFields += entryFields.size(); } for (int i = 0; i < numFields; i++) { insertFieldQuery.append(" INTO ") .append(escape_Table("FIELD")) .append(" (") .append(escape("ENTRY_SHARED_ID")) .append(", ") .append(escape("NAME")) .append(", ") .append(escape("VALUE")) .append(") VALUES (?, ?, ?)"); } insertFieldQuery.append(" SELECT * FROM DUAL"); try (PreparedStatement preparedFieldStatement = connection.prepareStatement(insertFieldQuery.toString())) { int fieldsCompleted = 0; for (int entryIndex = 0; entryIndex < fields.size(); entryIndex++) { for (int entryFieldsIndex = 0; entryFieldsIndex < fields.get(entryIndex).size(); entryFieldsIndex++) { // columnIndex starts with 1 preparedFieldStatement.setInt((3 * fieldsCompleted) + 1, bibEntries.get(entryIndex).getSharedBibEntryData().getSharedID()); preparedFieldStatement.setString((3 * fieldsCompleted) + 2, fields.get(entryIndex).get(entryFieldsIndex).getName()); preparedFieldStatement.setString((3 * fieldsCompleted) + 3, bibEntries.get(entryIndex).getField(fields.get(entryIndex).get(entryFieldsIndex)).get()); fieldsCompleted += 1; } } preparedFieldStatement.executeUpdate(); } } catch (SQLException e) { LOGGER.error("SQL Error during field insertion", e); } } @Override public void stopNotificationListener() { try { oracleConnection.unregisterDatabaseChangeNotification(databaseChangeRegistration); oracleConnection.close(); } catch (SQLException e) { LOGGER.error("SQL Error during stopping the notification listener", e); } } @Override public void notifyClients() { // Do nothing because Oracle triggers notifications automatically. } }
9,172
40.31982
173
java
null
jabref-main/src/main/java/org/jabref/logic/shared/PostgreSQLProcessor.java
package org.jabref.logic.shared; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.Map; import org.jabref.gui.JabRefExecutorService; import org.jabref.logic.shared.listener.PostgresSQLNotificationListener; import org.jabref.model.entry.BibEntry; import org.jabref.model.metadata.MetaData; import org.postgresql.PGConnection; /** * Processes all incoming or outgoing bib data to PostgreSQL database and manages its structure. */ public class PostgreSQLProcessor extends DBMSProcessor { private PostgresSQLNotificationListener listener; private Integer VERSION_DB_STRUCT_DEFAULT = -1; private Integer CURRENT_VERSION_DB_STRUCT = 1; public PostgreSQLProcessor(DatabaseConnection connection) { super(connection); } /** * Creates and sets up the needed tables and columns according to the database type. * * @throws SQLException */ @Override public void setUp() throws SQLException { if (CURRENT_VERSION_DB_STRUCT == 1 && checkTableAvailability("ENTRY", "FIELD", "METADATA")) { // checkTableAvailability does not distinguish if same table name exists in different schemas // VERSION_DB_STRUCT_DEFAULT must be forced VERSION_DB_STRUCT_DEFAULT = 0; } connection.createStatement().executeUpdate("CREATE SCHEMA IF NOT EXISTS jabref"); connection.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + escape_Table("ENTRY") + " (" + "\"SHARED_ID\" SERIAL PRIMARY KEY, " + "\"TYPE\" VARCHAR, " + "\"VERSION\" INTEGER DEFAULT 1)"); connection.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + escape_Table("FIELD") + " (" + "\"ENTRY_SHARED_ID\" INTEGER REFERENCES " + escape_Table("ENTRY") + "(\"SHARED_ID\") ON DELETE CASCADE, " + "\"NAME\" VARCHAR, " + "\"VALUE\" TEXT)"); connection.createStatement().executeUpdate( "CREATE TABLE IF NOT EXISTS " + escape_Table("METADATA") + " (" + "\"KEY\" VARCHAR," + "\"VALUE\" TEXT)"); Map<String, String> metadata = getSharedMetaData(); if (metadata.get(MetaData.VERSION_DB_STRUCT) != null) { try { VERSION_DB_STRUCT_DEFAULT = Integer.valueOf(metadata.get(MetaData.VERSION_DB_STRUCT)); } catch (Exception e) { LOGGER.warn("[VERSION_DB_STRUCT_DEFAULT] not Integer!"); } } else { LOGGER.warn("[VERSION_DB_STRUCT_DEFAULT] not Exist!"); } if (VERSION_DB_STRUCT_DEFAULT < CURRENT_VERSION_DB_STRUCT) { // We can to migrate from old table in new table if (VERSION_DB_STRUCT_DEFAULT == 0 && CURRENT_VERSION_DB_STRUCT == 1) { LOGGER.info("Migrating from VersionDBStructure == 0"); connection.createStatement().executeUpdate("INSERT INTO " + escape_Table("ENTRY") + " SELECT * FROM \"ENTRY\""); connection.createStatement().executeUpdate("INSERT INTO " + escape_Table("FIELD") + " SELECT * FROM \"FIELD\""); connection.createStatement().executeUpdate("INSERT INTO " + escape_Table("METADATA") + " SELECT * FROM \"METADATA\""); connection.createStatement().execute("SELECT setval(\'jabref.\"ENTRY_SHARED_ID_seq\"\', (select max(\"SHARED_ID\") from jabref.\"ENTRY\"))"); metadata = getSharedMetaData(); } metadata.put(MetaData.VERSION_DB_STRUCT, CURRENT_VERSION_DB_STRUCT.toString()); setSharedMetaData(metadata); } } @Override protected void insertIntoEntryTable(List<BibEntry> bibEntries) { StringBuilder insertIntoEntryQuery = new StringBuilder() .append("INSERT INTO ") .append(escape_Table("ENTRY")) .append("(") .append(escape("TYPE")) .append(") VALUES(?)"); // Number of commas is bibEntries.size() - 1 for (int i = 0; i < bibEntries.size() - 1; i++) { insertIntoEntryQuery.append(", (?)"); } try (PreparedStatement preparedEntryStatement = connection.prepareStatement(insertIntoEntryQuery.toString(), Statement.RETURN_GENERATED_KEYS)) { for (int i = 0; i < bibEntries.size(); i++) { preparedEntryStatement.setString(i + 1, bibEntries.get(i).getType().getName()); } preparedEntryStatement.executeUpdate(); try (ResultSet generatedKeys = preparedEntryStatement.getGeneratedKeys()) { // The following assumes that we get the generated keys in the order the entries were inserted // This should be the case for (BibEntry bibEntry : bibEntries) { generatedKeys.next(); bibEntry.getSharedBibEntryData().setSharedID(generatedKeys.getInt(1)); } if (generatedKeys.next()) { LOGGER.error("Some shared IDs left unassigned"); } } } catch (SQLException e) { LOGGER.error("SQL Error during entry insertion", e); } } @Override String escape(String expression) { return "\"" + expression + "\""; } @Override String escape_Table(String expression) { return "jabref." + escape(expression); } @Override Integer getCURRENT_VERSION_DB_STRUCT() { return CURRENT_VERSION_DB_STRUCT; } @Override public void startNotificationListener(DBMSSynchronizer dbmsSynchronizer) { // Disable cleanup output of ThreadedHousekeeper // Logger.getLogger(ThreadedHousekeeper.class.getName()).setLevel(Level.SEVERE); try { connection.createStatement().execute("LISTEN jabrefLiveUpdate"); // Do not use `new PostgresSQLNotificationListener(...)` as the object has to exist continuously! // Otherwise, the listener is going to be deleted by Java's garbage collector. PGConnection pgConnection = connection.unwrap(PGConnection.class); listener = new PostgresSQLNotificationListener(dbmsSynchronizer, pgConnection); JabRefExecutorService.INSTANCE.execute(listener); } catch (SQLException e) { LOGGER.error("SQL Error during starting the notification listener", e); } } @Override public void stopNotificationListener() { try { listener.stop(); connection.close(); } catch (SQLException e) { LOGGER.error("SQL Error during stopping the notification listener", e); } } @Override public void notifyClients() { try { connection.createStatement().execute("NOTIFY jabrefLiveUpdate, '" + PROCESSOR_ID + "';"); } catch (SQLException e) { LOGGER.error("SQL Error during client notification", e); } } }
7,254
39.988701
157
java
null
jabref-main/src/main/java/org/jabref/logic/shared/event/ConnectionLostEvent.java
package org.jabref.logic.shared.event; import org.jabref.model.database.BibDatabaseContext; /** * A new {@link ConnectionLostEvent} is fired, when the connection to the shared database gets lost. */ public class ConnectionLostEvent { private final BibDatabaseContext bibDatabaseContext; /** * @param bibDatabaseContext Affected {@link BibDatabaseContext} */ public ConnectionLostEvent(BibDatabaseContext bibDatabaseContext) { this.bibDatabaseContext = bibDatabaseContext; } public BibDatabaseContext getBibDatabaseContext() { return this.bibDatabaseContext; } }
619
25.956522
100
java
null
jabref-main/src/main/java/org/jabref/logic/shared/event/SharedEntriesNotPresentEvent.java
package org.jabref.logic.shared.event; import java.util.List; import org.jabref.model.entry.BibEntry; /** * This event is fired when the user tries to push changes of one or more obsolete * {@link BibEntry} to the server. */ public class SharedEntriesNotPresentEvent { private final List<BibEntry> bibEntries; /** * @param bibEntries Affected {@link BibEntry} */ public SharedEntriesNotPresentEvent(List<BibEntry> bibEntries) { this.bibEntries = bibEntries; } public List<BibEntry> getBibEntries() { return this.bibEntries; } }
587
21.615385
82
java
null
jabref-main/src/main/java/org/jabref/logic/shared/event/UpdateRefusedEvent.java
package org.jabref.logic.shared.event; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; /** * A new {@link UpdateRefusedEvent} is fired, when the user tries to push changes of an obsolete {@link BibEntry} to the server. */ public class UpdateRefusedEvent { private final BibDatabaseContext bibDatabaseContext; private final BibEntry localBibEntry; private final BibEntry sharedBibEntry; /** * @param bibDatabaseContext Affected {@link BibDatabaseContext} * @param localBibEntry Affected {@link BibEntry} */ public UpdateRefusedEvent(BibDatabaseContext bibDatabaseContext, BibEntry localBibEntry, BibEntry sharedBibEntry) { this.bibDatabaseContext = bibDatabaseContext; this.localBibEntry = localBibEntry; this.sharedBibEntry = sharedBibEntry; } public BibDatabaseContext getBibDatabaseContext() { return this.bibDatabaseContext; } public BibEntry getLocalBibEntry() { return localBibEntry; } public BibEntry getSharedBibEntry() { return sharedBibEntry; } }
1,126
29.459459
128
java
null
jabref-main/src/main/java/org/jabref/logic/shared/exception/InvalidDBMSConnectionPropertiesException.java
package org.jabref.logic.shared.exception; import org.jabref.logic.shared.DBMSConnectionProperties; /** * This exception is thrown in case that {@link DBMSConnectionProperties} does not provide all data needed for a connection. */ public class InvalidDBMSConnectionPropertiesException extends Exception { public InvalidDBMSConnectionPropertiesException() { super("Required connection details not present."); } }
433
30
124
java
null
jabref-main/src/main/java/org/jabref/logic/shared/exception/NotASharedDatabaseException.java
package org.jabref.logic.shared.exception; /** * This exception is thrown when a shared database is required, but it actually isn't one. */ public class NotASharedDatabaseException extends Exception { public NotASharedDatabaseException() { super("Required database is not shared."); } }
307
24.666667
90
java
null
jabref-main/src/main/java/org/jabref/logic/shared/exception/OfflineLockException.java
package org.jabref.logic.shared.exception; import org.jabref.model.entry.BibEntry; /** * This exception is thrown if a BibEntry with smaller version number is going to be used for an update on the shared side. * The principle of optimistic offline lock forbids updating with obsolete objects. */ public class OfflineLockException extends Exception { private final BibEntry localBibEntry; private final BibEntry sharedBibEntry; public OfflineLockException(BibEntry localBibEntry, BibEntry sharedBibEntry) { super("Local BibEntry data is not up-to-date."); this.localBibEntry = localBibEntry; this.sharedBibEntry = sharedBibEntry; } public BibEntry getLocalBibEntry() { return localBibEntry; } public BibEntry getSharedBibEntry() { return sharedBibEntry; } }
838
28.964286
123
java
null
jabref-main/src/main/java/org/jabref/logic/shared/exception/SharedEntryNotPresentException.java
package org.jabref.logic.shared.exception; import org.jabref.model.entry.BibEntry; /** * This exception is thrown if a BibEntry is going to be updated while it does not exist on the shared side. */ public class SharedEntryNotPresentException extends Exception { private final BibEntry nonPresentBibEntry; public SharedEntryNotPresentException(BibEntry nonPresentbibEntry) { super("Required BibEntry is not present on shared database."); this.nonPresentBibEntry = nonPresentbibEntry; } public BibEntry getNonPresentBibEntry() { return this.nonPresentBibEntry; } }
614
28.285714
108
java
null
jabref-main/src/main/java/org/jabref/logic/shared/listener/OracleNotificationListener.java
package org.jabref.logic.shared.listener; import org.jabref.logic.shared.DBMSSynchronizer; import oracle.jdbc.dcn.DatabaseChangeEvent; import oracle.jdbc.dcn.DatabaseChangeListener; /** * A listener for Oracle database notifications. */ public class OracleNotificationListener implements DatabaseChangeListener { private final DBMSSynchronizer dbmsSynchronizer; public OracleNotificationListener(DBMSSynchronizer dbmsSynchronizer) { this.dbmsSynchronizer = dbmsSynchronizer; } @Override public void onDatabaseChangeNotification(DatabaseChangeEvent event) { dbmsSynchronizer.pullChanges(); } }
641
25.75
75
java
null
jabref-main/src/main/java/org/jabref/logic/shared/listener/PostgresSQLNotificationListener.java
package org.jabref.logic.shared.listener; import java.sql.SQLException; import org.jabref.logic.shared.DBMSProcessor; import org.jabref.logic.shared.DBMSSynchronizer; import org.postgresql.PGConnection; import org.postgresql.PGNotification; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A listener for PostgreSQL database notifications. */ public class PostgresSQLNotificationListener implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(PostgresSQLNotificationListener.class); private final DBMSSynchronizer dbmsSynchronizer; private final PGConnection pgConnection; private volatile boolean stop; public PostgresSQLNotificationListener(DBMSSynchronizer dbmsSynchronizer, PGConnection pgConnection) { this.dbmsSynchronizer = dbmsSynchronizer; this.pgConnection = pgConnection; } @Override public void run() { stop = false; try { // noinspection InfiniteLoopStatement while (!stop) { PGNotification notifications[] = pgConnection.getNotifications(); if (notifications != null) { for (PGNotification notification : notifications) { if (!notification.getName().equals(DBMSProcessor.PROCESSOR_ID)) { dbmsSynchronizer.pullChanges(); } } } // Wait a while before checking again for new notifications Thread.sleep(500); } } catch (SQLException | InterruptedException exception) { LOGGER.error("Error while listening for updates to PostgresSQL", exception); } } public void stop() { stop = true; } }
1,797
30.54386
106
java
null
jabref-main/src/main/java/org/jabref/logic/shared/prefs/SharedDatabasePreferences.java
package org.jabref.logic.shared.prefs; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Optional; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import org.jabref.logic.shared.DatabaseConnectionProperties; import org.jabref.logic.shared.security.Password; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SharedDatabasePreferences { private static final Logger LOGGER = LoggerFactory.getLogger(SharedDatabasePreferences.class); private static final String DEFAULT_NODE = "default"; private static final String PREFERENCES_PATH_NAME = "/org/jabref-shared"; private static final String SHARED_DATABASE_TYPE = "sharedDatabaseType"; private static final String SHARED_DATABASE_HOST = "sharedDatabaseHost"; private static final String SHARED_DATABASE_PORT = "sharedDatabasePort"; private static final String SHARED_DATABASE_NAME = "sharedDatabaseName"; private static final String SHARED_DATABASE_USER = "sharedDatabaseUser"; private static final String SHARED_DATABASE_PASSWORD = "sharedDatabasePassword"; private static final String SHARED_DATABASE_FOLDER = "sharedDatabaseFolder"; private static final String SHARED_DATABASE_AUTOSAVE = "sharedDatabaseAutosave"; private static final String SHARED_DATABASE_REMEMBER_PASSWORD = "sharedDatabaseRememberPassword"; private static final String SHARED_DATABASE_USE_SSL = "sharedDatabaseUseSSL"; private static final String SHARED_DATABASE_KEYSTORE_FILE = "sharedDatabaseKeyStoreFile"; private static final String SHARED_DATABASE_SERVER_TIMEZONE = "sharedDatabaseServerTimezone"; // This {@link Preferences} is used only for things which should not appear in real JabRefPreferences due to security reasons. private final Preferences internalPrefs; public SharedDatabasePreferences() { this(DEFAULT_NODE); } public SharedDatabasePreferences(String sharedDatabaseID) { internalPrefs = Preferences.userRoot().node(PREFERENCES_PATH_NAME).node(sharedDatabaseID); } public Optional<String> getType() { return getOptionalValue(SHARED_DATABASE_TYPE); } public Optional<String> getHost() { return getOptionalValue(SHARED_DATABASE_HOST); } public Optional<String> getPort() { return getOptionalValue(SHARED_DATABASE_PORT); } public Optional<String> getName() { return getOptionalValue(SHARED_DATABASE_NAME); } public Optional<String> getUser() { return getOptionalValue(SHARED_DATABASE_USER); } public Optional<String> getPassword() { return getOptionalValue(SHARED_DATABASE_PASSWORD); } public Optional<String> getKeyStoreFile() { return getOptionalValue(SHARED_DATABASE_KEYSTORE_FILE); } public Optional<String> getServerTimezone() { return getOptionalValue(SHARED_DATABASE_SERVER_TIMEZONE); } public boolean getRememberPassword() { return internalPrefs.getBoolean(SHARED_DATABASE_REMEMBER_PASSWORD, false); } public Optional<String> getFolder() { return getOptionalValue(SHARED_DATABASE_FOLDER); } public boolean getAutosave() { return internalPrefs.getBoolean(SHARED_DATABASE_AUTOSAVE, false); } public boolean isUseSSL() { return internalPrefs.getBoolean(SHARED_DATABASE_USE_SSL, false); } public void setType(String type) { internalPrefs.put(SHARED_DATABASE_TYPE, type); } public void setHost(String host) { internalPrefs.put(SHARED_DATABASE_HOST, host); } public void setPort(String port) { internalPrefs.put(SHARED_DATABASE_PORT, port); } public void setName(String name) { internalPrefs.put(SHARED_DATABASE_NAME, name); } public void setUser(String user) { internalPrefs.put(SHARED_DATABASE_USER, user); } public void setPassword(String password) { internalPrefs.put(SHARED_DATABASE_PASSWORD, password); } public void setRememberPassword(boolean rememberPassword) { internalPrefs.putBoolean(SHARED_DATABASE_REMEMBER_PASSWORD, rememberPassword); } public void setFolder(String folder) { internalPrefs.put(SHARED_DATABASE_FOLDER, folder); } public void setAutosave(boolean autosave) { internalPrefs.putBoolean(SHARED_DATABASE_AUTOSAVE, autosave); } public void setUseSSL(boolean useSSL) { internalPrefs.putBoolean(SHARED_DATABASE_USE_SSL, useSSL); } public void setKeystoreFile(String keystoreFile) { internalPrefs.put(SHARED_DATABASE_KEYSTORE_FILE, keystoreFile); } public void setServerTimezone(String serverTimezone) { internalPrefs.put(SHARED_DATABASE_SERVER_TIMEZONE, serverTimezone); } public void clearPassword() { internalPrefs.remove(SHARED_DATABASE_PASSWORD); } public void clear() throws BackingStoreException { internalPrefs.clear(); } private Optional<String> getOptionalValue(String key) { return Optional.ofNullable(internalPrefs.get(key, null)); } public static void clearAll() throws BackingStoreException { Preferences.userRoot().node(PREFERENCES_PATH_NAME).clear(); } public void putAllDBMSConnectionProperties(DatabaseConnectionProperties properties) { assert (properties.isValid()); setType(properties.getType().toString()); setHost(properties.getHost()); setPort(String.valueOf(properties.getPort())); setName(properties.getDatabase()); setUser(properties.getUser()); setUseSSL(properties.isUseSSL()); setKeystoreFile(properties.getKeyStore()); setServerTimezone(properties.getServerTimezone()); try { setPassword(new Password(properties.getPassword().toCharArray(), properties.getUser()).encrypt()); } catch (GeneralSecurityException | UnsupportedEncodingException e) { LOGGER.error("Could not store the password due to encryption problems.", e); } } }
6,146
33.728814
130
java
null
jabref-main/src/main/java/org/jabref/logic/shared/security/Password.java
package org.jabref.logic.shared.security; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * {@link Password} contains methods which are useful to encrypt and decrypt passwords using symetric algorithms. */ public class Password { private final byte[] phrase; private final Cipher cipher; private final SecretKeySpec secretKey; private final IvParameterSpec ivSpec; /** * @param phrase Phrase which should be encrypted or decrypted * @param key Key which is used to improve symmetric encryption */ public Password(char[] phrase, String key) throws NoSuchAlgorithmException, NoSuchPaddingException { this(new String(phrase), key); } public Password(String phrase, String key) throws NoSuchAlgorithmException, NoSuchPaddingException { this.phrase = phrase.getBytes(); this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); this.secretKey = new SecretKeySpec(get128BitHash(key.getBytes()), "AES"); this.ivSpec = new IvParameterSpec("ThisIsA128BitKey".getBytes()); } /** * Encrypts the set phrase/password with a symmetric encryption algorithm. * * @return Encrypted phrase/password */ public String encrypt() throws GeneralSecurityException, UnsupportedEncodingException { cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); return new String(Base64.getEncoder().encode(cipher.doFinal(phrase)), StandardCharsets.UTF_8); } /** * Decrypts the set phrase/password which was encrypted via {@link Password#encrypt()}. * * @return Decrypted phrase/password */ public String decrypt() throws GeneralSecurityException, UnsupportedEncodingException { cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); return new String(cipher.doFinal(Base64.getDecoder().decode(phrase)), StandardCharsets.UTF_8); } /** * Returns a 128 bit hash using SHA-256. */ private byte[] get128BitHash(byte[] byteArrayToHash) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(byteArrayToHash); return Arrays.copyOf(messageDigest.digest(), 16); // return 128 bit } }
2,629
36.571429
113
java
null
jabref-main/src/main/java/org/jabref/logic/texparser/DefaultLatexParser.java
package org.jabref.logic.texparser; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.Reader; import java.io.UncheckedIOException; import java.nio.channels.ClosedChannelException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.model.texparser.LatexParserResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultLatexParser implements LatexParser { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLatexParser.class); private static final String TEX_EXT = ".tex"; private static final String BIB_EXT = ".bib"; /** * It is allowed to add new cite commands for pattern matching. Some valid examples: "citep", "[cC]ite", and * "[cC]ite(author|title|year|t|p)?". */ private static final String[] CITE_COMMANDS = { "[cC]ite(alt|alp|author|authorfull|date|num|p|t|text|title|url|year|yearpar)?", "([aA]|[aA]uto|fnote|foot|footfull|full|no|[nN]ote|[pP]aren|[pP]note|[tT]ext|[sS]mart|super)cite([s*]?)", "footcitetext", "(block|text)cquote" }; private static final String CITE_GROUP = "key"; private static final Pattern CITE_PATTERN = Pattern.compile( String.format("\\\\(%s)\\*?(?:\\[(?:[^\\]]*)\\]){0,2}\\{(?<%s>[^\\}]*)\\}(?:\\{[^\\}]*\\})?", String.join("|", CITE_COMMANDS), CITE_GROUP)); private static final String BIBLIOGRAPHY_GROUP = "bib"; private static final Pattern BIBLIOGRAPHY_PATTERN = Pattern.compile( String.format("\\\\(?:bibliography|addbibresource)\\{(?<%s>[^\\}]*)\\}", BIBLIOGRAPHY_GROUP)); private static final String INCLUDE_GROUP = "file"; private static final Pattern INCLUDE_PATTERN = Pattern.compile( String.format("\\\\(?:include|input)\\{(?<%s>[^\\}]*)\\}", INCLUDE_GROUP)); private final LatexParserResult latexParserResult; public DefaultLatexParser() { this.latexParserResult = new LatexParserResult(); } public LatexParserResult getLatexParserResult() { return latexParserResult; } @Override public LatexParserResult parse(String citeString) { matchCitation(Path.of(""), 1, citeString); return latexParserResult; } @Override public LatexParserResult parse(Path latexFile) { return parse(Collections.singletonList(latexFile)); } @Override public LatexParserResult parse(List<Path> latexFiles) { latexParserResult.addFiles(latexFiles); List<Path> referencedFiles = new ArrayList<>(); for (Path file : latexFiles) { if (!file.toFile().exists()) { LOGGER.error(String.format("File does not exist: %s", file)); continue; } try ( InputStream inputStream = Files.newInputStream(file); Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); LineNumberReader lineNumberReader = new LineNumberReader(reader)) { for (String line = lineNumberReader.readLine(); line != null; line = lineNumberReader.readLine()) { // Skip comments and blank lines. if (line.trim().isEmpty() || line.trim().charAt(0) == '%') { continue; } matchCitation(file, lineNumberReader.getLineNumber(), line); matchBibFile(file, line); matchNestedFile(file, latexFiles, referencedFiles, line); } } catch (ClosedChannelException e) { // User changed the underlying LaTeX file // We ignore this error and just continue with parsing LOGGER.info("Parsing has been interrupted"); } catch (IOException | UncheckedIOException e) { // Some weired error during reading // We ignore this error and just continue with parsing LOGGER.info("Error while parsing file {}", file, e); } } // Parse all files referenced by TEX files, recursively. if (!referencedFiles.isEmpty()) { // modifies class variable latexParserResult parse(referencedFiles); } return latexParserResult; } /** * Find cites along a specific line and store them. */ private void matchCitation(Path file, int lineNumber, String line) { Matcher citeMatch = CITE_PATTERN.matcher(line); while (citeMatch.find()) { for (String key : citeMatch.group(CITE_GROUP).split(",")) { latexParserResult.addKey(key.trim(), file, lineNumber, citeMatch.start(), citeMatch.end(), line); } } } /** * Find BIB files along a specific line and store them. */ private void matchBibFile(Path file, String line) { Matcher bibliographyMatch = BIBLIOGRAPHY_PATTERN.matcher(line); while (bibliographyMatch.find()) { for (String bibString : bibliographyMatch.group(BIBLIOGRAPHY_GROUP).split(",")) { bibString = bibString.trim(); Path bibFile = file.getParent().resolve( bibString.endsWith(BIB_EXT) ? bibString : String.format("%s%s", bibString, BIB_EXT)); if (bibFile.toFile().exists()) { latexParserResult.addBibFile(file, bibFile); } } } } /** * Find inputs and includes along a specific line and store them for parsing later. */ private void matchNestedFile(Path file, List<Path> texFiles, List<Path> referencedFiles, String line) { Matcher includeMatch = INCLUDE_PATTERN.matcher(line); while (includeMatch.find()) { String include = includeMatch.group(INCLUDE_GROUP); Path nestedFile = file.getParent().resolve( include.endsWith(TEX_EXT) ? include : String.format("%s%s", include, TEX_EXT)); if (nestedFile.toFile().exists() && !texFiles.contains(nestedFile)) { referencedFiles.add(nestedFile); } } } }
6,601
37.608187
117
java
null
jabref-main/src/main/java/org/jabref/logic/texparser/LatexParser.java
package org.jabref.logic.texparser; import java.nio.file.Path; import java.util.List; import org.jabref.model.texparser.LatexParserResult; /** * Parses a LaTeX file */ public interface LatexParser { /** * For testing purposes. * * @param citeString String that contains a citation * @return a LatexParserResult, where Path is "" and lineNumber is 1 */ LatexParserResult parse(String citeString); /** * Parse a single LaTeX file. * * @param latexFile Path to a LaTeX file * @return a LatexParserResult, which contains all data related to the bibliographic entries */ LatexParserResult parse(Path latexFile); /** * Parse a list of LaTeX files. * * @param latexFiles List of Path objects linked to a LaTeX file * @return a LatexParserResult, which contains all data related to the bibliographic entries */ LatexParserResult parse(List<Path> latexFiles); }
960
24.972973
96
java
null
jabref-main/src/main/java/org/jabref/logic/texparser/TexBibEntriesResolver.java
package org.jabref.logic.texparser; import java.io.IOException; import java.nio.file.Path; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.OpenDatabase; import org.jabref.logic.importer.ParserResult; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.texparser.Citation; import org.jabref.model.texparser.LatexBibEntriesResolverResult; import org.jabref.model.texparser.LatexParserResult; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.LibraryPreferences; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TexBibEntriesResolver { private static final Logger LOGGER = LoggerFactory.getLogger(TexBibEntriesResolver.class); private final BibDatabase masterDatabase; private final LibraryPreferences libraryPreferences; private final ImportFormatPreferences importFormatPreferences; private final FileUpdateMonitor fileMonitor; public TexBibEntriesResolver(BibDatabase masterDatabase, LibraryPreferences libraryPreferences, ImportFormatPreferences importFormatPreferences, FileUpdateMonitor fileMonitor) { this.masterDatabase = masterDatabase; this.libraryPreferences = libraryPreferences; this.importFormatPreferences = importFormatPreferences; this.fileMonitor = fileMonitor; } /** * Resolve all BibTeX entries and check if they are in the given database. */ public LatexBibEntriesResolverResult resolve(LatexParserResult latexParserResult) { LatexBibEntriesResolverResult resolverResult = new LatexBibEntriesResolverResult(latexParserResult); // Preload databases from BIB files. Map<Path, BibDatabase> bibDatabases = resolverResult.getBibFiles().values().stream().distinct().collect(Collectors.toMap( Function.identity(), path -> { try { return OpenDatabase.loadDatabase(path, importFormatPreferences, fileMonitor).getDatabase(); } catch (IOException e) { LOGGER.error("Error opening file '{}'", path, e); return ParserResult.fromError(e).getDatabase(); } })); // Get all pairs Entry<String entryKey, Citation>. Stream<Map.Entry<String, Citation>> citationsStream = latexParserResult.getCitations().entries().stream().distinct(); Set<BibEntry> newEntries = citationsStream.flatMap(mapEntry -> apply(mapEntry, latexParserResult, bibDatabases)).collect(Collectors.toSet()); // Add all new entries to the newEntries set. resolverResult.getNewEntries().addAll(newEntries); return resolverResult; } private Stream<? extends BibEntry> apply(Map.Entry<String, Citation> mapEntry, LatexParserResult latexParserResult, Map<Path, BibDatabase> bibDatabases) { return latexParserResult.getBibFiles().get(mapEntry.getValue().getPath()).stream().distinct().flatMap(bibFile -> // Get a specific entry from an entryKey and a BIB file. bibDatabases.get(bibFile).getEntriesByCitationKey(mapEntry.getKey()).stream().distinct() // Check if there is already an entry with the same key in the given database. .filter(entry -> !entry.equals(masterDatabase.getEntryByCitationKey(entry.getCitationKey().orElse("")).orElse(new BibEntry()))) // Add cross-referencing data to the entry (fill empty fields). .map(entry -> addCrossReferencingData(entry, bibFile, bibDatabases))); } private BibEntry addCrossReferencingData(BibEntry entry, Path bibFile, Map<Path, BibDatabase> bibDatabases) { bibDatabases.get(bibFile).getReferencedEntry(entry).ifPresent(refEntry -> refEntry.getFields().forEach(field -> entry.getFieldMap().putIfAbsent(field, refEntry.getFieldOrAlias(field).orElse("")))); return entry; } }
4,213
48
181
java
null
jabref-main/src/main/java/org/jabref/logic/undo/AddUndoableActionEvent.java
package org.jabref.logic.undo; /** * Event sent when a new undoable action is added to the undo manager */ public class AddUndoableActionEvent extends UndoChangeEvent { public AddUndoableActionEvent(boolean canUndo, String undoDescription, boolean canRedo, String redoDescription) { super(canUndo, undoDescription, canRedo, redoDescription); } }
366
29.583333
117
java
null
jabref-main/src/main/java/org/jabref/logic/undo/UndoChangeEvent.java
package org.jabref.logic.undo; /** * Event sent when something is undone or redone */ public class UndoChangeEvent { private final boolean canUndo; private final String undoDescription; private final boolean canRedo; private final String redoDescription; public UndoChangeEvent(boolean canUndo, String undoDescription, boolean canRedo, String redoDescription) { this.canUndo = canUndo; this.undoDescription = undoDescription; this.canRedo = canRedo; this.redoDescription = redoDescription; } /** * @return true if there is an action that can be undone */ public boolean isCanUndo() { return canUndo; } /** * @return A description of the action to be undone */ public String getUndoDescription() { return undoDescription; } /** * @return true if there is an action that can be redone */ public boolean isCanRedo() { return canRedo; } /** * @return A description of the action to be redone */ public String getRedoDescription() { return redoDescription; } }
1,141
22.791667
110
java
null
jabref-main/src/main/java/org/jabref/logic/undo/UndoRedoEvent.java
package org.jabref.logic.undo; /** * Event sent when something is undone or redone */ public class UndoRedoEvent extends UndoChangeEvent { public UndoRedoEvent(boolean canUndo, String undoDescription, boolean canRedo, String redoDescription) { super(canUndo, undoDescription, canRedo, redoDescription); } }
327
26.333333
108
java
null
jabref-main/src/main/java/org/jabref/logic/util/BackupFileType.java
package org.jabref.logic.util; import java.util.Collections; import java.util.List; public enum BackupFileType implements FileType { // Used at BackupManager BACKUP("Backup", "bak"), // Used when writing the .bib file. See {@link org.jabref.logic.exporter.AtomicFileWriter} // Used for copying the .bib away before overwriting on save. SAVE("AutoSaveFile", "sav"); private final List<String> extensions; private final String name; BackupFileType(String name, String extension) { this.extensions = Collections.singletonList(extension); this.name = name; } @Override public List<String> getExtensions() { return extensions; } @Override public String getName() { return this.name; } }
782
22.727273
94
java
null
jabref-main/src/main/java/org/jabref/logic/util/BuildInfo.java
package org.jabref.logic.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Locale; import java.util.Optional; import java.util.Properties; public final class BuildInfo { public static final String UNKNOWN_VERSION = "UNKNOWN"; public static final String OS = System.getProperty("os.name", UNKNOWN_VERSION); public static final String OS_VERSION = System.getProperty("os.version", UNKNOWN_VERSION).toLowerCase(Locale.ROOT); public static final String OS_ARCH = System.getProperty("os.arch", UNKNOWN_VERSION).toLowerCase(Locale.ROOT); public static final String JAVA_VERSION = System.getProperty("java.version", UNKNOWN_VERSION).toLowerCase(Locale.ROOT); public final Version version; public final String maintainers; public final String year; public final String azureInstrumentationKey; public final String springerNatureAPIKey; public final String astrophysicsDataSystemAPIKey; public final String ieeeAPIKey; public final String scienceDirectApiKey; public final String minRequiredJavaVersion; public final boolean allowJava9; public final String biodiversityHeritageApiKey; public BuildInfo() { this("/build.properties"); } public BuildInfo(String path) { Properties properties = new Properties(); try (InputStream stream = BuildInfo.class.getResourceAsStream(path)) { if (stream != null) { try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { properties.load(reader); } } } catch (IOException ignored) { // nothing to do -> default already set } version = Version.parse(properties.getProperty("version")); year = properties.getProperty("year", ""); maintainers = properties.getProperty("maintainers", ""); azureInstrumentationKey = BuildInfo.getValue(properties, "azureInstrumentationKey", ""); springerNatureAPIKey = BuildInfo.getValue(properties, "springerNatureAPIKey", "118d90a519d0fc2a01ee9715400054d4"); astrophysicsDataSystemAPIKey = BuildInfo.getValue(properties, "astrophysicsDataSystemAPIKey", "tAhPRKADc6cC26mZUnAoBt3MAjCvKbuCZsB4lI3c"); ieeeAPIKey = BuildInfo.getValue(properties, "ieeeAPIKey", "5jv3wyt4tt2bwcwv7jjk7pc3"); scienceDirectApiKey = BuildInfo.getValue(properties, "scienceDirectApiKey", "fb82f2e692b3c72dafe5f4f1fa0ac00b"); minRequiredJavaVersion = properties.getProperty("minRequiredJavaVersion", "1.8"); allowJava9 = "true".equals(properties.getProperty("allowJava9", "true")); biodiversityHeritageApiKey = BuildInfo.getValue(properties, "biodiversityHeritageApiKey", "36b910b6-2eb3-46f2-b64c-9abc149925ba"); } private static String getValue(Properties properties, String key, String defaultValue) { String result = Optional.ofNullable(properties.getProperty(key)) // workaround unprocessed build.properties file --> just remove the reference to some variable used in build.gradle .map(value -> value.replaceAll("\\$\\{.*\\}", "")) .orElse(""); if (!"".equals(result)) { return result; } return defaultValue; } }
3,438
46.109589
147
java
null
jabref-main/src/main/java/org/jabref/logic/util/CoarseChangeFilter.java
package org.jabref.logic.util; import java.util.Optional; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.event.BibDatabaseContextChangedEvent; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.event.FieldChangedEvent; import org.jabref.model.entry.field.Field; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; /** * Filters change events and only relays major changes. */ public class CoarseChangeFilter { private final BibDatabaseContext context; private final EventBus eventBus = new EventBus(); private Optional<Field> lastFieldChanged; private Optional<BibEntry> lastEntryChanged; private int totalDelta; public CoarseChangeFilter(BibDatabaseContext bibDatabaseContext) { // Listen for change events this.context = bibDatabaseContext; context.getDatabase().registerListener(this); context.getMetaData().registerListener(this); this.lastFieldChanged = Optional.empty(); this.lastEntryChanged = Optional.empty(); } @Subscribe public synchronized void listen(BibDatabaseContextChangedEvent event) { if (event instanceof FieldChangedEvent fieldChange) { // If editing has started boolean isNewEdit = lastFieldChanged.isEmpty() || lastEntryChanged.isEmpty(); boolean isChangedField = lastFieldChanged.filter(f -> !f.equals(fieldChange.getField())).isPresent(); boolean isChangedEntry = lastEntryChanged.filter(e -> !e.equals(fieldChange.getBibEntry())).isPresent(); boolean isEditChanged = !isNewEdit && (isChangedField || isChangedEntry); // Only deltas of 1 when typing in manually, major change means pasting something (more than one character) boolean isMajorChange = fieldChange.getMajorCharacterChange() > 1; fieldChange.setFilteredOut(!(isEditChanged || isMajorChange)); // Post each FieldChangedEvent - even the ones being marked as "filtered" eventBus.post(fieldChange); lastFieldChanged = Optional.of(fieldChange.getField()); lastEntryChanged = Optional.of(fieldChange.getBibEntry()); } else { eventBus.post(event); } } public void registerListener(Object listener) { eventBus.register(listener); } public void unregisterListener(Object listener) { eventBus.unregister(listener); } public void shutdown() { context.getDatabase().unregisterListener(this); context.getMetaData().unregisterListener(this); } }
2,655
36.408451
119
java
null
jabref-main/src/main/java/org/jabref/logic/util/DelayTaskThrottler.java
package org.jabref.logic.util; import java.util.concurrent.Callable; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.jabref.gui.JabRefExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class allows to throttle a list of tasks. * Use case: you have an event that occurs often, and every time you want to invoke the same task. * However, if a lot of events happen in a relatively short time span, then only one task should be invoked. * * @implNote Once {@link #schedule(Runnable)} is called, the task is delayed for a given time span. * If during this time, {@link #schedule(Runnable)} is called again, then the original task is canceled and the new one scheduled. */ public class DelayTaskThrottler { private static final Logger LOGGER = LoggerFactory.getLogger(DelayTaskThrottler.class); private final ScheduledThreadPoolExecutor executor; private int delay; private ScheduledFuture<?> scheduledTask; /** * @param delay delay in milliseconds */ public DelayTaskThrottler(int delay) { this.delay = delay; this.executor = new ScheduledThreadPoolExecutor(1); this.executor.setRemoveOnCancelPolicy(true); this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); } public ScheduledFuture<?> schedule(Runnable command) { if (scheduledTask != null) { cancel(); } try { scheduledTask = executor.schedule(command, delay, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { LOGGER.debug("Rejecting while another process is already running."); } return scheduledTask; } public <T> ScheduledFuture<?> scheduleTask(Callable<?> command) { if (scheduledTask != null) { cancel(); } try { scheduledTask = executor.schedule(command, delay, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { LOGGER.debug("Rejecting while another process is already running."); } return scheduledTask; } // Execute scheduled Runnable early public void execute(Runnable command) { delay = 0; schedule(command); } // Cancel scheduled Runnable gracefully public void cancel() { scheduledTask.cancel(false); } /** * Shuts everything down. Upon termination, this method returns. */ public void shutdown() { JabRefExecutorService.gracefullyShutdown(executor); } }
2,719
31.380952
138
java
null
jabref-main/src/main/java/org/jabref/logic/util/ExternalLinkCreator.java
package org.jabref.logic.util; import java.net.URISyntaxException; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.apache.http.client.utils.URIBuilder; public class ExternalLinkCreator { private static final String SHORTSCIENCE_SEARCH_URL = "https://www.shortscience.org/internalsearch"; /** * Get a URL to the search results of ShortScience for the BibEntry's title * * @param entry The entry to search for. Expects the BibEntry's title to be set for successful return. * @return The URL if it was successfully created */ public static Optional<String> getShortScienceSearchURL(BibEntry entry) { return entry.getField(StandardField.TITLE).map(title -> { URIBuilder uriBuilder; try { uriBuilder = new URIBuilder(SHORTSCIENCE_SEARCH_URL); } catch (URISyntaxException e) { // This should never be able to happen as it would require the field to be misconfigured. throw new AssertionError("ShortScience URL is invalid.", e); } // Direct the user to the search results for the title. uriBuilder.addParameter("q", title); return uriBuilder.toString(); }); } }
1,330
37.028571
106
java
null
jabref-main/src/main/java/org/jabref/logic/util/FileType.java
package org.jabref.logic.util; import java.util.List; import java.util.stream.Collectors; /** * Interface for {@link StandardFileType} which allows us to extend the underlying enum with own filetypes for custom exporters */ public interface FileType { default List<String> getExtensionsWithAsteriskAndDot() { return getExtensions().stream() .map(extension -> "*." + extension) .collect(Collectors.toList()); } List<String> getExtensions(); String getName(); }
551
25.285714
127
java
null
jabref-main/src/main/java/org/jabref/logic/util/MetadataSerializationConfiguration.java
package org.jabref.logic.util; import org.jabref.model.groups.AllEntriesGroup; import org.jabref.model.groups.AutomaticKeywordGroup; import org.jabref.model.groups.AutomaticPersonsGroup; import org.jabref.model.groups.ExplicitGroup; import org.jabref.model.groups.RegexKeywordGroup; import org.jabref.model.groups.SearchGroup; import org.jabref.model.groups.TexGroup; import org.jabref.model.groups.WordKeywordGroup; /** * Specifies how metadata is read and written. */ public class MetadataSerializationConfiguration { /** * Character used for quoting in the string representation. */ public static final char GROUP_QUOTE_CHAR = '\\'; /** * For separating units (e.g. name and hierarchic context) in the string representation */ public static final String GROUP_UNIT_SEPARATOR = ";"; /** * Identifier for {@link WordKeywordGroup} and {@link RegexKeywordGroup}. */ public static final String KEYWORD_GROUP_ID = "KeywordGroup:"; /** * Identifier for {@link AllEntriesGroup}. */ public static final String ALL_ENTRIES_GROUP_ID = "AllEntriesGroup:"; /** * Old identifier for {@link ExplicitGroup} (explicitly contained a list of {@link org.jabref.model.entry.BibEntry}). */ public static final String LEGACY_EXPLICIT_GROUP_ID = "ExplicitGroup:"; /** * Identifier for {@link ExplicitGroup}. */ public static final String EXPLICIT_GROUP_ID = "StaticGroup:"; /** * Identifier for {@link SearchGroup}. */ public static final String SEARCH_GROUP_ID = "SearchGroup:"; /** * Identifier for {@link AutomaticPersonsGroup}. */ public static final String AUTOMATIC_PERSONS_GROUP_ID = "AutomaticPersonsGroup:"; /** * Identifier for {@link AutomaticKeywordGroup}. */ public static final String AUTOMATIC_KEYWORD_GROUP_ID = "AutomaticKeywordGroup:"; /** * Identifier for {@link TexGroup}. */ public static final String TEX_GROUP_ID = "TexGroup:"; private MetadataSerializationConfiguration() { } }
2,083
29.202899
121
java
null
jabref-main/src/main/java/org/jabref/logic/util/OS.java
package org.jabref.logic.util; import java.util.Locale; import org.jabref.gui.desktop.os.DefaultDesktop; import org.jabref.gui.desktop.os.Linux; import org.jabref.gui.desktop.os.NativeDesktop; import org.jabref.gui.desktop.os.OSX; import org.jabref.gui.desktop.os.Windows; /** * Operating system (OS) detection * * For OS-specific actions see {@link org.jabref.gui.desktop.JabRefDesktop} and {@link org.jabref.gui.desktop.os.NativeDesktop}. */ public class OS { // No LOGGER may be initialized directly // Otherwise, org.jabref.cli.Launcher.addLogToDisk will fail, because tinylog's properties are frozen public static final String NEWLINE = System.lineSeparator(); public static final String APP_DIR_APP_NAME = "jabref"; public static final String APP_DIR_APP_AUTHOR = "org.jabref"; // https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SystemUtils.html private static final String OS_NAME = System.getProperty("os.name", "unknown").toLowerCase(Locale.ROOT); public static final boolean LINUX = OS_NAME.startsWith("linux"); public static final boolean WINDOWS = OS_NAME.startsWith("win"); public static final boolean OS_X = OS_NAME.startsWith("mac"); private OS() { } public static NativeDesktop getNativeDesktop() { if (WINDOWS) { return new Windows(); } else if (OS_X) { return new OSX(); } else if (LINUX) { return new Linux(); } return new DefaultDesktop(); } }
1,549
32.695652
128
java
null
jabref-main/src/main/java/org/jabref/logic/util/StandardFileType.java
package org.jabref.logic.util; import java.util.Arrays; import java.util.List; import org.jabref.model.util.OptionalUtil; /** * @implNote Enter the extensions in lowercase without a dot! The dot is added implicitly. */ public enum StandardFileType implements FileType { ENDNOTE("Endnote", "ref", "enw"), ISI("Isi", "isi", "txt"), MEDLINE("Medline", "nbib", "xml"), MEDLINE_PLAIN("Medline Plain", "nbib", "txt"), PUBMED("Pubmed", "fcgi"), SILVER_PLATTER("SilverPlatter", "dat", "txt"), AUX("Aux file", "aux"), BIBTEX_DB("Bibtex library", "bib"), CITATION_STYLE("Citation Style", "csl"), CLASS("Class file", "class"), CSV("CSV", "csv"), HTML("HTML", "html", "htm"), JAR("JAR", "jar"), JAVA_KEYSTORE("Java Keystore", "jks"), JSTYLE("LibreOffice layout style", "jstyle"), LAYOUT("Custom Exporter format", "layout"), ODS("OpenOffice Calc", "ods"), PDF("PDF", "pdf"), RIS("RIS", "ris"), TERMS("Protected terms", "terms"), TXT("Plain Text", "txt"), RDF("RDF", "rdf"), RTF("RTF", "rtf"), SXC("Open Office Calc 1.x", "sxc"), TEX("LaTeX", "tex"), XML("XML", "xml"), JSON("JSON", "json"), XMP("XMP", "xmp"), ZIP("Zip Archive", "zip"), CSS("CSS Styleshet", "css"), YAML("YAML Markup", "yaml"), CFF("CFF", "cff"), ANY_FILE("Any", "*"), CER("SSL Certificate", "cer"), CITAVI("Citavi", "ctv6bak", "ctv5bak"), MARKDOWN("Markdown", "md"); private final List<String> extensions; private final String name; StandardFileType(String name, String... extensions) { this.extensions = Arrays.asList(extensions); this.name = name; } @Override public List<String> getExtensions() { return extensions; } @Override public String getName() { return this.name; } public static FileType fromExtensions(String... extensions) { var exts = Arrays.asList(extensions); return OptionalUtil.orElse(Arrays.stream(StandardFileType.values()) .filter(field -> field.getExtensions().stream().anyMatch(exts::contains)) .findAny(), new UnknownFileType(extensions)); } }
2,296
27.7125
114
java
null
jabref-main/src/main/java/org/jabref/logic/util/TestEntry.java
package org.jabref.logic.util; import java.util.Arrays; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; public class TestEntry { private TestEntry() { } public static BibEntry getTestEntry() { BibEntry entry = new BibEntry(StandardEntryType.Article); entry.setCitationKey("Smith2016"); entry.setField(StandardField.AUTHOR, "Smith, Bill and Jones, Bob and Williams, Jeff"); entry.setField(StandardField.EDITOR, "Taylor, Phil"); entry.setField(StandardField.TITLE, "Title of the test entry"); entry.setField(StandardField.NUMBER, "3"); entry.setField(StandardField.VOLUME, "34"); entry.setField(StandardField.ISSUE, "7"); entry.setField(StandardField.YEAR, "2016"); entry.setField(StandardField.PAGES, "45--67"); entry.setField(StandardField.MONTH, "July"); entry.setField(StandardField.FILE, ":testentry.pdf:PDF"); entry.setField(StandardField.JOURNAL, "BibTeX Journal"); entry.setField(StandardField.PUBLISHER, "JabRef Publishing"); entry.setField(StandardField.ADDRESS, "Trondheim"); entry.setField(StandardField.URL, "https://github.com/JabRef"); entry.setField(StandardField.DOI, "10.1001/bla.blubb"); entry.setField(StandardField.ABSTRACT, "This entry describes a test scenario which may be useful in JabRef. By providing a test entry it is possible to see how certain things will look in this graphical BIB-file mananger."); entry.setField(StandardField.COMMENT, "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et " + "dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. " + "Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non " + "proident, sunt in culpa qui officia deserunt mollit anim id est laborum."); entry.putKeywords(Arrays.asList("KeyWord1", "KeyWord2", "KeyWord3", "Keyword4"), ';'); return entry; } public static BibEntry getTestEntryBook() { BibEntry entry = new BibEntry(StandardEntryType.Book); entry.setCitationKey("Harrer2018"); entry.setField(StandardField.AUTHOR, "Simon Harrer and Jörg Lenhard and Linus Dietz"); entry.setField(StandardField.EDITOR, "Andrea Steward"); entry.setField(StandardField.TITLE, "Java by Comparison"); entry.setField(StandardField.YEAR, "2018"); entry.setField(StandardField.MONTH, "March"); entry.setField(StandardField.PUBLISHER, "Pragmatic Bookshelf"); entry.setField(StandardField.ADDRESS, "Raleigh, NC"); return entry; } }
2,924
51.232143
201
java
null
jabref-main/src/main/java/org/jabref/logic/util/UnknownFileType.java
package org.jabref.logic.util; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Objects; public class UnknownFileType implements FileType { private final List<String> extensions; public UnknownFileType(String... extensions) { for (int i = 0; i < extensions.length; i++) { if (extensions[i].contains(".")) { extensions[i] = extensions[i].substring(extensions[i].indexOf('.') + 1); } extensions[i] = extensions[i].toLowerCase(Locale.ROOT); } this.extensions = Arrays.asList(extensions); } @Override public List<String> getExtensions() { return extensions; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FileType)) { return false; } FileType other = (FileType) o; Collections.sort(extensions); Collections.sort(other.getExtensions()); return extensions.equals(other.getExtensions()); } @Override public int hashCode() { return Objects.hash(extensions); } @Override public String getName() { return "Unknown File Type" + extensions.toString(); } }
1,321
24.423077
88
java
null
jabref-main/src/main/java/org/jabref/logic/util/UpdateField.java
package org.jabref.logic.util; import java.util.Collection; import java.util.Optional; import org.jabref.logic.preferences.OwnerPreferences; import org.jabref.logic.preferences.TimestampPreferences; import org.jabref.model.FieldChange; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; public class UpdateField { private UpdateField() { } /** * Updating a field will result in the entry being reformatted on save */ public static Optional<FieldChange> updateField(BibEntry be, Field field, String newValue) { return updateField(be, field, newValue, false); } /** * Updating a non-displayable field does not result in the entry being reformatted on save */ public static Optional<FieldChange> updateNonDisplayableField(BibEntry be, Field field, String newValue) { boolean changed = be.hasChanged(); Optional<FieldChange> fieldChange = updateField(be, field, newValue, false); be.setChanged(changed); return fieldChange; } /** * Undoable change of field value * * @param nullFieldIfValueIsTheSame If true the field value is removed when the current value is equals to newValue */ public static Optional<FieldChange> updateField(BibEntry be, Field field, String newValue, Boolean nullFieldIfValueIsTheSame) { String writtenValue = null; String oldValue = null; if (be.hasField(field)) { oldValue = be.getField(field).get(); if ((newValue == null) || (oldValue.equals(newValue) && nullFieldIfValueIsTheSame)) { // If the new field value is null or the old and the new value are the same and flag is set // Clear the field be.clearField(field); } else if (!oldValue.equals(newValue)) { // Update writtenValue = newValue; be.setField(field, newValue); } else { // Values are the same, do nothing return Optional.empty(); } } else { // old field value not set if (newValue == null) { // Do nothing return Optional.empty(); } else { // Set new value writtenValue = newValue; be.setField(field, newValue); } } return Optional.of(new FieldChange(be, field, oldValue, writtenValue)); } private static void setAutomaticFields(BibEntry entry, boolean setOwner, String owner, boolean setTimeStamp, String timeStamp) { // Set owner field if this option is enabled: if (setOwner) { // Set owner field to default value entry.setField(StandardField.OWNER, owner); } if (setTimeStamp) { entry.setField(StandardField.CREATIONDATE, timeStamp); } } /** * Sets empty or non-existing owner fields of bibtex entries inside a List to a specified default value. Timestamp * field is also set. Preferences are checked to see if these options are enabled. */ public static void setAutomaticFields(Collection<BibEntry> entries, OwnerPreferences ownerPreferences, TimestampPreferences timestampPreferences) { boolean globalSetOwner = ownerPreferences.isUseOwner(); boolean setTimeStamp = timestampPreferences.shouldAddCreationDate(); // Do not need to do anything if all options are disabled if (!(globalSetOwner || setTimeStamp)) { return; } String defaultOwner = ownerPreferences.getDefaultOwner(); boolean overwriteOwner = ownerPreferences.isOverwriteOwner(); String timestamp = timestampPreferences.now(); for (BibEntry curEntry : entries) { boolean setOwner = globalSetOwner && (overwriteOwner || (!curEntry.hasField(StandardField.OWNER))); setAutomaticFields(curEntry, setOwner, defaultOwner, setTimeStamp, timestamp); } } }
4,164
37.925234
151
java
null
jabref-main/src/main/java/org/jabref/logic/util/Version.java
package org.jabref.logic.util; 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.List; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import kong.unirest.json.JSONArray; import kong.unirest.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents the Application Version with the major and minor number, the full Version String and if it's a developer version */ public class Version { public static final String JABREF_DOWNLOAD_URL = "https://downloads.jabref.org"; private static final Version UNKNOWN_VERSION = new Version(); private final static Pattern VERSION_PATTERN = Pattern.compile("(?<major>\\d+)(\\.(?<minor>\\d+))?(\\.(?<patch>\\d+))?(?<stage>-alpha|-beta)?(?<num>\\d+)?(?<dev>-?dev)?.*"); private final static Pattern CI_SUFFIX_PATTERN = Pattern.compile("-ci\\.\\d+"); private static final String JABREF_GITHUB_RELEASES = "https://api.github.com/repos/JabRef/JabRef/releases"; private String fullVersion = BuildInfo.UNKNOWN_VERSION; private int major = -1; private int minor = -1; private int patch = -1; private DevelopmentStage developmentStage = DevelopmentStage.UNKNOWN; private int developmentNum = -1; private boolean isDevelopmentVersion; /** * Dummy constructor to create a local object (and {@link Version#UNKNOWN_VERSION}) */ private Version() { } /** * Tinylog does not allow for altering existing loging configuraitons after the logger was initialized . * Lazy initialization to enable tinylog writing to a file (and also still enabling loggin in this class) */ private static Logger getLogger() { return LoggerFactory.getLogger(Version.class); } /** * @param version must be in form of following pattern: {@code (\d+)(\.(\d+))?(\.(\d+))?(-alpha|-beta)?(-?dev)?} (e.g., 3.3; 3.4-dev) * @return the parsed version or {@link Version#UNKNOWN_VERSION} if an error occurred */ public static Version parse(String version) { if ((version == null) || "".equals(version) || version.equals(BuildInfo.UNKNOWN_VERSION) || "${version}".equals(version)) { return UNKNOWN_VERSION; } Version parsedVersion = new Version(); // remove "-ci.1" suffix Matcher ciSuffixMatcher = CI_SUFFIX_PATTERN.matcher(version); version = ciSuffixMatcher.replaceAll(""); parsedVersion.fullVersion = version; Matcher matcher = VERSION_PATTERN.matcher(version); if (matcher.find()) { try { parsedVersion.major = Integer.parseInt(matcher.group("major")); String minorString = matcher.group("minor"); parsedVersion.minor = minorString == null ? 0 : Integer.parseInt(minorString); String patchString = matcher.group("patch"); parsedVersion.patch = patchString == null ? 0 : Integer.parseInt(patchString); String versionStageString = matcher.group("stage"); parsedVersion.developmentStage = versionStageString == null ? DevelopmentStage.STABLE : DevelopmentStage.parse(versionStageString); String stageNumString = matcher.group("num"); parsedVersion.developmentNum = stageNumString == null ? 0 : Integer.parseInt(stageNumString); parsedVersion.isDevelopmentVersion = matcher.group("dev") != null; } catch (NumberFormatException e) { getLogger().warn("Invalid version string used: {}", version, e); return UNKNOWN_VERSION; } catch (IllegalArgumentException e) { getLogger().warn("Invalid version pattern is used", e); return UNKNOWN_VERSION; } } else { getLogger().warn("Version could not be recognized by the pattern"); return UNKNOWN_VERSION; } return parsedVersion; } /** * Grabs all the available releases from the GitHub repository */ public static List<Version> getAllAvailableVersions() throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(JABREF_GITHUB_RELEASES).openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); try (BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { JSONArray objects = new JSONArray(rd.readLine()); List<Version> versions = new ArrayList<>(objects.length()); for (int i = 0; i < objects.length(); i++) { JSONObject jsonObject = objects.getJSONObject(i); Version version = Version.parse(jsonObject.getString("tag_name").replaceFirst("v", "")); versions.add(version); } connection.disconnect(); return versions; } } /** * @return true if this version is newer than the passed one */ public boolean isNewerThan(Version otherVersion) { Objects.requireNonNull(otherVersion); if (Objects.equals(this, otherVersion)) { return false; } else if (this.getFullVersion().equals(BuildInfo.UNKNOWN_VERSION)) { return false; } else if (otherVersion.getFullVersion().equals(BuildInfo.UNKNOWN_VERSION)) { return false; } // compare the majors if (this.getMajor() > otherVersion.getMajor()) { return true; } else if (this.getMajor() == otherVersion.getMajor()) { // if the majors are equal compare the minors if (this.getMinor() > otherVersion.getMinor()) { return true; } else if (this.getMinor() == otherVersion.getMinor()) { // if the minors are equal compare the patch numbers if (this.getPatch() > otherVersion.getPatch()) { return true; } else if (this.getPatch() == otherVersion.getPatch()) { // if the patch numbers are equal compare the development stages if (this.developmentStage.isMoreStableThan(otherVersion.developmentStage)) { return true; } else if (this.developmentStage == otherVersion.developmentStage) { // if the development stage are equal compare the development number if (this.getDevelopmentNum() > otherVersion.getDevelopmentNum()) { return true; } else if (this.getDevelopmentNum() == otherVersion.getDevelopmentNum()) { // if the stage is equal check if this version is in development and the other is not return !this.isDevelopmentVersion && otherVersion.isDevelopmentVersion; } } } } } return false; } /** * Checks if this version should be updated to one of the given ones. Ignoring the other Version if this one is Stable and the other one is not. * * @return The version this one should be updated to, or an empty Optional */ public Optional<Version> shouldBeUpdatedTo(List<Version> availableVersions) { Optional<Version> newerVersion = Optional.empty(); for (Version version : availableVersions) { if (this.shouldBeUpdatedTo(version) && (!newerVersion.isPresent() || version.isNewerThan(newerVersion.get()))) { newerVersion = Optional.of(version); } } return newerVersion; } /** * Checks if this version should be updated to the given one. Ignoring the other Version if this one is Stable and the other one is not. * * @return True if this version should be updated to the given one */ public boolean shouldBeUpdatedTo(Version otherVersion) { // ignoring the other version if it is not stable, except if this version itself is not stable if (developmentStage == Version.DevelopmentStage.STABLE && otherVersion.developmentStage != Version.DevelopmentStage.STABLE) { return false; } // check if the other version is newer than given one return otherVersion.isNewerThan(this); } public String getFullVersion() { return fullVersion; } public int getMajor() { return major; } public int getMinor() { return minor; } public int getPatch() { return patch; } public int getDevelopmentNum() { return developmentNum; } public boolean isDevelopmentVersion() { return isDevelopmentVersion; } /** * @return The link to the changelog on GitHub to this specific version (https://github.com/JabRef/jabref/blob/vX.X/CHANGELOG.md) */ public String getChangelogUrl() { if (isDevelopmentVersion) { return "https://github.com/JabRef/jabref/blob/main/CHANGELOG.md#unreleased"; } else { StringBuilder changelogLink = new StringBuilder() .append("https://github.com/JabRef/jabref/blob/v") .append(this.getMajor()) .append(".") .append(this.getMinor()); if (this.getPatch() != 0) { changelogLink .append(".") .append(this.getPatch()); } changelogLink .append(this.developmentStage.stage); if (this.getDevelopmentNum() != 0) { changelogLink .append(this.getDevelopmentNum()); } changelogLink.append("/CHANGELOG.md"); return changelogLink.toString(); } } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Version)) { return false; } // till all the information are stripped from the fullversion this should suffice return this.getFullVersion().equals(((Version) other).getFullVersion()); } @Override public int hashCode() { return getFullVersion().hashCode(); } @Override public String toString() { return this.getFullVersion(); } public enum DevelopmentStage { UNKNOWN("", 0), ALPHA("-alpha", 1), BETA("-beta", 2), STABLE("", 3); /** * describes how stable this stage is, the higher the better */ private final int stability; private final String stage; DevelopmentStage(String stage, int stability) { this.stage = stage; this.stability = stability; } public static DevelopmentStage parse(String stage) { if (stage == null) { getLogger().warn("The stage cannot be null"); return UNKNOWN; } else if (stage.equals(STABLE.stage)) { return STABLE; } else if (stage.equals(ALPHA.stage)) { return ALPHA; } else if (stage.equals(BETA.stage)) { return BETA; } getLogger().warn("Unknown development stage: {}", stage); return UNKNOWN; } /** * @return true if this stage is more stable than the {@code otherStage} */ public boolean isMoreStableThan(DevelopmentStage otherStage) { return this.stability > otherStage.stability; } } }
11,940
36.432602
177
java
null
jabref-main/src/main/java/org/jabref/logic/util/WebViewStore.java
package org.jabref.logic.util; import java.util.ArrayDeque; import java.util.Queue; import javafx.application.Platform; import javafx.scene.web.WebView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A dynamic web view store. This is used primarily to prevent UI freezes while constructing web view instances. */ public class WebViewStore { private static final Logger LOGGER = LoggerFactory.getLogger(WebViewStore.class); private final static Queue<WebView> WEB_VIEWS = new ArrayDeque<>(); private static boolean isInitialized = false; private static Configuration config; /** * Initialize {@code WebViewStore} and preload web view instances. * <p> Note that this method must be called at application startup. </p> */ public static void init(Configuration config) { WebViewStore.config = config; for (int i = 0; i < config.getNumberOfPreloadedInstances(); i++) { addWebViewLater(); } isInitialized = true; } /** * Initialize {@code WebViewStore} and preload web view instance. * <p> Note that this method must be called at application startup. </p> */ public static void init() { init(new Configuration(4, 2)); } /** * Returns a preloaded web view instance if available; And it will create a new one if not. * * @return {@code WebView} instance * @throws IllegalStateException if the webViewStore has not been initialized */ public static WebView get() { if (!isInitialized) { throw new IllegalStateException("WebViewStore is uninitialized"); } if (WEB_VIEWS.size() <= config.getMinimumNumberOfInstances()) { addWebViewLater(); } if (hasMore()) { return WEB_VIEWS.poll(); } else { return new WebView(); } } private static void addWebViewLater() { Platform.runLater(() -> { WEB_VIEWS.add(new WebView()); LOGGER.debug("Cached Web views: {}", WEB_VIEWS.size()); }); } /** * @return {@code true} if the store has at least one web view instance available; {@code false} otherwise */ public static boolean hasMore() { return !WEB_VIEWS.isEmpty(); } public record Configuration( int numberOfPreloadedInstances, int minimumNumberOfInstances) { /** * @return The number of web view instances to be loaded at application startup */ public int getNumberOfPreloadedInstances() { return numberOfPreloadedInstances; } /** * @return The minimum number of web views the store can reach. The store needs to load more instances once it reaches this threshold */ public int getMinimumNumberOfInstances() { return minimumNumberOfInstances; } } }
2,938
30.265957
141
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/AutoLinkPreferences.java
package org.jabref.logic.util.io; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class AutoLinkPreferences { public enum CitationKeyDependency { START, // Filenames starting with the citation key EXACT, // Filenames exactly matching the citation key REGEX // Filenames matching a regular expression pattern } private final ObjectProperty<CitationKeyDependency> citationKeyDependency; private final StringProperty regularExpression; private final BooleanProperty askAutoNamingPdfs; private final ReadOnlyObjectProperty<Character> keywordSeparator; public AutoLinkPreferences(CitationKeyDependency citationKeyDependency, String regularExpression, boolean askAutoNamingPdfs, ObjectProperty<Character> keywordSeparatorProperty) { this.citationKeyDependency = new SimpleObjectProperty<>(citationKeyDependency); this.regularExpression = new SimpleStringProperty(regularExpression); this.askAutoNamingPdfs = new SimpleBooleanProperty(askAutoNamingPdfs); this.keywordSeparator = keywordSeparatorProperty; } /** * For testing purpose */ public AutoLinkPreferences(CitationKeyDependency citationKeyDependency, String regularExpression, boolean askAutoNamingPdfs, Character keywordSeparator) { this.citationKeyDependency = new SimpleObjectProperty<>(citationKeyDependency); this.regularExpression = new SimpleStringProperty(regularExpression); this.askAutoNamingPdfs = new SimpleBooleanProperty(askAutoNamingPdfs); this.keywordSeparator = new SimpleObjectProperty<>(keywordSeparator); } public CitationKeyDependency getCitationKeyDependency() { return citationKeyDependency.getValue(); } public ObjectProperty<CitationKeyDependency> citationKeyDependencyProperty() { return citationKeyDependency; } public void setCitationKeyDependency(CitationKeyDependency citationKeyDependency) { this.citationKeyDependency.set(citationKeyDependency); } public String getRegularExpression() { return regularExpression.getValue(); } public StringProperty regularExpressionProperty() { return regularExpression; } public void setRegularExpression(String regularExpression) { this.regularExpression.set(regularExpression); } public boolean shouldAskAutoNamingPdfs() { return askAutoNamingPdfs.getValue(); } public BooleanProperty askAutoNamingPdfsProperty() { return askAutoNamingPdfs; } public void setAskAutoNamingPdfs(boolean askAutoNamingPdfs) { this.askAutoNamingPdfs.set(askAutoNamingPdfs); } public Character getKeywordSeparator() { return keywordSeparator.getValue(); } }
3,259
36.471264
87
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/BackupFileUtil.java
package org.jabref.logic.util.io; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.HexFormat; import java.util.Optional; import org.jabref.logic.util.BackupFileType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BackupFileUtil { private static final Logger LOGGER = LoggerFactory.getLogger(BackupFileUtil.class); private BackupFileUtil() { } /** * Determines the path of the backup file (using the given extension) * * <p> * As default, a directory inside the user temporary dir is used.<br> * In case a AUTOSAVE backup is requested, a timestamp is added * </p> * <p> * <em>SIDE EFFECT</em>: Creates the directory. * In case that fails, the return path of the .bak file is set to be next to the .bib file * </p> * <p> * Note that this backup is different from the <code>.sav</code> file generated by {@link org.jabref.logic.autosaveandbackup.BackupManager} * (and configured in the preferences as "make backups") * </p> */ public static Path getPathForNewBackupFileAndCreateDirectory(Path targetFile, BackupFileType fileType, Path backupDir) { String extension = "." + fileType.getExtensions().get(0); String timeSuffix = ZonedDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd--HH.mm.ss")); // We choose the data directory, because a ".bak" file should survive cache cleanups Path directory = backupDir; try { Files.createDirectories(directory); } catch (IOException e) { Path result = FileUtil.addExtension(targetFile, extension); LOGGER.warn("Could not create bib writing directory {}, using {} as file", directory, result, e); return result; } String baseFileName = getUniqueFilePrefix(targetFile) + "--" + targetFile.getFileName() + "--" + timeSuffix; Path fileName = FileUtil.addExtension(Path.of(baseFileName), extension); return directory.resolve(fileName); } public static Optional<Path> getPathOfLatestExistingBackupFile(Path targetFile, BackupFileType fileType, Path backupDir) { // The code is similar to "getPathForNewBackupFileAndCreateDirectory" String extension = "." + fileType.getExtensions().get(0); if (Files.notExists(backupDir)) { // In case there is no app directory, we search in the directory of the bib file Path result = FileUtil.addExtension(targetFile, extension); if (Files.exists(result)) { return Optional.of(result); } else { return Optional.empty(); } } // Search the directory for the latest file final String prefix = getUniqueFilePrefix(targetFile) + "--" + targetFile.getFileName(); Optional<Path> mostRecentFile; try { mostRecentFile = Files.list(backupDir) // just list the .sav belonging to the given targetFile .filter(p -> p.getFileName().toString().startsWith(prefix)) .sorted() .reduce((first, second) -> second); } catch (IOException e) { LOGGER.error("Could not determine most recent file", e); return Optional.empty(); } return mostRecentFile; } /** * <p> * Determines a unique file prefix. * </p> * <p> * When creating a backup file, the backup file should belong to the original file. * Just adding ".bak" suffix to the filename, does not work in all cases: * It may be possible that the user has opened "paper.bib" twice. * Thus, we need to create a unique prefix to distinguish these files. * </p> */ public static String getUniqueFilePrefix(Path targetFile) { // Idea: use the hash code and convert it to hex // Thereby, use positive values only and use length 4 int positiveCode = Math.abs(targetFile.hashCode()); byte[] array = ByteBuffer.allocate(4).putInt(positiveCode).array(); return HexFormat.of().formatHex(array); } }
4,412
39.486239
147
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/CitationKeyBasedFileFinder.java
package org.jabref.logic.util.io; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BiPredicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.model.entry.BibEntry; import org.jabref.model.strings.StringUtil; class CitationKeyBasedFileFinder implements FileFinder { private final boolean exactKeyOnly; CitationKeyBasedFileFinder(boolean exactKeyOnly) { this.exactKeyOnly = exactKeyOnly; } @Override public List<Path> findAssociatedFiles(BibEntry entry, List<Path> directories, List<String> extensions) throws IOException { Objects.requireNonNull(directories); Objects.requireNonNull(entry); Optional<String> citeKeyOptional = entry.getCitationKey(); if (StringUtil.isBlank(citeKeyOptional)) { return Collections.emptyList(); } String citeKey = citeKeyOptional.get(); List<Path> result = new ArrayList<>(); // First scan directories Set<Path> filesWithExtension = findFilesByExtension(directories, extensions); // Now look for keys for (Path file : filesWithExtension) { String name = file.getFileName().toString(); String nameWithoutExtension = FileUtil.getBaseName(name); // First, look for exact matches if (nameWithoutExtension.equals(citeKey)) { result.add(file); continue; } // If we get here, we did not find any exact matches. If non-exact matches are allowed, try to find one if (!exactKeyOnly && matches(name, citeKey)) { result.add(file); } } return result.stream().sorted().collect(Collectors.toList()); } private boolean matches(String filename, String citeKey) { boolean startsWithKey = filename.startsWith(FileNameCleaner.cleanFileName(citeKey)); if (startsWithKey) { // The file name starts with the key, that's already a good start // However, we do not want to match "JabRefa" for "JabRef" since this is probably a file belonging to another entry published in the same time / same name char charAfterKey = filename.charAt(citeKey.length()); return !CitationKeyGenerator.APPENDIX_CHARACTERS.contains(Character.toString(charAfterKey)); } return false; } /** * Returns a list of all files in the given directories which have one of the given extension. */ private Set<Path> findFilesByExtension(List<Path> directories, List<String> extensions) throws IOException { Objects.requireNonNull(extensions, "Extensions must not be null!"); BiPredicate<Path, BasicFileAttributes> isFileWithCorrectExtension = (path, attributes) -> !Files.isDirectory(path) && extensions.contains(FileUtil.getFileExtension(path).orElse("")); Set<Path> result = new HashSet<>(); for (Path directory : directories) { if (Files.exists(directory)) { try (Stream<Path> pathStream = Files.find(directory, Integer.MAX_VALUE, isFileWithCorrectExtension, FileVisitOption.FOLLOW_LINKS)) { result.addAll(pathStream.collect(Collectors.toSet())); } catch (UncheckedIOException e) { throw new IOException("Problem in finding files", e); } } } return result; } }
3,903
38.04
166
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/DatabaseFileLookup.java
package org.jabref.logic.util.io; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.FilePreferences; /** * Search class for files. <br> * <br> * This class provides some functionality to search in a {@link BibDatabase} for files. <br> */ public class DatabaseFileLookup { private final Set<Path> fileCache = new HashSet<>(); private final List<Path> possibleFilePaths; private final Path pathOfDatabase; /** * Creates an instance by passing a {@link BibDatabase} which will be used for the searches. */ public DatabaseFileLookup(BibDatabaseContext databaseContext, FilePreferences filePreferences) { Objects.requireNonNull(databaseContext); possibleFilePaths = Optional.ofNullable(databaseContext.getFileDirectories(filePreferences)) .orElse(new ArrayList<>()); for (BibEntry entry : databaseContext.getDatabase().getEntries()) { fileCache.addAll(parseFileField(entry)); } this.pathOfDatabase = databaseContext.getDatabasePath().orElse(Path.of("")); } /** * Returns whether the File <code>file</code> is present in the database * as an attached File to an {@link BibEntry}. <br> * <br> * To do this, the field specified by the key <b>file</b> will be searched * for the provided file for every {@link BibEntry} in the database. <br> * <br> * For the matching, the absolute file paths will be used. * * @param pathname A {@link File} Object. * @return <code>true</code>, if the file Object is stored in at least one * entry in the database, otherwise <code>false</code>. */ public boolean lookupDatabase(Path pathname) { return fileCache.contains(pathname); } private List<Path> parseFileField(BibEntry entry) { Objects.requireNonNull(entry); return entry.getFiles().stream() .filter(file -> !file.isOnlineLink()) // Do not query external file links (huge performance leak) .map(file -> file.findIn(possibleFilePaths)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } /** * @return "" if the path does not exist */ public Path getPathOfDatabase() { return pathOfDatabase; } }
2,735
33.2
117
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/FileFinder.java
package org.jabref.logic.util.io; import java.io.IOException; import java.nio.file.Path; import java.util.List; import org.jabref.model.entry.BibEntry; public interface FileFinder { /** * Finds all files in the given directories that are probably associated with the given entries and have one of the passed extensions. * * @param entry The entry to search files for. * @param directories The root directories to search. * @param extensions The extensions that are acceptable. */ List<Path> findAssociatedFiles(BibEntry entry, List<Path> directories, List<String> extensions) throws IOException; }
647
31.4
138
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/FileFinders.java
package org.jabref.logic.util.io; public class FileFinders { /** * Creates a preconfigurated file finder based on the given AutoLink preferences. */ public static FileFinder constructFromConfiguration(AutoLinkPreferences autoLinkPreferences) { return switch (autoLinkPreferences.getCitationKeyDependency()) { case START -> new CitationKeyBasedFileFinder(false); case EXACT -> new CitationKeyBasedFileFinder(true); case REGEX -> new RegExpBasedFileFinder(autoLinkPreferences.getRegularExpression(), autoLinkPreferences.getKeywordSeparator()); }; } }
684
37.055556
133
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/FileHistory.java
package org.jabref.logic.util.io; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import javafx.collections.ModifiableObservableListBase; public class FileHistory extends ModifiableObservableListBase<Path> { private static final int HISTORY_SIZE = 8; private final List<Path> history; private FileHistory(List<Path> list) { history = new ArrayList<>(list); } @Override public Path get(int index) { return history.get(index); } public int size() { return history.size(); } @Override protected void doAdd(int index, Path element) { history.add(index, element); } @Override protected Path doSet(int index, Path element) { return history.set(index, element); } @Override protected Path doRemove(int index) { return history.remove(index); } /** * Adds the file to the top of the list. If it already is in the list, it is merely moved to the top. */ public void newFile(Path file) { removeItem(file); this.add(0, file); while (size() > HISTORY_SIZE) { history.remove(HISTORY_SIZE); } } public void removeItem(Path file) { this.remove(file); } public static FileHistory of(List<Path> list) { return new FileHistory(new ArrayList<>(list)); } }
1,398
21.564516
105
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/FileNameCleaner.java
package org.jabref.logic.util.io; /** * This class is based on http://stackoverflow.com/a/5626340/873282 * extended with LEFT CURLY BRACE and RIGHT CURLY BRACE * Replaces illegal characters in given file paths. * * Regarding the maximum length, see {@link FileUtil#getValidFileName(String)} */ public class FileNameCleaner { private FileNameCleaner() { } /** * Replaces illegal characters in given fileName by '_' * * @param badFileName the fileName to clean * @return a clean filename */ public static String cleanFileName(String badFileName) { StringBuilder cleanName = new StringBuilder(badFileName.length()); for (int i = 0; i < badFileName.length(); i++) { char c = badFileName.charAt(i); if (FileUtil.isCharLegal(c) && (c != '/') && (c != '\\')) { cleanName.append(c); } else { cleanName.append('_'); } } return cleanName.toString().trim(); } /** * Replaces illegal characters in given directoryName by '_'. * Directory name may contain directory separators, e.g. 'deep/in/a/tree'; these are left untouched. * * @param badFileName the fileName to clean * @return a clean filename */ public static String cleanDirectoryName(String badFileName) { StringBuilder cleanName = new StringBuilder(badFileName.length()); for (int i = 0; i < badFileName.length(); i++) { char c = badFileName.charAt(i); if (FileUtil.isCharLegal(c)) { cleanName.append(c); } else { cleanName.append('_'); } } return cleanName.toString().trim(); } }
1,748
31.388889
104
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/FileNameUniqueness.java
package org.jabref.logic.util.io; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.gui.DialogService; import org.jabref.logic.l10n.Localization; public class FileNameUniqueness { private static final Pattern DUPLICATE_MARK_PATTERN = Pattern.compile("(.*) \\(\\d+\\)"); /** * Returns a file name such that it does not match any existing files in targetDirectory * * @param targetDirectory The directory in which file name should be unique * @param fileName Suggested name for the file * @return a file name such that it does not match any existing files in targetDirectory */ public static String getNonOverWritingFileName(Path targetDirectory, String fileName) { Optional<String> extensionOptional = FileUtil.getFileExtension(fileName); // the suffix include the '.' , if extension is present Eg: ".pdf" String extensionSuffix; String fileNameWithoutExtension; if (extensionOptional.isPresent()) { extensionSuffix = '.' + extensionOptional.get(); fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.')); } else { extensionSuffix = ""; fileNameWithoutExtension = fileName; } String newFileName = fileName; int counter = 1; while (Files.exists(targetDirectory.resolve(newFileName))) { newFileName = fileNameWithoutExtension + " (" + counter + ")" + extensionSuffix; counter++; } return newFileName; } /** * This function decide whether the newly downloaded file has the same content with other files * It returns ture when the content is duplicate, while returns false if it is not * * @param directory The directory which saves the files (.pdf, for example) * @param fileName Suggest name for the newly downloaded file * @param dialogService To display the error and success message * @return true when the content of the newly downloaded file is same as the file with "similar" name, * false when there is no "similar" file name or the content is different from that of files with "similar" name * @throws IOException Fail when the file is not exist or something wrong when reading the file */ public static boolean isDuplicatedFile(Path directory, Path fileName, DialogService dialogService) throws IOException { Objects.requireNonNull(directory); Objects.requireNonNull(fileName); Objects.requireNonNull(dialogService); String extensionSuffix = FileUtil.getFileExtension(fileName).orElse(""); extensionSuffix = "".equals(extensionSuffix) ? extensionSuffix : "." + extensionSuffix; String newFilename = FileUtil.getBaseName(fileName) + extensionSuffix; String fileNameWithoutDuplicated = eraseDuplicateMarks(FileUtil.getBaseName(fileName)); String originalFileName = fileNameWithoutDuplicated + extensionSuffix; if (newFilename.equals(originalFileName)) { return false; } Path originalFile = directory.resolve(originalFileName); Path duplicateFile = directory.resolve(fileName); int counter = 1; while (Files.exists(originalFile)) { if (com.google.common.io.Files.equal(originalFile.toFile(), duplicateFile.toFile())) { if (duplicateFile.toFile().delete()) { dialogService.notify(Localization.lang("File '%1' is a duplicate of '%0'. Keeping '%0'", originalFileName, fileName)); } else { dialogService.notify(Localization.lang("File '%1' is a duplicate of '%0'. Keeping both due to deletion error", originalFileName, fileName)); } return true; } originalFileName = fileNameWithoutDuplicated + " (" + counter + ")" + extensionSuffix; counter++; if (newFilename.equals(originalFileName)) { return false; } originalFile = directory.resolve(originalFileName); } return false; } /** * This is the opposite function of getNonOverWritingFileName * It will recover the file name to origin if it has duplicate mark such as " (1)" * change the String whose format is "xxxxxx (number)" into "xxxxxx", while return the same String when it does not match the format * This is the opposite function of getNonOverWritingFileName * * @param fileName Suggested name for the file without extensionSuffix, if it has duplicate file name with other file, it will end with something like " (1)" * @return Suggested name for the file without extensionSuffix and duplicate marks such as " (1)" */ public static String eraseDuplicateMarks(String fileName) { Matcher m = DUPLICATE_MARK_PATTERN.matcher(fileName); return m.find() ? fileName.substring(0, fileName.lastIndexOf('(') - 1) : fileName; } }
5,265
42.520661
161
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/FileUtil.java
package org.jabref.logic.util.io; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.Stack; import java.util.Vector; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.citationkeypattern.BracketedPattern; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.OptionalUtil; import org.jabref.preferences.FilePreferences; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The idea of this class is to add general functionality that could possibly even in the * <a href="https://en.wikipedia.org/wiki/Non-blocking_I/O_(Java)">Java NIO package</a>, * such as getting/adding file extension etc. * * This class is the "successor" of {@link FileHelper}. In case you miss something here, * please look at {@link FileHelper} and migrate the functionality to here. */ public class FileUtil { public static final boolean IS_POSIX_COMPLIANT = FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); public static final int MAXIMUM_FILE_NAME_LENGTH = 255; private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class); /** * MUST ALWAYS BE A SORTED ARRAY because it is used in a binary search */ // @formatter:off private static final int[] ILLEGAL_CHARS = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 34, 42, 58, // ":" 60, 62, 63, 123, 124, 125 }; // @formatter:on private FileUtil() { } /** * Returns the extension of a file name or Optional.empty() if the file does not have one (no "." in name). * * @return the extension (without leading dot), trimmed and in lowercase. */ public static Optional<String> getFileExtension(String fileName) { int dotPosition = fileName.lastIndexOf('.'); if ((dotPosition > 0) && (dotPosition < (fileName.length() - 1))) { return Optional.of(fileName.substring(dotPosition + 1).trim().toLowerCase(Locale.ROOT)); } else { return Optional.empty(); } } /** * Returns the extension of a file or Optional.empty() if the file does not have one (no . in name). * * @return the extension (without leading dot), trimmed and in lowercase. */ public static Optional<String> getFileExtension(Path file) { return getFileExtension(file.getFileName().toString()); } /** * Returns the name part of a file name (i.e., everything in front of last "."). */ public static String getBaseName(String fileNameWithExtension) { return com.google.common.io.Files.getNameWithoutExtension(fileNameWithExtension); } /** * Returns the name part of a file name (i.e., everything in front of last "."). */ public static String getBaseName(Path fileNameWithExtension) { return getBaseName(fileNameWithExtension.getFileName().toString()); } /** * Returns a valid filename for most operating systems. * * Currently, only the length is restricted to 255 chars, see MAXIMUM_FILE_NAME_LENGTH. * * For "real" cleaning, {@link FileNameCleaner#cleanFileName(String)} should be used. */ public static String getValidFileName(String fileName) { String nameWithoutExtension = getBaseName(fileName); if (nameWithoutExtension.length() > MAXIMUM_FILE_NAME_LENGTH) { Optional<String> extension = getFileExtension(fileName); String shortName = nameWithoutExtension.substring(0, MAXIMUM_FILE_NAME_LENGTH - extension.map(s -> s.length() + 1).orElse(0)); LOGGER.info(String.format("Truncated the too long filename '%s' (%d characters) to '%s'.", fileName, fileName.length(), shortName)); return extension.map(s -> shortName + "." + s).orElse(shortName); } return fileName; } /** * Adds an extension to the given file name. The original extension is not replaced. That means, "demo.bib", ".sav" * gets "demo.bib.sav" and not "demo.sav" * * <emph>Warning! If "ext" is passed, this is literally added. Thus addExtension("tmp.txt", "ext") leads to "tmp.txtext"</emph> * * @param path the path to add the extension to * @param extension the extension to add * @return the with the modified file name */ public static Path addExtension(Path path, String extension) { return path.resolveSibling(path.getFileName() + extension); } /** * Looks for the unique directory, if any, different to the provided paths * * @param paths List of paths as Strings * @param comparePath The to be tested path */ public static Optional<String> getUniquePathDirectory(List<String> paths, Path comparePath) { String fileName = comparePath.getFileName().toString(); List<String> uniquePathParts = uniquePathSubstrings(paths); return uniquePathParts.stream() .filter(part -> comparePath.toString().contains(part) && !part.equals(fileName) && part.contains(File.separator)) .findFirst() .map(part -> part.substring(0, part.lastIndexOf(File.separator))); } /** * Looks for the shortest unique path of the in a list of paths * * @param paths List of paths as Strings * @param comparePath The to be shortened path */ public static Optional<String> getUniquePathFragment(List<String> paths, Path comparePath) { return uniquePathSubstrings(paths).stream() .filter(part -> comparePath.toString().contains(part)) .sorted(Comparator.comparingInt(String::length).reversed()) .findFirst(); } /** * Creates the minimal unique path substring for each file among multiple file paths. * * @param paths the file paths * @return the minimal unique path substring for each file path */ public static List<String> uniquePathSubstrings(List<String> paths) { List<Stack<String>> stackList = new ArrayList<>(paths.size()); // prepare data structures for (String path : paths) { List<String> directories = Arrays.asList(path.split(Pattern.quote(File.separator))); Stack<String> stack = new Stack<>(); stack.addAll(directories); stackList.add(stack); } List<String> pathSubstrings = new ArrayList<>(Collections.nCopies(paths.size(), "")); // compute the shortest folder substrings while (!stackList.stream().allMatch(Vector::isEmpty)) { for (int i = 0; i < stackList.size(); i++) { String tempString = pathSubstrings.get(i); if (tempString.isEmpty() && !stackList.get(i).isEmpty()) { pathSubstrings.set(i, stackList.get(i).pop()); } else if (!stackList.get(i).isEmpty()) { pathSubstrings.set(i, stackList.get(i).pop() + File.separator + tempString); } } for (int i = 0; i < stackList.size(); i++) { String tempString = pathSubstrings.get(i); if (Collections.frequency(pathSubstrings, tempString) == 1) { stackList.get(i).clear(); } } } return pathSubstrings; } /** * Copies a file. * * @param pathToSourceFile Path Source file * @param pathToDestinationFile Path Destination file * @param replaceExisting boolean Determines whether the copy goes on even if the file exists. * @return boolean Whether the copy succeeded, or was stopped due to the file already existing. */ public static boolean copyFile(Path pathToSourceFile, Path pathToDestinationFile, boolean replaceExisting) { // Check if the file already exists. if (!Files.exists(pathToSourceFile)) { LOGGER.error("Path to the source file doesn't exist."); return false; } if (Files.exists(pathToDestinationFile) && !replaceExisting) { LOGGER.error("Path to the destination file exists but the file shouldn't be replaced."); return false; } try { // Preserve Hard Links with OpenOption defaults included for clarity Files.write(pathToDestinationFile, Files.readAllBytes(pathToSourceFile), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); return true; } catch (IOException e) { LOGGER.error("Copying Files failed.", e); return false; } } /** * Converts an absolute file to a relative one, if possible. Returns the parameter file itself if no shortening is * possible. * <p> * This method works correctly only if directories are sorted decent in their length i.e. * /home/user/literature/important before /home/user/literature. * * @param file the file to be shortened * @param directories directories to check */ public static Path relativize(Path file, List<Path> directories) { if (!file.isAbsolute()) { return file; } for (Path directory : directories) { if (file.startsWith(directory)) { return directory.relativize(file); } } return file; } /** * Returns the list of linked files. The files have the absolute filename * * @param bes list of BibTeX entries * @param fileDirs list of directories to try for expansion * @return list of files. May be empty */ public static List<Path> getListOfLinkedFiles(List<BibEntry> bes, List<Path> fileDirs) { Objects.requireNonNull(bes); Objects.requireNonNull(fileDirs); return bes.stream() .flatMap(entry -> entry.getFiles().stream()) .flatMap(file -> OptionalUtil.toStream(file.findIn(fileDirs))) .collect(Collectors.toList()); } /** * Determines filename provided by an entry in a database * * @param database the database, where the entry is located * @param entry the entry to which the file should be linked to * @param fileNamePattern the filename pattern * @return a suggested fileName */ public static String createFileNameFromPattern(BibDatabase database, BibEntry entry, String fileNamePattern) { String targetName = BracketedPattern.expandBrackets(fileNamePattern, ';', entry, database); if (targetName.isEmpty()) { targetName = entry.getCitationKey().orElse("default"); } // Removes illegal characters from filename targetName = FileNameCleaner.cleanFileName(targetName); return targetName; } /** * Determines directory name provided by an entry in a database * * @param database the database, where the entry is located * @param entry the entry to which the directory should be linked to * @param directoryNamePattern the dirname pattern * @return a suggested dirName */ public static String createDirNameFromPattern(BibDatabase database, BibEntry entry, String directoryNamePattern) { String targetName = BracketedPattern.expandBrackets(directoryNamePattern, ';', entry, database); if (targetName.isEmpty()) { return targetName; } // Removes illegal characters from directory name targetName = FileNameCleaner.cleanDirectoryName(targetName); return targetName; } /** * Finds a file inside a directory structure. Will also look for the file inside nested directories. * * @param filename the name of the file that should be found * @param rootDirectory the rootDirectory that will be searched * @return the path to the first file that matches the defined conditions */ public static Optional<Path> findSingleFileRecursively(String filename, Path rootDirectory) { try (Stream<Path> pathStream = Files.walk(rootDirectory)) { return pathStream .filter(Files::isRegularFile) .filter(f -> f.getFileName().toString().equals(filename)) .findFirst(); } catch (UncheckedIOException | IOException ex) { LOGGER.error("Error trying to locate the file " + filename + " inside the directory " + rootDirectory); } return Optional.empty(); } public static Optional<Path> find(final BibDatabaseContext databaseContext, String fileName, FilePreferences filePreferences) { Objects.requireNonNull(fileName, "fileName"); return find(fileName, databaseContext.getFileDirectories(filePreferences)); } /** * Converts a relative filename to an absolute one, if necessary. Returns * an empty optional if the file does not exist. * <p> * Will look in each of the given directories starting from the beginning and * returning the first found file to match if any. */ public static Optional<Path> find(String fileName, List<Path> directories) { if (directories.isEmpty()) { // Fallback, if no directories to resolve are passed Path path = Path.of(fileName); if (path.isAbsolute()) { return Optional.of(path); } else { return Optional.empty(); } } return directories.stream() .flatMap(directory -> find(fileName, directory).stream()) .findFirst(); } /** * Converts a relative filename to an absolute one, if necessary. * * @param fileName the filename (e.g., a .pdf file), may contain path separators * @param directory the directory which should be search starting point * * @returns an empty optional if the file does not exist, otherwise, the absolute path */ public static Optional<Path> find(String fileName, Path directory) { Objects.requireNonNull(fileName); Objects.requireNonNull(directory); if (detectBadFileName(fileName)) { LOGGER.error("Invalid characters in path for file {} ", fileName); return Optional.empty(); } // Explicitly check for an empty string, as File.exists returns true on that empty path, because it maps to the default jar location. // If we then call toAbsoluteDir, it would always return the jar-location folder. This is not what we want here. if (fileName.isEmpty()) { return Optional.of(directory); } Path resolvedFile = directory.resolve(fileName); if (Files.exists(resolvedFile)) { return Optional.of(resolvedFile); } // get the furthest path element from root and check if our filename starts with the same name // workaround for old JabRef behavior String furthestDirFromRoot = directory.getFileName().toString(); if (fileName.startsWith(furthestDirFromRoot)) { resolvedFile = directory.resolveSibling(fileName); } if (Files.exists(resolvedFile)) { return Optional.of(resolvedFile); } else { return Optional.empty(); } } /** * Finds a file inside a list of directory structures. Will also look for the file inside nested directories. * * @param filename the name of the file that should be found * @param directories the directories that will be searched * @return a list including all found paths to files that match the defined conditions */ public static List<Path> findListOfFiles(String filename, List<Path> directories) { List<Path> files = new ArrayList<>(); for (Path dir : directories) { FileUtil.find(filename, dir).ifPresent(files::add); } return files; } /** * Creates a string representation of the given path that should work on all systems. This method should be used * when a path needs to be stored in the bib file or preferences. */ public static String toPortableString(Path path) { return path.toString() .replace('\\', '/'); } /** * Test if the file is a bib file by simply checking the extension to be ".bib" * * @param file The file to check * @return True if file extension is ".bib", false otherwise */ public static boolean isBibFile(Path file) { return getFileExtension(file).filter("bib"::equals).isPresent(); } /** * Test if the file is a pdf file by simply checking the extension to be ".pdf" * * @param file The file to check * @return True if file extension is ".pdf", false otherwise */ public static boolean isPDFFile(Path file) { return getFileExtension(file).filter("pdf"::equals).isPresent(); } /** * @return Path of current panel database directory or the standard working directory in case the database was not saved yet */ public static Path getInitialDirectory(BibDatabaseContext databaseContext, Path workingDirectory) { return databaseContext.getDatabasePath().map(Path::getParent).orElse(workingDirectory); } /** * Detect illegal characters in given filename. * * See also {@link org.jabref.logic.util.io.FileNameCleaner#cleanFileName} * * @param fileName the fileName to detect * @return Boolean whether there is an illegal name. */ public static boolean detectBadFileName(String fileName) { // fileName could be a path, we want to check the fileName only (and don't care about the path) // Reason: Handling of "c:\temp.pdf" is difficult, because ":" is an illegal character in the file name, // but a perfectly legal one in the path at this position try { fileName = Path.of(fileName).getFileName().toString(); } catch (InvalidPathException e) { // in case the internal method cannot parse the path, it is surely illegal return true; } for (int i = 0; i < fileName.length(); i++) { char c = fileName.charAt(i); if (!isCharLegal(c)) { return true; } } return false; } public static boolean isCharLegal(char c) { return Arrays.binarySearch(ILLEGAL_CHARS, c) < 0; } }
19,556
38.669371
144
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/RegExpBasedFileFinder.java
package org.jabref.logic.util.io; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.citationkeypattern.BracketedPattern; import org.jabref.model.entry.BibEntry; import org.jabref.model.strings.StringUtil; class RegExpBasedFileFinder implements FileFinder { private static final String EXT_MARKER = "__EXTENSION__"; private static final Pattern ESCAPE_PATTERN = Pattern.compile("([^\\\\])\\\\([^\\\\])"); private final String regExp; private final Character keywordDelimiter; /** * @param regExp The expression deciding which names are acceptable. */ RegExpBasedFileFinder(String regExp, Character keywordDelimiter) { this.regExp = regExp; this.keywordDelimiter = keywordDelimiter; } /** * Creates a Pattern that matches the file name corresponding to the last element of {@code fileParts} with any bracketed patterns expanded. * * @throws IOException throws an IOException if a PatternSyntaxException occurs */ private Pattern createFileNamePattern(String[] fileParts, String extensionRegExp, BibEntry entry) throws IOException { // Protect the extension marker so that it isn't treated as a bracketed pattern String filePart = fileParts[fileParts.length - 1].replace("[extension]", EXT_MARKER); // We need to supply a custom function to deal with the content of a bracketed expression and expandBracketContent is the default function Function<String, String> expandBracket = BracketedPattern.expandBracketContent(keywordDelimiter, entry, null); // but, we want to post-process the expanded content so that it can be used as a regex for finding a file name Function<String, String> bracketToFileNameRegex = expandBracket.andThen(RegExpBasedFileFinder::toFileNameRegex); String expandedBracketAsFileNameRegex = BracketedPattern.expandBrackets(filePart, bracketToFileNameRegex); String fileNamePattern = expandedBracketAsFileNameRegex .replaceAll(EXT_MARKER, extensionRegExp) // Replace the extension marker .replaceAll("\\\\\\\\", "\\\\"); try { return Pattern.compile('^' + fileNamePattern + '$', Pattern.CASE_INSENSITIVE); } catch (PatternSyntaxException e) { throw new IOException(String.format("There is a syntax error in the regular expression %s used to search for files", fileNamePattern), e); } } /** * Helper method for both exact matching (if the file name were not created by JabRef) and cleaned file name matching. * * @param expandedContent the expanded content of a bracketed expression * @return a String representation of a regex matching the expanded content and the expanded content cleaned for file name use */ private static String toFileNameRegex(String expandedContent) { var cleanedContent = FileNameCleaner.cleanFileName(expandedContent); return expandedContent.equals(cleanedContent) ? Pattern.quote(expandedContent) : "(" + Pattern.quote(expandedContent) + ")|(" + Pattern.quote(cleanedContent) + ")"; } /** * Method for searching for files using regexp. A list of extensions and directories can be * given. * * @param entry The entry to search for. * @param extensions The extensions that are acceptable. * @param directories The root directories to search. * @return A list of files paths matching the given criteria. */ @Override public List<Path> findAssociatedFiles(BibEntry entry, List<Path> directories, List<String> extensions) throws IOException { String extensionRegExp = '(' + String.join("|", extensions) + ')'; return findFile(entry, directories, extensionRegExp); } /** * Searches the given directory and filename pattern for a file for the * BibTeX entry. * * Used to fix: * * http://sourceforge.net/tracker/index.php?func=detail&aid=1503410&group_id=92314&atid=600309 * * Requirements: * - Be able to find the associated PDF in a set of given directories. * - Be able to return a relative path or absolute path. * - Be fast. * - Allow for flexible naming schemes in the PDFs. * * Syntax scheme for file: * <ul> * <li>* Any subDir</li> * <li>** Any subDir (recursive)</li> * <li>[key] Key from BibTeX file and database</li> * <li>.* Anything else is taken to be a Regular expression.</li> * </ul> * * @param entry non-null * @param dirs A set of root directories to start the search from. Paths are * returned relative to these directories if relative is set to * true. These directories will not be expanded or anything. Use * the file attribute for this. * @return Will return the first file found to match the given criteria or * null if none was found. */ private List<Path> findFile(BibEntry entry, List<Path> dirs, String extensionRegExp) throws IOException { List<Path> res = new ArrayList<>(); for (Path directory : dirs) { res.addAll(findFile(entry, directory, regExp, extensionRegExp)); } return res; } /** * The actual work-horse. Will find absolute filepaths starting from the * given directory using the given regular expression string for search. */ private List<Path> findFile(final BibEntry entry, final Path directory, final String file, final String extensionRegExp) throws IOException { List<Path> resultFiles = new ArrayList<>(); String fileName = file; Path actualDirectory; if (fileName.startsWith("/")) { actualDirectory = Path.of("."); fileName = fileName.substring(1); } else { actualDirectory = directory; } // Escape handling... Matcher m = ESCAPE_PATTERN.matcher(fileName); StringBuilder s = new StringBuilder(); while (m.find()) { m.appendReplacement(s, m.group(1) + '/' + m.group(2)); } m.appendTail(s); fileName = s.toString(); String[] fileParts = fileName.split("/"); if (fileParts.length == 0) { return resultFiles; } for (int index = 0; index < (fileParts.length - 1); index++) { String dirToProcess = fileParts[index]; if (dirToProcess.matches("^.:$")) { // Windows Drive Letter actualDirectory = Path.of(dirToProcess + '/'); continue; } if (".".equals(dirToProcess)) { // Stay in current directory continue; } if ("..".equals(dirToProcess)) { actualDirectory = actualDirectory.getParent(); continue; } if ("*".equals(dirToProcess)) { // Do for all direct subdirs File[] subDirs = actualDirectory.toFile().listFiles(); if (subDirs != null) { String restOfFileString = StringUtil.join(fileParts, "/", index + 1, fileParts.length); for (File subDir : subDirs) { if (subDir.isDirectory()) { resultFiles.addAll(findFile(entry, subDir.toPath(), restOfFileString, extensionRegExp)); } } } } // Do for all direct and indirect subdirs if ("**".equals(dirToProcess)) { String restOfFileString = StringUtil.join(fileParts, "/", index + 1, fileParts.length); final Path rootDirectory = actualDirectory; try (Stream<Path> pathStream = Files.walk(actualDirectory)) { // We only want to transverse directory (and not the current one; this is already done below) for (Path path : pathStream.filter(element -> isSubDirectory(rootDirectory, element)).collect(Collectors.toList())) { resultFiles.addAll(findFile(entry, path, restOfFileString, extensionRegExp)); } } catch (UncheckedIOException ioe) { throw ioe.getCause(); } } // End process directory information } // Last step: check if the given file can be found in this directory Pattern toMatch = createFileNamePattern(fileParts, extensionRegExp, entry); BiPredicate<Path, BasicFileAttributes> matcher = (path, attributes) -> toMatch.matcher(path.getFileName().toString()).matches(); try (Stream<Path> pathStream = Files.find(actualDirectory, 1, matcher, FileVisitOption.FOLLOW_LINKS)) { resultFiles.addAll(pathStream.collect(Collectors.toList())); } catch (UncheckedIOException uncheckedIOException) { // Previously, an empty list were returned here on both IOException and UncheckedIOException throw uncheckedIOException.getCause(); } return resultFiles; } private boolean isSubDirectory(Path rootDirectory, Path path) { return !rootDirectory.equals(path) && Files.isDirectory(path); } }
9,787
43.694064
150
java
null
jabref-main/src/main/java/org/jabref/logic/util/io/XMLUtil.java
package org.jabref.logic.util.io; import java.io.StringWriter; import java.util.AbstractList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.RandomAccess; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.jabref.architecture.AllowedToUseStandardStreams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Currently used for debugging only */ @AllowedToUseStandardStreams("Used for debugging only") public class XMLUtil { private static final Logger LOGGER = LoggerFactory.getLogger(XMLUtil.class); private XMLUtil() { } /** * Prints out the document to standard out. Used to generate files for test cases. */ public static void printDocument(Document doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(domSource, result); System.out.println(writer); } catch (TransformerException ex) { LOGGER.error("", ex); } } public static List<Node> asList(NodeList n) { return n.getLength() == 0 ? Collections.emptyList() : new NodeListWrapper(n); } /** * Gets the content of a subnode. * For example, * <item> * <nodeName>content</nodeName> * </item> */ public static Optional<String> getNodeContent(Node item, String nodeName) { if (item.getNodeType() != Node.ELEMENT_NODE) { return Optional.empty(); } NodeList metadata = ((Element) item).getElementsByTagName(nodeName); if (metadata.getLength() == 1) { return Optional.ofNullable(metadata.item(0).getTextContent()); } else { return Optional.empty(); } } /** * Gets the content of an attribute. * For example, * <item attributeName="content" /> */ public static Optional<String> getAttributeContent(Node item, String attributeName) { NamedNodeMap attributes = item.getAttributes(); return Optional.ofNullable(attributes.getNamedItem(attributeName)).map(Node::getTextContent); } /** * Gets a list of subnodes with the specified tag name. * For example, * <item> * <node>first hit</node> * <node>second hit</node> * </item> */ public static List<Node> getNodesByName(Node item, String nodeName) { if (item.getNodeType() != Node.ELEMENT_NODE) { return Collections.emptyList(); } NodeList nodes = ((Element) item).getElementsByTagName(nodeName); return asList(nodes); } /** * Gets a the first subnode with the specified tag name. * For example, * <item> * <node>hit</node> * <node>second hit, but not returned</node> * </item> */ public static Optional<Node> getNode(Node item, String nodeName) { return getNodesByName(item, nodeName).stream().findFirst(); } // Wrapper to make NodeList iterable, // taken from <a href="http://stackoverflow.com/questions/19589231/can-i-iterate-through-a-nodelist-using-for-each-in-java">StackOverflow Answer</a>. private static final class NodeListWrapper extends AbstractList<Node> implements RandomAccess { private final NodeList list; NodeListWrapper(NodeList list) { this.list = list; } @Override public Node get(int index) { return list.item(index); } @Override public int size() { return list.getLength(); } } }
4,265
29.913043
153
java
null
jabref-main/src/main/java/org/jabref/logic/util/strings/HTMLUnicodeConversionMaps.java
package org.jabref.logic.util.strings; import java.util.HashMap; import java.util.Map; public class HTMLUnicodeConversionMaps { // most of the LaTeX commands can be read at http://en.wikibooks.org/wiki/LaTeX/Accents // The symbols can be seen at http://www.fileformat.info/info/unicode/char/a4/index.htm. Replace "a4" with the U+ number // http://detexify.kirelabs.org/classify.html and http://www.ctan.org/tex-archive/info/symbols/comprehensive/ might help to find the right LaTeX command // http://llg.cubic.org/docs/ent2latex.html and http://www.w3.org/TR/xml-entity-names/byalpha.html are also useful public static final Map<String, String> HTML_LATEX_CONVERSION_MAP = new HashMap<>(); public static final Map<Integer, String> ESCAPED_ACCENTS = new HashMap<>(); public static final Map<String, String> UNICODE_ESCAPED_ACCENTS = new HashMap<>(); public static final Map<Integer, String> NUMERICAL_LATEX_CONVERSION_MAP = new HashMap<>(); public static final Map<String, String> UNICODE_LATEX_CONVERSION_MAP = new HashMap<>(); public static final Map<String, String> LATEX_HTML_CONVERSION_MAP = new HashMap<>(); public static final Map<String, String> LATEX_UNICODE_CONVERSION_MAP = new HashMap<>(); /* Portions © International Organization for Standardization 1986: Permission to copy in any form is granted for use with conforming SGML systems and applications as defined in ISO 8879, provided this notice is included in all copies. */ // as well as http://www.w3.org/Math/characters/unicode.xml // An array of arrays of strings in the format: // {"decimal number of HTML entity", "text HTML entity", "corresponding LaTeX command"} // Leaving a field empty is OK as it then will not be included private static final String[][] CONVERSION_LIST = new String[][] {{"160", "nbsp", "{~}"}, // no-break space = non-breaking space, // U+00A0 ISOnum {"161", "iexcl", "{\\textexclamdown}"}, // inverted exclamation mark, U+00A1 ISOnum {"162", "cent", "{\\textcent}"}, // cent sign, U+00A2 ISOnum {"163", "pound", "{\\pounds}"}, // pound sign, U+00A3 ISOnum {"164", "curren", "{\\textcurrency}"}, // currency sign, U+00A4 ISOnum {"165", "yen", "{\\textyen}"}, // yen sign = yuan sign, U+00A5 ISOnum {"166", "brvbar", "{\\textbrokenbar}"}, // broken bar = broken vertical bar, // U+00A6 ISOnum {"167", "sect", "{{\\S}}"}, // section sign, U+00A7 ISOnum {"168", "uml", "{\\\"{}}"}, // diaeresis = spacing diaeresis, // U+00A8 ISOdia {"169", "copy", "{\\copyright}"}, // copyright sign, U+00A9 ISOnum {"170", "ordf", "{\\textordfeminine}"}, // feminine ordinal indicator, U+00AA ISOnum {"171", "laquo", "{\\guillemotleft}"}, // left-pointing double angle quotation mark // = left pointing guillemet, U+00AB ISOnum {"172", "not", "$\\neg$"}, // not sign, U+00AC ISOnum {"173", "shy", "\\-"}, // soft hyphen = discretionary hyphen, // U+00AD ISOnum {"174", "reg", "{\\textregistered}"}, // registered sign = registered trade mark sign, // U+00AE ISOnum {"175", "macr", "{\\={}}"}, // macron = spacing macron = overline // = APL overbar, U+00AF ISOdia {"176", "deg", "{$^{\\circ}$}"}, // degree sign, U+00B0 ISOnum {"177", "plusmn", "$\\pm$"}, // plus-minus sign = plus-or-minus sign, // U+00B1 ISOnum {"178", "sup2", "\\textsuperscript{2}"}, // superscript two = superscript digit two // = squared, U+00B2 ISOnum {"179", "sup3", "\\textsuperscript{3}"}, // superscript three = superscript digit three // = cubed, U+00B3 ISOnum {"180", "acute", "{\\'{}}"}, // acute accent = spacing acute, // U+00B4 ISOdia {"181", "micro", "$\\mu$"}, // micro sign, U+00B5 ISOnum {"", "mu", "$\\mu$"}, // micro sign, U+00B5 ISOnum {"182", "para", "{{\\P}}"}, // pilcrow sign = paragraph sign, // U+00B6 ISOnum {"183", "middot", "$\\cdot$"}, // middle dot = Georgian comma // = Greek middle dot, U+00B7 ISOnum {"184", "cedil", "{\\c{}}"}, // cedilla = spacing cedilla, U+00B8 ISOdia {"185", "sup1", "\\textsuperscript{1}"}, // superscript one = superscript digit one, // U+00B9 ISOnum {"186", "ordm", "{\\textordmasculine}"}, // masculine ordinal indicator, // U+00BA ISOnum {"187", "raquo", "{\\guillemotright}"}, // right-pointing double angle quotation mark // = right pointing guillemet, U+00BB ISOnum {"188", "frac14", "$\\sfrac{1}{4}$"}, // vulgar fraction one quarter // = fraction one quarter, U+00BC ISOnum {"189", "frac12", "$\\sfrac{1}{2}$"}, // vulgar fraction one half // = fraction one half, U+00BD ISOnum {"190", "frac34", "$\\sfrac{3}{4}$"}, // vulgar fraction three quarters // = fraction three quarters, U+00BE ISOnum {"191", "iquest", "{\\textquestiondown}"}, // inverted question mark // = turned question mark, U+00BF ISOnum {"192", "Agrave", "{{\\`{A}}}"}, // latin capital letter A with grave // = latin capital letter A grave, // U+00C0 ISOlat1 {"193", "Aacute", "{{\\'{A}}}"}, // latin capital letter A with acute, // U+00C1 ISOlat1 {"194", "Acirc", "{{\\^{A}}}"}, // latin capital letter A with circumflex, // U+00C2 ISOlat1 {"195", "Atilde", "{{\\~{A}}}"}, // latin capital letter A with tilde, // U+00C3 ISOlat1 {"196", "Auml", "{{\\\"{A}}}"}, // latin capital letter A with diaeresis, // U+00C4 ISOlat1 {"197", "Aring", "{{\\AA}}"}, // latin capital letter A with ring above // = latin capital letter A ring, // U+00C5 ISOlat1 {"198", "AElig", "{{\\AE}}"}, // latin capital letter AE // = latin capital ligature AE, // U+00C6 ISOlat1 {"199", "Ccedil", "{{\\c{C}}}"}, // latin capital letter C with cedilla, // U+00C7 ISOlat1 {"200", "Egrave", "{{\\`{E}}}"}, // latin capital letter E with grave, // U+00C8 ISOlat1 {"201", "Eacute", "{{\\'{E}}}"}, // latin capital letter E with acute, // U+00C9 ISOlat1 {"202", "Ecirc", "{{\\^{E}}}"}, // latin capital letter E with circumflex, // U+00CA ISOlat1 {"203", "Euml", "{{\\\"{E}}}"}, // latin capital letter E with diaeresis, // U+00CB ISOlat1 {"204", "Igrave", "{{\\`{I}}}"}, // latin capital letter I with grave, // U+00CC ISOlat1 {"205", "Iacute", "{{\\'{I}}}"}, // latin capital letter I with acute, // U+00CD ISOlat1 {"206", "Icirc", "{{\\^{I}}}"}, // latin capital letter I with circumflex, // U+00CE ISOlat1 {"207", "Iuml", "{{\\\"{I}}}"}, // latin capital letter I with diaeresis, // U+00CF ISOlat1 {"208", "ETH", "{{\\DH}}"}, // latin capital letter ETH, U+00D0 ISOlat1 {"209", "Ntilde", "{{\\~{N}}}"}, // latin capital letter N with tilde, // U+00D1 ISOlat1 {"210", "Ograve", "{{\\`{O}}}"}, // latin capital letter O with grave, // U+00D2 ISOlat1 {"211", "Oacute", "{{\\'{O}}}"}, // latin capital letter O with acute, // U+00D3 ISOlat1 {"212", "Ocirc", "{{\\^{O}}}"}, // latin capital letter O with circumflex, // U+00D4 ISOlat1 {"213", "Otilde", "{{\\~{O}}}"}, // latin capital letter O with tilde, // U+00D5 ISOlat1 {"214", "Ouml", "{{\\\"{O}}}"}, // latin capital letter O with diaeresis, // U+00D6 ISOlat1 {"215", "times", "$\\times$"}, // multiplication sign, U+00D7 ISOnum {"216", "Oslash", "{{\\O}}"}, // latin capital letter O with stroke // = latin capital letter O slash, // U+00D8 ISOlat1 {"217", "Ugrave", "{{\\`{U}}}"}, // latin capital letter U with grave, // U+00D9 ISOlat1 {"218", "Uacute", "{{\\'{U}}}"}, // latin capital letter U with acute, // U+00DA ISOlat1 {"219", "Ucirc", "{{\\^{U}}}"}, // latin capital letter U with circumflex, // U+00DB ISOlat1 {"220", "Uuml", "{{\\\"{U}}}"}, // latin capital letter U with diaeresis, // U+00DC ISOlat1 {"221", "Yacute", "{{\\'{Y}}}"}, // latin capital letter Y with acute, // U+00DD ISOlat1 {"222", "THORN", "{{\\TH}}"}, // latin capital letter THORN, // U+00DE ISOlat1 {"223", "szlig", "{\\ss}"}, // latin small letter sharp s = ess-zed, // U+00DF ISOlat1 {"224", "agrave", "{\\`{a}}"}, // latin small letter a with grave // = latin small letter a grave, // U+00E0 ISOlat1 {"225", "aacute", "{\\'{a}}"}, // latin small letter a with acute, // U+00E1 ISOlat1 {"226", "acirc", "{\\^{a}}"}, // latin small letter a with circumflex, // U+00E2 ISOlat1 {"227", "atilde", "{\\~{a}}"}, // latin small letter a with tilde, // U+00E3 ISOlat1 {"228", "auml", "{\\\"{a}}"}, // latin small letter a with diaeresis, // U+00E4 ISOlat1 {"229", "aring", "{{\\aa}}"}, // latin small letter a with ring above // = latin small letter a ring, // U+00E5 ISOlat1 {"230", "aelig", "{\\ae}"}, // latin small letter ae // = latin small ligature ae, U+00E6 ISOlat1 {"231", "ccedil", "{\\c{c}}"}, // latin small letter c with cedilla, // U+00E7 ISOlat1 {"232", "egrave", "{\\`{e}}"}, // latin small letter e with grave, // U+00E8 ISOlat1 {"233", "eacute", "{\\'{e}}"}, // latin small letter e with acute, // U+00E9 ISOlat1 {"234", "ecirc", "{\\^{e}}"}, // latin small letter e with circumflex, // U+00EA ISOlat1 {"235", "euml", "{\\\"{e}}"}, // latin small letter e with diaeresis, // U+00EB ISOlat1 {"236", "igrave", "{\\`{i}}"}, // latin small letter i with grave, // U+00EC ISOlat1 {"237", "iacute", "{\\'{i}}"}, // latin small letter i with acute, // U+00ED ISOlat1 {"238", "icirc", "{\\^{i}}"}, // latin small letter i with circumflex, // U+00EE ISOlat1 {"239", "iuml", "{\\\"{i}}"}, // latin small letter i with diaeresis, // U+00EF ISOlat1 {"240", "eth", "{\\dh}"}, // latin small letter eth, U+00F0 ISOlat1 {"241", "ntilde", "{\\~{n}}"}, // latin small letter n with tilde, // U+00F1 ISOlat1 {"242", "ograve", "{\\`{o}}"}, // latin small letter o with grave, // U+00F2 ISOlat1 {"243", "oacute", "{\\'{o}}"}, // latin small letter o with acute, // U+00F3 ISOlat1 {"244", "ocirc", "{\\^{o}}"}, // latin small letter o with circumflex, // U+00F4 ISOlat1 {"245", "otilde", "{\\~{o}}"}, // latin small letter o with tilde, // U+00F5 ISOlat1 {"246", "ouml", "{\\\"{o}}"}, // latin small letter o with diaeresis, // U+00F6 ISOlat1 {"247", "divide", "$\\div$"}, // division sign, U+00F7 ISOnum {"248", "oslash", "{\\o}"}, // latin small letter o with stroke, // = latin small letter o slash, // U+00F8 ISOlat1 {"249", "ugrave", "{\\`{u}}"}, // latin small letter u with grave, // U+00F9 ISOlat1 {"250", "uacute", "{\\'{u}}"}, // latin small letter u with acute, // U+00FA ISOlat1 {"251", "ucirc", "{\\^{u}}"}, // latin small letter u with circumflex, // U+00FB ISOlat1 {"252", "uuml", "{\\\"{u}}"}, // latin small letter u with diaeresis, // U+00FC ISOlat1 {"253", "yacute", "{\\'{y}}"}, // latin small letter y with acute, // U+00FD ISOlat1 {"254", "thorn", "{\\th}"}, // latin small letter thorn, // U+00FE ISOlat1 {"255", "yuml", "{\\\"{y}}"}, // latin small letter y with diaeresis, // U+00FF ISOlat1 /* Greek */ {"913", "Alpha", "{{$\\Alpha$}}"}, // greek capital letter alpha, U+0391 {"914", "Beta", "{{$\\Beta$}}"}, // greek capital letter beta, U+0392 {"915", "Gamma", "{{$\\Gamma$}}"}, // greek capital letter gamma, // U+0393 ISOgrk3 {"916", "Delta", "{{$\\Delta$}}"}, // greek capital letter delta, // U+0394 ISOgrk3 {"917", "Epsilon", "{{$\\Epsilon$}}"}, // greek capital letter epsilon, U+0395 {"918", "Zeta", "{{$\\Zeta$}}"}, // greek capital letter zeta, U+0396 {"919", "Eta", "{{$\\Eta$}}"}, // greek capital letter eta, U+0397 {"920", "Theta", "{{$\\Theta$}}"}, // greek capital letter theta, // U+0398 ISOgrk3 {"921", "Iota", "{{$\\Iota$}}"}, // greek capital letter iota, U+0399 {"922", "Kappa", "{{$\\Kappa$}}"}, // greek capital letter kappa, U+039A {"923", "Lambda", "{{$\\Lambda$}}"}, // greek capital letter lambda, // U+039B ISOgrk3 {"924", "Mu", "{{$\\Mu$}}"}, // greek capital letter mu, U+039C {"925", "Nu", "{{$\\Nu$}}"}, // greek capital letter nu, U+039D {"926", "Xi", "{{$\\Xi$}}"}, // greek capital letter xi, U+039E ISOgrk3 {"927", "Omicron", "{{$\\Omicron$}}"}, // greek capital letter omicron, U+039F {"928", "Pi", "{{$\\Pi$}}"}, // greek capital letter pi, U+03A0 ISOgrk3 {"929", "Rho", "{{$\\Rho$}}"}, // greek capital letter rho, U+03A1 /* there is no Sigmaf, and no U+03A2 character either */ {"931", "Sigma", "{{$\\Sigma$}}"}, // greek capital letter sigma, // U+03A3 ISOgrk3 {"932", "Tau", "{{$\\Tau$}}"}, // greek capital letter tau, U+03A4 {"933", "Upsilon", "{{$\\Upsilon$}}"}, // greek capital letter upsilon, // U+03A5 ISOgrk3 {"934", "Phi", "{{$\\Phi$}}"}, // greek capital letter phi, // U+03A6 ISOgrk3 {"935", "Chi", "{{$\\Chi$}}"}, // greek capital letter chi, U+03A7 {"936", "Psi", "{{$\\Psi$}}"}, // greek capital letter psi, // U+03A8 ISOgrk3 {"937", "Omega", "{{$\\Omega$}}"}, // greek capital letter omega, // U+03A9 ISOgrk3 {"945", "alpha", "$\\alpha$"}, // greek small letter alpha, // U+03B1 ISOgrk3 {"946", "beta", "$\\beta$"}, // greek small letter beta, U+03B2 ISOgrk3 {"947", "gamma", "$\\gamma$"}, // greek small letter gamma, // U+03B3 ISOgrk3 {"948", "delta", "$\\delta$"}, // greek small letter delta, // U+03B4 ISOgrk3 {"949", "epsilon", "$\\epsilon$"}, // greek small letter epsilon, // U+03B5 ISOgrk3 {"950", "zeta", "$\\zeta$"}, // greek small letter zeta, U+03B6 ISOgrk3 {"951", "eta", "$\\eta$"}, // greek small letter eta, U+03B7 ISOgrk3 {"952", "theta", "$\\theta$"}, // greek small letter theta, // U+03B8 ISOgrk3 {"953", "iota", "$\\iota$"}, // greek small letter iota, U+03B9 ISOgrk3 {"954", "kappa", "$\\kappa$"}, // greek small letter kappa, // U+03BA ISOgrk3 {"955", "lambda", "$\\lambda$"}, // greek small letter lambda, // U+03BB ISOgrk3 {"956", "mu", "$\\mu$"}, // greek small letter mu, U+03BC ISOgrk3 {"957", "nu", "$\\nu$"}, // greek small letter nu, U+03BD ISOgrk3 {"958", "xi", "$\\xi$"}, // greek small letter xi, U+03BE ISOgrk3 {"959", "omicron", "$\\omicron$"}, // greek small letter omicron, U+03BF NEW {"960", "pi", "$\\pi$"}, // greek small letter pi, U+03C0 ISOgrk3 {"961", "rho", "$\\rho$"}, // greek small letter rho, U+03C1 ISOgrk3 {"962", "sigmaf", "$\\varsigma$"}, // greek small letter final sigma, // U+03C2 ISOgrk3 {"963", "sigma", "$\\sigma$"}, // greek small letter sigma, // U+03C3 ISOgrk3 {"964", "tau", "$\\tau$"}, // greek small letter tau, U+03C4 ISOgrk3 {"965", "upsilon", "$\\upsilon$"}, // greek small letter upsilon, {"", "upsi", "$\\upsilon$"}, // alias // U+03C5 ISOgrk3 {"966", "phi", "$\\phi$"}, // greek small letter phi, U+03C6 ISOgrk3 {"967", "chi", "$\\chi$"}, // greek small letter chi, U+03C7 ISOgrk3 {"968", "psi", "$\\psi$"}, // greek small letter psi, U+03C8 ISOgrk3 {"969", "omega", "$\\omega$"}, // greek small letter omega, // U+03C9 ISOgrk3 {"977", "thetasym", "$\\vartheta$"}, // greek small letter theta symbol, {"", "thetav", "$\\vartheta$"}, // greek small letter theta symbol, {"", "vartheta", "$\\vartheta$"}, // greek small letter theta symbol, // U+03D1 NEW {"978", "upsih", "{{$\\Upsilon$}}"}, // greek upsilon with hook symbol, // U+03D2 NEW {"982", "piv", "$\\varphi$"}, // greek pi symbol, U+03D6 ISOgrk3 /* General Punctuation */ {"8211", "ndash", "$\\textendash$"}, {"8212", "mdash", "$\\textemdash$"}, {"8226", "bull", "$\\bullet$"}, // bullet = black small circle, // U+2022 ISOpub /* bullet is NOT the same as bullet operator, U+2219 */ {"8230", "hellip", "{\\ldots}"}, // horizontal ellipsis = three dot leader, // U+2026 ISOpub {"8242", "prime", "$\\prime$"}, // prime = minutes = feet, U+2032 ISOtech {"8243", "Prime", "$\\prime\\prime$"}, // double prime = seconds = inches, // U+2033 ISOtech {"8254", "oline", "{\\={}}"}, // overline = spacing overscore, // U+203E NEW {"8260", "frasl", "/"}, // fraction slash, U+2044 NEW /* Letterlike Symbols */ {"8472", "weierp", "$\\wp$"}, // script capital P = power set // = Weierstrass p, U+2118 ISOamso {"8465", "image", "{{$\\Im$}}"}, // blackletter capital I = imaginary part, // U+2111 ISOamso {"8476", "real", "{{$\\Re$}}"}, // blackletter capital R = real part symbol, // U+211C ISOamso {"8482", "trade", "{\\texttrademark}"}, // trade mark sign, U+2122 ISOnum {"8501", "alefsym", "$\\aleph$"}, // alef symbol = first transfinite cardinal, // U+2135 NEW /* alef symbol is NOT the same as hebrew letter alef, U+05D0 although the same glyph could be used to depict both characters */ /* Arrows */ {"8592", "larr", "$\\leftarrow$"}, // leftwards arrow, U+2190 ISOnum {"8593", "uarr", "$\\uparrow$"}, // upwards arrow, U+2191 ISOnum {"8594", "rarr", "$\\rightarrow$"}, // rightwards arrow, U+2192 ISOnum {"8595", "darr", "$\\downarrow$"}, // downwards arrow, U+2193 ISOnum {"8596", "harr", "$\\leftrightarrow$"}, // left right arrow, U+2194 ISOamsa {"8629", "crarr", "$\\dlsh$"}, // downwards arrow with corner leftwards // = carriage return, U+21B5 NEW - require mathabx {"8656", "lArr", "{{$\\Leftarrow$}}"}, // leftwards double arrow, U+21D0 ISOtech /* ISO 10646 does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */ {"8657", "uArr", "{{$\\Uparrow$}}"}, // upwards double arrow, U+21D1 ISOamsa {"8658", "rArr", "{{$\\Rightarrow$}}"}, // rightwards double arrow, // U+21D2 ISOtech /* ISO 10646 does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */ {"8659", "dArr", "{{$\\Downarrow$}}"}, // downwards double arrow, U+21D3 ISOamsa {"8660", "hArr", "{{$\\Leftrightarrow$}}"}, // left right double arrow, // U+21D4 ISOamsa /* Mathematical Operators */ {"8704", "forall", "$\\forall$"}, // for all, U+2200 ISOtech {"8706", "part", "$\\partial$"}, // partial differential, U+2202 ISOtech {"8707", "exist", "$\\exists$"}, // there exists, U+2203 ISOtech {"8709", "empty", "$\\emptyset$"}, // empty set = null set = diameter, // U+2205 ISOamso {"8711", "nabla", "$\\nabla$"}, // nabla = backward difference, // U+2207 ISOtech {"8712", "isin", "$\\in$"}, // element of, U+2208 ISOtech {"8713", "notin", "$\\notin$"}, // not an element of, U+2209 ISOtech {"8715", "ni", "$\\ni$"}, // contains as member, U+220B ISOtech /* should there be a more memorable name than 'ni'? */ {"8719", "prod", "$\\prod$"}, // n-ary product = product sign, // U+220F ISOamsb /* prod is NOT the same character as U+03A0 'greek capital letter pi' though the same glyph might be used for both */ {"8721", "sum", "$\\sum$"}, // n-ary sumation, U+2211 ISOamsb /* sum is NOT the same character as U+03A3 'greek capital letter sigma' though the same glyph might be used for both */ {"8722", "minus", "$-$"}, // minus sign, U+2212 ISOtech {"8727", "lowast", "$\\ast$"}, // asterisk operator, U+2217 ISOtech {"8730", "radic", "$\\sqrt{}$"}, // square root = radical sign, // U+221A ISOtech {"8733", "prop", "$\\propto$"}, // proportional to, U+221D ISOtech {"8734", "infin", "$\\infty$"}, // infinity, U+221E ISOtech {"8736", "ang", "$\\angle$"}, // angle, U+2220 ISOamso {"8743", "and", "$\\land$"}, // logical and = wedge, U+2227 ISOtech {"8744", "or", "$\\lor$"}, // logical or = vee, U+2228 ISOtech {"8745", "cap", "$\\cap$"}, // intersection = cap, U+2229 ISOtech {"8746", "cup", "$\\cup$"}, // union = cup, U+222A ISOtech {"8747", "int", "$\\int$"}, // integral, U+222B ISOtech {"8756", "there4", "$\\therefore$"}, // therefore, U+2234 ISOtech; AMSSymb {"8764", "sim", "$\\sim$"}, // tilde operator = varies with = similar to, // U+223C ISOtech /* tilde operator is NOT the same character as the tilde, U+007E, although the same glyph might be used to represent both */ {"8773", "cong", "$\\cong$"}, // approximately equal to, U+2245 ISOtech {"8776", "asymp", "$\\approx$"}, // almost equal to = asymptotic to, // U+2248 ISOamsr {"8800", "ne", "$\\neq$"}, // not equal to, U+2260 ISOtech {"8801", "equiv", "$\\equiv$"}, // identical to, U+2261 ISOtech {"8804", "le", "$\\leq$"}, // less-than or equal to, U+2264 ISOtech {"8805", "ge", "$\\geq$"}, // greater-than or equal to, // U+2265 ISOtech {"8834", "sub", "$\\subset$"}, // subset of, U+2282 ISOtech {"8835", "sup", "$\\supset$"}, // superset of, U+2283 ISOtech /* note that nsup, 'not a superset of, U+2283' is not covered by the Symbol font encoding and is not included. Should it be, for symmetry? It is in ISOamsn */ {"8836", "nsub", "$\\not\\subset$"}, // not a subset of, U+2284 ISOamsn {"8838", "sube", "$\\subseteq$"}, // subset of or equal to, U+2286 ISOtech {"8839", "supe", "$\\supseteq$"}, // superset of or equal to, // U+2287 ISOtech {"8853", "oplus", "$\\oplus$"}, // circled plus = direct sum, // U+2295 ISOamsb {"8855", "otimes", "$\\otimes$"}, // circled times = vector product, // U+2297 ISOamsb {"8869", "perp", "$\\perp$"}, // up tack = orthogonal to = perpendicular, // U+22A5 ISOtech {"8901", "sdot", "$\\cdot$"}, // dot operator, U+22C5 ISOamsb /* dot operator is NOT the same character as U+00B7 middle dot */ {"8968", "lceil", "$\\lceil$"}, // left ceiling = apl upstile, // U+2308 ISOamsc {"8969", "rceil", "$\\rceil$"}, // right ceiling, U+2309 ISOamsc {"8970", "lfloor", "$\\lfloor$"}, // left floor = apl downstile, // U+230A ISOamsc {"8971", "rfloor", "$\\rfloor$"}, // right floor, U+230B ISOamsc /* Miscellaneous Technical */ {"9001", "lang", "$\\langle$"}, // left-pointing angle bracket = bra, // U+2329 ISOtech /* lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation mark' */ {"9002", "rang", "$\\rangle$"}, // right-pointing angle bracket = ket, // U+232A ISOtech /* rang is NOT the same character as U+003E 'greater than' or U+203A 'single right-pointing angle quotation mark' */ /* Geometric Shapes */ {"9674", "loz", "$\\lozenge$"}, // lozenge, U+25CA ISOpub /* Miscellaneous Symbols */ {"9824", "spades", "$\\spadesuit$"}, // black spade suit, U+2660 ISOpub /* black here seems to mean filled as opposed to hollow */ {"9827", "clubs", "$\\clubsuit$"}, // black club suit = shamrock, // U+2663 ISOpub {"9829", "hearts", "$\\heartsuit$"}, // black heart suit = valentine, // U+2665 ISOpub {"9830", "diams", "$\\diamondsuit$"}, // black diamond suit, U+2666 ISOpub {"34", "quot", "\""}, // quotation mark = APL quote, // U+0022 ISOnum {"38", "amp", "\\&"}, // ampersand, U+0026 ISOnum {"60", "lt", "$<$"}, // less-than sign, U+003C ISOnum {"62", "gt", "$>$"}, // greater-than sign, U+003E ISOnum /* General Punctuation */ {"8194", "ensp", "\\hspace{0.5em}"}, // en space, U+2002 ISOpub {"8195", "emsp", "\\hspace{1em}"}, // em space, U+2003 ISOpub {"8201", "thinsp", "\\hspace{0.167em}"}, // thin space, U+2009 ISOpub {"8202", "", "\\hspace{0.1em}"}, // hair space, U+2010 ISOpub {"8204", "zwnj", "\\/{}"}, // zero width non-joiner, // U+200C NEW RFC 2070 {"8205", "zwj", ""}, // zero width joiner, U+200D NEW RFC 2070 {"8206", "lrm", ""}, // left-to-right mark, U+200E NEW RFC 2070 {"8207", "rlm", ""}, // right-to-left mark, U+200F NEW RFC 2070 {"8211", "ndash", "--"}, // en dash, U+2013 ISOpub {"8212", "mdash", "---"}, // em dash, U+2014 ISOpub {"8216", "lsquo", "{\\textquoteleft}"}, // left single quotation mark, // U+2018 ISOnum {"8217", "rsquo", "{\\textquoteright}"}, // right single quotation mark, // U+2019 ISOnum {"8218", "sbquo", "{\\quotesinglbase}"}, // single low-9 quotation mark, U+201A NEW {"8220", "ldquo", "{\\textquotedblleft}"}, // left double quotation mark, // U+201C ISOnum {"8221", "rdquo", "{\\textquotedblright}"}, // right double quotation mark, // U+201D ISOnum {"8222", "bdquo", "{\\quotedblbase}"}, // double low-9 quotation mark, U+201E NEW {"8224", "dagger", "{\\dag}"}, // dagger, U+2020 ISOpub {"8225", "Dagger", "{\\ddag}"}, // double dagger, U+2021 ISOpub {"8240", "permil", "{\\textperthousand}"}, // per mille sign, U+2030 ISOtech {"8249", "lsaquo", "{\\guilsinglleft}"}, // single left-pointing angle quotation mark, // U+2039 ISO proposed /* lsaquo is proposed but not yet ISO standardized */ {"8250", "rsaquo", "{\\guilsinglright}"}, // single right-pointing angle quotation mark, // U+203A ISO proposed /* rsaquo is proposed but not yet ISO standardized */ {"8364", "euro", "{\\texteuro}"}, // euro sign, U+20AC NEW /* Manually added */ {"35", "", "\\#"}, // Hash {"36", "dollar", "\\$"}, // Dollar {"37", "#37", "\\%"}, // Percent (&percnt; is not displayed correctly in the entry preview) {"39", "apos", "'"}, // Apostrophe {"40", "lpar", "("}, // Left bracket {"41", "rpar", ")"}, // Right bracket {"42", "", "*"}, // Asterisk {"43", "plus", "+"}, // Plus {"44", "comma", ","}, // Comma {"45", "hyphen", "-"}, // Hyphen {"46", "period", "."}, // Period {"47", "slash", "/"}, // Slash (solidus) {"58", "colon", ":"}, // Colon {"59", "semi", ";"}, // Semi colon {"61", "equals", "="}, // Equals to {"91", "lsqb", "["}, // Left square bracket {"92", "bsol", "{\\textbackslash}"}, // Backslash {"93", "rsqb", "]"}, // Right square bracket {"94", "Hat", "{\\^{}}"}, // Circumflex {"95", "lowbar", "\\_"}, // Underscore {"96", "grave", "{\\`{}}"}, // Grave {"123", "lbrace", "\\{"}, // Left curly bracket {"", "lcub", "\\{"}, // Left curly bracket {"124", "vert", "|"}, // Vertical bar {"", "verbar", "|"}, // Vertical bar {"", "VerticalLine", "|"}, // Vertical bar {"125", "rbrace", "\\}"}, // Right curly bracket {"", "rcub", "\\}"}, // Right curly bracket // {"138", "", "{{\\v{S}}}"}, // Line tabulation set // {"141", "", ""}, // Reverse line feed {"145", "", "`"}, // Apostrophe {"146", "", "'"}, // Apostrophe {"147", "", "``"}, // Quotation mark {"148", "", "''"}, // Quotation mark {"150", "", "--"}, // En dash // {"154", "", "{\\v{s}}"}, // Single character introducer {"256", "", "{{\\={A}}}"}, // capital A with macron {"257", "", "{\\={a}}"}, // small a with macron {"258", "", "{{\\u{A}}}"}, // capital A with breve {"259", "", "{\\u{a}}"}, // small a with breve {"260", "Aogon", "{{\\k{A}}}"}, // capital A with ogonek {"261", "aogon", "{\\k{a}}"}, // small a with ogonek {"262", "Cacute", "{{\\'{C}}}"}, // capital C with acute {"263", "cacute", "{\\'{c}}"}, // small C with acute {"264", "Ccirc", "{{\\^{C}}}"}, // capital C with circumflex {"265", "ccirc", "{\\^{c}}"}, // small C with circumflex {"266", "Cdot", "{{\\.{C}}}"}, // capital C with dot above {"267", "cdot", "{\\.{c}}"}, // small C with dot above {"268", "Ccaron", "{{\\v{C}}}"}, // capital C with caron {"269", "ccaron", "{\\v{c}}"}, // small C with caron {"270", "", "{{\\v{D}}}"}, // capital D with caron {"271", "", "{\\v{d}}"}, // small d with caron {"272", "Dstrok", "{{\\DJ}}"}, // capital D with stroke {"273", "dstrok", "{{\\dj}}"}, // small d with stroke {"274", "", "{{\\={E}}}"}, // capital E with macron {"275", "", "{\\={e}}"}, // small e with macron {"276", "", "{{\\u{E}}}"}, // capital E with breve {"277", "", "{\\u{e}}"}, // small e with breve {"278", "", "{{\\.{E}}}"}, // capital E with dot above {"279", "", "{\\.{e}}"}, // small e with dot above {"280", "Eogon", "{{\\k{E}}}"}, // capital E with ogonek {"281", "eogon", "{\\k{e}}"}, // small e with ogonek {"282", "", "{{\\v{E}}}"}, // capital E with caron {"283", "", "{\\v{e}}"}, // small e with caron {"284", "", "{{\\^{G}}}"}, // capital G with circumflex {"285", "", "{\\^{g}}"}, // small g with circumflex {"286", "", "{{\\u{G}}}"}, // capital G with breve {"287", "", "{\\u{g}}"}, // small g with breve {"288", "", "{{\\.{G}}}"}, // capital G with dot above {"289", "", "{\\.{g}}"}, // small g with dot above {"290", "", "{{\\c{G}}}"}, // capital G with cedilla {"291", "", "{\\c{g}}"}, // small g with cedilla {"292", "", "{{\\^{H}}}"}, // capital H with circumflex {"293", "", "{\\^{h}}"}, // small h with circumflex {"294", "", "{{\\B{H}}}"}, // capital H with stroke {"295", "", "{\\B{h}}"}, // small h with stroke {"296", "", "{{\\~{I}}}"}, // capital I with tilde {"297", "", "{\\~{\\i}}"}, // small i with tilde {"298", "Imacr", "{{\\={I}}}"}, // capital I with macron {"299", "imacr", "{\\={\\i}}"}, // small i with macron {"300", "", "{{\\u{I}}}"}, // capital I with breve {"301", "", "{\\u{\\i}}"}, // small i with breve {"302", "Iogon", "{{\\k{I}}}"}, // capital I with ogonek {"303", "iogon", "{\\k{i}}"}, // small i with ogonek {"304", "Idot", "{{\\.{I}}}"}, // capital I with dot above {"305", "inodot", "{\\i}"}, // Small i without the dot {"", "imath", "{\\i}"}, // Small i without the dot {"306", "", "{{\\IJ}}"}, // Dutch di-graph IJ {"307", "", "{{\\ij}}"}, // Dutch di-graph ij {"308", "", "{{\\^{J}}}"}, // capital J with circumflex {"309", "", "{\\^{\\j}}"}, // small j with circumflex {"310", "", "{{\\c{K}}}"}, // capital K with cedilla {"311", "", "{\\c{k}}"}, // small k with cedilla {"312", "", "{\\textkra}"}, // Letter kra {"313", "", "{{\\'{L}}}"}, // capital L with acute {"314", "", "{\\'{l}}"}, // small l with acute {"315", "", "{{\\c{L}}}"}, // capital L with cedilla {"316", "", "{\\c{l}}"}, // small l with cedilla {"317", "", "{{\\v{L}}}"}, // capital L with caron {"318", "", "{\\v{l}}"}, // small l with caron // {"319", "Lmidot", "{\\Lmidot}"}, // upper case L with mid dot // {"320", "lmidot", "{\\lmidot}"}, // lower case l with mid dot {"321", "Lstrok", "{{\\L}}"}, // upper case L with stroke {"322", "lstrok", "{{\\l}}"}, // lower case l with stroke {"323", "Nacute", "{{\\'{N}}}"}, // upper case N with acute {"324", "nacute", "{{\\'{n}}}"}, // lower case n with acute {"325", "", "{{\\c{N}}}"}, // capital N with cedilla {"326", "", "{\\c{n}}"}, // small n with cedilla {"327", "", "{{\\v{N}}}"}, // capital N with caron {"328", "", "{\\v{n}}"}, // small n with caron {"329", "", "{'n}"}, // small n preceded with apostroph {"330", "", "{{\\NG}}"}, // upper case letter Eng {"331", "", "{{\\ng}}"}, // lower case letter Eng {"332", "Omacro", "{{\\={O}}}"}, // the capital letter O with macron {"333", "omacro", "{\\={o}}"}, // the small letter o with macron {"334", "", "{{\\u{O}}}"}, // the capital letter O with breve {"335", "", "{\\u{o}}"}, // the small letter o with breve {"336", "", "{{\\H{O}}}"}, // the capital letter O with double acute {"337", "", "{\\H{o}}"}, // the small letter o with double acute {"338", "OElig", "{{\\OE}}"}, // OE-ligature {"339", "oelig", "{{\\oe}}"}, // oe-ligature {"340", "", "{{\\'{R}}}"}, // upper case R with acute {"341", "", "{{\\'{r}}}"}, // lower case r with acute {"342", "", "{{\\c{R}}}"}, // upper case R with cedilla {"343", "", "{{\\c{r}}}"}, // lower case r with cedilla {"344", "", "{{\\v{R}}}"}, // upper case R with caron {"345", "", "{{\\v{r}}}"}, // lower case r with caron {"346", "", "{{\\'{S}}}"}, // upper case S with acute {"347", "", "{{\\'{s}}}"}, // lower case s with acute {"348", "Scirc", "{{\\^{S}}}"}, // upper case S with circumflex {"349", "scirc", "{\\^{s}}"}, // lower case s with circumflex {"350", "Scedil", "{{\\c{S}}}"}, // upper case S with cedilla {"351", "scedil", "{\\c{s}}"}, // lower case s with cedilla {"352", "Scaron", "{{\\v{S}}}"}, // latin capital letter S with caron, {"353", "scaron", "{\\v{s}}"}, // latin small letter s with caron, {"354", "", "{{\\c{T}}}"}, // upper case T with cedilla {"355", "", "{{\\c{T}}}"}, // lower case t with cedilla {"356", "", "{{\\v{T}}}"}, // latin capital letter T with caron, {"357", "", "{\\v{t}}"}, // latin small letter t with caron, {"358", "", "{{\\B{T}}}"}, // latin capital letter T with stroke, {"359", "", "{\\B{t}}"}, // latin small letter t with stroke, {"360", "", "{{\\~{U}}}"}, // capital U with tilde {"361", "", "{\\~{u}}"}, // small u with tilde {"362", "", "{{\\={U}}}"}, // capital U with macron {"363", "", "{\\={u}}"}, // small u with macron {"364", "", "{{\\u{U}}}"}, // capital U with breve {"365", "", "{\\u{u}}"}, // small u with breve {"366", "", "{{\\r{U}}}"}, // capital U with ring {"367", "", "{\\r{u}}"}, // small u with ring {"368", "", "{{\\={U}}}"}, // capital U with double acute {"369", "", "{\\={u}}"}, // small u with double acute {"370", "Uogon", "{{\\k{U}}}"}, // capital U with ogonek {"371", "uogon", "{\\k{u}}"}, // small u with ogonek {"372", "", "{{\\^{W}}}"}, // capital W with circumflex {"373", "", "{\\^{w}}"}, // small w with circumflex {"374", "", "{{\\^{Y}}}"}, // capital Y with circumflex {"375", "", "{\\^{y}}"}, // small y with circumflex {"376", "Yuml", "{{\\\"{Y}}}"}, // latin capital letter Y with diaeresis, {"377", "", "{{\\'{Z}}}"}, // capital Z with acute {"378", "", "{\\'{z}}"}, // small z with acute {"379", "", "{{\\.{Z}}}"}, // capital Z with dot above {"380", "", "{\\.{z}}"}, // small z with dot above {"381", "Zcaron", "{{\\v{Z}}}"}, // capital Z with caron {"382", "zcaron", "{\\v{z}}"}, // small z with caron // {"383", "", ""}, // long s {"384", "", "{\\B{b}}"}, // small b with stroke {"402", "fnof", "\\textit{f}"}, // latin small f with hook = function {"405", "", "{{\\hv}}"}, // small letter Hv {"416", "", "{{\\OHORN}}"}, // capital O with horn {"417", "", "{{\\ohorn}}"}, // small o with horn {"431", "", "{{\\UHORN}}"}, // capital U with horn {"432", "", "{{\\uhorn}}"}, // small u with horn {"490", "Oogon", "{{\\k{O}}}"}, // capital letter O with ogonek {"491", "oogon", "{\\k{o}}"}, // small letter o with ogonek {"492", "", "{{\\k{\\={O}}}}"}, // capital letter O with ogonek and macron {"493", "", "{\\k{\\={o}}}"}, // small letter o with ogonek and macron {"536", "", "{{\\cb{S}}}"}, // capital letter S with comma below, require combelow {"537", "", "{\\cb{s}}"}, // small letter S with comma below, require combelow {"538", "", "{{\\cb{T}}}"}, // capital letter T with comma below, require combelow {"539", "", "{\\cb{t}}"}, // small letter T with comma below, require combelow {"710", "circ", "{\\^{}}"}, // modifier letter circumflex accent, {"726", "", "+"}, // Modifier plus sign {"727", "", "-"}, // Modifier minus sign {"728", "breve", "{\\u{}}"}, // Breve {"", "Breve", "{\\u{}}"}, // Breve {"729", "dot", "{\\.{}}"}, // Dot above {"730", "ring", "{\\r{}}"}, // Ring above {"731", "ogon", "{\\k{}}"}, // Ogonek {"732", "tilde", "\\~{}"}, // Small tilde {"733", "dblac", "{{\\H{}}}"}, // Double acute {"949", "epsi", "$\\epsilon$"}, // Epsilon - double check {"1013", "epsiv", "$\\varepsilonup$"}, // lunate epsilon, requires txfonts // {"1055", "", "{{\\cyrchar\\CYRP}}"}, // Cyrillic capital Pe // {"1082", "", "{\\cyrchar\\cyrk}"}, // Cyrillic small Ka // {"2013", "", ""}, // NKO letter FA -- Maybe en dash = 0x2013? // {"2014", "", ""}, // NKO letter FA -- Maybe em dash = 0x2014? {"8192", "", "\\hspace{0.5em}"}, // en quad {"8193", "", "\\hspace{1em}"}, // em quad {"8196", "", "\\hspace{0.333em}"}, // Three-Per-Em Space {"8197", "", "\\hspace{0.25em}"}, // Four-Per-Em Space {"8198", "", "\\hspace{0.167em}"}, // Six-Per-Em Space {"8208", "hyphen", "-"}, // Hyphen {"8229", "nldr", "\\.{}\\.{}"}, // Double dots - en leader {"8241", "", "{\\textpertenthousand}"}, // per ten thousands sign {"8244", "", "{$\\prime\\prime\\prime$}"}, // triple prime {"8251", "", "{\\textreferencemark}"}, {"8253", "", "{\\textinterrobang}"}, {"8320", "", "$_{0}$"}, // sub-script 0 {"8321", "", "$_{1}$"}, // sub-script 1 {"8322", "", "$_{2}$"}, // sub-script 2 {"8323", "", "$_{3}$"}, // sub-script 3 {"8324", "", "$_{4}$"}, // sub-script 4 {"8325", "", "$_{5}$"}, // sub-script 5 {"8326", "", "$_{6}$"}, // sub-script 6 {"8327", "", "$_{7}$"}, // sub-script 7 {"8328", "", "$_{8}$"}, // sub-script 8 {"8329", "", "$_{9}$"}, // sub-script 9 {"8330", "", "$_{+}$"}, // sub-script + {"8331", "", "$_{-}$"}, // sub-script - {"8332", "", "$_{-}$"}, // sub-script = {"8333", "", "$_{(}$"}, // sub-script ( {"8334", "", "$_{)}$"}, // sub-script ) {"8450", "complexes", "$\\mathbb{C}$"}, // double struck capital C -- requires e.g. amsfonts {"8451", "", "{\\textcelsius}"}, // Degree Celsius {"8459", "Hscr", "{{$\\mathcal{H}$}}"}, // script capital H -- possibly use \mathscr {"8460", "Hfr", "{{$\\mathbb{H}$}}"}, // black letter capital H -- requires e.g. amsfonts {"8466", "Lscr", "{{$\\mathcal{L}$}}"}, // script capital L -- possibly use \mathscr {"8467", "ell", "{$\\ell$}"}, // script small l {"8469", "naturals", "{{$\\mathbb{N}$}}"}, // double struck capital N -- requires e.g. amsfonts {"8474", "Qopf", "{{$\\mathbb{Q}$}}"}, // double struck capital Q -- requires e.g. amsfonts {"8477", "reals", "{{$\\mathbb{R}$}}"}, // double struck capital R -- requires e.g. amsfonts {"8486", "", "${{\\Omega}}$"}, // Omega {"8491", "angst", "{{\\AA}}"}, // Angstrom {"8496", "Escr", "{{$\\mathcal{E}$}}"}, // script capital E {"8531", "frac13", "$\\sfrac{1}{3}$"}, // Vulgar fraction one third {"8532", "frac23", "$\\sfrac{2}{3}$"}, // Vulgar fraction two thirds {"8533", "frac15", "$\\sfrac{1}{5}$"}, // Vulgar fraction one fifth {"8534", "frac25", "$\\sfrac{2}{5}$"}, // Vulgar fraction two fifths {"8535", "frac35", "$\\sfrac{3}{5}$"}, // Vulgar fraction three fifths {"8536", "frac45", "$\\sfrac{4}{5}$"}, // Vulgar fraction four fifths {"8537", "frac16", "$\\sfrac{1}{6}$"}, // Vulgar fraction one sixth {"8538", "frac56", "$\\sfrac{5}{6}$"}, // Vulgar fraction five sixths {"8539", "frac18", "$\\sfrac{1}{8}$"}, // Vulgar fraction one eighth {"8540", "frac38", "$\\sfrac{3}{8}$"}, // Vulgar fraction three eighths {"8541", "frac58", "$\\sfrac{5}{8}$"}, // Vulgar fraction five eighths {"8542", "frac78", "$\\sfrac{7}{8}$"}, // Vulgar fraction seven eighths {"8710", "", "$\\triangle$"}, // Increment - could use a more appropriate symbol {"8714", "", "$\\in$"}, // Small element in {"8723", "mp", "$\\mp$"}, // Minus-plus {"8729", "bullet", "$\\bullet$"}, // Bullet operator {"8741", "", "$\\parallel$"}, // Parallel to {"8758", "ratio", ":"}, // Colon/ratio {"8771", "sime", "$\\simeq$"}, // almost equal to = asymptotic to, {"8776", "ap", "$\\approx$"}, // almost equal to = asymptotic to, {"8810", "ll", "$\\ll$"}, // Much less than {"", "Lt", "$\\ll$"}, // Much less than {"8811", "gg", "$\\gg$"}, // Much greater than {"", "Gt", "$\\gg$"}, // Much greater than {"8818", "lsim", "$\\lesssim$"}, // Less than or equivalent to {"8819", "gsim", "$\\gtrsim$"}, // Greater than or equivalent to {"8862", "boxplus", "$\\boxplus$"}, // Boxed plus -- requires amssymb {"8863", "boxminus", "$\\boxminus$"}, // Boxed minus -- requires amssymb {"8864", "boxtimes", "$\\boxtimes$"}, // Boxed times -- requires amssymb {"8882", "vltri", "$\\triangleleft$"}, // Left triangle {"8883", "vrtri", "$\\triangleright$"}, // Right triangle {"8896", "xwedge", "$\\bigwedge$"}, // Big wedge {"8897", "xvee", "$\\bigvee$"}, // Big vee {"8942", "vdots", "$\\vdots$"}, // vertical ellipsis U+22EE {"8943", "cdots", "$\\cdots$"}, // midline horizontal ellipsis U+22EF /* {"8944", "", "$\\ddots$"}, // up right diagonal ellipsis U+22F0 */ {"8945", "ddots", "$\\ddots$"}, // down right diagonal ellipsis U+22F1 {"9426", "circledc", "{\\copyright}"}, // circled small letter C {"9633", "square", "$\\square$"}, // White square {"9651", "xutri", "$\\bigtriangleup$"}, // White up-pointing big triangle {"9653", "utri", "$\\triangle$"}, // White up-pointing small triangle -- \vartriangle probably // better but requires amssymb {"10877", "les", "$\\leqslant$"}, // Less than slanted equal -- requires amssymb {"10878", "ges", "$\\geqslant$"}, // Less than slanted equal -- requires amssymb {"64256", "", "ff"}, // ff ligature (which LaTeX solves by itself) {"64257", "", "fi"}, // fi ligature (which LaTeX solves by itself) {"64258", "", "fl"}, // fl ligature (which LaTeX solves by itself) {"64259", "", "ffi"}, // ffi ligature (which LaTeX solves by itself) {"64260", "", "ffl"}, // ffl ligature (which LaTeX solves by itself) {"119978", "Oscr", "$\\mathcal{O}$"}, // script capital O -- possibly use \mathscr {"119984", "Uscr", "$\\mathcal{U}$"}, // script capital U -- possibly use \mathscr {"120598", "", "$\\epsilon$"}, // mathematical italic epsilon U+1D716 -- requires amsmath {"120599", "", "{{\\˜{n}}}"}, // n with tide }; // List of combining accents private static final String[][] ACCENT_LIST = new String[][] {{"768", "`"}, // Grave {"769", "'"}, // Acute {"770", "^"}, // Circumflex {"771", "~"}, // Tilde {"772", "="}, // Macron {"773", "="}, // Overline - not completely correct {"774", "u"}, // Breve {"775", "."}, // Dot above {"776", "\""}, // Diaeresis {"777", "h"}, // Hook above {"778", "r"}, // Ring {"779", "H"}, // Double acute {"780", "v"}, // Caron {"781", "|"}, // Vertical line above {"782", "U"}, // Double vertical line above {"783", "G"}, // Double grave {"784", "textdotbreve"}, // Candrabindu {"785", "t"}, // Inverted breve // {"786", ""}, // Turned comma above // {"787", ""}, // Comma above {"788", "textrevcommaabove"}, // Reversed comma above {"789", "textcommaabover"}, // Comma above right {"790", "textsubgrave"}, // Grave accent below -requires tipa {"791", "textsubacute"}, // Acute accent below - requires tipa {"792", "textadvancing"}, // Left tack below - requires tipa {"793", "textretracting"}, // Right tack below - requires tipa {"794", "textlangleabove"}, // Left angle above {"795", "textrighthorn"}, // Horn {"796", "textsublhalfring"}, // Left half ring below - requires tipa {"797", "textraising"}, // Up tack below - requires tipa {"798", "textlowering"}, // Down tack below - requires tipa {"799", "textsubplus"}, // Plus sign below - requires tipa {"800", "textsubbar"}, // Minus sign below {"801", "textpalhookbelow"}, // Palatalized hook below {"802", "M"}, // Retroflex hook below - textrethookbelow? {"803", "d"}, // Dot below {"804", "textsubumlaut"}, // Diaeresis below - requires tipa {"805", "textsubring"}, // Ring below - requires tipa {"806", "cb"}, // Comma below - requires combelow {"807", "c"}, // Cedilla {"808", "k"}, // Ogonek {"809", "textsyllabic"}, // Vertical line below - requires tipa {"810", "textsubbridge"}, // Bridge below - requires tipa {"811", "textsubw"}, // Inverted double arch below - requires tipa {"812", "textsubwedge"}, // Caron below {"813", "textsubcircum"}, // Circumflex accent below - requires tipa {"814", "textsubbreve"}, // Breve below {"815", "textsubarch"}, // Inverted breve below - requires tipa {"816", "textsubtilde"}, // Tilde below - requires tipa {"817", "b"}, // Macron below - not completely correct {"818", "b"}, // Underline {"819", "subdoublebar"}, // Double low line -- requires extraipa {"820", "textsuperimposetilde"}, // Tilde overlay - requires tipa {"821", "B"}, // Short stroke overlay - textsstrokethru? {"822", "textlstrokethru"}, // Long stroke overlay {"823", "textsstrikethru"}, // Short solidus overlay {"824", "textlstrikethru"}, // Long solidus overlay {"825", "textsubrhalfring"}, // Right half ring below - requires tipa {"826", "textinvsubbridge"}, // inverted bridge below - requires tipa {"827", "textsubsquare"}, // Square below - requires tipa {"828", "textseagull"}, // Seagull below - requires tipa {"829", "textovercross"}, // X above - requires tipa // {"830", ""}, // Vertical tilde // {"831", ""}, // Double overline // {"832", ""}, // Grave tone mark // {"833", ""}, // Acute tone mark // {"834", ""}, // Greek perispomeni // {"835", ""}, // Greek koronis // {"836", ""}, // Greek dialytika tonos // {"837", ""}, // Greek ypogegrammeni {"838", "overbridge"}, // Bridge above - requires extraipa {"839", "subdoublebar"}, // Equals sign below - requires extraipa {"840", "subdoublevert"}, // Double vertical line below - requires extraipa {"841", "subcorner"}, // Left angle below - requires extraipa {"842", "crtilde"}, // Not tilde above - requires extraipa {"843", "dottedtilde"}, // Homothetic above - requires extraipa {"844", "doubletilde"}, // Almost equal to above - requires extraipa {"845", "spreadlips"}, // Left right arrow below - requires extraipa {"846", "whistle"}, // Upwards arrow below - requires extraipa {"861", "textdoublebreve"}, // Double breve {"862", "textdoublemacron"}, // Double macron {"863", "textdoublemacronbelow"}, // Double macron below {"864", "textdoubletilde"}, // Double tilde {"865", "texttoptiebar"}, // Double inverted breve {"866", "sliding"}, // Double rightwards arrow below - requires extraipa }; static { for (String[] aConversionList : CONVERSION_LIST) { if (!(aConversionList[2].isEmpty())) { String strippedLaTeX = cleanLaTeX(aConversionList[2]); if (!(aConversionList[1].isEmpty())) { HTML_LATEX_CONVERSION_MAP.put("&" + aConversionList[1] + ";", aConversionList[2]); if (!strippedLaTeX.isEmpty()) { LATEX_HTML_CONVERSION_MAP.put(strippedLaTeX, "&" + aConversionList[1] + ";"); } } else if (!(aConversionList[0].isEmpty()) && !strippedLaTeX.isEmpty()) { LATEX_HTML_CONVERSION_MAP.put(strippedLaTeX, "&#" + aConversionList[0] + ";"); } if (!(aConversionList[0].isEmpty())) { NUMERICAL_LATEX_CONVERSION_MAP.put(Integer.decode(aConversionList[0]), aConversionList[2]); if (Integer.decode(aConversionList[0]) > 128) { String unicodeSymbol = String.valueOf(Character.toChars(Integer.decode(aConversionList[0]))); UNICODE_LATEX_CONVERSION_MAP.put(unicodeSymbol, aConversionList[2]); if (!strippedLaTeX.isEmpty()) { LATEX_UNICODE_CONVERSION_MAP.put(strippedLaTeX, unicodeSymbol); } } } } } for (String[] anAccentList : ACCENT_LIST) { ESCAPED_ACCENTS.put(Integer.decode(anAccentList[0]), anAccentList[1]); UNICODE_ESCAPED_ACCENTS.put(anAccentList[1], String.valueOf(Character.toChars(Integer.decode(anAccentList[0])))); } // Manually added values which are killed by cleanLaTeX LATEX_HTML_CONVERSION_MAP.put("$", "&dollar;"); LATEX_UNICODE_CONVERSION_MAP.put("$", "$"); // Manual corrections LATEX_HTML_CONVERSION_MAP.put("AA", "&Aring;"); // Overwritten by &angst; which is less supported LATEX_UNICODE_CONVERSION_MAP.put("AA", "Å"); // Overwritten by Ångstrom symbol // Manual additions // Support relax to the extent that it is simply removed LATEX_HTML_CONVERSION_MAP.put("relax", ""); LATEX_UNICODE_CONVERSION_MAP.put("relax", ""); // Support a special version of apostrophe LATEX_HTML_CONVERSION_MAP.put("textquotesingle", "&#39;"); LATEX_UNICODE_CONVERSION_MAP.put("textquotesingle", "'"); // apostrophe, U+00027 } private HTMLUnicodeConversionMaps() { } private static String cleanLaTeX(String escapedString) { // Get rid of \{}$ from the LaTeX-string return escapedString.replaceAll("[\\\\\\{\\}\\$]", ""); } }
60,816
65.831868
156
java
null
jabref-main/src/main/java/org/jabref/logic/util/strings/QuotedStringTokenizer.java
package org.jabref.logic.util.strings; /** * A String tokenizer that works just like StringTokenizer, but considers quoted * characters (which do not act as delimiters). */ public class QuotedStringTokenizer { private final String content; private final int contentLength; private final String delimiters; private final char quoteChar; private int index; /** * @param content The String to be tokenized. * @param delimiters The delimiter characters. * @param quoteCharacter The quoting character. Every character (including, but not limited to, delimiters) that is preceded by this character is not treated as a delimiter, but as a token component. */ public QuotedStringTokenizer(String content, String delimiters, char quoteCharacter) { this.content = content; this.delimiters = delimiters; quoteChar = quoteCharacter; contentLength = this.content.length(); // skip leading delimiters while (isDelimiter(this.content.charAt(index)) && index < contentLength) { ++index; } } /** * @return the next token from the content string, ending at the next * unquoted delimiter. Does not unquote the string itself. */ public String nextToken() { char c; StringBuilder stringBuilder = new StringBuilder(); while (index < contentLength) { c = content.charAt(index); if (c == quoteChar) { // next is quoted ++index; stringBuilder.append(c); if (index < contentLength) { stringBuilder.append(content.charAt(index)); // ignore for delimiter search! } } else if (isDelimiter(c)) { // unit finished // advance index until next token or end ++index; return stringBuilder.toString(); } else { stringBuilder.append(c); } ++index; } return stringBuilder.toString(); } private boolean isDelimiter(char c) { return delimiters.indexOf(c) >= 0; } public boolean hasMoreTokens() { return index < contentLength; } }
2,269
32.880597
203
java
null
jabref-main/src/main/java/org/jabref/logic/util/strings/RtfCharMap.java
package org.jabref.logic.util.strings; import java.util.HashMap; public class RtfCharMap { private final HashMap<String, String> rtfMap = new HashMap<>(); public RtfCharMap() { put("`a", "\\'e0"); put("`e", "\\'e8"); put("`i", "\\'ec"); put("`o", "\\'f2"); put("`u", "\\'f9"); put("'a", "\\'e1"); put("'e", "\\'e9"); put("'i", "\\'ed"); put("'o", "\\'f3"); put("'u", "\\'fa"); put("^a", "\\'e2"); put("^e", "\\'ea"); put("^i", "\\'ee"); put("^o", "\\'f4"); put("^u", "\\'fa"); put("\"a", "\\'e4"); put("\"e", "\\'eb"); put("\"i", "\\'ef"); put("\"o", "\\'f6"); put("\"u", "\\u252u"); put("~n", "\\'f1"); put("`A", "\\'c0"); put("`E", "\\'c8"); put("`I", "\\'cc"); put("`O", "\\'d2"); put("`U", "\\'d9"); put("'A", "\\'c1"); put("'E", "\\'c9"); put("'I", "\\'cd"); put("'O", "\\'d3"); put("'U", "\\'da"); put("^A", "\\'c2"); put("^E", "\\'ca"); put("^I", "\\'ce"); put("^O", "\\'d4"); put("^U", "\\'db"); put("\"A", "\\'c4"); put("\"E", "\\'cb"); put("\"I", "\\'cf"); put("\"O", "\\'d6"); put("\"U", "\\'dc"); // Use UNICODE characters for RTF-Chars which cannot be found in the // standard codepage put("S", "\\u167S"); // Section sign put("`!", "\\u161!"); // Inverted exclamation point put("pounds", "\\u163?"); // Pound sign put("copyright", "\\u169?"); // Copyright sign put("P", "\\u182P"); // Paragraph sign put("`?", "\\u191?"); // Inverted question mark put("~A", "\\u195A"); // "Atilde" put("AA", "\\u197A"); // "Aring" // RTFCHARS.put("AE", "{\\uc2\\u198AE}"); // "AElig" put("AE", "{\\u198AE}"); // "AElig" put("cC", "\\u199C"); // "Ccedil" put("DH", "\\u208D"); // "ETH" put("~N", "\\u209N"); // "Ntilde" put("~O", "\\u213O"); // "Otilde" // According to ISO 8859-1 the "\times" symbol should be placed here // (#215). // Omitting this, because it is a mathematical symbol. put("O", "\\u216O"); // "Oslash" // RTFCHARS.put("O", "\\'d8"); put("o", "\\'f8"); put("'Y", "\\u221Y"); // "Yacute" put("TH", "\\u222TH"); // "THORN" put("ss", "\\u223ss"); // "szlig" // RTFCHARS.put("ss", "AFFEN"); // "szlig" put("~a", "\\u227a"); // "atilde" put("aa", "\\u229a"); // "aring" // RTFCHARS.put("ae", "{\\uc2\\u230ae}"); // "aelig" \\u230e6 put("ae", "{\\u230ae}"); // "aelig" \\u230e6 put("cc", "\\u231c"); // "ccedil" put("dh", "\\u240d"); // "eth" put("~o", "\\u245o"); // "otilde" // According to ISO 8859-1 the "\div" symbol should be placed here // (#247). // Omitting this, because it is a mathematical symbol. put("o", "\\u248o"); // "oslash" // RTFCHARS.put("\"u", "\\u252"); // "uuml" exists in standard // codepage put("'y", "\\u253y"); // "yacute" put("th", "\\u254th"); // "thorn" put("\"y", "\\u255y"); // "yuml" put("=A", "\\u256A"); // "Amacr" put("=a", "\\u257a"); // "amacr" put("uA", "\\u258A"); // "Abreve" put("ua", "\\u259a"); // "abreve" put("kA", "\\u260A"); // "Aogon" put("ka", "\\u261a"); // "aogon" put("'C", "\\u262C"); // "Cacute" put("'c", "\\u263c"); // "cacute" put("^C", "\\u264C"); // "Ccirc" put("^c", "\\u265c"); // "ccirc" put(".C", "\\u266C"); // "Cdot" put(".c", "\\u267c"); // "cdot" put("vC", "\\u268C"); // "Ccaron" put("vc", "\\u269c"); // "ccaron" put("vD", "\\u270D"); // "Dcaron" // Symbol #271 (d) has no special Latex command put("DJ", "\\u272D"); // "Dstrok" put("dj", "\\u273d"); // "dstrok" put("=E", "\\u274E"); // "Emacr" put("=e", "\\u275e"); // "emacr" put("uE", "\\u276E"); // "Ebreve" put("ue", "\\u277e"); // "ebreve" put(".E", "\\u278E"); // "Edot" put(".e", "\\u279e"); // "edot" put("kE", "\\u280E"); // "Eogon" put("ke", "\\u281e"); // "eogon" put("vE", "\\u282E"); // "Ecaron" put("ve", "\\u283e"); // "ecaron" put("^G", "\\u284G"); // "Gcirc" put("^g", "\\u285g"); // "gcirc" put("uG", "\\u286G"); // "Gbreve" put("ug", "\\u287g"); // "gbreve" put(".G", "\\u288G"); // "Gdot" put(".g", "\\u289g"); // "gdot" put("cG", "\\u290G"); // "Gcedil" put("'g", "\\u291g"); // "gacute" put("^H", "\\u292H"); // "Hcirc" put("^h", "\\u293h"); // "hcirc" put("Hstrok", "\\u294H"); // "Hstrok" put("hstrok", "\\u295h"); // "hstrok" put("~I", "\\u296I"); // "Itilde" put("~i", "\\u297i"); // "itilde" put("=I", "\\u298I"); // "Imacr" put("=i", "\\u299i"); // "imacr" put("uI", "\\u300I"); // "Ibreve" put("ui", "\\u301i"); // "ibreve" put("kI", "\\u302I"); // "Iogon" put("ki", "\\u303i"); // "iogon" put(".I", "\\u304I"); // "Idot" // Symbol #306 (IJ) has no special Latex command // Symbol #307 (ij) has no special Latex command put("^J", "\\u308J"); // "Jcirc" put("^j", "\\u309j"); // "jcirc" put("cK", "\\u310K"); // "Kcedil" put("ck", "\\u311k"); // "kcedil" // Symbol #312 (k) has no special Latex command put("'L", "\\u313L"); // "Lacute" put("'l", "\\u314l"); // "lacute" put("cL", "\\u315L"); // "Lcedil" put("cl", "\\u316l"); // "lcedil" // Symbol #317 (L) has no special Latex command // Symbol #318 (l) has no special Latex command put("Lmidot", "\\u319L"); // "Lmidot" put("lmidot", "\\u320l"); // "lmidot" put("L", "\\u321L"); // "Lstrok" put("l", "\\u322l"); // "lstrok" put("'N", "\\u323N"); // "Nacute" put("'n", "\\u324n"); // "nacute" put("cN", "\\u325N"); // "Ncedil" put("cn", "\\u326n"); // "ncedil" put("vN", "\\u327N"); // "Ncaron" put("vn", "\\u328n"); // "ncaron" // Symbol #329 (n) has no special Latex command put("NG", "\\u330G"); // "ENG" put("ng", "\\u331g"); // "eng" put("=O", "\\u332O"); // "Omacr" put("=o", "\\u333o"); // "omacr" put("uO", "\\u334O"); // "Obreve" put("uo", "\\u335o"); // "obreve" put("HO", "\\u336?"); // "Odblac" put("Ho", "\\u337?"); // "odblac" put("OE", "{\\u338OE}"); // "OElig" put("oe", "{\\u339oe}"); // "oelig" put("'R", "\\u340R"); // "Racute" put("'r", "\\u341r"); // "racute" put("cR", "\\u342R"); // "Rcedil" put("cr", "\\u343r"); // "rcedil" put("vR", "\\u344R"); // "Rcaron" put("vr", "\\u345r"); // "rcaron" put("'S", "\\u346S"); // "Sacute" put("'s", "\\u347s"); // "sacute" put("^S", "\\u348S"); // "Scirc" put("^s", "\\u349s"); // "scirc" put("cS", "\\u350S"); // "Scedil" put("cs", "\\u351s"); // "scedil" put("vS", "\\u352S"); // "Scaron" put("vs", "\\u353s"); // "scaron" put("cT", "\\u354T"); // "Tcedil" put("ct", "\\u355t"); // "tcedil" put("vT", "\\u356T"); // "Tcaron" // Symbol #357 (t) has no special Latex command put("Tstrok", "\\u358T"); // "Tstrok" put("tstrok", "\\u359t"); // "tstrok" put("~U", "\\u360U"); // "Utilde" put("~u", "\\u361u"); // "utilde" put("=U", "\\u362U"); // "Umacr" put("=u", "\\u363u"); // "umacr" put("uU", "\\u364U"); // "Ubreve" put("uu", "\\u365u"); // "ubreve" put("rU", "\\u366U"); // "Uring" put("ru", "\\u367u"); // "uring" put("HU", "\\u368?"); // "Odblac" put("Hu", "\\u369?"); // "odblac" put("kU", "\\u370U"); // "Uogon" put("ku", "\\u371u"); // "uogon" put("^W", "\\u372W"); // "Wcirc" put("^w", "\\u373w"); // "wcirc" put("^Y", "\\u374Y"); // "Ycirc" put("^y", "\\u375y"); // "ycirc" put("\"Y", "\\u376Y"); // "Yuml" put("'Z", "\\u377Z"); // "Zacute" put("'z", "\\u378z"); // "zacute" put(".Z", "\\u379Z"); // "Zdot" put(".z", "\\u380z"); // "zdot" put("vZ", "\\u381Z"); // "Zcaron" put("vz", "\\u382z"); // "zcaron" // Symbol #383 (f) has no special Latex command } private void put(String key, String value) { rtfMap.put(key, value); } public String get(String key) { return rtfMap.get(key); } }
8,946
32.260223
76
java
null
jabref-main/src/main/java/org/jabref/logic/util/strings/StringLengthComparator.java
package org.jabref.logic.util.strings; import java.util.Comparator; public class StringLengthComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { if (o1.length() > o2.length()) { return -1; } else if (o1.length() == o2.length()) { return 0; } return 1; } }
371
20.882353
67
java
null
jabref-main/src/main/java/org/jabref/logic/util/strings/StringManipulator.java
package org.jabref.logic.util.strings; import org.jabref.logic.formatter.casechanger.CapitalizeFormatter; import org.jabref.logic.formatter.casechanger.LowerCaseFormatter; import org.jabref.logic.formatter.casechanger.UpperCaseFormatter; import org.jabref.model.util.ResultingStringState; public class StringManipulator { private enum LetterCase { UPPER, LOWER, CAPITALIZED } enum Direction { NEXT(1), PREVIOUS(-1); public final int OFFSET; Direction(int offset) { this.OFFSET = offset; } } /** * Change word casing in a string from the given position to the next word boundary. * * @param text The text to manipulate. * @param caretPosition The index to start from. * @param targetCase The case mode the string should be changed to. * * @return The resulting text and caret position. */ private static ResultingStringState setWordCase(String text, int caretPosition, LetterCase targetCase) { int nextWordBoundary = getNextWordBoundary(caretPosition, text, Direction.NEXT); // Preserve whitespaces int wordStartPosition = caretPosition; while (wordStartPosition < nextWordBoundary && Character.isWhitespace(text.charAt(wordStartPosition))) { wordStartPosition++; } String result = switch (targetCase) { case UPPER -> (new UpperCaseFormatter()).format(text.substring(wordStartPosition, nextWordBoundary)); case LOWER -> (new LowerCaseFormatter()).format(text.substring(wordStartPosition, nextWordBoundary)); case CAPITALIZED -> (new CapitalizeFormatter()).format(text.substring(wordStartPosition, nextWordBoundary)); }; return new ResultingStringState( nextWordBoundary, text.substring(0, wordStartPosition) + result + text.substring(nextWordBoundary)); } /** * Delete all characters in a string from the given position to the next word boundary. * * @param caretPosition The index to start from. * @param text The text to manipulate. * @param direction The direction to search. * * @return The resulting text and caret position. */ static ResultingStringState deleteUntilWordBoundary(int caretPosition, String text, Direction direction) { // Define cutout range int nextWordBoundary = getNextWordBoundary(caretPosition, text, direction); // Construct new string without cutout return switch (direction) { case NEXT -> new ResultingStringState( caretPosition, text.substring(0, caretPosition) + text.substring(nextWordBoundary)); case PREVIOUS -> new ResultingStringState( nextWordBoundary, text.substring(0, nextWordBoundary) + text.substring(caretPosition)); }; } /** * Utility method to find the next whitespace position in string after text * * @param caretPosition The current caret position * @param text The string to search in * @param direction The direction to move through string * * @return The position of the next whitespace after a word */ static int getNextWordBoundary(int caretPosition, String text, Direction direction) { int i = caretPosition; if (direction == Direction.PREVIOUS) { // Swallow whitespaces while (i > 0 && Character.isWhitespace((text.charAt(i + direction.OFFSET)))) { i += direction.OFFSET; } // Read next word while (i > 0 && !Character.isWhitespace(text.charAt(i + direction.OFFSET))) { i += direction.OFFSET; } } else if (direction == Direction.NEXT) { // Swallow whitespaces while (i < text.length() && Character.isWhitespace(text.charAt(i))) { i += direction.OFFSET; } // Read next word while (i < text.length() && !Character.isWhitespace((text.charAt(i)))) { i += direction.OFFSET; } } return i; } /** * Capitalize the word on the right side of the cursor. * * @param caretPosition The position of the cursor * @param text The string to manipulate * * @return String The resulting text and caret position. */ public static ResultingStringState capitalize(int caretPosition, String text) { return setWordCase(text, caretPosition, LetterCase.CAPITALIZED); } /** * Make all characters in the word uppercase. * * @param caretPosition The position of the cursor * @param text The string to manipulate * * @return String The resulting text and caret position. */ public static ResultingStringState uppercase(int caretPosition, String text) { return setWordCase(text, caretPosition, LetterCase.UPPER); } /** * Make all characters in the word lowercase. * * @param caretPosition The position of the cursor * @param text The string to manipulate * * @return String The resulting text and caret position. */ public static ResultingStringState lowercase(int caretPosition, String text) { return setWordCase(text, caretPosition, LetterCase.LOWER); } /** * Remove the next word on the right side of the cursor. * * @param caretPosition The position of the cursor * @param text The string to manipulate * * @return String The resulting text and caret position. */ public static ResultingStringState killWord(int caretPosition, String text) { return deleteUntilWordBoundary(caretPosition, text, Direction.NEXT); } /** * Remove the previous word on the left side of the cursor. * * @param caretPosition The position of the cursor * @param text The string to manipulate * * @return String The resulting text and caret position. */ public static ResultingStringState backwardKillWord(int caretPosition, String text) { return deleteUntilWordBoundary(caretPosition, text, Direction.PREVIOUS); } }
6,451
35.659091
120
java
null
jabref-main/src/main/java/org/jabref/logic/util/strings/StringSimilarity.java
package org.jabref.logic.util.strings; import java.util.Locale; import info.debatty.java.stringsimilarity.Levenshtein; public class StringSimilarity { private final Levenshtein METRIC_DISTANCE = new Levenshtein(); // edit distance threshold for entry title comparison private final int METRIC_THRESHOLD = 4; /** * String similarity based on Levenshtein, ignoreCase, and fixed metric threshold of 4. * * @param a String to compare * @param b String to compare * @return true if Strings are considered as similar by the algorithm */ public boolean isSimilar(String a, String b) { return editDistanceIgnoreCase(a, b) <= METRIC_THRESHOLD; } public double editDistanceIgnoreCase(String a, String b) { // TODO: Locale is dependent on the language of the strings. English is a good denominator. return METRIC_DISTANCE.distance(a.toLowerCase(Locale.ENGLISH), b.toLowerCase(Locale.ENGLISH)); } }
978
33.964286
102
java
null
jabref-main/src/main/java/org/jabref/logic/util/strings/UnicodeLigaturesMap.java
package org.jabref.logic.util.strings; import java.util.HashMap; public class UnicodeLigaturesMap extends HashMap<String, String> { /** * Ligature mapping taken from https://en.wikipedia.org/wiki/Typographic_ligature#Ligatures_in_Unicode_(Latin_alphabets) * * The mapping is bijective. In case it is ever needed to turn the extended version back to unicode ligatures, the * map can easily be reversed. */ public UnicodeLigaturesMap() { put("\uA732", "AA"); put("\uA733", "aa"); put("\u00C6", "AE"); put("\u00E6", "ae"); put("\uA734", "AO"); put("\uA735", "ao"); put("\uA736", "AU"); put("\uA737", "au"); put("\uA738", "AV"); put("\uA739", "av"); // AV, av with bar put("\uA73A", "AV"); put("\uA73B", "av"); put("\uA73C", "AY"); put("\uA73D", "ay"); put("\uD83D\uDE70", "et"); put("\uFB00", "ff"); put("\uFB01", "fi"); put("\uFB02", "fl"); put("\uFB03", "ffi"); put("\uFB04", "ffl"); put("\uFB05", "ſt"); put("\uFB06", "st"); put("\u0152", "OE"); put("\u0153", "oe"); put("\uA74E", "OO"); put("\uA74F", "oo"); // we explicitly decided to exclude the conversion of ß or ẞ // put("\u1E9E", "ſs"); // put("\u00DF", "ſz"); put("\uA728", "TZ"); put("\uA729", "tz"); put("\u1D6B", "ue"); put("\uA760", "VY"); put("\uA761", "vy"); // ligatures for phonetic transcription put("\u0238", "db"); put("\u02A3", "dz"); put("\u02A5", "dʑ"); put("\u02A4", "dʒ"); put("\u02A9", "fŋ"); put("\u0132", "IJ"); put("\u0133", "ij"); put("\u02AA", "ls"); put("\u02AB", "lz"); put("\u026E", "lʒ"); put("\u0239", "qp"); put("\u02A6", "ts"); put("\u02A7", "tʃ"); put("\u02A8", "tɕ"); put("\uAB50", "ui"); put("\uAB51", "turned ui"); } }
2,067
28.971014
124
java
null
jabref-main/src/main/java/org/jabref/logic/util/strings/XmlCharsMap.java
package org.jabref.logic.util.strings; import java.util.HashMap; public class XmlCharsMap extends HashMap<String, String> { public XmlCharsMap() { put("\\{\\\\\\\"\\{a\\}\\}", "&#x00E4;"); put("\\{\\\\\\\"\\{A\\}\\}", "&#x00C4;"); put("\\{\\\\\\\"\\{e\\}\\}", "&#x00EB;"); put("\\{\\\\\\\"\\{E\\}\\}", "&#x00CB;"); put("\\{\\\\\\\"\\{i\\}\\}", "&#x00EF;"); put("\\{\\\\\\\"\\{I\\}\\}", "&#x00CF;"); put("\\{\\\\\\\"\\{o\\}\\}", "&#x00F6;"); put("\\{\\\\\\\"\\{O\\}\\}", "&#x00D6;"); put("\\{\\\\\\\"\\{u\\}\\}", "&#x00FC;"); put("\\{\\\\\\\"\\{U\\}\\}", "&#x00DC;"); // next 2 rows were missing... put("\\{\\\\\\`\\{a\\}\\}", "&#x00E0;"); put("\\{\\\\\\`\\{A\\}\\}", "&#x00C0;"); put("\\{\\\\\\`\\{e\\}\\}", "&#x00E8;"); put("\\{\\\\\\`\\{E\\}\\}", "&#x00C8;"); put("\\{\\\\\\`\\{i\\}\\}", "&#x00EC;"); put("\\{\\\\\\`\\{I\\}\\}", "&#x00CC;"); put("\\{\\\\\\`\\{o\\}\\}", "&#x00F2;"); put("\\{\\\\\\`\\{O\\}\\}", "&#x00D2;"); put("\\{\\\\\\`\\{u\\}\\}", "&#x00F9;"); put("\\{\\\\\\`\\{U\\}\\}", "&#x00D9;"); // corrected these 10 lines below... put("\\{\\\\\\'\\{a\\}\\}", "&#x00E1;"); put("\\{\\\\\\'\\{A\\}\\}", "&#x00C1;"); put("\\{\\\\\\'\\{e\\}\\}", "&#x00E9;"); put("\\{\\\\\\'\\{E\\}\\}", "&#x00C9;"); put("\\{\\\\\\'\\{i\\}\\}", "&#x00ED;"); put("\\{\\\\\\'\\{I\\}\\}", "&#x00CD;"); put("\\{\\\\\\'\\{o\\}\\}", "&#x00F3;"); put("\\{\\\\\\'\\{O\\}\\}", "&#x00D3;"); put("\\{\\\\\\'\\{u\\}\\}", "&#x00FA;"); put("\\{\\\\\\'\\{U\\}\\}", "&#x00DA;"); // added next four chars... put("\\{\\\\\\'\\{c\\}\\}", "&#x0107;"); put("\\{\\\\\\'\\{C\\}\\}", "&#x0106;"); put("\\{\\\\c\\{c\\}\\}", "&#x00E7;"); put("\\{\\\\c\\{C\\}\\}", "&#x00C7;"); put("\\{\\\\\\\uFFFD\\{E\\}\\}", "&#x00C9;"); put("\\{\\\\\\\uFFFD\\{i\\}\\}", "&#x00ED;"); put("\\{\\\\\\\uFFFD\\{I\\}\\}", "&#x00CD;"); put("\\{\\\\\\\uFFFD\\{o\\}\\}", "&#x00F3;"); put("\\{\\\\\\\uFFFD\\{O\\}\\}", "&#x00D3;"); put("\\{\\\\\\\uFFFD\\{u\\}\\}", "&#x00FA;"); put("\\{\\\\\\\uFFFD\\{U\\}\\}", "&#x00DA;"); put("\\{\\\\\\\uFFFD\\{a\\}\\}", "&#x00E1;"); put("\\{\\\\\\\uFFFD\\{A\\}\\}", "&#x00C1;"); // next 2 rows were missing... put("\\{\\\\\\^\\{a\\}\\}", "&#x00E2;"); put("\\{\\\\\\^\\{A\\}\\}", "&#x00C2;"); put("\\{\\\\\\^\\{o\\}\\}", "&#x00F4;"); put("\\{\\\\\\^\\{O\\}\\}", "&#x00D4;"); put("\\{\\\\\\^\\{u\\}\\}", "&#x00F9;"); put("\\{\\\\\\^\\{U\\}\\}", "&#x00D9;"); put("\\{\\\\\\^\\{e\\}\\}", "&#x00EA;"); put("\\{\\\\\\^\\{E\\}\\}", "&#x00CA;"); put("\\{\\\\\\^\\{i\\}\\}", "&#x00EE;"); put("\\{\\\\\\^\\{I\\}\\}", "&#x00CE;"); put("\\{\\\\\\~\\{o\\}\\}", "&#x00F5;"); put("\\{\\\\\\~\\{O\\}\\}", "&#x00D5;"); put("\\{\\\\\\~\\{n\\}\\}", "&#x00F1;"); put("\\{\\\\\\~\\{N\\}\\}", "&#x00D1;"); put("\\{\\\\\\~\\{a\\}\\}", "&#x00E3;"); put("\\{\\\\\\~\\{A\\}\\}", "&#x00C3;"); put("\\{\\\\\\\"a\\}", "&#x00E4;"); put("\\{\\\\\\\"A\\}", "&#x00C4;"); put("\\{\\\\\\\"e\\}", "&#x00EB;"); put("\\{\\\\\\\"E\\}", "&#x00CB;"); put("\\{\\\\\\\"i\\}", "&#x00EF;"); put("\\{\\\\\\\"I\\}", "&#x00CF;"); put("\\{\\\\\\\"o\\}", "&#x00F6;"); put("\\{\\\\\\\"O\\}", "&#x00D6;"); put("\\{\\\\\\\"u\\}", "&#x00FC;"); put("\\{\\\\\\\"U\\}", "&#x00DC;"); // next 2 rows were missing... put("\\{\\\\\\`a\\}", "&#x00E0;"); put("\\{\\\\\\`A\\}", "&#x00C0;"); put("\\{\\\\\\`e\\}", "&#x00E8;"); put("\\{\\\\\\`E\\}", "&#x00C8;"); put("\\{\\\\\\`i\\}", "&#x00EC;"); put("\\{\\\\\\`I\\}", "&#x00CC;"); put("\\{\\\\\\`o\\}", "&#x00F2;"); put("\\{\\\\\\`O\\}", "&#x00D2;"); put("\\{\\\\\\`u\\}", "&#x00F9;"); put("\\{\\\\\\`U\\}", "&#x00D9;"); put("\\{\\\\\\'e\\}", "&#x00E9;"); put("\\{\\\\\\'E\\}", "&#x00C9;"); put("\\{\\\\\\'i\\}", "&#x00ED;"); put("\\{\\\\\\'I\\}", "&#x00CD;"); put("\\{\\\\\\'o\\}", "&#x00F3;"); put("\\{\\\\\\'O\\}", "&#x00D3;"); put("\\{\\\\\\'u\\}", "&#x00FA;"); put("\\{\\\\\\'U\\}", "&#x00DA;"); put("\\{\\\\\\'a\\}", "&#x00E1;"); put("\\{\\\\\\'A\\}", "&#x00C1;"); // added next two chars... put("\\{\\\\\\'c\\}", "&#x0107;"); put("\\{\\\\\\'C\\}", "&#x0106;"); // next two lines were wrong... put("\\{\\\\\\^a\\}", "&#x00E2;"); put("\\{\\\\\\^A\\}", "&#x00C2;"); put("\\{\\\\\\^o\\}", "&#x00F4;"); put("\\{\\\\\\^O\\}", "&#x00D4;"); put("\\{\\\\\\^u\\}", "&#x00F9;"); put("\\{\\\\\\^U\\}", "&#x00D9;"); put("\\{\\\\\\^e\\}", "&#x00EA;"); put("\\{\\\\\\^E\\}", "&#x00CA;"); put("\\{\\\\\\^i\\}", "&#x00EE;"); put("\\{\\\\\\^I\\}", "&#x00CE;"); put("\\{\\\\\\~o\\}", "&#x00F5;"); put("\\{\\\\\\~O\\}", "&#x00D5;"); put("\\{\\\\\\~n\\}", "&#x00F1;"); put("\\{\\\\\\~N\\}", "&#x00D1;"); put("\\{\\\\\\~a\\}", "&#x00E3;"); put("\\{\\\\\\~A\\}", "&#x00C3;"); } }
5,462
39.466667
58
java
null
jabref-main/src/main/java/org/jabref/logic/xmp/DocumentInformationExtractor.java
package org.jabref.logic.xmp; import java.util.Map; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryTypeFactory; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDDocumentInformation; public class DocumentInformationExtractor { private final PDDocumentInformation documentInformation; private final BibEntry bibEntry; public DocumentInformationExtractor(PDDocumentInformation documentInformation) { this.documentInformation = documentInformation; this.bibEntry = new BibEntry(); } private void extractAuthor() { String s = documentInformation.getAuthor(); if (s != null) { bibEntry.setField(StandardField.AUTHOR, s); } } private void extractTitle() { String s = documentInformation.getTitle(); if (s != null) { bibEntry.setField(StandardField.TITLE, s); } } private void extractKeywords() { String s = documentInformation.getKeywords(); if (s != null) { bibEntry.setField(StandardField.KEYWORDS, s); } } private void extractSubject() { String s = documentInformation.getSubject(); if (s != null) { bibEntry.setField(StandardField.ABSTRACT, s); } } private void extractOtherFields() { COSDictionary dict = documentInformation.getCOSObject(); for (Map.Entry<COSName, COSBase> o : dict.entrySet()) { String key = o.getKey().getName(); if (key.startsWith("bibtex/")) { String value = dict.getString(key); key = key.substring("bibtex/".length()); Field field = FieldFactory.parseField(key); if (InternalField.TYPE_HEADER == field) { bibEntry.setType(EntryTypeFactory.parse(value)); } else { bibEntry.setField(field, value); } } } } /** * Function for retrieving a BibEntry from the * PDDocumentInformation in a PDF file. * * To understand how to get hold of a PDDocumentInformation have a look in * the test cases for XMPUtilTest. * * The BibEntry is build by mapping individual fields in the document * information (like author, title, keywords) to fields in a bibtex entry. * * @return The bibtex entry found in the document information. */ public Optional<BibEntry> extractBibtexEntry() { bibEntry.setType(BibEntry.DEFAULT_TYPE); this.extractAuthor(); this.extractTitle(); this.extractKeywords(); this.extractSubject(); this.extractOtherFields(); if (bibEntry.getFields().isEmpty()) { return Optional.empty(); } else { return Optional.of(bibEntry); } } }
3,204
30.116505
84
java
null
jabref-main/src/main/java/org/jabref/logic/xmp/DublinCoreExtractor.java
package org.jabref.logic.xmp; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Consumer; import java.util.function.Predicate; import org.jabref.logic.TypedBibEntry; import org.jabref.logic.formatter.casechanger.UnprotectTermsFormatter; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.Author; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.Date; import org.jabref.model.entry.Month; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.model.strings.StringUtil; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.xmpbox.schema.DublinCoreSchema; import org.apache.xmpbox.type.BadFieldValueException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is used for <em>both</em> conversion from Dublin Core to BibTeX and conversion form BibTeX to Dublin Core */ public class DublinCoreExtractor { public static final String DC_COVERAGE = "coverage"; public static final String DC_RIGHTS = "rights"; public static final String DC_SOURCE = "source"; private static final Logger LOGGER = LoggerFactory.getLogger(DublinCoreExtractor.class); private final DublinCoreSchema dcSchema; private final XmpPreferences xmpPreferences; private final BibEntry bibEntry; private final UnprotectTermsFormatter unprotectTermsFormatter = new UnprotectTermsFormatter(); /** * @param dcSchema Metadata in DublinCore format. * @param resolvedEntry The BibEntry object, which is filled during metadata extraction. */ public DublinCoreExtractor(DublinCoreSchema dcSchema, XmpPreferences xmpPreferences, BibEntry resolvedEntry) { this.dcSchema = dcSchema; this.xmpPreferences = xmpPreferences; this.bibEntry = resolvedEntry; } /** * Editor in BibTeX - Contributor in DublinCore */ private void extractEditor() { List<String> contributors = dcSchema.getContributors(); if ((contributors != null) && !contributors.isEmpty()) { bibEntry.setField(StandardField.EDITOR, String.join(" and ", contributors)); } } /** * Author in BibTeX - Creator in DublinCore */ private void extractAuthor() { List<String> creators = dcSchema.getCreators(); if ((creators != null) && !creators.isEmpty()) { bibEntry.setField(StandardField.AUTHOR, String.join(" and ", creators)); } } /** * BibTeX-Fields : year, [month], [day] - 'dc:date' in DublinCore */ private void extractDate() { List<String> dates = dcSchema.getUnqualifiedSequenceValueList("date"); if ((dates != null) && !dates.isEmpty()) { String date = dates.get(0).trim(); Date.parse(date) .ifPresent(dateValue -> { dateValue.getDay().ifPresent(day -> bibEntry.setField(StandardField.DAY, Integer.toString(day))); dateValue.getMonth().ifPresent(bibEntry::setMonth); dateValue.getYear().ifPresent(year -> bibEntry.setField(StandardField.YEAR, Integer.toString(year))); }); } } /** * Abstract in BibTeX - Description in DublinCore */ private void extractAbstract() { String description = null; try { description = dcSchema.getDescription(); } catch (BadFieldValueException e) { LOGGER.warn("Could not get abstract", e); } if (!StringUtil.isNullOrEmpty(description)) { bibEntry.setField(StandardField.ABSTRACT, description); } } /** * DOI in BibTeX - Identifier in DublinCore */ private void extractDOI() { String identifier = dcSchema.getIdentifier(); if (!StringUtil.isNullOrEmpty(identifier)) { bibEntry.setField(StandardField.DOI, identifier); } } /** * Publisher are equivalent in both formats (BibTeX and DublinCore) */ private void extractPublisher() { List<String> publishers = dcSchema.getPublishers(); if ((publishers != null) && !publishers.isEmpty()) { bibEntry.setField(StandardField.PUBLISHER, String.join(" and ", publishers)); } } /** * This method sets all fields, which are custom in BibTeX and therefore supported by JabRef, but which are not * included in the DublinCore format. * <p> * The relation attribute of DublinCore is abused to store these custom fields. The prefix <code>bibtex</code> is used. */ private void extractBibTexFields() { Predicate<String> isBibTeXElement = s -> s.startsWith("bibtex/"); Consumer<String> splitBibTeXElement = s -> { // the default pattern is bibtex/key/value, but some fields contains url etc. // so the value property contains additional slashes, which makes the usage of // String#split complicated. String temp = s.substring("bibtex/".length()); int i = temp.indexOf('/'); if (i != -1) { Field key = FieldFactory.parseField(temp.substring(0, i)); String value = temp.substring(i + 1); bibEntry.setField(key, value); // only for month field - override value // workaround, because the date value of the xmp component of pdf box is corrupted // see also DublinCoreExtractor#extractYearAndMonth if (StandardField.MONTH == key) { Optional<Month> parsedMonth = Month.parse(value); parsedMonth.ifPresent(bibEntry::setMonth); } } }; List<String> relationships = dcSchema.getRelations(); if (relationships != null) { relationships.stream() .filter(isBibTeXElement) .forEach(splitBibTeXElement); } } /** * Rights are equivalent in both formats (BibTeX and DublinCore) */ private void extractRights() { String rights = null; try { rights = dcSchema.getRights(); } catch (BadFieldValueException e) { LOGGER.warn("Could not extract rights", e); } if (!StringUtil.isNullOrEmpty(rights)) { bibEntry.setField(new UnknownField(DC_RIGHTS), rights); } } /** * Source is equivalent in both formats (BibTeX and DublinCore) */ private void extractSource() { String source = dcSchema.getSource(); if (!StringUtil.isNullOrEmpty(source)) { bibEntry.setField(new UnknownField(DC_SOURCE), source); } } /** * Keywords in BibTeX - Subjects in DublinCore */ private void extractSubject() { List<String> subjects = dcSchema.getSubjects(); if ((subjects != null) && !subjects.isEmpty()) { bibEntry.addKeywords(subjects, xmpPreferences.getKeywordSeparator()); } } /** * Title is equivalent in both formats (BibTeX and DublinCore) */ private void extractTitle() { String title = null; try { title = dcSchema.getTitle(); } catch (BadFieldValueException e) { LOGGER.warn("Could not extract title", e); } if (!StringUtil.isNullOrEmpty(title)) { bibEntry.setField(StandardField.TITLE, title); } } /** * Type is equivalent in both formats (BibTeX and DublinCore) * <p>Opposite method: {@link DublinCoreExtractor#fillType()} */ private void extractType() { List<String> types = dcSchema.getTypes(); if ((types != null) && !types.isEmpty()) { String type = types.get(0); if (!StringUtil.isNullOrEmpty(type)) { bibEntry.setType(EntryTypeFactory.parse(type)); } } } /** * No Equivalent in BibTeX. Will create an Unknown "Coverage" Field */ private void extractCoverage() { String coverage = dcSchema.getCoverage(); if (!StringUtil.isNullOrEmpty(coverage)) { bibEntry.setField(FieldFactory.parseField(DC_COVERAGE), coverage); } } /** * Language is equivalent in both formats (BibTeX and DublinCore) */ private void extractLanguages() { StringBuilder builder = new StringBuilder(); List<String> languages = dcSchema.getLanguages(); if ((languages != null) && !languages.isEmpty()) { languages.forEach(language -> builder.append(",").append(language)); bibEntry.setField(StandardField.LANGUAGE, builder.substring(1)); } } /** * Helper function for retrieving a BibEntry from the DublinCore metadata in a PDF file. * <p> * To understand how to get hold of a DublinCore have a look in the test cases for XMPUtil. * <p> * The BibEntry is build by mapping individual fields in the dublin core (like creator, title, subject) to fields in * a bibtex bibEntry. In case special "bibtex/" entries are contained, the normal dublin core fields take * precedence. For instance, the dublin core date takes precedence over bibtex/month. * <p> * The opposite method is {@link DublinCoreExtractor#fillDublinCoreSchema()} * </p> * * @return The bibEntry extracted from the document information. */ public Optional<BibEntry> extractBibtexEntry() { // first extract "bibtex/" entries this.extractBibTexFields(); // then extract all "standard" dublin core entries this.extractType(); this.extractEditor(); this.extractAuthor(); this.extractDate(); this.extractAbstract(); this.extractDOI(); this.extractPublisher(); this.extractRights(); this.extractSource(); this.extractSubject(); this.extractTitle(); this.extractCoverage(); this.extractLanguages(); // we pass a new BibEntry in the constructor which is never empty as it already consists of "@misc" if (bibEntry.getFieldMap().isEmpty()) { return Optional.empty(); } return Optional.of(bibEntry); } /** * BibTeX: editor; DC: 'dc:contributor' */ private void fillContributor(String authors) { AuthorList list = AuthorList.parse(authors); for (Author author : list.getAuthors()) { dcSchema.addContributor(author.getFirstLast(false)); } } /** * BibTeX: author; DC: 'dc:creator' */ private void fillCreator(String creators) { AuthorList list = AuthorList.parse(creators); for (Author author : list.getAuthors()) { dcSchema.addCreator(author.getFirstLast(false)); } } /** * BibTeX: year, month; DC: 'dc:date' */ private void fillDate() { bibEntry.getFieldOrAlias(StandardField.DATE) .ifPresent(publicationDate -> dcSchema.addUnqualifiedSequenceValue("date", publicationDate)); } /** * BibTeX: abstract; DC: 'dc:description' */ private void fillDescription(String description) { dcSchema.setDescription(description); } /** * BibTeX:doi; DC: 'dc:identifier' */ private void fillIdentifier(String identifier) { dcSchema.setIdentifier(identifier); } /** * BibTeX: publisher, DC: dc:publisher */ private void fillPublisher(String publisher) { dcSchema.addPublisher(publisher); } /** * BibTeX: keywords; DC: 'dc:subject' */ private void fillKeywords(String value) { String[] keywords = value.split(xmpPreferences.getKeywordSeparator().toString()); for (String keyword : keywords) { dcSchema.addSubject(keyword.trim()); } } /** * BibTeX: title; DC: 'dc:title' */ private void fillTitle(String title) { dcSchema.setTitle(title); } /** * BibTeX: Coverage (Custom Field); DC Field : Coverage */ private void fillCoverage(String coverage) { dcSchema.setCoverage(coverage); } /** * BibTeX: language; DC: dc:language */ private void fillLanguages(String languages) { Arrays.stream(languages.split(",")) .forEach(dcSchema::addLanguage); } /** * BibTeX: Rights (Custom Field); DC: dc:rights */ private void fillRights(String rights) { dcSchema.addRights(null, rights.split(",")[0]); } /** * BibTeX: Source (Custom Field); DC: Source */ private void fillSource(String source) { dcSchema.setSource(source); } /** * All others (+ citation key) get packaged in the dc:relation attribute with <code>bibtex/</code> prefix in the content. * The value of the given field is fetched from the class variable {@link DublinCoreExtractor#bibEntry}. */ private void fillCustomField(Field field) { // We write the plain content of the field, because this is a custom DC field content with the semantics that // BibTeX data is stored. Thus, we do not need to get rid of BibTeX, but can keep it. String value = bibEntry.getField(field).get(); dcSchema.addRelation("bibtex/" + field.getName() + '/' + value); } /** * Opposite method: {@link DublinCoreExtractor#extractType()} */ private void fillType() { // BibTeX: entry type; DC: 'dc:type' TypedBibEntry typedEntry = new TypedBibEntry(bibEntry, BibDatabaseMode.BIBTEX); String typeForDisplay = typedEntry.getTypeForDisplay(); if (!typeForDisplay.isEmpty()) { dcSchema.addType(typeForDisplay); } } /** * Converts the content of the bibEntry to dublin core. * <p> * The opposite method is {@link DublinCoreExtractor#extractBibtexEntry()}. * <p> * A similar method for writing the DocumentInformationItem (DII) is {@link XmpUtilWriter#writeDocumentInformation(PDDocument, BibEntry, BibDatabase, XmpPreferences)} * </p> */ public void fillDublinCoreSchema() { // Query privacy filter settings boolean useXmpPrivacyFilter = xmpPreferences.shouldUseXmpPrivacyFilter(); SortedSet<Field> fields = new TreeSet<>(Comparator.comparing(Field::getName)); fields.addAll(bibEntry.getFields()); for (Field field : fields) { if (useXmpPrivacyFilter && xmpPreferences.getXmpPrivacyFilter().contains(field)) { continue; } String value = unprotectTermsFormatter.format(bibEntry.getField(field).get()); if (field instanceof StandardField standardField) { switch (standardField) { case EDITOR -> this.fillContributor(value); case AUTHOR -> this.fillCreator(value); case YEAR -> this.fillDate(); case ABSTRACT -> this.fillDescription(value); case DOI -> this.fillIdentifier(value); case PUBLISHER -> this.fillPublisher(value); case KEYWORDS -> this.fillKeywords(value); case TITLE -> this.fillTitle(value); case LANGUAGE -> this.fillLanguages(value); case FILE -> { // we do not write the "file" field, because the file is the PDF itself } case DAY, MONTH -> { // we do not write day and month separately if dc:year can be used if (!bibEntry.hasField(StandardField.YEAR)) { this.fillCustomField(field); } } default -> this.fillCustomField(field); } } else { if (DC_COVERAGE.equals(field.getName())) { this.fillCoverage(value); } else if (DC_RIGHTS.equals(field.getName())) { this.fillRights(value); } else if (DC_SOURCE.equals(field.getName())) { this.fillSource(value); } else { this.fillCustomField(field); } } } dcSchema.setFormat("application/pdf"); fillType(); } }
17,203
34.619048
174
java
null
jabref-main/src/main/java/org/jabref/logic/xmp/EncryptedPdfsNotSupportedException.java
package org.jabref.logic.xmp; import java.io.IOException; public class EncryptedPdfsNotSupportedException extends IOException { // no additional information needed }
172
20.625
69
java
null
jabref-main/src/main/java/org/jabref/logic/xmp/XmpPreferences.java
package org.jabref.logic.xmp; import java.util.Set; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import org.jabref.model.entry.field.Field; public class XmpPreferences { private final BooleanProperty useXmpPrivacyFilter; private final ObservableSet<Field> xmpPrivacyFilter; private final ObjectProperty<Character> keywordSeparator; public XmpPreferences(boolean useXmpPrivacyFilter, Set<Field> xmpPrivacyFilter, ObjectProperty<Character> keywordSeparator) { this.useXmpPrivacyFilter = new SimpleBooleanProperty(useXmpPrivacyFilter); this.xmpPrivacyFilter = FXCollections.observableSet(xmpPrivacyFilter); this.keywordSeparator = keywordSeparator; } public boolean shouldUseXmpPrivacyFilter() { return useXmpPrivacyFilter.getValue(); } public BooleanProperty useXmpPrivacyFilterProperty() { return useXmpPrivacyFilter; } public void setUseXmpPrivacyFilter(boolean useXmpPrivacyFilter) { this.useXmpPrivacyFilter.set(useXmpPrivacyFilter); } public ObservableSet<Field> getXmpPrivacyFilter() { return xmpPrivacyFilter; } public Character getKeywordSeparator() { return keywordSeparator.getValue(); } }
1,413
30.422222
129
java
null
jabref-main/src/main/java/org/jabref/logic/xmp/XmpUtilReader.java
package org.jabref.logic.xmp; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.schema.DublinCoreSchemaCustom; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.common.PDMetadata; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.schema.DublinCoreSchema; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class XmpUtilReader { private static final Logger LOGGER = LoggerFactory.getLogger(XmpUtilReader.class); private static final String START_TAG = "<rdf:Description"; private static final String END_TAG = "</rdf:Description>"; public XmpUtilReader() { // See: https://pdfbox.apache.org/2.0/getting-started.html System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider"); // To get higher rendering speed on java 8 oder 9 for images } /** * Will read the XMPMetadata from the given pdf file, closing the file afterwards. * * @param path The path to read the XMPMetadata from. * @return The XMPMetadata object found in the file */ public List<XMPMetadata> readRawXmp(Path path) throws IOException { try (PDDocument document = loadWithAutomaticDecryption(path)) { return getXmpMetadata(document); } } /** * Try to read the given BibTexEntry from the XMP-stream of the given * inputstream containing a PDF-file. * * Only supports Dublin Core as a metadata format. * * @param path The path to read from. * @return list of BibEntries retrieved from the stream. May be empty, but never null * @throws IOException Throws an IOException if the file cannot be read, so the user than remove a lock or cancel * the operation. */ public List<BibEntry> readXmp(Path path, XmpPreferences xmpPreferences) throws IOException { List<BibEntry> result = new LinkedList<>(); try (PDDocument document = loadWithAutomaticDecryption(path)) { List<XMPMetadata> xmpMetaList = getXmpMetadata(document); if (!xmpMetaList.isEmpty()) { // Only support Dublin Core since JabRef 4.2 for (XMPMetadata xmpMeta : xmpMetaList) { DublinCoreSchema dcSchema = DublinCoreSchemaCustom.copyDublinCoreSchema(xmpMeta.getDublinCoreSchema()); if (dcSchema != null) { DublinCoreExtractor dcExtractor = new DublinCoreExtractor(dcSchema, xmpPreferences, new BibEntry()); Optional<BibEntry> entry = dcExtractor.extractBibtexEntry(); entry.ifPresent(result::add); } } } if (result.isEmpty()) { // If we did not find any XMP metadata, search for non XMP metadata PDDocumentInformation documentInformation = document.getDocumentInformation(); DocumentInformationExtractor diExtractor = new DocumentInformationExtractor(documentInformation); Optional<BibEntry> entry = diExtractor.extractBibtexEntry(); entry.ifPresent(result::add); } } result.forEach(entry -> entry.addFile(new LinkedFile("", path.toAbsolutePath(), "PDF"))); return result; } /** * This method is a hack to generate multiple XMPMetadata objects, because the * implementation of the pdfbox does not support methods for reading multiple * DublinCoreSchemas from a single metadata entry. * <p/> * * * @return empty List if no metadata has been found, or cannot properly find start or end tag in metadata */ private List<XMPMetadata> getXmpMetadata(PDDocument document) { PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata metaRaw = catalog.getMetadata(); List<XMPMetadata> metaList = new ArrayList<>(); if (metaRaw == null) { return metaList; } String xmp = metaRaw.getCOSObject().toTextString(); int startDescriptionSection = xmp.indexOf(START_TAG); int endDescriptionSection = xmp.lastIndexOf(END_TAG) + END_TAG.length(); if ((startDescriptionSection < 0) || (startDescriptionSection > endDescriptionSection) || (endDescriptionSection == (END_TAG.length() - 1))) { return metaList; } // XML header for the xmpDomParser String start = xmp.substring(0, startDescriptionSection); // descriptionArray - mid part of the textual metadata String[] descriptionsArray = xmp.substring(startDescriptionSection, endDescriptionSection).split(END_TAG); // XML footer for the xmpDomParser String end = xmp.substring(endDescriptionSection); for (String s : descriptionsArray) { // END_TAG is appended, because of the split operation above String xmpMetaString = start + s + END_TAG + end; try { metaList.add(XmpUtilShared.parseXmpMetadata(new ByteArrayInputStream(xmpMetaString.getBytes()))); } catch (IOException ex) { LOGGER.warn("Problem parsing XMP schema. Continuing with other schemas.", ex); } } return metaList; } /** * Loads the specified file with the basic pdfbox functionality and uses an empty string as default password. * * @param path The path to load. * @throws IOException from the underlying @link PDDocument#load(File) */ public PDDocument loadWithAutomaticDecryption(Path path) throws IOException { // try to load the document // also uses an empty string as default password return Loader.loadPDF(path.toFile()); } }
6,187
40.253333
150
java
null
jabref-main/src/main/java/org/jabref/logic/xmp/XmpUtilShared.java
package org.jabref.logic.xmp; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.util.List; import org.jabref.model.entry.BibEntry; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.xml.DomXmpParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * XMPUtilShared provides support for reading (@link XMPUtilReader) and writing (@link XMPUtilWriter) BibTex data as XMP metadata * in PDF-documents. */ public class XmpUtilShared { private static final Logger LOGGER = LoggerFactory.getLogger(XmpUtilShared.class); private XmpUtilShared() { } protected static XMPMetadata parseXmpMetadata(InputStream is) throws IOException { XMPMetadata meta; try { DomXmpParser parser = new DomXmpParser(); meta = parser.parse(is); return meta; } catch (Exception e) { // bad style to catch Exception but as this is called in a loop we do not want to break here when any schema encounters an error throw new IOException(e); } } /** * Will try to read XMP metadata from the given file, returning whether * metadata was found. * * Caution: This method is as expensive as it is reading the actual metadata * itself from the PDF. * * @param path the path to the PDF. * @return whether a BibEntry was found in the given PDF. */ public static boolean hasMetadata(Path path, XmpPreferences xmpPreferences) { try { List<BibEntry> bibEntries = new XmpUtilReader().readXmp(path, xmpPreferences); return !bibEntries.isEmpty(); } catch (EncryptedPdfsNotSupportedException ex) { LOGGER.info("Encryption not supported by XMPUtil"); return false; } catch (IOException e) { XmpUtilShared.LOGGER.debug("No metadata was found. Path: {}", path.toString()); return false; } } }
1,994
31.704918
140
java
null
jabref-main/src/main/java/org/jabref/logic/xmp/XmpUtilWriter.java
package org.jabref.logic.xmp; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.xml.transform.TransformerException; import org.jabref.logic.exporter.EmbeddedBibFilePdfExporter; import org.jabref.logic.formatter.casechanger.UnprotectTermsFormatter; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.model.schema.DublinCoreSchemaCustom; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.common.PDMetadata; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.schema.DublinCoreSchema; import org.apache.xmpbox.xml.XmpSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Writes given BibEntries into the XMP part of a PDF file. * * The conversion of a BibEntry to the XMP data (using Dublin Core) is done at * {@link DublinCoreExtractor#fillDublinCoreSchema()} */ public class XmpUtilWriter { private static final String XMP_BEGIN_END_TAG = "?xpacket"; private static final Logger LOGGER = LoggerFactory.getLogger(XmpUtilWriter.class); private final UnprotectTermsFormatter unprotectTermsFormatter = new UnprotectTermsFormatter(); private final XmpPreferences xmpPreferences; public XmpUtilWriter(XmpPreferences xmpPreferences) { this.xmpPreferences = xmpPreferences; } /** * Try to write the given BibTexEntry in the XMP-stream of the given * PDF-file. * * Throws an IOException if the file cannot be read or written, so the user * can remove a lock or cancel the operation. * * The method will overwrite existing BibTeX-XMP-data, but keep other * existing metadata. * * This is a convenience method for writeXMP(File, Collection). * * @param file The path to write to. * @param entry The entry to write. * @param database An optional database which the given bibtex entries belong to, which will be used to * resolve strings. If the database is null the strings will not be resolved. * @throws TransformerException If the entry was malformed or unsupported. * @throws IOException If the file could not be written to or could not be found. */ public void writeXmp(Path file, BibEntry entry, BibDatabase database) throws IOException, TransformerException { writeXmp(file, List.of(entry), database); } /** * Writes the information of the bib entry to the dublin core schema using * a custom extractor. * * @param dcSchema Dublin core schema, which is filled with the bib entry. * @param entry The entry, which is added to the dublin core metadata. * @param database An optional database which the given bibtex entries belong to, which will be used to * resolve strings. If the database is null the strings will not be resolved. */ private void writeToDCSchema(DublinCoreSchema dcSchema, BibEntry entry, BibDatabase database) { BibEntry resolvedEntry = getDefaultOrDatabaseEntry(entry, database); writeToDCSchema(dcSchema, resolvedEntry); } /** * Writes the information of the bib entry to the dublin core schema using a custom extractor. * * @param dcSchema Dublin core schema, which is filled with the bib entry. * @param entry The entry, which is added to the dublin core metadata. */ private void writeToDCSchema(DublinCoreSchema dcSchema, BibEntry entry) { DublinCoreExtractor dcExtractor = new DublinCoreExtractor(dcSchema, xmpPreferences, entry); dcExtractor.fillDublinCoreSchema(); } /** * Try to write the given BibTexEntries as DublinCore XMP Schemas * * Existing DublinCore schemas in the document are removed * * @param document The pdf document to write to. * @param entries The BibTeX entries that are written as schemas * @param database An optional database which the given BibTeX entries belong to, which will be used to * resolve strings. If the database is null the strings will not be resolved. */ private void writeDublinCore(PDDocument document, List<BibEntry> entries, BibDatabase database) throws IOException, TransformerException { List<BibEntry> resolvedEntries; if (database == null) { resolvedEntries = entries; } else { resolvedEntries = database.resolveForStrings(entries, false); } PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata metaRaw = catalog.getMetadata(); XMPMetadata meta; if (metaRaw == null) { meta = XMPMetadata.createXMPMetadata(); } else { try { meta = XmpUtilShared.parseXmpMetadata(metaRaw.createInputStream()); // In case, that the pdf file has no namespace definition for xmp, // but metadata in a different format, the parser throws an exception // Creating an empty xmp metadata element solves this problem } catch (IOException e) { meta = XMPMetadata.createXMPMetadata(); } } // Remove all current Dublin-Core schemas meta.removeSchema(meta.getDublinCoreSchema()); for (BibEntry entry : resolvedEntries) { DublinCoreSchema dcSchema = DublinCoreSchemaCustom.copyDublinCoreSchema(meta.createAndAddDublinCoreSchema()); writeToDCSchema(dcSchema, entry, null); } // Save to stream and then input that stream to the PDF ByteArrayOutputStream os = new ByteArrayOutputStream(); XmpSerializer serializer = new XmpSerializer(); serializer.serialize(meta, os, true); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); PDMetadata metadataStream = new PDMetadata(document, is); catalog.setMetadata(metadataStream); } /** * This method generates an xmp metadata string in dublin core format. * * @param entries A list of entries, which are added to the dublin core metadata. * * @return If something goes wrong (e.g. an exception is thrown), the method returns an empty string, * otherwise it returns the xmp metadata as a string in dublin core format. */ private String generateXmpStringWithXmpDeclaration(List<BibEntry> entries) { XMPMetadata meta = XMPMetadata.createXMPMetadata(); for (BibEntry entry : entries) { DublinCoreSchema dcSchema = meta.createAndAddDublinCoreSchema(); writeToDCSchema(dcSchema, entry); } try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { XmpSerializer serializer = new XmpSerializer(); serializer.serialize(meta, os, true); return os.toString(StandardCharsets.UTF_8); } catch (TransformerException e) { LOGGER.warn("Transformation into XMP not possible: " + e.getMessage(), e); return ""; } catch (UnsupportedEncodingException e) { LOGGER.warn("Unsupported encoding to UTF-8 of bib entries in XMP metadata.", e); return ""; } catch (IOException e) { LOGGER.warn("IO Exception thrown by closing the output stream.", e); return ""; } } /** * This method generates an xmp metadata string in dublin core format without the * metadata section <?xpacket begin=...>. * <br/> * * @param entries A list of entries, which are added to the dublin core metadata. * * @return If something goes wrong (e.g. an exception is thrown), the method returns an empty string, * otherwise it returns the xmp metadata without metadata description as a string in dublin core format. */ public String generateXmpStringWithoutXmpDeclaration(List<BibEntry> entries) { String xmpContent = generateXmpStringWithXmpDeclaration(entries); // remove the <?xpacket *> tags to enable the usage of the CTAN package xmpincl Predicate<String> isBeginOrEndTag = s -> s.contains(XMP_BEGIN_END_TAG); return Arrays.stream(xmpContent.split(System.lineSeparator())) .filter(isBeginOrEndTag.negate()) .collect(Collectors.joining(System.lineSeparator())); } /** * Try to write the given BibTexEntry in the Document Information (the * properties of the pdf). * <p> * Existing fields values are overridden if the bibtex entry has the * corresponding value set. * <p> * The method to write DublinCore is {@link DublinCoreExtractor#fillDublinCoreSchema()} * * @param document The pdf document to write to. * @param entry The Bibtex entry that is written into the PDF properties. * * @param database An optional database which the given bibtex entries belong to, which will be used to * resolve strings. If the database is null the strings will not be resolved. */ private void writeDocumentInformation(PDDocument document, BibEntry entry, BibDatabase database) { PDDocumentInformation di = document.getDocumentInformation(); BibEntry resolvedEntry = getDefaultOrDatabaseEntry(entry, database); boolean useXmpPrivacyFilter = xmpPreferences.shouldUseXmpPrivacyFilter(); for (Field field : resolvedEntry.getFields()) { if (useXmpPrivacyFilter && xmpPreferences.getXmpPrivacyFilter().contains(field)) { // erase field instead of adding it if (StandardField.AUTHOR == field) { di.setAuthor(null); } else if (StandardField.TITLE == field) { di.setTitle(null); } else if (StandardField.KEYWORDS == field) { di.setKeywords(null); } else if (StandardField.ABSTRACT == field) { di.setSubject(null); } else { di.setCustomMetadataValue("bibtex/" + field, null); } continue; } // LaTeX content is removed from the string for "standard" fields in the PDF String value = unprotectTermsFormatter.format(resolvedEntry.getField(field).get()); if (StandardField.AUTHOR == field) { di.setAuthor(value); } else if (StandardField.TITLE == field) { di.setTitle(value); } else if (StandardField.KEYWORDS == field) { di.setKeywords(value); } else if (StandardField.ABSTRACT == field) { di.setSubject(value); } else { // We hit the case of an PDF-unsupported field --> write it directly di.setCustomMetadataValue("bibtex/" + field, resolvedEntry.getField(field).get()); } } di.setCustomMetadataValue("bibtex/entrytype", resolvedEntry.getType().getDisplayName()); } /** * Try to write the given BibTexEntry in the XMP-stream of the given * PDF-file. * * Throws an IOException if the file cannot be read or written, so the user * can remove a lock or cancel the operation. * * The method will overwrite existing BibTeX-XMP-data, but keep other * existing metadata. * * The code for using PDFBox is also used at {@link EmbeddedBibFilePdfExporter#embedBibTex(String, Path)}. * * @param path The file to write the entries to. * @param bibtexEntries The entries to write to the file. * * @param database An optional database which the given bibtex entries belong to, which will be used * to resolve strings. If the database is null the strings will not be resolved. * @throws TransformerException If the entry was malformed or unsupported. * @throws IOException If the file could not be written to or could not be found. */ public void writeXmp(Path path, List<BibEntry> bibtexEntries, BibDatabase database) throws IOException, TransformerException { List<BibEntry> resolvedEntries; if (database == null) { resolvedEntries = bibtexEntries; } else { resolvedEntries = database.resolveForStrings(bibtexEntries, false); } // Read from another file // Reason: Apache PDFBox does not support writing while the file is opened // See https://issues.apache.org/jira/browse/PDFBOX-4028 Path newFile = Files.createTempFile("JabRef", "pdf"); try (PDDocument document = Loader.loadPDF(path.toFile())) { if (document.isEncrypted()) { throw new EncryptedPdfsNotSupportedException(); } // Write schemas (PDDocumentInformation and DublinCoreSchema) to the document metadata if (resolvedEntries.size() > 0) { writeDocumentInformation(document, resolvedEntries.get(0), null); writeDublinCore(document, resolvedEntries, null); } // Save updates to original file try { document.save(newFile.toFile()); FileUtil.copyFile(newFile, path, true); } catch (IOException e) { LOGGER.debug("Could not write XMP metadata", e); throw new TransformerException("Could not write XMP metadata: " + e.getLocalizedMessage(), e); } } Files.delete(newFile); } private BibEntry getDefaultOrDatabaseEntry(BibEntry defaultEntry, BibDatabase database) { if (database == null) { return defaultEntry; } else { return database.resolveForStrings(defaultEntry, false); } } }
14,850
42.93787
121
java
null
jabref-main/src/main/java/org/jabref/migrations/ConvertLegacyExplicitGroups.java
package org.jabref.migrations; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.jabref.logic.importer.ParserResult; import org.jabref.model.entry.BibEntry; import org.jabref.model.groups.ExplicitGroup; import org.jabref.model.groups.GroupTreeNode; /** * Converts legacy explicit groups, where the group contained a list of assigned entries, to the new format, * where the entry stores a list of groups it belongs to. */ public class ConvertLegacyExplicitGroups implements PostOpenMigration { @Override public void performMigration(ParserResult parserResult) { Objects.requireNonNull(parserResult); if (!parserResult.getMetaData().getGroups().isPresent()) { return; } for (ExplicitGroup group : getExplicitGroupsWithLegacyKeys(parserResult.getMetaData().getGroups().get())) { for (String entryKey : group.getLegacyEntryKeys()) { for (BibEntry entry : parserResult.getDatabase().getEntriesByCitationKey(entryKey)) { group.add(entry); } } group.clearLegacyEntryKeys(); } } private List<ExplicitGroup> getExplicitGroupsWithLegacyKeys(GroupTreeNode node) { Objects.requireNonNull(node); List<ExplicitGroup> findings = new ArrayList<>(); if (node.getGroup() instanceof ExplicitGroup) { ExplicitGroup group = (ExplicitGroup) node.getGroup(); if (!group.getLegacyEntryKeys().isEmpty()) { findings.add(group); } } node.getChildren().forEach(child -> findings.addAll(getExplicitGroupsWithLegacyKeys(child))); return findings; } }
1,731
32.960784
115
java
null
jabref-main/src/main/java/org/jabref/migrations/ConvertMarkingToGroups.java
package org.jabref.migrations; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.collections.ObservableList; import org.jabref.logic.groups.DefaultGroupsFactory; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.groups.ExplicitGroup; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.GroupTreeNode; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; /** * Converts legacy explicit groups, where the group contained a list of assigned entries, to the new format, * where the entry stores a list of groups it belongs to. */ public class ConvertMarkingToGroups implements PostOpenMigration { private static final Pattern MARKING_PATTERN = Pattern.compile("\\[(.*):(\\d+)\\]"); @Override public void performMigration(ParserResult parserResult) { Objects.requireNonNull(parserResult); ObservableList<BibEntry> entries = parserResult.getDatabase().getEntries(); Multimap<String, BibEntry> markings = getMarkingWithEntries(entries); if (!markings.isEmpty()) { GroupTreeNode markingRoot = GroupTreeNode.fromGroup( new ExplicitGroup(Localization.lang("Markings"), GroupHierarchyType.INCLUDING, ',')); for (Map.Entry<String, Collection<BibEntry>> marking : markings.asMap().entrySet()) { String markingName = marking.getKey(); Collection<BibEntry> markingMatchedEntries = marking.getValue(); GroupTreeNode markingGroup = markingRoot.addSubgroup( new ExplicitGroup(markingName, GroupHierarchyType.INCLUDING, ',')); markingGroup.addEntriesToGroup(markingMatchedEntries); } if (!parserResult.getMetaData().getGroups().isPresent()) { parserResult.getMetaData().setGroups(GroupTreeNode.fromGroup(DefaultGroupsFactory.getAllEntriesGroup())); } GroupTreeNode root = parserResult.getMetaData().getGroups().get(); root.addChild(markingRoot, 0); parserResult.getMetaData().setGroups(root); clearMarkings(entries); } } /** * Looks for markings (such as __markedentry = {[Nicolas:6]}) in the given list of entries. */ private Multimap<String, BibEntry> getMarkingWithEntries(List<BibEntry> entries) { Multimap<String, BibEntry> markings = MultimapBuilder.treeKeys().linkedListValues().build(); for (BibEntry entry : entries) { Optional<String> marking = entry.getField(InternalField.MARKED_INTERNAL); if (!marking.isPresent()) { continue; } Matcher matcher = MARKING_PATTERN.matcher(marking.get()); if (matcher.find()) { String owner = matcher.group(1); String number = matcher.group(2); markings.put(owner + ":" + number, entry); } else { // Not in the expected format, so just add it to not loose information markings.put(marking.get(), entry); } } return markings; } private void clearMarkings(List<BibEntry> entries) { entries.forEach(entry -> entry.clearField(InternalField.MARKED_INTERNAL)); } }
3,622
37.956989
121
java
null
jabref-main/src/main/java/org/jabref/migrations/CustomEntryTypePreferenceMigration.java
package org.jabref.migrations; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.jabref.gui.Globals; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibEntryTypeBuilder; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.preferences.JabRefPreferences; class CustomEntryTypePreferenceMigration { // non-default preferences private static final String CUSTOM_TYPE_NAME = "customTypeName_"; private static final String CUSTOM_TYPE_REQ = "customTypeReq_"; private static final String CUSTOM_TYPE_OPT = "customTypeOpt_"; private static final String CUSTOM_TYPE_PRIOPT = "customTypePriOpt_"; private static JabRefPreferences prefs = Globals.prefs; private CustomEntryTypePreferenceMigration() { } static void upgradeStoredBibEntryTypes(BibDatabaseMode defaultBibDatabaseMode) { List<BibEntryType> storedOldTypes = new ArrayList<>(); int number = 0; Optional<BibEntryType> type; while ((type = getBibEntryType(number)).isPresent()) { Globals.entryTypesManager.addCustomOrModifiedType(type.get(), defaultBibDatabaseMode); storedOldTypes.add(type.get()); number++; } prefs.storeCustomEntryTypesRepository(Globals.entryTypesManager); } /** * Retrieves all deprecated information about the entry type in preferences, with the tag given by number. * <p> * (old implementation which has been copied) */ private static Optional<BibEntryType> getBibEntryType(int number) { String nr = String.valueOf(number); String name = prefs.get(CUSTOM_TYPE_NAME + nr); if (name == null) { return Optional.empty(); } List<String> req = prefs.getStringList(CUSTOM_TYPE_REQ + nr); List<String> opt = prefs.getStringList(CUSTOM_TYPE_OPT + nr); List<String> priOpt = prefs.getStringList(CUSTOM_TYPE_PRIOPT + nr); BibEntryTypeBuilder entryTypeBuilder = new BibEntryTypeBuilder() .withType(EntryTypeFactory.parse(name)) .withRequiredFields(req.stream().map(FieldFactory::parseOrFields).collect(Collectors.toList())); if (priOpt.isEmpty()) { entryTypeBuilder = entryTypeBuilder .withImportantFields(opt.stream().map(FieldFactory::parseField).collect(Collectors.toSet())); return Optional.of(entryTypeBuilder.build()); } else { List<String> secondary = new ArrayList<>(opt); secondary.removeAll(priOpt); entryTypeBuilder = entryTypeBuilder .withImportantFields(priOpt.stream().map(FieldFactory::parseField).collect(Collectors.toSet())) .withDetailFields(secondary.stream().map(FieldFactory::parseField).collect(Collectors.toSet())); return Optional.of(entryTypeBuilder.build()); } } }
3,103
39.842105
116
java
null
jabref-main/src/main/java/org/jabref/migrations/MergeReviewIntoCommentMigration.java
package org.jabref.migrations; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MergeReviewIntoCommentMigration { private static final Logger LOGGER = LoggerFactory.getLogger(MergeReviewIntoCommentMigration.class); public static boolean needsMigration(ParserResult parserResult) { return parserResult.getDatabase().getEntries().stream() .anyMatch(bibEntry -> bibEntry.getField(StandardField.REVIEW).isPresent()); } public void performMigration(ParserResult parserResult) { /* This migration only handles the non-conflicting entries. * For the other see this.performConflictingMigration(). */ List<BibEntry> entries = Objects.requireNonNull(parserResult).getDatabase().getEntries(); entries.stream() .filter(MergeReviewIntoCommentMigration::hasReviewField) .filter(entry -> !MergeReviewIntoCommentMigration.hasCommentField(entry)) .forEach(entry -> migrate(entry, parserResult)); } public static List<BibEntry> collectConflicts(ParserResult parserResult) { List<BibEntry> entries = Objects.requireNonNull(parserResult).getDatabase().getEntries(); return entries.stream() .filter(MergeReviewIntoCommentMigration::hasReviewField) .filter(MergeReviewIntoCommentMigration::hasCommentField) .collect(Collectors.toList()); } public void performConflictingMigration(ParserResult parserResult) { collectConflicts(parserResult).forEach(entry -> migrate(entry, parserResult)); } private static boolean hasCommentField(BibEntry entry) { return entry.getField(StandardField.COMMENT).isPresent(); } private static boolean hasReviewField(BibEntry entry) { return entry.getField(StandardField.REVIEW).isPresent(); } private String mergeCommentFieldIfPresent(BibEntry entry, String review) { if (entry.getField(StandardField.COMMENT).isPresent()) { LOGGER.info(String.format("Both Comment and Review fields are present in %s! Merging them into the comment field.", entry.getAuthorTitleYear(150))); return String.format("%s\n%s:\n%s", entry.getField(StandardField.COMMENT).get().trim(), Localization.lang("Review"), review.trim()); } return review; } private void migrate(BibEntry entry, ParserResult parserResult) { if (hasReviewField(entry)) { updateFields(entry, mergeCommentFieldIfPresent(entry, entry.getField(StandardField.REVIEW).get())); parserResult.wasChangedOnMigration(); } } private void updateFields(BibEntry entry, String review) { entry.setField(StandardField.COMMENT, review); entry.clearField(StandardField.REVIEW); } }
3,130
40.197368
160
java
null
jabref-main/src/main/java/org/jabref/migrations/PostOpenMigration.java
package org.jabref.migrations; import org.jabref.logic.importer.ParserResult; public interface PostOpenMigration { void performMigration(ParserResult parserResult); }
173
20.75
53
java
null
jabref-main/src/main/java/org/jabref/migrations/PreferencesMigrations.java
package org.jabref.migrations; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.UnaryOperator; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import java.util.stream.Collectors; import javafx.scene.control.TableColumn; import org.jabref.gui.maintable.ColumnPreferences; import org.jabref.gui.maintable.MainTableColumnModel; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.logic.cleanup.FieldFormatterCleanups; import org.jabref.logic.shared.security.Password; import org.jabref.logic.util.OS; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.model.strings.StringUtil; import org.jabref.preferences.CleanupPreferences; import org.jabref.preferences.JabRefPreferences; import com.github.javakeyring.Keyring; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PreferencesMigrations { private static final Logger LOGGER = LoggerFactory.getLogger(PreferencesMigrations.class); private PreferencesMigrations() { } /** * Perform checks and changes for users with a preference set from an older JabRef version. */ public static void runMigrations(JabRefPreferences preferences) { Preferences mainPrefsNode = Preferences.userRoot().node("/org/jabref"); upgradePrefsToOrgJabRef(mainPrefsNode); upgradeSortOrder(preferences); upgradeFaultyEncodingStrings(preferences); upgradeLabelPatternToCitationKeyPattern(preferences, mainPrefsNode); upgradeImportFileAndDirePatterns(preferences, mainPrefsNode); upgradeStoredBibEntryTypes(preferences, mainPrefsNode); upgradeKeyBindingsToJavaFX(preferences); addCrossRefRelatedFieldsForAutoComplete(preferences); upgradePreviewStyle(preferences); // changeColumnVariableNamesFor51 needs to be run before upgradeColumnPre50Preferences to ensure // backwardcompatibility, as it copies the old values to new variable names and keeps th old sored with the old // variable names. However, the variables from 5.0 need to be copied to the new variable name too. changeColumnVariableNamesFor51(preferences); upgradeColumnPreferences(preferences); restoreVariablesForBackwardCompatibility(preferences); upgradeCleanups(preferences); moveApiKeysToKeyring(preferences); } /** * Migrate all preferences from net/sf/jabref to org/jabref */ private static void upgradePrefsToOrgJabRef(Preferences mainPrefsNode) { try { if (mainPrefsNode.childrenNames().length != 0) { // skip further processing as prefs already have been migrated LOGGER.debug("New prefs node already exists with content - skipping migration"); } else { if (mainPrefsNode.parent().parent().nodeExists("net/sf/jabref")) { LOGGER.info("Migrating old preferences."); Preferences oldNode = mainPrefsNode.parent().parent().node("net/sf/jabref"); copyPrefsRecursively(oldNode, mainPrefsNode); } } } catch (BackingStoreException ex) { LOGGER.error("Migrating old preferences failed.", ex); } } private static void copyPrefsRecursively(Preferences from, Preferences to) throws BackingStoreException { for (String key : from.keys()) { String newValue = from.get(key, ""); if (newValue.contains("net.sf")) { newValue = newValue.replaceAll("net\\.sf", "org"); } to.put(key, newValue); } for (String child : from.childrenNames()) { Preferences childNode = from.node(child); Preferences newChildNode = to.node(child); copyPrefsRecursively(childNode, newChildNode); } } /** * Added from Jabref 2.11 beta 4 onwards to fix wrong encoding names */ private static void upgradeFaultyEncodingStrings(JabRefPreferences prefs) { String defaultEncoding = prefs.get(JabRefPreferences.DEFAULT_ENCODING); if (defaultEncoding == null) { return; } Map<String, String> encodingMap = new HashMap<>(); encodingMap.put("UTF8", "UTF-8"); encodingMap.put("Cp1250", "CP1250"); encodingMap.put("Cp1251", "CP1251"); encodingMap.put("Cp1252", "CP1252"); encodingMap.put("Cp1253", "CP1253"); encodingMap.put("Cp1254", "CP1254"); encodingMap.put("Cp1257", "CP1257"); encodingMap.put("ISO8859_1", "ISO8859-1"); encodingMap.put("ISO8859_2", "ISO8859-2"); encodingMap.put("ISO8859_3", "ISO8859-3"); encodingMap.put("ISO8859_4", "ISO8859-4"); encodingMap.put("ISO8859_5", "ISO8859-5"); encodingMap.put("ISO8859_6", "ISO8859-6"); encodingMap.put("ISO8859_7", "ISO8859-7"); encodingMap.put("ISO8859_8", "ISO8859-8"); encodingMap.put("ISO8859_9", "ISO8859-9"); encodingMap.put("ISO8859_13", "ISO8859-13"); encodingMap.put("ISO8859_15", "ISO8859-15"); encodingMap.put("KOI8_R", "KOI8-R"); encodingMap.put("Big5_HKSCS", "Big5-HKSCS"); encodingMap.put("EUC_JP", "EUC-JP"); if (encodingMap.containsKey(defaultEncoding)) { prefs.put(JabRefPreferences.DEFAULT_ENCODING, encodingMap.get(defaultEncoding)); } } /** * Upgrade the sort order preferences for the current version * The old preference is kept in case an old version of JabRef is used with * these preferences, but it is only used when the new preference does not * exist */ private static void upgradeSortOrder(JabRefPreferences prefs) { if (prefs.get(JabRefPreferences.EXPORT_IN_SPECIFIED_ORDER, null) == null) { if (prefs.getBoolean("exportInStandardOrder", false)) { prefs.putBoolean(JabRefPreferences.EXPORT_IN_SPECIFIED_ORDER, true); prefs.put(JabRefPreferences.EXPORT_PRIMARY_SORT_FIELD, StandardField.AUTHOR.getName()); prefs.put(JabRefPreferences.EXPORT_SECONDARY_SORT_FIELD, StandardField.EDITOR.getName()); prefs.put(JabRefPreferences.EXPORT_TERTIARY_SORT_FIELD, StandardField.YEAR.getName()); prefs.putBoolean(JabRefPreferences.EXPORT_PRIMARY_SORT_DESCENDING, false); prefs.putBoolean(JabRefPreferences.EXPORT_SECONDARY_SORT_DESCENDING, false); prefs.putBoolean(JabRefPreferences.EXPORT_TERTIARY_SORT_DESCENDING, false); } else if (prefs.getBoolean("exportInTitleOrder", false)) { // exportInTitleOrder => title, author, editor prefs.putBoolean(JabRefPreferences.EXPORT_IN_SPECIFIED_ORDER, true); prefs.put(JabRefPreferences.EXPORT_PRIMARY_SORT_FIELD, StandardField.TITLE.getName()); prefs.put(JabRefPreferences.EXPORT_SECONDARY_SORT_FIELD, StandardField.AUTHOR.getName()); prefs.put(JabRefPreferences.EXPORT_TERTIARY_SORT_FIELD, StandardField.EDITOR.getName()); prefs.putBoolean(JabRefPreferences.EXPORT_PRIMARY_SORT_DESCENDING, false); prefs.putBoolean(JabRefPreferences.EXPORT_SECONDARY_SORT_DESCENDING, false); prefs.putBoolean(JabRefPreferences.EXPORT_TERTIARY_SORT_DESCENDING, false); } } } /** * Migrate all customized entry types from versions <=3.7 */ private static void upgradeStoredBibEntryTypes(JabRefPreferences prefs, Preferences mainPrefsNode) { try { if (mainPrefsNode.nodeExists(JabRefPreferences.CUSTOMIZED_BIBTEX_TYPES) || mainPrefsNode.nodeExists(JabRefPreferences.CUSTOMIZED_BIBLATEX_TYPES)) { // skip further processing as prefs already have been migrated } else { LOGGER.info("Migrating old custom entry types."); CustomEntryTypePreferenceMigration.upgradeStoredBibEntryTypes(prefs.getLibraryPreferences().getDefaultBibDatabaseMode()); } } catch (BackingStoreException ex) { LOGGER.error("Migrating old custom entry types failed.", ex); } } /** * Migrate LabelPattern configuration from versions <=3.5 to new CitationKeyPatterns. * <p> * Introduced in <a href="https://github.com/JabRef/jabref/pull/1704">#1704</a> */ private static void upgradeLabelPatternToCitationKeyPattern(JabRefPreferences prefs, Preferences mainPrefsNode) { final String V3_6_DEFAULT_BIBTEX_KEYPATTERN = "defaultBibtexKeyPattern"; final String V3_6_BIBTEX_KEYPATTERN_NODE = "bibtexkeypatterns"; final String V3_3_DEFAULT_LABELPATTERN = "defaultLabelPattern"; final String V3_3_LOGIC_LABELPATTERN = "logic/labelpattern"; // version 3.3 - 3.5, mind the case final String V3_0_LOGIC_LABELPATTERN = "logic/labelPattern"; // node used for version 3.0 - 3.2 final String LEGACY_LABELPATTERN = "labelPattern"; // version <3.0 try { // Migrate default pattern if (mainPrefsNode.get(V3_6_DEFAULT_BIBTEX_KEYPATTERN, null) == null) { // Check whether old defaultLabelPattern is set String oldDefault = mainPrefsNode.get(V3_3_DEFAULT_LABELPATTERN, null); if (oldDefault != null) { prefs.put(V3_6_DEFAULT_BIBTEX_KEYPATTERN, oldDefault); LOGGER.info("Upgraded old default key generator pattern '{}' to new version.", oldDefault); } } // Pref node already exists do not migrate from previous version if (mainPrefsNode.nodeExists(V3_6_BIBTEX_KEYPATTERN_NODE)) { return; } // Migrate type specific patterns if (mainPrefsNode.nodeExists(V3_3_LOGIC_LABELPATTERN)) { migrateTypedKeyPrefs(prefs, mainPrefsNode.node(V3_3_LOGIC_LABELPATTERN)); } else if (mainPrefsNode.nodeExists(V3_0_LOGIC_LABELPATTERN)) { migrateTypedKeyPrefs(prefs, mainPrefsNode.node(V3_0_LOGIC_LABELPATTERN)); } else if (mainPrefsNode.nodeExists(LEGACY_LABELPATTERN)) { migrateTypedKeyPrefs(prefs, mainPrefsNode.node(LEGACY_LABELPATTERN)); } } catch (BackingStoreException e) { LOGGER.error("Migrating old bibtexKeyPatterns failed.", e); } } /** * Migrate Import File Name and Directory name Patterns from versions <=4.0 to new BracketedPatterns */ private static void migrateFileImportPattern(String oldStylePattern, String newStylePattern, JabRefPreferences prefs, Preferences mainPrefsNode) { String preferenceFileNamePattern = mainPrefsNode.get(JabRefPreferences.IMPORT_FILENAMEPATTERN, null); if ((preferenceFileNamePattern != null) && oldStylePattern.equals(preferenceFileNamePattern)) { // Upgrade the old-style File Name pattern to new one: mainPrefsNode.put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePattern); LOGGER.info("migrated old style " + JabRefPreferences.IMPORT_FILENAMEPATTERN + " value \"" + oldStylePattern + "\" to new value \"" + newStylePattern + "\" in the preference file"); if (prefs.hasKey(JabRefPreferences.IMPORT_FILENAMEPATTERN)) { // Update also the key in the current application settings, if necessary: String fileNamePattern = prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN); if (oldStylePattern.equals(fileNamePattern)) { prefs.put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePattern); LOGGER.info("migrated old style " + JabRefPreferences.IMPORT_FILENAMEPATTERN + " value \"" + oldStylePattern + "\" to new value \"" + newStylePattern + "\" in the running application"); } } } } static void upgradeImportFileAndDirePatterns(JabRefPreferences prefs, Preferences mainPrefsNode) { // Migrate Import patterns // Check for prefs node for Version <= 4.0 if (mainPrefsNode.get(JabRefPreferences.IMPORT_FILENAMEPATTERN, null) != null) { String[] oldStylePatterns = new String[]{ "\\bibtexkey", "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"}; String[] newStylePatterns = new String[]{"[citationkey]", "[citationkey] - [title]"}; String[] oldDisplayStylePattern = new String[]{"bibtexkey", "bibtexkey - title"}; for (int i = 0; i < oldStylePatterns.length; i++) { migrateFileImportPattern(oldStylePatterns[i], newStylePatterns[i], prefs, mainPrefsNode); } for (int i = 0; i < oldDisplayStylePattern.length; i++) { migrateFileImportPattern(oldDisplayStylePattern[i], newStylePatterns[i], prefs, mainPrefsNode); } } // Directory preferences are not yet migrated, since it is not quote clear how to parse and reinterpret // the user defined old-style patterns, and the default pattern is "". } private static void upgradeKeyBindingsToJavaFX(JabRefPreferences prefs) { UnaryOperator<String> replaceKeys = str -> { String result = str.replace("ctrl ", "ctrl+"); result = result.replace("shift ", "shift+"); result = result.replace("alt ", "alt+"); result = result.replace("meta ", "meta+"); return result; }; List<String> keys = prefs.getStringList(JabRefPreferences.BINDINGS); keys.replaceAll(replaceKeys); prefs.putStringList(JabRefPreferences.BINDINGS, keys); } private static void addCrossRefRelatedFieldsForAutoComplete(JabRefPreferences prefs) { // LinkedHashSet because we want to retain the order and add new fields to the end Set<String> keys = new LinkedHashSet<>(prefs.getStringList(JabRefPreferences.AUTOCOMPLETER_COMPLETE_FIELDS)); keys.add("crossref"); keys.add("related"); keys.add("entryset"); prefs.putStringList(JabRefPreferences.AUTOCOMPLETER_COMPLETE_FIELDS, new ArrayList<>(keys)); } private static void migrateTypedKeyPrefs(JabRefPreferences prefs, Preferences oldPatternPrefs) throws BackingStoreException { LOGGER.info("Found old Bibtex Key patterns which will be migrated to new version."); GlobalCitationKeyPattern keyPattern = GlobalCitationKeyPattern.fromPattern( prefs.get(JabRefPreferences.DEFAULT_CITATION_KEY_PATTERN)); for (String key : oldPatternPrefs.keys()) { keyPattern.addCitationKeyPattern(EntryTypeFactory.parse(key), oldPatternPrefs.get(key, null)); } prefs.storeGlobalCitationKeyPattern(keyPattern); } /** * Customizable preview style migrations * <ul> * <li> Since v5.0-alpha the custom preview layout shows the 'comment' field instead of the 'review' field (<a href="https://github.com/JabRef/jabref/pull/4100">#4100</a>).</li> * <li> Since v5.1 a marker enables markdown in comments (<a href="https://github.com/JabRef/jabref/pull/6232">#6232</a>).</li> * <li> Since v5.2 'bibtexkey' is rebranded as citationkey (<a href="https://github.com/JabRef/jabref/pull/6875">#6875</a>).</li> * </ul> */ protected static void upgradePreviewStyle(JabRefPreferences prefs) { String currentPreviewStyle = prefs.get(JabRefPreferences.PREVIEW_STYLE); String migratedStyle = currentPreviewStyle.replace("\\begin{review}<BR><BR><b>Review: </b> \\format[HTMLChars]{\\review} \\end{review}", "\\begin{comment}<BR><BR><b>Comment: </b> \\format[HTMLChars]{\\comment} \\end{comment}") .replace("\\format[HTMLChars]{\\comment}", "\\format[Markdown,HTMLChars]{\\comment}") .replace("<b><i>\\bibtextype</i><a name=\"\\bibtexkey\">\\begin{bibtexkey} (\\bibtexkey)</a>", "<b><i>\\bibtextype</i><a name=\"\\citationkey\">\\begin{citationkey} (\\citationkey)</a>") .replace("\\end{bibtexkey}</b><br>__NEWLINE__", "\\end{citationkey}</b><br>__NEWLINE__"); prefs.put(JabRefPreferences.PREVIEW_STYLE, migratedStyle); } /** * The former preferences default of columns was a simple list of strings ("author;title;year;..."). Since 5.0 * the preferences store the type of the column too, so that the formerly hardwired columns like the graphic groups * column or the other icon columns can be reordered in the main table and behave like any other field column * ("groups;linked_id;field:author;special:readstatus;extrafile:pdf;..."). * <p> * Simple strings are by default parsed as a FieldColumn, so there is nothing to do there, but the formerly hard * wired columns need to be added. * <p> * In 5.1 variable names in JabRefPreferences have changed to offer backward compatibility with pre 5.0 releases * Pre 5.1: columnNames, columnWidths, columnSortTypes, columnSortOrder * Since 5.1: mainTableColumnNames, mainTableColumnWidths, mainTableColumnSortTypes, mainTableColumnSortOrder */ static void upgradeColumnPreferences(JabRefPreferences preferences) { List<String> columnNames = preferences.getStringList(JabRefPreferences.COLUMN_NAMES); List<Double> columnWidths = preferences.getStringList(JabRefPreferences.COLUMN_WIDTHS) .stream() .map(string -> { try { return Double.parseDouble(string); } catch (NumberFormatException e) { return ColumnPreferences.DEFAULT_COLUMN_WIDTH; } }).toList(); // "field:" String normalFieldTypeString = MainTableColumnModel.Type.NORMALFIELD.getName() + MainTableColumnModel.COLUMNS_QUALIFIER_DELIMITER; if (!columnNames.isEmpty() && columnNames.stream().noneMatch(name -> name.contains(normalFieldTypeString))) { List<MainTableColumnModel> columns = new ArrayList<>(); columns.add(new MainTableColumnModel(MainTableColumnModel.Type.GROUPS)); columns.add(new MainTableColumnModel(MainTableColumnModel.Type.FILES)); columns.add(new MainTableColumnModel(MainTableColumnModel.Type.LINKED_IDENTIFIER)); for (int i = 0; i < columnNames.size(); i++) { String name = columnNames.get(i); double columnWidth = ColumnPreferences.DEFAULT_COLUMN_WIDTH; MainTableColumnModel.Type type = SpecialField.fromName(name) .map(field -> MainTableColumnModel.Type.SPECIALFIELD) .orElse(MainTableColumnModel.Type.NORMALFIELD); if (i < columnWidths.size()) { columnWidth = columnWidths.get(i); } columns.add(new MainTableColumnModel(type, name, columnWidth)); } preferences.putStringList(JabRefPreferences.COLUMN_NAMES, columns.stream() .map(MainTableColumnModel::getName) .collect(Collectors.toList())); preferences.putStringList(JabRefPreferences.COLUMN_WIDTHS, columns.stream() .map(MainTableColumnModel::getWidth) .map(Double::intValue) .map(Object::toString) .collect(Collectors.toList())); // ASCENDING by default preferences.putStringList(JabRefPreferences.COLUMN_SORT_TYPES, columns.stream() .map(MainTableColumnModel::getSortType) .map(TableColumn.SortType::toString) .collect(Collectors.toList())); } } static void changeColumnVariableNamesFor51(JabRefPreferences preferences) { // The variable names have to be hardcoded, because they have changed between 5.0 and 5.1 final String V5_0_COLUMN_NAMES = "columnNames"; final String V5_0_COLUMN_WIDTHS = "columnWidths"; final String V5_0_COLUMN_SORT_TYPES = "columnSortTypes"; final String V5_0_COLUMN_SORT_ORDER = "columnSortOrder"; final String V5_1_COLUMN_NAMES = "mainTableColumnNames"; final String V5_1_COLUMN_WIDTHS = "mainTableColumnWidths"; final String V5_1_COLUMN_SORT_TYPES = "mainTableColumnSortTypes"; final String V5_1_COLUMN_SORT_ORDER = "mainTableColumnSortOrder"; List<String> oldColumnNames = preferences.getStringList(V5_0_COLUMN_NAMES); List<String> columnNames = preferences.getStringList(V5_1_COLUMN_NAMES); if (!oldColumnNames.isEmpty() && columnNames.isEmpty()) { preferences.putStringList(V5_1_COLUMN_NAMES, preferences.getStringList(V5_0_COLUMN_NAMES)); preferences.putStringList(V5_1_COLUMN_WIDTHS, preferences.getStringList(V5_0_COLUMN_WIDTHS)); preferences.putStringList(V5_1_COLUMN_SORT_TYPES, preferences.getStringList(V5_0_COLUMN_SORT_TYPES)); preferences.putStringList(V5_1_COLUMN_SORT_ORDER, preferences.getStringList(V5_0_COLUMN_SORT_ORDER)); } } /** * In 5.0 the format of column names have changed. That made newer versions of JabRef preferences incompatible with * earlier versions of JabRef. As some complains came up, we decided to change the variable names and to clear the * variable contents if they are unreadable, so former versions of JabRef would automatically create preferences * they can deal with. */ static void restoreVariablesForBackwardCompatibility(JabRefPreferences preferences) { List<String> oldColumnNames = preferences.getStringList(JabRefPreferences.COLUMN_NAMES); List<String> fieldColumnNames = oldColumnNames.stream() .filter(columnName -> columnName.startsWith("field:") || columnName.startsWith("special:")) .map(columnName -> { if (columnName.startsWith("field:")) { return columnName.substring(6); } else { // special return columnName.substring(8); } }).collect(Collectors.toList()); if (!fieldColumnNames.isEmpty()) { preferences.putStringList("columnNames", fieldColumnNames); List<String> fieldColumnWidths = new ArrayList<>(Collections.emptyList()); for (int i = 0; i < fieldColumnNames.size(); i++) { fieldColumnWidths.add("100"); } preferences.putStringList("columnWidths", fieldColumnWidths); preferences.put("columnSortTypes", ""); preferences.put("columnSortOrder", ""); } // Ensure font size is a parsable int variable try { // some versions stored the font size as double to the **same** key // since the preference store is type-safe, we need to add this workaround String fontSizeAsString = preferences.get(JabRefPreferences.MAIN_FONT_SIZE); int fontSizeAsInt = (int) Math.round(Double.parseDouble(fontSizeAsString)); preferences.putInt(JabRefPreferences.MAIN_FONT_SIZE, fontSizeAsInt); } catch (ClassCastException e) { // already an integer } } /** * In version 6.0 the formatting of the CleanUps preferences changed. Instead of using several keys that have have a variable name a single preference key is introduced containing just the active cleanup jobs. Also instead of a combined field for the field formatters and the enabled status of all of them, they are split for easier parsing. * <p> * <h3>Changes:</h3> * <table> * <tr> <td> key </td> <td> value </td> </tr> * <tr> <td colspan="2"> CLEANUP - old format: </td> </tr> * <tr> <td> CleanUpCLEAN_UP_DOI </td> <td> enabled </td> </tr> * <tr> <td> CleanUpRENAME_PDF </td> <td> disabled </td> </tr> * <tr> <td> CleanUpMOVE_PDF </td> <td> enabled<br> * <tr> <td colspan="2"> ... </td> </tr> * <tr> <td> &nbsp; </td> </tr> * <tr> <td colspan="2"> CLEANUP_JOBS - new format: </td> </tr> * <tr> <td> CleanUpJobs </td> <td> CLEAN_UP_DOI;RENAME_PDF;MOVE_PDF </td> </tr> * <tr> <td> &nbsp; </td> </tr> * <tr> <td colspan="2"> CLEANUP_FORMATTERS - old format: </td> </tr> * <tr> <td> CleanUpFormatters </td> <td> ENABLED\nfield[formatter,formatter...]\nfield[...]\nfield[...]... </td> </tr> * <tr> <td> &nbsp; </td> </tr> * <tr> <td colspan="2"> CLEANUP_FORMATTERS - new format: </td> </tr> * <tr> <td> CleanUpFormattersEnabled </td> <td> TRUE </td> </tr> * <tr> <td> CleanUpFormatters </td> <td> field[formatter,formatter...]\nfield[...]\nfield[...]... </td> </tr> * </table> */ private static void upgradeCleanups(JabRefPreferences prefs) { final String V5_8_CLEANUP = "CleanUp"; final String V6_0_CLEANUP_JOBS = "CleanUpJobs"; final String V5_8_CLEANUP_FIELD_FORMATTERS = "CleanUpFormatters"; final String V6_0_CLEANUP_FIELD_FORMATTERS = "CleanUpFormatters"; final String V6_0_CLEANUP_FIELD_FORMATTERS_ENABLED = "CleanUpFormattersEnabled"; List<String> activeJobs = new ArrayList<>(); for (CleanupPreferences.CleanupStep action : EnumSet.allOf(CleanupPreferences.CleanupStep.class)) { Optional<String> job = prefs.getAsOptional(V5_8_CLEANUP + action.name()); if (job.isPresent() && Boolean.parseBoolean(job.get())) { activeJobs.add(action.name()); // prefs.deleteKey(V5_8_CLEANUP + action.name()); // for backward compatibility in comments } } if (!activeJobs.isEmpty()) { prefs.put(V6_0_CLEANUP_JOBS, String.join(";", activeJobs)); } List<String> formatterCleanups = List.of(StringUtil.unifyLineBreaks(prefs.get(V5_8_CLEANUP_FIELD_FORMATTERS), "\n") .split("\n")); if (formatterCleanups.size() >= 2 && (formatterCleanups.get(0).equals(FieldFormatterCleanups.ENABLED) || formatterCleanups.get(0).equals(FieldFormatterCleanups.DISABLED))) { prefs.putBoolean(V6_0_CLEANUP_FIELD_FORMATTERS_ENABLED, formatterCleanups.get(0).equals(FieldFormatterCleanups.ENABLED) ? Boolean.TRUE : Boolean.FALSE); prefs.put(V6_0_CLEANUP_FIELD_FORMATTERS, String.join(OS.NEWLINE, formatterCleanups.subList(1, formatterCleanups.size() - 1))); } } static void moveApiKeysToKeyring(JabRefPreferences preferences) { final String V5_9_FETCHER_CUSTOM_KEY_NAMES = "fetcherCustomKeyNames"; final String V5_9_FETCHER_CUSTOM_KEYS = "fetcherCustomKeys"; List<String> names = preferences.getStringList(V5_9_FETCHER_CUSTOM_KEY_NAMES); List<String> keys = preferences.getStringList(V5_9_FETCHER_CUSTOM_KEYS); if (keys.size() > 0 && names.size() == keys.size()) { try (final Keyring keyring = Keyring.create()) { for (int i = 0; i < names.size(); i++) { keyring.setPassword("org.jabref.customapikeys", names.get(i), new Password( keys.get(i), preferences.getInternalPreferences().getUserAndHost()) .encrypt()); } preferences.deleteKey(V5_9_FETCHER_CUSTOM_KEYS); } catch (Exception ex) { LOGGER.error("Unable to open key store", ex); } } } }
29,295
52.754128
345
java
null
jabref-main/src/main/java/org/jabref/migrations/SpecialFieldsToSeparateFields.java
package org.jabref.migrations; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.jabref.logic.importer.ParserResult; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.Keyword; import org.jabref.model.entry.KeywordList; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.entry.field.SpecialFieldValue; public class SpecialFieldsToSeparateFields implements PostOpenMigration { private final KeywordList possibleKeywordsToMigrate; private final Character keywordDelimiter; private final Map<String, SpecialField> migrationTable = getMigrationTable(); public SpecialFieldsToSeparateFields(Character keywordDelimiter) { List<SpecialFieldValue> specialFieldValues = Arrays.asList(SpecialFieldValue.values()); possibleKeywordsToMigrate = new KeywordList(specialFieldValues.stream() .map(SpecialFieldValue::getKeyword) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList())); this.keywordDelimiter = keywordDelimiter; } @Override public void performMigration(ParserResult parserResult) { parserResult.getDatabase().getEntries().forEach(this::migrateEntry); } private void migrateEntry(BibEntry entry) { for (Keyword keyword : possibleKeywordsToMigrate) { if (entry.getKeywords(keywordDelimiter).contains(keyword) && migrationTable.containsKey(keyword.get())) { entry.setField(migrationTable.get(keyword.get()), keyword.get()); } } entry.removeKeywords(possibleKeywordsToMigrate, keywordDelimiter); } /** * Mapping of special field values (contained in the keywords) to their corresponding special field */ private Map<String, SpecialField> getMigrationTable() { Map<String, SpecialField> map = new HashMap<>(); map.put("printed", SpecialField.PRINTED); map.put("prio1", SpecialField.PRIORITY); map.put("prio2", SpecialField.PRIORITY); map.put("prio3", SpecialField.PRIORITY); map.put("qualityAssured", SpecialField.QUALITY); map.put("rank1", SpecialField.RANKING); map.put("rank2", SpecialField.RANKING); map.put("rank3", SpecialField.RANKING); map.put("rank4", SpecialField.RANKING); map.put("rank5", SpecialField.RANKING); map.put("read", SpecialField.READ_STATUS); map.put("skimmed", SpecialField.READ_STATUS); map.put("relevant", SpecialField.RELEVANCE); return map; } }
2,926
38.554054
117
java
null
jabref-main/src/main/java/org/jabref/model/ChainNode.java
package org.jabref.model; import java.util.Objects; import java.util.Optional; /** * Represents a node in a chain. * We view a chain as a vertical hierarchy and thus refer to the previous node as parent and the next node is a child. * <p> * In usual implementations, nodes function as wrappers around a data object. Thus normally they have a value property * which allows access to the value stored in the node. * In contrast to this approach, the ChainNode&lt;T> class is designed to be used as a base class which provides the * tree traversing functionality via inheritance. * <p> * Example usage: * private class BasicChainNode extends ChainNode&lt;BasicChainNode> { * public BasicChainNode() { * super(BasicChainNode.class); * } * } * * @param <T> the type of the class */ @SuppressWarnings("unchecked") // We use some explicit casts of the form "(T) this". The constructor ensures that this cast is valid. public abstract class ChainNode<T extends ChainNode<T>> { /** * This node's parent, or null if this node has no parent */ private T parent; /** * This node's child, or null if this node has no child */ private T child; /** * Constructs a chain node without parent and no child. * * @param derivingClass class deriving from TreeNode&lt;T>. It should always be "T.class". * We need this parameter since it is hard to get this information by other means. */ public ChainNode(Class<T> derivingClass) { parent = null; child = null; if (!derivingClass.isInstance(this)) { throw new UnsupportedOperationException("The class extending ChainNode<T> has to derive from T"); } } /** * Returns this node's parent or an empty Optional if this node has no parent. * * @return this node's parent T, or an empty Optional if this node has no parent */ public Optional<T> getParent() { return Optional.ofNullable(parent); } /** * Sets the parent node of this node. * <p> * This method does not set this node as the child of the new parent nor does it remove this node * from the old parent. You should probably call {@link #moveTo(ChainNode)} to change the chain. * * @param parent the new parent */ protected void setParent(T parent) { this.parent = Objects.requireNonNull(parent); } /** * Returns this node's child or an empty Optional if this node has no child. * * @return this node's child T, or an empty Optional if this node has no child */ public Optional<T> getChild() { return Optional.ofNullable(child); } /** * Adds the node as the child. Also sets the parent of the given node to this node. * The given node is not allowed to already be in a tree (i.e. it has to have no parent). * * @param child the node to add as child * @return the child node * @throws UnsupportedOperationException if the given node has already a parent */ public T setChild(T child) { Objects.requireNonNull(child); if (child.getParent().isPresent()) { throw new UnsupportedOperationException("Cannot add a node which already has a parent, use moveTo instead"); } child.setParent((T) this); this.child = child; return child; } /** * Removes this node from its parent and makes it a child of the specified node. * In this way the whole subchain based at this node is moved to the given node. * * @param target the new parent * @throws NullPointerException if target is null * @throws UnsupportedOperationException if target is an descendant of this node */ public void moveTo(T target) { Objects.requireNonNull(target); // Check that the target node is not an ancestor of this node, because this would create loops in the tree if (this.isAncestorOf(target)) { throw new UnsupportedOperationException("the target cannot be a descendant of this node"); } // Remove from previous parent getParent().ifPresent(ChainNode::removeChild); // Add as child target.setChild((T) this); } /** * Removes the child from this node's child list, giving it an empty parent. */ public void removeChild() { if (child != null) { // NPE if this is ever called child.setParent(null); } child = null; } /** * Returns true if this node is an ancestor of the given node. * <p> * A node is considered an ancestor of itself. * * @param anotherNode node to test * @return true if anotherNode is a descendant of this node * @throws NullPointerException if anotherNode is null */ public boolean isAncestorOf(T anotherNode) { Objects.requireNonNull(anotherNode); if (anotherNode == this) { return true; } else { return child.isAncestorOf(anotherNode); } } /** * Adds the given node at the end of the chain. * E.g., "A > B > C" + "D" -> "A > B > C > D". */ public void addAtEnd(T node) { if (child == null) { setChild(node); } else { child.addAtEnd(node); } } }
5,408
31.584337
133
java
null
jabref-main/src/main/java/org/jabref/model/FieldChange.java
package org.jabref.model; import java.util.Objects; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; /** * This class is used in the instance of a field being modified, removed or added. */ public class FieldChange { private final BibEntry entry; private final Field field; private final String oldValue; private final String newValue; public FieldChange(BibEntry entry, Field field, String oldValue, String newValue) { this.entry = Objects.requireNonNull(entry); this.field = Objects.requireNonNull(field); this.oldValue = oldValue; this.newValue = newValue; } public BibEntry getEntry() { return this.entry; } public Field getField() { return this.field; } public String getOldValue() { return this.oldValue; } public String getNewValue() { return this.newValue; } @Override public int hashCode() { return Objects.hash(entry, field, newValue, oldValue); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof FieldChange other) { if (entry == null) { if (other.entry != null) { return false; } } else if (!entry.equals(other.entry)) { return false; } if (field == null) { if (other.field != null) { return false; } } else if (!field.equals(other.field)) { return false; } if (newValue == null) { if (other.newValue != null) { return false; } } else if (!newValue.equals(other.newValue)) { return false; } if (oldValue == null) { return other.oldValue == null; } else { return oldValue.equals(other.oldValue); } } return false; } @Override public String toString() { return "FieldChange [entry=" + entry.getCitationKey().orElse("") + ", field=" + field + ", oldValue=" + oldValue + ", newValue=" + newValue + "]"; } }
2,333
25.522727
109
java
null
jabref-main/src/main/java/org/jabref/model/TreeNode.java
package org.jabref.model; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Predicate; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * Represents a node in a tree. * <p> * Usually, tree nodes have a value property which allows access to the value stored in the node. * In contrast to this approach, the TreeNode&lt;T> class is designed to be used as a base class which provides the * tree traversing functionality via inheritance. * <p> * Example usage: * private class BasicTreeNode extends TreeNode&lt;BasicTreeNode> { * public BasicTreeNode() { * super(BasicTreeNode.class); * } * } * <p> * This class started out as a copy of javax.swing.tree.DefaultMutableTreeNode. * * @param <T> the type of the class */ // We use some explicit casts of the form "(T) this". The constructor ensures that this cast is valid. @SuppressWarnings("unchecked") public abstract class TreeNode<T extends TreeNode<T>> { /** * Array of children, may be empty if this node has no children (but never null) */ private final ObservableList<T> children; /** * This node's parent, or null if this node has no parent */ private T parent; /** * The function which is invoked when something changed in the subtree. */ private Consumer<T> onDescendantChanged = t -> { /* Do nothing */ }; /** * Constructs a tree node without parent and no children. * * @param derivingClass class deriving from TreeNode&lt,T>. It should always be "T.class". * We need this parameter since it is hard to get this information by other means. */ public TreeNode(Class<T> derivingClass) { parent = null; children = FXCollections.observableArrayList(); if (!derivingClass.isInstance(this)) { throw new UnsupportedOperationException("The class extending TreeNode<T> has to derive from T"); } } /** * Get the path from the root node to this node. * <p> * The elements in the returned list represent the child index of each node in the path, starting at the root. * If this node is the root node, the returned list has zero elements. * * @return a list of numbers which represent an indexed path from the root node to this node */ public List<Integer> getIndexedPathFromRoot() { if (parent == null) { return new ArrayList<>(); } List<Integer> path = parent.getIndexedPathFromRoot(); path.add(getPositionInParent()); return path; } /** * Get the descendant of this node as indicated by the indexedPath. * <p> * If the path could not be traversed completely (i.e. one of the child indices did not exist), * an empty Optional will be returned. * * @param indexedPath sequence of child indices that describe a path from this node to one of its descendants. * Be aware that if indexedPath was obtained by getIndexedPathFromRoot(), this node should * usually be the root node. * @return descendant found by evaluating indexedPath */ public Optional<T> getDescendant(List<Integer> indexedPath) { T cursor = (T) this; for (int index : indexedPath) { Optional<T> child = cursor.getChildAt(index); if (child.isPresent()) { cursor = child.get(); } else { return Optional.empty(); } } return Optional.of(cursor); } /** * Get the child index of this node in its parent. * <p> * If this node is a root, then an UnsupportedOperationException is thrown. * Use the isRoot method to check for this case. * * @return the child index of this node in its parent */ public int getPositionInParent() { return getParent().orElseThrow(() -> new UnsupportedOperationException("Roots have no position in parent")) .getIndexOfChild((T) this).get(); } /** * Gets the index of the specified child in this node's child list. * <p> * If the specified node is not a child of this node, returns an empty Optional. * This method performs a linear search and is O(n) where n is the number of children. * * @param childNode the node to search for among this node's children * @return an integer giving the index of the node in this node's child list * or an empty Optional if the specified node is a not a child of this node * @throws NullPointerException if childNode is null */ public Optional<Integer> getIndexOfChild(T childNode) { Objects.requireNonNull(childNode); int index = children.indexOf(childNode); if (index == -1) { return Optional.empty(); } else { return Optional.of(index); } } /** * Gets the number of levels above this node, i.e. the distance from the root to this node. * <p> * If this node is the root, returns 0. * * @return an int giving the number of levels above this node */ public int getLevel() { if (parent == null) { return 0; } return parent.getLevel() + 1; } /** * Returns the number of children of this node. * * @return an int giving the number of children of this node */ public int getNumberOfChildren() { return children.size(); } /** * Removes this node from its parent and makes it a child of the specified node * by adding it to the end of children list. * In this way the whole subtree based at this node is moved to the given node. * * @param target the new parent * @throws NullPointerException if target is null * @throws ArrayIndexOutOfBoundsException if targetIndex is out of bounds * @throws UnsupportedOperationException if target is an descendant of this node */ public void moveTo(T target) { Objects.requireNonNull(target); Optional<T> oldParent = getParent(); if (oldParent.isPresent() && (oldParent.get() == target)) { this.moveTo(target, target.getNumberOfChildren() - 1); } else { this.moveTo(target, target.getNumberOfChildren()); } } /** * Returns the path from the root, to get to this node. The last element in the path is this node. * * @return a list of nodes giving the path, where the first element in the path is the root * and the last element is this node. */ public List<T> getPathFromRoot() { if (parent == null) { List<T> pathToMe = new ArrayList<>(); pathToMe.add((T) this); return pathToMe; } List<T> path = parent.getPathFromRoot(); path.add((T) this); return path; } /** * Returns the next sibling of this node in the parent's children list. * Returns an empty Optional if this node has no parent or if it is the parent's last child. * <p> * This method performs a linear search that is O(n) where n is the number of children. * To traverse the entire children collection, use the parent's getChildren() instead. * * @return the sibling of this node that immediately follows this node * @see #getChildren */ public Optional<T> getNextSibling() { return getRelativeSibling(+1); } /** * Returns the previous sibling of this node in the parent's children list. * Returns an empty Optional if this node has no parent or is the parent's first child. * <p> * This method performs a linear search that is O(n) where n is the number of children. * * @return the sibling of this node that immediately precedes this node * @see #getChildren */ public Optional<T> getPreviousSibling() { return getRelativeSibling(-1); } /** * Returns the sibling which is shiftIndex away from this node. */ private Optional<T> getRelativeSibling(int shiftIndex) { if (parent == null) { return Optional.empty(); } else { int indexInParent = getPositionInParent(); int indexTarget = indexInParent + shiftIndex; if (parent.childIndexExists(indexTarget)) { return parent.getChildAt(indexTarget); } else { return Optional.empty(); } } } /** * Returns this node's parent or an empty Optional if this node has no parent. * * @return this node's parent T, or an empty Optional if this node has no parent */ public Optional<T> getParent() { return Optional.ofNullable(parent); } /** * Sets the parent node of this node. * <p> * This method does not add this node to the children collection of the new parent nor does it remove this node * from the old parent. You should probably call moveTo or remove to change the tree. * * @param parent the new parent */ protected void setParent(T parent) { this.parent = parent; } /** * Returns the child at the specified index in this node's children collection. * * @param index an index into this node's children collection * @return the node in this node's children collection at the specified index, * or an empty Optional if the index does not point to a child */ public Optional<T> getChildAt(int index) { return childIndexExists(index) ? Optional.of(children.get(index)) : Optional.empty(); } /** * Returns whether the specified index is a valid index for a child. * * @param index the index to be tested * @return returns true when index is at least 0 and less then the count of children */ protected boolean childIndexExists(int index) { return (index >= 0) && (index < children.size()); } /** * Returns true if this node is the root of the tree. * The root is the only node in the tree with an empty parent; every tree has exactly one root. * * @return true if this node is the root of its tree */ public boolean isRoot() { return parent == null; } /** * Returns true if this node is an ancestor of the given node. * <p> * A node is considered an ancestor of itself. * * @param anotherNode node to test * @return true if anotherNode is a descendant of this node * @throws NullPointerException if anotherNode is null * @see #isNodeDescendant */ public boolean isAncestorOf(T anotherNode) { Objects.requireNonNull(anotherNode); if (anotherNode == this) { return true; } else { for (T child : children) { if (child.isAncestorOf(anotherNode)) { return true; } } return false; } } /** * Returns the root of the tree that contains this node. The root is the ancestor with an empty parent. * Thus a node without a parent is considered its own root. * * @return the root of the tree that contains this node */ public T getRoot() { if (parent == null) { return (T) this; } else { return parent.getRoot(); } } /** * Returns true if this node has no children. * * @return true if this node has no children */ public boolean isLeaf() { return getNumberOfChildren() == 0; } /** * Removes the subtree rooted at this node from the tree, giving this node an empty parent. * Does nothing if this node is the root of it tree. */ public void removeFromParent() { if (parent != null) { parent.removeChild((T) this); } } /** * Removes all of this node's children, setting their parents to empty. * If this node has no children, this method does nothing. */ public void removeAllChildren() { while (getNumberOfChildren() > 0) { removeChild(0); } } /** * Returns this node's first child if it exists (otherwise returns an empty Optional). * * @return the first child of this node */ public Optional<T> getFirstChild() { return getChildAt(0); } /** * Returns this node's last child if it exists (otherwise returns an empty Optional). * * @return the last child of this node */ public Optional<T> getLastChild() { return getChildAt(children.size() - 1); } /** * Returns true if anotherNode is a descendant of this node * -- if it is this node, one of this node's children, or a descendant of one of this node's children. * Note that a node is considered a descendant of itself. * <p> * If anotherNode is null, an exception is thrown. * * @param anotherNode node to test as descendant of this node * @return true if this node is an ancestor of anotherNode * @see #isAncestorOf */ public boolean isNodeDescendant(T anotherNode) { Objects.requireNonNull(anotherNode); return this.isAncestorOf(anotherNode); } /** * Gets a forward-order list of this node's children. * <p> * The returned list is unmodifiable - use the add and remove methods to modify the nodes children. * However, changing the nodes children (for example by calling moveTo) is reflected in a change of * the list returned by getChildren. In other words, getChildren provides a read-only view on the children but * not a copy. * * @return a list of this node's children */ public ObservableList<T> getChildren() { return FXCollections.unmodifiableObservableList(children); } /** * Removes the given child from this node's child list, giving it an empty parent. * * @param child a child of this node to remove */ public void removeChild(T child) { Objects.requireNonNull(child); children.remove(child); child.setParent(null); notifyAboutDescendantChange((T) this); } /** * Removes the child at the specified index from this node's children and sets that node's parent to empty. * <p> * Does nothing if the index does not point to a child. * * @param childIndex the index in this node's child array of the child to remove */ public void removeChild(int childIndex) { Optional<T> child = getChildAt(childIndex); if (child.isPresent()) { children.remove(childIndex); child.get().setParent(null); } notifyAboutDescendantChange((T) this); } /** * Adds the node at the end the children collection. Also sets the parent of the given node to this node. * The given node is not allowed to already be in a tree (i.e. it has to have no parent). * * @param child the node to add * @return the child node */ public T addChild(T child) { return addChild(child, children.size()); } /** * Adds the node at the given position in the children collection. Also sets the parent of the given node to this node. * The given node is not allowed to already be in a tree (i.e. it has to have no parent). * * @param child the node to add * @param index the position where the node should be added * @return the child node * @throws IndexOutOfBoundsException if the index is out of range */ public T addChild(T child, int index) { Objects.requireNonNull(child); if (child.getParent().isPresent()) { throw new UnsupportedOperationException("Cannot add a node which already has a parent, use moveTo instead"); } child.setParent((T) this); children.add(index, child); notifyAboutDescendantChange((T) this); return child; } /** * Removes all children from this node and makes them a child of the specified node * by adding it to the specified position in the children list. * * @param target the new parent * @param targetIndex the position where the children should be inserted * @throws NullPointerException if target is null * @throws ArrayIndexOutOfBoundsException if targetIndex is out of bounds * @throws UnsupportedOperationException if target is an descendant of one of the children of this node */ public void moveAllChildrenTo(T target, int targetIndex) { while (getNumberOfChildren() > 0) { getLastChild().get().moveTo(target, targetIndex); } } /** * Sorts the list of children according to the order induced by the specified {@link Comparator}. * <p> * All children must be mutually comparable using the specified comparator * (that is, {@code c.compare(e1, e2)} must not throw a {@code ClassCastException} * for any children {@code e1} and {@code e2} in the list). * * @param comparator the comparator used to compare the child nodes * @param recursive if true the whole subtree is sorted * @throws NullPointerException if the comparator is null */ public void sortChildren(Comparator<? super T> comparator, boolean recursive) { Objects.requireNonNull(comparator); if (this.isLeaf()) { return; // nothing to sort } int j = getNumberOfChildren() - 1; int lastModified; while (j > 0) { lastModified = j + 1; j = -1; for (int i = 1; i < lastModified; ++i) { T child1 = getChildAt(i - 1).get(); T child2 = getChildAt(i).get(); if (comparator.compare(child1, child2) > 0) { child1.moveTo((T) this, i); j = i; } } } if (recursive) { for (T child : getChildren()) { child.sortChildren(comparator, true); } } } /** * Removes this node from its parent and makes it a child of the specified node * by adding it to the specified position in the children list. * In this way the whole subtree based at this node is moved to the given node. * * @param target the new parent * @param targetIndex the position where the children should be inserted * @throws NullPointerException if target is null * @throws ArrayIndexOutOfBoundsException if targetIndex is out of bounds * @throws UnsupportedOperationException if target is an descendant of this node */ public void moveTo(T target, int targetIndex) { Objects.requireNonNull(target); // Check that the target node is not an ancestor of this node, because this would create loops in the tree if (this.isAncestorOf(target)) { throw new UnsupportedOperationException("the target cannot be a descendant of this node"); } // Remove from previous parent Optional<T> oldParent = getParent(); if (oldParent.isPresent()) { oldParent.get().removeChild((T) this); } // Add as child target.addChild((T) this, targetIndex); } /** * Creates a deep copy of this node and all of its children. * * @return a deep copy of the subtree */ public T copySubtree() { T copy = copyNode(); for (T child : getChildren()) { child.copySubtree().moveTo(copy); } return copy; } /** * Creates a copy of this node, completely separated from the tree (i.e. no children and no parent) * * @return a deep copy of this node */ public abstract T copyNode(); /** * Adds the given function to the list of subscribers which are notified when something changes in the subtree. * * The following events are supported (the text in parentheses specifies which node is passed as the source): * - addChild (new parent) * - removeChild (old parent) * - move (old parent and new parent) * * @param subscriber function to be invoked upon a change */ public void subscribeToDescendantChanged(Consumer<T> subscriber) { onDescendantChanged = onDescendantChanged.andThen(subscriber); } /** * Helper method which notifies all subscribers about a change in the subtree and bubbles the event to all parents. * * @param source the node which changed */ protected void notifyAboutDescendantChange(T source) { onDescendantChanged.accept(source); if (!isRoot()) { parent.notifyAboutDescendantChange(source); } } /** * Returns the group and any of its children in the tree satisfying the given condition. */ public List<T> findChildrenSatisfying(Predicate<T> matcher) { List<T> hits = new ArrayList<>(); if (matcher.test((T) this)) { hits.add((T) this); } for (T child : getChildren()) { hits.addAll(child.findChildrenSatisfying(matcher)); } return hits; } }
21,607
33.298413
123
java
null
jabref-main/src/main/java/org/jabref/model/database/BibDatabase.java
package org.jabref.model.database; import java.math.BigInteger; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.stream.Collectors; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.jabref.logic.bibtex.FieldWriter; import org.jabref.model.database.event.EntriesAddedEvent; import org.jabref.model.database.event.EntriesRemovedEvent; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibtexString; import org.jabref.model.entry.Month; import org.jabref.model.entry.event.EntriesEventSource; import org.jabref.model.entry.event.EntryChangedEvent; import org.jabref.model.entry.event.FieldChangedEvent; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.StandardField; import org.jabref.model.strings.StringUtil; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A bibliography database. This is the "bib" file (or the library stored in a shared SQL database) */ public class BibDatabase { private static final Logger LOGGER = LoggerFactory.getLogger(BibDatabase.class); private static final Pattern RESOLVE_CONTENT_PATTERN = Pattern.compile(".*#[^#]+#.*"); /** * State attributes */ private final ObservableList<BibEntry> entries = FXCollections.synchronizedObservableList(FXCollections.observableArrayList(BibEntry::getObservables)); private Map<String, BibtexString> bibtexStrings = new ConcurrentHashMap<>(); private final EventBus eventBus = new EventBus(); private String preamble; // All file contents below the last entry in the file private String epilog = ""; private String sharedDatabaseID; private String newLineSeparator = System.lineSeparator(); public BibDatabase(List<BibEntry> entries, String newLineSeparator) { this(entries); this.newLineSeparator = newLineSeparator; } public BibDatabase(List<BibEntry> entries) { this(); insertEntries(entries); } public BibDatabase() { this.registerListener(new KeyChangeListener(this)); } /** * @param toResolve maybenull The text to resolve. * @param database maybenull The database to use for resolving the text. * @return The resolved text or the original text if either the text or the database are null * @deprecated use {@link BibDatabase#resolveForStrings(String)} * <p> * Returns a text with references resolved according to an optionally given database. */ @Deprecated public static String getText(String toResolve, BibDatabase database) { if ((toResolve != null) && (database != null)) { return database.resolveForStrings(toResolve); } return toResolve; } /** * Returns the number of entries. */ public int getEntryCount() { return entries.size(); } /** * Checks if the database contains entries. */ public boolean hasEntries() { return !entries.isEmpty(); } /** * Returns the list of entries sorted by the given comparator. */ public List<BibEntry> getEntriesSorted(Comparator<BibEntry> comparator) { List<BibEntry> entriesSorted = new ArrayList<>(entries); entriesSorted.sort(comparator); return entriesSorted; } /** * Returns whether an entry with the given ID exists (-> entry_type + hashcode). */ public boolean containsEntryWithId(String id) { return entries.stream().anyMatch(entry -> entry.getId().equals(id)); } public ObservableList<BibEntry> getEntries() { return FXCollections.unmodifiableObservableList(entries); } /** * Returns a set of Strings, that contains all field names that are visible. This means that the fields * are not internal fields. Internal fields are fields, that are starting with "_". * * @return set of fieldnames, that are visible */ public Set<Field> getAllVisibleFields() { Set<Field> allFields = new TreeSet<>(Comparator.comparing(Field::getName)); for (BibEntry e : getEntries()) { allFields.addAll(e.getFields()); } return allFields.stream().filter(field -> !FieldFactory.isInternalField(field)) .collect(Collectors.toSet()); } /** * Returns the entry with the given citation key. */ public synchronized Optional<BibEntry> getEntryByCitationKey(String key) { for (BibEntry entry : entries) { if (key.equals(entry.getCitationKey().orElse(null))) { return Optional.of(entry); } } return Optional.empty(); } /** * Collects entries having the specified citation key and returns these entries as list. * The order of the entries is the order they appear in the database. * * @return list of entries that contains the given key */ public synchronized List<BibEntry> getEntriesByCitationKey(String key) { List<BibEntry> result = new ArrayList<>(); for (BibEntry entry : entries) { entry.getCitationKey().ifPresent(entryKey -> { if (key.equals(entryKey)) { result.add(entry); } }); } return result; } /** * Inserts the entry. * * @param entry entry to insert */ public synchronized void insertEntry(BibEntry entry) { insertEntry(entry, EntriesEventSource.LOCAL); } /** * Inserts the entry. * * @param entry entry to insert * @param eventSource source the event is sent from */ public synchronized void insertEntry(BibEntry entry, EntriesEventSource eventSource) { insertEntries(Collections.singletonList(entry), eventSource); } public synchronized void insertEntries(BibEntry... entries) { insertEntries(Arrays.asList(entries), EntriesEventSource.LOCAL); } public synchronized void insertEntries(List<BibEntry> entries) { insertEntries(entries, EntriesEventSource.LOCAL); } public synchronized void insertEntries(List<BibEntry> newEntries, EntriesEventSource eventSource) { Objects.requireNonNull(newEntries); for (BibEntry entry : newEntries) { entry.registerListener(this); } if (newEntries.isEmpty()) { eventBus.post(new EntriesAddedEvent(newEntries, eventSource)); } else { eventBus.post(new EntriesAddedEvent(newEntries, newEntries.get(0), eventSource)); } entries.addAll(newEntries); } public synchronized void removeEntry(BibEntry bibEntry) { removeEntries(Collections.singletonList(bibEntry)); } public synchronized void removeEntry(BibEntry bibEntry, EntriesEventSource eventSource) { removeEntries(Collections.singletonList(bibEntry), eventSource); } /** * Removes the given entries. * The entries removed based on the id {@link BibEntry#getId()} * * @param toBeDeleted Entries to delete */ public synchronized void removeEntries(List<BibEntry> toBeDeleted) { removeEntries(toBeDeleted, EntriesEventSource.LOCAL); } /** * Removes the given entries. * The entries are removed based on the id {@link BibEntry#getId()} * * @param toBeDeleted Entry to delete * @param eventSource Source the event is sent from */ public synchronized void removeEntries(List<BibEntry> toBeDeleted, EntriesEventSource eventSource) { Objects.requireNonNull(toBeDeleted); List<String> ids = new ArrayList<>(); for (BibEntry entry : toBeDeleted) { ids.add(entry.getId()); } boolean anyRemoved = entries.removeIf(entry -> ids.contains(entry.getId())); if (anyRemoved) { eventBus.post(new EntriesRemovedEvent(toBeDeleted, eventSource)); } } /** * Returns the database's preamble. * If the preamble text consists only of whitespace, then also an empty optional is returned. */ public synchronized Optional<String> getPreamble() { if (StringUtil.isBlank(preamble)) { return Optional.empty(); } else { return Optional.of(preamble); } } /** * Sets the database's preamble. */ public synchronized void setPreamble(String preamble) { this.preamble = preamble; } /** * Inserts a Bibtex String. */ public synchronized void addString(BibtexString string) throws KeyCollisionException { String id = string.getId(); if (hasStringByName(string.getName())) { throw new KeyCollisionException("A string with that label already exists", id); } if (bibtexStrings.containsKey(id)) { throw new KeyCollisionException("Duplicate BibTeX string id.", id); } bibtexStrings.put(id, string); } /** * Replaces the existing lists of BibTexString with the given one * Duplicates throw KeyCollisionException * * @param stringsToAdd The collection of strings to set */ public void setStrings(List<BibtexString> stringsToAdd) { bibtexStrings = new ConcurrentHashMap<>(); stringsToAdd.forEach(this::addString); } /** * Removes the string with the given id. */ public void removeString(String id) { bibtexStrings.remove(id); } /** * Returns a Set of keys to all BibtexString objects in the database. * These are in no sorted order. */ public Set<String> getStringKeySet() { return bibtexStrings.keySet(); } /** * Returns a Collection of all BibtexString objects in the database. * These are in no particular order. */ public Collection<BibtexString> getStringValues() { return bibtexStrings.values(); } /** * Returns the string with the given id. */ public BibtexString getString(String id) { return bibtexStrings.get(id); } /** * Returns the string with the given name/label */ public Optional<BibtexString> getStringByName(String name) { return getStringValues().stream().filter(string -> string.getName().equals(name)).findFirst(); } /** * Returns the number of strings. */ public int getStringCount() { return bibtexStrings.size(); } /** * Check if there are strings. */ public boolean hasNoStrings() { return bibtexStrings.isEmpty(); } /** * Copies the preamble of another BibDatabase. * * @param database another BibDatabase */ public void copyPreamble(BibDatabase database) { setPreamble(database.getPreamble().orElse("")); } /** * Returns true if a string with the given label already exists. */ public synchronized boolean hasStringByName(String label) { return bibtexStrings.values().stream().anyMatch(value -> value.getName().equals(label)); } /** * Resolves any references to strings contained in this field content, * if possible. */ public String resolveForStrings(String content) { Objects.requireNonNull(content, "Content for resolveForStrings must not be null."); return resolveContent(content, new HashSet<>(), new HashSet<>()); } /** * Get all strings used in the entries. */ public Collection<BibtexString> getUsedStrings(Collection<BibEntry> entries) { List<BibtexString> result = new ArrayList<>(); Set<String> allUsedIds = new HashSet<>(); // All entries for (BibEntry entry : entries) { for (String fieldContent : entry.getFieldValues()) { resolveContent(fieldContent, new HashSet<>(), allUsedIds); } } // Preamble if (preamble != null) { resolveContent(preamble, new HashSet<>(), allUsedIds); } for (String stringId : allUsedIds) { result.add((BibtexString) bibtexStrings.get(stringId).clone()); } return result; } /** * Take the given collection of BibEntry and resolve any string * references. * * @param entriesToResolve A collection of BibtexEntries in which all strings of the form * #xxx# will be resolved against the hash map of string * references stored in the database. * @param inPlace If inPlace is true then the given BibtexEntries will be modified, if false then copies of the BibtexEntries are made before resolving the strings. * @return a list of bibtexentries, with all strings resolved. It is dependent on the value of inPlace whether copies are made or the given BibtexEntries are modified. */ public List<BibEntry> resolveForStrings(Collection<BibEntry> entriesToResolve, boolean inPlace) { Objects.requireNonNull(entriesToResolve, "entries must not be null."); List<BibEntry> results = new ArrayList<>(entriesToResolve.size()); for (BibEntry entry : entriesToResolve) { results.add(this.resolveForStrings(entry, inPlace)); } return results; } /** * Take the given BibEntry and resolve any string references. * * @param entry A BibEntry in which all strings of the form #xxx# will be * resolved against the hash map of string references stored in * the database. * @param inPlace If inPlace is true then the given BibEntry will be * modified, if false then a copy is made using close made before * resolving the strings. * @return a BibEntry with all string references resolved. It is * dependent on the value of inPlace whether a copy is made or the * given BibtexEntries is modified. */ public BibEntry resolveForStrings(BibEntry entry, boolean inPlace) { BibEntry resultingEntry; if (inPlace) { resultingEntry = entry; } else { resultingEntry = (BibEntry) entry.clone(); } for (Map.Entry<Field, String> field : resultingEntry.getFieldMap().entrySet()) { resultingEntry.setField(field.getKey(), this.resolveForStrings(field.getValue())); } return resultingEntry; } /** * If the label represents a string contained in this database, returns * that string's content. Resolves references to other strings, taking * care not to follow a circular reference pattern. * If the string is undefined, returns null. */ private String resolveString(String label, Set<String> usedIds, Set<String> allUsedIds) { Objects.requireNonNull(label); Objects.requireNonNull(usedIds); Objects.requireNonNull(allUsedIds); for (BibtexString string : bibtexStrings.values()) { if (string.getName().equalsIgnoreCase(label)) { // First check if this string label has been resolved // earlier in this recursion. If so, we have a // circular reference, and have to stop to avoid // infinite recursion. if (usedIds.contains(string.getId())) { LOGGER.info("Stopped due to circular reference in strings: " + label); return label; } // If not, log this string's ID now. usedIds.add(string.getId()); if (allUsedIds != null) { allUsedIds.add(string.getId()); } // Ok, we found the string. Now we must make sure we // resolve any references to other strings in this one. String result = string.getContent(); result = resolveContent(result, usedIds, allUsedIds); // Finished with recursing this branch, so we remove our // ID again: usedIds.remove(string.getId()); return result; } } // If we get to this point, the string has obviously not been defined locally. // Check if one of the standard BibTeX month strings has been used: Optional<Month> month = Month.getMonthByShortName(label); return month.map(Month::getFullName).orElse(null); } private String resolveContent(String result, Set<String> usedIds, Set<String> allUsedIds) { String res = result; if (RESOLVE_CONTENT_PATTERN.matcher(res).matches()) { StringBuilder newRes = new StringBuilder(); int piv = 0; int next; while ((next = res.indexOf(FieldWriter.BIBTEX_STRING_START_END_SYMBOL, piv)) >= 0) { // We found the next string ref. Append the text // up to it. if (next > 0) { newRes.append(res, piv, next); } int stringEnd = res.indexOf(FieldWriter.BIBTEX_STRING_START_END_SYMBOL, next + 1); if (stringEnd >= 0) { // We found the boundaries of the string ref, // now resolve that one. String refLabel = res.substring(next + 1, stringEnd); String resolved = resolveString(refLabel, usedIds, allUsedIds); if (resolved == null) { // Could not resolve string. Display the # // characters rather than removing them: newRes.append(res, next, stringEnd + 1); } else { // The string was resolved, so we display its meaning only, // stripping the # characters signifying the string label: newRes.append(resolved); } piv = stringEnd + 1; } else { // We did not find the boundaries of the string ref. This // makes it impossible to interpret it as a string label. // So we should just append the rest of the text and finish. newRes.append(res.substring(next)); piv = res.length(); break; } } if (piv < (res.length() - 1)) { newRes.append(res.substring(piv)); } res = newRes.toString(); } return res; } public String getEpilog() { return epilog; } public void setEpilog(String epilog) { this.epilog = epilog; } /** * Registers a listener object (subscriber) to the internal event bus. * The following events are posted: * * - {@link EntriesAddedEvent} * - {@link EntryChangedEvent} * - {@link EntriesRemovedEvent} * * @param listener listener (subscriber) to add */ public void registerListener(Object listener) { this.eventBus.register(listener); } /** * Unregisters an listener object. * * @param listener listener (subscriber) to remove */ public void unregisterListener(Object listener) { try { this.eventBus.unregister(listener); } catch (IllegalArgumentException e) { // occurs if the event source has not been registered, should not prevent shutdown LOGGER.debug("Problem unregistering", e); } } @Subscribe private void relayEntryChangeEvent(FieldChangedEvent event) { eventBus.post(event); } public Optional<BibEntry> getReferencedEntry(BibEntry entry) { return entry.getField(StandardField.CROSSREF).flatMap(this::getEntryByCitationKey); } public Optional<String> getSharedDatabaseID() { return Optional.ofNullable(this.sharedDatabaseID); } public void setSharedDatabaseID(String sharedDatabaseID) { this.sharedDatabaseID = sharedDatabaseID; } public boolean isShared() { return getSharedDatabaseID().isPresent(); } public void clearSharedDatabaseID() { this.sharedDatabaseID = null; } /** * Generates and sets a random ID which is globally unique. * * @return The generated sharedDatabaseID */ public String generateSharedDatabaseID() { this.sharedDatabaseID = new BigInteger(128, new SecureRandom()).toString(32); return this.sharedDatabaseID; } /** * Returns the number of occurrences of the given citation key in this database. */ public long getNumberOfCitationKeyOccurrences(String key) { return entries.stream() .flatMap(entry -> entry.getCitationKey().stream()) .filter(key::equals) .count(); } /** * Checks if there is more than one occurrence of the citation key. */ public boolean isDuplicateCitationKeyExisting(String key) { return getNumberOfCitationKeyOccurrences(key) > 1; } /** * Set the newline separator. */ public void setNewLineSeparator(String newLineSeparator) { this.newLineSeparator = newLineSeparator; } /** * Returns the string used to indicate a linebreak */ public String getNewLineSeparator() { return newLineSeparator; } }
22,063
33.049383
171
java
null
jabref-main/src/main/java/org/jabref/model/database/BibDatabaseContext.java
package org.jabref.model.database; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.gui.LibraryTab; import org.jabref.logic.crawler.Crawler; import org.jabref.logic.crawler.StudyRepository; import org.jabref.logic.shared.DatabaseLocation; import org.jabref.logic.shared.DatabaseSynchronizer; import org.jabref.logic.util.CoarseChangeFilter; import org.jabref.logic.util.OS; import org.jabref.model.entry.BibEntry; import org.jabref.model.metadata.MetaData; import org.jabref.model.study.Study; import org.jabref.preferences.FilePreferences; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents everything related to a BIB file. * * <p> The entries are stored in BibDatabase, the other data in MetaData * and the options relevant for this file in Defaults. * </p> * <p> * To get an instance for a .bib file, use {@link org.jabref.logic.importer.fileformat.BibtexParser}. * </p> */ @AllowedToUseLogic("because it needs access to shared database features") public class BibDatabaseContext { private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class); private final BibDatabase database; private MetaData metaData; /** * The path where this database was last saved to. */ private Path path; private DatabaseSynchronizer dbmsSynchronizer; private CoarseChangeFilter dbmsListener; private DatabaseLocation location; public BibDatabaseContext() { this(new BibDatabase()); } public BibDatabaseContext(BibDatabase database) { this(database, new MetaData()); } public BibDatabaseContext(BibDatabase database, MetaData metaData) { this.database = Objects.requireNonNull(database); this.metaData = Objects.requireNonNull(metaData); this.location = DatabaseLocation.LOCAL; } public BibDatabaseContext(BibDatabase database, MetaData metaData, Path path) { this(database, metaData, path, DatabaseLocation.LOCAL); } public BibDatabaseContext(BibDatabase database, MetaData metaData, Path path, DatabaseLocation location) { this(database, metaData); Objects.requireNonNull(location); this.path = path; if (location == DatabaseLocation.LOCAL) { convertToLocalDatabase(); } } public BibDatabaseMode getMode() { return metaData.getMode().orElse(BibDatabaseMode.BIBLATEX); } public void setMode(BibDatabaseMode bibDatabaseMode) { metaData.setMode(bibDatabaseMode); } public void setDatabasePath(Path file) { this.path = file; } /** * Get the path where this database was last saved to or loaded from, if any. * * @return Optional of the relevant Path, or Optional.empty() if none is defined. */ public Optional<Path> getDatabasePath() { return Optional.ofNullable(path); } public void clearDatabasePath() { this.path = null; } public BibDatabase getDatabase() { return database; } public MetaData getMetaData() { return metaData; } public void setMetaData(MetaData metaData) { this.metaData = Objects.requireNonNull(metaData); } public boolean isBiblatexMode() { return getMode() == BibDatabaseMode.BIBLATEX; } /** * Returns whether this .bib file belongs to a {@link Study} */ public boolean isStudy() { return this.getDatabasePath() .map(path -> path.getFileName().toString().equals(Crawler.FILENAME_STUDY_RESULT_BIB) && Files.exists(path.resolveSibling(StudyRepository.STUDY_DEFINITION_FILE_NAME))) .orElse(false); } /** * Look up the directories set up for this database. * There can be up to four directories definitions for these files: * <ol> * <li>next to the .bib file.</li> * <li>the preferences can specify a default one.</li> * <li>the database's metadata can specify a general directory.</li> * <li>the database's metadata can specify a user-specific directory.</li> * </ol> * <p> * The settings are prioritized in the following order, and the first defined setting is used: * <ol> * <li>user-specific metadata directory</li> * <li>general metadata directory</li> * <li>BIB file directory (if configured in the preferences AND none of the two above directories are configured)</li> * <li>preferences directory (if .bib file directory should not be used according to the preferences)</li> * </ol> * * @param preferences The fileDirectory preferences */ public List<Path> getFileDirectories(FilePreferences preferences) { List<Path> fileDirs = new ArrayList<>(); // 1. Metadata user-specific directory metaData.getUserFileDirectory(preferences.getUserAndHost()) .ifPresent(userFileDirectory -> fileDirs.add(getFileDirectoryPath(userFileDirectory))); // 2. Metadata general directory metaData.getDefaultFileDirectory() .ifPresent(metaDataDirectory -> fileDirs.add(getFileDirectoryPath(metaDataDirectory))); // 3. BIB file directory or Main file directory // fileDirs.isEmpty in the case, 1) no user-specific file directory and 2) no general file directory is set // (in the metadata of the bib file) if (fileDirs.isEmpty() && preferences.shouldStoreFilesRelativeToBibFile()) { getDatabasePath().ifPresent(dbPath -> { Path parentPath = dbPath.getParent(); if (parentPath == null) { parentPath = Path.of(System.getProperty("user.dir")); } Objects.requireNonNull(parentPath, "BibTeX database parent path is null"); fileDirs.add(parentPath); }); } else { // Main file directory preferences.getMainFileDirectory().ifPresent(fileDirs::add); } return fileDirs.stream().map(Path::toAbsolutePath).collect(Collectors.toList()); } /** * Returns the first existing file directory from {@link #getFileDirectories(FilePreferences)} * * @return the path - or an empty optional, if none of the directories exists */ public Optional<Path> getFirstExistingFileDir(FilePreferences preferences) { return getFileDirectories(preferences).stream() .filter(Files::exists) .findFirst(); } private Path getFileDirectoryPath(String directoryName) { Path directory = Path.of(directoryName); // If this directory is relative, we try to interpret it as relative to // the file path of this BIB file: Optional<Path> databaseFile = getDatabasePath(); if (!directory.isAbsolute() && databaseFile.isPresent()) { return databaseFile.get().getParent().resolve(directory).normalize(); } return directory; } public DatabaseSynchronizer getDBMSSynchronizer() { return this.dbmsSynchronizer; } public void clearDBMSSynchronizer() { this.dbmsSynchronizer = null; } public DatabaseLocation getLocation() { return this.location; } public void convertToSharedDatabase(DatabaseSynchronizer dmbsSynchronizer) { this.dbmsSynchronizer = dmbsSynchronizer; this.dbmsListener = new CoarseChangeFilter(this); dbmsListener.registerListener(dbmsSynchronizer); this.location = DatabaseLocation.SHARED; } public void convertToLocalDatabase() { if (Objects.nonNull(dbmsListener) && (location == DatabaseLocation.SHARED)) { dbmsListener.unregisterListener(dbmsSynchronizer); dbmsListener.shutdown(); } this.location = DatabaseLocation.LOCAL; } public List<BibEntry> getEntries() { return database.getEntries(); } public Path getFulltextIndexPath() { Path appData = OS.getNativeDesktop().getFulltextIndexBaseDirectory(); Path indexPath; if (getDatabasePath().isPresent()) { indexPath = appData.resolve(String.valueOf(this.getDatabasePath().get().hashCode())); LOGGER.debug("Index path for {} is {}", getDatabasePath().get(), indexPath); return indexPath; } indexPath = appData.resolve("unsaved"); LOGGER.debug("Using index for unsaved database: {}", indexPath); return indexPath; } @Override public String toString() { return "BibDatabaseContext{" + "metaData=" + metaData + ", mode=" + getMode() + ", databasePath=" + getDatabasePath() + ", biblatexMode=" + isBiblatexMode() + ", fulltextIndexPath=" + getFulltextIndexPath() + '}'; } }
9,199
33.586466
126
java
null
jabref-main/src/main/java/org/jabref/model/database/BibDatabaseMode.java
package org.jabref.model.database; import java.util.Locale; /** * An enum which contains the possible {@link BibDatabase} Modes. * Possible are BibTeX and biblatex. */ public enum BibDatabaseMode { BIBTEX, BIBLATEX; /** * @return the name of the current mode as String */ public String getFormattedName() { if (this == BIBTEX) { return "BibTeX"; } else { return "biblatex"; } } /** * Returns the opposite mode of the current mode as {@link BibDatabaseMode}. * * @return biblatex if the current mode is BIBTEX, BibTeX else */ public BibDatabaseMode getOppositeMode() { if (this == BIBTEX) { return BIBLATEX; } else { return BIBTEX; } } /** * Returns the {@link BibDatabaseMode} that equals the given string. The use of capital and small letters * in the string doesn't matter.If neither "bibtex" nor "biblatex" is the given string, then an * {@link IllegalArgumentException} will be thrown. * * @return BIBTEX, if the string is bibtex<br> * BIBLATEX, if the string is biblatex<br> */ public static BibDatabaseMode parse(String data) { return BibDatabaseMode.valueOf(data.toUpperCase(Locale.ENGLISH)); } /** * @return The current mode as String in lowercase */ public String getAsString() { return getFormattedName().toLowerCase(Locale.ENGLISH); } }
1,510
25.982143
109
java
null
jabref-main/src/main/java/org/jabref/model/database/BibDatabaseModeDetection.java
package org.jabref.model.database; import java.util.stream.Stream; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.EntryTypeFactory; public class BibDatabaseModeDetection { private BibDatabaseModeDetection() { } /** * Tries to infer the database type by examining a BibDatabase database. * * All checks are based on the case-insensitive comparison of entry tag names. * Only standard BibTex and Biblatex entry types are considered in the decision process. * * 1. Check if any of the entries is a type exclusive to Biblatex * 2. Otherwise return BibTex * * @param database a BibDatabase database * @return the inferred database type */ public static BibDatabaseMode inferMode(BibDatabase database) { final Stream<EntryType> entryTypes = database.getEntries().stream().map(BibEntry::getType); if (entryTypes.anyMatch(EntryTypeFactory::isExclusiveBiblatex)) { return BibDatabaseMode.BIBLATEX; } else { return BibDatabaseMode.BIBTEX; } } }
1,148
30.916667
99
java
null
jabref-main/src/main/java/org/jabref/model/database/BibDatabases.java
package org.jabref.model.database; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.jabref.model.entry.BibEntry; public class BibDatabases { private BibDatabases() { } /** * Receives a Collection of BibEntry instances, iterates through them, and * removes all entries that have no fields set. This is useful for rooting out * an unsucessful import (wrong format) that returns a number of empty entries. */ public static List<BibEntry> purgeEmptyEntries(Collection<BibEntry> entries) { return entries.stream() .filter(entry -> !entry.getFields().isEmpty()) .collect(Collectors.toList()); } }
738
28.56
83
java
null
jabref-main/src/main/java/org/jabref/model/database/KeyChangeListener.java
package org.jabref.model.database; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.jabref.model.database.event.EntriesRemovedEvent; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.event.FieldChangedEvent; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.FieldProperty; import org.jabref.model.entry.field.InternalField; import com.google.common.eventbus.Subscribe; public class KeyChangeListener { private final BibDatabase database; public KeyChangeListener(BibDatabase database) { this.database = database; } @Subscribe public void listen(FieldChangedEvent event) { if (event.getField().equals(InternalField.KEY_FIELD)) { String newKey = event.getNewValue(); String oldKey = event.getOldValue(); updateEntryLinks(newKey, oldKey); } } @Subscribe public void listen(EntriesRemovedEvent event) { List<BibEntry> entries = event.getBibEntries(); for (BibEntry entry : entries) { Optional<String> citeKey = entry.getCitationKey(); citeKey.ifPresent(oldkey -> updateEntryLinks(null, oldkey)); } } private void updateEntryLinks(String newKey, String oldKey) { for (BibEntry entry : database.getEntries()) { for (Field field : FieldFactory.getKeyFields()) { entry.getField(field).ifPresent(fieldContent -> { if (field.getProperties().contains(FieldProperty.SINGLE_ENTRY_LINK)) { replaceSingleKeyInField(newKey, oldKey, entry, field, fieldContent); } else { // MULTIPLE_ENTRY_LINK replaceKeyInMultiplesKeyField(newKey, oldKey, entry, field, fieldContent); } }); } } } private void replaceKeyInMultiplesKeyField(String newKey, String oldKey, BibEntry entry, Field field, String fieldContent) { List<String> keys = new ArrayList<>(Arrays.asList(fieldContent.split(","))); int index = keys.indexOf(oldKey); if (index != -1) { if (newKey == null) { keys.remove(index); } else { keys.set(index, newKey); } entry.setField(field, String.join(",", keys)); } } private void replaceSingleKeyInField(String newKey, String oldKey, BibEntry entry, Field field, String fieldContent) { if (fieldContent.equals(oldKey)) { if (newKey == null) { entry.clearField(field); } else { entry.setField(field, newKey); } } } }
2,816
33.777778
128
java
null
jabref-main/src/main/java/org/jabref/model/database/KeyCollisionException.java
package org.jabref.model.database; public class KeyCollisionException extends RuntimeException { private String id; public KeyCollisionException() { super(); } public KeyCollisionException(String msg, String id) { super(msg); this.id = id; } public KeyCollisionException(String msg, Throwable exception) { super(msg, exception); } public KeyCollisionException(Throwable exception) { super(exception); } public String getId() { return id; } }
541
18.357143
67
java
null
jabref-main/src/main/java/org/jabref/model/database/event/AutosaveEvent.java
package org.jabref.model.database.event; /** * This Event is fired from {@link org.jabref.logic.autosaveandbackup.AutosaveManager} in case that a save task is pending. */ public class AutosaveEvent { // no data }
220
23.555556
123
java
null
jabref-main/src/main/java/org/jabref/model/database/event/BibDatabaseContextChangedEvent.java
package org.jabref.model.database.event; import org.jabref.model.entry.event.EntriesEvent; import org.jabref.model.groups.event.GroupUpdatedEvent; import org.jabref.model.metadata.event.MetaDataChangedEvent; /** * This event is automatically fired at the same time as {@link EntriesEvent}, {@link GroupUpdatedEvent}, or {@link MetaDataChangedEvent}, * because all three inherit from this class. */ public abstract class BibDatabaseContextChangedEvent { // If the event has been filtered out private boolean filteredOut; public BibDatabaseContextChangedEvent() { this(false); } public BibDatabaseContextChangedEvent(boolean filteredOut) { this.filteredOut = filteredOut; } /** * Check if this event can be filtered out to be synchronized with a database at a later time. */ public boolean isFilteredOut() { return filteredOut; } public void setFilteredOut(boolean filtered) { this.filteredOut = filtered; } }
1,003
28.529412
138
java
null
jabref-main/src/main/java/org/jabref/model/database/event/ChangePropagation.java
package org.jabref.model.database.event; public enum ChangePropagation { POST_EVENT, DO_NOT_POST_EVENT }
110
17.5
40
java
null
jabref-main/src/main/java/org/jabref/model/database/event/EntriesAddedEvent.java
package org.jabref.model.database.event; import java.util.List; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.event.EntriesEvent; import org.jabref.model.entry.event.EntriesEventSource; /** * {@link EntriesAddedEvent} is fired when at least {@link BibEntry} is being added to the {@link BibDatabase}. */ public class EntriesAddedEvent extends EntriesEvent { // firstEntry used by listeners that used to listen to AllInsertsFinishedEvent // final? private final BibEntry firstEntry; /** * @param bibEntries the entries which are being added * @param firstEntry the first entry being added */ public EntriesAddedEvent(List<BibEntry> bibEntries, BibEntry firstEntry, EntriesEventSource location) { super(bibEntries, location); this.firstEntry = firstEntry; } /** * @param bibEntries <code>List</code> of <code>BibEntry</code> objects which are being added. * @param location Location affected by this event */ public EntriesAddedEvent(List<BibEntry> bibEntries, EntriesEventSource location) { super(bibEntries, location); this.firstEntry = null; } public BibEntry getFirstEntry() { return this.firstEntry; } }
1,303
30.047619
111
java
null
jabref-main/src/main/java/org/jabref/model/database/event/EntriesRemovedEvent.java
package org.jabref.model.database.event; import java.util.List; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.event.EntriesEvent; import org.jabref.model.entry.event.EntriesEventSource; /** * <code>EntriesRemovedEvent</code> is fired when at least one <code>BibEntry</code> is being removed * from the database. */ public class EntriesRemovedEvent extends EntriesEvent { /** * @param bibEntries <code>List</code> of <code>BibEntry</code> objects which are being removed. */ public EntriesRemovedEvent(List<BibEntry> bibEntries) { super(bibEntries); } /** * @param bibEntries <code>List</code> of <code>BibEntry</code> objects which are being removed. * @param location Location affected by this event */ public EntriesRemovedEvent(List<BibEntry> bibEntries, EntriesEventSource location) { super(bibEntries, location); } }
922
28.774194
101
java
null
jabref-main/src/main/java/org/jabref/model/entry/Author.java
package org.jabref.model.entry; import java.util.Objects; import java.util.Optional; import org.jabref.model.strings.LatexToUnicodeAdapter; import org.jabref.model.strings.StringUtil; /** * This is an immutable class that keeps information regarding single author. It is just a container for the information, with very simple methods to access it. * <p> * Current usage: only methods <code>getLastOnly</code>, <code>getFirstLast</code>, and <code>getLastFirst</code> are used; all other methods are provided for completeness. */ public class Author { /** * Object indicating the <code>others</code> author. This is a BibTeX feature mostly rendered in "et al." in LaTeX. * Example: <code>authors = {Oliver Kopp and others}</code>. This is then appearing as "Oliver Kopp et al.". * In the context of BibTeX key generation, this is "Kopp+" (<code>+</code> for "et al.") and not "KO". */ public static final Author OTHERS = new Author("", "", null, "others", null); private final String firstPart; private final String firstAbbr; private final String vonPart; private final String lastPart; private final String jrPart; private Author latexFreeAuthor; /** * Creates the Author object. If any part of the name is absent, <CODE>null</CODE> must be passed; otherwise other methods may return erroneous results. * * @param first the first name of the author (may consist of several tokens, like "Charles Louis Xavier Joseph" in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin") * @param firstabbr the abbreviated first name of the author (may consist of several tokens, like "C. L. X. J." in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin"). It is a responsibility of the caller to create a reasonable abbreviation of the first name. * @param von the von part of the author's name (may consist of several tokens, like "de la" in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin") * @param last the last name of the author (may consist of several tokens, like "Vall{\'e}e Poussin" in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin") * @param jr the junior part of the author's name (may consist of several tokens, like "Jr. III" in "Smith, Jr. III, John") */ public Author(String first, String firstabbr, String von, String last, String jr) { firstPart = addDotIfAbbreviation(removeStartAndEndBraces(first)); firstAbbr = removeStartAndEndBraces(firstabbr); vonPart = removeStartAndEndBraces(von); lastPart = removeStartAndEndBraces(last); jrPart = removeStartAndEndBraces(jr); } public static String addDotIfAbbreviation(String name) { if ((name == null) || name.isEmpty()) { return name; } // If only one character (uppercase letter), add a dot and return immediately: if ((name.length() == 1) && Character.isLetter(name.charAt(0)) && Character.isUpperCase(name.charAt(0))) { return name + "."; } StringBuilder sb = new StringBuilder(); char lastChar = name.charAt(0); for (int i = 0; i < name.length(); i++) { if (i > 0) { lastChar = name.charAt(i - 1); } char currentChar = name.charAt(i); sb.append(currentChar); if (currentChar == '.') { // A.A. -> A. A. if (((i + 1) < name.length()) && Character.isUpperCase(name.charAt(i + 1))) { sb.append(' '); } } boolean currentIsUppercaseLetter = Character.isLetter(currentChar) && Character.isUpperCase(currentChar); if (!currentIsUppercaseLetter) { // No uppercase letter, hence nothing to do continue; } boolean lastIsLowercaseLetter = Character.isLetter(lastChar) && Character.isLowerCase(lastChar); if (lastIsLowercaseLetter) { // previous character was lowercase (probably an acronym like JabRef) -> don't change anything continue; } if ((i + 1) >= name.length()) { // Current character is last character in input, so append dot sb.append('.'); continue; } char nextChar = name.charAt(i + 1); if ('-' == nextChar) { // A-A -> A.-A. sb.append("."); continue; } if ('.' == nextChar) { // Dot already there, so nothing to do continue; } // AA -> A. A. // Only append ". " if the rest of the 'word' is uppercase boolean nextWordIsUppercase = true; char furtherChar = Character.MIN_VALUE; for (int j = i + 1; j < name.length(); j++) { furtherChar = name.charAt(j); if (Character.isWhitespace(furtherChar) || (furtherChar == '-') || (furtherChar == '~') || (furtherChar == '.')) { // end of word break; } boolean furtherIsUppercaseLetter = Character.isLetter(furtherChar) && Character.isUpperCase(furtherChar); if (!furtherIsUppercaseLetter) { nextWordIsUppercase = false; break; } } if (nextWordIsUppercase) { if (Character.isWhitespace(furtherChar)) { sb.append("."); } else { sb.append(". "); } } } return sb.toString().trim(); } @Override public int hashCode() { return Objects.hash(firstAbbr, firstPart, jrPart, lastPart, vonPart); } /** * Compare this object with the given one. * * @return `true` iff the other object is an Author and all fields are `Objects.equals`. */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof Author that) { return Objects.equals(firstPart, that.firstPart) && Objects.equals(firstAbbr, that.firstAbbr) && Objects.equals(vonPart, that.vonPart) && Objects.equals(lastPart, that.lastPart) && Objects.equals(jrPart, that.jrPart); } return false; } /** * @return true iff the brackets in s are properly paired */ private boolean properBrackets(String s) { // nested construct is there, check for "proper" nesting int i = 0; int level = 0; while (i < s.length()) { char c = s.charAt(i); switch (c) { case '{': level++; break; case '}': level--; if (level == -1) { // improper nesting return false; } break; default: break; } i++; } return level == 0; } /** * Removes start and end brace at a string * <p> * E.g., * <ul> * <li>{Vall{\'e}e Poussin} -> Vall{\'e}e Poussin</li> * <li>{Vall{\'e}e} {Poussin} -> Vall{\'e}e Poussin</li> * <li>Vall{\'e}e Poussin -> Vall{\'e}e Poussin</li> * </ul> */ private String removeStartAndEndBraces(String name) { if (StringUtil.isBlank(name)) { return null; } if (!name.contains("{")) { return name; } String[] split = name.split(" "); StringBuilder b = new StringBuilder(); for (String s : split) { if ((s.length() > 2) && s.startsWith("{") && s.endsWith("}")) { // quick solution (which we don't do: just remove first "{" and last "}" // however, it might be that s is like {A}bbb{c}, where braces may not be removed // inner String inner = s.substring(1, s.length() - 1); if (inner.contains("}")) { if (properBrackets(inner)) { s = inner; } } else { // no inner curly brackets found, no check needed, inner can just be used as s s = inner; } } b.append(s).append(' '); } // delete last b.deleteCharAt(b.length() - 1); // now, all inner words are cleared // case {word word word} remains // as above, we have to be aware of {w}ord word wor{d} and {{w}ord word word} String newName = b.toString(); if (newName.startsWith("{") && newName.endsWith("}")) { String inner = newName.substring(1, newName.length() - 1); if (properBrackets(inner)) { return inner; } else { return newName; } } else { return newName; } } /** * Returns the first name of the author stored in this object ("First"). * * @return first name of the author (may consist of several tokens) */ public Optional<String> getFirst() { return Optional.ofNullable(firstPart); } /** * Returns the abbreviated first name of the author stored in this object ("F."). * * @return abbreviated first name of the author (may consist of several tokens) */ public Optional<String> getFirstAbbr() { return Optional.ofNullable(firstAbbr); } /** * Returns the von part of the author's name stored in this object ("von"). * * @return von part of the author's name (may consist of several tokens) */ public Optional<String> getVon() { return Optional.ofNullable(vonPart); } /** * Returns the last name of the author stored in this object ("Last"). * * @return last name of the author (may consist of several tokens) */ public Optional<String> getLast() { return Optional.ofNullable(lastPart); } /** * Returns the junior part of the author's name stored in this object ("Jr"). * * @return junior part of the author's name (may consist of several tokens) or null if the author does not have a Jr. Part */ public Optional<String> getJr() { return Optional.ofNullable(jrPart); } /** * Returns von-part followed by last name ("von Last"). If both fields were specified as <CODE>null</CODE>, the empty string <CODE>""</CODE> is returned. * * @return 'von Last' */ public String getLastOnly() { if (vonPart == null) { return getLast().orElse(""); } else { return lastPart == null ? vonPart : vonPart + ' ' + lastPart; } } /** * Returns the author's name in form 'von Last, Jr., First' with the first name full or abbreviated depending on parameter. * * @param abbr <CODE>true</CODE> - abbreviate first name, <CODE>false</CODE> - do not abbreviate * @return 'von Last, Jr., First' (if <CODE>abbr==false</CODE>) or 'von Last, Jr., F.' (if <CODE>abbr==true</CODE>) */ public String getLastFirst(boolean abbr) { StringBuilder res = new StringBuilder(getLastOnly()); getJr().ifPresent(jr -> res.append(", ").append(jr)); if (abbr) { getFirstAbbr().ifPresent(firstA -> res.append(", ").append(firstA)); } else { getFirst().ifPresent(first -> res.append(", ").append(first)); } return res.toString(); } /** * Returns the author's name in form 'First von Last, Jr.' with the first name full or abbreviated depending on parameter. * * @param abbr <CODE>true</CODE> - abbreviate first name, <CODE>false</CODE> - do not abbreviate * @return 'First von Last, Jr.' (if <CODE>abbr==false</CODE>) or 'F. von Last, Jr.' (if <CODE>abbr==true</CODE>) */ public String getFirstLast(boolean abbr) { StringBuilder res = new StringBuilder(); if (abbr) { getFirstAbbr().map(firstA -> firstA + ' ').ifPresent(res::append); } else { getFirst().map(first -> first + ' ').ifPresent(res::append); } res.append(getLastOnly()); getJr().ifPresent(jr -> res.append(", ").append(jr)); return res.toString(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("Author{"); sb.append("firstPart='").append(firstPart).append('\''); sb.append(", firstAbbr='").append(firstAbbr).append('\''); sb.append(", vonPart='").append(vonPart).append('\''); sb.append(", lastPart='").append(lastPart).append('\''); sb.append(", jrPart='").append(jrPart).append('\''); sb.append('}'); return sb.toString(); } /** * Returns the name as "Last, Jr, F." omitting the von-part and removing starting braces. * * @return "Last, Jr, F." as described above or "" if all these parts are empty. */ public String getNameForAlphabetization() { StringBuilder res = new StringBuilder(); getLast().ifPresent(res::append); getJr().ifPresent(jr -> res.append(", ").append(jr)); getFirstAbbr().ifPresent(firstA -> res.append(", ").append(firstA)); while ((res.length() > 0) && (res.charAt(0) == '{')) { res.deleteCharAt(0); } return res.toString(); } /** * Returns a LaTeX-free version of this `Author`. */ public Author latexFree() { if (latexFreeAuthor == null) { String first = getFirst().map(LatexToUnicodeAdapter::format).orElse(null); String firstabbr = getFirstAbbr().map(LatexToUnicodeAdapter::format).orElse(null); String von = getVon().map(LatexToUnicodeAdapter::format).orElse(null); String last = getLast().map(LatexToUnicodeAdapter::format).orElse(null); String jr = getJr().map(LatexToUnicodeAdapter::format).orElse(null); latexFreeAuthor = new Author(first, firstabbr, von, last, jr); latexFreeAuthor.latexFreeAuthor = latexFreeAuthor; } return latexFreeAuthor; } }
14,580
37.070496
267
java