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;
 }
 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());
    }
  }
 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);
   }
 }
예제 #6
0
 @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];
   }
 }
예제 #7
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;
   }
 }
  /**
   * 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;
    }
  }
예제 #9
0
  /** @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);
    }
  }
 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);
   }
 }
 /**
  * < <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);
   }
 }
 /**
  * < <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);
   }
 }
 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;
 }
예제 #14
0
  /**
   * @param name the name of the project
   * @param summary the description of the project
   * @param path the target location of the new resource
   * @param licence
   */
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public void createProject(String path, String name, String summary, String licence)
      throws ProjectException {
    logger.debug("starting project creation");
    try {

      if (name == null || name == "")
        throw new ProjectException("your must specify a name for your project");
      if (summary.length() < 10)
        throw new ProjectException("describe in a more comprehensive manner your project");
      if (summary.length() > 255)
        throw new ProjectException(
            "Your project description is too long. Please make it smaller than 256 bytes.");

      String caller = membership.getProfilePathForConnectedIdentifier();
      // create entity object
      Project project = new Project();
      project.setName(name);
      project.setSummary(summary);
      project.setLicence(licence);
      project.setId(UUID.randomUUID().toString());
      em.persist(project);
      // service orchestration
      pep.checkSecurity(caller, PathHelper.getParentPath(path), "create");

      binding.bind(project.getFactoryResourceIdentifier(), path);
      binding.setProperty(
          path, FactoryResourceProperty.CREATION_TIMESTAMP, System.currentTimeMillis() + "");
      binding.setProperty(
          path, FactoryResourceProperty.LAST_UPDATE_TIMESTAMP, System.currentTimeMillis() + "");
      binding.setProperty(path, FactoryResourceProperty.AUTHOR, caller);

      // create default policy
      String policyId = UUID.randomUUID().toString();
      pap.createPolicy(policyId, PAPServiceHelper.buildOwnerPolicy(policyId, caller, path));
      binding.setProperty(path, FactoryResourceProperty.OWNER, caller);
      binding.setProperty(path, FactoryResourceProperty.POLICY_ID, policyId);

      notification.throwEvent(
          new Event(
              path,
              caller,
              ProjectService.SERVICE_NAME,
              Event.buildEventType(ProjectService.SERVICE_NAME, Project.RESOURCE_NAME, "create"),
              ""));

    } catch (Exception e) {

      ctx.setRollbackOnly();
      throw new ProjectException(e);
    }
  }
  /**
   * Persists that passed {@link UdaDefinition} and checks the business key uniqueness.
   *
   * @param def the {@link UdaDefinition} to persist
   * @throws NonUniqueBusinessKeyException in case a {@link UdaDefinition} with the same id and
   *     target type exist for the owning {@link Organization}
   */
  void createDefinition(UdaDefinition def) throws NonUniqueBusinessKeyException {

    try {
      ds.persist(def);
    } catch (NonUniqueBusinessKeyException e) {
      logger.logWarn(
          Log4jLogger.SYSTEM_LOG,
          e,
          LogMessageIdentifier.WARN_NON_UNIQUE_BUSINESS_KEY_UDA_DEFINITION);
      ctx.setRollbackOnly();
      throw e;
    }
  }
