Example usage for java.lang Double longValue

List of usage examples for java.lang Double longValue

Introduction

In this page you can find the example usage for java.lang Double longValue.

Prototype

public long longValue() 

Source Link

Document

Returns the value of this Double as a long after a narrowing primitive conversion.

Usage

From source file:info.raack.appliancelabeler.web.MainController.java

@RequestMapping(value = "/energy/{frequency}", method = RequestMethod.GET)
public void getEnergyData(@PathVariable("frequency") String frequency,
        @RequestParam(value = "start", required = false) Double startMillis,
        @RequestParam(value = "end", required = false) Double endMillis,
        @RequestParam(value = "ticks", required = false) Integer ticks, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    // need to get latest values from stepgreen service

    EnergyMonitor energyMonitor = getCurrentEnergyMonitor(request, response);

    Date start = new Date();
    Date end = new Date();

    if (startMillis != null && endMillis != null) {
        start = new Date(startMillis.longValue());
        end = new Date(endMillis.longValue());
    } else if (startMillis != null && endMillis == null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(startMillis.longValue());
        start = new Date();
        start.setTime(startMillis.longValue());

        c.add(Calendar.DATE, 1);//  w  w w .j  a v  a 2  s  .co  m
        end = c.getTime();
    } else if (startMillis == null && endMillis != null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(endMillis.longValue());
        end = new Date();
        end.setTime(endMillis.longValue());

        c.add(Calendar.DATE, -1);
        start = c.getTime();

    } else {
        createOneDaySpan(energyMonitor, start, end);
    }

    if (ticks == null) {
        ticks = 300;
    }

    Date queryStart = null;
    Date queryEnd = null;

    // if the time window is less than 5 minutes, then just take the window as is; otherwise, enlarge the window to the 5 minute interval requested
    if (end.getTime() - start.getTime() > (5 * 60 * 1000)) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(start);
        queryStart = dateUtils.getPreviousFiveMinuteIncrement(cal).getTime();

        cal = new GregorianCalendar();
        cal.setTime(end);
        queryEnd = dateUtils.getNextFiveMinuteIncrement(cal).getTime();
    } else {
        queryStart = start;
        queryEnd = end;
    }

    List<SecondData> data = getEnergyDataWithLimits(energyMonitor,
            DataService.DataFrequency.valueOf(frequency.toUpperCase()), queryStart, queryEnd, ticks);
    Map<UserAppliance, List<EnergyTimestep>> predictedEnergyUsage = dataService
            .getApplianceEnergyConsumptionForMonitor(energyMonitor, algorithm.getId(), queryStart, queryEnd);
    Map<UserAppliance, List<ApplianceStateTransition>> predictedApplianceStateTransitions = dataService
            .getPredictedApplianceStateTransitionsForMonitor(energyMonitor, algorithm.getId(), queryStart,
                    queryEnd);

    JsonSerializer<EnergyTimestep> dateSerializer = new JsonSerializer<EnergyTimestep>() {
        // serialize date to milliseconds since epoch
        public JsonElement serialize(EnergyTimestep energyTimestep, Type me, JsonSerializationContext arg2) {
            JsonArray object = new JsonArray();
            object.add(new JsonPrimitive(energyTimestep.getStartTime().getTime()));
            object.add(new JsonPrimitive(energyTimestep.getEnergyConsumed()));
            return object;
        }
    };

    EnergyWrapper energyWrapper = new EnergyWrapper(data, predictedEnergyUsage,
            predictedApplianceStateTransitions, database.getEnergyCost(energyMonitor));

    String dataJS = new GsonBuilder().registerTypeAdapter(EnergyTimestep.class, dateSerializer)
            .excludeFieldsWithModifiers(Modifier.STATIC).setExclusionStrategies(new ExclusionStrategy() {

                // skip logger
                public boolean shouldSkipClass(Class<?> clazz) {
                    return clazz.equals(Logger.class);
                }

                public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                    // skip endTime of energytimestep
                    return (fieldAttributes.getName().equals("endTime")
                            && fieldAttributes.getDeclaringClass() == EnergyTimestep.class) ||
                    // skip userAppliance, detectionAlgorithmId of appliance state transition
                    ((fieldAttributes.getName().equals("userAppliance")
                            || fieldAttributes.getName().equals("detectionAlgorithmId"))
                            && fieldAttributes.getDeclaringClass() == ApplianceStateTransition.class);
                }
            }).create().toJson(energyWrapper);

    response.getWriter().write(dataJS);

    // set appropriate JSON response type
    response.setContentType("application/json");
}

From source file:org.obiba.onyx.quartz.editor.openAnswer.OpenAnswerPanel.java

