Example usage for java.sql Timestamp getTime

List of usage examples for java.sql Timestamp getTime

Introduction

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

Prototype

public long getTime() 

Source Link

Document

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.

Usage

From source file:com.rogchen.common.xml.UtilDateTime.java

public static Timestamp addDaysToTimestamp(Timestamp start, Double days) {
    return new Timestamp(start.getTime() + ((int) (24L * 60L * 60L * 1000L * days)));
}

From source file:org.kuali.kfs.module.ar.businessobject.lookup.ContractsGrantsLOCReportLookupableHelperServiceImpl.java

@Override
public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) {
    Map lookupFormFields = lookupForm.getFieldsForLookup();

    final String reportType = (String) lookupFormFields.get("reportType");

    setBackLocation((String) lookupForm.getFieldsForLookup().get(KRADConstants.BACK_LOCATION));
    setDocFormKey((String) lookupForm.getFieldsForLookup().get(KRADConstants.DOC_FORM_KEY));

    OperatorAndValue amountAvailableToDrawOperator = buildOperatorAndValueFromField(lookupFormFields,
            ArPropertyConstants.AMOUNT_AVAILABLE_TO_DRAW);
    OperatorAndValue claimOnCashBalanceOperator = buildOperatorAndValueFromField(lookupFormFields,
            ArPropertyConstants.CLAIM_ON_CASH_BALANCE);
    OperatorAndValue amountToDrawOperator = buildOperatorAndValueFromField(lookupFormFields,
            ArPropertyConstants.AMOUNT_TO_DRAW);
    OperatorAndValue fundsNotDrawnOperator = buildOperatorAndValueFromField(lookupFormFields,
            ArPropertyConstants.FUNDS_NOT_DRAWN);

    Collection<ContractsGrantsLOCReport> displayList = new ArrayList<ContractsGrantsLOCReport>();

    Map<String, String> locLookupFields = buildCriteriaForLetterOfCreditLookup(lookupFormFields);
    locLookupFields.put(/*w  ww.j a va  2s . com*/
            KFSPropertyConstants.DOCUMENT_HEADER + "." + KFSPropertyConstants.WORKFLOW_DOCUMENT_STATUS_CODE,
            StringUtils.join(getFinancialSystemDocumentService().getSuccessfulDocumentStatuses(),
                    SearchOperator.OR.op()));
    Collection<ContractsGrantsLetterOfCreditReviewDocument> cgLOCReviewDocs = getLookupService()
            .findCollectionBySearchHelper(ContractsGrantsLetterOfCreditReviewDocument.class, locLookupFields,
                    true);

    for (ContractsGrantsLetterOfCreditReviewDocument cgLOCReviewDoc : cgLOCReviewDocs) {
        List<ContractsGrantsLetterOfCreditReviewDetail> headerReviewDetails = cgLOCReviewDoc
                .getHeaderReviewDetails();
        List<ContractsGrantsLetterOfCreditReviewDetail> accountReviewDetails = cgLOCReviewDoc
                .getAccountReviewDetails();
        if (accountReviewDetails.size() > 0) {

            KualiDecimal totalAmountAvailableToDraw = KualiDecimal.ZERO;
            KualiDecimal totalClaimOnCashBalance = KualiDecimal.ZERO;
            KualiDecimal totalAmountToDraw = KualiDecimal.ZERO;
            KualiDecimal totalFundsNotDrawn = KualiDecimal.ZERO;

            ContractsGrantsLOCReport cgLOCReport = new ContractsGrantsLOCReport();

            for (ContractsGrantsLetterOfCreditReviewDetail accountReviewDetailEntry : accountReviewDetails) {
                KualiDecimal claimOnCashBalance = ObjectUtils
                        .isNull(accountReviewDetailEntry.getClaimOnCashBalance()) ? KualiDecimal.ZERO
                                : accountReviewDetailEntry.getClaimOnCashBalance();
                // previousDraw should be sum of amountToDraw?
                KualiDecimal previousDraw = ObjectUtils.isNull(accountReviewDetailEntry.getAmountToDraw())
                        ? KualiDecimal.ZERO
                        : accountReviewDetailEntry.getAmountToDraw();
                KualiDecimal fundsNotDrawn = ObjectUtils.isNull(accountReviewDetailEntry.getFundsNotDrawn())
                        ? KualiDecimal.ZERO
                        : accountReviewDetailEntry.getFundsNotDrawn();

                totalClaimOnCashBalance = totalClaimOnCashBalance.add(claimOnCashBalance);
                totalAmountToDraw = totalAmountToDraw.add(previousDraw);
                totalFundsNotDrawn = totalFundsNotDrawn.add(fundsNotDrawn);
            }

            for (ContractsGrantsLetterOfCreditReviewDetail accountReviewDetailEntry : headerReviewDetails) {
                KualiDecimal amountAvailableToDraw = ObjectUtils
                        .isNull(accountReviewDetailEntry.getAmountAvailableToDraw()) ? KualiDecimal.ZERO
                                : accountReviewDetailEntry.getAmountAvailableToDraw();
                totalAmountAvailableToDraw = totalAmountAvailableToDraw.add(amountAvailableToDraw);
            }

            // skip the calculated fields values if necessary
            if (amountAvailableToDrawOperator != null
                    && !amountAvailableToDrawOperator.applyComparison(totalAmountAvailableToDraw)) {
                continue;
            }
            if (claimOnCashBalanceOperator != null
                    && !claimOnCashBalanceOperator.applyComparison(totalClaimOnCashBalance)) {
                continue;
            }
            if (amountToDrawOperator != null && !amountToDrawOperator.applyComparison(totalAmountToDraw)) {
                continue;
            }
            if (fundsNotDrawnOperator != null && !fundsNotDrawnOperator.applyComparison(totalFundsNotDrawn)) {
                continue;
            }

            cgLOCReport.setDocumentNumber(cgLOCReviewDoc.getDocumentNumber());
            cgLOCReport.setLetterOfCreditFundCode(cgLOCReviewDoc.getLetterOfCreditFundCode());
            cgLOCReport.setLetterOfCreditFundGroupCode(cgLOCReviewDoc.getLetterOfCreditFundGroupCode());

            final Timestamp dateCreated = cgLOCReviewDoc.getFinancialSystemDocumentHeader()
                    .getWorkflowCreateDate();
            if (ObjectUtils.isNotNull(dateCreated)) {
                cgLOCReport.setLetterOfCreditReviewCreateDate(new java.sql.Date(dateCreated.getTime()));
            }
            cgLOCReport.setAmountAvailableToDraw(totalAmountAvailableToDraw);
            cgLOCReport.setClaimOnCashBalance(totalClaimOnCashBalance);
            cgLOCReport.setAmountToDraw(totalAmountToDraw);
            cgLOCReport.setFundsNotDrawn(totalFundsNotDrawn);

            if (reportType.equals(ArConstants.LOCReportTypeFieldValues.AMOUNTS_NOT_DRAWN)) {
                if (totalFundsNotDrawn.isGreaterThan(KualiDecimal.ZERO)) {
                    displayList.add(cgLOCReport);
                }
            } else {
                displayList.add(cgLOCReport);
            }

        }
    }

    buildResultTable(lookupForm, displayList, resultTable);
    return displayList;
}

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.IdeaInstanceDAO.java

