Search in sources :

Example 1 with SubstanceUUID

use of ambit2.base.data.substance.SubstanceUUID in project ambit-mirror by ideaconsult.

the class SubstanceStudyResource method createQuery.

@Override
protected Q createQuery(Context context, Request request, Response response) throws ResourceException {
    Object key = request.getAttributes().get(SubstanceResource.idsubstance);
    if (key == null) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
    } else {
        substanceUUID = key.toString();
        try {
            Form form = getRequest().getResourceRef().getQueryAsForm();
            String topCategory = form.getFirstValue("top");
            String category = form.getFirstValue("category");
            String property = form.getFirstValue("property");
            String property_uri = form.getFirstValue("property_uri");
            String document_uuid = form.getFirstValue("document_uuid");
            String investigation_uuid = form.getFirstValue("investigation");
            ReadSubstanceStudy q = new ReadSubstanceStudy();
            q.setFieldname(substanceUUID);
            if (topCategory != null || category != null || property != null || property_uri != null || investigation_uuid != null || document_uuid != null) {
                Protocol p = new ambit2.base.data.study.Protocol("");
                p.setTopCategory(topCategory);
                p.setCategory(category);
                ProtocolApplication papp = new ProtocolApplication(p);
                papp.setDocumentUUID(document_uuid);
                papp.setInvestigationUUID(investigation_uuid);
                if (property_uri != null)
                    try {
                        // not nice REST style, but easiest to parse the URI
                        // not nice REST style, but easiest to parse the URI
                        Reference puri = new Reference(property_uri.endsWith("/") ? property_uri.substring(0, property_uri.length() - 2) : property_uri);
                        // the very last segment denotes protocol, then study type, then one is the endpoint hash
                        if (// this is the protocol
                        puri.getSegments().get(puri.getSegments().size() - 1).indexOf("-") > 0)
                            property = puri.getSegments().get(puri.getSegments().size() - 3);
                        else
                            property = puri.getSegments().get(puri.getSegments().size() - 2);
                        if (property.length() != 40)
                            property = null;
                    } catch (Exception x) {
                    }
                if (property != null) {
                    EffectRecord effect = new EffectRecord();
                    effect.setSampleID(property);
                    papp.addEffect(effect);
                }
                q.setValue(papp);
            }
            // q.setFieldname(relation);
            return (Q) q;
        } catch (Exception x) {
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
        }
    }
}
Also used : Form(org.restlet.data.Form) Reference(org.restlet.data.Reference) ReadSubstanceStudy(ambit2.db.substance.study.ReadSubstanceStudy) AmbitException(net.idea.modbcum.i.exceptions.AmbitException) ResourceException(org.restlet.resource.ResourceException) ProtocolApplication(ambit2.base.data.study.ProtocolApplication) EffectRecord(ambit2.base.data.study.EffectRecord) ResourceException(org.restlet.resource.ResourceException) Protocol(ambit2.base.data.study.Protocol)

Example 2 with SubstanceUUID

use of ambit2.base.data.substance.SubstanceUUID in project ambit-mirror by ideaconsult.

the class SubstanceByOwnerResource method createQuery.

@Override
protected Q createQuery(Context context, Request request, Response response) throws ResourceException {
    Object owneruuid = request.getAttributes().get(OwnerSubstanceFacetResource.idowner);
    ReadSubstanceByOwner q = new ReadSubstanceByOwner(ReadSubstanceByOwner._ownersearchmode.owner_uuid, owneruuid.toString()) {

        /**
         */
        private static final long serialVersionUID = 6003910893547753024L;

        public ambit2.base.data.SubstanceRecord getObject(java.sql.ResultSet rs) throws AmbitException {
            ambit2.base.data.SubstanceRecord record = super.getObject(rs);
            record.setRecordProperty(new SubstancePublicName(), record.getPublicName());
            record.setRecordProperty(new SubstanceName(), record.getSubstanceName());
            record.setRecordProperty(new SubstanceUUID(), record.getSubstanceUUID());
            record.setRecordProperty(new SubstanceOwner(), record.getOwnerName());
            return record;
        }
    };
    return (Q) q;
}
Also used : SubstanceName(ambit2.base.data.substance.SubstanceName) SubstanceOwner(ambit2.base.data.substance.SubstanceOwner) SubstanceUUID(ambit2.base.data.substance.SubstanceUUID) SubstanceRecord(ambit2.base.data.SubstanceRecord) ReadSubstanceByOwner(ambit2.db.substance.ReadSubstanceByOwner) SubstancePublicName(ambit2.base.data.substance.SubstancePublicName)