public OpenAnswerPanel(String id, IModel<OpenAnswerDefinition> model, IModel<Category> categoryModel,
        final IModel<Question> questionModel, final IModel<Questionnaire> questionnaireModel,
        IModel<LocaleProperties> localePropertiesModel, final FeedbackPanel feedbackPanel,
        final FeedbackWindow feedbackWindow) {
    super(id, model);
    this.questionModel = questionModel;
    this.questionnaireModel = questionnaireModel;
    this.localePropertiesModel = localePropertiesModel;
    this.feedbackPanel = feedbackPanel;
    this.feedbackWindow = feedbackWindow;

    final Question question = questionModel.getObject();
    final Category category = categoryModel.getObject();
    final OpenAnswerDefinition openAnswer = model.getObject();

    validatorWindow = new ModalWindow("validatorWindow");
    validatorWindow.setCssClassName("onyx");
    validatorWindow.setInitialWidth(850);
    validatorWindow.setInitialHeight(300);
    validatorWindow.setResizable(true);/*ww  w.  jav a2  s  .  c o  m*/
    validatorWindow.setTitle(new ResourceModel("Validator"));
    add(validatorWindow);

    initialName = model.getObject().getName();
    final TextField<String> name = new TextField<String>("name", new PropertyModel<String>(model, "name"));
    name.setLabel(new ResourceModel("Name"));
    name.add(new RequiredFormFieldBehavior());
    name.add(new PatternValidator(QuartzEditorPanel.ELEMENT_NAME_PATTERN));
    name.add(new AbstractValidator<String>() {
        @Override
        protected void onValidate(IValidatable<String> validatable) {
            if (!StringUtils.equals(initialName, validatable.getValue())) {
                boolean alreadyContains = false;
                if (category != null) {
                    Map<String, OpenAnswerDefinition> openAnswerDefinitionsByName = category
                            .getOpenAnswerDefinitionsByName();
                    alreadyContains = openAnswerDefinitionsByName.containsKey(validatable.getValue())
                            && openAnswerDefinitionsByName.get(validatable.getValue()) != openAnswer;
                }
                QuestionnaireFinder questionnaireFinder = QuestionnaireFinder
                        .getInstance(questionnaireModel.getObject());
                questionnaireModel.getObject().setQuestionnaireCache(null);
                OpenAnswerDefinition findOpenAnswerDefinition = questionnaireFinder
                        .findOpenAnswerDefinition(validatable.getValue());
                if (alreadyContains
                        || findOpenAnswerDefinition != null && findOpenAnswerDefinition != openAnswer) {
                    error(validatable, "OpenAnswerAlreadyExists");
                }
            }
        }
    });
    add(name).add(new SimpleFormComponentLabel("nameLabel", name));
    add(new HelpTooltipPanel("nameHelp", new ResourceModel("Name.Tooltip")));

    variable = new TextField<String>("variable", new MapModel<String>(
            new PropertyModel<Map<String, String>>(model, "variableNames"), question.getName()));
    variable.setLabel(new ResourceModel("Variable"));
    add(variable).add(new SimpleFormComponentLabel("variableLabel", variable));
    add(new HelpTooltipPanel("variableHelp", new ResourceModel("Variable.Tooltip")));

    if (category == null) {
        variableNameBehavior = new VariableNameBehavior(name, variable, question.getParentQuestion(), question,
                null) {
            @Override
            @SuppressWarnings("hiding")
            protected String generateVariableName(Question parentQuestion, Question question, Category category,
                    String name) {
                if (StringUtils.isBlank(name))
                    return "";
                if (category != null) {
                    return super.generateVariableName(parentQuestion, question, category, name);
                }
                String variableName = parentQuestion == null ? "" : parentQuestion.getName() + ".";
                if (question != null) {
                    variableName += question.getName() + "." + question.getName() + ".";
                }
                return variableName + StringUtils.trimToEmpty(name);
            }
        };
    } else {
        variableNameBehavior = new VariableNameBehavior(name, variable, question.getParentQuestion(), question,
                category);
    }

    add(variableNameBehavior);

    List<DataType> typeChoices = new ArrayList<DataType>(Arrays.asList(DataType.values()));
    typeChoices.remove(DataType.BOOLEAN);
    typeChoices.remove(DataType.DATA);
    dataTypeDropDown = new DropDownChoice<DataType>("dataType", new PropertyModel<DataType>(model, "dataType"),
            typeChoices, new IChoiceRenderer<DataType>() {
                @Override
                public Object getDisplayValue(DataType type) {
                    return new StringResourceModel("DataType." + type, OpenAnswerPanel.this, null).getString();
                }

                @Override
                public String getIdValue(DataType type, int index) {
                    return type.name();
                }
            });

    dataTypeDropDown.setLabel(new ResourceModel("DataType"));
    dataTypeDropDown.add(new RequiredFormFieldBehavior());
    dataTypeDropDown.setNullValid(false);

    add(dataTypeDropDown).add(new SimpleFormComponentLabel("dataTypeLabel", dataTypeDropDown));
    // add(new HelpTooltipPanel("dataTypeHelp", new ResourceModel("DataType.Tooltip")));

    TextField<String> unit = new TextField<String>("unit", new PropertyModel<String>(model, "unit"));
    unit.setLabel(new ResourceModel("Unit"));
    add(unit).add(new SimpleFormComponentLabel("unitLabel", unit));
    add(new HelpTooltipPanel("unitHelp", new ResourceModel("Unit.Tooltip")));

    PatternValidator numericPatternValidator = new PatternValidator("\\d*");
    // ui Arguments
    Integer size = openAnswer.getInputSize();
    sizeField = new TextField<String>("size", new Model<String>(size == null ? null : String.valueOf(size)));
    sizeField.add(numericPatternValidator);
    sizeField.setLabel(new ResourceModel("SizeLabel"));
    add(new SimpleFormComponentLabel("sizeLabel", sizeField));
    add(sizeField);

    Integer rows = openAnswer.getInputNbRows();
    rowsField = new TextField<String>("rows", new Model<String>(rows == null ? null : String.valueOf(rows)));
    rowsField.add(numericPatternValidator);
    rowsField.setLabel(new ResourceModel("RowsLabel"));
    add(new SimpleFormComponentLabel("rowsLabel", rowsField));
    add(rowsField);

    localePropertiesUtils.load(localePropertiesModel.getObject(), questionnaireModel.getObject(), openAnswer);

    Map<String, Boolean> visibleStates = new HashMap<String, Boolean>();
    if (openAnswer.isSuggestionAnswer()) {
        for (String item : new OpenAnswerDefinitionSuggestion(openAnswer).getSuggestionItems()) {
            visibleStates.put(item, false);
        }
    }
    add(labelsPanel = new LabelsPanel("labels", localePropertiesModel, model, feedbackPanel, feedbackWindow,
            null, visibleStates));

    CheckBox requiredCheckBox = new CheckBox("required", new PropertyModel<Boolean>(model, "required"));
    requiredCheckBox.setLabel(new ResourceModel("AnswerRequired"));
    add(requiredCheckBox);
    add(new SimpleFormComponentLabel("requiredLabel", requiredCheckBox));

    // min/max validators
    String maxValue = null, minValue = null, patternValue = null;
    for (IDataValidator<?> dataValidator : openAnswer.getDataValidators()) {
        IValidator<?> validator = dataValidator.getValidator();
        if (validator instanceof RangeValidator<?>) {
            RangeValidator<?> rangeValidator = (RangeValidator<?>) validator;
            Object minimum = rangeValidator.getMinimum();
            Object maximum = rangeValidator.getMaximum();
            if (dataValidator.getDataType() == DataType.DATE) {
                if (minimum != null)
                    minValue = onyxSettings.getDateFormat().format((Date) minimum);
                if (maximum != null)
                    maxValue = onyxSettings.getDateFormat().format((Date) maximum);
            } else {
                if (minimum != null)
                    minValue = String.valueOf(minimum);
                if (maximum != null)
                    maxValue = String.valueOf(maximum);
            }
        } else if (validator instanceof StringValidator.MaximumLengthValidator) {
            int maximum = ((StringValidator.MaximumLengthValidator) validator).getMaximum();
            if (maximum > 0)
                maxValue = String.valueOf(maximum);
        } else if (validator instanceof MaximumValidator<?>) {
            Object maximum = ((MaximumValidator<?>) validator).getMaximum();
            if (dataValidator.getDataType() == DataType.DATE) {
                if (maximum != null)
                    maxValue = onyxSettings.getDateFormat().format((Date) maximum);
            } else {
                if (maximum != null)
                    maxValue = String.valueOf(maximum);
            }
        } else if (validator instanceof StringValidator.MinimumLengthValidator) {
            int minimum = ((StringValidator.MinimumLengthValidator) validator).getMinimum();
            if (minimum > 0)
                minValue = String.valueOf(minimum);
        } else if (validator instanceof MinimumValidator<?>) {
            Object minimum = ((MinimumValidator<?>) validator).getMinimum();
            if (dataValidator.getDataType() == DataType.DATE) {
                if (minimum != null)
                    minValue = onyxSettings.getDateFormat().format((Date) minimum);
            } else {
                if (minimum != null)
                    minValue = String.valueOf(minimum);
            }
        } else if (validator instanceof PatternValidator) {
            patternValue = ((PatternValidator) validator).getPattern().toString();
        }
    }

    patternField = new TextField<String>("patternValidator", new Model<String>(patternValue));
    patternField.setLabel(new ResourceModel("PatternLabel"));
    patternField.setOutputMarkupId(true);
    add(new SimpleFormComponentLabel("patternLabel", patternField));
    add(patternField);

    minMaxContainer = new WebMarkupContainer("minMaxContainer");
    minMaxContainer.setOutputMarkupId(true);
    add(minMaxContainer);

    minLength = new TextField<String>("minLength", new Model<String>(minValue), String.class);
    minLength.setLabel(new ResourceModel("Minimum.length"));
    minMaxContainer.add(minLength);

    maxLength = new TextField<String>("maxLength", new Model<String>(maxValue), String.class);
    maxLength.setLabel(new ResourceModel("Maximum.length"));
    minMaxContainer.add(maxLength);

    minNumeric = new TextField<String>("minNumeric", new Model<String>(minValue), String.class);
    minNumeric.setLabel(new ResourceModel("Minimum"));
    minNumeric.add(numericPatternValidator);
    minMaxContainer.add(minNumeric);

    maxNumeric = new TextField<String>("maxNumeric", new Model<String>(maxValue), String.class);
    maxNumeric.setLabel(new ResourceModel("Maximum"));
    maxNumeric.add(numericPatternValidator);
    minMaxContainer.add(maxNumeric);

    PatternValidator decimalPatternValidator = new PatternValidator("\\d*(\\.\\d+)?");
    minDecimal = new TextField<String>("minDecimal", new Model<String>(minValue), String.class);
    minDecimal.setLabel(new ResourceModel("Minimum"));
    minDecimal.add(decimalPatternValidator);
    minMaxContainer.add(minDecimal);

    maxDecimal = new TextField<String>("maxDecimal", new Model<String>(maxValue), String.class);
    maxDecimal.setLabel(new ResourceModel("Maximum"));
    maxDecimal.add(decimalPatternValidator);
    minMaxContainer.add(maxDecimal);

    String patternStr = onyxSettings.getDateFormat().toPattern();

    beforeDate = new TextField<String>("beforeDate", new Model<String>(maxValue), String.class);
    beforeDate.setLabel(new Model<String>(
            new StringResourceModel("Before", this, null).getObject() + " (" + patternStr + ")"));
    minMaxContainer.add(beforeDate);

    afterDate = new TextField<String>("afterDate", new Model<String>(minValue), String.class);
    afterDate.setLabel(new Model<String>(
            new StringResourceModel("After", this, null).getObject() + " (" + patternStr + ")"));
    minMaxContainer.add(afterDate);

    minMaxContainer.add(minimumLabel = new SimpleFormComponentLabel("minimumLabel", minLength));
    minMaxContainer.add(maximumLabel = new SimpleFormComponentLabel("maximumLabel", maxLength));

    setMinMaxLabels(dataTypeDropDown.getModelObject());

    add(validators = new OnyxEntityList<ComparingDataSource>("validators", new ValidationDataSourcesProvider(),
            new ValidationDataSourcesColumnProvider(), new ResourceModel("Validators")));

    AjaxLink<Void> addValidator = new AjaxLink<Void>("addValidator") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            if (dataTypeDropDown.getModelObject() == null) {
                info(new StringResourceModel("SelectDataTypeFirst", OpenAnswerPanel.this, null).getString());
                feedbackWindow.setContent(feedbackPanel);
                feedbackWindow.show(target);
            } else {
                validatorWindow.setContent(new ValidationDataSourceWindow("content",
                        new Model<ComparingDataSource>(), questionModel, questionnaireModel,
                        dataTypeDropDown.getModelObject(), validatorWindow) {
                    @Override
                    protected void onSave(@SuppressWarnings("hiding") AjaxRequestTarget target,
                            ComparingDataSource comparingDataSource) {
                        openAnswer.addValidationDataSource(comparingDataSource);
                        target.addComponent(validators);
                    }
                });
                validatorWindow.show(target);
            }
        }
    };
    addValidator.setOutputMarkupId(true);
    add(addValidator.add(new Image("img", Images.ADD)));

    dataTypeDropDown.add(new OnChangeAjaxBehavior() {

        @SuppressWarnings("incomplete-switch")
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            setFieldType();
            String value = dataTypeDropDown.getValue(); // use value because model is not set if validation error
            DataType valueOf = DataType.valueOf(value);
            if (value != null) {
                OpenAnswerDefinition openAnswerDefinition = (OpenAnswerDefinition) getDefaultModelObject();
                for (Data data : openAnswerDefinition.getDefaultValues()) {

                    switch (valueOf) {
                    case DATE:
                        try {
                            onyxSettings.getDateFormat().parse(data.getValueAsString());
                        } catch (ParseException nfe) {
                            error(new StringResourceModel("InvalidCastType", OpenAnswerPanel.this, null)
                                    .getObject());
                            showFeedbackErrorAndReset(target);
                            return;
                        }
                        break;
                    case DECIMAL:
                        try {
                            Double.parseDouble(data.getValueAsString());
                        } catch (NumberFormatException nfe) {
                            error(new StringResourceModel("InvalidCastType", OpenAnswerPanel.this, null)
                                    .getObject());
                            showFeedbackErrorAndReset(target);
                            return;
                        }
                        break;
                    case INTEGER:
                        if (data.getType() == DataType.DECIMAL) {
                            Double d = data.getValue();
                            if (d != d.longValue()) {
                                error(new StringResourceModel("InvalidCastType", OpenAnswerPanel.this, null)
                                        .getObject());
                                showFeedbackErrorAndReset(target);
                                return;
                            }
                        } else {
                            try {
                                Long.parseLong(data.getValueAsString());
                            } catch (NumberFormatException nfe) {
                                error(new StringResourceModel("InvalidCastType", OpenAnswerPanel.this, null)
                                        .getObject());
                                showFeedbackErrorAndReset(target);
                                return;
                            }
                        }
                        break;
                    case TEXT:
                        break;
                    }
                }
                for (Data data : openAnswerDefinition.getDefaultValues()) {
                    switch (valueOf) {
                    case DATE:
                        try {
                            data.setTypeAndValue(valueOf,
                                    onyxSettings.getDateFormat().parse(data.getValueAsString()));
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    case DECIMAL:
                        data.setTypeAndValue(valueOf, Double.parseDouble(data.getValueAsString()));
                        break;
                    case INTEGER:
                        if (data.getType() == DataType.DECIMAL) {
                            data.setTypeAndValue(valueOf, ((Double) data.getValue()).longValue());
                        } else {
                            data.setTypeAndValue(valueOf, Integer.parseInt(data.getValueAsString()));
                        }
                        break;
                    case TEXT:
                        data.setTypeAndValue(valueOf,
                                data.getType() == DataType.DATE
                                        ? onyxSettings.getDateFormat().format(data.getValue())
                                        : data.getValueAsString());
                        break;
                    }
                }
            }
            setMinMaxLabels(value == null ? null : valueOf);
            target.addComponent(minMaxContainer);
            target.addComponent(patternField);
            defaultValuesList.refreshList(target);
        }

        private void showFeedbackErrorAndReset(AjaxRequestTarget target) {
            dataTypeDropDown.setModelObject(openAnswer.getDefaultValues().get(0).getType());
            target.addComponent(dataTypeDropDown);
            OpenAnswerPanel.this.feedbackWindow.setContent(OpenAnswerPanel.this.feedbackPanel);
            OpenAnswerPanel.this.feedbackWindow.show(target);
        }
    });

    final IModel<String> addDefaultValuesModel = new Model<String>();

    List<ITab> tabs = new ArrayList<ITab>();
    tabs.add(new AbstractTab(new ResourceModel("Add.simple")) {
        @Override
        public Panel getPanel(String panelId) {
            return new SimpleAddPanel(panelId, addDefaultValuesModel);
        }
    });
    tabs.add(new AbstractTab(new ResourceModel("Add.bulk")) {
        @Override
        public Panel getPanel(String panelId) {
            return new BulkAddPanel(panelId, addDefaultValuesModel);
        }
    });
    add(new AjaxTabbedPanel("addTabs", tabs));

    defaultValuesList = new SortableList<Data>("defaultValues", openAnswer.getDefaultValues(), true) {

        @Override
        public Component getItemTitle(@SuppressWarnings("hiding") String id, Data data) {
            return new Label(id,
                    data.getType() == DataType.DATE ? onyxSettings.getDateFormat().format(data.getValue())
                            : data.getValueAsString());
        }

        @Override
        public void editItem(Data t, AjaxRequestTarget target) {

        }

        @SuppressWarnings("unchecked")
        @Override
        public void deleteItem(final Data data, AjaxRequestTarget target) {
            ((OpenAnswerDefinition) OpenAnswerPanel.this.getDefaultModelObject()).removeDefaultData(data);
            for (Locale locale : OpenAnswerPanel.this.localePropertiesModel.getObject().getLocales()) {
                List<KeyValue> list = OpenAnswerPanel.this.localePropertiesModel.getObject()
                        .getElementLabels(openAnswer).get(locale);
                Collection<KeyValue> toDelete = Collections2.filter(list, new Predicate<KeyValue>() {

                    @Override
                    public boolean apply(KeyValue input) {
                        return input.getKey().equals(data.getValue().toString());
                    }

                });
                list.remove(toDelete.iterator().next());
            }
            OpenAnswerPanel.this.addOrReplace(
                    labelsPanel = new LabelsPanel("labels", OpenAnswerPanel.this.localePropertiesModel,
                            (IModel<OpenAnswerDefinition>) OpenAnswerPanel.this.getDefaultModel(),
                            OpenAnswerPanel.this.feedbackPanel, OpenAnswerPanel.this.feedbackWindow));
            target.addComponent(labelsPanel);
            refreshList(target);
        }

        @Override
        public Button[] getButtons() {
            return null;
        }

    };
    add(defaultValuesList);
    add(new HelpTooltipPanel("defaultValuesHelp", new ResourceModel("DefaultValues.Tooltip")));
}