예제 #16
0
파일: UserEJB.java 프로젝트: jacasanova/xcs
  /**
   * Register an user
   *
   * @param registration indicates the user to register
   * @throws LoginDuplicateException if the {@code user} login already exists
   * @throws EmailDuplicateException if the {@code user} email already exists
   * @throws MessagingException exception thrown by the Messaging classes
   */
  @PermitAll
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public void registerUser(final Registration registration)
      throws LoginDuplicateException, EmailDuplicateException, MessagingException {
    if (checkLogin(registration.getLogin())) {
      ctx.setRollbackOnly();

      throw new LoginDuplicateException("Login duplicated");
    }

    if (checkEmail(registration.getEmail())) {
      ctx.setRollbackOnly();

      throw new EmailDuplicateException("Email duplicated");
    }

    em.persist(registration);

    mailer.sendEmail(
        "*****@*****.**",
        registration.getEmail(),
        "Confirm your registration",
        generateRegistrationMessage(registration.getUuid()));
  }
 @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
 public void insertarFormularioImpuesto(
     FileItem bf, String separadorCampos, Integer numeroFormulario) throws Exception {
   try {
     InputStream uploadedStream = bf.getInputStream();
     BufferedReader reader = new BufferedReader(new InputStreamReader(uploadedStream));
     String[] lineas = LectorConfiguracionSet.lineasDelArchivo(new BufferedReader(reader));
     uploadedStream.close();
     for (String linea : lineas) {
       String[] token = LectorConfiguracionSet.tokensDeLaLinea(linea, separadorCampos);
       if (FORM_IMP_POS_FORMULARIO < token.length) {
         if ((numeroFormulario == null)
             || (Integer.parseInt(token[FORM_IMP_POS_FORMULARIO]) == numeroFormulario)) {
           Integer impuesto;
           if (FORM_IMP_POS_IMPUESTO < token.length
               && token[FORM_IMP_POS_IMPUESTO].length() >= 0) {
             impuesto = Integer.parseInt(token[FORM_IMP_POS_IMPUESTO]);
           } else {
             throw new Exception("No contiene numero de impuesto");
           }
           String obligacion = null;
           if (FORM_IMP_POS_OBLIGACION < token.length
               && token[FORM_IMP_POS_OBLIGACION].length() >= 0) {
             obligacion = token[FORM_IMP_POS_OBLIGACION];
           }
           FormularioImpuesto fi = new FormularioImpuesto();
           fi.setImpuesto(impuesto);
           fi.setNumeroFormulario(Integer.parseInt(token[FORM_IMP_POS_FORMULARIO]));
           if (this.total(fi) == 0) {
             fi.setObligacion(obligacion);
             this.save(fi);
           } else {
             fi = this.get(fi);
             fi.setObligacion(obligacion);
             this.update(fi);
           }
         }
       }
     }
   } catch (Exception e) {
     // abortar transaccion
     context.setRollbackOnly();
     e.printStackTrace();
     throw e;
   }
 }
예제 #18
0
  /**
   * @param path the location of the project in the resource tree
   * @param name
   * @param status if the project is on alpha, beta or release state
   * @param summary
   * @param licence
   */
  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public void updateProject(String path, String name, String status, String summary, String licence)
      throws ProjectException {
    try {
      if (name == null || name == "")
        throw new ProjectException("your must specify a name for your project");
      if (summary.length() < 10)
        throw new ProjectException("describe in a more comprehensive manner your project");
      if (summary.length() > 255)
        throw new ProjectException(
            "Your project description is too long. Please make it smaller than 256 bytes.");

      String caller = membership.getProfilePathForConnectedIdentifier();

      pep.checkSecurity(caller, path, "update");
      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());
      }
      project.setName(name);
      project.setDev_status(status);
      project.setSummary(summary);
      project.setLicence(licence);
      em.merge(project);

      binding.setProperty(
          path, FactoryResourceProperty.LAST_UPDATE_TIMESTAMP, System.currentTimeMillis() + "");
      notification.throwEvent(
          new Event(
              path,
              caller,
              ProjectService.SERVICE_NAME,
              Event.buildEventType(ProjectService.SERVICE_NAME, Project.RESOURCE_NAME, "update"),
              ""));

    } catch (Exception e) {
      ctx.setRollbackOnly();
      throw new ProjectException(e);
    }
  }
