Skip to content

Commit

Permalink
Fix #46
Browse files Browse the repository at this point in the history
Language optional in conversion
  • Loading branch information
tfrancart committed Jan 5, 2021
1 parent 75ed9aa commit a7a87d9
Show file tree
Hide file tree
Showing 5 changed files with 204 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package fr.sparna.rdf.skosplay;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFWriterRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import fr.sparna.rdf.skosplay.log.LogEntry;
import fr.sparna.rdf.xls2rdf.ModelWriterFactory;
import fr.sparna.rdf.xls2rdf.ModelWriterIfc;
import fr.sparna.rdf.xls2rdf.SkosPostProcessor;
import fr.sparna.rdf.xls2rdf.SkosXlPostProcessor;
import fr.sparna.rdf.xls2rdf.Xls2RdfConverter;
import fr.sparna.rdf.xls2rdf.Xls2RdfException;
import fr.sparna.rdf.xls2rdf.Xls2RdfPostProcessorIfc;




/**
*
* @author Thomas Francart
*
*/
@Controller
@RequestMapping(value = "/api")
public class SkosPlayConvertApiController {

private Logger log = LoggerFactory.getLogger(this.getClass().getName());

@Autowired
protected ServletContext servletContext;

@RequestMapping(value = "/convert",method = RequestMethod.GET)
public ModelAndView convertRDF(
@RequestParam(value="input", required=true) String input,
// the request
HttpServletRequest request,
// the response
HttpServletResponse response
) throws Exception {

final SessionData sessionData = SessionData.get(request.getSession());

String format = "text/turtle";
String language = "fr";
boolean useskosxl = false;
boolean useZip = false;
boolean useGraph = false;
boolean ignorePostProc = false;
String url = input;

// format
RDFFormat theFormat = RDFWriterRegistry.getInstance().getFileFormatForMIMEType(format).orElse(RDFFormat.RDFXML);

URL baseURL = new URL("http://"+request.getServerName()+((request.getServerPort() != 80)?":"+request.getServerPort():"")+request.getContextPath());
log.debug("Base URL is "+baseURL.toString());
ConvertFormData data = new ConvertFormData();
data.setBaseUrl(baseURL.toString());


/**************************CONVERSION RDF**************************/
InputStream in = null;
String resultFileName = "skos-play-convert";


log.debug("*Conversion à partir d'une Google Spreadsheet : "+input);

// String googleSpreadsheetUrlString = input+"/export?format=xlsx";
String googleSpreadsheetUrlString = input;
log.debug("Google spreadsheet URL "+googleSpreadsheetUrlString);
URL googleSpreadsheetUrl = new URL(googleSpreadsheetUrlString);

InputStream urlInputStream = googleSpreadsheetUrl.openStream(); // throws an IOException
urlInputStream = new DataInputStream(new BufferedInputStream(urlInputStream));

final java.io.File tempFile = java.io.File.createTempFile("skosplay", ".xlsx");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(urlInputStream, out);
}

in = new FileInputStream(tempFile);

try {
log.debug("*Lancement de la conversion avec lang="+language+" et usexl="+useskosxl);
// le content type est toujours positionné à "application/zip" si on nous a demandé un zip, sinon il dépend du format de retour demandé
response.setContentType((useZip)?"application/zip":theFormat.getDefaultMIMEType());
// le nom du fichier de retour
// strip extension, if any
resultFileName = (resultFileName.contains("."))?resultFileName.substring(0, resultFileName.lastIndexOf('.')):resultFileName;
String extension = (useZip)?"zip":theFormat.getDefaultFileExtension();

// add the date in the filename
String dateString = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

response.setHeader("Content-Disposition", "inline; filename=\""+resultFileName+"-"+dateString+"."+extension+"\"");

List<String> identifiant = runConversion(
new ModelWriterFactory(useZip, theFormat, useGraph).buildNewModelWriter(response.getOutputStream()),
in,
language.equals("")?null:language,
useskosxl,
ignorePostProc
);

// sort to garantee order
List<String> uri=new ArrayList<String>(identifiant);
Collections.sort(uri);

// insert a log
SkosPlayConfig.getInstance().getSqlLogDao().insertLog(new LogEntry(
language,
null,
null,
url,
"convert",
uri.toString()
));

} catch (Xls2RdfException e) {
response.reset();
e.printStackTrace();
return doErrorConvert(request, e.getMessage());
} finally {
try {
if(in != null) {
in.close();
}
} catch (IOException ioe) { }
}

return null;
}