From source file:org.egov.wtms.web.controller.application.UpdateConnectionController.java

private String loadViewData(final Model model, final HttpServletRequest request,
        final WaterConnectionDetails waterConnectionDetails) {
    model.addAttribute("stateType", waterConnectionDetails.getClass().getSimpleName());
    final WorkflowContainer workflowContainer = new WorkflowContainer();
    Boolean isCommissionerLoggedIn = Boolean.FALSE;
    Boolean isSanctionedDetailEnable = isCommissionerLoggedIn;
    final String loggedInUserDesignation = waterTaxUtils.loggedInUserDesignation(waterConnectionDetails);

    if (REGULARIZE_CONNECTION.equalsIgnoreCase(waterConnectionDetails.getApplicationType().getCode())
            && (APPLICATION_STATUS_CREATED.equalsIgnoreCase(waterConnectionDetails.getStatus().getCode())
                    || APPLICATION_STATUS_ESTIMATENOTICEGEN
                            .equalsIgnoreCase(waterConnectionDetails.getStatus().getCode()))) {
        final DonationDetails donationDetails = connectionDemandService
                .getDonationDetails(waterConnectionDetails);
        final Double donationAmount = donationDetails == null ? 0d
                : connectionDemandService.getDonationDetails(waterConnectionDetails).getAmount();
        BigDecimal penaltyPercent = BigDecimal.ZERO;
        final AppConfig appConfig = appConfigService.getAppConfigByModuleNameAndKeyName(MODULE_NAME,
                WCMS_PENALTY_CHARGES_PERCENTAGE);
        if (appConfig != null && !appConfig.getConfValues().isEmpty())
            penaltyPercent = BigDecimal.valueOf(Long.valueOf(appConfig.getConfValues().get(0).getValue()));
        model.addAttribute(DONATION_AMOUNT, donationAmount.longValue());
        model.addAttribute(PENALTY_AMOUNT,
                BigDecimal.valueOf(donationAmount).multiply(penaltyPercent).divide(new BigDecimal(100)));
        model.addAttribute("currentDemand", waterTaxUtils.getCurrentDemand(waterConnectionDetails).getDemand());
    }/*from   w ww  . ja v  a 2 s.c o m*/

    if (waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_FEEPAID)
            || waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_DIGITALSIGNPENDING)
            || waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_CLOSERDIGSIGNPENDING)
            || waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_RECONNDIGSIGNPENDING)
            || (waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_RECONNCTIONINPROGRESS)
                    || waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_CLOSERINPROGRESS))
                    && !waterConnectionDetails.getState().getValue().equals(WF_STATE_REJECTED))
        workflowContainer.setCurrentDesignation(loggedInUserDesignation);
    if (loggedInUserDesignation != null
            && (loggedInUserDesignation.equalsIgnoreCase(SENIOR_ASSISTANT_DESIGN)
                    || loggedInUserDesignation.equalsIgnoreCase(JUNIOR_ASSISTANT_DESIGN))
            && waterConnectionDetails.getStatus() != null
            && (waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_CREATED)
                    || waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_CLOSERINITIATED)
                    || waterConnectionDetails.getStatus().getCode().equals(WORKFLOW_RECONNCTIONINITIATED))
            || loggedInUserDesignation.equalsIgnoreCase(ASSISTANT_ENGINEER_DESIGN) && (waterConnectionDetails
                    .getStatus().getCode().equals(APPLICATION_STATUS_CLOSERINITIATED)
                    || waterConnectionDetails.getStatus().getCode().equals(WORKFLOW_RECONNCTIONINITIATED)))
        workflowContainer.setCurrentDesignation(null);
    if (waterConnectionDetails.getCloseConnectionType() != null
            && waterConnectionDetails.getReConnectionReason() == null) {
        model.addAttribute(ADDITIONALRULE, CLOSECONNECTION);
        workflowContainer.setAdditionalRule(CLOSECONNECTION);
        if (waterConnectionDetails.getCloseConnectionType().equals(PERMENENTCLOSECODE))
            waterConnectionDetails.setCloseConnectionType(ClosureType.Permanent.getName());
        else
            waterConnectionDetails.setCloseConnectionType(ClosureType.Temporary.getName());

        model.addAttribute("radioButtonMap", Arrays.asList(ClosureType.values()));
    }
    model.addAttribute("applicationDocList", waterConnectionDetailsService
            .getApplicationDocForExceptClosureAndReConnection(waterConnectionDetails));
    if (waterConnectionDetails.getCloseConnectionType() != null
            && (waterConnectionDetails.getReConnectionReason() == null
                    || waterConnectionDetails.getReConnectionReason() != null))
        if (!waterConnectionDetails.getApplicationDocs().isEmpty())
            for (final ApplicationDocuments appDoc : waterConnectionDetails.getApplicationDocs()) {
                if (appDoc.getDocumentNames() != null
                        && appDoc.getDocumentNames().getApplicationType().getCode().equals(CLOSINGCONNECTION)) {
                    final List<ApplicationDocuments> tempListDoc = new ArrayList<>();
                    tempListDoc.add(appDoc);
                    model.addAttribute(APP_DOCUMENT_LIST, tempListDoc);
                }
                if (appDoc.getDocumentNames() != null
                        && appDoc.getDocumentNames().getApplicationType().getCode().equals(RECONNECTION)) {
                    final List<ApplicationDocuments> tempListDocrecon = new ArrayList<>();
                    tempListDocrecon.add(appDoc);
                    model.addAttribute(APP_DOCUMENT_LIST, tempListDocrecon);
                }

            }
        else
            model.addAttribute(APP_DOCUMENT_LIST, waterConnectionDetails.getApplicationDocs());

    if (waterConnectionDetails.getCloseConnectionType() != null
            && waterConnectionDetails.getReConnectionReason() != null) {
        model.addAttribute(ADDITIONALRULE, RECONNECTION);
        workflowContainer.setAdditionalRule(RECONNECTION);

    } else if (isBlank(workflowContainer.getAdditionalRule())) {
        workflowContainer.setAdditionalRule(waterConnectionDetails.getApplicationType().getCode());
        model.addAttribute(ADDITIONALRULE, waterConnectionDetails.getApplicationType().getCode());
    }
    if (WF_STATE_APPROVAL_PENDING.equalsIgnoreCase(waterConnectionDetails.getCurrentState().getValue())
            && waterConnectionDetails.getApprovalNumber() != null
            && COMMISSIONER_DESGN.equalsIgnoreCase(loggedInUserDesignation)
            && APPLICATION_STATUS_DIGITALSIGNPENDING
                    .equalsIgnoreCase(waterConnectionDetails.getStatus().getCode()))
        workflowContainer.setPendingActions(PENDING_DIGI_SIGN);
    else if (Arrays.asList(NEWCONNECTION, ADDNLCONNECTION, CHANGEOFUSE)
            .contains(waterConnectionDetails.getApplicationType().getCode())
            && APPLICATION_STATUS_FEEPAID.equalsIgnoreCase(waterConnectionDetails.getStatus().getCode())
            && COMMISSIONER_DESGN.equalsIgnoreCase(loggedInUserDesignation))
        workflowContainer.setPendingActions(COMM_APPROVAL_PENDING);
    prepareWorkflow(model, waterConnectionDetails, workflowContainer);
    model.addAttribute("currentState", waterConnectionDetails.getCurrentState().getValue());
    model.addAttribute("currentUser", waterTaxUtils.getCurrentUserRole(securityUtils.getCurrentUser()));
    model.addAttribute("waterConnectionDetails", waterConnectionDetails);
    model.addAttribute("feeDetails", connectionDemandService.getSplitFee(waterConnectionDetails));
    model.addAttribute("connectionType", waterConnectionDetailsService.getConnectionTypesMap()
            .get(waterConnectionDetails.getConnectionType().name()));
    model.addAttribute("applicationHistory", waterConnectionDetailsService.getHistory(waterConnectionDetails));
    model.addAttribute("approvalDepartmentList", departmentService.getAllDepartments());
    if (waterConnectionDetails.getStatus() != null
            && waterConnectionDetails.getStatus().getCode().equalsIgnoreCase(APPLICATION_STATUS_WOGENERATED))
        model.addAttribute("meterCostMasters",
                meterCostService.findByPipeSize(waterConnectionDetails.getPipeSize()));

    if (waterConnectionDetails.getStatus() != null
            && waterConnectionDetails.getStatus().getCode().equalsIgnoreCase(APPLICATION_STATUS_FEEPAID)) {
        final ChairPerson chairPerson = chairPersonService.getActiveChairPersonAsOnCurrentDate();
        model.addAttribute("chairPerson", chairPerson);
        model.addAttribute("sanctionDateLowerLimit",
                DateUtils.daysBetween(waterConnectionDetails.getApplicationDate(), new Date()));

    }

    appendModeBasedOnApplicationCreator(model, request, waterConnectionDetails);
    if (loggedInUserDesignation != null && !"".equals(loggedInUserDesignation)
            && loggedInUserDesignation.equalsIgnoreCase(COMMISSIONER_DESGN)
            && (waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_DIGITALSIGNPENDING)
                    || waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_FEEPAID)
                    || waterConnectionDetails.getStatus().getCode()
                            .equals(APPLICATION_STATUS_CLOSERDIGSIGNPENDING)
                    || waterConnectionDetails.getStatus().getCode()
                            .equals(APPLICATION_STATUS_RECONNCTIONINPROGRESS)
                    || waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_CLOSERINPROGRESS)
                    || waterConnectionDetails.getStatus().getCode()
                            .equals(APPLICATION_STATUS_RECONNDIGSIGNPENDING)))
        isCommissionerLoggedIn = Boolean.TRUE;
    if (COMMISSIONER_DESGN.equalsIgnoreCase(loggedInUserDesignation)
            || DEPUTY_ENGINEER_DESIGN.equalsIgnoreCase(loggedInUserDesignation)
            || EXECUTIVE_ENGINEER_DESIGN.equalsIgnoreCase(loggedInUserDesignation)
            || MUNICIPAL_ENGINEER_DESIGN.equalsIgnoreCase(loggedInUserDesignation)
            || SUPERIENTEND_ENGINEER_DESIGN.equalsIgnoreCase(loggedInUserDesignation)
            || SUPERINTENDING_ENGINEER_DESIGNATION.equalsIgnoreCase(loggedInUserDesignation)
                    && (waterConnectionDetails.getApprovalNumber() == null
                            || !APPLICATION_STATUS_DIGITALSIGNPENDING
                                    .equalsIgnoreCase(waterConnectionDetails.getStatus().getCode())))
        isSanctionedDetailEnable = Boolean.TRUE;

    final BigDecimal waterTaxDueforParent = waterConnectionDetailsService
            .getWaterTaxDueAmount(waterConnectionDetails);
    model.addAttribute("waterTaxDueforParent", waterTaxDueforParent);
    if (loggedInUserDesignation != null
            && (loggedInUserDesignation.equals(SENIOR_ASSISTANT_DESIGN)
                    || loggedInUserDesignation.equals(JUNIOR_ASSISTANT_DESIGN))
            && waterConnectionDetails.getStatus() != null
            && (waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_CREATED)
                    || waterConnectionDetails.getStatus().getCode().equals(APPLICATION_STATUS_CLOSERINITIATED)
                    || waterConnectionDetails.getStatus().getCode().equals(WORKFLOW_RECONNCTIONINITIATED))
            || loggedInUserDesignation.equalsIgnoreCase(ASSISTANT_ENGINEER_DESIGN) && (waterConnectionDetails
                    .getStatus().getCode().equals(APPLICATION_STATUS_CLOSERINITIATED)
                    || waterConnectionDetails.getStatus().getCode().equals(WORKFLOW_RECONNCTIONINITIATED)))
        model.addAttribute("currentDesignation", "");
    else
        model.addAttribute("currentDesignation", loggedInUserDesignation);

    if (!WF_STATE_REJECTED.equals(waterConnectionDetails.getState().getValue())
            && !WF_STATE_CLERK_APPROVED.equals(waterConnectionDetails.getState().getValue())) {
        final AppConfig appConfig = appConfigService.getAppConfigByModuleNameAndKeyName(MODULE_NAME,
                NON_METERED.equals(waterConnectionDetails.getConnectionType())
                        ? PROCEED_WITHOUT_NONMETER_EST_AMT
                        : PROCEED_WITHOUT_METER_EST_AMT);
        if (YES.equalsIgnoreCase(appConfig.getConfValues().get(0).getValue()))
            model.addAttribute("proceedWithoutDonation", "true");
    }
    model.addAttribute("hasJuniorOrSeniorAssistantRole",
            waterTaxUtils.isLoggedInUserJuniorOrSeniorAssistant(ApplicationThreadLocals.getUserId()));
    model.addAttribute("reassignEnabled", waterTaxUtils.reassignEnabled());
    model.addAttribute("applicationState", waterConnectionDetails.getState().getValue());
    model.addAttribute("statuscode", waterConnectionDetails.getStatus().getCode());
    model.addAttribute("isCommissionerLoggedIn", isCommissionerLoggedIn);
    model.addAttribute("isSanctionedDetailEnable", isSanctionedDetailEnable);
    model.addAttribute("usageTypes", usageTypeService.getActiveUsageTypes());
    model.addAttribute("connectionCategories", connectionCategoryService.getAllActiveConnectionCategory());
    model.addAttribute("pipeSizes", pipeSizeService.getAllActivePipeSize());
    model.addAttribute("typeOfConnection", waterConnectionDetails.getApplicationType().getCode());
    model.addAttribute("ownerPosition", waterConnectionDetails.getState().getOwnerPosition().getId());
    return "newconnection-edit";
}