예제 #19
0
  /**
   * update meta information about the project
   *
   * @param path the location of the project in the resource tree
   * @param os the operating system used by this project
   * @param topics
   * @param language natural language used by this project
   * @param programming_language programming language used by this project
   * @param intended_audience
   */
  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public void updateTagsProject(
      String path,
      String[] os,
      String[] topics,
      String[] language,
      String[] programming_language,
      String[] intended_audience)
      throws ProjectException {
    try {
      String caller = membership.getProfilePathForConnectedIdentifier();

      pep.checkSecurity(caller, path, "update");
      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());
      }
      project.setOs(os);
      project.setTopics(topics);
      project.setSpoken_language(language);
      project.setProgramming_language(programming_language);
      project.setIntended_audience(intended_audience);
      em.merge(project);

      binding.setProperty(
          path, FactoryResourceProperty.LAST_UPDATE_TIMESTAMP, System.currentTimeMillis() + "");
      notification.throwEvent(
          new Event(
              path,
              caller,
              ProjectService.SERVICE_NAME,
              Event.buildEventType(ProjectService.SERVICE_NAME, Project.RESOURCE_NAME, "update"),
              ""));

    } catch (Exception e) {
      ctx.setRollbackOnly();
      throw new ProjectException(e);
    }
  }
예제 #20
0
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public int save(Object... msg) {

    try {
      MsgFeedback mf = new MsgFeedback();

      mf.setName((String) msg[0]);
      mf.setEmail((String) msg[1]);
      mf.setMsg((String) msg[2]);
      mf.setSubjectId((MsgSubject) msg[3]);

      em.persist(mf);
      return mf.getId();

    } catch (Exception e) {
      //			e.printStackTrace();
      context.setRollbackOnly();
      return 0;
    }
  }
예제 #21
0
  @Override
  public IndexableDocument getIndexableDocument(String path) throws IndexingServiceException {
    try {
      // use internal findResource
      Name name = (Name) findResource(path, false);
      IndexableContent content = new IndexableContent();
      content.addContentPart(name.getValue());

      IndexableDocument doc = new IndexableDocument();

      doc.setIndexableContent(content);
      doc.setResourceService(getServiceName());
      doc.setResourceShortName(name.getValue());
      doc.setResourceType(Name.RESOURCE_NAME);
      doc.setResourcePath(path);
      doc.setResourceFRI(name.getFactoryResourceIdentifier());

      return doc;
    } catch (Exception e) {
      ctx.setRollbackOnly();
      logger.error("unable to convert name to IndexableContent " + path, e);
      throw new IndexingServiceException("unable to convert name to IndexableContent" + path, e);
    }
  }