@Override
public IdeaInstance loadIdeaInstance(String code, Collection<Integer> ideaStatus) {
    IdeaInstance ideainstance = null;//from   ww w  .  ja va 2s .co  m
    Connection conn = null;
    PreparedStatement stat = null;
    ResultSet res = null;
    try {
        conn = this.getConnection();
        stat = conn.prepareStatement(LOAD_IDEAINSTANCE);
        int index = 1;
        stat.setString(index++, code);
        res = stat.executeQuery();
        if (res.next()) {
            ideainstance = new IdeaInstance();
            ideainstance.setCode(res.getString("code"));
            Timestamp createdatValue = res.getTimestamp("createdat");
            if (null != createdatValue) {
                ideainstance.setCreatedat(new Date(createdatValue.getTime()));
            }
        }
        if (null != ideainstance) {
            List<String> groups = this.loadIdeaInstanceGroups(code, conn);
            ideainstance.setGroups(groups);
            List<Integer> ideas = this.loadIdeaInstanceIdeas(code, ideaStatus, conn);
            ideainstance.setChildren(ideas);
        }

    } catch (Throwable t) {
        _logger.error("Error loading ideainstance with code {}", code, t);
        throw new RuntimeException("Error loading ideainstance", t);
    } finally {
        closeDaoResources(res, stat, conn);
    }
    return ideainstance;
}

