Search in sources :

Example 26 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class EntityUtils method getTypedValue.

/**
 * Convert a string value to a typed value based on the attribute data type.
 *
 * @param valueStr      string value
 * @param attr          attribute
 * @param entityManager entity manager used to convert referenced entity values
 * @return typed value
 */
public static Object getTypedValue(String valueStr, Attribute attr, EntityManager entityManager) {
    if (valueStr == null)
        return null;
    switch(attr.getDataType()) {
        case BOOL:
            return Boolean.valueOf(valueStr);
        case CATEGORICAL:
        case FILE:
        case XREF:
            EntityType xrefEntity = attr.getRefEntity();
            Object xrefIdValue = getTypedValue(valueStr, xrefEntity.getIdAttribute(), entityManager);
            return entityManager.getReference(xrefEntity, xrefIdValue);
        case CATEGORICAL_MREF:
        case MREF:
        case ONE_TO_MANY:
            EntityType mrefEntity = attr.getRefEntity();
            List<String> mrefIdStrValues = ListEscapeUtils.toList(valueStr);
            return mrefIdStrValues.stream().map(mrefIdStrValue -> getTypedValue(mrefIdStrValue, mrefEntity.getIdAttribute(), entityManager)).map(mrefIdValue -> entityManager.getReference(mrefEntity, mrefIdValue)).collect(toList());
        case COMPOUND:
            throw new IllegalArgumentException("Compound attribute has no value");
        case DATE:
            try {
                return parseLocalDate(valueStr);
            } catch (DateTimeParseException e) {
                throw new MolgenisDataException(format(FAILED_TO_PARSE_ATTRIBUTE_AS_DATE_MESSAGE, attr.getName(), valueStr), e);
            }
        case DATE_TIME:
            try {
                return parseInstant(valueStr);
            } catch (DateTimeParseException e) {
                throw new MolgenisDataException(format(FAILED_TO_PARSE_ATTRIBUTE_AS_DATETIME_MESSAGE, attr.getName(), valueStr), e);
            }
        case DECIMAL:
            return Double.valueOf(valueStr);
        case EMAIL:
        case ENUM:
        case HTML:
        case HYPERLINK:
        case SCRIPT:
        case STRING:
        case TEXT:
            return valueStr;
        case INT:
            return Integer.valueOf(valueStr);
        case LONG:
            return Long.valueOf(valueStr);
        default:
            throw new UnexpectedEnumException(attr.getDataType());
    }
}
Also used : EntityType(org.molgenis.data.meta.model.EntityType) ListEscapeUtils(org.molgenis.util.ListEscapeUtils) Iterables(com.google.common.collect.Iterables) Pair(org.molgenis.util.Pair) Attribute(org.molgenis.data.meta.model.Attribute) Tag(org.molgenis.data.meta.model.Tag) AttributeType(org.molgenis.data.meta.AttributeType) Iterator(java.util.Iterator) EntityTypeUtils(org.molgenis.data.support.EntityTypeUtils) MolgenisDateFormat(org.molgenis.data.util.MolgenisDateFormat) EntityType(org.molgenis.data.meta.model.EntityType) PACKAGE_SYSTEM(org.molgenis.data.system.model.RootSystemPackage.PACKAGE_SYSTEM) String.format(java.lang.String.format) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) Objects(java.util.Objects) DateTimeParseException(java.time.format.DateTimeParseException) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) StreamSupport.stream(java.util.stream.StreamSupport.stream) COMPOUND(org.molgenis.data.meta.AttributeType.COMPOUND) DataService(org.molgenis.data.DataService) Package(org.molgenis.data.meta.model.Package) MolgenisDataException(org.molgenis.data.MolgenisDataException) EntityManager(org.molgenis.data.EntityManager) Entity(org.molgenis.data.Entity) DateTimeParseException(java.time.format.DateTimeParseException) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) MolgenisDataException(org.molgenis.data.MolgenisDataException)

Example 27 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class EntityUtils method hashCode.

