/* (non-Javadoc)
   * @see #updateTaxMap(org.mifosplatform.infrastructure.core.api.JsonCommand, java.lang.Long)
   */
  @Transactional
  @Override
  public CommandProcessingResult updateTaxMap(final JsonCommand command, final Long taxMapId) {
    TaxMap taxMap = null;
    try {
      this.context.authenticatedUser();
      this.apiJsonDeserializer.validateForCreate(command);
      taxMap = retrieveTaxMapById(taxMapId);
      final Map<String, Object> changes = taxMap.update(command);

      if (!changes.isEmpty()) {
        this.taxMapRepository.saveAndFlush(taxMap);
      }

      return new CommandProcessingResultBuilder()
          .withCommandId(command.commandId())
          .withEntityId(taxMap.getId())
          .with(changes)
          .build();
    } catch (final DataIntegrityViolationException dve) {
      if (dve.getCause() instanceof ConstraintViolationException) {
        handleDataIntegrityIssues(command, dve);
      }
      return new CommandProcessingResult(Long.valueOf(-1));
    }
  }
  /*
   * Guaranteed to throw an exception no matter what the data integrity issue
   * is.
   */
  private void handleOfficeDataIntegrityIssues(
      final JsonCommand command, DataIntegrityViolationException dve) {

    Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("externalid_org")) {
      final String externalId = command.stringValueOfParameterNamed("externalId");
      throw new PlatformDataIntegrityException(
          "error.msg.office.duplicate.externalId",
          "Office with externalId `" + externalId + "` already exists",
          "externalId",
          externalId);
    } else if (realCause.getMessage().contains("name_org")) {
      final String name = command.stringValueOfParameterNamed("name");
      throw new PlatformDataIntegrityException(
          "error.msg.office.duplicate.name",
          "Office with name `" + name + "` already exists",
          "name",
          name);
    }

    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException(
        "error.msg.office.unknown.data.integrity.issue",
        "Unknown data integrity issue with resource.");
  }
  public void testInterceptorWithFlushFailure() throws Throwable {
    MockControl sfControl = MockControl.createControl(SessionFactory.class);
    SessionFactory sf = (SessionFactory) sfControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    Session session = (Session) sessionControl.getMock();
    sf.openSession();
    sfControl.setReturnValue(session, 1);
    session.getSessionFactory();
    sessionControl.setReturnValue(sf, 1);
    SQLException sqlEx = new SQLException("argh", "27");
    session.flush();
    ConstraintViolationException jdbcEx = new ConstraintViolationException("", sqlEx, null);
    sessionControl.setThrowable(jdbcEx, 1);
    session.close();
    sessionControl.setReturnValue(null, 1);
    sfControl.replay();
    sessionControl.replay();

    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sf);
    try {
      interceptor.invoke(new TestInvocation(sf));
      fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
      // expected
      assertEquals(jdbcEx, ex.getCause());
    }

    sfControl.verify();
    sessionControl.verify();
  }