From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentExporter.java

private String getValues(final ResultSet rs, final String columnName, final Integer columnType)
        throws SQLException {

    String res = null;//from w ww .j av  a  2 s . co m

    try {
        switch (columnType) {
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            final InputStream is = rs.getBinaryStream(columnName);
            if (is != null) {
                res = DatatypeConverter.printHexBinary(IOUtils.toByteArray(is));
            }
            break;

        case Types.BLOB:
            final Blob blob = rs.getBlob(columnName);
            if (blob != null) {
                res = DatatypeConverter.printHexBinary(IOUtils.toByteArray(blob.getBinaryStream()));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            if (rs.getBoolean(columnName)) {
                res = "1";
            } else {
                res = "0";
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            final Timestamp timestamp = rs.getTimestamp(columnName);
            if (timestamp != null) {
                res = FormatUtils.format(new Date(timestamp.getTime()));
            }
            break;

        default:
            res = rs.getString(columnName);
        }
    } catch (IOException e) {
        LOG.error("Error retrieving hexadecimal string", e);
    }

    return res;
}

From source file:org.apache.ofbiz.content.data.DataResourceWorker.java

public static void renderDataResourceAsText(Delegator delegator, String dataResourceId, Appendable out,
        Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache,
        List<GenericValue> webAnalytics) throws GeneralException, IOException {
    if (dataResourceId == null) {
        throw new GeneralException("Cannot lookup data resource with for a null dataResourceId");
    }/*  ww  w  . ja v a  2s  .  com*/
    if (templateContext == null) {
        templateContext = new HashMap<String, Object>();
    }
    if (UtilValidate.isEmpty(targetMimeTypeId)) {
        targetMimeTypeId = "text/html";
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }

    // if the target mimeTypeId is not a text type, throw an exception
    if (!targetMimeTypeId.startsWith("text/")) {
        throw new GeneralException(
                "The desired mime-type is not a text type, cannot render as text: " + targetMimeTypeId);
    }

    // get the data resource object
    GenericValue dataResource = EntityQuery.use(delegator).from("DataResource")
            .where("dataResourceId", dataResourceId).cache(cache).queryOne();

    if (dataResource == null) {
        throw new GeneralException(
                "No data resource object found for dataResourceId: [" + dataResourceId + "]");
    }

    // a data template attached to the data resource
    String dataTemplateTypeId = dataResource.getString("dataTemplateTypeId");

    // no template; or template is NONE; render the data
    if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) {
        DataResourceWorker.writeDataResourceText(dataResource, targetMimeTypeId, locale, templateContext,
                delegator, out, cache);
    } else {
        // a template is defined; render the template first
        templateContext.put("mimeTypeId", targetMimeTypeId);

        // FTL template
        if ("FTL".equals(dataTemplateTypeId)) {
            try {
                // get the template data for rendering
                String templateText = getDataResourceText(dataResource, targetMimeTypeId, locale,
                        templateContext, delegator, cache);

                // if use web analytics.
                if (UtilValidate.isNotEmpty(webAnalytics)) {
                    StringBuffer newTemplateText = new StringBuffer(templateText);
                    String webAnalyticsCode = "<script language=\"JavaScript\" type=\"text/javascript\">";
                    for (GenericValue webAnalytic : webAnalytics) {
                        StringWrapper wrapString = StringUtil
                                .wrapString((String) webAnalytic.get("webAnalyticsCode"));
                        webAnalyticsCode += wrapString.toString();
                    }
                    webAnalyticsCode += "</script>";
                    newTemplateText.insert(templateText.lastIndexOf("</head>"), webAnalyticsCode);
                    templateText = newTemplateText.toString();
                }

                // render the FTL template
                boolean useTemplateCache = cache
                        && !UtilProperties.getPropertyAsBoolean("content", "disable.ftl.template.cache", false);
                Timestamp lastUpdatedStamp = dataResource.getTimestamp("lastUpdatedStamp");
                FreeMarkerWorker.renderTemplateFromString(
                        "delegator:" + delegator.getDelegatorName() + ":DataResource:" + dataResourceId,
                        templateText, templateContext, out, lastUpdatedStamp.getTime(), useTemplateCache);
            } catch (TemplateException e) {
                throw new GeneralException("Error rendering FTL template", e);
            }

        } else if ("XSLT".equals(dataTemplateTypeId)) {
            File sourceFileLocation = null;
            File targetFileLocation = new File(
                    System.getProperty("ofbiz.home") + "/runtime/tempfiles/docbook.css");
            if (templateContext.get("visualThemeId") != null) {
                Map<String, Object> layoutSettings = UtilGenerics
                        .checkMap(templateContext.get("layoutSettings"));
                List<String> docbookStyleSheets = UtilGenerics
                        .checkList(layoutSettings.get("VT_DOCBOOKSTYLESHEET"));
                String docbookStyleLocation = docbookStyleSheets.get(0);
                sourceFileLocation = new File(
                        System.getProperty("ofbiz.home") + "/themes" + docbookStyleLocation);
            }
            if (sourceFileLocation != null && sourceFileLocation.exists()) {
                UtilMisc.copyFile(sourceFileLocation, targetFileLocation);
            } else {
                String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME",
                        delegator);
                if (defaultVisualThemeId != null) {
                    GenericValue themeValue = EntityQuery.use(delegator).from("VisualThemeResource")
                            .where("visualThemeId", defaultVisualThemeId, "resourceTypeEnumId",
                                    "VT_DOCBOOKSTYLESHEET", "sequenceId", "01")
                            .cache().queryOne();
                    sourceFileLocation = new File(
                            System.getProperty("ofbiz.home") + "/themes" + themeValue.get("resourceValue"));
                    UtilMisc.copyFile(sourceFileLocation, targetFileLocation);
                }
            }
            // get the template data for rendering
            String templateLocation = DataResourceWorker
                    .getContentFile(dataResource.getString("dataResourceTypeId"),
                            dataResource.getString("objectInfo"), (String) templateContext.get("contextRoot"))
                    .toString();
            // render the XSLT template and file
            String outDoc = null;
            try {
                outDoc = XslTransform.renderTemplate(templateLocation, (String) templateContext.get("docFile"));
            } catch (TransformerException c) {
                Debug.logError("XSL TransformerException: " + c.getMessage(), module);
            }
            out.append(outDoc);

            // Screen Widget template
        } else if ("SCREEN_COMBINED".equals(dataTemplateTypeId)) {
            try {
                MapStack<String> context = MapStack.create(templateContext);
                context.put("locale", locale);
                // prepare the map for preRenderedContent
                String textData = (String) context.get("textData");
                if (UtilValidate.isNotEmpty(textData)) {
                    Map<String, Object> prc = new HashMap<String, Object>();
                    String mapKey = (String) context.get("mapKey");
                    if (mapKey != null) {
                        prc.put(mapKey, mapKey);
                    }
                    prc.put("body", textData); // used for default screen defs
                    context.put("preRenderedContent", prc);
                }
                // get the screen renderer; or create a new one
                ScreenRenderer screens = (ScreenRenderer) context.get("screens");
                if (screens == null) {
                    // TODO: replace "screen" to support dynamic rendering of different output
                    ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(
                            EntityUtilProperties.getPropertyValue("widget", "screen.name", delegator),
                            EntityUtilProperties.getPropertyValue("widget", "screen.screenrenderer",
                                    delegator));
                    screens = new ScreenRenderer(out, context, screenStringRenderer);
                    screens.getContext().put("screens", screens);
                }
                // render the screen
                ModelScreen modelScreen = null;
                ScreenStringRenderer renderer = screens.getScreenStringRenderer();
                String combinedName = dataResource.getString("objectInfo");
                if ("URL_RESOURCE".equals(dataResource.getString("dataResourceTypeId"))
                        && UtilValidate.isNotEmpty(combinedName) && combinedName.startsWith("component://")) {
                    modelScreen = ScreenFactory.getScreenFromLocation(combinedName);
                } else { // stored in  a single file, long or short text
                    Document screenXml = UtilXml.readXmlDocument(getDataResourceText(dataResource,
                            targetMimeTypeId, locale, templateContext, delegator, cache), true, true);
                    Map<String, ModelScreen> modelScreenMap = ScreenFactory.readScreenDocument(screenXml,
                            "DataResourceId: " + dataResource.getString("dataResourceId"));
                    if (UtilValidate.isNotEmpty(modelScreenMap)) {
                        Map.Entry<String, ModelScreen> entry = modelScreenMap.entrySet().iterator().next(); // get first entry, only one screen allowed per file
                        modelScreen = entry.getValue();
                    }
                }
                if (UtilValidate.isNotEmpty(modelScreen)) {
                    modelScreen.renderScreenString(out, context, renderer);
                } else {
                    throw new GeneralException(
                            "The dataResource file [" + dataResourceId + "] could not be found");
                }
            } catch (SAXException e) {
                throw new GeneralException("Error rendering Screen template", e);
            } catch (ParserConfigurationException e) {
                throw new GeneralException("Error rendering Screen template", e);
            } catch (TemplateException e) {
                throw new GeneralException("Error creating Screen renderer", e);
            }
        } else {
            throw new GeneralException(
                    "The dataTemplateTypeId [" + dataTemplateTypeId + "] is not yet supported");
        }
    }
}

