Search in sources :

Example 1 with ConformerURIReporter

use of ambit2.rest.structure.ConformerURIReporter in project ambit-mirror by ideaconsult.

the class StructureQueryResource method createConvertor.

@Override
public RepresentationConvertor createConvertor(Variant variant) throws AmbitException, ResourceException {
    /* workaround for clients not being able to set accept headers */
    if ((queryObject == null) && !(variant.getMediaType().equals(MediaType.TEXT_HTML)))
        throw new NotFoundException();
    setTemplate(template);
    Form acceptform = getResourceRef(getRequest()).getQueryAsForm();
    String media = acceptform.getFirstValue("accept-header");
    if (media != null) {
        variant.setMediaType(new MediaType(media));
    }
    String filenamePrefix = getRequest().getResourceRef().getPath();
    if (variant.getMediaType().equals(ChemicalMediaType.CHEMICAL_MDLSDF)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new SDFReporter<QueryStructureByID>(template, getGroupProperties(), changeLineSeparators), ChemicalMediaType.CHEMICAL_MDLSDF, filenamePrefix);
    } else if (variant.getMediaType().equals(ChemicalMediaType.CHEMICAL_MDLMOL)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new SDFReporter<QueryStructureByID>(new Template(), getGroupProperties(), true, changeLineSeparators), ChemicalMediaType.CHEMICAL_MDLMOL, filenamePrefix);
    } else if (variant.getMediaType().equals(ChemicalMediaType.CHEMICAL_CML)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new CMLReporter<QueryStructureByID>(), ChemicalMediaType.CHEMICAL_CML, filenamePrefix);
    } else if (variant.getMediaType().equals(ChemicalMediaType.CHEMICAL_SMILES)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new SmilesReporter<QueryStructureByID>(true, getTemplate()), ChemicalMediaType.CHEMICAL_SMILES, filenamePrefix);
    } else if (variant.getMediaType().equals(ChemicalMediaType.CHEMICAL_INCHI)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new SmilesReporter<QueryStructureByID>(false, Mode.InChI, getTemplate()), ChemicalMediaType.CHEMICAL_INCHI, filenamePrefix);
    } else if (variant.getMediaType().equals(MediaType.APPLICATION_PDF)) {
        return new PDFConvertor<IStructureRecord, QueryStructureByID, PDFReporter<QueryStructureByID>>(new PDFReporter<QueryStructureByID>(getTemplate(), getGroupProperties()), filenamePrefix);
    } else if (variant.getMediaType().equals(MediaType.TEXT_PLAIN)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(createTXTReporter(), MediaType.TEXT_PLAIN);
    } else if (variant.getMediaType().equals(MediaType.TEXT_URI_LIST)) {
        ConformerURIReporter<QueryStructureByID> reporter = new ConformerURIReporter<QueryStructureByID>(getCompoundInDatasetPrefix(), getRequest(), queryObject.isPrescreen());
        return new StringConvertor(reporter, MediaType.TEXT_URI_LIST, filenamePrefix);
    } else if (variant.getMediaType().equals(MediaType.IMAGE_PNG)) {
        return new ImageConvertor<IStructureRecord, QueryStructureByID>(new ImageReporter<QueryStructureByID>(MediaType.IMAGE_PNG.getMainType(), MediaType.IMAGE_PNG.getSubType()), MediaType.IMAGE_PNG);
    } else if (variant.getMediaType().equals(MediaType.IMAGE_GIF)) {
        return new ImageConvertor<IStructureRecord, QueryStructureByID>(new ImageReporter<QueryStructureByID>(MediaType.IMAGE_GIF.getMainType(), MediaType.IMAGE_GIF.getSubType()), MediaType.IMAGE_GIF);
    } else if (variant.getMediaType().equals(MediaType.APPLICATION_JSON)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new CompoundJSONReporter(getTemplate(), getGroupProperties(), folders, bundles, getRequest(), getRequest().getRootRef().toString() + getCompoundInDatasetPrefix(), includeMol, null), MediaType.APPLICATION_JSON, filenamePrefix);
    } else if (variant.getMediaType().equals(MediaType.APPLICATION_JAVASCRIPT)) {
        String jsonpcallback = getParams().getFirstValue("jsonp");
        if (jsonpcallback == null)
            jsonpcallback = getParams().getFirstValue("callback");
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new CompoundJSONReporter(getTemplate(), getGroupProperties(), folders, bundles, getRequest(), getRequest().getRootRef().toString() + getCompoundInDatasetPrefix(), includeMol, jsonpcallback), MediaType.APPLICATION_JAVASCRIPT, filenamePrefix);
    } else if (variant.getMediaType().equals(ChemicalMediaType.WEKA_ARFF)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new ARFFResourceReporter(getTemplate(), getGroupProperties(), getRequest(), String.format("%s%s", getRequest().getRootRef(), getCompoundInDatasetPrefix())), ChemicalMediaType.WEKA_ARFF, filenamePrefix);
    } else if (variant.getMediaType().equals(ChemicalMediaType.THREECOL_ARFF)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new ARFF3ColResourceReporter(getTemplate(), getGroupProperties(), getRequest(), String.format("%s%s", getRequest().getRootRef(), getCompoundInDatasetPrefix())), ChemicalMediaType.THREECOL_ARFF, filenamePrefix);
    } else if (variant.getMediaType().equals(MediaType.TEXT_CSV)) {
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(createCSVReporter(), MediaType.TEXT_CSV, filenamePrefix);
    } else if (variant.getMediaType().equals(MediaType.APPLICATION_RDF_XML)) {
        switch(rdfwriter) {
            case stax:
                {
                    return new RDFStaXConvertor<IStructureRecord, IQueryRetrieval<IStructureRecord>>(new DatasetRDFStaxReporter(getCompoundInDatasetPrefix(), getRequest(), getTemplate(), getGroupProperties()), filenamePrefix);
                }
            default:
                {
                    // jena
                    return new RDFJenaConvertor<IStructureRecord, IQueryRetrieval<IStructureRecord>>(new DatasetRDFReporter(getCompoundInDatasetPrefix(), getRequest(), variant.getMediaType(), getTemplate(), getGroupProperties()), variant.getMediaType(), filenamePrefix);
                }
        }
    } else if (variant.getMediaType().equals(MediaType.APPLICATION_RDF_TURTLE) || variant.getMediaType().equals(MediaType.TEXT_RDF_N3) || variant.getMediaType().equals(MediaType.TEXT_RDF_NTRIPLES) || variant.getMediaType().equals(MediaType.APPLICATION_RDF_TRIG) || variant.getMediaType().equals(MediaType.APPLICATION_RDF_TRIX) || variant.getMediaType().equals(ChemicalMediaType.APPLICATION_JSONLD)) {
        return new RDFJenaConvertor<IStructureRecord, IQueryRetrieval<IStructureRecord>>(new DatasetRDFReporter(getCompoundInDatasetPrefix(), getRequest(), variant.getMediaType(), getTemplate(), getGroupProperties()), variant.getMediaType(), filenamePrefix);
    } else
        return new OutputWriterConvertor<IStructureRecord, QueryStructureByID>(new SDFReporter<QueryStructureByID>(template, getGroupProperties(), changeLineSeparators), ChemicalMediaType.CHEMICAL_MDLSDF, filenamePrefix);
}
Also used : Form(org.restlet.data.Form) OutputWriterConvertor(net.idea.restnet.db.convertors.OutputWriterConvertor) PDFReporter(ambit2.db.reporters.PDFReporter) NotFoundException(net.idea.modbcum.i.exceptions.NotFoundException) QueryStructureByID(ambit2.db.search.structure.QueryStructureByID) Template(ambit2.base.data.Template) IStructureRecord(ambit2.base.interfaces.IStructureRecord) ARFF3ColResourceReporter(ambit2.rest.dataset.ARFF3ColResourceReporter) SDFReporter(ambit2.db.reporters.SDFReporter) ChemicalMediaType(net.idea.restnet.c.ChemicalMediaType) MediaType(org.restlet.data.MediaType) RDFJenaConvertor(ambit2.rest.RDFJenaConvertor) CompoundJSONReporter(ambit2.rest.structure.CompoundJSONReporter) SmilesReporter(ambit2.db.reporters.SmilesReporter) DatasetRDFStaxReporter(ambit2.rest.dataset.DatasetRDFStaxReporter) StringConvertor(net.idea.restnet.c.StringConvertor) ImageReporter(ambit2.db.reporters.ImageReporter) RDFStaXConvertor(ambit2.rest.RDFStaXConvertor) ARFFResourceReporter(ambit2.rest.dataset.ARFFResourceReporter) ConformerURIReporter(ambit2.rest.structure.ConformerURIReporter) ImageConvertor(ambit2.rest.ImageConvertor) DatasetRDFReporter(ambit2.rest.dataset.DatasetRDFReporter)

