Skip to content

Commit

Permalink
Introduced Optional return values (#1573)
Browse files Browse the repository at this point in the history
* Introduced Optional return values
  • Loading branch information
oscargus authored and simonharrer committed Jul 12, 2016
1 parent eddf636 commit aa42800
Show file tree
Hide file tree
Showing 13 changed files with 92 additions and 100 deletions.
34 changes: 12 additions & 22 deletions src/main/java/net/sf/jabref/JabRefPreferences.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.prefs.BackingStoreException;
import java.util.prefs.InvalidPreferencesFormatException;
Expand Down Expand Up @@ -1013,10 +1014,10 @@ public List<String> getStringList(String key) {

StringReader rd = new StringReader(names);
List<String> res = new ArrayList<>();
String rs;
Optional<String> rs;
try {
while ((rs = getNextUnit(rd)) != null) {
res.add(rs);
while ((rs = getNextUnit(rd)).isPresent()) {
res.add(rs.get());
}
} catch (IOException ignored) {
// Ignored
Expand Down Expand Up @@ -1205,7 +1206,7 @@ private Object getObject(String key) {
}


private static String getNextUnit(Reader data) throws IOException {
private static Optional<String> getNextUnit(Reader data) throws IOException {
// character last read
// -1 if end of stream
// initialization necessary, because of Java compiler
Expand Down Expand Up @@ -1240,12 +1241,12 @@ private static String getNextUnit(Reader data) throws IOException {
}
}
if (res.length() > 0) {
return res.toString();
return Optional.of(res.toString());
} else if (c == -1) {
// end of stream
return null;
return Optional.empty();
} else {
return "";
return Optional.of("");
}
}

Expand All @@ -1265,22 +1266,22 @@ public void storeCustomEntryType(CustomEntryType tp, int number) {
/**
* Retrieves all information about the entry type in preferences, with the tag given by number.
*/
public CustomEntryType getCustomEntryType(int number) {
public Optional<CustomEntryType> getCustomEntryType(int number) {
String nr = String.valueOf(number);
String name = get(JabRefPreferences.CUSTOM_TYPE_NAME + nr);
if (name == null) {
return null;
return Optional.empty();
}
List<String> req = getStringList(JabRefPreferences.CUSTOM_TYPE_REQ + nr);
List<String> opt = getStringList(JabRefPreferences.CUSTOM_TYPE_OPT + nr);
List<String> priOpt = getStringList(JabRefPreferences.CUSTOM_TYPE_PRIOPT + nr);
if (priOpt.isEmpty()) {
return new CustomEntryType(EntryUtil.capitalizeFirst(name), req, opt);
return Optional.of(new CustomEntryType(EntryUtil.capitalizeFirst(name), req, opt));
}
List<String> secondary = new ArrayList<>(opt);
secondary.removeAll(priOpt);

return new CustomEntryType(EntryUtil.capitalizeFirst(name), req, priOpt, secondary);
return Optional.of(new CustomEntryType(EntryUtil.capitalizeFirst(name), req, priOpt, secondary));

}

Expand All @@ -1297,17 +1298,6 @@ public void purgeCustomEntryTypes(int number) {
purgeSeries(JabRefPreferences.CUSTOM_TYPE_PRIOPT, number);
}

public void purgeCustomEntryTypes() {
int number = 0;
if(getCustomEntryType(number) != null) {
number++;
}

for(int i = 0; i < number; i++) {
purgeCustomEntryTypes(i);
}
}

/**
* Removes all entries keyed by prefix+number, where number is equal to or higher than the given number.
*
Expand Down
12 changes: 6 additions & 6 deletions src/main/java/net/sf/jabref/MetaData.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ private MetaData(Map<String, String> inData) throws ParseException {
List<String> orderedData = new ArrayList<>();
// We must allow for ; and \ in escape sequences.
try {
String unit;
while ((unit = getNextUnit(data)) != null) {
orderedData.add(unit);
Optional<String> unit;
while ((unit = getNextUnit(data)).isPresent()) {
orderedData.add(unit.get());
}
} catch (IOException ex) {
LOGGER.error("Weird error while parsing meta data.", ex);
Expand Down Expand Up @@ -200,7 +200,7 @@ public void setGroups(GroupTreeNode root) {
/**
* Reads the next unit. Units are delimited by ';'.
*/
private static String getNextUnit(Reader reader) throws IOException {
private static Optional<String> getNextUnit(Reader reader) throws IOException {
int c;
boolean escape = false;
StringBuilder res = new StringBuilder();
Expand All @@ -217,9 +217,9 @@ private static String getNextUnit(Reader reader) throws IOException {
}
}
if (res.length() > 0) {
return res.toString();
return Optional.of(res.toString());
}
return null;
return Optional.empty();
}

public DBStrings getDBStrings() {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/net/sf/jabref/bst/BibtexCaseChanger.java
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ private int convertCharIfBraceLevelIsZero(char[] c, int start, StringBuilder sb,

/**
* Determine whether there starts a special char at pos (e.g., oe, AE). Return it as string.
* If nothing found, return null
* If nothing found, return Optional.empty()
*
* Also used by BibtexPurify
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.OS;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.specialfields.SpecialField;
import net.sf.jabref.specialfields.SpecialFieldValue;
import net.sf.jabref.specialfields.SpecialFieldsUtils;

Expand Down Expand Up @@ -351,19 +350,20 @@ public void mouseClicked(MouseEvent e) {
* @param columnName the name of the specialfield column
*/
private void handleSpecialFieldLeftClick(MouseEvent e, String columnName) {
SpecialField field = SpecialFieldsUtils.getSpecialFieldInstanceFromFieldName(columnName);
if ((e.getClickCount() == 1) && (field != null)) {
// special field found
if (field.isSingleValueField()) {
// directly execute toggle action instead of showing a menu with one action
field.getValues().get(0).getAction(panel.frame()).action();
} else {
JPopupMenu menu = new JPopupMenu();
for (SpecialFieldValue val : field.getValues()) {
menu.add(val.getMenuAction(panel.frame()));
if ((e.getClickCount() == 1)) {
SpecialFieldsUtils.getSpecialFieldInstanceFromFieldName(columnName).ifPresent(field -> {
// special field found
if (field.isSingleValueField()) {
// directly execute toggle action instead of showing a menu with one action
field.getValues().get(0).getAction(panel.frame()).action();
} else {
JPopupMenu menu = new JPopupMenu();
for (SpecialFieldValue val : field.getValues()) {
menu.add(val.getMenuAction(panel.frame()));
}
menu.show(table, e.getX(), e.getY());
}
menu.show(table, e.getX(), e.getY());
}
});
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import net.sf.jabref.MetaData;
import net.sf.jabref.importer.ParserResult;
Expand Down Expand Up @@ -280,12 +281,12 @@ private void parseJabRefComment(Map<String, String> meta) throws IOException {
.equals(CustomEntryType.ENTRYTYPE_FLAG)) {
// A custom entry type can also be stored in a
// "@comment"
CustomEntryType typ = CustomEntryType.parse(comment);
if(typ == null) {
Optional<CustomEntryType> typ = CustomEntryType.parse(comment);
if (typ.isPresent()) {
entryTypes.put(typ.get().getName(), typ.get());
} else {
parserResult.addWarning(Localization.lang("Ill-formed entrytype comment in bib file") + ": " +
comment);
} else {
entryTypes.put(typ.getName(), typ);
}

// custom entry types are always re-written by JabRef and not stored in the file
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.model.EntryTypes;
Expand All @@ -19,10 +20,10 @@ public class CustomEntryTypesManager {
*/
public static void loadCustomEntryTypes(JabRefPreferences prefs) {
int number = 0;
CustomEntryType type;
while ((type = prefs.getCustomEntryType(number)) != null) {
EntryTypes.addOrModifyCustomEntryType(type);
ALL.add(type);
Optional<CustomEntryType> type;
while ((type = prefs.getCustomEntryType(number)).isPresent()) {
EntryTypes.addOrModifyCustomEntryType(type.get());
ALL.add(type.get());
number++;
}
}
Expand Down
11 changes: 6 additions & 5 deletions src/main/java/net/sf/jabref/logic/fulltext/MimeTypeDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Optional;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
Expand All @@ -11,19 +12,19 @@ public class MimeTypeDetector {
private static final Log LOGGER = LogFactory.getLog(MimeTypeDetector.class);

public static boolean isPdfContentType(String url) {
String contentType = getMimeType(url);
Optional<String> contentType = getMimeType(url);

return contentType != null && contentType.toLowerCase().startsWith("application/pdf");
return contentType.isPresent() && contentType.get().toLowerCase().startsWith("application/pdf");
}

private static String getMimeType(String url) {
private static Optional<String> getMimeType(String url) {
try {
URLConnection connection = new URL(url).openConnection();

return connection.getContentType();
return Optional.ofNullable(connection.getContentType());
} catch (IOException e) {
LOGGER.debug("Error getting MIME type of URL", e);
return null;
return Optional.empty();
}
}
}
6 changes: 2 additions & 4 deletions src/main/java/net/sf/jabref/logic/xmp/XMPUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -695,10 +695,8 @@ private static void writeToDCSchema(XMPSchemaDublinCore dcSchema,
*
* Bibtex-Fields used: year, month
*/
String publicationDate = entry.getPublicationDate();
if (publicationDate != null) {
dcSchema.addSequenceValue("dc:date", publicationDate);
}
entry.getPublicationDate()
.ifPresent(publicationDate -> dcSchema.addSequenceValue("dc:date", publicationDate));
continue;
}
/**
Expand Down
26 changes: 12 additions & 14 deletions src/main/java/net/sf/jabref/model/entry/AuthorListParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;

public class AuthorListParser {
Expand All @@ -26,7 +27,7 @@ public class AuthorListParser {
/** true if upper-case token, false if lower-case */
private boolean tokenCase;


// Constant HashSet containing names of TeX special characters
private static final Set<String> TEX_NAMES = new HashSet<>();

Expand Down Expand Up @@ -84,21 +85,18 @@ public AuthorList parse(String listOfNames) {
// Parse author by author
List<Author> authors = new ArrayList<>(5); // 5 seems to be reasonable initial size
while (tokenStart < original.length()) {
Author author = getAuthor();
if (author != null) {
authors.add(author);
}
getAuthor().ifPresent(authors::add);
}
return new AuthorList(authors);
}

/**
* Parses one author name and returns preformatted information.
*
* @return Preformatted author name; <CODE>null</CODE> if author name is
* @return Preformatted author name; <CODE>Optional.empty()</CODE> if author name is
* empty.
*/
private Author getAuthor() {
private Optional<Author> getAuthor() {

List<Object> tokens = new ArrayList<>(); // initialization
int vonStart = -1;
Expand Down Expand Up @@ -135,8 +133,8 @@ private Author getAuthor() {
}
if (vonStart < 0) {
if (!tokenCase) {
int previousTermToken = tokens.size() - TOKEN_GROUP_LENGTH - TOKEN_GROUP_LENGTH + OFFSET_TOKEN_TERM;
if(previousTermToken >= 0 && tokens.get(previousTermToken).equals('-')) {
int previousTermToken = (tokens.size() - TOKEN_GROUP_LENGTH - TOKEN_GROUP_LENGTH) + OFFSET_TOKEN_TERM;
if((previousTermToken >= 0) && tokens.get(previousTermToken).equals('-')) {
// We are in a first name which contained a hyphen
break;
}
Expand All @@ -156,7 +154,7 @@ private Author getAuthor() {
// Second step: split name into parts (here: calculate indices
// of parts in 'tokens' Vector)
if (tokens.isEmpty()) {
return null; // no author information
return Optional.empty(); // no author information
}

// the following negatives indicate absence of the corresponding part
Expand Down Expand Up @@ -251,13 +249,13 @@ private Author getAuthor() {
false);
String jrPart = jrPartStart < 0 ? null : concatTokens(tokens, jrPartStart, jrPartEnd, OFFSET_TOKEN, false);

if(firstPart != null && lastPart != null && lastPart.equals(lastPart.toUpperCase()) && lastPart.length() < 5) {
if((firstPart != null) && (lastPart != null) && lastPart.equals(lastPart.toUpperCase()) && (lastPart.length() < 5)) {
// The last part is a small string in complete upper case, so interpret it as initial of the first name
// This is the case for example in "Smith SH" which we think of as lastname=Smith and firstname=SH
// The length < 5 constraint should allow for "Smith S.H." as input
return new Author(lastPart, lastPart, vonPart, firstPart, jrPart);
return Optional.of(new Author(lastPart, lastPart, vonPart, firstPart, jrPart));
} else {
return new Author(firstPart, firstAbbr, vonPart, lastPart, jrPart);
return Optional.of(new Author(firstPart, firstAbbr, vonPart, lastPart, jrPart));
}
}

Expand Down Expand Up @@ -356,7 +354,7 @@ private int getToken() {
if (c == '{') {
bracesLevel++;
}
if (firstLetterIsFound && (tokenAbbr < 0) && (bracesLevel == 0 || c == '{')) {
if (firstLetterIsFound && (tokenAbbr < 0) && ((bracesLevel == 0) || (c == '{'))) {
tokenAbbr = tokenEnd;
}
if ((c == '}') && (bracesLevel > 0)) {
Expand Down
13 changes: 7 additions & 6 deletions src/main/java/net/sf/jabref/model/entry/BibEntry.java
Original file line number Diff line number Diff line change
Expand Up @@ -497,17 +497,18 @@ public String getAuthorTitleYear(int maxCharacters) {
*
* @return will return the publication date of the entry or null if no year was found.
*/
public String getPublicationDate() {
public Optional<String> getPublicationDate() {
if (!hasField("year")) {
return null;
return Optional.empty();
}

String year = getField("year");
Optional<String> year = getFieldOptional("year");

if (hasField("month")) {
MonthUtil.Month month = MonthUtil.getMonth(getField("month"));
Optional<String> monthString = getFieldOptional("month");
if (monthString.isPresent()) {
MonthUtil.Month month = MonthUtil.getMonth(monthString.get());
if (month.isValid()) {
return year + "-" + month.twoDigitNumber;
return Optional.of(year.orElse("") + "-" + month.twoDigitNumber);
}
}
return year;
Expand Down
Loading

0 comments on commit aa42800

Please sign in to comment.