From source file:com.funambol.foundation.items.dao.DataBaseFileDataObjectMetadataDAO.java

private static String utcDateTime(Timestamp timestamp) {

    if (timestamp == null) {
        return null;
    }/*from   w ww  .j a v a2s.com*/

    SimpleDateFormat formatter = new SimpleDateFormat(TimeUtils.PATTERN_UTC);
    formatter.setTimeZone(TimeUtils.TIMEZONE_UTC);

    return formatter.format(new Date(timestamp.getTime()));

}

From source file:keepinchecker.network.PacketSniffer.java

private void sendPacketsToDatabase(Map<Timestamp, Packet> packetMap) throws Exception {
    Set<KeepInCheckerPacket> objectionablePackets = new HashSet<>();

    for (Map.Entry<Timestamp, Packet> entry : packetMap.entrySet()) {
        Timestamp packetTime = entry.getKey();
        ZoneId currentTimezone = ZonedDateTime.now().getZone();
        String packetString = PacketParser.convertToHumanReadableFormat(entry.getValue());

        for (String objectionableWord : Constants.OBJECTIONABLE_WORDS) {
            if (StringUtils.contains(packetString, objectionableWord)) {
                KeepInCheckerPacket packet = new KeepInCheckerPacket();

                packet.setTimestamp(packetTime.getTime());
                packet.setTimezone(currentTimezone.getId());

                String parsedGetValue = PacketParser.parse(PacketParser.GET, packetString);
                String parsedHostValue = PacketParser.parse(PacketParser.HOST, packetString);
                String parsedReferValue = PacketParser.parse(PacketParser.REFERER, packetString);
                packet.setGetValue(parsedGetValue.getBytes(StandardCharsets.UTF_8));
                packet.setHostValue(parsedHostValue.getBytes(StandardCharsets.UTF_8));
                packet.setRefererValue(parsedReferValue.getBytes(StandardCharsets.UTF_8));

                if (!areGetHostAndRefererValuesEmpty(packet)) {
                    objectionablePackets.add(packet);
                }//  ww w  .  ja  v  a2  s  .  c  o m

                break;
            }
        }
    }

    if (!objectionablePackets.isEmpty()) {
        packetManager.savePackets(objectionablePackets);
    }
}