Example 2 with ConformerURIReporter

use of ambit2.rest.structure.ConformerURIReporter in project ambit-mirror by ideaconsult.

the class CallableFileImport method importFile.

public TaskResult importFile(File file) throws Exception {
    try {
        // if target dataset is not defined, create new dataset
        final SourceDataset dataset = targetDataset != null ? targetDataset : datasetMeta(file);
        if (targetDataset == null)
            dataset.setId(-1);
        final BatchDBProcessor<String> batch = new BatchDBProcessor<String>() {

            /**
             */
            private static final long serialVersionUID = -7971761364143510120L;

            @Override
            public Iterator<String> getIterator(IInputState target) throws AmbitException {
                try {
                    File file = ((FileInputState) target).getFile();
                    RDFIteratingReader i = getRDFIterator(file, getReporter().getBaseReference().toString());
                    if (i == null) {
                        IIteratingChemObjectReader ni = getNanoCMLIterator(file, getReporter().getBaseReference().toString());
                        if (ni == null)
                            return super.getIterator(target);
                        else
                            return ni;
                    } else {
                        /*
			     * RDFMetaDatasetIterator datasets = null; try {
			     * datasets = new
			     * RDFMetaDatasetIterator(i.getJenaModel());
			     * datasets
			     * .setBaseReference(getReporter().getBaseReference
			     * ()); while (datasets.hasNext()) { SourceDataset d
			     * = datasets.next(); dataset.setId(d.getId());
			     * dataset.setName(d.getName());
			     * dataset.setTitle(d.getTitle());
			     * dataset.setURL(d.getURL()); } } catch (Exception
			     * x) { x.printStackTrace(); } finally { try {
			     * datasets.close();} catch (Exception x) {} }
			     */
                        return i;
                    }
                } catch (AmbitException x) {
                    throw x;
                } catch (Exception x) {
                    throw new AmbitException(x);
                }
            }

            @Override
            public void onItemProcessed(String input, Object output, IBatchStatistics stats) {
                super.onItemProcessed(input, output, stats);
                if (firstCompoundOnly && (stats.getRecords(RECORDS_STATS.RECORDS_PROCESSED) >= 1)) {
                    cancelled = true;
                    if (output != null)
                        if ((output instanceof ArrayList) && ((ArrayList) output).size() > 0) {
                            if (((ArrayList) output).get(0) instanceof IStructureRecord)
                                recordImported = (IStructureRecord) ((ArrayList) output).get(0);
                        } else if (output instanceof IStructureRecord)
                            recordImported = (IStructureRecord) output;
                }
            }
        };
        batch.setReference(dataset.getReference());
        batch.setConnection(connection);
        final RepositoryWriter writer = new RepositoryWriter();
        writer.setUseExistingStructure(isPropertyOnly());
        writer.setPropertyKey(getMatcher());
        writer.setDataset(dataset);
        final ProcessorsChain<String, IBatchStatistics, IProcessor> chain = new ProcessorsChain<String, IBatchStatistics, IProcessor>();
        chain.add(writer);
        batch.setProcessorChain(chain);
        writer.setConnection(connection);
        FileInputState fin = new FileInputState(file);
        IBatchStatistics stats = batch.process(fin);
        if (firstCompoundOnly) {
            if (recordImported == null)
                throw new Exception("No compound imported");
            if (compoundReporter == null)
                compoundReporter = new ConformerURIReporter("", null, false);
            try {
                batch.close();
            } catch (Exception xx) {
            }
            return new TaskResult(compoundReporter.getURI(recordImported));
        } else {
            ReadDataset q = new ReadDataset();
            q.setValue(dataset);
            QueryExecutor<ReadDataset> x = new QueryExecutor<ReadDataset>();
            x.setConnection(connection);
            ResultSet rs = x.process(q);
            ISourceDataset newDataset = null;
            while (rs.next()) {
                newDataset = q.getObject(rs);
                break;
            }
            x.closeResults(rs);
            x.setConnection(null);
            if (newDataset == null)
                throw new ResourceException(Status.SUCCESS_NO_CONTENT);
            if (reporter == null)
                reporter = new DatasetURIReporter<IQueryRetrieval<ISourceDataset>, ISourceDataset>();
            try {
                batch.close();
            } catch (Exception xx) {
            }
            return new TaskResult(reporter.getURI(newDataset));
        }
    } catch (ResourceException x) {
        throw x;
    } catch (Exception x) {
        throw new ResourceException(new Status(Status.SERVER_ERROR_INTERNAL, x.getMessage()));
    } finally {
        try {
            connection.close();
        } catch (Exception x) {
        }
        connection = null;
    }
}
Also used : RDFIteratingReader(ambit2.rest.dataset.RDFIteratingReader) ArrayList(java.util.ArrayList) RepositoryWriter(ambit2.db.processors.RepositoryWriter) IStructureRecord(ambit2.base.interfaces.IStructureRecord) ISourceDataset(ambit2.base.data.ISourceDataset) ProcessorsChain(net.idea.modbcum.i.processors.ProcessorsChain) IInputState(ambit2.core.io.IInputState) QueryExecutor(ambit2.db.search.QueryExecutor) ResultSet(java.sql.ResultSet) ResourceException(org.restlet.resource.ResourceException) Status(org.restlet.data.Status) IIteratingChemObjectReader(org.openscience.cdk.io.iterator.IIteratingChemObjectReader) IBatchStatistics(net.idea.modbcum.i.batch.IBatchStatistics) IProcessor(net.idea.modbcum.i.processors.IProcessor) BatchDBProcessor(ambit2.db.processors.BatchDBProcessor) AmbitException(net.idea.modbcum.i.exceptions.AmbitException) CDKException(org.openscience.cdk.exception.CDKException) ResourceException(org.restlet.resource.ResourceException) ConformerURIReporter(ambit2.rest.structure.ConformerURIReporter) ISourceDataset(ambit2.base.data.ISourceDataset) SourceDataset(ambit2.base.data.SourceDataset) File(java.io.File) FileInputState(ambit2.core.io.FileInputState) ReadDataset(ambit2.db.update.dataset.ReadDataset) AmbitException(net.idea.modbcum.i.exceptions.AmbitException) DatasetURIReporter(ambit2.rest.dataset.DatasetURIReporter)