From source file:com.redhat.rhn.taskomatic.task.CobblerSyncTask.java

/**
 * {@inheritDoc}//from  ww w.  j av  a  2 s. com
 */
public void execute(JobExecutionContext ctxIn) throws JobExecutionException {

    try {
        XMLRPCInvoker invoker = (XMLRPCInvoker) MethodUtil
                .getClassFromConfig(CobblerXMLRPCHelper.class.getName());

        Double mtime = null;
        try {
            mtime = (Double) invoker.invokeMethod("last_modified_time", new ArrayList());
        } catch (XmlRpcFault e) {
            log.error("Error calling cobbler.", e);
        }

        CobblerDistroSyncCommand distSync = new CobblerDistroSyncCommand();
        ValidatorError ve = distSync.syncNullDistros();
        if (ve != null && distroWarnCount < 1) {
            TaskHelper.sendErrorEmail(log, ve.getMessage());
            distroWarnCount++;
        }

        // if we need to update a profile's kickstart tree, do that now
        List<KickstartData> profiles = KickstartFactory.lookupKickstartDataByUpdateable();
        for (KickstartData profile : profiles) {
            KickstartableTree tree = KickstartFactory.getNewestTree(profile.getRealUpdateType(),
                    profile.getChannel().getId(), profile.getOrg());
            if (tree != null && !tree.equals(profile.getTree())) {
                KickstartEditCommand cmd = new KickstartEditCommand(profile, null);
                cmd.updateKickstartableTree(profile.getChannel().getId(), profile.getOrg().getId(),
                        tree.getId(), tree.getDefaultDownloadLocation(""));
                if (StringUtils.isNotEmpty(profile.getCobblerId())) {
                    CobblerProfileEditCommand cpec = new CobblerProfileEditCommand(profile);
                    cpec.store();
                }
            }
        }

        log.debug("mtime: " + mtime.longValue() + ", last modified: " + LAST_UPDATED.get());
        //If we got an mtime from cobbler and that mtime is before our last update
        // Then don't update anything
        if (mtime.longValue() < CobblerSyncTask.LAST_UPDATED.get()) {
            log.debug("Cobbler mtime is less than last change, skipping");
            return;
        }
        log.debug("Syncing distros and profiles.");

        ve = distSync.store();
        if (ve != null) {
            TaskHelper.sendErrorEmail(log, ve.getMessage());
        }

        CobblerProfileSyncCommand profSync = new CobblerProfileSyncCommand();
        profSync.store();

        LAST_UPDATED.set((new Date()).getTime() / 1000 + 1);
    } catch (RuntimeException re) {
        log.error("RuntimeExceptionError trying to sync to cobbler: " + re.getMessage(), re);
        // Only throw up one error.  Otherwise if say cobblerd is shutoff you can
        // possibly generate 1 stacktrace email per minute which is quite spammy.
        if (errorCount < 1) {
            errorCount++;
            log.error("re-throwing exception since we havent yet.");
            throw re;
        }
        log.error("Not re-throwing any more errors.");
    }
}