예제 #22
0
  public ArrayList<Integer> cargaMasiva(String file) throws IOException {
    Boolean fallo = false;
    ArrayList<Integer> errores = new ArrayList<Integer>();
    BufferedReader br = null;
    String line = "";
    String splitBy = ";";
    Boolean formato;
    Integer numeroDeLinea = 0;
    Compra CompraNuevo;
    CompraDetalle nuevoDetalle;
    Proveedor p;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {

      br = new BufferedReader(new FileReader(file));
      while ((line = br.readLine()) != null) {
        System.out.println("---- LINEA NUMERO " + Integer.valueOf(numeroDeLinea + 1) + "----");
        System.out.println(line);
        numeroDeLinea++;
        String[] element = line.split(splitBy);
        for (String s : element) {
          System.out.println(s);
        }
        CompraNuevo = new Compra();

        try {
          formato = true;
          if (element[0].compareTo("") != 0
              && element[1].compareTo("") != 0
              && element[2].compareTo("") != 0) {
            try {
              System.out.println(1);
              p = (Proveedor) em.find(Proveedor.class, element[0]);
            } catch (Exception e) {
              System.out.println("No se encontró el proveedor");
              formato = false;
              p = null;
            }
            System.out.println(2);
            CompraNuevo.setProveedor(p);
            System.out.println(3);
            CompraNuevo.setMontoTotal(Integer.valueOf(element[1]));
            System.out.println(4);
            CompraNuevo.setFecha(sdf.parse(element[2]));
            System.out.println(5);
            Integer pos = 3;
            System.out.println(6);
            ArrayList<CompraDetalle> listaDetalle = new ArrayList<CompraDetalle>();

            if ((element.length - 3) % 3 == 0) {
              while (pos < element.length) {
                System.out.print(" ## Detalles ## ");
                System.out.println(
                    Integer.valueOf(pos)
                        + " "
                        + Integer.valueOf(pos + 1)
                        + " "
                        + Integer.valueOf(pos + 2));
                System.out.println(element[pos]);
                System.out.println(element[pos + 1]);
                System.out.println(element[pos + 2]);
                nuevoDetalle = new CompraDetalle();
                Producto pro;
                try {
                  pro = (Producto) em.find(Producto.class, Integer.valueOf(element[pos]));
                  nuevoDetalle.setProducto(pro);
                  nuevoDetalle.setCantidad(Integer.valueOf(element[pos + 1]));
                  nuevoDetalle.setPrecio(Integer.valueOf(element[pos + 2]));
                  nuevoDetalle.setCompra(CompraNuevo);
                  pro.setStock(pro.getStock() + nuevoDetalle.getCantidad());
                  listaDetalle.add(nuevoDetalle);
                } catch (Exception e) {
                  System.out.println("No se encontro del producto");
                  pro = null;
                  formato = false;
                }
                pos += 3;
              }

            } else {
              formato = false;
            }

          } else {
            System.out.println("Fallo formato");
            formato = false;
          }
        } catch (Exception e) {
          System.out.println("Salto excepcion por campos vacios");
          System.out.println("Ex" + e.getMessage());
          formato = false;
        }
        if (formato) {
          System.out.println("Intento Persistir");
          if (!this.persistir(CompraNuevo)) {
            fallo = true;
            errores.add(numeroDeLinea);
          }
        } else {
          fallo = true;
          errores.add(numeroDeLinea);
        }
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    if (fallo) {
      context.setRollbackOnly();
    }
    return errores;
  }
예제 #23
0
  @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
  public void agregarFacturadores(Long idRed, String[] idFacturadores, String[] idCuentas)
      throws Exception {
    try {
      HabilitacionFactRed ejemplo = new HabilitacionFactRed();
      ejemplo.setRed(new Red(idRed));
      // se trae todos los facturadores de esta red
      List<Facturador> listaFacturadoresHabilitados = this.obtenerFacturadoresHabilitados(idRed);
      // aqui se cargara los facturadores recibidos
      List<Facturador> listaFacturadoresRecibidos = new ArrayList<Facturador>();
      // Map<Long, Long> mapaFacturadorCuenta = new HashMap();
      Map<Long, String> mapaFacturadorCuenta = new HashMap<Long, String>();
      for (int i = 0; i < idFacturadores.length; i++) {
        Facturador facturador = new Facturador();
        facturador.setIdFacturador(new Long(idFacturadores[i]));
        listaFacturadoresRecibidos.add(facturador);
        // mapaFacturadorCuenta.put(facturador.getIdFacturador(), new Long(idCuentas[i]));
        mapaFacturadorCuenta.put(facturador.getIdFacturador(), idCuentas[i]);
      }
      // en esta lista se cargara los que deberan agregarse
      // que dueron los recibidos y que no estan habilitados actualmente
      List<Facturador> listaFacturadoresParaAgregar = new ArrayList<Facturador>();
      // copiamos todos los recibidos
      listaFacturadoresParaAgregar.addAll(listaFacturadoresRecibidos);
      // sacamos los que ya estan habilitados
      // y la lista ya tendra solo aquellos que habra que agregar
      listaFacturadoresParaAgregar.removeAll(listaFacturadoresHabilitados);

      // en esta lista se cargara los que deberan borrarse
      // que estan habilitados actualmente pero que no estan entre los recibidos
      // por tanto hay que borrarlos
      List<Facturador> listaFacturadoresParaBorrar = new ArrayList<Facturador>();
      // copiamos todos los recibidos
      listaFacturadoresParaBorrar.addAll(listaFacturadoresHabilitados);
      // sacamos los que ya estan habilitados
      // y la lista ya tendra solo aquellos que habra que agregar
      listaFacturadoresParaBorrar.removeAll(listaFacturadoresRecibidos);

      // agregamos los nuevos
      for (Facturador f : listaFacturadoresParaAgregar) {
        HabilitacionFactRed hab = new HabilitacionFactRed();
        HabilitacionFactRedPK habPK = new HabilitacionFactRedPK();
        habPK.setRed(idRed);
        habPK.setFacturador(f.getIdFacturador());
        hab.setHabilitacionFactRedPK(habPK);
        // hab.setCuenta(new Cuenta(mapaFacturadorCuenta.get(f.getIdFacturador())));
        hab.setNumeroCuenta(mapaFacturadorCuenta.get(f.getIdFacturador()));
        habilitacionFacturadorRedFacade.save(hab);
      }

      // borramos los que ya no estan
      HabilitacionFactRedPK habPK = new HabilitacionFactRedPK();
      habPK.setRed(idRed);
      for (Facturador f : listaFacturadoresParaBorrar) {
        habPK.setFacturador(f.getIdFacturador());
        this.habilitacionFacturadorRedFacade.delete(habPK);
      }
    } catch (Exception e) {
      context.setRollbackOnly();
      e.printStackTrace();
      throw e;
    }
  }
예제 #24
0
  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public void createName(String path, String value) throws GreetingServiceException {

    logger.info("createName(...) called");
    logger.debug("params : path=" + path + ", value=" + value);

    try {
      // Checking if the connected user has the permission to create a resource giving pep :
      //  - the profile path of the connected user (caller)
      //  - the parent of the path (we check the 'create' permission on the parent of the given
      // path)
      //  - the name of the permission to check ('create')
      String caller = membership.getProfilePathForConnectedIdentifier();
      pep.checkSecurity(caller, PathHelper.getParentPath(path), "create");

      // STARTING SPECIFIC EXTERNAL SERVICE RESOURCE CREATION OR METHOD CALL
      Name name = new Name();
      name.setId(UUID.randomUUID().toString());
      name.setValue(value);
      em.persist(name);
      // END OF EXTERNAL INVOCATION

      // Binding the external resource in the naming using the generated resource ID :
      binding.bind(name.getFactoryResourceIdentifier(), path);

      // Need to set some properties on the node :
      binding.setProperty(
          path, FactoryResourceProperty.CREATION_TIMESTAMP, "" + System.currentTimeMillis());
      binding.setProperty(
          path, FactoryResourceProperty.LAST_UPDATE_TIMESTAMP, "" + System.currentTimeMillis());
      binding.setProperty(path, FactoryResourceProperty.AUTHOR, caller);

      // Need to create a new security policy for this resource :
      // Giving the caller the Owner permission (aka all permissions)
      String policyId = UUID.randomUUID().toString();
      pap.createPolicy(policyId, PAPServiceHelper.buildOwnerPolicy(policyId, caller, path));
      pap.createPolicy(
          UUID.randomUUID().toString(),
          PAPServiceHelper.buildPolicy(policyId, caller, path, new String[] {"read"}));

      // Setting security properties on the node :
      binding.setProperty(path, FactoryResourceProperty.OWNER, caller);
      binding.setProperty(path, FactoryResourceProperty.POLICY_ID, policyId);

      // Using the notification service to throw an event :
      notification.throwEvent(
          new Event(
              path,
              caller,
              Name.RESOURCE_NAME,
              Event.buildEventType(GreetingService.SERVICE_NAME, Name.RESOURCE_NAME, "create"),
              ""));

      // Using the indexing service to index the name newly created
      indexing.index(getServiceName(), path);
    } catch (Exception e) {
      ctx.setRollbackOnly();
      logger.error("unable to create the name at path " + path, e);
      throw new GreetingServiceException("unable to create the name at path " + path, e);
    }
  }
  /**
   * < <Descrição do método>>
   *
   * @param tabelaAuxiliarAbstrata Descrição do parâmetro
   * @throws ControladorException
   */
  public void atualizarTabelaAuxiliar(TabelaAuxiliarAbstrata tabelaAuxiliarAbstrata)
      throws ControladorException {

    try {

      // -----VALIDAÇÃO DOS TIMESTAMP PARA ATUALIZAÇÃO DE CADASTRO

      // Validação para Tabela Auxiliar
      if (tabelaAuxiliarAbstrata instanceof TabelaAuxiliar) {
        // Cria o objeto
        TabelaAuxiliar tabelaAuxiliar = null;

        // Faz o casting
        tabelaAuxiliar = (TabelaAuxiliar) tabelaAuxiliarAbstrata;

        // Cria o filtro
        FiltroTabelaAuxiliar filtroTabelaAuxiliar = new FiltroTabelaAuxiliar();
        // Pega o nome do pacote do objeto
        String nomePacoteObjeto = tabelaAuxiliar.getClass().getName();

        // Seta os parametros do filtro
        filtroTabelaAuxiliar.adicionarParametro(
            new ParametroSimples(FiltroTabelaAuxiliar.ID, tabelaAuxiliar.getId()));

        // Pesquisa a coleção de acordo com o filtro passado
        Collection tabelasAuxiliares =
            repositorioUtil.pesquisar(filtroTabelaAuxiliar, nomePacoteObjeto);
        TabelaAuxiliar tabelaAuxiliarNaBase = (TabelaAuxiliar) tabelasAuxiliares.iterator().next();

        // Verifica se a data de alteração do objeto gravado na base é
        // maior que a na instancia
        if ((tabelaAuxiliarNaBase
            .getUltimaAlteracao()
            .after(tabelaAuxiliar.getUltimaAlteracao()))) {
          sessionContext.setRollbackOnly();
          throw new ControladorException("erro.atualizacao.timestamp");
        }
        // Faz uma referencia ao objeto
        tabelaAuxiliarAbstrata = tabelaAuxiliar;
      }

      // Validação para Tabela Auxiliar Abreviada
      if (tabelaAuxiliarAbstrata instanceof TabelaAuxiliarAbreviada) {
        // Cria o objeto
        TabelaAuxiliarAbreviada tabelaAuxiliarAbreviada = null;

        // Faz o casting
        tabelaAuxiliarAbreviada = (TabelaAuxiliarAbreviada) tabelaAuxiliarAbstrata;

        // Cria o filtro
        FiltroTabelaAuxiliarAbreviada filtroTabelaAuxiliarAbreviada =
            new FiltroTabelaAuxiliarAbreviada();
        // Pega o nome do pacote do objeto
        String nomePacoteObjeto = tabelaAuxiliarAbreviada.getClass().getName();

        // Seta os parametros do filtro
        filtroTabelaAuxiliarAbreviada.adicionarParametro(
            new ParametroSimples(
                FiltroTabelaAuxiliarAbreviada.ID, tabelaAuxiliarAbreviada.getId()));

        // Pesquisa a coleção de acordo com o filtro passado
        Collection tabelasAuxiliaresAbreviadas =
            repositorioUtil.pesquisar(filtroTabelaAuxiliarAbreviada, nomePacoteObjeto);
        TabelaAuxiliar tabelaAuxiliarAbreviadaNaBase =
            (TabelaAuxiliar) tabelasAuxiliaresAbreviadas.iterator().next();

        // Verifica se a data de alteração do objeto gravado na base é
        // maior que a na instancia
        if ((tabelaAuxiliarAbreviadaNaBase
            .getUltimaAlteracao()
            .after(tabelaAuxiliarAbreviada.getUltimaAlteracao()))) {
          sessionContext.setRollbackOnly();
          throw new ControladorException("erro.atualizacao.timestamp");
        }
        // Faz uma referencia ao objeto
        tabelaAuxiliarAbstrata = tabelaAuxiliarAbreviada;
      }

      // Validação para Tabela Auxiliar Faixa
      if (tabelaAuxiliarAbstrata instanceof TabelaAuxiliarFaixa) {
        // Cria o objeto
        TabelaAuxiliarFaixa tabelaAuxiliarFaixa = null;

        // Faz o casting
        tabelaAuxiliarFaixa = (TabelaAuxiliarFaixa) tabelaAuxiliarAbstrata;

        // Cria o filtro
        FiltroTabelaAuxiliarFaixa filtroTabelaAuxiliarFaixa = new FiltroTabelaAuxiliarFaixa();
        // Pega o nome do pacote do objeto
        String nomePacoteObjeto = tabelaAuxiliarFaixa.getClass().getName();

        // Seta os parametros do filtro
        filtroTabelaAuxiliarFaixa.adicionarParametro(
            new ParametroSimples(FiltroTabelaAuxiliarFaixa.ID, tabelaAuxiliarFaixa.getId()));

        // Pesquisa a coleção de acordo com o filtro passado
        Collection tabelasAuxiliaresFaixas =
            repositorioUtil.pesquisar(filtroTabelaAuxiliarFaixa, nomePacoteObjeto);
        TabelaAuxiliarFaixa tabelaAuxiliarFaixaNaBase =
            (TabelaAuxiliarFaixa) tabelasAuxiliaresFaixas.iterator().next();

        // Verifica se a data de alteração do objeto gravado na base é
        // maior que a na instancia
        if ((tabelaAuxiliarFaixaNaBase
            .getUltimaAlteracao()
            .after(tabelaAuxiliarFaixa.getUltimaAlteracao()))) {
          sessionContext.setRollbackOnly();
          throw new AtualizacaoInvalidaException();
        }
        // Faz uma referencia ao objeto
        tabelaAuxiliarAbstrata = tabelaAuxiliarFaixa;
      }

      // Validação para Tabela Auxiliar
      if (tabelaAuxiliarAbstrata instanceof TabelaAuxiliarTipo) {
        // Cria o objeto
        TabelaAuxiliarTipo tabelaAuxiliarTipo = null;

        // Faz o casting
        tabelaAuxiliarTipo = (TabelaAuxiliarTipo) tabelaAuxiliarAbstrata;

        // Cria o filtro
        FiltroTabelaAuxiliarTipo filtroTabelaAuxiliarTipo = new FiltroTabelaAuxiliarTipo();
        // Pega o nome do pacote do objeto
        String nomePacoteObjeto = tabelaAuxiliarTipo.getClass().getName();

        // Seta os parametros do filtro
        filtroTabelaAuxiliarTipo.adicionarParametro(
            new ParametroSimples(FiltroTabelaAuxiliarTipo.ID, tabelaAuxiliarTipo.getId()));

        // Pesquisa a coleção de acordo com o filtro passado
        Collection tabelasAuxiliaresTipos =
            repositorioUtil.pesquisar(filtroTabelaAuxiliarTipo, nomePacoteObjeto);
        TabelaAuxiliarTipo tabelaAuxiliarTipoNaBase =
            (TabelaAuxiliarTipo) tabelasAuxiliaresTipos.iterator().next();

        // Verifica se a data de alteração do objeto gravado na base é
        // maior que a na instancia
        if ((tabelaAuxiliarTipoNaBase
            .getUltimaAlteracao()
            .after(tabelaAuxiliarTipo.getUltimaAlteracao()))) {
          sessionContext.setRollbackOnly();
          throw new ControladorException("erro.atualizacao.timestamp");
        }
        // Faz uma referencia ao objeto
        tabelaAuxiliarAbstrata = tabelaAuxiliarTipo;
      }

      // Seta a data/hora
      tabelaAuxiliarAbstrata.setUltimaAlteracao(new Date());
      // Atualiza objeto

      repositorioUtil.atualizar(tabelaAuxiliarAbstrata);
    } catch (ErroRepositorioException ex) {
      sessionContext.setRollbackOnly();
      throw new ControladorException("erro.sistema", ex);
    }
  }