Example usage for java.sql Timestamp valueOf

List of usage examples for java.sql Timestamp valueOf

Introduction

In this page you can find the example usage for java.sql Timestamp valueOf.

Prototype

@SuppressWarnings("deprecation")
public static Timestamp valueOf(LocalDateTime dateTime) 

Source Link

Document

Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime .

Usage

From source file:pt.ist.fenixedu.contracts.tasks.giafsync.ImportPersonServiceExemptionsFromGiaf.java

@Override
public List<Modification> processChanges(GiafMetadata metadata, PrintWriter log, Logger logger)
        throws Exception {
    List<Modification> modifications = new ArrayList<>();
    PersistentSuportGiaf oracleConnection = PersistentSuportGiaf.getInstance();
    PreparedStatement preparedStatement = oracleConnection.prepareStatement(getQuery());
    ResultSet result = preparedStatement.executeQuery();
    int count = 0;
    int news = 0;
    int notImported = 0;
    int dontExist = 0;
    Set<Person> importedButInvalid = new HashSet<Person>();
    while (result.next()) {
        count++;// w  ww.j  a v  a  2 s . c  o  m
        String numberString = result.getString("emp_num");
        Person person = metadata.getPerson(numberString, logger);
        if (person == null) {
            logger.debug("Invalid person with number: " + numberString);
            dontExist++;
            continue;
        }
        PersonProfessionalData personProfessionalData = person.getPersonProfessionalData();
        if (personProfessionalData == null) {
            logger.debug("Empty personProfessionalData: " + numberString);
            dontExist++;
            continue;
        }
        final GiafProfessionalData giafProfessionalData = personProfessionalData
                .getGiafProfessionalDataByGiafPersonIdentification(numberString);
        if (giafProfessionalData == null) {
            logger.debug("Empty giafProfessionalData: " + numberString);
            dontExist++;
            continue;
        }
        final String serviceExemptionGiafId = result.getString("tip_disp");
        final ServiceExemption serviceExemption = metadata.exemption(serviceExemptionGiafId);
        if (serviceExemption == null) {
            logger.debug("Empty serviceExemption: " + serviceExemptionGiafId + " for person number: "
                    + numberString);
            importedButInvalid.add(person);

        }
        String beginDateString = result.getString("DATA_INICIO");
        final LocalDate beginDate = StringUtils.isEmpty(beginDateString) ? null
                : new LocalDate(Timestamp.valueOf(beginDateString));
        if (beginDate == null) {
            logger.debug("Empty beginDate. Person number: " + numberString + " ServiceExemption: "
                    + serviceExemptionGiafId);
            importedButInvalid.add(person);
        }
        String endDateString = result.getString("DATA_FIM");
        final LocalDate endDate = StringUtils.isEmpty(endDateString) ? null
                : new LocalDate(Timestamp.valueOf(endDateString));
        if (beginDate != null && endDate != null) {
            if (beginDate.isAfter(endDate)) {
                logger.debug("BeginDate after endDate. Person number: " + numberString + " begin: " + beginDate
                        + " end: " + endDate);
                importedButInvalid.add(person);
            }
        }
        String creationDateString = result.getString("data_criacao");
        if (StringUtils.isEmpty(creationDateString)) {
            logger.debug("Empty creationDate. Person number: " + numberString + " ServiceExemption: "
                    + serviceExemptionGiafId);
            notImported++;
            continue;
        }
        final DateTime creationDate = new DateTime(Timestamp.valueOf(creationDateString));

        String modifiedDateString = result.getString("data_alteracao");
        final DateTime modifiedDate = StringUtils.isEmpty(modifiedDateString) ? null
                : new DateTime(Timestamp.valueOf(modifiedDateString));

        if (!hasPersonServiceExemption(giafProfessionalData, beginDate, endDate, serviceExemption,
                serviceExemptionGiafId, creationDate, modifiedDate)) {
            modifications.add(new Modification() {
                @Override
                public void execute() {
                    new PersonServiceExemption(giafProfessionalData, beginDate, endDate, serviceExemption,
                            serviceExemptionGiafId, creationDate, modifiedDate);
                }
            });
            news++;
        }
    }
    result.close();
    preparedStatement.close();

    int deleted = 0;
    int totalInFenix = 0;
    int repeted = 0;
    for (GiafProfessionalData giafProfessionalData : Bennu.getInstance().getGiafProfessionalDataSet()) {
        for (PersonProfessionalExemption personProfessionalExemption : giafProfessionalData
                .getPersonProfessionalExemptionsSet()) {
            if (personProfessionalExemption instanceof PersonServiceExemption
                    && personProfessionalExemption.getAnulationDate() == null) {
                final PersonServiceExemption personServiceExemption = (PersonServiceExemption) personProfessionalExemption;
                int countThisPersonServiceExemptionOnGiaf = countThisPersonServiceExemptionOnGiaf(
                        oracleConnection, personServiceExemption, logger);
                if (countThisPersonServiceExemptionOnGiaf == 0) {
                    modifications.add(new Modification() {
                        @Override
                        public void execute() {
                            personServiceExemption.setAnulationDate(new DateTime());
                        }
                    });
                    deleted++;
                } else {
                    totalInFenix++;
                    if (countThisPersonServiceExemptionOnGiaf > 1) {
                        repeted += countThisPersonServiceExemptionOnGiaf - 1;
                    }
                }
            }
        }
    }

    oracleConnection.closeConnection();
    log.println("-- Service Exemptions --");
    log.println("Total GIAF: " + count);
    log.println("New: " + news);
    log.println("Deleted: " + deleted);
    log.println("Not imported: " + notImported);
    log.println("Imported with errors: " + importedButInvalid.size());
    log.println("Repeted: " + repeted);
    log.println("Invalid persons: " + dontExist);
    log.println("Total Fnix: " + totalInFenix);
    log.println("Total Fnix without errors: " + (totalInFenix - importedButInvalid.size()));
    log.println("Missing in Fnix: " + (count - totalInFenix));
    return modifications;
}

