Search in sources :

Example 1 with DatasetDescriptionMap

use of org.apache.jena.fuseki.build.DatasetDescriptionMap in project jena by apache.

the class ActionDatasets method execPostContainer.

// ---- POST
@Override
protected JsonValue execPostContainer(HttpAction action) {
    UUID uuid = UUID.randomUUID();
    DatasetDescriptionMap registry = new DatasetDescriptionMap();
    ContentType ct = ActionLib.getContentType(action);
    boolean hasParams = action.getRequestParameterNames().hasMoreElements();
    if (ct == null && !hasParams)
        ServletOps.errorBadRequest("Bad request - Content-Type or both parameters dbName and dbType required");
    boolean committed = false;
    // Also acts as a concurrency lock
    system.begin(ReadWrite.WRITE);
    String systemFileCopy = null;
    String configFile = null;
    try {
        // Where to build the templated service/database.
        Model model = ModelFactory.createDefaultModel();
        StreamRDF dest = StreamRDFLib.graph(model.getGraph());
        if (hasParams || WebContent.isHtmlForm(ct))
            assemblerFromForm(action, dest);
        else if (WebContent.isMultiPartForm(ct))
            assemblerFromUpload(action, dest);
        else
            assemblerFromBody(action, dest);
        AssemblerUtils.addRegistered(model);
        // ----
        // Keep a persistent copy immediately.  This is not used for
        // anything other than being "for the record".
        systemFileCopy = FusekiWebapp.dirSystemFileArea.resolve(uuid.toString()).toString();
        try (OutputStream outCopy = IO.openOutputFile(systemFileCopy)) {
            RDFDataMgr.write(outCopy, model, Lang.TURTLE);
        }
        // ----
        // Process configuration.
        // Returns the "service fu:name NAME" statement
        Statement stmt = findService(model);
        Resource subject = stmt.getSubject();
        Literal object = stmt.getObject().asLiteral();
        if (object.getDatatype() != null && !object.getDatatype().equals(XSDDatatype.XSDstring))
            action.log.warn(format("[%d] Service name '%s' is not a string", action.id, FmtUtils.stringForRDFNode(object)));
        String datasetPath;
        {
            // Check the name provided.
            String datasetName = object.getLexicalForm();
            // ---- Check and canonicalize name.
            if (datasetName.isEmpty())
                ServletOps.error(HttpSC.BAD_REQUEST_400, "Empty dataset name");
            if (StringUtils.isBlank(datasetName))
                ServletOps.error(HttpSC.BAD_REQUEST_400, format("Whitespace dataset name: '%s'", datasetName));
            if (datasetName.contains(" "))
                ServletOps.error(HttpSC.BAD_REQUEST_400, format("Bad dataset name (contains spaces) '%s'", datasetName));
            if (datasetName.equals("/"))
                ServletOps.error(HttpSC.BAD_REQUEST_400, format("Bad dataset name '%s'", datasetName));
            datasetPath = DataAccessPoint.canonical(datasetName);
            // ---- Check whether it already exists
            if (action.getDataAccessPointRegistry().isRegistered(datasetPath))
                // And abort.
                ServletOps.error(HttpSC.CONFLICT_409, "Name already registered " + datasetPath);
        }
        action.log.info(format("[%d] Create database : name = %s", action.id, datasetPath));
        configFile = FusekiWebapp.generateConfigurationFilename(datasetPath);
        List<String> existing = FusekiWebapp.existingConfigurationFile(datasetPath);
        if (!existing.isEmpty())
            ServletOps.error(HttpSC.CONFLICT_409, "Configuration file for '" + datasetPath + "' already exists");
        // Write to configuration directory.
        try (OutputStream outCopy = IO.openOutputFile(configFile)) {
            RDFDataMgr.write(outCopy, model, Lang.TURTLE);
        }
        // Currently do nothing with the system database.
        // In the future ... maybe ...
        // Model modelSys = system.getNamedModel(gn.getURI());
        // modelSys.removeAll(null, pStatus, null);
        // modelSys.add(subject, pStatus, FusekiVocab.stateActive);
        // Need to be in Resource space at this point.
        DataAccessPoint dataAccessPoint = FusekiConfig.buildDataAccessPoint(subject, registry);
        if (dataAccessPoint == null) {
            FmtLog.error(action.log, "Failed to build DataAccessPoint: datasetPath = %s; DataAccessPoint name = %s", datasetPath, dataAccessPoint);
            ServletOps.errorBadRequest("Failed to build DataAccessPoint");
            return null;
        }
        dataAccessPoint.getDataService().setEndpointProcessors(action.getOperationRegistry());
        dataAccessPoint.getDataService().goActive();
        if (!datasetPath.equals(dataAccessPoint.getName()))
            FmtLog.warn(action.log, "Inconsistent names: datasetPath = %s; DataAccessPoint name = %s", datasetPath, dataAccessPoint);
        action.getDataAccessPointRegistry().register(dataAccessPoint);
        action.setResponseContentType(WebContent.contentTypeTextPlain);
        ServletOps.success(action);
        system.commit();
        committed = true;
    } catch (IOException ex) {
        IO.exception(ex);
    } finally {
        if (!committed) {
            if (systemFileCopy != null)
                FileOps.deleteSilent(systemFileCopy);
            if (configFile != null)
                FileOps.deleteSilent(configFile);
            system.abort();
        }
        system.end();
    }
    return null;
}
Also used : ContentType(org.apache.jena.atlas.web.ContentType) OutputStream(java.io.OutputStream) DataAccessPoint(org.apache.jena.fuseki.server.DataAccessPoint) RuntimeIOException(org.apache.jena.atlas.RuntimeIOException) IOException(java.io.IOException) StreamRDF(org.apache.jena.riot.system.StreamRDF) DatasetDescriptionMap(org.apache.jena.fuseki.build.DatasetDescriptionMap)