From source file:com.mothsoft.alexis.engine.predictive.OpenNLPMaxentModelExecutorTask.java

private boolean doExecute(final Model model) {
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from  w w  w.  java2  s .  c om*/

    boolean result = false;

    try {
        logger.info(String.format("Executing model %d", model.getId()));

        // load model file
        final File userDirectory = new File(baseDirectory, "" + model.getUserId());
        final File modelFile = new File(userDirectory, model.getId() + BIN_GZ_EXT);
        final AbstractModel maxentModel = new SuffixSensitiveGISModelReader(modelFile).getModel();

        final Date now = new Date();
        final TimeUnits timeUnits = model.getTimeUnits();
        final Timestamp topOfPeriod = new Timestamp(TimeUnits.floor(now, timeUnits).getTime());
        final Timestamp endOfPeriod = new Timestamp(topOfPeriod.getTime() + timeUnits.getDuration() - 1);

        // first position: sum of changes predicted, second position: number
        // of samples--will calculate a boring old mean...
        final double[][] changeByPeriod = new double[model.getLookahead()][2];

        // initialize
        for (int i = 0; i < changeByPeriod.length; i++) {
            changeByPeriod[i][0] = 0.0d;
            changeByPeriod[i][1] = 0.0d;
        }

        // find the most recent point value
        // FIXME - some sparse data sets may require executing the model on
        // all documents since that point or applying some sort of
        // dead-reckoning logic for smoothing
        final DataSetPoint initial = this.dataSetPointDao.findLastPointBefore(model.getTrainingDataSet(),
                endOfPeriod);

        // let's get the corner cases out of the way
        if (initial == null) {
            logger.warn("Insufficient data to execute model!");
            return false;
        }

        // happy path
        // build consolidated context of events in this period
        // find current value of training data set for this period
        final double[] probs = eval(model, topOfPeriod, endOfPeriod, maxentModel);

        // predict from the last available point, adjusted for time
        // remaining in period
        final double y0 = initial.getY();

        // map outcomes to periods in the future (at least no earlier than
        // this period)
        for (int i = 0; i < probs.length; i++) {
            // in the form +nU:+/-x, where n is the number of periods, U is
            // the unit type for the period, +/- is the direction, and x is
            // a discrete value from Model.OUTCOME_ARRAY
            final String outcome = maxentModel.getOutcome(i);

            final Matcher matcher = OUTCOME_PATTERN.matcher(outcome);

            if (!matcher.matches()) {
                logger.warn("Can't process outcome: " + outcome + "; skipping");
                continue;
            }

            final int period = Integer.valueOf(matcher.group(1));
            final String units = matcher.group(2);
            final double percentChange = Double.valueOf(matcher.group(3));

            // record the observation and the count of observations
            changeByPeriod[period][0] += percentChange;
            changeByPeriod[period][1] += 1.0d;

            if (logger.isDebugEnabled()) {
                final double yi = y0 * (1 + percentChange);
                logger.debug(String.format("Outcome: %s, %s: +%d, change: %f, new value: %f, probability: %f",
                        outcome, units, period, percentChange, yi, probs[i]));
            }
        }

        // build points for predictive data set
        double yn = y0;

        // we need to track the points and remove any that were not
        // predicted by this execution of the model
        final Timestamp endOfPredictionRange = new Timestamp(
                topOfPeriod.getTime() + (changeByPeriod.length * timeUnits.getDuration()));
        final List<DataSetPoint> existingPoints = this.dataSetPointDao
                .findByTimeRange(model.getPredictionDataSet(), topOfPeriod, endOfPredictionRange);

        for (int period = 0; period < changeByPeriod.length; period++) {
            final double totalPercentChange = changeByPeriod[period][0];
            final double sampleCount = changeByPeriod[period][1];
            double percentChange;

            if (totalPercentChange == 0.0d || sampleCount == 0.0d) {
                percentChange = 0.0d;
            } else {
                percentChange = totalPercentChange / sampleCount;
            }

            // apply adjustments only if the initial point is within the
            // time period, and only for the first time period
            boolean applyAdjustment = period == 0 && topOfPeriod.before(initial.getX());

            if (applyAdjustment) {
                final double adjustmentFactor = findAdjustmentFactor(initial.getX(), timeUnits);
                percentChange = (totalPercentChange / sampleCount) * adjustmentFactor;
            }

            // figure out the next value and coerce to a sane number of
            // decimal places (2);
            final double newValue = (double) Math.round(yn * (1.0d + percentChange) * 100) / 100;

            final Timestamp timestamp = new Timestamp(
                    topOfPeriod.getTime() + (period * timeUnits.getDuration()));

            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Model %d for data set %d predicted point: (%s, %f)", model.getId(),
                        model.getTrainingDataSet().getId(), DateFormat.getInstance().format(timestamp),
                        newValue));
            }

            DataSetPoint ithPoint = this.dataSetPointDao.findByTimestamp(model.getPredictionDataSet(),
                    timestamp);

            // conditionally create
            if (ithPoint == null) {
                ithPoint = new DataSetPoint(model.getPredictionDataSet(), timestamp, newValue);
                this.dataSetPointDao.add(ithPoint);
            } else {
                // or update
                ithPoint.setY(newValue);

                // updated points retained, other existing removed
                existingPoints.remove(ithPoint);
            }

            // store current and use as starting point for next iteration
            yn = newValue;
        }

        // remove stale points from an old model execution
        for (final DataSetPoint toRemove : existingPoints) {
            this.dataSetPointDao.remove(toRemove);
        }

        result = true;

    } catch (final Exception e) {
        logger.warn("Model " + model.getId() + " failed with: " + e, e);
        result = false;
    } finally {
        stopWatch.stop();
        logger.info(String.format("Executing model %d took %s", model.getId(), stopWatch.toString()));
    }

    return result;
}

