Search in sources :

Example 36 with MolgenisDataException

use of org.molgenis.data.MolgenisDataException in project molgenis by molgenis.

the class ImportWizardController method importFile.

private ImportRun importFile(HttpServletRequest request, File file, String action, Boolean notify, String packageId) {
    // no action specified? default is ADD just like the importerPlugin
    ImportRun importRun;
    String fileExtension = getExtension(file.getName());
    DatabaseAction databaseAction = getDatabaseAction(file, action);
    if (fileExtension.contains("vcf") && dataService.hasRepository(getBaseName(file.getName()))) {
        throw new MolgenisDataException("A repository with name " + getBaseName(file.getName()) + " already exists");
    }
    ImportService importService = importServiceFactory.getImportService(file.getName());
    RepositoryCollection repositoryCollection = fileRepositoryCollectionFactory.createFileRepositoryCollection(file);
    importRun = importRunService.addImportRun(SecurityUtils.getCurrentUsername(), Boolean.TRUE.equals(notify));
    asyncImportJobs.execute(new ImportJob(importService, SecurityContextHolder.getContext(), repositoryCollection, databaseAction, importRun.getId(), importRunService, request.getSession(), packageId));
    return importRun;
}
Also used : DatabaseAction(org.molgenis.data.DatabaseAction) RepositoryCollection(org.molgenis.data.RepositoryCollection) MolgenisDataException(org.molgenis.data.MolgenisDataException)

Example 37 with MolgenisDataException

use of org.molgenis.data.MolgenisDataException 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 38 with MolgenisDataException

use of org.molgenis.data.MolgenisDataException in project molgenis by molgenis.

the class AccountServiceImpl method createUser.

@Override
@RunAsSystem
@Transactional
public void createUser(User user, String baseActivationUri) throws UsernameAlreadyExistsException, EmailAlreadyExistsException {
    // Check if username already exists
    if (userService.getUser(user.getUsername()) != null) {
        throw new UsernameAlreadyExistsException("Username '" + user.getUsername() + "' already exists.");
    }
    // Check if email already exists
    if (userService.getUserByEmail(user.getEmail()) != null) {
        throw new EmailAlreadyExistsException("Email '" + user.getEmail() + "' is already registered.");
    }
    // collect activation info
    String activationCode = idGenerator.generateId(SECURE_RANDOM);
    List<String> activationEmailAddresses;
    if (authenticationSettings.getSignUpModeration()) {
        activationEmailAddresses = userService.getSuEmailAddresses();
        if (activationEmailAddresses == null || activationEmailAddresses.isEmpty())
            throw new MolgenisDataException("Administrator account is missing required email address");
    } else {
        String activationEmailAddress = user.getEmail();
        if (activationEmailAddress == null || activationEmailAddress.isEmpty())
            throw new MolgenisDataException("User '" + user.getUsername() + "' is missing required email address");
        activationEmailAddresses = asList(activationEmailAddress);
    }
    // create user
    user.setActivationCode(activationCode);
    user.setActive(false);
    dataService.add(USER, user);
    LOG.debug("created user " + user.getUsername());
    // add user to group
    Group group = dataService.query(GROUP, Group.class).eq(NAME, ALL_USER_GROUP).findOne();
    GroupMember groupMember = null;
    if (group != null) {
        groupMember = groupMemberFactory.create();
        groupMember.setGroup(group);
        groupMember.setUser(user);
        dataService.add(GROUP_MEMBER, groupMember);
    }
    // send activation email
    URI activationUri = URI.create(baseActivationUri + '/' + activationCode);
    try {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(activationEmailAddresses.toArray(new String[] {}));
        mailMessage.setSubject("User registration for " + appSettings.getTitle());
        mailMessage.setText(createActivationEmailText(user, activationUri));
        mailSender.send(mailMessage);
    } catch (MailException mce) {
        LOG.error("Could not send signup mail", mce);
        if (groupMember != null) {
            dataService.delete(GROUP_MEMBER, groupMember);
        }
        dataService.delete(USER, user);
        throw new MolgenisUserException("An error occurred. Please contact the administrator. You are not signed up!");
    }
    LOG.debug("send activation email for user " + user.getUsername() + " to " + StringUtils.join(activationEmailAddresses, ','));
}
Also used : Group(org.molgenis.data.security.auth.Group) GroupMember(org.molgenis.data.security.auth.GroupMember) MolgenisDataException(org.molgenis.data.MolgenisDataException) SimpleMailMessage(org.springframework.mail.SimpleMailMessage) MolgenisUserException(org.molgenis.security.user.MolgenisUserException) MailException(org.springframework.mail.MailException) URI(java.net.URI) RunAsSystem(org.molgenis.security.core.runas.RunAsSystem) Transactional(org.springframework.transaction.annotation.Transactional)

Example 39 with MolgenisDataException

use of org.molgenis.data.MolgenisDataException in project molgenis by molgenis.

the class MultiAllelicResultFilterTest method filterResultsMergeMultilineMismatchChrom.