Exemplo n.º 4
0
  public void testUpdateUser() throws Exception {
    User user = dao.get(1L);

    Address address = user.getAddress();
    address.setAddress1("new address");
    user.setTimeZone("US/Central");

    dao.saveUser(user);

    user = dao.get(1L);
    assertEquals(address, user.getAddress());
    assertEquals("new address", user.getAddress().getAddress1());
    assertEquals("US/Central", user.getTimeZone());

    // verify that violation occurs when adding new user with same username
    user.setId(null);

    endTransaction();

    try {
      dao.saveUser(user);
      // flush();
      fail("saveUser didn't throw DataIntegrityViolationException");
    } catch (DataIntegrityViolationException e) {
      assertNotNull(e);
      log.debug("expected exception: " + e.getMessage());
    }
  }
  @Transactional
  @Override
  public void generateStatementPdf(final Long billId) {

    try {
      BillMaster billMaster = this.billMasterRepository.findOne(billId);
      final String fileLocation = FileUtils.MIFOSX_BASE_DIR;
      /** Recursively create the directory if it does not exist * */
      if (!new File(fileLocation).isDirectory()) {
        new File(fileLocation).mkdirs();
      }
      final String statementDetailsLocation = fileLocation + File.separator + "StatementPdfFiles";
      if (!new File(statementDetailsLocation).isDirectory()) {
        new File(statementDetailsLocation).mkdirs();
      }
      final String printStatementLocation =
          statementDetailsLocation + File.separator + "Bill_" + billMaster.getId() + ".pdf";
      final String jpath = fileLocation + File.separator + "jasper";
      final String tenant = ThreadLocalContextUtil.getTenant().getTenantIdentifier();
      final String jfilepath = jpath + File.separator + "Statement_" + tenant + ".jasper";
      File destinationFile = new File(jfilepath);
      if (!destinationFile.exists()) {
        File sourceFile =
            new File(
                this.getClass().getClassLoader().getResource("Files/Statement.jasper").getFile());
        FileUtils.copyFileUsingApacheCommonsIO(sourceFile, destinationFile);
      }
      final Connection connection = this.dataSource.getConnection();
      Map<String, Object> parameters = new HashMap<String, Object>();
      final Integer id = Integer.valueOf(billMaster.getId().toString());
      parameters.put("param1", id);
      parameters.put("SUBREPORT_DIR", jpath + "" + File.separator);
      final JasperPrint jasperPrint =
          JasperFillManager.fillReport(jfilepath, parameters, connection);
      JasperExportManager.exportReportToPdfFile(jasperPrint, printStatementLocation);
      billMaster.setFileName(printStatementLocation);
      this.billMasterRepository.save(billMaster);
      connection.close();
      System.out.println("Filling report successfully...");

    } catch (final DataIntegrityViolationException ex) {

      LOGGER.error("Filling report failed..." + ex.getLocalizedMessage());
      System.out.println("Filling report failed...");
      ex.printStackTrace();

    } catch (final JRException | JRRuntimeException e) {

      LOGGER.error("Filling report failed..." + e.getLocalizedMessage());
      System.out.println("Filling report failed...");
      e.printStackTrace();

    } catch (final Exception e) {

      LOGGER.error("Filling report failed..." + e.getLocalizedMessage());
      System.out.println("Filling report failed...");
      e.printStackTrace();
    }
  }
 private void handleCodeDataIntegrityIssues(
     JsonCommand command, DataIntegrityViolationException dve) {
   Throwable realCause = dve.getMostSpecificCause();
   LOGGER.error(dve.getMessage(), dve);
   throw new PlatformDataIntegrityException(
       "error.msg.cund.unknown.data.integrity.issue",
       "Unknown data integrity issue with resource: " + realCause.getMessage());
 }
  public String deleteSettleMargin() {
    this.logger.debug("enter deleteSettleMargin");

    String[] ids = this.request.getParameterValues("ids");

    if (ids != null) {
      String prompt = "";
      int count = 0;
      for (int i = 0; i < ids.length; i++) {
        String[] idArr = ids[i].split(",");
        String firmID = idArr[0];
        String commodityID = idArr[1];
        try {
          String sysStatus = this.firmSpecialService.getSystemStatus();
          if (("5".equals(sysStatus)) || ("6".equals(sysStatus))) {
            addReturnValue(-1, 151103L, new Object[] {"此时市场状态不允许删除!"});
            count++;
            break;
          }

          FirmSettleMargin settleMargin = new FirmSettleMargin();
          settleMargin.setFirmID(firmID);
          settleMargin.setCommodityID(commodityID);
          getService().delete(settleMargin);

          writeOperateLog(
              1505,
              "删除特殊商品交收保证金! 交易商ID:"
                  + settleMargin.getFirmID()
                  + ",商品ID:"
                  + settleMargin.getCommodityID(),
              1,
              "");
        } catch (DataIntegrityViolationException e) {
          e.getStackTrace();
          prompt = prompt + ids[i] + ",";
          addReturnValue(-1, 151103L, new Object[] {"[" + ids[i] + "]与其他数据关联,删除失败!"});
          count++;
        }
      }
      if (!prompt.equals("")) {
        prompt = prompt.substring(0, prompt.length() - 1);
        prompt = prompt + "与其他数据关联,不能删除!";
        addReturnValue(0, 151103L, new Object[] {prompt});
        count++;
      }
      if (count == 0) {
        addReturnValue(1, 119903L);
      }
    } else {
      addReturnValue(-1, 151103L, new Object[] {"删除主键为空或错误,请修改~!"});
    }

    return "success";
  }
  @Override
  public CommandProcessingResult createGameMediaAsset(JsonCommand command) {

    MediaAsset mediaAsset = null;
    try {
      this.context.authenticatedUser();
      fromApiJsonDeserializer.validateForCreateGame(command.json());
      mediaAsset = MediaAsset.fromGameMediaJsonForm(command);

      PartnerAccountData contentProvider =
          mediaSettlementReadPlatformService.retrieveContentProviderPartnerId(
              mediaAsset.getContentProvider());
      if (!command.stringValueOfParameterNamed("mediaCategory").equalsIgnoreCase("Games")) {
        throw new NotaContentProviderException(
            "This game category is not available", "this game category is not available");
      }
      if (contentProvider == null) {
        throw new NotaContentProviderException();
      } else if (contentProvider != null) {
        if (!contentProvider.getPartnerName().equalsIgnoreCase("Content Provider")) {
          throw new NotaContentProviderException();
        }
      }
      mediaAsset.setContentProvider(contentProvider.getId().toString());
      assetRepository.save(mediaAsset);

      /*final JsonArray gameData = command.arrayOfParameterNamed("gameMediaData").getAsJsonArray();
      for(int i=0; i<gameData.size();i++){
      	String currentData = gameData.get(i).toString();
      	final JsonElement element = fromApiJsonHelper.parse(currentData);

      	 final BigDecimal amount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element);
        final String category = fromApiJsonHelper.extractStringNamed("category", element);
        final String mediaContentProvider = fromApiJsonHelper.extractStringNamed("mediaContentProvider", element);
        final String mt = fromApiJsonHelper.extractStringNamed("mediaType", element);
        final Character mediaType = mt.equals("Flat")?'F':'P';
        final Long sequence = fromApiJsonHelper.extractLongNamed("sequence", element);
        final String source = fromApiJsonHelper.extractStringNamed("source", element);


        Settlement settlement = Settlement.fromJson(mediaAsset.getId(),amount,category,mediaContentProvider,mediaType,sequence,source);
        settlementJpaRepository.save(settlement);
      }*/

    } catch (EmptyResultDataAccessException e) {
      throw new PlatformDataIntegrityException(
          "not.a.valid.content.provider", "not.a.valid.content.provider", "ContentProvider");
    } catch (DataIntegrityViolationException dve) {
      handleCodeDataIntegrityIssues(command, dve);
      throw new DataIntegrityViolationException(dve.toString());
    } catch (Exception e) {
      throw new DataIntegrityViolationException(e.toString());
    }
    return new CommandProcessingResult(mediaAsset.getId());
  }
  @Transactional
  @Override
  public String generateInovicePdf(final Long invoiceId) {

    final String fileLocation = FileUtils.MIFOSX_BASE_DIR;
    /** Recursively create the directory if it does not exist * */
    if (!new File(fileLocation).isDirectory()) {
      new File(fileLocation).mkdirs();
    }
    final String InvoiceDetailsLocation = fileLocation + File.separator + "InvoicePdfFiles";
    if (!new File(InvoiceDetailsLocation).isDirectory()) {
      new File(InvoiceDetailsLocation).mkdirs();
    }
    final String printInvoiceLocation =
        InvoiceDetailsLocation + File.separator + "Invoice_" + invoiceId + ".pdf";
    final Integer id = Integer.valueOf(invoiceId.toString());
    try {

      final String jpath = fileLocation + File.separator + "jasper";
      final String tenant = ThreadLocalContextUtil.getTenant().getTenantIdentifier();
      final String jasperfilepath = jpath + File.separator + "Invoicereport_" + tenant + ".jasper";
      File destinationFile = new File(jasperfilepath);
      if (!destinationFile.exists()) {
        File sourceFile =
            new File(
                this.getClass()
                    .getClassLoader()
                    .getResource("Files/Invoicereport.jasper")
                    .getFile());
        FileUtils.copyFileUsingApacheCommonsIO(sourceFile, destinationFile);
      }
      final Connection connection = this.dataSource.getConnection();
      Map<String, Object> parameters = new HashMap<String, Object>();
      parameters.put("param1", id);
      final JasperPrint jasperPrint =
          JasperFillManager.fillReport(jasperfilepath, parameters, connection);
      JasperExportManager.exportReportToPdfFile(jasperPrint, printInvoiceLocation);
      connection.close();
      System.out.println("Filling report successfully...");

    } catch (final DataIntegrityViolationException ex) {
      LOGGER.error("Filling report failed..." + ex.getLocalizedMessage());
      System.out.println("Filling report failed...");
      ex.printStackTrace();
    } catch (final JRException | JRRuntimeException e) {
      LOGGER.error("Filling report failed..." + e.getLocalizedMessage());
      System.out.println("Filling report failed...");
      e.printStackTrace();
    } catch (final Exception e) {
      LOGGER.error("Filling report failed..." + e.getLocalizedMessage());
      System.out.println("Filling report failed...");
      e.printStackTrace();
    }
    return printInvoiceLocation;
  }