Example 3 with ConformerURIReporter

use of ambit2.rest.structure.ConformerURIReporter in project ambit-mirror by ideaconsult.

the class FileUpload method upload.

public Representation upload(Representation entity, Variant variant, boolean newEntry, boolean propertyOnly, USERID token, String referer, ClientInfo clientInfo) throws ResourceException {
    if ((entity == null) || !entity.isAvailable())
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Empty content");
    if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType())) {
        // propertyOnly POST:
        boolean clearPreviousContent = !propertyOnly;
        // false, PUT : true
        return copyDatasetToQueryResultsTable(new Form(entity), token, clearPreviousContent, referer, clientInfo);
    } else if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // factory.setSizeThreshold(100);
        RestletFileUpload upload = new RestletFileUpload(factory);
        Connection connection = null;
        try {
            DBConnection dbc = new DBConnection(getApplication().getContext());
            connection = dbc.getConnection(30, true, 8);
            List<FileItem> items = upload.parseRequest(getRequest());
            DatasetURIReporter<IQueryRetrieval<ISourceDataset>, ISourceDataset> reporter = new DatasetURIReporter<IQueryRetrieval<ISourceDataset>, ISourceDataset>(getRequest());
            ConformerURIReporter<IQueryRetrieval<IStructureRecord>> compoundReporter = new ConformerURIReporter<IQueryRetrieval<IStructureRecord>>(getRequest());
            CallableFileImport callable = new CallableFileImport(getRequest().getClientInfo(), dataset, items, fileUploadField, connection, reporter, compoundReporter, firstCompoundOnly, token);
            callable.setPropertyOnly(propertyOnly);
            ITask<Reference, Object> task = ((ITaskApplication) getApplication()).addTask("File import", callable, getRequest().getRootRef(), token);
            ITaskStorage storage = ((ITaskApplication) getApplication()).getTaskStorage();
            FactoryTaskConvertor<Object> tc = new FactoryTaskConvertor<Object>(storage);
            task.update();
            getResponse().setStatus(task.isDone() ? Status.SUCCESS_OK : Status.SUCCESS_ACCEPTED);
            return tc.createTaskRepresentation(task.getUuid(), variant, getRequest(), getResponse(), null);
        } catch (Exception x) {
            try {
                connection.close();
            } catch (Exception xx) {
                xx.printStackTrace();
            }
            throw new ResourceException(Status.SERVER_ERROR_INTERNAL, x);
        }
    } else if (isAllowedMediaType(entity.getMediaType())) {
        Connection connection = null;
        try {
            DBConnection dbc = new DBConnection(getApplication().getContext());
            connection = dbc.getConnection(30, true, 8);
            DatasetURIReporter<IQueryRetrieval<ISourceDataset>, ISourceDataset> reporter = new DatasetURIReporter<IQueryRetrieval<ISourceDataset>, ISourceDataset>(getRequest());
            ConformerURIReporter<IQueryRetrieval<IStructureRecord>> compoundReporter = new ConformerURIReporter<IQueryRetrieval<IStructureRecord>>(getRequest());
            CallableFileImport callable = new CallableFileImport(getRequest().getClientInfo(), dataset, entity, connection, reporter, compoundReporter, firstCompoundOnly, token);
            callable.setPropertyOnly(propertyOnly);
            ITask<ITaskResult, Object> task = ((AmbitApplication) getApplication()).addTask(String.format("File import %s [%d]", entity.getDownloadName() == null ? entity.getMediaType() : entity.getDownloadName(), entity.getSize()), callable, getRequest().getRootRef(), token == null ? null : token.toString());
            ITaskStorage storage = ((ITaskApplication) getApplication()).getTaskStorage();
            FactoryTaskConvertor<Object> tc = new FactoryTaskConvertor<Object>(storage);
            task.update();
            getResponse().setStatus(task.isDone() ? Status.SUCCESS_OK : Status.SUCCESS_ACCEPTED);
            return tc.createTaskRepresentation(task.getUuid(), variant, getRequest(), getResponse(), null);
        } catch (Exception x) {
            try {
                connection.close();
            } catch (Exception xx) {
                xx.printStackTrace();
            }
            throw new ResourceException(Status.SERVER_ERROR_INTERNAL, x);
        }
    } else
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, String.format("Unsupported Content-type=%s", entity.getMediaType()));
}
Also used : DBConnection(ambit2.rest.DBConnection) ITask(net.idea.restnet.i.task.ITask) RestletFileUpload(org.restlet.ext.fileupload.RestletFileUpload) Form(org.restlet.data.Form) ITaskApplication(net.idea.restnet.i.task.ITaskApplication) IStructureRecord(ambit2.base.interfaces.IStructureRecord) ISourceDataset(ambit2.base.data.ISourceDataset) FactoryTaskConvertor(ambit2.rest.task.FactoryTaskConvertor) ResourceException(org.restlet.resource.ResourceException) List(java.util.List) ITaskStorage(net.idea.restnet.i.task.ITaskStorage) Connection(java.sql.Connection) DBConnection(ambit2.rest.DBConnection) AmbitApplication(ambit2.rest.AmbitApplication) IQueryRetrieval(net.idea.modbcum.i.IQueryRetrieval) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ResourceException(org.restlet.resource.ResourceException) ConformerURIReporter(ambit2.rest.structure.ConformerURIReporter) ITaskResult(net.idea.restnet.i.task.ITaskResult) CallableFileImport(ambit2.rest.task.CallableFileImport)

