BibTeX exporter finished.

git-svn-id: https://svn.libreccm.org/ccm/trunk@735 8810af33-2d31-482b-a856-94f89814c4df
master
jensp 2011-02-05 19:03:57 +00:00
parent b941214736
commit fc02385f72
8 changed files with 354 additions and 64 deletions

View File

@ -48,7 +48,7 @@ public class PublicationPropertyForm
private static final Logger s_log = Logger.getLogger( private static final Logger s_log = Logger.getLogger(
PublicationPropertyForm.class); PublicationPropertyForm.class);
private PublicationPropertiesStep m_step; private PublicationPropertiesStep m_step;
public static final String ID = "Publication_edit"; public static final String ID = "Publication_edit";
public PublicationPropertyForm(ItemSelectionModel itemModel) { public PublicationPropertyForm(ItemSelectionModel itemModel) {
@ -122,9 +122,7 @@ public class PublicationPropertyForm
publication.setAbstract((String) data.get(Publication.ABSTRACT)); publication.setAbstract((String) data.get(Publication.ABSTRACT));
publication.setMisc((String) data.get(Publication.MISC)); publication.setMisc((String) data.get(Publication.MISC));
publication.save(); publication.save();
init(fse);
} }
} }
@ -140,5 +138,5 @@ public class PublicationPropertyForm
protected String getTitleLabel() { protected String getTitleLabel() {
return (String) PublicationGlobalizationUtil.globalize( return (String) PublicationGlobalizationUtil.globalize(
"publications.ui.publication.title").localize(); "publications.ui.publication.title").localize();
} }
} }

View File