Exemplo n.º 10
0
  // public functions
  @Override
  @Transactional
  public CommandProcessingResult createPublicUser(final JsonCommand command) {
    try {
      this.userDataValidator.validateCreate(command.getJsonCommand());

      User user = User.fromJson(command, false, true);

      generateKeyUsedForPasswordSalting(user);
      final String encodePassword = this.applicationPasswordEncoder.encode(user);
      user.updatePassword(encodePassword);

      this.userRepository.save(user);

      final JsonElement element = this.fromJsonHelper.parse(command.getJsonCommand());
      final String returnUrl = this.fromJsonHelper.extractStringNamed(ReturnUrlParamName, element);

      final String email = user.getUsername();
      final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      final String nowDate = sf.format(DateTime.now().toDate());
      final String text = nowDate + email + nowDate + Math.random();

      final String otp = new String(Base64.encode(text.getBytes()));
      final UserOtp userOtp =
          UserOtp.createOtp(user, email, otp.substring(3, otp.length() - 5), returnUrl);

      this.userOtpRepository.save(userOtp);

      final String finalOtp = userOtp.getOtp();
      final String verificationLink =
          DefaultAppUrl + "userapi/activate" + "?e=" + email + "&uas=" + finalOtp;
      String toEmails[] = new String[] {email};
      this.emailSenderService.sendEmail(
          toEmails,
          null,
          null,
          EmailTemplates.activateUserEmailSubject(),
          EmailTemplates.activateUserEmailTemplate(user.getName(), verificationLink));
      return new CommandProcessingResultBuilder().withSuccessStatus().build();
    } catch (DataIntegrityViolationException ex) {
      ex.printStackTrace();
      final Throwable realCause = ex.getCause();
      if (realCause.getMessage().toLowerCase().contains("email")) {
        throw new PlatformDataIntegrityException(
            "error.msg.email.already.exist",
            "The email provided already exitst in the system." + realCause.getMessage());
      }
      throw new PlatformDataIntegrityException(
          "error.msg.unknown.data.integrity.issue",
          "Unknown data integrity issue with resource: " + realCause.getMessage());
    }
  }
  private void handleDataIntegrityIssues(
      final JsonCommand element, final DataIntegrityViolationException dve) {

    Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("serial_no_constraint")) {
      throw new PlatformDataIntegrityException(
          "validation.error.msg.inventory.item.duplicate.serialNumber",
          "validation.error.msg.inventory.item.duplicate.serialNumber",
          "validation.error.msg.inventory.item.duplicate.serialNumber",
          "");
    }

    LOGGER.error(dve.getMessage(), dve);
  }
  private void handleDataIntegrityIssues(
      final JsonCommand element, final DataIntegrityViolationException dve) {

    Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("UK_PRICING_COMPKEY")) {
      throw new PlatformDataIntegrityException(
          "event.pricing.price.already.exist",
          "event.pricing.price.already.exist",
          "event.pricing.price.already.exist",
          "");
    }

    logger.error(dve.getMessage(), dve);
  }
  /**
   * @param command
   * @param dve
   */
  private void handleGLClosureIntegrityIssues(
      final JsonCommand command, final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("office_id_closing_date")) {
      throw new GLClosureDuplicateException(
          command.longValueOfParameterNamed(GLClosureJsonInputParams.OFFICE_ID.getValue()),
          new LocalDate(
              command.DateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue())));
    }

    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException(
        "error.msg.glClosure.unknown.data.integrity.issue",
        "Unknown data integrity issue with resource GL Closure: " + realCause.getMessage());
  }
