@PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, USER}) public User modify(@NotNull User user) { User existingUser = null; if (sessionContext.isCallerInRole(USER) && !sessionContext.isCallerInRole(ADMIN)) { existingUser = userFinder.findByLogin(sessionContext.getCallerPrincipal().getName()); if (!existingUser.getId().equals(user.getId()) || !existingUser.getLogin().equals(user.getLogin())) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } user.setActivated(existingUser.getActivated()); user.setDisabled(existingUser.getDisabled()); user.setActionToken(existingUser.getActionToken()); } if (existingUser == null) { existingUser = entityManager.find(User.class, user.getId()); } checkNotNull(existingUser); user.setPassword(existingUser.getPassword()); user.setCreationDate(existingUser.getCreationDate()); user.setRoles(existingUser.getRoles()); return entityManager.merge(user); }
public void lookupJMSConnectionFactory() throws TestFailureException { try { try { Object obj = ejbContext.lookup("jms"); Assert.assertNotNull("The JMS ConnectionFactory is null", obj); Assert.assertTrue("Not an instance of ConnectionFactory", obj instanceof ConnectionFactory); ConnectionFactory connectionFactory = (ConnectionFactory) obj; testJmsConnection(connectionFactory.createConnection()); obj = ejbContext.lookup("TopicCF"); Assert.assertNotNull("The JMS TopicConnectionFactory is null", obj); Assert.assertTrue( "Not an instance of TopicConnectionFactory", obj instanceof TopicConnectionFactory); TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) obj; testJmsConnection(topicConnectionFactory.createConnection()); obj = ejbContext.lookup("QueueCF"); Assert.assertNotNull("The JMS QueueConnectionFactory is null", obj); Assert.assertTrue( "Not an instance of QueueConnectionFactory", obj instanceof QueueConnectionFactory); QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) obj; testJmsConnection(queueConnectionFactory.createConnection()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (AssertionFailedError afe) { throw new TestFailureException(afe); } }
@RolesAllowed({"BANKADMIN", "BANKUSER"}) public Transaction getTransaction(int tranId) throws InvalidTranException, NotAuthorizedException, NotFoundException { String user = sctx.getCallerPrincipal().getName(); Transaction tran = em.find(Transaction.class, tranId); if (tran == null) throw new NotFoundException(); if (user.equals(tran.getAccount().getUserId()) || sctx.isCallerInRole("BANKADMIN")) return tran; else throw new NotAuthorizedException(); }
@RolesAllowed({"BANKADMIN", "BANKUSER"}) public int createTransaction(Transaction tran, int id) throws InvalidTranException, NotAuthorizedException, NotFoundException { String user = sctx.getCallerPrincipal().getName(); Account account = accountDao.getAccount(id); tran.setAccount(account); if (user.equals(tran.getAccount().getUserId()) || sctx.isCallerInRole("BANKADMIN")) em.persist(tran); return tran.getId(); }
public void update(EnvAspOtherMatrixMethodDao attrs) throws UserException { try { dao.update(attrs); } catch (NamingException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no servidor de nomes.", ex); } catch (SQLException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no SQL!", ex); } this.attrs = attrs; }
@Override @RolesAllowed({"AppTwo", "Intern"}) public String invokeSecured(String text) { Principal caller = context.getCallerPrincipal(); LOGGER.info("Secured invocation [" + caller.getName() + "] " + text); LOGGER.info( "Is in Role AppTwo=" + context.isCallerInRole("AppTwo") + " Intern=" + context.isCallerInRole("Intern")); return "app2[" + caller.getName() + "]@" + getJBossNodeName(); }
public void findByPrimaryKey(EnvAspOtherMatrixMethodDao attrs) throws RowNotFoundException, UserException { try { dao.findByPrimaryKey((Object) attrs); this.attrs = (EnvAspOtherMatrixMethodDao) dao.load(attrs); } catch (NamingException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no servidor de nomes.", ex); } catch (SQLException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no SQL !", ex); } }
public Collection listAll() throws RowNotFoundException, UserException { try { return dao.listAll(); } catch (RowNotFoundException ex) { ctx.setRollbackOnly(); throw ex; } catch (NamingException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no servidor de nomes.", ex); } catch (SQLException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no SQL !", ex); } }
/** * Tries to save the passed list of {@link VOUdaDefinition}s. Checks if the passed values are * valid and permitted to be accessed. * * @param defs the {@link VOUdaDefinition}s to save * @param caller the calling (owning) {@link Organization} * @throws ValidationException in case of an invalid {@link VOUdaDefinition} * @throws OrganizationAuthoritiesException in case the calling {@link Organization} has * insufficient roles to create {@link UdaDefinition}s of the set {@link UdaTargetType}. * @throws NonUniqueBusinessKeyException in case a {@link UdaDefinition} with the passed id and * target type already exists for the owning {@link Organization} * @throws OperationNotPermittedException in case it was tries to update a {@link UdaDefinition} * owned by another {@link Organization}. * @throws ConcurrentModificationException in case the {@link UdaDefinition} to update was * concurrently changed * @throws ObjectNotFoundException in case on of the {@link UdaDefinition}s to update was not * found */ public void saveUdaDefinitions(List<VOUdaDefinition> defs, Organization caller) throws ValidationException, OrganizationAuthoritiesException, NonUniqueBusinessKeyException, OperationNotPermittedException, ConcurrentModificationException, ObjectNotFoundException { for (VOUdaDefinition voDef : defs) { // convert and validate UdaDefinition def; try { def = UdaAssembler.toUdaDefinition(voDef); def.setOrganization(caller); } catch (ValidationException e) { logger.logWarn( Log4jLogger.SYSTEM_LOG, e, LogMessageIdentifier.WARN_INVALID_UDA_DEFINITION, voDef.getUdaId()); ctx.setRollbackOnly(); throw e; } // check if target type is allowed for organization UdaTargetType type = def.getTargetType(); if (!type.canSaveDefinition(caller.getGrantedRoleTypes())) { String roles = rolesToString(type.getRoles()); OrganizationAuthoritiesException e = new OrganizationAuthoritiesException( "Insufficient authorization. Required role(s) '" + roles + "'.", new Object[] {roles}); logger.logWarn( Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG, e, LogMessageIdentifier.WARN_ORGANIZATION_ROLE_REQUIRED, Long.toString(caller.getKey()), roles); ctx.setRollbackOnly(); throw e; } if (voDef.getKey() > 0) { updateDefinition(voDef, caller); } else { createDefinition(def); } UdaDefinition storedUda = (UdaDefinition) ds.find(def); if (storedUda == null) { return; } storeLocalizedAttributeName(storedUda.getKey(), voDef.getName(), voDef.getLanguage()); } }
@Override public String addForm(Form form) throws AddFormException { logger.info("------------> Adding a new Form 848"); try { logger.info("Finding principal user"); User user = null; try { user = userManager.findUserByName(sc.getCallerPrincipal().getName()); } catch (Exception e1) { logger.error("Imposible to retrieve principal user.", e1); throw new AddFormException(e1.getClass() + " --> " + e1.getMessage()); } Form848 form848 = new Form848(user); form848.fillForm(form); em.persist(form848); form848.setPrePrintedNumber(form848.getId().toString()); return form848.getId().toString(); } catch (FillFormException e) { logger.error(e); throw new AddFormException(e.getClass() + " --> " + e.getMessage()); } }
public void insert(EnvAspOtherMatrixMethodDao attrs) throws DupKeyException, UserException { try { this.attrs = attrs; dao.create(this.attrs); dao.update(this.attrs); } catch (DupKeyException ex) { ctx.setRollbackOnly(); throw ex; } catch (NamingException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no servidor de nomes.", ex); } catch (SQLException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no SQL!", ex); } }
public void delete(EnvAspOtherMatrixMethodDao attrs) throws ConstraintViolatedException, UserException { try { this.attrs = attrs; dao.remove(attrs); } catch (ConstraintViolatedException ex) { ctx.setRollbackOnly(); throw ex; } catch (NamingException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no servidor de nomes.", ex); } catch (SQLException ex) { ctx.setRollbackOnly(); throw new UserException("Erro no SQL!", ex); } }
/** @param path location of the project in the resource tree */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public void deleteProject(String path) throws ProjectException { try { String caller = membership.getProfilePathForConnectedIdentifier(); pep.checkSecurity(caller, path, "delete"); FactoryResourceIdentifier identifier = binding.lookup(path); checkResourceType(identifier, Project.RESOURCE_NAME); Project project = em.find(Project.class, identifier.getId()); if (project == null) { throw new ProjectException("unable to find a project for id " + identifier.getId()); } em.remove(project); String policyId = binding.getProperty(path, FactoryResourceProperty.POLICY_ID, false); pap.deletePolicy(policyId); binding.unbind(path); notification.throwEvent( new Event( path, membership.getProfilePathForConnectedIdentifier(), ProjectService.SERVICE_NAME, Event.buildEventType(ProjectService.SERVICE_NAME, Project.RESOURCE_NAME, "delete"), "")); } catch (Exception e) { ctx.setRollbackOnly(); throw new ProjectException("unable to delete the project at path " + path); } }
/** * Updates an existing {@link UdaDefinition} - if it was not found, nothing will be done. Checks * if the caller is the owner, performs business key uniqueness check if the id has changed and * validates the passed {@link VOUdaDefinition}. * * @param voDef the updated {@link VOUdaDefinition} * @param owner the owning {@link Organization} * @throws OperationNotPermittedException in case the calling {@link Organization} is not the * owner * @throws ValidationException in case the passed {@link VOUdaDefinition} is invalid * @throws ConcurrentModificationException in case the {@link UdaDefinition} to update has been * changed concurrently * @throws NonUniqueBusinessKeyException in case the change leads to a non-unique business key * @throws ObjectNotFoundException in case the {@link UdaDefinition} to update was not found */ void updateDefinition(VOUdaDefinition voDef, Organization owner) throws OperationNotPermittedException, ValidationException, ConcurrentModificationException, NonUniqueBusinessKeyException, ObjectNotFoundException { UdaDefinition existing = ds.getReference(UdaDefinition.class, voDef.getKey()); PermissionCheck.owns(existing, owner, logger, ctx); // target type and encryption flag must not be changed as it will cause // inconsistencies for all depending UDAs voDef.setTargetType(existing.getTargetType().name()); voDef.setEncrypted(existing.isEncrypted()); // verify business key uniqueness UdaDefinition tempForUniquenessCheck = null; tempForUniquenessCheck = UdaAssembler.toUdaDefinition(voDef); tempForUniquenessCheck.setOrganization(owner); tempForUniquenessCheck.setKey(existing.getKey()); try { ds.validateBusinessKeyUniqueness(tempForUniquenessCheck); UdaAssembler.updateUdaDefinition(existing, voDef); } catch (NonUniqueBusinessKeyException e) { logger.logWarn( Log4jLogger.SYSTEM_LOG, e, LogMessageIdentifier.WARN_NON_UNIQUE_BUSINESS_KEY_UDA_DEFINITION); ctx.setRollbackOnly(); throw e; } }
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @WebMethod public Long[] getProximoRangoOrden(@WebParam Long idRecaudador) throws Exception { try { synchronized (RedFacadeImpl.bloqueo) { Recaudador rec = this.recaudadorFacade.getLocked(idRecaudador); Red red = this.getLocked(rec.getRed().getIdRed()); Long rangoValores[] = new Long[2]; rangoValores[0] = red.getNumeroOrdenProximo(); // incluye el extremo rangoValores[1] = rangoValores[0] + (rec.getNumeroOrdenTamRango() - 1); red.setNumeroOrdenProximo(rangoValores[1] + 1); this.merge(red); RedRecaudadorNumeroOrden rrno = new RedRecaudadorNumeroOrden(); rrno.setFechaHora(new Date()); rrno.setNumeroInicial(rangoValores[0]); rrno.setNumeroFinal(rangoValores[1]); rrno.setRecaudador(rec); rrno.setRed(rec.getRed()); this.redRecNumeroOrdenFacade.merge(rrno); return rangoValores; } } catch (Exception e) { context.setRollbackOnly(); e.printStackTrace(); return new Long[0]; } }
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void agregarEntidadesPoliticas(Long idRed, String[] idEntidades, String[] idCuentas) throws Exception { try { List<Entidad> lista = new ArrayList<Entidad>(); Map<Long, String> mapaEntidadCuenta = new HashMap<Long, String>(); for (int i = 0; i < idEntidades.length; i++) { Entidad entidad = new Entidad(); entidad.setIdEntidad(new Long(idEntidades[i])); lista.add(entidad); mapaEntidadCuenta.put(entidad.getIdEntidad(), idCuentas[i]); } Red red = new Red(idRed); for (Entidad f : lista) { EntidadPolitica ep = new EntidadPolitica(); ep.setEntidad(f); ep.setRed(red); ep.setNumeroCuenta(mapaEntidadCuenta.get(f.getIdEntidad())); epFacade.save(ep); } } catch (Exception e) { context.setRollbackOnly(); e.printStackTrace(); throw e; } }
private boolean checkModificationAccessBySlot(String productID) throws OntologyErrorException { return DefaultSecurityManager.getInstance() .checkPersonCanModifyEntity( DefaultSecurityManager.getInstance().getParentProcess(productID), DefaultSecurityManager.getInstance() .getUserID(sessionCoontext.getCallerPrincipal().getName())); }
@PostConstruct public void afterCreate() { System.out.println("In SlessEJB3::afterCreate() marked as PostConstruct"); // Access to getBusinessObject is allowed here ((SessionContext) ejbContext).getBusinessObject(SlessSub.class); }
public String echo(String arg) { System.out.println("PublicSessionBean.echo, arg=" + arg); Principal p = sessionContext.getCallerPrincipal(); System.out.println("PublicSessionBean.echo, callerPrincipal=" + p); System.out.println( "PublicSessionBean.echo, isCallerInRole('EchoUser')=" + sessionContext.isCallerInRole("EchoUser")); try { InitialContext ctx = new InitialContext(); SessionHome home = (SessionHome) ctx.lookup("java:comp/env/ejb/PrivateSession"); Session bean = home.create(); System.out.println("PublicSessionBean.echo, created PrivateSession"); arg = bean.echo(arg); } catch (Exception e) { } return arg; }
/** * < <Descrição do método>> * * @param objetoTeste Descrição do parâmetro * @return Descrição do retorno * @throws ControladorException */ public Object inserirTeste(Object objetoTeste) throws ControladorException { try { return repositorioUtil.inserir(objetoTeste); } catch (ErroRepositorioException ex) { sessionContext.setRollbackOnly(); throw new ControladorException("erro.sistema", ex); } }
/** * Gets the caller authorization. * * @param methodname not null methodname. * @param classname not null classname. * @return {@link Authorization}. * @throws OntologyErrorException if an error occurs in ontology back end */ private Authorization getCallerAuthorization(String methodname, String classname) throws OntologyErrorException { return DefaultSecurityManager.getInstance() .createAuthorization( organizationEntity.getUser(sessionCoontext.getCallerPrincipal().getName()).getID(), methodname, classname); }
@SuppressWarnings("unchecked") @RolesAllowed({"BANKADMIN", "BANKUSER"}) public List<Transaction> getAllTransactionsForUser(int start, int size) { Query q = em.createNamedQuery("getAllTransactionForUser"); q.setMaxResults(size); q.setFirstResult(start); q.setParameter("userId", sctx.getCallerPrincipal().getName()); return q.getResultList(); }
/** * This checks every not administrator caller if he can change the process model. <br> * this returns true if the process (in this context call) can be changed from the caller. * * @param parameters the method parameter. * @return true if the caller can change the process. * @throws OntologyErrorException if an error occurs in ontology back end */ private boolean checkNotAdminUser(Object[] parameters) throws OntologyErrorException { String modelID = (String) parameters[0]; LOG.debug("checkNotAdminUser PARAM[0] " + modelID); return DefaultSecurityManager.getInstance() .checkPersonCanModifyEntity( modelID, organizationEntity.getUser(sessionCoontext.getCallerPrincipal().getName()).getID()); }
/** * < <Descrição do método>> * * @param filtroTeste Descrição do parâmetro * @param nomePacoteObjeto Descrição do parâmetro * @return Descrição do retorno * @throws ControladorException */ public Collection pesquisarTeste(Filtro filtroTeste, String nomePacoteObjeto) throws ControladorException { try { return repositorioUtil.pesquisar(filtroTeste, nomePacoteObjeto); } catch (ErroRepositorioException ex) { sessionContext.setRollbackOnly(); throw new ControladorException("erro.sistema", ex); } }
@Override public void beforeCompletion() throws EJBException, RemoteException { loger.log( Level.INFO, simpleDateHere.format(new Date()).toString() + " || Transakcja o ID: " + IDTransakcji + " przed zakonczeniem przez użytownka " + sessionContext.getCallerPrincipal().getName()); }
public String[] createUpdateETBooking(ETBookingServiceVO objETBookingServiceVO) { logger.info("createUpdateETBooking Entered"); Connection connection = null; String intBookingHeaderId = null; String intPackDtlId = null; String intPoAndInvDtlId = null; String intContainerDtlId = null; String intcontStuffDtlId = null; String[] bookingStatus = new String[3]; JournalEntryDAO objJournalEntryDAO = null; ArrayList<String> journalIdArrayList = null; try { connection = dataSource.getConnection(); intBookingHeaderId = ETIntegrationDAO.insertETBookingHeaderDetails(connection, objETBookingServiceVO); if (intBookingHeaderId != null) { objETBookingServiceVO.setIntBookingHeaderId(intBookingHeaderId); intPackDtlId = ETIntegrationDAO.insertETPackDetails(connection, objETBookingServiceVO); intPoAndInvDtlId = ETIntegrationDAO.insertETPoAndInvDetails(connection, objETBookingServiceVO); intContainerDtlId = ETIntegrationDAO.insertETSContainerDtl(connection, objETBookingServiceVO); intcontStuffDtlId = ETIntegrationDAO.insertETSContStuffDtl(connection, objETBookingServiceVO); if (!"".equals(StringUtility.noNull(objETBookingServiceVO.getShipmentMode()))) bookingStatus = ETIntegrationDAO.validateAndCreateETBooking( connection, intBookingHeaderId, objETBookingServiceVO.getShipmentMode()); if (bookingStatus != null && bookingStatus.length > 0) logger.info("Booking Status.." + bookingStatus[0]); if (bookingStatus != null && bookingStatus.length > 1) logger.info("Booking Id.." + bookingStatus[1]); if (bookingStatus != null && bookingStatus.length > 2) logger.info("Booking Status from DB.." + bookingStatus[2]); /*if(bookingStatus != null && bookingStatus.length > 1){ try{ objJournalEntryDAO=new JournalEntryDAO(); journalIdArrayList=objJournalEntryDAO.getJournalId(bookingStatus[1]); objJournalEntryDAO.pushJournalsToQueue(journalIdArrayList); }catch(Exception ex){ logger.error("Exception in createUpdateETBooking While Pushing Jounal Entries to Queue..",ex); ex.printStackTrace(); } }*/ } logger.info("createUpdateETBooking Exit"); } catch (Exception ex) { ex.printStackTrace(); sessionContext.setRollbackOnly(); throw new EJBException(ex.getMessage()); } finally { ConnectionUtil.closeConnection(connection); } return bookingStatus; }
public void kaufen(String produkt, int anzahl) { System.out.println(sessionContext.getCallerPrincipal().getName()); System.out.println(timeService.getTime()); if (map.containsKey(produkt)) { int alt = map.get(produkt); int neu = alt + anzahl; map.put(produkt, neu); } else { map.put(produkt, anzahl); } }
@Override public void afterBegin() throws EJBException, RemoteException { IDTransakcji = System.currentTimeMillis(); loger.log( Level.INFO, simpleDateHere.format(new Date()).toString() + " || Transakcja o ID: " + IDTransakcji + " zostala rozpoczeta ,przez użytkownika " + sessionContext.getCallerPrincipal().getName()); }
public Transaction getUserTransaction() throws RemoteException { UserTransaction ut = null; try { ut = ejbContext.getUserTransaction(); } catch (IllegalStateException ise) { throw new RemoteException(ise.getMessage()); } if (ut == null) return null; return new Transaction(ut); }
public String callBusinessMethodB(String words) { log.debug("StatefulSessionBean.callBusinessMethodB(String) called"); // Check that my EJBObject is there EJBObject ejbObject = sessionContext.getEJBObject(); if (ejbObject == null) { return "ISNULL:NOT FOUND!!!!!"; } else { return "OK ejbObject is " + ejbObject.toString() + " words " + words; } }