@ -36,7 +36,6 @@ import com.arsdigita.cms.contenttypes.PublicationWithPublisher;
import com.arsdigita.cms.contenttypes.Publisher; import com.arsdigita.cms.contenttypes.Publisher;
import com.arsdigita.cms.ui.ItemSearchWidget; import com.arsdigita.cms.ui.ItemSearchWidget;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.lucene.analysis.LengthFilter;
/** /**
* *
@ -124,9 +123,10 @@ public class PublicationWithPublisherPropertyForm
@Override @Override
public void init(FormSectionEvent fse) throws FormProcessException { public void init(FormSectionEvent fse) throws FormProcessException {
FormData data = fse.getFormData();
super.init(fse); super.init(fse);
FormData data = fse.getFormData();
PublicationWithPublisher publication = PublicationWithPublisher publication =
(PublicationWithPublisher) super. (PublicationWithPublisher) super.
initBasicWidgets(fse); initBasicWidgets(fse);
@ -144,9 +144,9 @@ public class PublicationWithPublisherPropertyForm
@Override @Override
public void process(FormSectionEvent fse) throws FormProcessException { public void process(FormSectionEvent fse) throws FormProcessException {
FormData data = fse.getFormData();
super.process(fse); super.process(fse);
FormData data = fse.getFormData();
PublicationWithPublisher publication = PublicationWithPublisher publication =
(PublicationWithPublisher) super. (PublicationWithPublisher) super.
processBasicWidgets(fse); processBasicWidgets(fse);

View File

@ -1,8 +1,23 @@
package com.arsdigita.cms.scipublications; package com.arsdigita.cms.scipublications;
import com.arsdigita.categorization.Categorization;
import com.arsdigita.categorization.CategorizedCollection;
import com.arsdigita.categorization.Category;
import com.arsdigita.cms.ContentBundle;
import com.arsdigita.cms.contenttypes.Publication;
import com.arsdigita.cms.scipublications.exporter.SciPublicationsExporter;
import com.arsdigita.cms.scipublications.exporter.SciPublicationsExporters;
import com.arsdigita.domain.DataObjectNotFoundException;
import com.arsdigita.domain.DomainObjectFactory;
import com.arsdigita.kernel.ACSObject;
import com.arsdigita.web.Application; import com.arsdigita.web.Application;
import com.arsdigita.web.BaseApplicationServlet; import com.arsdigita.web.BaseApplicationServlet;
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -53,23 +68,266 @@ public class SciPublicationsServlet extends BaseApplicationServlet {
logger.debug("pathInfo is null, responding with default..."); logger.debug("pathInfo is null, responding with default...");
/*response.setContentType("application/text"); /*response.setContentType("application/text");
response.setHeader("Content-Disposition", response.setHeader("Content-Disposition",
"attachment; filename=ccm-publication-exporter.txt"); "attachment; filename=ccm-publication-exporter.txt");
response.getWriter().append("This is the sci-publication-exporter");*/ response.getWriter().append("This is the sci-publication-exporter");*/
response.setContentType("text/plain"); response.setContentType("text/plain");
response.getWriter().append("Please choose an application."); response.getWriter().append("Please choose an application.");
//ToDo: Show a menu? //ToDo: Show a menu?
} else if("export".equals(path)) { } else if ("export".equals(path)) {
logger.debug("Export a publication"); logger.debug("Export a publication");
response.setContentType("text/plain"); Map<String, String[]> parameters;
response.getWriter().append("Calling exporter..."); String format;
parameters = request.getParameterMap();
if (parameters.containsKey("format")) {
if (parameters.get("format").length == 1) {
format = parameters.get("format")[0];
} else {
logger.warn("Query parameter 'format' contains no value"
+ "or more than one value. It is expected that "
+ "'format' contains excactly one value. Responding"
+ "with BAD_REQUEST status.");
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Query parameter 'format' contains no value or more"
+ "than one value. It is expected that "
+ "'format' contains excactly one value.");
return;
}
} else {
logger.warn("Missing query parameter 'format'. "
+ "Responsding with BAD_REQUEST status code.");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
if (parameters.containsKey("category")) {
Publication publication;
SciPublicationsExporter exporter;
String categoryIdStr;
BigDecimal categoryId;
Category category;
CategorizedCollection objects;
logger.debug("Found parameter 'category'...");
if (parameters.get("category").length != 1) {
logger.error("The parameter 'category' is expected to"
+ "have exactly one parameter.");
response.sendError(response.SC_BAD_REQUEST,
"The parameter 'category' is expected to"
+ "have exactly one pareameter.");
return;
}
categoryIdStr = parameters.get("category")[0];
try {
categoryId = new BigDecimal(categoryIdStr);
} catch (NumberFormatException ex) {
logger.error("The category id could not be converted to"
+ "an BigDecimal value.",
ex);
response.sendError(response.SC_BAD_REQUEST,
"The category id could not be converted to"
+ "an BigDecimal value.");
return;
}
try {
category = new Category(categoryId);
} catch (DataObjectNotFoundException ex) {
logger.error(String.format("No category with the provided "
+ "id '%s' found.",
categoryIdStr),
ex);
response.sendError(response.SC_BAD_REQUEST,
String.format("No category with the provided "
+ "id '%s' found.",
categoryIdStr));
return;
}
logger.debug(String.format("Category: %s", category.getName()));
exporter = SciPublicationsExporters.getInstance().
getExporterForFormat(
format);
if (exporter == null) {
logger.warn(String.format(
"The requested export format '%s' is not supported yet.",
format));
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
String.format(
"The requested export format '%s' is not supported yet.",
format));
return;
}
objects = category.getObjects(ACSObject.BASE_DATA_OBJECT_TYPE);
logger.debug(String.format("Category contains %d objects.",
objects.size()));
ContentBundle bundle;
ACSObject object;
while (objects.next()) {
bundle = (ContentBundle) objects.getACSObject();
object = bundle.getInstance(bundle.getDefaultLanguage());
if (object instanceof Publication) {
publication = (Publication) object;
} else {
logger.debug("Object is not a publication, ignoring it.");
continue;
}
if (!publication.isLiveVersion()) {
logger.debug("Object is no a published version, "
+ "ignoring it.");
continue;
}
response.getWriter().append(exporter.exportPublication(
publication));
response.getWriter().append('\n');
}
response.setContentType(exporter.getSupportedFormat().
getMimeType().getBaseType());
response.setHeader("Content-Disposition",
String.format("attachment; filename=%s.bib",
category.getName()));
return;
} else if (parameters.containsKey("publication")) {
String[] publications;
List<BigDecimal> publicationIds;
publications = parameters.get("publication");
if (publications.length < 1) {
logger.warn("Parameter 'publications' has no value(s). "
+ "Responding with status BAD_REQUEST.");
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Parameter 'publication' has no "
+ "value(s).");
return;
}
BigDecimal publicationId;
publicationIds = new ArrayList<BigDecimal>();
for (int i = 0; i < publications.length; i++) {
try {
publicationId = new BigDecimal(publications[i]);
} catch (NumberFormatException ex) {
logger.warn(String.format(
"Can't convert publication id "
+ "'%s' on index %d to a BigDecimal.",
publications[i], i));
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
String.format(
"Can't convert the publication id"
+ "on index %d to a number.", i));
return;
}
publicationIds.add(publicationId);
}
exportPublications(format, publicationIds, response);
} else {
logger.warn("Export action needs either a publication id or a "
+ "term id. Neither was found in the query parameters."
+ "Responding with BAD_REQUEST status.");
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"The export action needs either a publication id or "
+ "a term id. Neither was found in the query parameters.");
return;
}
//ToDo: Call the exporter here.
} else { } else {
logger.debug("Unknown pathinfo, responding with 404..."); logger.warn(String.format("Unknown pathinfo '%s', "
response.setStatus(HttpServletResponse.SC_NOT_FOUND); + "responding with 404...",
path));
response.sendError(HttpServletResponse.SC_NOT_FOUND,
String.format("The path '%s' is not known.", path));
}
}
private void exportPublications(final String format,
final List<BigDecimal> publicationIds,
final HttpServletResponse response)
throws IOException {
SciPublicationsExporter exporter;
exporter = SciPublicationsExporters.getInstance().getExporterForFormat(
format);
if (exporter == null) {
logger.warn(String.format(
"The requested export format '%s' is not supported yet.",
format));
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
String.format(
"The requested export format '%s' is not supported yet.",
format));
return;
}
response.setContentType(exporter.getSupportedFormat().getMimeType().
getBaseType());
Publication publication = null;
String publicationName = "publication";
for (BigDecimal publicationId : publicationIds) {
try {
publication = new Publication(publicationId);
logger.debug(String.format("OID of publication: %s",
publication.getOID()));
publication = (Publication) DomainObjectFactory.newInstance(publication.
getOID());
} catch (DataObjectNotFoundException ex) {
logger.warn(String.format("No publication found for id '%s'.",
publicationId.toPlainString()), ex);
response.sendError(HttpServletResponse.SC_NOT_FOUND,
String.format(
"No publication found for id '%s'.",
publicationId.toPlainString()));
}
logger.debug(String.format("Publication is of type: %s",
publication.getClass().getName()));
response.getWriter().append(exporter.exportPublication(publication));
response.getWriter().append('\n');
publicationName = publication.getName();
}
if (publicationIds.size() == 1) {
response.setHeader("Content-Disposition",
String.format("attachment; filename=%s.bib",
publicationName));
} else {
response.setHeader("Content-Disposition",
"attachment; filename=publications.bib");
} }
} }
} }