Exemplo n.º 14
0
  public void addGame(Game game) throws GameServiceException {
    SimpleJdbcInsert insertGame = new SimpleJdbcInsert(getDataSource()).withTableName("games");
    Map<String, Object> gameParameters = new HashMap<String, Object>(5);
    gameParameters.put("gameid", game.getGameId());
    gameParameters.put("startTime", game.getStartTime());
    gameParameters.put("teamHomeid", game.getTeamHome().getTeamId());
    gameParameters.put("teamAwayid", game.getTeamAway().getTeamId());
    gameParameters.put("venueid", game.getVenue().getVenueId());

    try {
      insertGame.execute(gameParameters);
    } catch (DataIntegrityViolationException divex) {
      log.warning("Duplicate entry");
      throw new GameServiceException(divex.getMessage(), divex);
    }
  }
  private void handleDataIntegrityIssues(
      final JsonCommand command, final DataIntegrityViolationException dve) {

    Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("external_id")) {

      final String externalId = command.stringValueOfParameterNamed("externalId");
      throw new PlatformDataIntegrityException(
          "error.msg.client.duplicate.externalId",
          "Client with externalId `" + externalId + "` already exists",
          "externalId",
          externalId);
    } else if (realCause.getMessage().contains("account_no_UNIQUE")) {
      final String accountNo = command.stringValueOfParameterNamed("accountNo");
      throw new PlatformDataIntegrityException(
          "error.msg.client.duplicate.accountNo",
          "Client with accountNo `" + accountNo + "` already exists",
          "accountNo",
          accountNo);
    } else if (realCause.getMessage().contains("email_key")) {
      final String email = command.stringValueOfParameterNamed("email");
      throw new PlatformDataIntegrityException(
          "error.msg.client.duplicate.email",
          "Client with email `" + email + "` already exists",
          "email",
          email);
    }

    logAsErrorUnexpectedDataIntegrityException(dve);
    throw new PlatformDataIntegrityException(
        "error.msg.client.unknown.data.integrity.issue",
        "Unknown data integrity issue with resource.");
  }
  @ExceptionHandler({DataIntegrityViolationException.class})
  public void constraintViolation(HttpServletResponse response, DataIntegrityViolationException ex)
      throws IOException {
    String message;
    Throwable cause = ex.getCause();
    if (cause instanceof ConstraintViolationException) {
      ConstraintViolationException cEx = (ConstraintViolationException) cause;
      message =
          "Application already contain sent data (Constraint "
              + cEx.getConstraintName()
              + " violates).";
    } else {
      message = ex.getMessage();
    }

    response.sendError(CONFLICT.value(), message);
  }