public static int hashCode(Entity entity) {
    int h = 0;
    for (Attribute attr : entity.getEntityType().getAtomicAttributes()) {
        int hValue = 0;
        String attrName = attr.getName();
        switch(attr.getDataType()) {
            case BOOL:
                hValue = Objects.hashCode(entity.getBoolean(attrName));
                break;
            case CATEGORICAL:
            case FILE:
            case XREF:
                Entity xrefValue = entity.getEntity(attrName);
                Object xrefIdValue = xrefValue != null ? xrefValue.getIdValue() : null;
                hValue = Objects.hashCode(xrefIdValue);
                break;
            case CATEGORICAL_MREF:
            case ONE_TO_MANY:
            case MREF:
                for (Entity mrefValue : entity.getEntities(attrName)) {
                    Object mrefIdValue = mrefValue != null ? mrefValue.getIdValue() : null;
                    hValue += Objects.hashCode(mrefIdValue);
                }
                break;
            case COMPOUND:
                throw new RuntimeException(format("Invalid data type [%s]", attr.getDataType()));
            case DATE:
                hValue = Objects.hashCode(entity.getLocalDate(attrName));
                break;
            case DATE_TIME:
                hValue = Objects.hashCode(entity.getInstant(attrName));
                break;
            case DECIMAL:
                hValue = Objects.hashCode(entity.getDouble(attrName));
                break;
            case EMAIL:
            case ENUM:
            case HTML:
            case HYPERLINK:
            case SCRIPT:
            case STRING:
            case TEXT:
                hValue = Objects.hashCode(entity.getString(attrName));
                break;
            case INT:
                hValue = Objects.hashCode(entity.getInt(attrName));
                break;
            case LONG:
                hValue = Objects.hashCode(entity.getLong(attrName));
                break;
            default:
                throw new UnexpectedEnumException(attr.getDataType());
        }
        h += Objects.hashCode(attrName) ^ hValue;
    }
    int result = entity.getEntityType().getId().hashCode();
    return 31 * result + h;
}
Also used : Entity(org.molgenis.data.Entity) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) Attribute(org.molgenis.data.meta.model.Attribute)

Example 28 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class DataExplorerController method download.

@PostMapping("/download")
public void download(@RequestParam("dataRequest") String dataRequestStr, HttpServletResponse response) throws IOException {
    DataExplorerDownloadHandler download = new DataExplorerDownloadHandler(dataService, attrMetaFactory);
    // Workaround because binding with @RequestBody is not possible:
    // http://stackoverflow.com/a/9970672
    dataRequestStr = URLDecoder.decode(dataRequestStr, "UTF-8");
    LOG.info("Download request: [" + dataRequestStr + "]");
    DataRequest dataRequest = gson.fromJson(dataRequestStr, DataRequest.class);
    final String fileName = getDownloadFilename(dataRequest.getEntityName(), LocalDateTime.now(), dataRequest.getDownloadType());
    ServletOutputStream outputStream;
    switch(dataRequest.getDownloadType()) {
        case DOWNLOAD_TYPE_CSV:
            response.setContentType("text/csv");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            outputStream = response.getOutputStream();
            download.writeToCsv(dataRequest, outputStream, ',');
            break;
        case DOWNLOAD_TYPE_XLSX:
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            outputStream = response.getOutputStream();
            download.writeToExcel(dataRequest, outputStream);
            break;
        default:
            throw new UnexpectedEnumException(dataRequest.getDownloadType());
    }
}
Also used : UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) ServletOutputStream(javax.servlet.ServletOutputStream) DataExplorerDownloadHandler(org.molgenis.dataexplorer.download.DataExplorerDownloadHandler)

Example 29 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class DataExplorerController method getModules.

/**
 * Returns modules configuration for this entity based on current user permissions.
 */