@Test
public void filterResultsMergeMultilineMismatchChrom() {
    MultiAllelicResultFilter filter = new MultiAllelicResultFilter(Collections.singletonList(attributeFactory.create().setName("annotation").setDataType(STRING)), true, vcfAttributes);
    try {
        filter.filterResults(Arrays.asList(resultEntity10, entityMismatchChrom), entity10, false);
        Assert.fail("Should throw exception for mismatching chromosomes");
    } catch (MolgenisDataException actual) {
        assertEquals(actual.getMessage(), "Mismatch in location! Location{chrom=1, pos=100} vs Location{chrom=2, pos=100}");
    }
}
Also used : MolgenisDataException(org.molgenis.data.MolgenisDataException) MultiAllelicResultFilter(org.molgenis.data.annotation.core.filter.MultiAllelicResultFilter) Test(org.testng.annotations.Test) AbstractMolgenisSpringTest(org.molgenis.data.AbstractMolgenisSpringTest)

Example 40 with MolgenisDataException

use of org.molgenis.data.MolgenisDataException in project molgenis by molgenis.

the class SnpEffRunner method getSnpEffects.

@SuppressWarnings("resource")
public Iterator<Entity> getSnpEffects(Iterator<Entity> source, final File inputVcf) {
    try {
        if (!source.hasNext())
            return Collections.<Entity>emptyList().iterator();
        // get meta data by peeking at the first entity (work-around for issue #4701)
        PeekingIterator<Entity> peekingSourceIterator = Iterators.peekingIterator(source);
        EntityType sourceEMD = peekingSourceIterator.peek().getEntityType();
        List<String> params = Arrays.asList("-Xmx2g", getSnpEffPath(), "hg19", "-noStats", "-noLog", "-lof", "-canon", "-ud", "0", "-spliceSiteSize", "5");
        File outputVcf = jarRunner.runJar(NAME, params, inputVcf);
        VcfRepository repo = new VcfRepository(outputVcf, "SNPEFF_OUTPUT_VCF_" + inputVcf.getName(), vcfAttributes, entityTypeFactory, attributeFactory);
        PeekingIterator<Entity> snpEffResultIterator = peekingIterator(repo.iterator());
        return new Iterator<Entity>() {

            final LinkedList<Entity> effects = Lists.newLinkedList();

            @Override
            public boolean hasNext() {
                return (peekingSourceIterator.hasNext() || !effects.isEmpty());
            }

            @Override
            public Entity next() {
                if (effects.isEmpty()) {
                    // go to next source entity and get effects
                    Entity sourceEntity = peekingSourceIterator.next();
                    String chromosome = sourceEntity.getString(VcfAttributes.CHROM);
                    Integer position = sourceEntity.getInt(VcfAttributes.POS);
                    if (chromosome != null && position != null) {
                        Entity snpEffEntity = getSnpEffEntity(snpEffResultIterator, chromosome, position);
                        if (snpEffEntity != null) {
                            effects.addAll(getSnpEffectsFromSnpEffEntity(sourceEntity, snpEffEntity, getTargetEntityType(sourceEMD)));
                        } else {
                            effects.add(getEmptyEffectsEntity(sourceEntity, getTargetEntityType(sourceEMD)));
                        }
                    } else {
                        effects.add(getEmptyEffectsEntity(sourceEntity, getTargetEntityType(sourceEMD)));
                    }
                }
                return effects.removeFirst();
            }
        };
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (InterruptedException e) {
        throw new MolgenisDataException("Exception running SnpEff", e);
    }
}
Also used : DynamicEntity(org.molgenis.data.support.DynamicEntity) Entity(org.molgenis.data.Entity) VcfRepository(org.molgenis.data.vcf.VcfRepository) EntityType(org.molgenis.data.meta.model.EntityType) MolgenisDataException(org.molgenis.data.MolgenisDataException) PeekingIterator(com.google.common.collect.PeekingIterator) Iterators.peekingIterator(com.google.common.collect.Iterators.peekingIterator) File.createTempFile(java.io.File.createTempFile)

Aggregations

MolgenisDataException (org.molgenis.data.MolgenisDataException)51 Entity (org.molgenis.data.Entity)16 Attribute (org.molgenis.data.meta.model.Attribute)11 EntityType (org.molgenis.data.meta.model.EntityType)11 Test (org.testng.annotations.Test)7 IOException (java.io.IOException)6 List (java.util.List)6 DynamicEntity (org.molgenis.data.support.DynamicEntity)6 File (java.io.File)5 AttributeType (org.molgenis.data.meta.AttributeType)5 UnexpectedEnumException (org.molgenis.util.UnexpectedEnumException)5 Instant (java.time.Instant)4 LocalDate (java.time.LocalDate)4 Collectors.toList (java.util.stream.Collectors.toList)4 DataService (org.molgenis.data.DataService)4 RepositoryCollection (org.molgenis.data.RepositoryCollection)4 String.format (java.lang.String.format)3 DateTimeParseException (java.time.format.DateTimeParseException)3 Map (java.util.Map)3 Stream (java.util.stream.Stream)3