From source file:org.projectforge.task.TaskDao.java

/**
 * Gets the total duration of all time sheets of the given task (excluding the child tasks).
 * @param node//from  www.  j  ava 2  s. c  om
 * @return
 */
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public long readTotalDuration(final Integer taskId) {
    log.debug("Calculating duration for all tasks");
    final String intervalInSeconds = DatabaseSupport.instance().getIntervalInSeconds("startTime", "stopTime");
    if (intervalInSeconds != null) {
        @SuppressWarnings("unchecked")
        final List<Object> list = getHibernateTemplate()
                .find("select " + DatabaseSupport.instance().getIntervalInSeconds("startTime", "stopTime")
                        + " from TimesheetDO where task.id = ? and deleted=false", taskId);
        if (list.size() == 0) {
            return new Long(0);
        }
        Validate.isTrue(list.size() == 1);
        if (list.get(0) == null) { // Has happened one time, why (PROJECTFORGE-543)?
            return new Long(0);
        } else if (list.get(0) instanceof Integer) {
            return new Long((Integer) list.get(0));
        } else {
            return (Long) list.get(0);
        }
    }
    @SuppressWarnings("unchecked")
    final List<Object[]> result = getHibernateTemplate()
            .find("select startTime, stopTime from TimesheetDO where task.id = ? and deleted=false", taskId);
    if (CollectionUtils.isEmpty(result) == true) {
        return new Long(0);
    }
    long totalDuration = 0;
    for (final Object[] oa : result) {
        final Timestamp startTime = (Timestamp) oa[0];
        final Timestamp stopTime = (Timestamp) oa[1];
        final long duration = stopTime.getTime() - startTime.getTime();
        totalDuration += duration;
    }
    return totalDuration / 1000;
}