Aggregations

IStructureRecord (ambit2.base.interfaces.IStructureRecord)3 ConformerURIReporter (ambit2.rest.structure.ConformerURIReporter)3 ISourceDataset (ambit2.base.data.ISourceDataset)2 Form (org.restlet.data.Form)2 SourceDataset (ambit2.base.data.SourceDataset)1 Template (ambit2.base.data.Template)1 FileInputState (ambit2.core.io.FileInputState)1 IInputState (ambit2.core.io.IInputState)1 BatchDBProcessor (ambit2.db.processors.BatchDBProcessor)1 RepositoryWriter (ambit2.db.processors.RepositoryWriter)1 ImageReporter (ambit2.db.reporters.ImageReporter)1 PDFReporter (ambit2.db.reporters.PDFReporter)1 SDFReporter (ambit2.db.reporters.SDFReporter)1 SmilesReporter (ambit2.db.reporters.SmilesReporter)1 QueryExecutor (ambit2.db.search.QueryExecutor)1 QueryStructureByID (ambit2.db.search.structure.QueryStructureByID)1 ReadDataset (ambit2.db.update.dataset.ReadDataset)1 AmbitApplication (ambit2.rest.AmbitApplication)1 DBConnection (ambit2.rest.DBConnection)1 ImageConvertor (ambit2.rest.ImageConvertor)1