Example 3 with SubstanceUUID

use of ambit2.base.data.substance.SubstanceUUID in project ambit-mirror by ideaconsult.

the class CallableSubstanceI5Query method doCall.

@Override
public TaskResult doCall() throws Exception {
    Connection connection = null;
    DBConnection dbc = null;
    IUCLIDLightClient i5 = null;
    DBSubstanceWriter writer = null;
    FileHandler logHandler = null;
    StreamHandler streamHandler = null;
    OutputStream out = new ByteArrayOutputStream();
    try {
        logger.log(Level.INFO, String.format("Logging to %s", logFile));
        logHandler = new FileHandler(logFile);
        localLogger.addHandler(logHandler);
        SimpleFormatter formatter = new SimpleFormatter();
        streamHandler = new StreamHandler(out, formatter);
        localLogger.addHandler(streamHandler);
        logHandler.setFormatter(formatter);
        localLogger.setUseParentHandlers(false);
        localLogger.fine("Start()");
        if (useUUID) {
            if (substanceUUID == null || "".equals(substanceUUID))
                throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Empty UUID");
            dbc = new DBConnection(context);
            if (server == null)
                server = dbc.getProperty(iuclidversion.getProperty(".server"));
            if (user == null)
                user = dbc.getProperty(iuclidversion.getProperty(".user"));
            if (pass == null)
                pass = dbc.getProperty(iuclidversion.getProperty(".pass"));
            try {
                i5 = iuclidversion.createClient(server);
                if (i5.login(user, pass)) {
                    IContainerClient ccli = i5.getContainerClient();
                    substanceUUID = iuclidversion.formatQueryUUID(substanceUUID);
                    localLogger.log(Level.FINE, String.format("Retieving %s from %s", substanceUUID, server));
                    List<IIdentifiableResource<IIdentifier>> container = null;
                    try {
                        container = ccli.get(new Identifier(substanceUUID));
                    } catch (Exception x) {
                        localLogger.log(Level.SEVERE, String.format("Failed to retrieve %s from %s. Error %s", substanceUUID, server, x.getMessage()));
                        streamHandler.flush();
                        String msg = out.toString();
                        throw new ImportSubstanceException(new Status(Status.SERVER_ERROR_BAD_GATEWAY, String.format("Failed to retrieve %s", substanceUUID)), msg);
                    }
                    connection = dbc.getConnection();
                    localLogger.log(Level.INFO, String.format("Importing %s", substanceUUID, server));
                    writer = new DBSubstanceWriter(DBSubstanceWriter.datasetMeta(), new SubstanceRecord(), clearMeasurements, clearComposition);
                    writer.setI5mode(true);
                    writer.setCloseConnection(false);
                    writer.setConnection(connection);
                    writer.open();
                    IIdentifiableResource<IIdentifier> result = processContainer(container, writer, server);
                } else
                    throw new ImportSubstanceException(new Status(Status.SERVER_ERROR_BAD_GATEWAY, "IUCLID5 server login failed"), "IUCLID5 server login failed [" + server + "].");
            } catch (ResourceException x) {
                throw x;
            } catch (Exception x) {
                streamHandler.flush();
                String msg = out.toString();
                throw new ImportSubstanceException(new Status(Status.SERVER_ERROR_BAD_GATEWAY, x.getMessage()), msg);
            }
        } else {
            // query
            if (extIDType == null || extIDValue == null)
                throw new ImportSubstanceException(new Status(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid query"), "Invalid query");
            dbc = new DBConnection(context);
            if (server == null)
                server = dbc.getProperty(iuclidversion.getProperty(".server"));
            if (user == null)
                user = dbc.getProperty(iuclidversion.getProperty(".user"));
            if (pass == null)
                pass = dbc.getProperty(iuclidversion.getProperty(".pass"));
            try {
                i5 = iuclidversion.createClient(server);
                if (i5.login(user, pass)) {
                    IQueryToolClient cli = i5.getQueryToolClient();
                    List<IIdentifiableResource<IIdentifier>> queryResults = cli.executeQuery(iuclidversion.createQuery(extIDValue), extIDType, extIDValue);
                    if (queryResults != null && queryResults.size() > 0) {
                        connection = dbc.getConnection();
                        writer = new DBSubstanceWriter(DBSubstanceWriter.datasetMeta(), new SubstanceRecord(), clearMeasurements, clearComposition);
                        writer.setI5mode(true);
                        writer.setCloseConnection(false);
                        writer.setConnection(connection);
                        writer.open();
                        IContainerClient ccli = i5.getContainerClient();
                        int imported = 0;
                        int importError = 0;
                        for (IIdentifiableResource<IIdentifier> item : queryResults) try {
                            localLogger.log(Level.FINE, item.getResourceIdentifier().toString());
                            List<IIdentifiableResource<IIdentifier>> container = ccli.get(new Identifier(iuclidversion.formatQueryUUID(item.getResourceIdentifier().toString())));
                            processContainer(container, writer, server);
                            imported++;
                        } catch (Exception x) {
                            localLogger.log(Level.SEVERE, x.getMessage());
                            importError++;
                        }
                        String foundMsg = String.format("Found %d substance(s), imported %d substance(s) %d error(s).", queryResults.size(), imported, importError);
                        localLogger.log(Level.INFO, foundMsg);
                        streamHandler.flush();
                        String msg = out.toString();
                        if (importError != 0) {
                            if (imported > 0) {
                                TaskResult result = createReference(connection);
                                msg = msg + String.format("The imported substances are available at %s", result.getUri());
                            }
                            throw new ImportSubstanceException(new Status(Status.SERVER_ERROR_BAD_GATEWAY, foundMsg), msg);
                        } else if (imported == 0) {
                            throw new ImportSubstanceException(new Status(Status.CLIENT_ERROR_NOT_FOUND, foundMsg), msg);
                        }
                    } else {
                        streamHandler.flush();
                        String msg = out.toString();
                        throw new ImportSubstanceException(new Status(Status.CLIENT_ERROR_NOT_FOUND, "No substances found."), msg);
                    }
                } else
                    throw new ImportSubstanceException(new Status(Status.SERVER_ERROR_BAD_GATEWAY, "IUCLID server login failed"), "IUCLID server login failed [" + server + "].");
            } catch (ResourceException x) {
                throw x;
            } catch (Exception x) {
                localLogger.log(Level.SEVERE, x.getMessage());
                streamHandler.flush();
                String msg = out.toString();
                throw new ImportSubstanceException(new Status(Status.SERVER_ERROR_BAD_GATEWAY, "Error when retrieving substances"), msg);
            }
        }
        return createReference(connection);
    } catch (ResourceException x) {
        localLogger.log(Level.SEVERE, x.getMessage(), x);
        throw x;
    } catch (Exception x) {
        localLogger.log(Level.SEVERE, x.getMessage(), x);
        throw x;
    } finally {
        localLogger.fine("Done");
        try {
            if (i5 != null)
                i5.logout();
        } catch (Exception x) {
            localLogger.warning(x.getMessage());
        }
        try {
            if (i5 != null)
                i5.close();
        } catch (Exception x) {
            localLogger.warning(x.getMessage());
        }
        try {
            writer.setConnection(null);
        } catch (Exception x) {
        }
        try {
            writer.close();
        } catch (Exception x) {
        }
        try {
            if (connection != null)
                connection.close();
        } catch (Exception x) {
            localLogger.warning(x.getMessage());
        }
        try {
            if (logHandler != null) {
                localLogger.setUseParentHandlers(true);
                localLogger.removeHandler(logHandler);
                localLogger.removeHandler(streamHandler);
                logHandler.close();
            }
        } catch (Exception x) {
        }
    }
}
Also used : DBConnection(ambit2.rest.DBConnection) DBSubstanceWriter(ambit2.db.substance.processor.DBSubstanceWriter) ImportSubstanceException(ambit2.rest.exception.ImportSubstanceException) IIdentifiableResource(net.idea.opentox.cli.IIdentifiableResource) IIdentifier(net.idea.opentox.cli.id.IIdentifier) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) OutputStream(java.io.OutputStream) Identifier(net.idea.opentox.cli.id.Identifier) IIdentifier(net.idea.opentox.cli.id.IIdentifier) StreamHandler(java.util.logging.StreamHandler) ResourceException(org.restlet.resource.ResourceException) List(java.util.List) IContainerClient(net.idea.iuclid.cli.IContainerClient) Status(org.restlet.data.Status) SimpleFormatter(java.util.logging.SimpleFormatter) Connection(java.sql.Connection) DBConnection(ambit2.rest.DBConnection) SubstanceRecord(ambit2.base.data.SubstanceRecord) IQueryToolClient(net.idea.iuclid.cli.IQueryToolClient) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) ResourceException(org.restlet.resource.ResourceException) ImportSubstanceException(ambit2.rest.exception.ImportSubstanceException) AmbitIOException(ambit2.base.exceptions.AmbitIOException) FileHandler(java.util.logging.FileHandler) IUCLIDLightClient(net.idea.iuclid.cli.IUCLIDLightClient) TaskResult(ambit2.rest.task.TaskResult)