@GetMapping("/modules")
@ResponseBody
public ModulesConfigResponse getModules(@RequestParam("entity") String entityTypeId) {
    boolean modAggregates = dataExplorerSettings.getModAggregates();
    boolean modAnnotators = dataExplorerSettings.getModAnnotators();
    boolean modData = dataExplorerSettings.getModData();
    boolean modReports = dataExplorerSettings.getModReports();
    if (modAggregates) {
        modAggregates = dataService.getCapabilities(entityTypeId).contains(RepositoryCapability.AGGREGATEABLE);
    }
    // set data explorer permission
    Permission pluginPermission = null;
    if (permissionService.hasPermission(new EntityTypeIdentity(entityTypeId), EntityTypePermission.WRITE))
        pluginPermission = WRITE;
    else if (permissionService.hasPermission(new EntityTypeIdentity(entityTypeId), EntityTypePermission.READ))
        pluginPermission = READ;
    else if (permissionService.hasPermission(new EntityTypeIdentity(entityTypeId), EntityTypePermission.COUNT))
        pluginPermission = Permission.COUNT;
    ModulesConfigResponse modulesConfig = new ModulesConfigResponse();
    String aggregatesTitle = messageSource.getMessage("dataexplorer_aggregates_title", new Object[] {}, LocaleContextHolder.getLocale());
    if (pluginPermission != null) {
        switch(pluginPermission) {
            case COUNT:
                if (modAggregates) {
                    modulesConfig.add(new ModuleConfig("aggregates", aggregatesTitle, "grid-icon.png"));
                }
                break;
            case READ:
            case WRITE:
                if (modData) {
                    modulesConfig.add(new ModuleConfig("data", "Data", "grid-icon.png"));
                }
                if (modAggregates) {
                    modulesConfig.add(new ModuleConfig("aggregates", aggregatesTitle, "aggregate-icon.png"));
                }
                if (modAnnotators && pluginPermission == WRITE) {
                    modulesConfig.add(new ModuleConfig("annotators", "Annotators", "annotator-icon.png"));
                }
                if (modReports) {
                    String modEntitiesReportName = dataExplorerSettings.getEntityReport(entityTypeId);
                    if (modEntitiesReportName != null) {
                        modulesConfig.add(new ModuleConfig("entitiesreport", modEntitiesReportName, "report-icon.png"));
                    }
                }
                break;
            case NONE:
                break;
            default:
                throw new UnexpectedEnumException(pluginPermission);
        }
    }
    return modulesConfig;
}
Also used : EntityTypeIdentity(org.molgenis.data.security.EntityTypeIdentity) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) Permission(org.molgenis.security.core.Permission) EntityTypePermission(org.molgenis.data.security.EntityTypePermission)

Example 30 with UnexpectedEnumException

use of org.molgenis.util.UnexpectedEnumException in project molgenis by molgenis.

the class ExcelSheetWriter method toValue.

private String toValue(Object obj) {
    String value;
    if (obj == null) {
        value = null;
    } else if (obj instanceof Entity) {
        if (getEntityWriteMode() != null) {
            switch(getEntityWriteMode()) {
                case ENTITY_IDS:
                    value = ((Entity) obj).getIdValue().toString();
                    break;
                case ENTITY_LABELS:
                    Object labelValue = ((Entity) obj).getLabelValue();
                    value = labelValue != null ? labelValue.toString() : null;
                    break;
                default:
                    throw new UnexpectedEnumException(getEntityWriteMode());
            }
        } else {
            Object labelValue = ((Entity) obj).getLabelValue();
            value = labelValue != null ? labelValue.toString() : null;
        }
    } else if (obj instanceof Iterable<?>) {
        StringBuilder strBuilder = new StringBuilder();
        for (Object listItem : (Iterable<?>) obj) {
            if (strBuilder.length() > 0)
                strBuilder.append(',');
            strBuilder.append(toValue(listItem));
        }
        // TODO apply cell processors to list elements?
        value = strBuilder.toString();
    } else {
        value = obj.toString();
    }
    return AbstractCellProcessor.processCell(value, false, cellProcessors);
}
Also used : Entity(org.molgenis.data.Entity) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException)

Aggregations

UnexpectedEnumException (org.molgenis.util.UnexpectedEnumException)39 AttributeType (org.molgenis.data.meta.AttributeType)26 Attribute (org.molgenis.data.meta.model.Attribute)20 Entity (org.molgenis.data.Entity)13 Instant (java.time.Instant)10 LocalDate (java.time.LocalDate)10 String.format (java.lang.String.format)4 Collectors.toList (java.util.stream.Collectors.toList)4 MolgenisDataException (org.molgenis.data.MolgenisDataException)4 Iterator (java.util.Iterator)3 List (java.util.List)3 StreamSupport.stream (java.util.stream.StreamSupport.stream)3 EntityType (org.molgenis.data.meta.model.EntityType)3 UTC (java.time.ZoneOffset.UTC)2 ChronoUnit (java.time.temporal.ChronoUnit)2 Collection (java.util.Collection)2 Objects.requireNonNull (java.util.Objects.requireNonNull)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Collectors.joining (java.util.stream.Collectors.joining)2 Stream (java.util.stream.Stream)2