private List<? extends Authority> getUserPermissions(String userId, String authorityPrefix) {
    MolgenisUser molgenisUser =
        dataService.findOne(MolgenisUser.ENTITY_NAME, userId, MolgenisUser.class);
    if (molgenisUser == null) throw new RuntimeException("unknown user id [" + userId + "]");
    List<Authority> userPermissions = getUserPermissions(molgenisUser, authorityPrefix);

    Iterable<MolgenisGroupMember> groupMembersIt =
        dataService.findAll(
            MolgenisGroupMember.ENTITY_NAME,
            new QueryImpl().eq(MolgenisGroupMember.MOLGENISUSER, molgenisUser),
            MolgenisGroupMember.class);

    if (groupMembersIt == null) {
      return Collections.emptyList();
    }

    List<MolgenisGroupMember> groupMembers = Lists.newArrayList(groupMembersIt);

    if (groupMembers != null && !groupMembers.isEmpty()) {
      List<MolgenisGroup> molgenisGroups =
          Lists.transform(
              groupMembers,
              new Function<MolgenisGroupMember, MolgenisGroup>() {
                @Override
                public MolgenisGroup apply(MolgenisGroupMember molgenisGroupMember) {
                  return molgenisGroupMember.getMolgenisGroup();
                }
              });
      List<Authority> groupAuthorities = getGroupPermissions(molgenisGroups, authorityPrefix);
      if (groupAuthorities != null && !groupAuthorities.isEmpty())
        userPermissions.addAll(groupAuthorities);
    }

    return userPermissions;
  }
  private EntityMapping toEntityMapping(Entity entityMappingEntity) {
    String identifier = entityMappingEntity.getString(EntityMappingMetaData.IDENTIFIER);

    EntityType targetEntityType;
    try {
      targetEntityType =
          dataService.getEntityType(
              entityMappingEntity.getString(EntityMappingMetaData.TARGET_ENTITY_TYPE));
    } catch (UnknownEntityException uee) {
      LOG.error(uee.getMessage());
      targetEntityType = null;
    }

    EntityType sourceEntityType;
    try {
      sourceEntityType =
          dataService.getEntityType(
              entityMappingEntity.getString(EntityMappingMetaData.SOURCE_ENTITY_TYPE));
    } catch (UnknownEntityException uee) {
      LOG.error(uee.getMessage());
      sourceEntityType = null;
    }

    List<Entity> attributeMappingEntities =
        Lists.<Entity>newArrayList(
            entityMappingEntity.getEntities(EntityMappingMetaData.ATTRIBUTE_MAPPINGS));
    List<AttributeMapping> attributeMappings =
        attributeMappingRepository.getAttributeMappings(
            attributeMappingEntities, sourceEntityType, targetEntityType);

    return new EntityMapping(identifier, sourceEntityType, targetEntityType, attributeMappings);
  }
  @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
    // Run it as System
    // Remember the original context
    SecurityContext origCtx = SecurityContextHolder.getContext();
    try {
      // Set a SystemSecurityToken
      SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
      SecurityContextHolder.getContext().setAuthentication(new SystemSecurityToken());

      Query q =
          new QueryImpl()
              .eq(ObservableFeature.DATATYPE, FieldTypeEnum.CATEGORICAL.toString().toLowerCase());
      for (ObservableFeature categoricalFeature :
          dataService.findAll(ObservableFeature.ENTITY_NAME, q, ObservableFeature.class)) {
        OmxLookupTableRepository repo =
            new OmxLookupTableRepository(
                dataService, categoricalFeature.getIdentifier(), queryResolver);
        dataService.addRepository(repo);
      }
    } finally {
      // Set the original context back when method is finished
      SecurityContextHolder.setContext(origCtx);
    }
  }
  @RequestMapping(method = RequestMethod.GET)
  public String init(
      @RequestParam(value = "selectedDataSet", required = false) String selectedDataSetId,
      Model model) {
    Iterable<DataSet> allDataSets = dataService.findAll(DataSet.ENTITY_NAME, new QueryImpl());

    List<DataSet> dataSets = new ArrayList<DataSet>();
    for (DataSet dataSet : allDataSets) {
      if (selectedDataSetId == null) selectedDataSetId = dataSet.getId().toString();
      if (!dataSet.getProtocolUsed().getIdentifier().equals(PROTOCOL_IDENTIFIER))
        dataSets.add(dataSet);
    }
    model.addAttribute("dataSets", dataSets);

    List<String> mappedDataSets = new ArrayList<String>();
    if (selectedDataSetId != null) {
      model.addAttribute("selectedDataSet", selectedDataSetId);
      Iterable<DataSet> it =
          dataService.findAll(
              DataSet.ENTITY_NAME, new QueryImpl().like(DataSet.IDENTIFIER, selectedDataSetId));
      for (DataSet dataSet : it) {
        if (dataSet
            .getIdentifier()
            .startsWith(SecurityUtils.getCurrentUsername() + "-" + selectedDataSetId)) {
          String[] dataSetIds = dataSet.getIdentifier().toString().split("-");
          if (dataSetIds.length > 1) mappedDataSets.add(dataSetIds[2]);
        }
      }
    }
    model.addAttribute("mappedDataSets", mappedDataSets);
    return "EvaluationPlugin";
  }
  /**
   * @param entityName The name of the entity to update
   * @param attributeName The name of the attribute to update
   * @param request EntityCollectionBatchRequestV2
   * @param response HttpServletResponse
   * @throws Exception
   */
  @RequestMapping(value = "/{entityName}/{attributeName}", method = PUT)
  @ResponseStatus(OK)
  public synchronized void updateAttribute(
      @PathVariable("entityName") String entityName,
      @PathVariable("attributeName") String attributeName,
      @RequestBody @Valid EntityCollectionBatchRequestV2 request,
      HttpServletResponse response)
      throws Exception {
    final EntityMetaData meta = dataService.getEntityMetaData(entityName);
    if (meta == null) {
      throw createUnknownEntityException(entityName);
    }

    try {
      AttributeMetaData attr = meta.getAttribute(attributeName);
      if (attr == null) {
        throw createUnknownAttributeException(entityName, attributeName);
      }

      if (attr.isReadonly()) {
        throw createMolgenisDataAccessExceptionReadOnlyAttribute(entityName, attributeName);
      }

      final List<Entity> entities =
          request
              .getEntities()
              .stream()
              .filter(e -> e.size() == 2)
              .map(e -> this.restService.toEntity(meta, e))
              .collect(Collectors.toList());
      if (entities.size() != request.getEntities().size()) {
        throw createMolgenisDataExceptionIdentifierAndValue();
      }

      final List<Entity> updatedEntities = new ArrayList<Entity>();
      int count = 0;
      for (Entity entity : entities) {
        String id = checkForEntityId(entity, count);

        Entity originalEntity = dataService.findOne(entityName, id);
        if (originalEntity == null) {
          throw createUnknownEntityExceptionNotValidId(id);
        }

        Object value = this.restService.toEntityValue(attr, entity.get(attributeName));
        originalEntity.set(attributeName, value);
        updatedEntities.add(originalEntity);
        count++;
      }

      // update all entities
      this.dataService.update(entityName, updatedEntities.stream());
      response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_NO_CONTENT);
      throw e;
    }
  }
 private void registerNewIndexActionForDirtyJobs(IndexJobExecution indexJobExecution) {
   String id = indexJobExecution.getIndexActionJobID();
   dataService
       .findAll(
           IndexActionMetaData.INDEX_ACTION,
           new QueryImpl<IndexAction>().eq(IndexActionMetaData.INDEX_ACTION_GROUP_ATTR, id),
           IndexAction.class)
       .forEach(
           action ->
               indexActionRegisterService.register(
                   action.getEntityFullName(), action.getEntityId()));
   dataService.delete(IndexJobExecutionMeta.INDEX_JOB_EXECUTION, indexJobExecution);
 }
 private Map<String, String> getGenomeBrowserSetsToModel() {
   Map<String, String> genomeBrowserSets = new HashMap<String, String>();
   for (String entityName : dataService.getEntityNames()) {
     EntityMetaData entityMetaData = dataService.getEntityMetaData(entityName);
     AttributeMetaData attributeStartPosition =
         entityMetaData.getAttribute(MUTATION_START_POSITION);
     AttributeMetaData attributeId = entityMetaData.getAttribute(MUTATION_ID);
     AttributeMetaData attributeChromosome = entityMetaData.getAttribute(MUTATION_CHROMOSOME);
     if (attributeStartPosition != null && attributeId != null && attributeChromosome != null) {
       genomeBrowserSets.put(entityName, entityMetaData.getLabel());
     }
   }
   return genomeBrowserSets;
 }
 private Entity upsert(EntityMapping entityMapping) {
   List<Entity> attributeMappingEntities =
       attributeMappingRepository.upsert(entityMapping.getAttributeMappings());
   Entity entityMappingEntity;
   if (entityMapping.getIdentifier() == null) {
     entityMapping.setIdentifier(idGenerator.generateId());
     entityMappingEntity = toEntityMappingEntity(entityMapping, attributeMappingEntities);
     dataService.add(entityMappingMetaData.getName(), entityMappingEntity);
   } else {
     entityMappingEntity = toEntityMappingEntity(entityMapping, attributeMappingEntities);
     dataService.update(entityMappingMetaData.getName(), entityMappingEntity);
   }
   return entityMappingEntity;
 }
  // RULE: Feature can only belong to one Protocol in a DataSet.(see issue #1136)
  private void checkFeatureCanOnlyBelongToOneProtocolForOneDataSet() {
    // RULE: Feature can only belong to one Protocol in a DataSet. Check it (see issue #1136)
    Iterable<DataSet> dataSets = dataService.findAll(DataSet.ENTITY_NAME, DataSet.class);
    for (DataSet dataSet : dataSets) {
      List<Protocol> dataSetProtocols =
          ProtocolUtils.getProtocolDescendants(dataSet.getProtocolUsed(), true);

      for (Protocol protocol : dataSetProtocols) {
        for (ObservableFeature feature : protocol.getFeatures()) {
          for (Protocol p : dataSetProtocols) {
            if (!p.equals(protocol) && p.getFeatures().contains(feature)) {
              String message =
                  String.format(
                      "An ObservableFeature can only belong to one Protocol but feature '%s' belongs to both '%s' and '%s'",
                      feature.getIdentifier(), p.getIdentifier(), protocol.getIdentifier());

              throw new MolgenisValidationException(
                  Sets.newHashSet(
                      new ConstraintViolation(
                          message, feature.getIdentifier(), feature, null, null, 0)));
            }
          }
        }
      }
    }
  }
  @RunAsSystem
  public FileIngestJob createJob(FileIngestJobExecution fileIngestJobExecution) {
    dataService.add(FileIngestJobExecutionMetaData.ENTITY_NAME, fileIngestJobExecution);
    String username = fileIngestJobExecution.getUser();
    Progress progress = new ProgressImpl(fileIngestJobExecution, jobExecutionUpdater, mailSender);
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    RunAsUserToken runAsAuthentication =
        new RunAsUserToken(
            "Job Execution",
            username,
            null,
            userDetailsService.loadUserByUsername(username).getAuthorities(),
            null);
    Entity fileIngestEntity = fileIngestJobExecution.getFileIngest();
    Entity targetEntityEntity = fileIngestEntity.getEntity(FileIngestMetaData.ENTITY_META_DATA);
    String targetEntityName = targetEntityEntity.getString(EntityMetaDataMetaData.FULL_NAME);
    String url = fileIngestEntity.getString(FileIngestMetaData.URL);
    String loader = fileIngestEntity.getString(FileIngestMetaData.LOADER);
    String failureEmail = fileIngestEntity.getString(FileIngestMetaData.FAILURE_EMAIL);

    return new FileIngestJob(
        progress,
        transactionTemplate,
        runAsAuthentication,
        fileIngester,
        targetEntityName,
        url,
        loader,
        failureEmail,
        fileIngestJobExecution.getIdentifier());
  }
  @RequestMapping(value = "/{id:.+}", method = GET)
  public void getFile(@PathVariable("id") String id, HttpServletResponse response)
      throws IOException {
    FileMeta fileMeta = dataService.findOne(FileMeta.ENTITY_NAME, id, FileMeta.class);
    if (fileMeta == null) {
      response.setStatus(HttpStatus.NOT_FOUND.value());
    } else {

      java.io.File fileStoreFile = fileStore.getFile(fileMeta.getFilename());

      // if file meta data exists for this file
      String outputFilename = fileMeta.getFilename();

      String contentType = fileMeta.getContentType();
      if (contentType != null) {
        response.setContentType(contentType);
      }

      Long size = fileMeta.getSize();
      if (size != null) {
        response.setContentLength(size.intValue());
      }

      response.setHeader(
          "Content-Disposition", "attachment; filename=" + outputFilename.replace(" ", "_"));

      InputStream is = new FileInputStream(fileStoreFile);
      try {
        FileCopyUtils.copy(is, response.getOutputStream());
      } finally {
        is.close();
      }
    }
  }
  @RequestMapping(
      value = "/aggregate",
      method = RequestMethod.POST,
      produces = "application/json",
      consumes = "application/json")
  @ResponseBody
  public AggregateResponse aggregate(@Valid @RequestBody AggregateRequest request) {
    // TODO create utility class to extract info from entity/attribute uris
    String[] attributeUriTokens = request.getAttributeUri().split("/");
    String entityName = attributeUriTokens[3];
    String attributeName = attributeUriTokens[5];
    QueryImpl q = request.getQ() != null ? new QueryImpl(request.getQ()) : new QueryImpl();

    EntityMetaData entityMeta = dataService.getEntityMetaData(entityName);
    AttributeMetaData attributeMeta = entityMeta.getAttribute(attributeName);
    FieldTypeEnum dataType = attributeMeta.getDataType().getEnumType();
    if (dataType != FieldTypeEnum.BOOL && dataType != FieldTypeEnum.CATEGORICAL) {
      throw new RuntimeException("Unsupported data type " + dataType);
    }

    EntityMetaData refEntityMeta = null;
    String refAttributeName = null;
    if (dataType == FieldTypeEnum.CATEGORICAL) {
      refEntityMeta = attributeMeta.getRefEntity();
      refAttributeName = refEntityMeta.getLabelAttribute().getName();
    }
    Map<String, Integer> aggregateMap = new HashMap<String, Integer>();
    for (Entity entity : dataService.findAll(entityName, q)) {
      String val;
      switch (dataType) {
        case BOOL:
          val = entity.getString(attributeName);
          break;
        case CATEGORICAL:
          Entity refEntity = (Entity) entity.get(attributeName);
          val = refEntity.getString(refAttributeName);
          break;
        default:
          throw new RuntimeException("Unsupported data type " + dataType);
      }

      Integer count = aggregateMap.get(val);
      if (count == null) aggregateMap.put(val, 1);
      else aggregateMap.put(val, count + 1);
    }
    return new AggregateResponse(aggregateMap);
  }
 @Override
 public void unloadCatalog(String id) throws UnknownCatalogException {
   Protocol protocol =
       dataService.findOne(
           Protocol.ENTITY_NAME, new QueryImpl().eq(Protocol.ID, id), Protocol.class);
   if (protocol == null) throw new UnknownCatalogException("Catalog [" + id + "] does not exist");
   setProtocolActive(protocol, false);
 }
 @Override
 public boolean isCatalogActivated(String id) throws UnknownCatalogException {
   Protocol protocol =
       dataService.findOne(
           Protocol.ENTITY_NAME, new QueryImpl().eq(Protocol.ID, id), Protocol.class);
   if (protocol == null) throw new UnknownCatalogException("Catalog [" + id + "] does not exist");
   return protocol.getActive();
 }
 @Override
 public Catalog getCatalog(String id) throws UnknownCatalogException {
   Protocol protocol =
       dataService.findOne(
           Protocol.ENTITY_NAME, new QueryImpl().eq(Protocol.ID, id), Protocol.class);
   if (protocol == null) throw new UnknownCatalogException("Catalog [" + id + "] does not exist");
   return new OmxCatalog(protocol, dataService);
 }
 @Override
 public boolean isCatalogOfStudyDefinitionLoaded(String id)
     throws UnknownCatalogException, UnknownStudyDefinitionException {
   StudyDataRequest studyDataRequest =
       dataService.findOne(
           StudyDataRequest.ENTITY_NAME,
           new QueryImpl().eq(StudyDataRequest.ID, Integer.valueOf(id)),
           StudyDataRequest.class);
   if (studyDataRequest == null)
     throw new UnknownStudyDefinitionException("Study definition [" + id + "] does not exist");
   Protocol protocol =
       dataService.findOne(
           Protocol.ENTITY_NAME, new QueryImpl().eq(Protocol.ID, id), Protocol.class);
   if (protocol == null)
     throw new UnknownCatalogException("No catalog defined for study definition [" + id + "]");
   return protocol.getActive();
 }
  @Test
  public void deleteNoMetadata() throws IOException {
    when(dataService.findOne(
            DataSet.ENTITY_NAME, new QueryImpl().eq(DataSet.IDENTIFIER, "dataset1")))
        .thenReturn(dataset);

    dataSetDeleterServiceImpl.deleteData("dataset1");
    verify(dataService, Mockito.times(0)).delete(DataSet.ENTITY_NAME, dataset);
  }
  @RequestMapping(value = "/{entityName}/{id:.+}", method = POST, params = "_method=GET")
  @ResponseBody
  public Map<String, Object> retrieveEntityPost(
      @PathVariable("entityName") String entityName,
      @PathVariable("id") Object id,
      @RequestParam(value = "attrs", required = false) AttributeFilter attributeFilter) {
    EntityMetaData entityMeta = dataService.getEntityMetaData(entityName);
    Fetch fetch =
        AttributeFilterToFetchConverter.convert(
            attributeFilter, entityMeta, languageService.getCurrentUserLanguageCode());

    Entity entity = dataService.findOne(entityName, id, fetch);
    if (entity == null) {
      throw new UnknownEntityException(entityName + " [" + id + "] not found");
    }

    return createEntityResponse(entity, fetch, true);
  }
  @RequestMapping(value = "/download", method = POST)
  public void download(
      @RequestParam("dataRequest") String dataRequestStr, HttpServletResponse response)
      throws IOException {
    // Workaround because binding with @RequestBody is not possible:
    // http://stackoverflow.com/a/9970672
    dataRequestStr = URLDecoder.decode(dataRequestStr, "UTF-8");
    logger.info("Download request: [" + dataRequestStr + "]");
    DataRequest dataRequest =
        new GsonHttpMessageConverter().getGson().fromJson(dataRequestStr, DataRequest.class);

    String entityName = dataRequest.getEntityName();
    EntityMetaData entityMetaData = dataService.getEntityMetaData(entityName);
    final Set<String> attributes = new HashSet<String>(dataRequest.getAttributeNames());
    String fileName =
        entityName + '_' + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".csv";

    response.setContentType("text/csv");
    response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

    CsvWriter csvWriter = new CsvWriter(response.getOutputStream());
    try {
      csvWriter.writeAttributeNames(
          Iterables.transform(
              Iterables.filter(
                  entityMetaData.getAtomicAttributes(),
                  new Predicate<AttributeMetaData>() {
                    @Override
                    public boolean apply(AttributeMetaData attributeMetaData) {
                      return attributes.contains(attributeMetaData.getName());
                    }
                  }),
              new Function<AttributeMetaData, String>() {
                @Override
                public String apply(AttributeMetaData attributeMetaData) {
                  return attributeMetaData.getName();
                }
              }));
      csvWriter.add(dataService.findAll(entityName, dataRequest.getQuery()));
    } finally {
      csvWriter.close();
    }
  }
  private void replaceUserPermissions(
      List<UserAuthority> entityAuthorities, String userId, String authorityType) {
    MolgenisUser molgenisUser =
        dataService.findOne(MolgenisUser.ENTITY_NAME, userId, MolgenisUser.class);
    if (molgenisUser == null) throw new RuntimeException("unknown user id [" + userId + "]");

    // inject user
    for (UserAuthority entityAuthority : entityAuthorities)
      entityAuthority.setMolgenisUser(molgenisUser);

    // delete old plugin authorities
    List<? extends Authority> oldEntityAuthorities =
        getUserPermissions(molgenisUser, authorityType);
    if (oldEntityAuthorities != null && !oldEntityAuthorities.isEmpty())
      dataService.delete(UserAuthority.ENTITY_NAME, oldEntityAuthorities);

    // insert new plugin authorities
    if (!entityAuthorities.isEmpty()) dataService.add(UserAuthority.ENTITY_NAME, entityAuthorities);
  }
  private void replaceGroupPermissions(
      List<GroupAuthority> entityAuthorities, String groupId, String authorityPrefix) {
    MolgenisGroup molgenisGroup =
        dataService.findOne(MolgenisGroup.ENTITY_NAME, groupId, MolgenisGroup.class);
    if (molgenisGroup == null) throw new RuntimeException("unknown group id [" + groupId + "]");

    // inject user
    for (GroupAuthority entityAuthority : entityAuthorities)
      entityAuthority.setMolgenisGroup(molgenisGroup);

    // delete old plugin authorities
    List<Authority> oldEntityAuthorities = getGroupPermissions(molgenisGroup, authorityPrefix);
    if (oldEntityAuthorities != null && !oldEntityAuthorities.isEmpty())
      dataService.delete(GroupAuthority.ENTITY_NAME, oldEntityAuthorities);

    // insert new plugin authorities
    if (!entityAuthorities.isEmpty())
      dataService.add(GroupAuthority.ENTITY_NAME, entityAuthorities);
  }
  /**
   * Show the explorer page
   *
   * @param model
   * @return the view name
   */
  @RequestMapping(method = RequestMethod.GET)
  public String init(
      @RequestParam(value = "dataset", required = false) String selectedEntityName,
      @RequestParam(value = "wizard", required = false) Boolean wizard,
      Model model)
      throws Exception {
    // set entityExplorer URL for link to EntityExplorer for x/mrefs, but only if the user has
    // permission to see the
    // plugin
    if (molgenisPermissionService.hasPermissionOnPlugin(
            EntityExplorerController.ID, Permission.READ)
        || molgenisPermissionService.hasPermissionOnPlugin(
            EntityExplorerController.ID, Permission.WRITE)) {
      model.addAttribute("entityExplorerUrl", EntityExplorerController.ID);
    }

    Iterable<EntityMetaData> entitiesMeta =
        Iterables.transform(
            dataService.getEntityNames(),
            new Function<String, EntityMetaData>() {
              @Override
              public EntityMetaData apply(String entityName) {
                return dataService.getEntityMetaData(entityName);
              }
            });
    model.addAttribute("entitiesMeta", entitiesMeta);

    if (selectedEntityName == null) {
      selectedEntityName = entitiesMeta.iterator().next().getName();
    }
    model.addAttribute("selectedEntityName", selectedEntityName);
    model.addAttribute("wizard", (wizard != null) && wizard.booleanValue());

    // Init genome browser
    model.addAttribute("genomeBrowserSets", getGenomeBrowserSetsToModel());

    String appHrefCss = molgenisSettings.getProperty(KEY_APP_HREF_CSS);
    if (appHrefCss != null) model.addAttribute(KEY_APP_HREF_CSS.replaceAll("\\.", "_"), appHrefCss);

    // including/excluding charts
    Boolean appIncludeCharts =
        molgenisSettings.getBooleanProperty(KEY_APP_INCLUDE_CHARTS, INCLUDE_CHARTS_MODULE);
    model.addAttribute(MODEL_APP_INCLUDE_CHARTS, appIncludeCharts);

    model.addAttribute(INITLOCATION, molgenisSettings.getProperty(INITLOCATION));
    model.addAttribute(COORDSYSTEM, molgenisSettings.getProperty(COORDSYSTEM));
    model.addAttribute(CHAINS, molgenisSettings.getProperty(CHAINS));
    model.addAttribute(SOURCES, molgenisSettings.getProperty(SOURCES));
    model.addAttribute(BROWSERLINKS, molgenisSettings.getProperty(BROWSERLINKS));
    model.addAttribute(SEARCHENDPOINT, molgenisSettings.getProperty(SEARCHENDPOINT));
    model.addAttribute(KARYOTYPEENDPOINT, molgenisSettings.getProperty(KARYOTYPEENDPOINT));
    model.addAttribute(GENOMEBROWSERTABLE, molgenisSettings.getProperty(GENOMEBROWSERTABLE));

    return "view-dataexplorer";
  }
 @Test
 public void testUpdateUnknown() {
   mappingProject.setIdentifier("mappingProjectID");
   when(dataService.findOne(ENTITY_NAME, "mappingProjectID")).thenReturn(null);
   try {
     mappingProjectRepositoryImpl.update(mappingProject);
     fail("Expected exception");
   } catch (MolgenisDataException expected) {
     assertEquals(expected.getMessage(), "MappingProject does not exist");
   }
 }
 @Test
 public void testFindAll() {
   Query q = new QueryImpl();
   q.eq(OWNER, "flup");
   when(dataService.findAll(ENTITY_NAME)).thenReturn(Stream.of(mappingProjectEntity));
   when(userService.getUser("flup")).thenReturn(owner);
   when(mappingTargetRepository.toMappingTargets(mappingTargetEntities))
       .thenReturn(asList(mappingTarget1, mappingTarget2));
   List<MappingProject> result = mappingProjectRepositoryImpl.getAllMappingProjects();
   mappingProject.setIdentifier("mappingProjectID");
   assertEquals(result, asList(mappingProject));
 }
  @Test
  public void deleteData() {
    when(dataService.findAllAsList(
            ObservationSet.ENTITY_NAME, new QueryImpl().eq(ObservationSet.PARTOFDATASET, dataset)))
        .thenReturn(observationSets0);
    dataSetDeleterServiceImpl.deleteData(dataset);
    // verify that only observationsets and abservedvalues belonging to the dataset are removed
    verify(dataService, Mockito.atLeastOnce())
        .delete(eq(ObservationSet.ENTITY_NAME), captorObservationSetsArrayList.capture());

    assertEquals(new Integer(0), captorObservationSetsArrayList.getValue().get(0).getId());
    assertEquals(1, captorObservationSetsArrayList.getValue().size());
  }
 @Override
 @PreAuthorize("hasAnyRole('ROLE_SU')")
 @Transactional(readOnly = true)
 public Permissions getGroupEntityClassPermissions(String groupId) {
   MolgenisGroup molgenisGroup =
       dataService.findOne(MolgenisGroup.ENTITY_NAME, groupId, MolgenisGroup.class);
   if (molgenisGroup == null) throw new RuntimeException("unknown group id [" + groupId + "]");
   List<Authority> groupPermissions = getGroupPermissions(molgenisGroup);
   Permissions permissions =
       createPermissions(groupPermissions, SecurityUtils.AUTHORITY_ENTITY_PREFIX);
   permissions.setGroupId(groupId);
   return permissions;
 }
  @Test
  public void testGenerateRules() {
    EntityType targetRefEntityType = createCategoricalRefEntityType("HOP_HYPERTENSION");
    Entity targetEntity1 =
        new DynamicEntity(
            targetRefEntityType, of("code", 0, "label", "Never had high blood pressure "));
    Entity targetEntity2 =
        new DynamicEntity(
            targetRefEntityType, of("code", 1, "label", "Ever had high blood pressure "));
    Entity targetEntity3 =
        new DynamicEntity(targetRefEntityType, of("code", 9, "label", "Missing"));
    Mockito.when(dataService.findAll(targetRefEntityType.getName()))
        .thenReturn(Stream.of(targetEntity1, targetEntity2, targetEntity3));
    targetAttribute =
        attrMetaFactory.create().setName("History of Hypertension").setDataType(CATEGORICAL);
    targetAttribute.setRefEntity(targetRefEntityType);

    EntityType sourceRefEntityType = createCategoricalRefEntityType("High_blood_pressure_ref");
    Entity sourceEntity1 = new DynamicEntity(targetRefEntityType, of("code", 1, "label", "yes"));
    Entity sourceEntity2 = new DynamicEntity(targetRefEntityType, of("code", 2, "label", "no"));
    Entity sourceEntity3 =
        new DynamicEntity(targetRefEntityType, of("code", 3, "label", "I do not know"));
    Mockito.when(dataService.findAll(sourceRefEntityType.getName()))
        .thenReturn(Stream.of(sourceEntity1, sourceEntity2, sourceEntity3));

    sourceAttribute =
        attrMetaFactory.create().setName("High_blood_pressure").setDataType(CATEGORICAL);
    sourceAttribute.setRefEntity(sourceRefEntityType);

    String generatedAlgorithm =
        categoryAlgorithmGenerator.generate(
            targetAttribute, singletonList(sourceAttribute), targetEntityType, sourceEntityType);

    String expectedAlgorithm =
        "$('High_blood_pressure').map({\"1\":\"1\",\"2\":\"0\",\"3\":\"9\"}, null, null).value();";

    Assert.assertEquals(generatedAlgorithm, expectedAlgorithm);
  }
  @Test(expectedExceptions = UnknownTokenException.class)
  public void findUserByTokenExpired() {
    MolgenisToken molgenisToken = new MolgenisToken();
    molgenisToken.setToken("token");
    molgenisToken.setExpirationDate(DateUtils.addDays(new Date(), -1));

    when(dataService.findOne(
            MolgenisToken.ENTITY_NAME,
            new QueryImpl().eq(MolgenisToken.TOKEN, "token"),
            MolgenisToken.class))
        .thenReturn(molgenisToken);

    tokenService.findUserByToken("token");
  }
 @Override
 public Catalog getCatalogOfStudyDefinition(String id)
     throws UnknownCatalogException, UnknownStudyDefinitionException {
   StudyDataRequest studyDataRequest =
       dataService.findOne(
           StudyDataRequest.ENTITY_NAME,
           new QueryImpl().eq(StudyDataRequest.ID, Integer.valueOf(id)),
           StudyDataRequest.class);
   if (studyDataRequest == null)
     throw new UnknownStudyDefinitionException("Study definition [" + id + "] does not exist");
   Protocol protocol = studyDataRequest.getProtocol();
   if (protocol == null) throw new UnknownCatalogException("Catalog [" + id + "] does not exist");
   return new OmxCatalog(protocol, dataService);
 }
  @Test
  public void removeToken() {
    MolgenisToken molgenisToken = new MolgenisToken();
    molgenisToken.setToken("token");

    when(dataService.findOne(
            MolgenisToken.ENTITY_NAME,
            new QueryImpl().eq(MolgenisToken.TOKEN, "token"),
            MolgenisToken.class))
        .thenReturn(molgenisToken);

    tokenService.removeToken("token");
    verify(dataService).delete(MolgenisToken.ENTITY_NAME, molgenisToken);
  }