Example 4 with SubstanceUUID

use of ambit2.base.data.substance.SubstanceUUID in project ambit-mirror by ideaconsult.

the class SubstanceDatasetResource method createXLSXReporter.

protected IProcessor<Q, Representation> createXLSXReporter(MediaType media, boolean hssf, String filenamePrefix) {
    groupProperties.add(new SubstancePublicName());
    groupProperties.add(new SubstanceName());
    groupProperties.add(new SubstanceUUID());
    groupProperties.add(new SubstanceOwner());
    String jsonpcallback = getParams().getFirstValue("jsonp");
    if (jsonpcallback == null)
        jsonpcallback = getParams().getFirstValue("callback");
    String configResource = String.format("config-%s.js", ((IFreeMarkerApplication) getApplication()).getProfile());
    return new OutputStreamConvertor(new StructureRecordXLSXReporter(getRequest().getRootRef().toString(), hssf, getTemplate(), getGroupProperties(), getBundles(), null, true, configResource) {

        @Override
        protected void configurePropertyProcessors() {
            getCompositionProcessors(getProcessors());
            getProcessors().add(getPropertyProcessors(false, false));
        }

        @Override
        protected void initColumns(int afterCol) {
            for (I5_ROOT_OBJECTS section : I5_ROOT_OBJECTS.values()) {
                if (section.isIUCLID5() && section.isScientificPart() && section.isSupported() && !section.isNanoMaterialTemplate()) {
                    int last = mergedProperties.size();
                    mergedProperties.put("http://www.opentox.org/echaEndpoints.owl#" + section.name(), last);
                    Cell hcell = sheet.getRow(0).createCell(last + afterCol);
                    hcell.setCellStyle(hstyle);
                    hcell.setCellType(CellType.STRING);
                    hcell.setCellValue(section.getNumber() + ". " + section.getTitle());
                    sheet.autoSizeColumn(hcell.getColumnIndex(), true);
                    // initially hide all columns, unhide if data is added
                    // to
                    sheet.setColumnHidden(hcell.getColumnIndex(), true);
                }
            }
        }
    }, media, filenamePrefix);
}
Also used : SubstanceName(ambit2.base.data.substance.SubstanceName) OutputStreamConvertor(ambit2.rest.OutputStreamConvertor) SubstanceOwner(ambit2.base.data.substance.SubstanceOwner) SubstanceUUID(ambit2.base.data.substance.SubstanceUUID) I5_ROOT_OBJECTS(net.idea.i5.io.I5_ROOT_OBJECTS) StructureRecordXLSXReporter(ambit2.db.reporters.xlsx.StructureRecordXLSXReporter) Cell(org.apache.poi.ss.usermodel.Cell) SubstancePublicName(ambit2.base.data.substance.SubstancePublicName)