Exemplo n.º 17
0
  /** {@inheritDoc} */
  public User saveUser(User user) throws UserExistsException {

    if (user.getVersion() == null) {
      // if new user, lowercase userId
      user.setUsername(user.getUsername().toLowerCase());
    }

    // Get and prepare password management-related artifacts
    boolean passwordChanged = false;
    if (passwordEncoder != null) {
      // Check whether we have to encrypt (or re-encrypt) the password
      if (user.getVersion() == null) {
        // New user, always encrypt
        passwordChanged = true;
      } else {
        // Existing user, check password in DB
        String currentPassword = userDao.getUserPassword(user.getUsername());
        if (currentPassword == null) {
          passwordChanged = true;
        } else {
          if (!currentPassword.equals(user.getPassword())) {
            passwordChanged = true;
          }
        }
      }

      // If password was changed (or new user), encrypt it
      if (passwordChanged) {
        user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
      }
    } else {
      log.warn("PasswordEncoder not set, skipping password encryption...");
    }

    try {
      return userDao.saveUser(user);
    } catch (DataIntegrityViolationException e) {
      // e.printStackTrace();
      log.warn(e.getMessage());
      throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
    } catch (JpaSystemException e) { // needed for JPA
      // e.printStackTrace();
      log.warn(e.getMessage());
      throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
    }
  }
  /*
   * Guaranteed to throw an exception no matter what the data integrity issue
   * is.
   */
  private void handleDataIntegrityIssues(
      final DepositAccountCommand command, final DataIntegrityViolationException dve) {

    Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("deposit_acc_external_id")) {
      throw new PlatformDataIntegrityException(
          "error.msg.desposit.account.duplicate.externalId",
          "Deposit account with externalId " + command.getExternalId() + " already exists",
          "externalId",
          command.getExternalId());
    }

    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException(
        "error.msg.deposit.account.unknown.data.integrity.issue",
        "Unknown data integrity issue with resource.");
  }