View File

@ -5,6 +5,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import org.apache.log4j.Logger;
/** /**
* *
@ -12,6 +13,8 @@ import java.util.ServiceLoader;
*/ */
public final class SciPublicationsExporters { public final class SciPublicationsExporters {
private static final Logger logger = Logger.getLogger(
SciPublicationsExporters.class);
private Map<String, SciPublicationsExporter> exporters = private Map<String, SciPublicationsExporter> exporters =
new HashMap<String, SciPublicationsExporter>(); new HashMap<String, SciPublicationsExporter>();
@ -22,16 +25,24 @@ public final class SciPublicationsExporters {
} }
private SciPublicationsExporters() { private SciPublicationsExporters() {
ServiceLoader<SciPublicationsExporter> exporterServices ; logger.debug("Creating SciPublicationsExporter instance...");
ServiceLoader<SciPublicationsExporter> exporterServices;
logger.debug("Loading all available implementations of the "
+ "SciPublicationsExporter interface...");
exporterServices = ServiceLoader.load(SciPublicationsExporter.class); exporterServices = ServiceLoader.load(SciPublicationsExporter.class);
for(SciPublicationsExporter exporter : exporterServices) { for (SciPublicationsExporter exporter : exporterServices) {
exporters.put(exporter.getSupportedFormat().getName(), exporter); logger.debug(String.format("Found exporter for format '%s'...",
exporter.getSupportedFormat().getName().
toLowerCase()));
exporters.put(exporter.getSupportedFormat().getName().toLowerCase(),
exporter);
} }
logger.debug(String.format("Found %d exporters.", exporters.size()));
} }
public SciPublicationsExporters getInstance() { public static SciPublicationsExporters getInstance() {
return Instance.INSTANCE; return Instance.INSTANCE;
} }
@ -44,7 +55,8 @@ public final class SciPublicationsExporters {
supportedFormats = new ArrayList<PublicationFormat>(); supportedFormats = new ArrayList<PublicationFormat>();
for(Map.Entry<String, SciPublicationsExporter> entry : exporters.entrySet()) { for (Map.Entry<String, SciPublicationsExporter> entry : exporters.
entrySet()) {
supportedFormats.add(entry.getValue().getSupportedFormat()); supportedFormats.add(entry.getValue().getSupportedFormat());
} }

View File

@ -1,23 +1,9 @@
package com.arsdigita.cms.scipublications.exporter.bibtex; package com.arsdigita.cms.scipublications.exporter.bibtex;
import com.arsdigita.cms.scipublications.exporter.bibtex.builders.BibTeXBuilder;
import com.arsdigita.cms.scipublications.exporter.bibtex.builders.BibTeXBuilders;
import com.arsdigita.cms.contenttypes.ArticleInCollectedVolume;
import com.arsdigita.cms.contenttypes.ArticleInJournal;
import com.arsdigita.cms.contenttypes.CollectedVolume;
import com.arsdigita.cms.contenttypes.Expertise;
import com.arsdigita.cms.contenttypes.GreyLiterature;
import com.arsdigita.cms.contenttypes.InProceedings;
import com.arsdigita.cms.contenttypes.InternetArticle;
import com.arsdigita.cms.contenttypes.Journal;
import com.arsdigita.cms.contenttypes.Monograph;
import com.arsdigita.cms.contenttypes.Proceedings;
import com.arsdigita.cms.contenttypes.Publication; import com.arsdigita.cms.contenttypes.Publication;
import com.arsdigita.cms.contenttypes.PublicationWithPublisher;
import com.arsdigita.cms.contenttypes.Review;
import com.arsdigita.cms.contenttypes.WorkingPaper;
import com.arsdigita.cms.scipublications.exporter.PublicationFormat; import com.arsdigita.cms.scipublications.exporter.PublicationFormat;
import com.arsdigita.cms.scipublications.exporter.SciPublicationsExporter; import com.arsdigita.cms.scipublications.exporter.SciPublicationsExporter;
import com.arsdigita.cms.scipublications.exporter.bibtex.converters.BibTeXConverters;
import javax.activation.MimeType; import javax.activation.MimeType;
import javax.activation.MimeTypeParseException; import javax.activation.MimeTypeParseException;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
@ -45,11 +31,7 @@ public class BibTeXExporter implements SciPublicationsExporter {
} }
} }
public String exportPublication(final Publication publication) { public String exportPublication(final Publication publication) {
return BibTeXConverters.getInstance().convert(publication);
throw new UnsupportedOperationException("Not implemented yet.");
} }
} }

