javax.persistence.EntityNotFoundException Java Examples

The following examples show how to use javax.persistence.EntityNotFoundException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RoleDAOJPAImpl.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@Override
public void removeEntitlementFromRole(Role role, Entitlement entitlement) {
    RoleEntity roleEntity = null;
    if (role.getId() != 0) {
        roleEntity = em.find(RoleEntity.class, role.getId());
    } else {
        roleEntity = getRoleEntity(role.getName(), em);
    }

    EntitlementEntity entitlementEntity = null;
    if (entitlement.getId() != 0) {
        entitlementEntity = em.find(EntitlementEntity.class, entitlement.getId());
    } else {
        entitlementEntity = EntitlementDAOJPAImpl.getEntitlementEntity(entitlement.getName(), em);
    }

    if (entitlementEntity == null) {
        throw new EntityNotFoundException("EntitlementEntity not found");
    }

    if (!roleEntity.getEntitlements().remove(entitlementEntity)) {
        throw new EntityNotFoundException("EntitlementEntity not assigned to RoleEntity");
    }

    LOG.debug("Entitlement '{}' removed from Role '{}'", entitlement.getName(), role.getName());
}
 
Example #2
Source File: SpaceController.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the default {@link Space} of the given {@link Tenant}.
 *
 * @return 404 {@link HttpStatus#NOT_FOUND} if no default space exists, 200 {@link HttpStatus#OK} if the space is found
 * @param tenant a {@link java.lang.String} object.
 */
@RequestMapping(value = "default", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public ResponseEntity<Space> getDefaultSpace(
		@ApiIgnore @RequestHeader(value=Constants.HTTP_TENANT_HEADER, required=false) String tenant) {
	
	// Check whether tenant exists or retrieve default
	Tenant t = null;
	try {
		t = this.tenantRepository.getTenant(tenant);
	} catch (Exception e){
		log.error("Error retrieving tenant: " + e);
		return new ResponseEntity<Space>(HttpStatus.NOT_FOUND);
	}
	try {
		// Get default space
		final Space def = this.spaceRepository.findDefault(t.getTenantToken());
		if(def==null)
			throw new EntityNotFoundException("No default space can be found for tenant [" + t.getTenantToken() + "]");
		else
			return new ResponseEntity<Space>(def, HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		return new ResponseEntity<Space>(HttpStatus.NOT_FOUND);
	}
}
 
Example #3
Source File: HubIntegrationController.java    From steady with Apache License 2.0 6 votes vote down vote up
static ExportItem fromString(String _string, String _separator, SpaceRepository _space_repo, ApplicationRepository _app_repo) throws IllegalArgumentException, EntityNotFoundException {
	// Space
	String token = null;
	final int idx_start = _string.indexOf("(");
	final int idx_end   = _string.indexOf(")");
	if(idx_start==-1 || idx_end==-1)
		throw new IllegalArgumentException("Cannot find space token in argument [" + _string + "]");
	else
		token = _string.substring(idx_start+1, idx_end);

	Space space = SpaceRepository.FILTER.findOne(_space_repo.findBySecondaryKey(token));
	Application app = null;

	// Application
	final String app_string = _string.substring(idx_end+1);
	if(app_string!=null && !app_string.equalsIgnoreCase("")) {
		final String[] app_gav = app_string.split(_separator);
		if(app_gav.length!=3)
			throw new IllegalArgumentException("Cannot find application identifier in argument [" + _string + "]");
		app = ApplicationRepository.FILTER.findOne(_app_repo.findByGAV(revertEscapedCharacters(app_gav[0].trim()),  revertEscapedCharacters(app_gav[1].trim()),  revertEscapedCharacters(app_gav[2].trim()), space));
	}

	return new ExportItem(space, app);
}
 
Example #4
Source File: JogadorService.java    From acelera-dev-sp-2019 with Apache License 2.0 6 votes vote down vote up
public void adicionaJogador(JogadorDto jogadorDto) {
    // Verificar se jogador ja existe antes de adicionar
    try{
        getJogador(jogadorDto.getNome());
        throw new IllegalArgumentException("Tentando adicionar Jogador que já existe");

    }catch (EntityNotFoundException e){
        Jogador novoJogador = new Jogador();
        novoJogador.setNome(jogadorDto.getNome());
        novoJogador.setCidade(jogadorDto.getCidade());
        novoJogador.setPais(jogadorDto.getPais());
        novoJogador.setPosicao(jogadorDto.getPosicao());
        novoJogador.setGols(jogadorDto.getGols());
        novoJogador.setTime(timeRepository.findById(jogadorDto.getTime())
                .orElseThrow(() -> new EntityNotFoundException("Time nao encontrado")));
        jogadorRepository.save(novoJogador);
    }
}
 
Example #5
Source File: ReferenceUpdater.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether any of the referenced {@link ConstructId}s already exist in the database.
 * If yes, they are read and replaced from the database so that the internal ID is set.
 * Otherwise, if the internal ID of referenced {@link ConstructId}s is null, it would always
 * result in the saving of a new {@link ConstructId}, which in turn results in the violation of
 * unique constraints defined in {@link ConstructId}.
 *
 * @param _constructs a {@link java.util.Collection} object.
 * @return a {@link java.util.Collection} object.
 */
public Collection<ConstructId> saveNestedConstructIds(Collection<ConstructId> _constructs) {
	final Collection<ConstructId> constructs = new HashSet<ConstructId>();
	if(_constructs!=null) {
		ConstructId managed_cid = null;
		for(ConstructId provided_cid: _constructs) {
			try {
				managed_cid  = ConstructIdRepository.FILTER.findOne(this.cidRepository.findConstructId(provided_cid.getLang(), provided_cid.getType(), provided_cid.getQname()));
			} catch (EntityNotFoundException e) {
				try {
					managed_cid = this.cidRepository.save(provided_cid);
				} catch (Exception e1) {
					log.error("Error while saving constructId [" + provided_cid + "], will be skipped: " + e1);
					managed_cid = null;
				}
			}
			if(managed_cid!=null)
				constructs.add(managed_cid);
		}
	}
	return constructs;
}
 
Example #6
Source File: JogadorService.java    From acelera-dev-sp-2019 with Apache License 2.0 6 votes vote down vote up
public JogadorDto atualizaJogador(String nome, JogadorDto jogadorDto) {
    //Verificar se jogador existe antes de atualizar
    getJogador(nome);

    Jogador jogador = jogadorRepository.findById(nome)
            .orElseThrow(() -> new EntityNotFoundException("Jogador nao encontrado"));
    jogador.setNome(jogadorDto.getNome());
    jogador.setCidade(jogadorDto.getCidade());
    jogador.setGols(jogadorDto.getGols());
    jogador.setPais(jogadorDto.getPais());
    jogador.setPosicao(jogadorDto.getPosicao());
    jogador.setTime(timeRepository.findById(jogadorDto.getTime())
            .orElseThrow(() -> new EntityNotFoundException("Time nao encontrado")));

    return JogadorDtoBuilder.buildFromEntity(
            jogadorRepository.save(jogador)
    );
}
 
Example #7
Source File: SpaceController.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all {@link Space}s of the given {@link Tenant}.
 *
 * @return 404 {@link HttpStatus#NOT_FOUND} if space with given token does not exist, 200 {@link HttpStatus#OK} if the space is found
 * @param tenant a {@link java.lang.String} object.
 */
@RequestMapping(value = "", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public ResponseEntity<Collection<Space>> getAllSpaces(
		@ApiIgnore @RequestHeader(value=Constants.HTTP_TENANT_HEADER, required=false) String tenant) {
	
	// Check whether tenant exists or retrieve default
	Tenant t = null;
	try {
		t = this.tenantRepository.getTenant(tenant);
	} catch (Exception e){
		log.error("Error retrieving tenant: " + e);
		return new ResponseEntity<Collection<Space>>(HttpStatus.NOT_FOUND);
	}

	try {
		// Get all its spaces
		final Collection<Space> all_tenant_spaces = this.spaceRepository.findAllTenantSpaces(t.getTenantToken(), true);
		return new ResponseEntity<Collection<Space>>(all_tenant_spaces, HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		return new ResponseEntity<Collection<Space>>(HttpStatus.NOT_FOUND);
	}
}
 
Example #8
Source File: InvalidPullRequestPage.java    From onedev with MIT License 6 votes vote down vote up
public InvalidPullRequestPage(PageParameters params) {
	super(params);
	
	requestModel = new LoadableDetachableModel<PullRequest>() {

		@Override
		protected PullRequest load() {
			Long requestNumber = params.get(PARAM_REQUEST).toLong();
			PullRequest request = OneDev.getInstance(PullRequestManager.class).find(getProject(), requestNumber);
			if (request == null)
				throw new EntityNotFoundException("Unable to find pull request #" + requestNumber + " in project " + getProject());
			Preconditions.checkState(!request.isValid());
			return request;
		}

	};
}
 
Example #9
Source File: IssueDetailPage.java    From onedev with MIT License 6 votes vote down vote up
public IssueDetailPage(PageParameters params) {
	super(params);
	
	String issueNumberString = params.get(PARAM_ISSUE).toString();
	if (StringUtils.isBlank(issueNumberString))
		throw new RestartResponseException(ProjectIssueListPage.class, ProjectIssueListPage.paramsOf(getProject(), null, 0));
	
	issueModel = new LoadableDetachableModel<Issue>() {

		@Override
		protected Issue load() {
			Long issueNumber = Long.valueOf(issueNumberString);
			Issue issue = OneDev.getInstance(IssueManager.class).find(getProject(), issueNumber);
			if (issue == null)
				throw new EntityNotFoundException("Unable to find issue #" + issueNumber + " in project " + getProject());
			else if (!issue.getProject().equals(getProject()))
				throw new RestartResponseException(getPageClass(), paramsOf(issue));
			else
				return issue;
		}

	};
}
 
Example #10
Source File: BuildDetailPage.java    From onedev with MIT License 6 votes vote down vote up
public BuildDetailPage(PageParameters params) {
	super(params);
	
	String buildNumberString = params.get(PARAM_BUILD).toString();
	if (StringUtils.isBlank(buildNumberString))
		throw new RestartResponseException(ProjectBuildsPage.class, ProjectBuildsPage.paramsOf(getProject(), null, 0));
		
	buildModel = new LoadableDetachableModel<Build>() {

		@Override
		protected Build load() {
			Long buildNumber = params.get(PARAM_BUILD).toLong();
			Build build = OneDev.getInstance(BuildManager.class).find(getProject(), buildNumber);
			if (build == null)
				throw new EntityNotFoundException("Unable to find build #" + buildNumber + " in project " + getProject());
			else if (!build.getProject().equals(getProject()))
				throw new RestartResponseException(getPageClass(), paramsOf(build));
			else
				return build;
		}

	};

	if (!getBuild().isValid())
		throw new RestartResponseException(InvalidBuildPage.class, InvalidBuildPage.paramsOf(getBuild()));
}
 
Example #11
Source File: InvalidBuildPage.java    From onedev with MIT License 6 votes vote down vote up
public InvalidBuildPage(PageParameters params) {
	super(params);
	
	buildModel = new LoadableDetachableModel<Build>() {

		@Override
		protected Build load() {
			Long buildNumber = params.get(PARAM_BUILD).toLong();
			Build build = OneDev.getInstance(BuildManager.class).find(getProject(), buildNumber);
			if (build == null)
				throw new EntityNotFoundException("Unable to find build #" + buildNumber + " in project " + getProject());
			Preconditions.checkState(!build.isValid());
			return build;
		}

	};
}
 
Example #12
Source File: BugController.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a set of {@link AffectedLibrary}s for the given {@link Bug} and {@link AffectedVersionSource}.
 * Note that {@link AffectedLibrary}s cannot be created, modified or deleted individually, but always as bulk for a given {@link AffectedVersionSource}.
 *
 * @return 409 {@link HttpStatus#CONFLICT} if bug with given bug ID already exists, 201 {@link HttpStatus#CREATED} if the bug was successfully created
 * @param bugid a {@link java.lang.String} object.
 * @param source a {@link com.sap.psr.vulas.shared.enums.AffectedVersionSource} object.
 */
@RequestMapping(value = "/{bugid}/affectedLibIds", method = RequestMethod.DELETE, produces = {"application/json;charset=UTF-8"})
public ResponseEntity<List<AffectedLibrary>> deleteAffectedLibraries(@PathVariable String bugid, @RequestParam(value="source", required=true) AffectedVersionSource source) {
	// Ensure that bug exists
	Bug bug = null;
	try { bug = BugRepository.FILTER.findOne(this.bugRepository.findByBugId(bugid)); }
	catch (EntityNotFoundException e) { return new ResponseEntity<List<AffectedLibrary>>(HttpStatus.NOT_FOUND); }

	// Ensure that affected libs for bug and source exist
	final List<AffectedLibrary> aff_libs = this.afflibRepository.findByBugAndSource(bug, source);
	if(aff_libs==null || aff_libs.size()==0)
		return new ResponseEntity<List<AffectedLibrary>>(HttpStatus.NOT_FOUND);
	for(AffectedLibrary aff_lib: aff_libs){
		if(aff_lib.getAffectedcc()!=null)
			//Delete affected construct changes
			this.afflibRepository.deleteCCByAffLib(aff_lib);
	}
	
	// Delete and return
	this.afflibRepository.deleteByBugAndSource(bug, source); 
	return new ResponseEntity<List<AffectedLibrary>>(HttpStatus.OK);
}
 
Example #13
Source File: CategorizationServiceBean.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * @param toBeDeleted
 * @throws OperationNotPermittedException
 * @throws ObjectNotFoundException
 */
private void deleteCategories(List<VOCategory> toBeDeleted)
        throws OperationNotPermittedException, ObjectNotFoundException {
    final Organization currentOrg = dm.getCurrentUser().getOrganization();
    final Query marketplaceQuery = dm
            .createNamedQuery("Marketplace.findByBusinessKey");
    for (VOCategory voCategory : toBeDeleted) {
        final Category category = dm.getReference(Category.class,
                voCategory.getKey());
        try {
            marketplaceQuery.setParameter("marketplaceId", category
                    .getMarketplace().getMarketplaceId());
        } catch (EntityNotFoundException e) {
            throw new ObjectNotFoundException(ClassEnum.MARKETPLACE,
                    voCategory.getMarketplaceId());
        }
        final Marketplace marketplace = (Marketplace) marketplaceQuery
                .getSingleResult();
        PermissionCheck.owns(marketplace, currentOrg, logger, null);
        List<PlatformUser> usersToBeNotified = collectUsersToBeNotified(category);
        prefetchRequiredObject(category);
        dm.remove(category);
        sendNotification(category, usersToBeNotified);
    }
}
 
Example #14
Source File: BugController.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
	 * Adds a set of {@link AffectedLibrary}s for the given {@link Bug} and {@link AffectedVersionSource}.
	 * This method is only allows for source CHECK_VERSION, AST_EQUALITY, MINOR_EQUALITY MAJOR_EQUALITY GREATER_RELEASE TO_REVIEW
	 *
	 * @return 409 {@link HttpStatus#CONFLICT} if bug with given bug ID already exists, 201 {@link HttpStatus#CREATED} if the bug was successfully created
	 * @param bugid a {@link java.lang.String} object.
	 * @param source a {@link com.sap.psr.vulas.shared.enums.AffectedVersionSource} object.
	 * @param affectedLibraries an array of {@link com.sap.psr.vulas.backend.model.AffectedLibrary} objects.
	 */
	@RequestMapping(value = "/{bugid}/affectedLibIds", method = RequestMethod.PUT, consumes = {"application/json;charset=UTF-8"}, produces = {"application/json;charset=UTF-8"})
	@JsonView(Views.BugAffLibs.class)
	public ResponseEntity<List<AffectedLibrary>> addAffectedLibrary(@PathVariable String bugid, @RequestParam(value="source", required=true) AffectedVersionSource source, @RequestBody AffectedLibrary[] affectedLibraries) {
		//Ensure that PUT is only used by CHECK_VERSION or PATCH EVAL results
		final StopWatch sw = new StopWatch("PUT affected libraries for source: " + source).start();
//		if(!source.equals(AffectedVersionSource.CHECK_VERSION)&&!source.equals(AffectedVersionSource.AST_EQUALITY)&&!source.equals(AffectedVersionSource.GREATER_RELEASE)&&!source.equals(AffectedVersionSource.INTERSECTION)&&!source.equals(AffectedVersionSource.MINOR_EQUALITY)&&!source.equals(AffectedVersionSource.MAJOR_EQUALITY)&&!source.equals(AffectedVersionSource.TO_REVIEW) &&!source.equals(AffectedVersionSource.PROPAGATE_MANUAL)){
//			sw.lap("not allowed",true);
//			return new ResponseEntity<List<AffectedLibrary>>(HttpStatus.UNPROCESSABLE_ENTITY);
//		}
		
		// Ensure that bug exists
		Bug bug = null;
		try { bug = BugRepository.FILTER.findOne(this.bugRepository.findByBugId(bugid)); }
		catch (EntityNotFoundException e) { return new ResponseEntity<List<AffectedLibrary>>(HttpStatus.NOT_FOUND); }

		// Ensure consistency of path variable and JSON content
		for(AffectedLibrary afflib: affectedLibraries)
			if(!source.equals(afflib.getSource())){
				sw.lap("path/json inconsistency",true);
				return new ResponseEntity<List<AffectedLibrary>>(HttpStatus.UNPROCESSABLE_ENTITY);
			}
		sw.stop();
		// Save and return
		return new ResponseEntity<List<AffectedLibrary>>(this.afflibRepository.customSave(bug, affectedLibraries), HttpStatus.OK);
	}
 
Example #15
Source File: BugController.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes the {@link Bug} with the given external ID. This ID is provided by the user when creating a bug, e.g., a CVE identifier.
 *
 * @return 404 {@link HttpStatus#NOT_FOUND} if bug with given bug ID does not exist, 200 {@link HttpStatus#OK} if the bug was successfully deleted
 * @param bugid a {@link java.lang.String} object.
 */
@RequestMapping(value = "/{bugid}", method = RequestMethod.DELETE)
@CacheEvict(value = "bug")
public ResponseEntity<Resource<Bug>> deleteBug(@PathVariable String bugid) {
	try {
		final Bug b = BugRepository.FILTER.findOne(this.bugRepository.findByBugId(bugid));
		
		// Ensure that no affected libs for bug exist
		final List<AffectedLibrary> aff_libs = this.afflibRepository.findByBug(b);
		if(aff_libs!=null && aff_libs.size()>0) 
			return new ResponseEntity<Resource<Bug>>(HttpStatus.UNPROCESSABLE_ENTITY);
		this.bugRepository.delete(b);
		return new ResponseEntity<Resource<Bug>>(HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		return new ResponseEntity<Resource<Bug>>(HttpStatus.NOT_FOUND);
	}
}
 
Example #16
Source File: BugController.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * <p>isBugExisting.</p>
 *
 * @return 404 {@link HttpStatus#NOT_FOUND} if bug with given bugid does not exist, 200 {@link HttpStatus#OK} if the bug is found
 * @param bugid a {@link java.lang.String} object.
 */
@RequestMapping(value = "/{bugid}", method = RequestMethod.OPTIONS)
public ResponseEntity<Bug> isBugExisting(@PathVariable String bugid) {
	final StopWatch sw = new StopWatch("OPTIONS bug [" + bugid + "]").start();
	try {
		BugRepository.FILTER.findOne(this.bugRepository.findByBugId(bugid));
		sw.stop();
		return new ResponseEntity<Bug>(HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		sw.stop(enfe);
		return new ResponseEntity<Bug>(HttpStatus.NOT_FOUND);
	}
	catch(Exception e) {
		sw.stop(e);
		return new ResponseEntity<Bug>(HttpStatus.INTERNAL_SERVER_ERROR);
	}
}
 
Example #17
Source File: BugController.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@link Bug} with the given external ID. This ID is provided by the user when creating a bug, e.g., a CVE identifier.
 *
 * @return 404 {@link HttpStatus#NOT_FOUND} if bug with given bug ID does not exist, 200 {@link HttpStatus#OK} if the bug is found
 * @param bugid a {@link java.lang.String} object.
 */
@RequestMapping(value = "/{bugid}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@JsonView(Views.BugDetails.class)
public ResponseEntity<Bug> getBug(@PathVariable String bugid) {
	final StopWatch sw = new StopWatch("GET bug [" + bugid + "]").start();
	try {
		final Bug b = BugRepository.FILTER.findOne(this.bugRepository.findByBugId(bugid));
		this.bugRepository.updateCachedCveData(b, false);
		sw.stop();
		return new ResponseEntity<Bug>(b, HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		sw.stop(enfe);
		return new ResponseEntity<Bug>(HttpStatus.NOT_FOUND);
	}
	catch(Exception e) {
		sw.stop(e);
		return new ResponseEntity<Bug>(HttpStatus.INTERNAL_SERVER_ERROR);
	}
}
 
Example #18
Source File: TenantRepositoryImpl.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * Returns the tenant for the given tenant token. In case a tenant token is not provided, it returns the default tenant (if existing, null otherwise)
 */
public Tenant getTenant(String _tenantToken) {
	Tenant tenant = null;		
	if(_tenantToken==null){
		tenant = tenantRepository.findDefault();
		if(tenant==null){
			log.error("No default tenant exists");
			throw new EntityNotFoundException("Default tenant does not exists");
		}
	}
	else{
		try {
			tenant = TenantRepository.FILTER.findOne(this.tenantRepository.findBySecondaryKey(_tenantToken));
		}
		catch(EntityNotFoundException enfe) {
			log.error("A tenant with token [" + _tenantToken + "] does not exist: " + enfe.getMessage());
			throw enfe; 
		}
	}
	
	log.debug("Found " + tenant + " for token [" + _tenantToken + "]");
	return tenant;
}
 
Example #19
Source File: SpaceRepositoryImpl.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * Returns the default space for the given tenant token. In case the tenant token is not provided, it uses the default tenant. If
 * the default space for the given tenant or the default tenant do not exist, it returns null.
 */
public Space getDefaultSpace(String _tenant_token) {
	Space s = null;
	if(_tenant_token==null){
		try{
			_tenant_token = tenantRepository.findDefault().getTenantToken();
		}
		catch(EntityNotFoundException tnfe){
			log.error("A default tenant does not exists, please create one: " + tnfe.getMessage());
		}
	}
	try{
		s = spaceRepository.findDefault(_tenant_token);
	}
	catch (EntityNotFoundException snfe){
		log.error("A default space for tenant token [" + _tenant_token + "] does not exists, please create one: " + snfe.getMessage());
	}
	catch(Exception e){
		log.error("Cannot find default space for tenant token [" + _tenant_token + "]: " + e.getMessage());
	}
	return s;
}
 
Example #20
Source File: IdpDAOJPAImpl.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@Override
public void removeApplicationFromIdp(Idp idp, Application application) {
    IdpEntity idpEntity = null;
    if (idp.getId() != 0) {
        idpEntity = em.find(IdpEntity.class, idp.getId());
    } else {
        idpEntity = getIdpEntity(idp.getRealm(), em);
    }

    ApplicationEntity applicationEntity = null;
    if (application.getId() != 0) {
        applicationEntity = em.find(ApplicationEntity.class, application.getId());
    } else {
        applicationEntity = ApplicationDAOJPAImpl.getApplicationEntity(application.getRealm(), em);
    }

    if (applicationEntity == null) {
        throw new EntityNotFoundException("ApplicationEntity not found");
    }

    if (!idpEntity.getApplications().remove(applicationEntity)) {
        throw new EntityNotFoundException("ApplicationEntity not assigned to IdpEntity");
    }

    LOG.debug("Application '{}' removed from IDP '{}'", application.getRealm(), idp.getRealm());
}
 
Example #21
Source File: SpaceRepositoryImpl.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * Returns the space for the given space token. In case a space token is not provided, it returns the default space of the
 * default tenant (if existing, null otherwise)
 */
public Space getSpace(String _spaceToken) {
	Space space = null;		
	if(_spaceToken==null)
		space = spaceRepository.getDefaultSpace(null);
	else{
		try {
			space = SpaceRepository.FILTER.findOne(this.spaceRepository.findBySecondaryKey(_spaceToken));
		}
		catch(EntityNotFoundException enfe) {
			log.error("A space with token [" + _spaceToken + "] does not exist: " + enfe.getMessage());
			throw enfe; 
		}
	}
	
	log.debug("Found " + space + " for token [" + _spaceToken + "]");
	return space;
}
 
Example #22
Source File: SpaceController.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether a {@link Space} with the given token exists for the given {@link Tenant}.
 *
 * @param token a {@link java.lang.String} object.
 * @return 404 {@link HttpStatus#NOT_FOUND} if space with given token does not exist, 200 {@link HttpStatus#OK} if the space is found
 * @param tenant a {@link java.lang.String} object.
 */
@RequestMapping(value = "/{token:.+}", method = RequestMethod.OPTIONS)
public ResponseEntity<Space> isSpaceExisting(
		@PathVariable String token,
		@ApiIgnore @RequestHeader(value=Constants.HTTP_TENANT_HEADER, required=false) String tenant) {
	// Check whether tenant exists or retrieve default
	Tenant t = null;
	try {
		t = this.tenantRepository.getTenant(tenant);
	} catch (Exception e){
		log.error("Error retrieving tenant: " + e);
		return new ResponseEntity<Space>(HttpStatus.NOT_FOUND);
	}
	try {
		SpaceRepository.FILTER.findOne(this.spaceRepository.findBySecondaryKey(t.getTenantToken(), token));
		return new ResponseEntity<Space>(HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		return new ResponseEntity<Space>(HttpStatus.NOT_FOUND);
	}
}
 
Example #23
Source File: LibraryController.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * <p>isLibraryExisting.</p>
 *
 * @param digest a {@link java.lang.String} object.
 * @return 404 {@link HttpStatus#NOT_FOUND} if library with given digest does not exist, 200 {@link HttpStatus#OK} if the library is found
 */
@RequestMapping(value = "/{digest}", method = RequestMethod.OPTIONS)
public ResponseEntity<Library> isLibraryExisting(@PathVariable String digest) {
	try {
		LibraryRepository.FILTER.findOne(this.libRepository.findByDigest(digest));
		return new ResponseEntity<Library>(HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		return new ResponseEntity<Library>(HttpStatus.NOT_FOUND);
	}
}
 
Example #24
Source File: LibraryController.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the {@link Library} with the given external ID. This ID is provided by the user when creating a bug, e.g., a CVE identifier.
 *
 * @return 404 {@link HttpStatus#NOT_FOUND} if bug with given bug ID does not exist, 200 {@link HttpStatus#OK} if the bug was successfully deleted
 * @param digest a {@link java.lang.String} object.
 */
@RequestMapping(value = "/{digest}", method = RequestMethod.DELETE, produces = {"application/json;charset=UTF-8"})
public ResponseEntity<Resource<Library>> deleteLibrary(@PathVariable String digest) {
	try {
		final Library lib = LibraryRepository.FILTER.findOne(this.libRepository.findByDigest(digest));
		this.libRepository.delete(lib);
		return new ResponseEntity<Resource<Library>>(HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		return new ResponseEntity<Resource<Library>>(HttpStatus.NOT_FOUND);
	}
}
 
Example #25
Source File: VariableDAOJpa.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean delete(IVariable variable) {
    try {
        variable = entityManager
                .getReference(Variable.class, variable.getId());
        entityManager.remove(variable);
        entityManager.flush();
        return true;
    } catch (EntityNotFoundException e) {
        logger.debug("Variable[{}] not found", variable.getId());
        return false;
    }
}
 
Example #26
Source File: LibraryController.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link Application} with dependencies on the given digest.
 *
 * @param digest a {@link java.lang.String} object.
 * @return 404 {@link HttpStatus#NOT_FOUND} if no application depends on the given digest or digest does not exists, 200 {@link HttpStatus#OK} if the applications are found
 */
@RequestMapping(value = "/{digest}/apps", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@JsonView(Views.AppDepDetails.class)
public ResponseEntity<List<Application>> getLibraryApplications(@PathVariable String digest) {
	try {
		// To throw an exception if the entity is not found
		Library l = LibraryRepository.FILTER.findOne(this.libRepository.findByDigest(digest));

		return new ResponseEntity<List<Application>>( this.appRepository.findAppsWithDigest(digest), HttpStatus.OK);
	}
	catch(EntityNotFoundException enfe) {
		return new ResponseEntity<List<Application>>(HttpStatus.NOT_FOUND);
	}
}
 
Example #27
Source File: JobService.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public Job getJobById(String jobId) {
  Optional<Job> byId = jobRepository.findById(jobId);
  if (byId.isPresent()) {
    return byId.get();
  }
  throw new EntityNotFoundException("No Job found with ID " + jobId);
}
 
Example #28
Source File: GoalExecutionRepositoryImpl.java    From steady with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public GoalExecution customSave(Application _app, GoalExecution _provided_gexe) {
	GoalExecution managed_gexe = null;

	try{
		managed_gexe = GoalExecutionRepository.FILTER.findOne(this.gexeRepository.findByExecutionId(_provided_gexe.getExecutionId()));
		_provided_gexe.setId(managed_gexe.getId());
		_provided_gexe.setCreatedAt(managed_gexe.getCreatedAt());
	} catch (EntityNotFoundException e1) {}
	
	// Update refs to independent entities
	_provided_gexe.setApp(_app);
	_provided_gexe.setConfiguration(refUpdater.saveNestedProperties(_provided_gexe.getConfiguration()));	
	_provided_gexe.setSystemInfo(refUpdater.saveNestedProperties(this.filterSystemInfo(_provided_gexe.getSystemInfo())));

	//update the lastScan timestamp of the application (we already have a managed application here)
	appRepository.refreshLastScanbyApp(_app);

	// Save
	try {
		managed_gexe = this.gexeRepository.save(_provided_gexe);
	} catch (Exception e) {
		throw new PersistenceException("Error while saving goal execution [" + _provided_gexe + "]: " + e.getMessage());
	}
	return managed_gexe;
}
 
Example #29
Source File: AffectedLibraryRepositoryImpl.java    From steady with Apache License 2.0 5 votes vote down vote up
private AffectedLibrary updateNestedLib(@NotNull AffectedLibrary _aff_lib) {
	final Library provided_lib = _aff_lib.getLib();
	Library managed_lib = null;
	if(provided_lib!=null) {
		try {
			managed_lib = LibraryRepository.FILTER.findOne(this.libRepository.findByDigest(provided_lib.getDigest()));

		} catch (EntityNotFoundException e) {
			throw new PersistenceException("Error while saving lib " + provided_lib + ": " + e.getMessage());
		}
		_aff_lib.setLib(managed_lib);
	}
	return _aff_lib;
}
 
Example #30
Source File: ApplicationControllerTest.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
   * Repo-save and rest-clean (fails due to read-only space)
   * @param obj
   * @return
   */
  @Test
  @Transactional
  public void testCleanAppReadOnlySpace() throws Exception {
  	final Library lib = this.createExampleLibrary();
  	this.libRepository.customSave(lib);
  	Application app = this.createExampleApplication();
  	app = this.appRepository.customSave(app);
  	
  	// Repo must contain 1
  	assertEquals(1, this.appRepository.count());
  	
  	// Make the space read-only
  	try{
	final Space default_space = SpaceRepository.FILTER.findOne(spaceRepository.findBySecondaryKey(TEST_DEFAULT_SPACE));
	default_space.setReadOnly(true);
} catch(EntityNotFoundException e) {
	e.printStackTrace();
	assertTrue(false);
}
  	
  	// Rest-post
  	final MockHttpServletRequestBuilder post_builder = post(getAppUri(app))
  			.param("clean", "true")
		.accept(MediaType.APPLICATION_JSON);
  	mockMvc.perform(post_builder)	
              .andExpect(status().isBadRequest());
  	
  	// Repo must still contain 1
  	assertEquals(1, this.appRepository.count());
  }