Example 5 with SubstanceUUID

use of ambit2.base.data.substance.SubstanceUUID in project ambit-mirror by ideaconsult.

the class SubstanceDatasetResource method createCSVReporter.

protected IProcessor<Q, Representation> createCSVReporter(String filenamePrefix) {
    groupProperties.add(new SubstancePublicName());
    groupProperties.add(new SubstanceName());
    groupProperties.add(new SubstanceUUID());
    groupProperties.add(new SubstanceOwner());
    CSVReporter csvreporter = new CSVReporter(getRequest().getRootRef().toString(), getTemplate(), groupProperties, String.format("%s%s", getRequest().getRootRef(), "")) {

        @Override
        protected void configurePropertyProcessors() {
            getProcessors().add(getPropertyProcessors(false, false));
        }
    };
    try {
        Form form = getParams();
        csvreporter.setNumberofHeaderLines(Integer.parseInt(form.getFirstValue("headerlines")));
    } catch (Exception x) {
        csvreporter.setNumberofHeaderLines(3);
    }
    return new OutputWriterConvertor<SubstanceRecord, Q>(csvreporter, MediaType.TEXT_CSV, filenamePrefix);
}
Also used : SubstanceName(ambit2.base.data.substance.SubstanceName) SubstanceOwner(ambit2.base.data.substance.SubstanceOwner) SubstanceUUID(ambit2.base.data.substance.SubstanceUUID) Form(org.restlet.data.Form) OutputWriterConvertor(net.idea.restnet.db.convertors.OutputWriterConvertor) CSVReporter(ambit2.db.reporters.CSVReporter) SubstancePublicName(ambit2.base.data.substance.SubstancePublicName) AmbitException(net.idea.modbcum.i.exceptions.AmbitException) ResourceException(org.restlet.resource.ResourceException)