Exemplo n.º 19
0
  private void initDatabase() {

    User enatis = new User();
    enatis.setUserName("ENatis");
    enatis.setPassword("123");
    enatis.setName("Edgardo Natis");
    enatis.setActive("1");
    enatis.setStatus(User.STATUS_OPEN);
    enatis.setServerId("1081EFAA375B683B01378991228E39CB");

    try {
      userRepository.save(enatis);

    } catch (DataIntegrityViolationException dive) {
      System.out.println("\nDatabase Error: " + dive.getMessage() + "\n");
    }
  }
  private void handleDataIntegrityIssues(
      final JsonCommand command, final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("holiday_name")) {
      final String name = command.stringValueOfParameterNamed("name");
      throw new PlatformDataIntegrityException(
          "error.msg.holiday.duplicate.name",
          "Holiday with name `" + name + "` already exists",
          "name",
          name);
    }

    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException(
        "error.msg.office.unknown.data.integrity.issue",
        "Unknown data integrity issue with resource.");
  }
  private void handleCodeDataIntegrityIssues(
      JsonCommand command, DataIntegrityViolationException dve) {

    Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("title_UNIQUE")) {
      throw new PlatformDataIntegrityException(
          "game already exist", "game already exist", "game already exist", "");
    }
  }
  /*
   * Guaranteed to throw an exception no matter what the data integrity issue
   * is.
   */
  private void handleDataIntegrityIssues(
      final JsonCommand command, final DataIntegrityViolationException dve) {

    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("username_org")) {
      final String username = command.stringValueOfParameterNamed("username");
      final StringBuilder defaultMessageBuilder =
          new StringBuilder("User with username ").append(username).append(" already exists.");
      throw new PlatformDataIntegrityException(
          "error.msg.user.duplicate.username",
          defaultMessageBuilder.toString(),
          "username",
          username);
    }

    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException(
        "error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource.");
  }
  private void handleDataIntegrityIssues(
      final JsonCommand command, final DataIntegrityViolationException dve) {

    final Throwable realCause = dve.getMostSpecificCause();

    LOGGER.error(dve.getMessage(), dve);
    if (realCause.getMessage().contains("taxcode")) {
      throw new PlatformDataIntegrityException(
          "validation.error.msg.taxmap.taxcode.duplicate",
          "A taxcode with name'"
              + command.stringValueOfParameterNamed("taxCode")
              + "'already exists",
          command.stringValueOfParameterNamed("taxCode"));
    } else {
      throw new PlatformDataIntegrityException(
          "error.msg.could.unknown.data.integrity.issue",
          "Unknown data integrity issue with resource: " + dve.getMessage());
    }
  }
  @Transactional
  @Override
  @CacheEvict(value = "hooks", allEntries = true)
  public CommandProcessingResult deleteHook(final Long hookId) {

    this.context.authenticatedUser();

    final Hook hook = retrieveHookBy(hookId);

    try {
      this.hookRepository.delete(hook);
      this.hookRepository.flush();
    } catch (final DataIntegrityViolationException e) {
      throw new PlatformDataIntegrityException(
          "error.msg.unknown.data.integrity.issue",
          "Unknown data integrity issue with resource: " + e.getMostSpecificCause());
    }
    return new CommandProcessingResultBuilder().withEntityId(hookId).build();
  }