From source file:org.mule.modules.clarizen.api.ClarizenDateConverter.java

/**
 * Convert the input object into a Date object of the
 * specified type.//from  ww  w . j a  va  2 s.  c o m
 * <p>
 * This method handles conversions between the following
 * types:
 * <ul>
 *     <li><code>javax.xml.datatype.XMLGregorianCalendar</code></li>
 *     <li><code>java.util.Date</code></li>
 *     <li><code>java.util.Calendar</code></li>
 *     <li><code>java.sql.Date</code></li>
 *     <li><code>java.sql.Time</code></li>
 *     <li><code>java.sql.Timestamp</code></li>
 * </ul>
 *
 * It also handles conversion from a <code>String</code> to
 * any of the above types.
 * <p>
 *
 * For <code>String</code> conversion, if the converter has been configured
 * with one or more patterns (using <code>setPatterns()</code>), then
 * the conversion is attempted with each of the specified patterns.
 * Otherwise the default <code>DateFormat</code> for the default locale
 * (and <i>style</i> if configured) will be used.
 *
 * @param targetType Data type to which this value should be converted.
 * @param value The input value to be converted.
 * @return The converted value.
 * @throws Exception if conversion cannot be performed successfully
 */
@SuppressWarnings("rawtypes")
protected Object convertToType(Class targetType, Object value) throws Exception {

    Class sourceType = value.getClass();

    // For XMLGregorianCalendar
    if (value instanceof XMLGregorianCalendar) {
        XMLGregorianCalendar gregorianCalendar = (XMLGregorianCalendar) value;
        return toDate(targetType, gregorianCalendar.toGregorianCalendar().getTime().getTime());
    }

    // Handle java.sql.Timestamp
    if (value instanceof java.sql.Timestamp) {

        // ---------------------- JDK 1.3 Fix ----------------------
        // N.B. Prior to JDK 1.4 the Timestamp's getTime() method
        //      didn't include the milliseconds. The following code
        //      ensures it works consistently accross JDK versions
        java.sql.Timestamp timestamp = (java.sql.Timestamp) value;
        long timeInMillis = ((timestamp.getTime() / 1000) * 1000);
        timeInMillis += timestamp.getNanos() / 1000000;
        // ---------------------- JDK 1.3 Fix ----------------------
        return toDate(targetType, timeInMillis);
    }

    // Handle Date (includes java.sql.Date & java.sql.Time)
    if (value instanceof Date) {
        Date date = (Date) value;
        return toDate(targetType, date.getTime());
    }

    // Handle Calendar
    if (value instanceof Calendar) {
        Calendar calendar = (Calendar) value;
        return toDate(targetType, calendar.getTime().getTime());
    }

    // Handle Long
    if (value instanceof Long) {
        Long longObj = (Long) value;
        return toDate(targetType, longObj.longValue());
    }

    // Convert all other types to String & handle
    String stringValue = value.toString().trim();
    if (stringValue.length() == 0) {
        return handleMissing(targetType);
    }

    // Parse the Date/Time
    if (useLocaleFormat) {
        Calendar calendar = null;
        if (patterns != null && patterns.length > 0) {
            calendar = parse(sourceType, targetType, stringValue);
        } else {
            DateFormat format = getFormat(locale, timeZone);
            calendar = parse(sourceType, targetType, stringValue, format);
        }
        if (Calendar.class.isAssignableFrom(targetType)) {
            return calendar;
        } else {
            return toDate(targetType, calendar.getTime().getTime());
        }
    }

    // Default String conversion
    return toDate(targetType, stringValue);

}