Aggregations

SubstanceName (ambit2.base.data.substance.SubstanceName)8 SubstanceOwner (ambit2.base.data.substance.SubstanceOwner)8 SubstancePublicName (ambit2.base.data.substance.SubstancePublicName)8 SubstanceUUID (ambit2.base.data.substance.SubstanceUUID)8 SubstanceRecord (ambit2.base.data.SubstanceRecord)6 ResourceException (org.restlet.resource.ResourceException)6 AmbitException (net.idea.modbcum.i.exceptions.AmbitException)5 Form (org.restlet.data.Form)4 Property (ambit2.base.data.Property)2 Protocol (ambit2.base.data.study.Protocol)2 SubstanceEndpointsBundle (ambit2.base.data.substance.SubstanceEndpointsBundle)2 SubstanceProperty (ambit2.base.data.substance.SubstanceProperty)2 ProtocolEffectRecord2SubstanceProperty (ambit2.core.io.study.ProtocolEffectRecord2SubstanceProperty)2 ReadSubstanceChemicalsUnionByBundle (ambit2.db.update.bundle.substance.ReadSubstanceChemicalsUnionByBundle)2 ReadSubstancesByBundle (ambit2.db.update.bundle.substance.ReadSubstancesByBundle)2 ResultSet (java.sql.ResultSet)2 OutputWriterConvertor (net.idea.restnet.db.convertors.OutputWriterConvertor)2 Reference (org.restlet.data.Reference)2 LiteratureEntry (ambit2.base.data.LiteratureEntry)1 EffectRecord (ambit2.base.data.study.EffectRecord)1