View File

@ -52,9 +52,10 @@ public abstract class AbstractBibTeXBuilder implements BibTeXBuilder {
if (checkMandatoryFields()) { if (checkMandatoryFields()) {
type = getBibTeXType(); type = getBibTeXType();
} else { } else {
logger.warn(String.format("Missing mandandory field" logger.warn(String.format(
+ "for BibTeX type '%s'. Using type 'type'.", "Missing mandandory field "
getBibTeXType())); + "for BibTeX type '%s'. Using type 'misc'.",
getBibTeXType()));
type = "misc"; type = "misc";
} }
@ -64,7 +65,7 @@ public abstract class AbstractBibTeXBuilder implements BibTeXBuilder {
builder.append(type); builder.append(type);
builder.append('{'); builder.append('{');
builder.append(generateBibTeXId()); builder.append(generateBibTeXId());
builder.append(",\n"); //builder.append(",\n");
if (authors.size() > 0) { if (authors.size() > 0) {
addField("author", generatePersonFieldValue(authors), builder); addField("author", generatePersonFieldValue(authors), builder);
@ -80,11 +81,11 @@ public abstract class AbstractBibTeXBuilder implements BibTeXBuilder {
builder); builder);
} }
builder.append('}');
return builder.toString(); return builder.toString();
} }
protected String generateBibTeXId() { protected String generateBibTeXId() {
StringBuilder builder; StringBuilder builder;
@ -102,7 +103,7 @@ public abstract class AbstractBibTeXBuilder implements BibTeXBuilder {
return builder.toString(); return builder.toString();
} }
protected abstract List<BibTeXField> getMandatoryFields(); protected abstract List<BibTeXField> getMandatoryFields();
protected abstract boolean isFieldSupported(final BibTeXField name); protected abstract boolean isFieldSupported(final BibTeXField name);
@ -110,11 +111,15 @@ public abstract class AbstractBibTeXBuilder implements BibTeXBuilder {
private boolean checkMandatoryFields() { private boolean checkMandatoryFields() {
if (getMandatoryFields().contains(BibTeXField.AUTHOR) if (getMandatoryFields().contains(BibTeXField.AUTHOR)
&& authors.isEmpty()) { && authors.isEmpty()) {
logger.warn("Field authors is mandatory, but publications has "
+ "not authors.");
return false; return false;
} }
if (getMandatoryFields().contains(BibTeXField.EDITOR) if (getMandatoryFields().contains(BibTeXField.EDITOR)
&& editors.isEmpty()) { && editors.isEmpty()) {
logger.warn("Field editors is mandatory, but publications has "
+ "no editors.");
return false; return false;
} }
@ -122,6 +127,10 @@ public abstract class AbstractBibTeXBuilder implements BibTeXBuilder {
if (!BibTeXField.AUTHOR.equals(field) if (!BibTeXField.AUTHOR.equals(field)
&& !BibTeXField.EDITOR.equals(field) && !BibTeXField.EDITOR.equals(field)
&& !fields.containsKey(field)) { && !fields.containsKey(field)) {
logger.warn(String.format(
"Field '%s' is mandandory for the "
+ "selected BibTeX type, but is not set.",
field.name().toLowerCase()));
return false; return false;
} }
} }
@ -152,10 +161,11 @@ public abstract class AbstractBibTeXBuilder implements BibTeXBuilder {
private void addField(final String name, private void addField(final String name,
final String value, final String value,
final StringBuilder builder) { final StringBuilder builder) {
builder.append(",\n");
builder.append(' '); builder.append(' ');
builder.append(name); builder.append(name);
builder.append(" = \""); builder.append(" = \"");
builder.append(value); builder.append(value);
builder.append("\",\n"); builder.append("\"");
} }
} }

View File

@ -50,7 +50,7 @@ public abstract class AbstractBibTeXConverter implements BibTeXConverter {
throws UnsupportedFieldException { throws UnsupportedFieldException {
if (publication.getPublisher() != null) { if (publication.getPublisher() != null) {
if ((publication.getPublisher().getPlace() == null) if ((publication.getPublisher().getPlace() == null)
&& publication.getPublisher().getPlace().isEmpty()) { || publication.getPublisher().getPlace().isEmpty()) {
getBibTeXBuilder().setField(BibTeXField.PUBLISHER, getBibTeXBuilder().setField(BibTeXField.PUBLISHER,
publication.getPublisher().getTitle()); publication.getPublisher().getTitle());
} else { } else {

View File

@ -4,6 +4,9 @@ import com.arsdigita.cms.contenttypes.Publication;
import com.arsdigita.cms.contenttypes.PublicationWithPublisher; import com.arsdigita.cms.contenttypes.PublicationWithPublisher;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.ServiceLoader;
import java.util.logging.Level;
import org.apache.log4j.Logger;
/** /**
* *
@ -11,10 +14,23 @@ import java.util.Map;
*/ */
public class BibTeXConverters { public class BibTeXConverters {
private static final Logger logger = Logger.getLogger(BibTeXConverters.class);
private Map<String, BibTeXConverter> converters = private Map<String, BibTeXConverter> converters =
new HashMap<String, BibTeXConverter>(); new HashMap<String, BibTeXConverter>();
private BibTeXConverters() { private BibTeXConverters() {
logger.debug("Loading BibTeX converters...");
ServiceLoader<BibTeXConverter> converterServices;
converterServices = ServiceLoader.load(BibTeXConverter.class);
for(BibTeXConverter converter : converterServices) {
logger.debug(String.format("Found converter for CCM type '%s'...",
converter.getCcmType()));
converters.put(converter.getCcmType(), converter);
}
logger.debug(String.format("Found %d converters.", converters.size()));
} }
private static class Instance { private static class Instance {
@ -27,20 +43,34 @@ public class BibTeXConverters {
} }
public String convert(final Publication publication) { public String convert(final Publication publication) {
BibTeXConverter converter; try {
BibTeXConverter converter;
converter = converters.get(publication.getClass().getName()); logger.debug(String.format("Trying to find converter for type '%s'.",
publication.getClass().getName()));
if (converter == null) { converter = converters.get(publication.getClass().getName());
if (publication instanceof PublicationWithPublisher) { if (converter == null) {
converter = converters.get(PublicationWithPublisher.class. logger.debug("No converter found...");
getName()); if (publication instanceof PublicationWithPublisher) {
} else { logger.debug("Publication is a PublicationWithPublisher, using" +
converter = converters.get(Publication.class.getName()); "converter for this type.");
converter =
converters.get(PublicationWithPublisher.class.getName());
} else {
logger.debug("Publication is a Publication, using" +
"converter for this type.");
converter =
converters.get(Publication.class.getName());
}
} }
} converter = converter.getClass().newInstance();
return converter.convert(publication);
return converter.convert(publication); } catch (InstantiationException ex) {
logger.warn("Failed to instaniate BibTeX converter.", ex);
return null;
} catch (IllegalAccessException ex) {
logger.warn("Failed to instaniate BibTeX converter.", ex);
return null;
}
} }
} }