Exemplo n.º 25
0
  public void addFantasyTeam(FantasyTeam fantasyTeam) {
    JdbcTemplate queryFantasyTeams = new JdbcTemplate(this.getDataSource());
    int userId = fantasyTeam.getUserId();
    String sql1 = "SELECT * FROM fantasyteams WHERE userid = ?";
    boolean hasTeam = true;

    try {
      queryFantasyTeams.queryForObject(sql1, new Object[] {userId}, new FantasyTeamRowMapper());
    } catch (EmptyResultDataAccessException e) {
      hasTeam = false;
    }

    if (!hasTeam) {
      SimpleJdbcInsert insertToFantasyTeams =
          (new SimpleJdbcInsert(this.getDataSource())).withTableName("fantasyteams");

      String sql2 = "SELECT MAX(fantasyteamid) FROM fantasyteams";

      int nextId = 1;
      try {
        nextId += queryFantasyTeams.queryForObject(sql2, Integer.class);
      } catch (NullPointerException ignored) {
      }

      Map<String, Object> fantasyteamsParameters = new HashMap<String, Object>(2);
      fantasyteamsParameters.put("fantasyteamid", nextId);
      fantasyteamsParameters.put("userid", fantasyTeam.getUserId());

      try {
        insertToFantasyTeams.execute(fantasyteamsParameters);
      } catch (DataIntegrityViolationException dive) {
        this.log.warning(dive.getMessage());
      }

      for (int i = 1; i <= 11; ++i) {
        FantasyTeamReg reg = new FantasyTeamReg(nextId, 0, 0, i);
        fantasyTeamRegServiceData.addFantasyTeamReg(reg);
      }
    }
  }
 @PreAuthorize("hasAuthority('ADMIN')")
 @RequestMapping(value = "/admin/media/create", method = RequestMethod.POST)
 public String handleMediaCreateForm(
     @Valid @ModelAttribute("form") MediaCreateForm form, BindingResult bindingResult) {
   LOGGER.debug("Processing media create form={}, bindingResult={}", form, bindingResult);
   if (bindingResult.hasErrors()) {
     // failed validation
     LOGGER.info("create media: failed validation");
     return "media/mediacreate";
   }
   try {
     mediaService.create(form);
   } catch (DataIntegrityViolationException e) {
     LOGGER.info("create media: failed exception " + e.toString());
     // probably email already exists - very rare case when multiple admins are adding same user
     // at the same time and form validation has passed for more than one of them.
     LOGGER.warn("Exception occurred when trying to save media", e);
     bindingResult.reject("media exception", e.toString());
     return "media/mediacreate";
   }
   // ok, redirect
   return "redirect:/admin/media/list/" + form.getPage() + "/" + form.getType();
 }
  private void handleHookDataIntegrityIssues(
      final JsonCommand command, final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("hook_name")) {
      final String name = command.stringValueOfParameterNamed("name");
      throw new PlatformDataIntegrityException(
          "error.msg.hook.duplicate.name",
          "A hook with name '" + name + "' already exists",
          "name",
          name);
    }

    throw new PlatformDataIntegrityException(
        "error.msg.unknown.data.integrity.issue",
        "Unknown data integrity issue with resource: " + realCause.getMessage());
  }
Exemplo n.º 28
0
  public static String getDataIntegrityViolationExceptionCause(
      DataIntegrityViolationException pException) {

    String message = "";

    ConstraintViolationException mConstraintViolationException =
        (ConstraintViolationException) pException.getCause();
    if (mConstraintViolationException == null) return message;

    // La CAUSE de un ConstraintViolationException usualmente será un (PSQLException), pero por
    // motivos de seguridad, hasta no tener
    // claros todos los posibles casos, usaremos Throwable.

    Throwable mCause = mConstraintViolationException.getCause();
    if (mCause == null) return message;

    message = mCause.getMessage();

    return message;
  }
