Skip to content

Commit 5b70e9c

Browse files
committed
Merge pull request #718 from tobiasdiez/databaseWriter
Improve database writer
2 parents a243769 + c510134 commit 5b70e9c

File tree

86 files changed

+2024
-1122
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

86 files changed

+2024
-1122
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ to [sourceforge feature requests](https://sourceforge.net/p/jabref/features/) by
1313
## [Unreleased]
1414

1515
### Changed
16+
- Implemented [#756](https://github.com/JabRef/jabref/issues/756): Add possibility to reformat all entries on save (under Preferences, File)
17+
- Comments and preamble are serialized with capitalized first letter, i.e. `@Comment` instead of `@comment` and `@Preamble` instead of `@PREAMBLE`.
1618
- Global sorting options and preferences are removed. Databases can still be sorted on save, but this is configured locally and stored in the file
1719
- OvidImporter now also imports fields: doi, issn, language and keywords
1820
- Implemented [#647](https://github.com/JabRef/jabref/issues/647): The preview can now be copied
@@ -26,6 +28,7 @@ to [sourceforge feature requests](https://sourceforge.net/p/jabref/features/) by
2628

2729

2830
### Fixed
31+
- Fixed [#621](https://github.com/JabRef/jabref/issues/621) and [#669](https://github.com/JabRef/jabref/issues/669): Encoding and preamble now end with newline.
2932
- Make BibTex parser more robust against missing newlines
3033
- Fix bug that prevented the import of BibTex entries having only a key as content
3134
- Fixed [#666](https://github.com/JabRef/jabref/issues/666): MS Office 2007 export is working again

src/main/java/net/sf/jabref/BibDatabaseContext.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,6 @@ public BibDatabaseContext(BibDatabase database, MetaData metaData, Defaults defa
3232
this.defaults = Objects.requireNonNull(defaults);
3333
this.database = Objects.requireNonNull(database);
3434
this.metaData = Objects.requireNonNull(metaData);
35-
36-
this.setMode(getMode());
3735
}
3836

3937
public BibDatabaseContext(BibDatabase database, MetaData metaData, File file, Defaults defaults) {

src/main/java/net/sf/jabref/JabRef.java

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -309,11 +309,13 @@ public Optional<Vector<ParserResult>> processArguments(String[] args, boolean in
309309
if (!pr.isInvalid()) {
310310
try {
311311
System.out.println(Localization.lang("Saving") + ": " + data[0]);
312-
Defaults defaults = new Defaults(BibDatabaseMode.fromPreference(Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_MODE)));
313-
SaveSession session = FileActions.saveDatabase(
314-
new BibDatabaseContext(pr.getDatabase(), pr.getMetaData(), defaults),
315-
new File(data[0]), Globals.prefs, false, false,
316-
Globals.prefs.getDefaultEncoding(), false);
312+
SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs);
313+
Defaults defaults = new Defaults(BibDatabaseMode
314+
.fromPreference(Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_MODE)));
315+
BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
316+
SaveSession session = databaseWriter.saveDatabase(
317+
new BibDatabaseContext(pr.getDatabase(), pr.getMetaData(), defaults), prefs);
318+
317319
// Show just a warning message if encoding didn't work for all characters:
318320
if (!session.getWriter().couldEncodeAll()) {
319321
System.err.println(Localization.lang("Warning") + ": "
@@ -323,7 +325,7 @@ public Optional<Vector<ParserResult>> processArguments(String[] args, boolean in
323325
+ " "
324326
+ session.getWriter().getProblemCharacters());
325327
}
326-
session.commit();
328+
session.commit(new File(data[0]));
327329
} catch (SaveException ex) {
328330
System.err.println(Localization.lang("Could not save file.") + "\n"
329331
+ ex.getLocalizedMessage());
@@ -399,10 +401,14 @@ public Optional<Vector<ParserResult>> processArguments(String[] args, boolean in
399401

400402
try {
401403
System.out.println(Localization.lang("Saving") + ": " + subName);
402-
Defaults defaults = new Defaults(BibDatabaseMode.fromPreference(Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_MODE)));
403-
SaveSession session = FileActions.saveDatabase(new BibDatabaseContext(newBase, defaults),
404-
new File(subName), Globals.prefs, false, false,
405-
Globals.prefs.getDefaultEncoding(), false);
404+
SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs);
405+
BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
406+
Defaults defaults = new Defaults(BibDatabaseMode
407+
.fromPreference(Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_MODE)));
408+
SaveSession session = databaseWriter.saveDatabase(
409+
new BibDatabaseContext(newBase, defaults), prefs);
410+
411+
406412
// Show just a warning message if encoding didn't work for all characters:
407413
if (!session.getWriter().couldEncodeAll()) {
408414
System.err.println(Localization.lang("Warning") + ": "
@@ -412,7 +418,7 @@ public Optional<Vector<ParserResult>> processArguments(String[] args, boolean in
412418
+ " "
413419
+ session.getWriter().getProblemCharacters());
414420
}
415-
session.commit();
421+
session.commit(new File(subName));
416422
} catch (SaveException ex) {
417423
System.err.println(Localization.lang("Could not save file.") + "\n"
418424
+ ex.getLocalizedMessage());

src/main/java/net/sf/jabref/JabRefPreferences.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@
6060
public class JabRefPreferences {
6161
private static final Log LOGGER = LogFactory.getLog(JabRefPreferences.class);
6262
public static final String EXTERNAL_FILE_TYPES = "externalFileTypes";
63-
6463
/**
6564
* HashMap that contains all preferences which are set by default
6665
*/
@@ -110,6 +109,7 @@ public class JabRefPreferences {
110109
public static final String TABLE_SECONDARY_SORT_DESCENDING = "secDescending";
111110
public static final String TABLE_TERTIARY_SORT_FIELD = "terSort";
112111
public static final String TABLE_TERTIARY_SORT_DESCENDING = "terDescending";
112+
public static final String REFORMAT_FILE_ON_SAVE_AND_EXPORT = "reformatFileOnSaveAndExport";
113113
public static final String EXPORT_IN_ORIGINAL_ORDER = "exportInOriginalOrder";
114114
public static final String EXPORT_IN_SPECIFIED_ORDER = "exportInSpecifiedOrder";
115115
public static final String EXPORT_PRIMARY_SORT_FIELD = "exportPriSort";
@@ -505,6 +505,8 @@ private JabRefPreferences() {
505505
defaults.put(TABLE_TERTIARY_SORT_FIELD, "title");
506506
defaults.put(TABLE_TERTIARY_SORT_DESCENDING, Boolean.FALSE);
507507

508+
defaults.put(REFORMAT_FILE_ON_SAVE_AND_EXPORT, Boolean.FALSE);
509+
508510
// export order
509511
defaults.put(EXPORT_IN_ORIGINAL_ORDER, Boolean.FALSE);
510512
defaults.put(EXPORT_IN_SPECIFIED_ORDER, Boolean.FALSE);

src/main/java/net/sf/jabref/MetaData.java

Lines changed: 7 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,17 @@
2424
import net.sf.jabref.logic.labelPattern.DatabaseLabelPattern;
2525
import net.sf.jabref.model.database.BibDatabase;
2626
import net.sf.jabref.sql.DBStrings;
27-
import net.sf.jabref.logic.util.strings.StringUtil;
2827

2928
public class MetaData implements Iterable<String> {
3029

3130
public static final String META_FLAG = "jabref-meta: ";
31+
public static final String SAVE_ORDER_CONFIG = "saveOrderConfig";
3232
private static final String PREFIX_KEYPATTERN = "keypattern_";
3333
private static final String KEYPATTERNDEFAULT = "keypatterndefault";
3434
static final String DATABASE_TYPE = "DATABASE_TYPE";
35+
public static final String GROUPSVERSION = "groupsversion";
36+
public static final String GROUPSTREE = "groupstree";
37+
public static final String GROUPS = "groups";
3538

3639
private final Map<String, List<String>> metaData = new HashMap<>();
3740
private GroupTreeNode groupsRoot;
@@ -70,16 +73,16 @@ public MetaData(Map<String, String> inData, BibDatabase db) {
7073
} catch (IOException ex) {
7174
System.err.println("Weird error while parsing meta data.");
7275
}
73-
if ("groupsversion".equals(entry.getKey())) {
76+
if (GROUPSVERSION.equals(entry.getKey())) {
7477
if (!orderedData.isEmpty()) {
7578
groupsVersionOnDisk = Integer.parseInt(orderedData.get(0));
7679
}
77-
} else if ("groupstree".equals(entry.getKey())) {
80+
} else if (GROUPSTREE.equals(entry.getKey())) {
7881
groupsTreePresent = true;
7982
treeGroupsData = orderedData; // save for later user
8083
// actual import operation is handled later because "groupsversion"
8184
// tag might not yet have been read
82-
} else if ("groups".equals(entry.getKey())) {
85+
} else if (GROUPS.equals(entry.getKey())) {
8386
flatGroupsData = orderedData;
8487
} else {
8588
putData(entry.getKey(), orderedData);
@@ -260,55 +263,6 @@ public void setGroups(GroupTreeNode root) {
260263
groupTreeValid = true;
261264
}
262265

263-
/**
264-
* Writes all data to the specified writer, using each object's toString()
265-
* method.
266-
*/
267-
public void writeMetaData(Writer out) throws IOException {
268-
// write all meta data except groups
269-
SortedSet<String> sortedKeys = new TreeSet<>(metaData.keySet());
270-
271-
for (String key : sortedKeys) {
272-
273-
StringBuffer sb = new StringBuffer();
274-
sb.append(Globals.NEWLINE).append(Globals.NEWLINE);
275-
List<String> orderedData = metaData.get(key);
276-
sb.append("@comment{").append(META_FLAG).append(key).append(':');
277-
for (String data : orderedData) {
278-
sb.append(StringUtil.quote(data, ";", '\\')).append(';');
279-
}
280-
sb.append('}');
281-
282-
out.write(sb.toString());
283-
}
284-
// write groups if present. skip this if only the root node exists
285-
// (which is always the AllEntriesGroup).
286-
if ((groupsRoot != null) && (groupsRoot.getChildCount() > 0)) {
287-
StringBuffer sb = new StringBuffer();
288-
// write version first
289-
sb.append(Globals.NEWLINE).append(Globals.NEWLINE);
290-
sb.append("@comment{").append(META_FLAG).append("groupsversion:");
291-
sb.append(VersionHandling.CURRENT_VERSION).append(";}");
292-
293-
out.write(sb.toString());
294-
295-
// now write actual groups
296-
sb = new StringBuffer();
297-
sb.append(Globals.NEWLINE).append(Globals.NEWLINE);
298-
sb.append("@comment{").append(META_FLAG).append("groupstree:");
299-
sb.append(Globals.NEWLINE);
300-
// GroupsTreeNode.toString() uses "\n" for separation
301-
StringTokenizer tok = new StringTokenizer(groupsRoot.getTreeAsString(), Globals.NEWLINE);
302-
while (tok.hasMoreTokens()) {
303-
StringBuffer s = new StringBuffer(StringUtil.quote(tok.nextToken(), ";", '\\')).append(';');
304-
sb.append(s);
305-
sb.append(Globals.NEWLINE);
306-
}
307-
sb.append('}');
308-
out.write(sb.toString());
309-
}
310-
}
311-
312266
/**
313267
* Reads the next unit. Units are delimited by ';'.
314268
*/

src/main/java/net/sf/jabref/bibtex/BibEntryWriter.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,17 @@ public BibEntryWriter(LatexFieldFormatter fieldFormatter, boolean write) {
2727
}
2828

2929
public void write(BibEntry entry, Writer out, BibDatabaseMode bibDatabaseMode) throws IOException {
30+
write(entry, out, bibDatabaseMode, false);
31+
}
32+
public void write(BibEntry entry, Writer out, BibDatabaseMode bibDatabaseMode, Boolean reformat) throws IOException {
3033
// if the entry has not been modified, write it as it was
31-
if (!entry.hasChanged()) {
34+
if (!reformat && !entry.hasChanged()) {
3235
out.write(entry.getParsedSerialization());
3336
return;
3437
}
35-
out.write(Globals.NEWLINE + Globals.NEWLINE);
36-
38+
out.write(Globals.NEWLINE);
3739
writeRequiredFieldsFirstRemainingFieldsSecond(entry, out, bibDatabaseMode);
40+
out.write(Globals.NEWLINE);
3841
}
3942

4043
public void writeWithoutPrependedNewlines(BibEntry entry, Writer out, BibDatabaseMode bibDatabaseMode) throws IOException {

src/main/java/net/sf/jabref/bibtex/comparator/FieldComparator.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import net.sf.jabref.gui.InternalBibtexFields;
1919
import net.sf.jabref.gui.maintable.MainTableFormat;
20+
import net.sf.jabref.logic.config.SaveOrderConfig;
2021
import net.sf.jabref.logic.util.strings.StringUtil;
2122
import net.sf.jabref.model.entry.AuthorList;
2223
import net.sf.jabref.model.entry.MonthUtil;
@@ -27,6 +28,7 @@
2728
import java.text.ParseException;
2829
import java.text.RuleBasedCollator;
2930
import java.util.Comparator;
31+
import java.util.Objects;
3032

3133
/**
3234
*
@@ -71,7 +73,7 @@ public FieldComparator(String field) {
7173
}
7274

7375
public FieldComparator(String field, boolean reversed) {
74-
this.fieldName = field;
76+
this.fieldName = Objects.requireNonNull(field);
7577
this.field = field.split(MainTableFormat.COL_DEFINITION_FIELD_SEPARATOR);
7678
multiplier = reversed ? -1 : 1;
7779
isTypeHeader = this.field[0].equals(BibEntry.TYPE_HEADER);
@@ -82,6 +84,10 @@ public FieldComparator(String field, boolean reversed) {
8284
isNumeric = InternalBibtexFields.isNumeric(this.field[0]);
8385
}
8486

87+
public FieldComparator(SaveOrderConfig.SortCriterion sortCriterion) {
88+
this(sortCriterion.field, sortCriterion.descending);
89+
}
90+
8591
@Override
8692
public int compare(BibEntry e1, BibEntry e2) {
8793
Object f1;

src/main/java/net/sf/jabref/collab/ChangeScanner.java

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@
2828
import org.apache.commons.logging.LogFactory;
2929

3030
import net.sf.jabref.*;
31-
import net.sf.jabref.exporter.FileActions;
31+
import net.sf.jabref.exporter.BibDatabaseWriter;
3232
import net.sf.jabref.exporter.SaveException;
33+
import net.sf.jabref.exporter.SavePreferences;
3334
import net.sf.jabref.exporter.SaveSession;
3435
import net.sf.jabref.groups.GroupTreeNode;
3536
import net.sf.jabref.gui.BasePanel;
@@ -158,11 +159,14 @@ private void storeTempDatabase() {
158159
@Override
159160
public void run() {
160161
try {
162+
SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs)
163+
.withMakeBackup(false)
164+
.withEncoding(panel.getEncoding());
165+
161166
Defaults defaults = new Defaults(BibDatabaseMode.fromPreference(Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_MODE)));
162-
SaveSession ss = FileActions.saveDatabase(new BibDatabaseContext(inTemp, mdInTemp, defaults),
163-
Globals.fileUpdateMonitor.getTempFile(panel.fileMonitorHandle()), Globals.prefs, false,
164-
false, panel.getEncoding(), true);
165-
ss.commit();
167+
BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
168+
SaveSession ss = databaseWriter.saveDatabase(new BibDatabaseContext(inTemp, mdInTemp, defaults), prefs);
169+
ss.commit(Globals.fileUpdateMonitor.getTempFile(panel.fileMonitorHandle()));
166170
} catch (SaveException ex) {
167171
LOGGER.warn("Problem updating tmp file after accepting external changes", ex);
168172
}

src/main/java/net/sf/jabref/exporter/AutoSaveManager.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,13 @@ private static boolean autoSave(BasePanel panel) {
9696
File databaseFile = panel.getBibDatabaseContext().getDatabaseFile();
9797
File backupFile = AutoSaveManager.getAutoSaveFile(databaseFile);
9898
try {
99-
SaveSession ss = FileActions.saveDatabase(panel.getBibDatabaseContext(),
100-
backupFile, Globals.prefs, false, false, panel.getEncoding(), true);
101-
ss.commit();
99+
SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs)
100+
.withMakeBackup(false)
101+
.withEncoding(panel.getEncoding());
102+
103+
BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
104+
SaveSession ss = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);
105+
102106
} catch (SaveException e) {
103107
LOGGER.error("Problem with automatic save", e);
104108
return false;

0 commit comments

Comments
 (0)