Example 2 with DatasetDescriptionMap

use of org.apache.jena.fuseki.build.DatasetDescriptionMap in project jena by apache.

the class FusekiWebapp method configFromTemplate.

private static DataAccessPoint configFromTemplate(String templateFile, String datasetPath, boolean allowUpdate, Map<String, String> params) {
    DatasetDescriptionMap registry = new DatasetDescriptionMap();
    // ---- Setup
    if (params == null) {
        params = new HashMap<>();
        params.put(Template.NAME, datasetPath);
    } else {
        if (!params.containsKey(Template.NAME)) {
            Fuseki.configLog.warn("No NAME found in template parameters (added)");
            params.put(Template.NAME, datasetPath);
        }
    }
    // -- Logging
    Fuseki.configLog.info("Template file: " + templateFile);
    String dir = params.get(Template.DIR);
    if (dir != null) {
        if (!Objects.equals(dir, Names.memName) && !FileOps.exists(dir))
            throw new CmdException("Directory not found: " + dir);
    }
    // -- Logging
    datasetPath = DataAccessPoint.canonical(datasetPath);
    // DRY -- ActionDatasets (and others?)
    addGlobals(params);
    String str = TemplateFunctions.templateFile(templateFile, params, Lang.TTL);
    Lang lang = RDFLanguages.filenameToLang(str, Lang.TTL);
    StringReader sr = new StringReader(str);
    Model model = ModelFactory.createDefaultModel();
    RDFDataMgr.read(model, sr, datasetPath, lang);
    // ---- DataAccessPoint
    Statement stmt = getOne(model, null, FusekiVocab.pServiceName, null);
    if (stmt == null) {
        StmtIterator sIter = model.listStatements(null, FusekiVocab.pServiceName, (RDFNode) null);
        if (!sIter.hasNext())
            ServletOps.errorBadRequest("No name given in description of Fuseki service");
        sIter.next();
        if (sIter.hasNext())
            ServletOps.errorBadRequest("Multiple names given in description of Fuseki service");
        throw new InternalErrorException("Inconsistent: getOne didn't fail the second time");
    }
    Resource subject = stmt.getSubject();
    if (!allowUpdate) {
    // Opportunity for more sophisticated "read-only" mode.
    // 1 - clean model, remove "fu:serviceUpdate", "fu:serviceUpload", "fu:serviceReadGraphStore", "fu:serviceReadWriteGraphStore"
    // 2 - set a flag on DataAccessPoint
    }
    DataAccessPoint dap = FusekiConfig.buildDataAccessPoint(subject, registry);
    return dap;
}
Also used : CmdException(org.apache.jena.cmd.CmdException) StringReader(java.io.StringReader) DataAccessPoint(org.apache.jena.fuseki.server.DataAccessPoint) Lang(org.apache.jena.riot.Lang) InternalErrorException(org.apache.jena.atlas.lib.InternalErrorException) DatasetDescriptionMap(org.apache.jena.fuseki.build.DatasetDescriptionMap)

Aggregations

DatasetDescriptionMap (org.apache.jena.fuseki.build.DatasetDescriptionMap)2 DataAccessPoint (org.apache.jena.fuseki.server.DataAccessPoint)2 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 StringReader (java.io.StringReader)1 RuntimeIOException (org.apache.jena.atlas.RuntimeIOException)1 InternalErrorException (org.apache.jena.atlas.lib.InternalErrorException)1 ContentType (org.apache.jena.atlas.web.ContentType)1 CmdException (org.apache.jena.cmd.CmdException)1 Lang (org.apache.jena.riot.Lang)1 StreamRDF (org.apache.jena.riot.system.StreamRDF)1