Skip to content

Commit

Permalink
Merge pull request #541 from oscargus/moreoptional
Browse files Browse the repository at this point in the history
More use of Optional and some other fixes
  • Loading branch information
simonharrer committed Dec 21, 2015
2 parents 1c4bfe6 + 8834265 commit 85904c7
Show file tree
Hide file tree
Showing 20 changed files with 111 additions and 152 deletions.
65 changes: 25 additions & 40 deletions src/main/java/net/sf/jabref/JabRef.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Vector;
import java.util.prefs.BackingStoreException;

Expand Down Expand Up @@ -158,22 +159,22 @@ public void start(String[] args) {
// The preferences return the system newline character sequence as default
Globals.NEWLINE = Globals.prefs.get(JabRefPreferences.NEWLINE);

Vector<ParserResult> loaded = processArguments(args, true);
Optional<Vector<ParserResult>> loaded = processArguments(args, true);

if ((loaded == null) || cli.isDisableGui() || cli.isShowVersion()) {
if ((!(loaded.isPresent())) || cli.isDisableGui() || cli.isShowVersion()) {
JabRefExecutorService.INSTANCE.shutdownEverything();
return;
}

SwingUtilities.invokeLater(() -> openWindow(loaded));
SwingUtilities.invokeLater(() -> openWindow(loaded.get()));
}

private void setupLogHandlerForErrorConsole() {
Globals.handler = new CacheableHandler();
((Jdk14Logger) LOGGER).getLogger().addHandler(Globals.handler);
}

public Vector<ParserResult> processArguments(String[] args, boolean initialStartup) {
public Optional<Vector<ParserResult>> processArguments(String[] args, boolean initialStartup) {

cli = new JabRefCLI(args);

Expand All @@ -183,7 +184,7 @@ public Vector<ParserResult> processArguments(String[] args, boolean initialStart

if (initialStartup && cli.isHelp()) {
cli.printUsage();
return null; // TODO replace with optional one day
return Optional.empty();
}

// Check if we should reset all preferences to default values:
Expand Down Expand Up @@ -246,12 +247,7 @@ public Vector<ParserResult> processArguments(String[] args, boolean initialStart
if (initialStartup) {
toImport.add(aLeftOver);
} else {
ParserResult res = JabRef.importToOpenBase(aLeftOver);
if (res != null) {
loaded.add(res);
} else {
loaded.add(ParserResult.INVALID_FORMAT);
}
loaded.add(JabRef.importToOpenBase(aLeftOver).orElse(ParserResult.INVALID_FORMAT));
}
} else if (pr != ParserResult.FILE_LOCKED) {
loaded.add(pr);
Expand All @@ -265,24 +261,15 @@ public Vector<ParserResult> processArguments(String[] args, boolean initialStart
}

for (String filenameString : toImport) {
ParserResult pr = JabRef.importFile(filenameString);
if (pr != null) {
loaded.add(pr);
}
importFile(filenameString).ifPresent(loaded::add);
}

if (!cli.isBlank() && cli.isImportToOpenBase()) {
ParserResult res = JabRef.importToOpenBase(cli.getImportToOpenBase());
if (res != null) {
loaded.add(res);
}
importToOpenBase(cli.getImportToOpenBase()).ifPresent(loaded::add);
}

if (!cli.isBlank() && cli.isFetcherEngine()) {
ParserResult res = fetch(cli.getFetcherEngine());
if (res != null) {
loaded.add(res);
}
fetch(cli.getFetcherEngine()).ifPresent(loaded::add);
}

if (cli.isExportMatches()) {
Expand Down Expand Up @@ -315,7 +302,7 @@ public Vector<ParserResult> processArguments(String[] args, boolean initialStart
System.err.println(
Localization.lang("Output file missing").concat(". \n \t ").concat("Usage").concat(": ")
+ JabRefCLI.getExportMatchesSyntax());
return null; // TODO replace with optional one day
return Optional.empty();
} //end switch

//export new database
Expand Down Expand Up @@ -479,7 +466,7 @@ public Vector<ParserResult> processArguments(String[] args, boolean initialStart
}
}

return loaded;
return Optional.of(loaded);
}

/**
Expand All @@ -491,12 +478,12 @@ public Vector<ParserResult> processArguments(String[] args, boolean initialStart
* the search query, separated by a :
* @return A parser result containing the entries fetched or null if an error occurred.
*/
private ParserResult fetch(String fetchCommand) {
private Optional<ParserResult> fetch(String fetchCommand) {

if ((fetchCommand == null) || !fetchCommand.contains(":") || (fetchCommand.split(":").length != 2)) {
System.out.println(Localization.lang("Expected syntax for --fetch='<name of fetcher>:<query>'"));
System.out.println(Localization.lang("The following fetchers are available:"));
return null;
return Optional.empty();
}

String[] split = fetchCommand.split(":");
Expand All @@ -517,7 +504,7 @@ private ParserResult fetch(String fetchCommand) {
for (EntryFetcher e : EntryFetchers.INSTANCE.getEntryFetchers()) {
System.out.println(" " + e.getClass().getSimpleName().replaceAll("Fetcher", "").toLowerCase());
}
return null;
return Optional.empty();
}

System.out.println(Localization.lang("Running Query '%0' with fetcher '%1'.", query, engine) + " "
Expand All @@ -527,10 +514,10 @@ private ParserResult fetch(String fetchCommand) {
if ((result == null) || result.isEmpty()) {
System.out.println(
Localization.lang("Query '%0' with fetcher '%1' did not return any results.", query, engine));
return null;
return Optional.empty();
}

return new ParserResult(result);
return Optional.of(new ParserResult(result));
}

private void setLookAndFeel() {
Expand Down Expand Up @@ -832,7 +819,7 @@ public static ParserResult openBibFile(String name, boolean ignoreAutosave) {

}

private static ParserResult importFile(String argument) {
private static Optional<ParserResult> importFile(String argument) {
String[] data = argument.split(",");
try {
if ((data.length > 1) && !"*".equals(data[1])) {
Expand All @@ -845,10 +832,10 @@ private static ParserResult importFile(String argument) {
entries = Globals.importFormatReader.importFromFile(data[1],
data[0].replaceAll("~", System.getProperty("user.home")), JabRef.jrf);
}
return new ParserResult(entries);
return Optional.of(new ParserResult(entries));
} catch (IllegalArgumentException ex) {
System.err.println(Localization.lang("Unknown import format") + ": " + data[1]);
return null;
return Optional.empty();
}
} else {
// * means "guess the format":
Expand All @@ -865,7 +852,7 @@ private static ParserResult importFile(String argument) {
if (importResult != null) {
System.out.println(Localization.lang("Format used") + ": " + importResult.format);

return importResult.parserResult;
return Optional.of(importResult.parserResult);
} else {
System.out.println(Localization.lang("Could not find a suitable import format."));
}
Expand All @@ -874,7 +861,7 @@ private static ParserResult importFile(String argument) {
System.err.println(
Localization.lang("Error opening file") + " '" + data[0] + "': " + ex.getLocalizedMessage());
}
return null;
return Optional.empty();
}

/**
Expand All @@ -883,12 +870,10 @@ private static ParserResult importFile(String argument) {
* @param argument See importFile.
* @return ParserResult with setToOpenTab(true)
*/
private static ParserResult importToOpenBase(String argument) {
ParserResult result = JabRef.importFile(argument);
private static Optional<ParserResult> importToOpenBase(String argument) {
Optional<ParserResult> result = JabRef.importFile(argument);

if (result != null) {
result.setToOpenTab(true);
}
result.ifPresent(x -> x.setToOpenTab(true));

return result;
}
Expand Down
7 changes: 4 additions & 3 deletions src/main/java/net/sf/jabref/bibtex/DuplicateCheck.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import java.util.HashMap;
import java.util.HashSet;
import java.util.Optional;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
Expand Down Expand Up @@ -207,13 +208,13 @@ public static double compareEntriesStrictly(BibEntry one, BibEntry two) {
* @param entry The entry of which we are looking for duplicates.
* @return The first duplicate entry found. null if no duplicates are found.
*/
public static BibEntry containsDuplicate(BibDatabase database, BibEntry entry) {
public static Optional<BibEntry> containsDuplicate(BibDatabase database, BibEntry entry) {
for (BibEntry other : database.getEntries()) {
if (DuplicateCheck.isDuplicate(entry, other)) {
return other; // Duplicate found.
return Optional.of(other); // Duplicate found.
}
}
return null; // No duplicate found.
return Optional.empty(); // No duplicate found.
}

/**
Expand Down
24 changes: 12 additions & 12 deletions src/main/java/net/sf/jabref/collab/ChangeScanner.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Optional;
import java.util.Vector;
import java.util.ArrayList;

Expand Down Expand Up @@ -412,10 +413,10 @@ private void scanStrings(BibDatabase inMem1, BibDatabase onTmp, BibDatabase onDi
// We have found a string with a matching name.
if ((tmp.getContent() != null) && !tmp.getContent().equals(disk.getContent())) {
// But they have nonmatching contents, so we've found a change.
BibtexString mem = findString(inMem1, tmp.getName(), usedInMem);
if (mem != null) {
changes.add(
new StringChange(mem, tmp, tmp.getName(), mem.getContent(), disk.getContent()));
Optional<BibtexString> mem = findString(inMem1, tmp.getName(), usedInMem);
if (mem.isPresent()) {
changes.add(new StringChange(mem.get(), tmp, tmp.getName(), mem.get().getContent(),
disk.getContent()));
} else {
changes.add(new StringChange(null, tmp, tmp.getName(), null, disk.getContent()));
}
Expand Down Expand Up @@ -477,10 +478,9 @@ private void scanStrings(BibDatabase inMem1, BibDatabase onTmp, BibDatabase onDi
// Still one or more non-matched strings. So they must have been removed.
for (String nmId : notMatched) {
BibtexString tmp = onTmp.getString(nmId);
BibtexString mem = findString(inMem1, tmp.getName(), usedInMem);
if (mem != null) { // The removed string is not removed from the mem version.
changes.add(new StringRemoveChange(tmp, tmp, mem));
}
// The removed string is not removed from the mem version.
findString(inMem1, tmp.getName(), usedInMem)
.ifPresent(x -> changes.add(new StringRemoveChange(tmp, tmp, x)));
}
}

Expand All @@ -496,18 +496,18 @@ private void scanStrings(BibDatabase inMem1, BibDatabase onTmp, BibDatabase onDi
}
}

private static BibtexString findString(BibDatabase base, String name, HashSet<Object> used) {
private static Optional<BibtexString> findString(BibDatabase base, String name, HashSet<Object> used) {
if (!base.hasStringLabel(name)) {
return null;
return Optional.empty();
}
for (String key : base.getStringKeySet()) {
BibtexString bs = base.getString(key);
if (bs.getName().equals(name) && !used.contains(key)) {
used.add(key);
return bs;
return Optional.of(bs);
}
}
return null;
return Optional.empty();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,10 +301,8 @@ public String getColumnName(int column) {
return Localization.lang("Extension");
case 3:
return Localization.lang("MIME type");
case 4:
default: // Five columns
return Localization.lang("Application");
default:
return null;
}
}

Expand All @@ -329,10 +327,8 @@ public Object getValueAt(int rowIndex, int columnIndex) {
return type.getExtension();
case 3:
return type.getMimeType();
case 4:
default: // Five columns
return type.getOpenWith();
default:
return null;
}
}
}
Expand Down
26 changes: 0 additions & 26 deletions src/main/java/net/sf/jabref/external/SynchronizeFileField.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,6 @@ public void run() {
int progress = 0;
final NamedCompound ce = new NamedCompound(Localization.lang("Autoset %0 field", fieldName));

//final OpenFileFilter off = Util.getFileFilterForField(fieldName);

//ExternalFilePanel extPan = new ExternalFilePanel(fieldName, panel.metaData(), null, null, off);
//TextField editor = new TextField(fieldName, "", false);

Set<BibEntry> changedEntries = new HashSet<>();

// First we try to autoset fields
Expand All @@ -120,30 +115,9 @@ public void run() {
// Start the autosetting process:
Runnable r = Util.autoSetLinks(entries, ce, changedEntries, null, panel.metaData(), null, null);
JabRefExecutorService.INSTANCE.executeAndWait(r);
/*
progress += weightAutoSet;
panel.frame().setProgressBarValue(progress);
Object old = sel[i].getField(fieldName);
FileListTableModel tableModel = new FileListTableModel();
if (old != null)
tableModel.setContent((String)old);
Thread t = FileListEditor.autoSetLinks(sel[i], tableModel, null, null);
if (!tableModel.getStringRepresentation().equals(old)) {
String toSet = tableModel.getStringRepresentation();
if (toSet.length() == 0)
toSet = null;
ce.addEdit(new UndoableFieldChange(sel[i], fieldName, old, toSet));
sel[i].setField(fieldName, toSet);
entriesChanged++;
}
} */

}
progress += sel.length * weightAutoSet;
panel.frame().setProgressBarValue(progress);
//System.out.println("Done setting");
// The following loop checks all external links that are already set.
if (checkExisting) {
boolean removeAllBroken = false;
Expand Down
Loading

0 comments on commit 85904c7

Please # to comment.