private List<String> runConversion(ModelWriterIfc Writer, InputStream filefrom, String lang, boolean generatexl, boolean ignorePostProc) {
Xls2RdfConverter converter = new Xls2RdfConverter(Writer, lang);
List<Xls2RdfPostProcessorIfc> postProcessors = new ArrayList<>();
if(!ignorePostProc) {
postProcessors.add(new SkosPostProcessor());
}
if(!ignorePostProc && generatexl) {
postProcessors.add(new SkosXlPostProcessor(generatexl, generatexl));
}
converter.setPostProcessors(postProcessors);
converter.processInputStream(filefrom);
return converter.getConvertedVocabularyIdentifiers();
}



protected ModelAndView doErrorConvert(
HttpServletRequest request,
String message
) {
ConvertFormData data = new ConvertFormData();
data.setErrorMessagefile(message);
request.setAttribute(ConvertFormData.KEY, data);
return new ModelAndView("/convert");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public ModelAndView convertRDF(
) throws Exception {


log.debug("convert(source="+sourceString+",file="+file+"format="+format+",usexl="+useskosxl+",broaderTransitive="+broaderTransitive+",useZip="+useZip+"language="+language+",url="+url+",ex="+example+")");
log.debug("convert(source="+sourceString+",file="+file+"format="+format+",usexl="+useskosxl+",broaderTransitive="+broaderTransitive+",useZip="+useZip+",language="+language+",url="+url+",ex="+example+")");
final SessionData sessionData = SessionData.get(request.getSession());
//source, it can be: file, example, url or google
SOURCE_TYPE source = SOURCE_TYPE.valueOf(sourceString.toUpperCase());
Expand Down Expand Up @@ -296,7 +296,13 @@ public ModelAndView convertRDF(
}

private List<String> runConversion(ModelWriterIfc writer, InputStream filefrom, String lang, boolean generatexl, boolean broaderTransitive, boolean ignorePostProc) {
Xls2RdfConverter converter = new Xls2RdfConverter(writer, lang);
Xls2RdfConverter converter;
if(lang == null || lang.trim().equals("")) {
converter = new Xls2RdfConverter(writer);
} else {
converter = new Xls2RdfConverter(writer, lang);
}

List<Xls2RdfPostProcessorIfc> postProcessors = new ArrayList<>();

if(!ignorePostProc) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ convert.form.localFile.remove = Remove
convert.form.localFile.select = Select
convert.form.language.legend = Enter/select language
convert.form.advanced.legend = Advanced options
convert.form.legend.language = What is the default language of the labels ?
convert.form.legend.language = What is the default language of the labels (optional) ?
convert.form.Example.download = Download example :
convert.form.luxembourg = This development was partly founded by the government of Luxembourg (Minist\u00E8re d'Etat - Service central de l\u00E9gislation)
convert.form.length.googleID.error = <p style="color:#f5500c;">Warning : Google Spreadsheet ID should have 44 characters.</p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ convert.form.remoteUrl = Sur le web
convert.form.remoteUrl.help = URL http du fichier à convertir
convert.form.advanced.legend = Options avanc\u00E9es
convert.form.providedExample = Dans un des fichiers d'exemple fourni
convert.form.legend.language = Quelle est la langue des libell\u00E9s ?
convert.form.legend.language = Quelle est la langue par d\u00E9faut des libell\u00E9s (optionnelle) ?
convert.form.Example.download = T\u00E9l\u00E9charger l'exemple :
convert.form.luxembourg = Ce d\u00E9veloppement a \u00E9t\u00E9 en partie financ\u00E9 par le gouvernement luxembourgeois (Minist\u00E8re d'Etat - Service central de l\u00E9gislation)
convert.form.length.googleID.error = <p style="color:#f5500c;">Attention : L'ID de document Google devrait avoir 44 caractères.</p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,13 +222,14 @@
<fmt:message key="convert.form.language.legend" />
</label>
<div class="col-sm-10">
<select id="choice_Language" class="ui-select" name="language" id="lg" style="width:4em;">
<option value="de" <c:if test="${data.defaultLanguage == 'de'}">selected</c:if>>de</option>
<option value="en" <c:if test="${data.defaultLanguage == 'en'}">selected</c:if>>en</option>
<option value="es" <c:if test="${data.defaultLanguage == 'es'}">selected</c:if>>es</option>
<option value="fr" <c:if test="${data.defaultLanguage == 'fr'}">selected</c:if>>fr</option>
<option value="it" <c:if test="${data.defaultLanguage == 'it'}">selected</c:if>>it</option>
<option value="ru" <c:if test="${data.defaultLanguage == 'ru'}">selected</c:if>>ru</option>
<select id="choice_Language" class="ui-select" name="language" id="lg" style="width:4em;">
<option value="" selected></option>
<option value="de">de</option>
<option value="en">en</option>
<option value="es">es</option>
<option value="fr">fr</option>
<option value="it">it</option>
<option value="ru">ru</option>
</select>
</div>
</div>
Expand Down

0 comments on commit a7a87d9

Please sign in to comment.