From source file:cn.com.sinosoft.ebusiness.log.LoggingEventWrapper.java

public Date getEndTime() {
    if ("1".equals(getLogType())) {
        try {//from  w  w  w .  j a  va 2 s .  co m
            String message = getMessage();
            Timestamp endTime = Timestamp.valueOf(message.split("--")[1]);
            return endTime;
        } catch (Exception e) {
            logger.warn("err eventwrpper get endtime");
        }
    }
    return null;
}

From source file:pt.ist.fenixedu.contracts.tasks.giafsync.ImportPersonProfessionalRelationsFromGiaf.java

@Override
public List<Modification> processChanges(GiafMetadata metadata, PrintWriter log, Logger logger)
        throws Exception {
    List<Modification> modifications = new ArrayList<>();
    PersistentSuportGiaf oracleConnection = PersistentSuportGiaf.getInstance();
    PreparedStatement preparedStatement = oracleConnection.prepareStatement(getQuery());
    ResultSet result = preparedStatement.executeQuery();
    int count = 0;
    int news = 0;
    int notImported = 0;
    int dontExist = 0;
    Set<Person> importedButInvalid = new HashSet<Person>();
    while (result.next()) {
        count++;//from w ww .j  a  v a  2  s  . c  o m
        String numberString = result.getString("emp_num");
        Person person = metadata.getPerson(numberString, logger);
        if (person == null) {
            logger.debug("Invalid person with number: " + numberString);
            dontExist++;
            continue;
        }

        PersonProfessionalData personProfessionalData = person.getPersonProfessionalData();
        if (personProfessionalData == null) {
            logger.debug("Empty personProfessionalData: " + numberString);
            dontExist++;
            continue;
        }
        final GiafProfessionalData giafProfessionalData = personProfessionalData
                .getGiafProfessionalDataByGiafPersonIdentification(numberString);
        if (giafProfessionalData == null) {
            logger.debug("Empty giafProfessionalData: " + numberString);
            dontExist++;
            continue;
        }
        final String professionalRelationGiafId = result.getString("emp_vinculo");
        final ProfessionalRelation professionalRelation = metadata.relation(professionalRelationGiafId);
        if (professionalRelation == null) {
            logger.debug(
                    "Empty relation: " + professionalRelationGiafId + " for person number:" + numberString);
            importedButInvalid.add(person);
        }
        String beginDateString = result.getString("emp_dt_inic");
        final LocalDate beginDate = StringUtils.isEmpty(beginDateString) ? null
                : new LocalDate(Timestamp.valueOf(beginDateString));
        if (beginDate == null) {
            logger.debug("Empty beginDate. Person number: " + numberString + " Relation: "
                    + professionalRelationGiafId);
            importedButInvalid.add(person);
        }
        String endDateString = result.getString("emp_dt_fim");
        final LocalDate endDate = StringUtils.isEmpty(endDateString) ? null
                : new LocalDate(Timestamp.valueOf(endDateString));
        if (endDate != null) {
            if (beginDate != null && beginDate.isAfter(endDate)) {
                logger.debug("BeginDate after endDate. Person number: " + numberString + " begin: " + beginDate
                        + " end:" + endDate);
                importedButInvalid.add(person);
            }
        }

        final String professionalCategoryGiafId = result.getString("emp_cat_func");
        final ProfessionalCategory professionalCategory = metadata.category(professionalCategoryGiafId);
        if ((!StringUtils.isEmpty(professionalCategoryGiafId)) && professionalCategory == null) {
            logger.debug("Empty category " + professionalCategoryGiafId + ". Person number: " + numberString);
            importedButInvalid.add(person);
        }

        String creationDateString = result.getString("data_criacao");
        if (StringUtils.isEmpty(creationDateString)) {
            logger.debug("Empty creationDate. Person number: " + numberString + " Relation: "
                    + professionalRelationGiafId);
            continue;
        }
        final DateTime creationDate = new DateTime(Timestamp.valueOf(creationDateString));

        String modifiedDateString = result.getString("data_alteracao");
        final DateTime modifiedDate = StringUtils.isEmpty(modifiedDateString) ? null
                : new DateTime(Timestamp.valueOf(modifiedDateString));

        if (!hasPersonProfessionalRelation(giafProfessionalData, beginDate, endDate, professionalRelation,
                professionalRelationGiafId, professionalCategory, professionalCategoryGiafId, creationDate,
                modifiedDate)) {
            modifications.add(new Modification() {
                @Override
                public void execute() {
                    new PersonProfessionalRelation(giafProfessionalData, beginDate, endDate,
                            professionalRelation, professionalRelationGiafId, professionalCategory,
                            professionalCategoryGiafId, creationDate, modifiedDate);
                }
            });
            news++;
        }
    }
    result.close();
    preparedStatement.close();

    int deleted = 0;
    int totalInFenix = 0;
    int repeted = 0;
    for (GiafProfessionalData giafProfessionalData : Bennu.getInstance().getGiafProfessionalDataSet()) {
        for (final PersonProfessionalRelation personProfessionalRelation : giafProfessionalData
                .getPersonProfessionalRelationsSet()) {
            if (personProfessionalRelation.getAnulationDate() == null) {
                int countThisPersonProfessionalRelationOnGiaf = countThisPersonProfessionalRelationOnGiaf(
                        oracleConnection, personProfessionalRelation, logger);
                if (countThisPersonProfessionalRelationOnGiaf == 0) {
                    modifications.add(new Modification() {
                        @Override
                        public void execute() {
                            personProfessionalRelation.setAnulationDate(new DateTime());
                        }
                    });
                    deleted++;
                } else {
                    totalInFenix++;
                    if (countThisPersonProfessionalRelationOnGiaf > 1) {
                        repeted += countThisPersonProfessionalRelationOnGiaf - 1;
                    }
                }
            }
        }
    }

    oracleConnection.closeConnection();
    log.println("-- Professional relations --");
    log.println("Total GIAF: " + count);
    log.println("New: " + news);
    log.println("Deleted: " + deleted);
    log.println("Not imported: " + notImported);
    log.println("Imported with errors: " + importedButInvalid.size());
    log.println("Repeted: " + repeted);
    log.println("Invalid persons: " + dontExist);
    log.println("Total Fnix: " + totalInFenix);
    log.println("Total Fnix without errors: " + (totalInFenix - importedButInvalid.size()));
    log.println("Missing in Fnix: " + (count - totalInFenix));
    return modifications;
}