Exemplo n.º 29
0
  @Override
  public void insert(
      String organizationId,
      String orderNumber,
      String orderId,
      String memberCode,
      String unifiedCustomerId,
      String tenantId,
      String settlementType,
      String settlementName,
      String settlementContents,
      BigDecimal itemAmount,
      BigDecimal fee,
      BigDecimal carriage,
      BigDecimal discount,
      BigDecimal orderAmount,
      BigDecimal grantPoint,
      BigDecimal usePoint,
      String mail,
      String postalCode,
      String state,
      String coupon,
      BigDecimal couponDiscount,
      String couponEventId,
      Date orderDate,
      Date cancelDate,
      BigDecimal sessionNumber,
      String affiliate,
      String status,
      String siteId,
      BigDecimal carriageHurry,
      BigDecimal giftAmount,
      String returnFlag,
      String exchangeFlag,
      String reserveFlag,
      Date updatedDate,
      String user) {
    // TODO Auto-generated method stub
    try {
      Parchase object = new Parchase();

      object.setId(new UUIDBean().generatePrimaryKey());
      object.setOrganizationId(organizationId);
      object.setOrderNumber(orderNumber);
      object.setOrderId(orderId);
      object.setMemberCode(memberCode);
      object.setUnifiedCustomerId(unifiedCustomerId);
      object.setTenantId(tenantId);
      object.setSettlementType(settlementType);
      object.setSettlementName(settlementName);
      object.setSettlementContents(settlementContents);
      object.setItemAmount(itemAmount);
      object.setFee(fee);
      object.setCarriage(carriageHurry);
      object.setDiscount(couponDiscount);
      object.setOrderAmount(orderAmount);
      object.setGrantPoint(grantPoint);
      object.setUsePoint(usePoint);
      object.setMail(mail);
      object.setPostalCode(postalCode);
      object.setState(state);
      object.setCoupon(coupon);
      object.setCouponDiscount(couponDiscount);
      object.setCouponEventId(couponEventId);
      object.setOrderDate(orderDate);
      object.setCancelDate(cancelDate);
      object.setSessionNumber(sessionNumber);
      object.setAffiliate(affiliate);
      object.setStatus(status);
      object.setSiteId(siteId);
      object.setCarriageHurry(carriageHurry);
      object.setGiftAmount(giftAmount);
      object.setReturnFlag(returnFlag);
      object.setExchangeFlag(exchangeFlag);
      object.setReserveFlag(reserveFlag);
      object.setUpdatedDate(updatedDate);
      object.setDeleteFlag(Boolean.FALSE);
      object.setCreateDate(new Date(System.currentTimeMillis()));
      object.setCreateUser(user);
      object.setAmendDate(new Date(System.currentTimeMillis()));
      object.setAmendUser(user);

      getHibernateTemplate().save(object);
      getHibernateTemplate().flush();
      getHibernateTemplate().clear();
    } catch (DataIntegrityViolationException e) {
      throw new ParchaseBusinessException(e.getMessage(), e);
    } catch (HibernateSystemException e) {
      throw new ParchaseRuntimeException(e);
    }
  }
  @Transactional
  @Override
  public void registerDatatable(final String dataTableName, final String applicationTableName) {

    // FIXME - KW - hardcoded supported app tables are m_loan or m_client?
    validateAppTable(applicationTableName);

    final String registerDatatableSql =
        "insert into x_registered_table (registered_table_name, application_table_name) values ('"
            + dataTableName
            + "', '"
            + applicationTableName
            + "')";

    final String createPermission = "'CREATE_" + dataTableName + "'";
    final String createPermissionChecker = "'CREATE_" + dataTableName + "_CHECKER'";
    final String readPermission = "'READ_" + dataTableName + "'";
    final String updatePermission = "'UPDATE_" + dataTableName + "'";
    final String updatePermissionChecker = "'UPDATE_" + dataTableName + "_CHECKER'";
    final String deletePermission = "'DELETE_" + dataTableName + "'";
    final String deletePermissionChecker = "'DELETE_" + dataTableName + "_CHECKER'";

    final String permissionsSql =
        "insert into m_permission (grouping, code, action_name, entity_name, can_maker_checker) values "
            + "('datatable', "
            + createPermission
            + ", 'CREATE', '"
            + dataTableName
            + "', true),"
            + "('datatable', "
            + createPermissionChecker
            + ", 'CREATE', '"
            + dataTableName
            + "', false),"
            + "('datatable', "
            + readPermission
            + ", 'READ', '"
            + dataTableName
            + "', false),"
            + "('datatable', "
            + updatePermission
            + ", 'UPDATE', '"
            + dataTableName
            + "', true),"
            + "('datatable', "
            + updatePermissionChecker
            + ", 'UPDATE', '"
            + dataTableName
            + "', false),"
            + "('datatable', "
            + deletePermission
            + ", 'DELETE', '"
            + dataTableName
            + "', true),"
            + "('datatable', "
            + deletePermissionChecker
            + ", 'DELETE', '"
            + dataTableName
            + "', false)";

    try {
      String[] sqlArray = {registerDatatableSql, permissionsSql};
      this.jdbcTemplate.batchUpdate(sqlArray);

    } catch (DataIntegrityViolationException dve) {
      Throwable realCause = dve.getMostSpecificCause();
      // even if duplicate is only due to permission duplicate, okay to show duplicate datatable
      // error msg
      if (realCause.getMessage().contains("Duplicate entry")) {
        throw new PlatformDataIntegrityException(
            "error.msg.datatable.registered",
            "Datatable `" + dataTableName + "` is already registered against an application table.",
            "dataTableName",
            dataTableName);
      }

      logAsErrorUnexpectedDataIntegrityException(dve);
      throw new PlatformDataIntegrityException(
          "error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource.");
    }
  }