From source file:com.google.acre.script.HostEnv.java

@JSFunction
public void async_wait(Double timeout_ms) {
    long timeout = (LIMIT_EXECUTION_TIME)
            ? req._deadline - System.currentTimeMillis() - NETWORK_DEADLINE_ADVANCE
            : ACRE_URLFETCH_TIMEOUT;

    // XXX consider throwing, or at least warning if this condition fails
    if (!timeout_ms.isNaN() && timeout_ms.longValue() < timeout) {
        timeout = timeout_ms.longValue();
    }//from  ww  w .j  a va 2s . c  om

    _async_fetch.wait_on_result(timeout, TimeUnit.MILLISECONDS);
}

From source file:de.otto.mongodb.profiler.web.OpProfileController.java

@RequestMapping(value = "/{id:.+}/stats", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<String> getStatsData(@PathVariable("connectionId") final String connectionId,
        @PathVariable("databaseName") final String databaseName, @PathVariable("id") final String id,
        @RequestParam(value = "datum", required = false) final List<String> datum,
        @RequestParam(value = "from", required = false) final Long from,
        @RequestParam(value = "to", required = false) final Long to,
        @RequestParam(value = "min", required = false) final Double min,
        @RequestParam(value = "max", required = false) final Double max,
        @RequestParam(value = "limit", required = false) final Integer limit) throws Exception {

    final ProfiledDatabase database = requireDatabase(connectionId, databaseName);

    final OpProfile profile = requireProfile(database, id);

    final JsonObject json = new JsonObject();
    final JsonObject outliersJson = new JsonObject();

    final JsonObject params = new JsonObject();
    outliersJson.add("params", params);

    final JsonArray datumParamValues = new JsonArray();
    params.add("datum", datumParamValues);
    if (datum != null) {
        for (String datumValue : datum) {
            datumParamValues.add(new JsonPrimitive(datumValue));
        }/*from w  w  w .  j  av a 2s .  c om*/
    }

    final DateTime lowerTimeBound = from != null ? new DateTime(from.longValue()) : null;
    final DateTime upperTimeBound = to != null ? new DateTime(to.longValue()) : null;

    if (lowerTimeBound != null && upperTimeBound != null && !upperTimeBound.isAfter(lowerTimeBound)) {
        throw new IllegalArgumentException("'to' must not be lower than or equal to 'from'");
    }

    params.add("from", from != null ? new JsonPrimitive(from.longValue()) : null);
    params.add("to", to != null ? new JsonPrimitive(to.longValue()) : null);

    if (min != null && max != null && !(max.longValue() > min.longValue())) {
        throw new IllegalArgumentException("'max' must not be lower than or equal to 'min'");
    }

    params.add("min", min != null ? new JsonPrimitive(min.intValue()) : null);
    params.add("max", max != null ? new JsonPrimitive(max.intValue()) : null);

    if (limit != null && limit.intValue() < 1) {
        throw new IllegalArgumentException("'limit' must not be lower than 1");
    }

    final int maximumValues = limit != null && limit.intValue() > 0 ? limit.intValue() : maximumGraphValues;

    params.add("limit", new JsonPrimitive(maximumValues));

    if (profile.getOutlierConfiguration() != null && profile.getOutlierConfiguration().captureOutliers()) {

        final OutlierGraphDataBuilder builder = new OutlierGraphDataBuilder(datum, maximumValues,
                lowerTimeBound, upperTimeBound, min, max);

        builder.add("executionTimeOutliers", "Execution time outliers", profile.getAverageMillisOutliers());
        builder.add("readLockAcquisitionTimeOutliers", "Read lock acquisition time outliers",
                profile.getAverageAcquireReadLockMicrosOutliers());
        builder.add("writeLockAcquisitionTimeOutliers", "Write lock acquisition time outliers",
                profile.getAverageAcquireWriteLockMicrosOutliers());
        builder.add("readLockTimeOutliers", "Read lock time outliers",
                profile.getAverageLockedReadMicrosOutliers());
        builder.add("writeLockTimeOutliers", "Write lock time outliers",
                profile.getAverageLockedWriteMicrosOutliers());

        outliersJson.add("data", builder.getGroups());
        outliersJson.add("lowestTime", new JsonPrimitive(builder.getLowestTime()));
        outliersJson.add("highestTime", new JsonPrimitive(builder.getHighestTime()));

        final JsonArray warningJson = new JsonArray();

        if (!builder.getKeysWithTooMuchData().isEmpty()) {
            final StringBuilder warning = new StringBuilder();
            final JsonArray tooMuchDataFor = new JsonArray();
            for (String key : builder.getKeysWithTooMuchData()) {
                tooMuchDataFor.add(new JsonPrimitive(key));
                if (warning.length() > 0) {
                    warning.append(", ");
                }
                warning.append(key);
            }
            warningJson.add(new JsonPrimitive(String.format(
                    "The maximum amount of %d values has been exceeded. "
                            + "The following data could not be (completely) returned: %s. "
                            + "Please narrow your filter to get applicable results.",
                    maximumValues, warning.toString())));
        }

        if (warningJson.size() > 0) {
            outliersJson.add("warnings", warningJson);
        }
    }

    json.add("outliers", outliersJson);

    return new HttpEntity<>(json.toString());
}

From source file:spade.storage.CDM.java

/**
 * Converts the given time (in seconds) to nanoseconds
 * /*from www. j a  v a 2  s  .c o  m*/
 * If failed to convert the given time for any reason then the default value is
 * returned.
 * 
 * @param eventId id of the event
 * @param time timestamp in seconds
 * @param defaultValue default value
 * @return the time in nanoseconds
 */
private Long convertTimeToNanoseconds(Long eventId, String time, Long defaultValue) {
    try {
        if (time == null) {
            return defaultValue;
        }
        Double timeNanosecondsDouble = Double.parseDouble(time) * 1000; // Going to convert to long so multiply before
        Long timeNanosecondsLong = timeNanosecondsDouble.longValue();
        timeNanosecondsLong = timeNanosecondsLong * 1000 * 1000; //converting milliseconds to nanoseconds
        return timeNanosecondsLong;
    } catch (Exception e) {
        logger.log(Level.INFO, "Time type is not Double: {0}. event id = {1}", new Object[] { time, eventId });
        return defaultValue;
    }
}

From source file:com.comcast.cqs.persistence.RedisSortedSetPersistence.java

public List<String> getIdsFromHead(String queueUrl, int shard, String previousReceiptHandle,
        String nextReceiptHandle, int num) throws PersistenceException {

    if (previousReceiptHandle != null && Util.getShardFromReceiptHandle(previousReceiptHandle) != shard) {
        logger.warn("event=inconsistent_shard_information shard=" + shard + " receipt_handle="
                + previousReceiptHandle);
    }//from w  w w .  j ava 2s.  com

    boolean cacheAvailable = checkCacheConsistency(queueUrl, shard, true);

    if (!cacheAvailable) {
        return Collections.emptyList();
    }

    CQSQueue queue = null;
    int retention;
    try {
        queue = CQSCache.getCachedQueue(queueUrl);
        if (queue != null) {
            retention = queue.getMsgRetentionPeriod();
        } else {
            retention = CMBProperties.getInstance().getCQSMessageRetentionPeriod();
        }
    } catch (Exception e) {
        throw new PersistenceException(e);
    }

    List<String> memIdsRet = new LinkedList<String>();
    Set<String> memIds = null;
    boolean brokenJedis = false;
    ShardedJedis jedis = null;

    try {

        jedis = getResource();
        String key = queueUrl + "-" + shard + "-Q";

        long llen = jedis.zcount(key, System.currentTimeMillis() - retention * 1000L,
                System.currentTimeMillis());

        if (llen == 0L) {
            return Collections.emptyList();
        }

        //if no previousReceiptHandle and no nextReceiptHandle, just retrieve from beginning
        if (previousReceiptHandle == null && nextReceiptHandle == null) {
            memIds = jedis.zrangeByScore(key, System.currentTimeMillis() - retention * 1000L,
                    System.currentTimeMillis(), 0, num);
            if (memIds != null) {
                memIdsRet = new ArrayList<String>(memIds);
            }
        }
        //else find the score for previous receipt,
        //    if not exist, same as no previous receipt
        //    else use zrangeByScore with limit
        else if (previousReceiptHandle != null) {
            Double previousScore = jedis.zscore(key, previousReceiptHandle);
            if (previousScore == null) {
                memIds = jedis.zrangeByScore(key, System.currentTimeMillis() - retention * 1000L,
                        System.currentTimeMillis(), 0, num);
                if (memIds != null) {
                    memIdsRet = new ArrayList<String>(memIds);
                }
            } else {

                long startTime = previousScore.longValue();
                if (startTime < System.currentTimeMillis() - retention * 1000L) {
                    startTime = System.currentTimeMillis() - retention * 1000L;
                }

                int retCount = 0;
                int i = 0;
                boolean includeSet = (previousReceiptHandle == null) ? true : false;

                while (retCount < num && i < llen) {

                    memIds = jedis.zrangeByScore(key, startTime, System.currentTimeMillis(), i, num);

                    if (memIds.size() == 0) {
                        break; // done
                    }

                    i += num; // next time, exclude the last one in this set

                    for (String memId : memIds) {
                        if (!includeSet) {
                            if (memId.equals(previousReceiptHandle)) {
                                includeSet = true;
                                //skip over this one since it was the last el of the last call
                            }
                        } else {
                            memIdsRet.add(memId);
                            retCount++;
                            if (retCount >= num) {
                                break; //done
                            }
                        }
                    }
                }
            }
        } else { //this means previousReceiptHandle == null and nextReceiptHandle != null. Retrieve id backward
            //return result will exclude the nextReceiptHandle
            //retrieve nextReceiptHandle, get index. if not exist, retrieve from beginning.
            Long endRank = jedis.zrank(key, nextReceiptHandle);
            if (endRank == null) {
                memIds = jedis.zrangeByScore(key, System.currentTimeMillis() - retention * 1000L,
                        System.currentTimeMillis(), 0, num);
                if (memIds != null) {
                    memIdsRet = new ArrayList<String>(memIds);
                }
            }
            //if index exist, retrieve based on index. When get result, remove expired id
            else {
                long startIndex = endRank - num;
                if (startIndex < 0) {
                    startIndex = 0;
                }
                Set<Tuple> memIdWithScores = jedis.zrangeWithScores(key, startIndex, endRank);
                long expiredTime = System.currentTimeMillis() - retention * 1000L;
                for (Tuple t : memIdWithScores) {
                    if (t.getScore() < expiredTime || t.getElement().equals(nextReceiptHandle)) {
                        continue;
                    } else {
                        memIdsRet.add(t.getElement());
                    }
                }
            }
        }
    } catch (JedisException e) {
        brokenJedis = true;
        throw e;
    } finally {
        if (jedis != null) {
            returnResource(jedis, brokenJedis);
        }
    }
    return memIdsRet;
}

From source file:com.flowzr.activity.Report2DChartActivity.java

/**
 * Fill statistics panel based on report data
 *//*from  w  w w  .  j a  v  a  2 s .c  o m*/
private void fillStatistics() {
    boolean considerNull = MyPreferences.considerNullResultsInReport(this.getActivity());
    Double max;
    Double min;
    Double mean;
    Double sum = new Double(reportData.getDataBuilder().getSum());
    if (considerNull) {
        max = new Double(reportData.getDataBuilder().getMaxValue());
        min = new Double(reportData.getDataBuilder().getMinValue());
        mean = new Double(reportData.getDataBuilder().getMean());
        if ((min * max >= 0)) {
            // absolute calculation (all points over the x axis)
            max = new Double(reportData.getDataBuilder().getAbsoluteMaxValue());
            min = new Double(reportData.getDataBuilder().getAbsoluteMinValue());
            mean = Math.abs(mean);
            sum = Math.abs(sum);
        }
    } else {
        // exclude impact of null values in statistics
        max = new Double(reportData.getDataBuilder().getMaxExcludingNulls());
        min = new Double(reportData.getDataBuilder().getMinExcludingNulls());
        mean = new Double(reportData.getDataBuilder().getMeanExcludingNulls());
        if ((min * max >= 0)) {
            // absolute calculation (all points over the x axis)
            max = new Double(reportData.getDataBuilder().getAbsoluteMaxExcludingNulls());
            min = new Double(reportData.getDataBuilder().getAbsoluteMinExcludingNulls());
            mean = Math.abs(mean);
            sum = Math.abs(sum);
        }
    }
    // chart limits
    ((TextView) getView().findViewById(R.id.report_max_result))
            .setText(Utils.amountToString(reportData.getCurrency(), max.longValue()));
    ((TextView) getView().findViewById(R.id.report_min_result))
            .setText(Utils.amountToString(reportData.getCurrency(), min.longValue()));
    // sum and mean
    ((TextView) getView().findViewById(R.id.report_mean_result))
            .setText(Utils.amountToString(reportData.getCurrency(), mean.longValue()));
    ((TextView) getView().findViewById(R.id.report_mean_result)).setTextColor(Report2DChartView.meanColor);
    //((TextView)getView().findViewById(R.id.report_sum_result)).setText(Utils.amountToString(reportData.getCurrency(), sum.longValue()));
}

From source file:io.hummer.util.test.GenericTestResult.java

public String getPlottableAverages(List<?> levels, String[] xValueNames, String indexColumn, ResultType type,
        String... additionalCommands) {
    StringBuilder b = new StringBuilder();
    NumberFormat f = NumberFormat.getInstance(Locale.US);
    f.setMinimumFractionDigits(3);/*from www .ja  v a 2 s .  c om*/
    f.setMaximumFractionDigits(3);
    f.setGroupingUsed(false);

    List<String> commandsList = Arrays.asList(additionalCommands);

    for (int i = 0; i < levels.size(); i++) {
        String index = "" + levels.get(i);
        if (indexColumn != null) {
            index = "" + getMean(indexColumn.replaceAll("<level>", "" + levels.get(i)));
        }

        int modulo = commandsList.contains(CMD_ONLY_EVERY_2ND_XTICS) ? 2
                : commandsList.contains(CMD_ONLY_EVERY_3RD_XTICS) ? 3 : 1;
        if (i % modulo == 0) {
            b.append(index);
        } else {
            b.append("_");
        }

        for (int j = 0; j < xValueNames.length; j++) {
            b.append("\t");
            String nameString = xValueNames[j];
            nameString = nameString.replaceAll("<level>", "" + levels.get(i));
            if (nameString.equals(xValueNames[j]))
                nameString = nameString + levels.get(i);

            String[] actualNames = nameString.split(":");
            for (String name : actualNames) {

                Double theValue = 0.0;
                if (name.endsWith(".min")) {

                    theValue = getMinimum(name.substring(0, name.length() - ".min".length()));

                } else if (name.endsWith(".max")) {

                    theValue = getMaximum(name.substring(0, name.length() - ".max".length()));

                } else {
                    List<Double> values = getValues(name);
                    if (type == ResultType.MEAN) {
                        Number mean = getMean(values);
                        theValue = mean.doubleValue();
                    } else if (type == ResultType.THROUGHPUT) {
                        theValue = getThroughput(name);
                    }
                    if (values.size() <= 0) {
                        theValue = Double.NaN;
                    }
                }
                if (theValue > 1000000) {
                    b.append(theValue.longValue());
                } else {
                    String val = f.format(theValue);
                    if ((theValue).isNaN()) {
                        //val = "0";
                        val = "NaN";
                    }
                    while (val.length() < 10)
                        val = " " + val;
                    b.append(val);
                }

            }

        }
        b.append("\n");
    }
    return b.toString();
}