From source file:eu.domibus.common.dao.MessageLogDao.java

public List<MessageLogEntry> findPaged(int from, int max, String column, boolean asc,
        HashMap<String, Object> filters) {

    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<MessageLogEntry> cq = cb.createQuery(MessageLogEntry.class);
    Root<MessageLogEntry> mle = cq.from(MessageLogEntry.class);
    cq.select(mle);//from   w  w  w . j a v a 2s  .c o  m
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Map.Entry<String, Object> filter : filters.entrySet()) {
        if (filter.getValue() != null) {
            if (filter.getValue() instanceof String) {
                if (!filter.getValue().toString().isEmpty()) {
                    switch (filter.getKey().toString()) {
                    case "receivedFrom":
                        predicates.add(cb.greaterThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "receivedTo":
                        predicates.add(cb.lessThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    default:
                        predicates.add(cb.like(mle.<String>get(filter.getKey()), (String) filter.getValue()));
                        break;
                    }
                }
            } else {
                predicates.add(cb.equal(mle.<String>get(filter.getKey()), filter.getValue()));
            }
        }
    }
    cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    if (column != null) {
        if (asc) {
            cq.orderBy(cb.asc(mle.get(column)));
        } else {
            cq.orderBy(cb.desc(mle.get(column)));
        }

    }
    final TypedQuery<MessageLogEntry> query = this.em.createQuery(cq);
    query.setFirstResult(from);
    query.setMaxResults(max);
    return query.getResultList();
}

From source file:org.wso2.carbon.governance.api.util.CheckpointTimeUtils.java

/**
 * This method used to calculate time difference between timestamp to present.
 *
 * @param timeStamp earlier timestamp.// w ww.ja va  2 s  .co m
 * @return timeDurationTimestamp    timestamp difference from current time to current lifecycle last state changed
 *                                  time.
 */
public static long calculateTimeDifferenceToPresent(String timeStamp) {
    if (StringUtils.isEmpty(getCurrentTime()) && StringUtils.isEmpty(timeStamp)) {
        throw new IllegalArgumentException(
                "Invalid arguments supplied as timestamp two: '" + timeStamp + "' is not set");
    }
    return Timestamp.valueOf(getCurrentTime()).getTime() - Timestamp.valueOf(timeStamp).getTime();
}

From source file:edumsg.core.commands.tweet.GetTweetCommand.java

@Override
public void execute() {

    try {//from  w  w w . j  a  v a2 s.  com
        Tweet t = new Tweet();
        User creator = new User();
        details = null; //Cache.returnTweet(map.get("tweet_id"));

        if (details == null) {

            dbConn = PostgresConnection.getDataSource().getConnection();
            dbConn.setAutoCommit(false);
            proc = dbConn.prepareCall("{? = call get_tweet(?)}");
            proc.setPoolable(true);
            proc.registerOutParameter(1, Types.OTHER);
            proc.setInt(2, Integer.parseInt(map.get("tweet_id")));
            proc.execute();

            set = (ResultSet) proc.getObject(1);

            root.put("app", map.get("app"));
            root.put("method", map.get("method"));
            root.put("status", "ok");
            root.put("code", "200");

            if (set.next()) {
                details = new HashMap<>();
                Integer id = set.getInt(1);
                String tweet = set.getString(2);
                String image_url = set.getString(5);
                Timestamp created_at = set.getTimestamp(4);
                String creator_username = set.getString(6);
                String creator_name = set.getString(7);
                String creator_avatar = set.getString(8);
                int retweets = set.getInt(9);
                int favorites = set.getInt(10);

                t.setId(id);
                t.setTweetText(tweet);
                t.setImageUrl(image_url);
                t.setCreatedAt(created_at);
                t.setRetweets(retweets);
                t.setFavorites(favorites);
                creator.setName(creator_name);
                creator.setAvatarUrl(creator_avatar);
                creator.setUsername(creator_username);
                t.setCreator(creator);

                //                    details.put("tweet_text",tweet);
                //                    details.put("creator_id",Cache.returnUserID(creator_username));
                //                    details.put("creator_at",created_at.toString());
                //                    details.put("image_url",image_url);
                //Cache.cacheTweet(id+"",details);

            }
            set.close();

            ValueNode child = nf.pojoNode(t);
            root.set("tweet", child);
            try {
                CommandsHelp.submit(map.get("app"), mapper.writeValueAsString(root), map.get("correlation_id"),
                        LOGGER);
            } catch (JsonGenerationException e) {
                //Logger.log(Level.SEVERE, e.getMessage(), e);
            } catch (JsonMappingException e) {
                //Logger.log(Level.SEVERE, e.getMessage(), e);
            } catch (IOException e) {
                //Logger.log(Level.SEVERE, e.getMessage(), e);
            }

            dbConn.commit();

        } else {
            t.setId(Integer.parseInt(details.get("id")));
            t.setTweetText(details.get("tweet_text"));
            t.setImageUrl(details.get("image_url"));
            t.setCreatedAt(Timestamp.valueOf(details.get("created_at")));
            t.setRetweets(Integer.parseInt(details.get("retweets")));
            t.setFavorites(Integer.parseInt(details.get("favorites")));
            //                creator.setName(creator_name);
            //                creator.setAvatarUrl(creator_avatar);
            //                creator.setUsername(creator_username);
            t.setCreator(creator);
        }
    } catch (PSQLException e) {
        CommandsHelp.handleError(map.get("app"), map.get("method"), e.getMessage(), map.get("correlation_id"),
                LOGGER);
        //Logger.log(Level.SEVERE, e.getMessage(), e);
    } catch (SQLException e) {
        CommandsHelp.handleError(map.get("app"), map.get("method"), e.getMessage(), map.get("correlation_id"),
                LOGGER);
        //Logger.log(Level.SEVERE, e.getMessage(), e);
    } finally {
        PostgresConnection.disconnect(set, proc, dbConn);
    }
}

From source file:com.fns.grivet.service.NamedQueryServiceSprocTest.java

@Test
public void testNamedQueryNotExecutedBecauseParamSuppliedForExecutionNotCorrectlyNamed() throws IOException {
    Assertions.assertThrows(IllegalArgumentException.class, () -> {
        Resource r = resolver.getResource("classpath:TestSprocQuery.json");
        String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        NamedQuery namedQuery = objectMapper.readValue(json, NamedQuery.class);
        namedQueryService.create(namedQuery);

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        Timestamp tomorrow = Timestamp.valueOf(LocalDateTime.now().plusDays(1));
        params.add("timeCreated", tomorrow);
        namedQueryService.get("sproc.getAttributesCreatedBefore", params);
    });/*ww w.ja v  a 2  s.  c  om*/
}

From source file:pt.ist.fenixedu.contracts.tasks.giafsync.ImportPersonFunctionsAccumulationsFromGiaf.java

@Override
public List<Modification> processChanges(GiafMetadata metadata, PrintWriter log, Logger logger)
        throws Exception {
    List<Modification> modifications = new ArrayList<>();
    PersistentSuportGiaf oracleConnection = PersistentSuportGiaf.getInstance();
    PreparedStatement preparedStatement = oracleConnection.prepareStatement(getQuery());
    ResultSet result = preparedStatement.executeQuery();
    int count = 0;
    int news = 0;
    int notImported = 0;
    int dontExist = 0;
    Set<Person> importedButInvalid = new HashSet<Person>();
    while (result.next()) {
        count++;/*from  w ww. ja va 2s . co m*/
        String numberString = result.getString("emp_num");
        Person person = metadata.getPerson(numberString, logger);
        if (person == null) {
            logger.debug("Invalid person with number: " + numberString);
            dontExist++;
            continue;
        }

        PersonProfessionalData personProfessionalData = person.getPersonProfessionalData();
        if (personProfessionalData == null) {
            logger.debug("Empty personProfessionalData: " + numberString);
            dontExist++;
            continue;
        }

        final GiafProfessionalData giafProfessionalData = personProfessionalData
                .getGiafProfessionalDataByGiafPersonIdentification(numberString);
        if (giafProfessionalData == null) {
            logger.debug("Empty giafProfessionalData: " + numberString);
            dontExist++;
            continue;
        }

        final String functionsAccumulationGiafId = result.getString("TIPO");
        final FunctionsAccumulation functionsAccumulation = metadata.accumulation(functionsAccumulationGiafId);
        if (functionsAccumulation == null) {
            logger.debug("Empty FunctionsAccumulation: " + functionsAccumulationGiafId + " for person number: "
                    + numberString);
            importedButInvalid.add(person);
        }
        String beginDateString = result.getString("DATA_INICIO");
        final LocalDate beginDate = StringUtils.isEmpty(beginDateString) ? null
                : new LocalDate(Timestamp.valueOf(beginDateString));
        if (beginDate == null) {
            logger.debug("Empty beginDate: " + numberString + " FunctionsAccumulation: "
                    + functionsAccumulationGiafId);
            importedButInvalid.add(person);
        }

        String endDateString = result.getString("DATA_FIM");
        final LocalDate endDate = StringUtils.isEmpty(endDateString) ? null
                : new LocalDate(Timestamp.valueOf(endDateString));
        if (beginDate != null && endDate != null) {
            if (beginDate != null && beginDate.isAfter(endDate)) {
                logger.debug("BeginDate after EndDate. Person number: " + numberString + ". begin: " + beginDate
                        + " end:" + endDate);
                importedButInvalid.add(person);
            }
        }
        final BigDecimal hours = result.getBigDecimal("horas_sem");

        final String professionalRegimeGiafId = result.getString("EMP_REGIME");
        final ProfessionalRegime professionalRegime = metadata.regime(professionalRegimeGiafId);
        if (professionalRegime == null) {
            logger.debug("Empty regime: " + numberString);
            importedButInvalid.add(person);
        }
        String creationDateString = result.getString("data_criacao");
        if (StringUtils.isEmpty(creationDateString)) {
            logger.debug("Empty creation Date. Person number: " + numberString + " FunctionsAccumulation: "
                    + functionsAccumulationGiafId);
            notImported++;
            continue;
        }
        final DateTime creationDate = new DateTime(Timestamp.valueOf(creationDateString));

        String modifiedDateString = result.getString("data_alteracao");
        final DateTime modifiedDate = StringUtils.isEmpty(modifiedDateString) ? null
                : new DateTime(Timestamp.valueOf(modifiedDateString));

        if (!hasPersonFunctionsAccumulations(giafProfessionalData, beginDate, endDate, hours,
                functionsAccumulation, functionsAccumulationGiafId, professionalRegime,
                professionalRegimeGiafId, creationDate, modifiedDate)) {
            modifications.add(new Modification() {
                @Override
                public void execute() {
                    new PersonFunctionsAccumulation(giafProfessionalData, beginDate, endDate, hours,
                            functionsAccumulation, functionsAccumulationGiafId, professionalRegime,
                            professionalRegimeGiafId, creationDate, modifiedDate);
                }
            });
            news++;
        }
    }
    result.close();
    preparedStatement.close();

    int deleted = 0;
    int totalInFenix = 0;
    int repeted = 0;

    for (GiafProfessionalData giafProfessionalData : Bennu.getInstance().getGiafProfessionalDataSet()) {
        for (final PersonFunctionsAccumulation personFunctionsAccumulation : giafProfessionalData
                .getPersonFunctionsAccumulationsSet()) {
            if (personFunctionsAccumulation.getAnulationDate() == null) {
                int countThisPersonFunctionsAccumulationOnGiaf = countThisPersonFunctionsAccumulationOnGiaf(
                        oracleConnection, personFunctionsAccumulation, logger);
                if (countThisPersonFunctionsAccumulationOnGiaf == 0) {
                    modifications.add(new Modification() {
                        @Override
                        public void execute() {
                            personFunctionsAccumulation.setAnulationDate(new DateTime());
                        }
                    });
                    deleted++;
                } else {
                    totalInFenix++;
                    if (countThisPersonFunctionsAccumulationOnGiaf > 1) {
                        repeted += countThisPersonFunctionsAccumulationOnGiaf - 1;
                    }
                }
            }
        }
    }

    oracleConnection.closeConnection();
    log.println("-- Function accumuations --");
    log.println("Total GIAF: " + count);
    log.println("New: " + news);
    log.println("Deleted: " + deleted);
    log.println("Not imported: " + notImported);
    log.println("Imported with errors: " + importedButInvalid.size());
    log.println("Repeted: " + repeted);
    log.println("Invalid persons: " + dontExist);
    log.println("Total Fnix: " + totalInFenix);
    log.println("Total Fnix without errors: " + (totalInFenix - importedButInvalid.size()));
    log.println("Missing in Fnix: " + (count - totalInFenix));
    return modifications;
}

From source file:pt.ist.fenixedu.contracts.tasks.giafsync.ImportPersonProfessionalCategoriesFromGiaf.java

@Override
public List<Modification> processChanges(GiafMetadata metadata, PrintWriter log, Logger logger)
        throws Exception {
    List<Modification> modifications = new ArrayList<>();
    PersistentSuportGiaf oracleConnection = PersistentSuportGiaf.getInstance();
    PreparedStatement preparedStatement = oracleConnection.prepareStatement(getQuery());
    ResultSet result = preparedStatement.executeQuery();
    int count = 0;
    int novos = 0;
    int notImported = 0;
    int dontExist = 0;
    Set<Person> importedButInvalid = new HashSet<Person>();
    while (result.next()) {
        count++;/* w  w  w  . j ava2  s  .  co m*/
        String numberString = result.getString("emp_num");
        Person person = metadata.getPerson(numberString, logger);
        if (person == null) {
            logger.debug("Invalid person with number: " + numberString);
            dontExist++;
            continue;
        }
        PersonProfessionalData personProfessionalData = person.getPersonProfessionalData();
        if (personProfessionalData == null) {
            logger.debug("Empty employeeProfessionalData: " + numberString);
            dontExist++;
            continue;
        }
        final GiafProfessionalData giafProfessionalData = personProfessionalData
                .getGiafProfessionalDataByGiafPersonIdentification(numberString);
        if (giafProfessionalData == null) {
            logger.debug("Empty giafProfessionalData: " + numberString);
            dontExist++;
            continue;
        }
        final String professionalCategoryGiafId = result.getString("emp_cat_func");
        final ProfessionalCategory professionalCategory = metadata.category(professionalCategoryGiafId);
        if (professionalCategory == null) {
            logger.debug(
                    "Empty category : " + professionalCategoryGiafId + " for person number: " + numberString);
            importedButInvalid.add(person);
        }
        String beginDateString = result.getString("emp_dt_inicio");
        final LocalDate beginDate = StringUtils.isEmpty(beginDateString) ? null
                : new LocalDate(Timestamp.valueOf(beginDateString));
        if (beginDate == null) {
            logger.debug("Empty beginDate. Person number: " + numberString + " category: "
                    + professionalCategoryGiafId);
            importedButInvalid.add(person);
        }
        String endDateString = result.getString("emp_dt_fim");
        final LocalDate endDate = StringUtils.isEmpty(endDateString) ? null
                : new LocalDate(Timestamp.valueOf(endDateString));
        if (endDate != null) {
            if (beginDate != null && beginDate.isAfter(endDate)) {
                logger.debug("BeginDate after endDate. Person number: " + numberString + " begin: " + beginDate
                        + " end:" + endDate);
                importedButInvalid.add(person);
            }
        }

        final String step = result.getString("emp_escalao");
        final String level = result.getString("emp_venc_nvl");

        // a.emp_regime, a.emp_vinculo
        final String professionalRegimeGiafId = result.getString("emp_regime");
        final ProfessionalRegime professionalRegime = metadata.regime(professionalRegimeGiafId);
        if (professionalRegime == null && (!StringUtils.isEmpty(professionalRegimeGiafId))) {
            logger.debug("Empty regime: " + professionalRegimeGiafId + ". Person number: " + numberString);
            importedButInvalid.add(person);
        }

        final String professionalRelationGiafId = result.getString("emp_vinculo");
        final ProfessionalRelation professionalRelation = metadata.relation(professionalRelationGiafId);
        if (professionalRelation == null && (!StringUtils.isEmpty(professionalRelationGiafId))) {
            logger.debug("Empty relation: " + professionalRelationGiafId + ". Person number: " + numberString);
            importedButInvalid.add(person);
        }
        // ,a.data_criacao,a.data_alteracao
        String creationDateString = result.getString("data_criacao");
        if (StringUtils.isEmpty(creationDateString)) {
            logger.debug("Empty creationDate. Person number: " + numberString + " Category: "
                    + professionalCategoryGiafId);
            notImported++;
            continue;
        }
        final DateTime creationDate = new DateTime(Timestamp.valueOf(creationDateString));

        String modifiedDateString = result.getString("data_alteracao");
        final DateTime modifiedDate = StringUtils.isEmpty(modifiedDateString) ? null
                : new DateTime(Timestamp.valueOf(modifiedDateString));

        if (!hasPersonProfessionalCategory(giafProfessionalData, beginDate, endDate, professionalCategory,
                professionalCategoryGiafId, professionalRegime, professionalRegimeGiafId, professionalRelation,
                professionalRelationGiafId, step, level, creationDate, modifiedDate)) {
            modifications.add(new Modification() {
                @Override
                public void execute() {
                    new PersonProfessionalCategory(giafProfessionalData, beginDate, endDate,
                            professionalCategory, professionalCategoryGiafId, professionalRegime,
                            professionalRegimeGiafId, professionalRelation, professionalRelationGiafId, step,
                            level, creationDate, modifiedDate);
                }
            });
            novos++;
        }

    }
    result.close();
    preparedStatement.close();

    int deleted = 0;
    int totalInFenix = 0;
    int repeted = 0;
    for (GiafProfessionalData giafProfessionalData : Bennu.getInstance().getGiafProfessionalDataSet()) {
        for (final PersonProfessionalCategory personProfessionalCategory : giafProfessionalData
                .getPersonProfessionalCategoriesSet()) {
            if (personProfessionalCategory.getAnulationDate() == null) {
                int countThisPersonProfessionalCategoryOnGiaf = countThisPersonProfessionalCategoryOnGiaf(
                        oracleConnection, personProfessionalCategory, logger);
                if (countThisPersonProfessionalCategoryOnGiaf == 0) {
                    modifications.add(new Modification() {
                        @Override
                        public void execute() {
                            personProfessionalCategory.setAnulationDate(new DateTime());
                        }
                    });
                    deleted++;
                } else {
                    if (countThisPersonProfessionalCategoryOnGiaf > 1) {
                        repeted += countThisPersonProfessionalCategoryOnGiaf - 1;
                    }
                    totalInFenix++;
                }
            }
        }
    }

    oracleConnection.closeConnection();
    log.println("-- Professional categories --");
    log.println("Total GIAF: " + count);
    log.println("New: " + novos);
    log.println("Deleted: " + deleted);
    log.println("Not imported: " + notImported);
    log.println("Imported with errors: " + importedButInvalid.size());
    log.println("Repeted: " + repeted);
    log.println("Invalid persons: " + dontExist);
    log.println("Total Fnix: " + totalInFenix);
    log.println("Total Fnix without errors: " + (totalInFenix - importedButInvalid.size()));
    log.println("Missing in Fnix: " + (count - totalInFenix));
    return modifications;
}

From source file:org.apache.stratos.usage.summary.helper.util.DataAccessObject.java

public String getAndUpdateLastUsageDailyTimestamp() throws SQLException {

    Timestamp lastSummaryTs = null;
    Connection connection = null;

    try {/*from www .j a  v  a 2 s  .c  o m*/
        connection = dataSource.getConnection();
        String sql = "SELECT TIMESTMP FROM USAGE_LAST_DAILY_TS WHERE ID='LatestTS'";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            lastSummaryTs = resultSet.getTimestamp("TIMESTMP");
        } else {
            lastSummaryTs = new Timestamp(0);
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        Timestamp currentTs = Timestamp.valueOf(formatter.format(new Date()));

        String currentSql = "INSERT INTO USAGE_LAST_DAILY_TS (ID, TIMESTMP) VALUES('LatestTS',?) ON DUPLICATE KEY UPDATE TIMESTMP=?";
        PreparedStatement ps1 = connection.prepareStatement(currentSql);
        ps1.setTimestamp(1, currentTs);
        ps1.setTimestamp(2, currentTs);
        ps1.execute();

    } catch (SQLException e) {
        log.error("Error occurred while trying to get and update the last daily timestamp. ", e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    return lastSummaryTs.toString();
}