Example usage for java.lang Double intValue

List of usage examples for java.lang Double intValue

Introduction

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

Prototype

public int intValue() 

Source Link

Document

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

Usage

From source file:org.apache.synapse.mediators.eip.aggregator.AggregateMediator.java

/**
 * Aggregate messages flowing through this mediator according to the correlation criteria
 * and the aggregation algorithm specified to it
 *
 * @param synCtx - MessageContext to be mediated and aggregated
 * @return boolean true if the complete condition for the particular aggregate is validated
 *//*from w  w w .  j av  a2 s . co m*/
public boolean mediate(MessageContext synCtx) {

    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : Aggregate mediator");

        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }

    try {
        Aggregate aggregate = null;
        String correlationIdName = (id != null ? EIPConstants.AGGREGATE_CORRELATION + "." + id
                : EIPConstants.AGGREGATE_CORRELATION);
        // if a correlateExpression is provided and there is a coresponding
        // element in the current message prepare to correlate the messages on that
        Object result = null;
        if (correlateExpression != null) {
            result = correlateExpression.evaluate(synCtx);
            if (result instanceof List) {
                if (((List) result).isEmpty()) {
                    handleException(
                            "Failed to evaluate correlate expression: " + correlateExpression.toString(),
                            synCtx);
                }
            }
        }
        if (result != null) {

            while (aggregate == null) {

                synchronized (lock) {

                    if (activeAggregates.containsKey(correlateExpression.toString())) {

                        aggregate = activeAggregates.get(correlateExpression.toString());
                        if (aggregate != null) {
                            if (!aggregate.getLock()) {
                                aggregate = null;
                            }
                        }

                    } else {

                        if (synLog.isTraceOrDebugEnabled()) {
                            synLog.traceOrDebug("Creating new Aggregator - " + (completionTimeoutMillis > 0
                                    ? "expires in : " + (completionTimeoutMillis / 1000) + "secs"
                                    : "without expiry time"));
                        }

                        Double minMsg = Double.parseDouble(minMessagesToComplete.evaluateValue(synCtx));
                        Double maxMsg = Double.parseDouble(maxMessagesToComplete.evaluateValue(synCtx));

                        aggregate = new Aggregate(synCtx.getEnvironment(), correlateExpression.toString(),
                                completionTimeoutMillis, minMsg.intValue(), maxMsg.intValue(), this);

                        if (completionTimeoutMillis > 0) {
                            synCtx.getConfiguration().getSynapseTimer().schedule(aggregate,
                                    completionTimeoutMillis);
                        }
                        aggregate.getLock();
                        activeAggregates.put(correlateExpression.toString(), aggregate);
                    }
                }
            }

        } else if (synCtx.getProperty(correlationIdName) != null) {
            // if the correlattion cannot be found using the correlateExpression then
            // try the default which is through the AGGREGATE_CORRELATION message property
            // which is the unique original message id of a split or iterate operation and
            // which thus can be used to uniquely group messages into aggregates

            Object o = synCtx.getProperty(correlationIdName);
            String correlation;

            if (o != null && o instanceof String) {
                correlation = (String) o;
                while (aggregate == null) {
                    synchronized (lock) {
                        if (activeAggregates.containsKey(correlation)) {
                            aggregate = activeAggregates.get(correlation);
                            if (aggregate != null) {
                                if (!aggregate.getLock()) {
                                    aggregate = null;
                                }
                            } else {
                                break;
                            }
                        } else {
                            if (synLog.isTraceOrDebugEnabled()) {
                                synLog.traceOrDebug("Creating new Aggregator - " + (completionTimeoutMillis > 0
                                        ? "expires in : " + (completionTimeoutMillis / 1000) + "secs"
                                        : "without expiry time"));
                            }

                            Double minMsg = -1.0;
                            if (minMessagesToComplete != null) {
                                minMsg = Double.parseDouble(minMessagesToComplete.evaluateValue(synCtx));
                            }
                            Double maxMsg = -1.0;
                            if (maxMessagesToComplete != null) {
                                maxMsg = Double.parseDouble(maxMessagesToComplete.evaluateValue(synCtx));
                            }

                            aggregate = new Aggregate(synCtx.getEnvironment(), correlation,
                                    completionTimeoutMillis, minMsg.intValue(), maxMsg.intValue(), this);

                            if (completionTimeoutMillis > 0) {
                                synchronized (aggregate) {
                                    if (!aggregate.isCompleted()) {
                                        synCtx.getConfiguration().getSynapseTimer().schedule(aggregate,
                                                completionTimeoutMillis);
                                    }
                                }
                            }
                            aggregate.getLock();
                            activeAggregates.put(correlation, aggregate);
                        }
                    }
                }

            } else {
                synLog.traceOrDebug("Unable to find aggrgation correlation property");
                return true;
            }
        } else {
            synLog.traceOrDebug("Unable to find aggrgation correlation XPath or property");
            return true;
        }

        // if there is an aggregate continue on aggregation
        if (aggregate != null) {
            //this is a temporary fix              
            synCtx.getEnvelope().build();
            boolean collected = aggregate.addMessage(synCtx);
            if (synLog.isTraceOrDebugEnabled()) {
                if (collected) {
                    synLog.traceOrDebug("Collected a message during aggregation");
                    if (synLog.isTraceTraceEnabled()) {
                        synLog.traceTrace("Collected message : " + synCtx);
                    }
                }
            }

            // check the completeness of the aggregate and if completed aggregate the messages
            // if not completed return false and block the message sequence till it completes

            if (aggregate.isComplete(synLog)) {
                synLog.traceOrDebug("Aggregation completed - invoking onComplete");
                boolean onCompleteSeqResult = completeAggregate(aggregate);

                synLog.traceOrDebug("End : Aggregate mediator");
                return onCompleteSeqResult;
            } else {
                aggregate.releaseLock();
            }

        } else {
            // if the aggregation correlation cannot be found then continue the message on the
            // normal path by returning true

            synLog.traceOrDebug("Unable to find an aggregate for this message - skip");
            return true;
        }

    } catch (JaxenException e) {
        handleException("Unable to execute the XPATH over the message", e, synCtx);
    }

    synLog.traceOrDebug("End : Aggregate mediator");

    // When Aggregation is not completed return false to hold the flow
    return false;
}

From source file:gov.nasa.arc.spife.core.plan.advisor.resources.ProfileConstraintPlanAdvisor.java

private Object parseValue(Profile profile, String valueLiteral) throws ParseException {
    Object value = null;/*from  w  w w  .  j a va2  s . c om*/
    if (valueLiteral == null) {
        return null;
    } else {
        EDataType dataType = profile.getDataType();
        try {
            if (dataType != null) {
                EPackage ePackage = dataType.getEPackage();
                EFactory eFactory = ePackage.getEFactoryInstance();
                value = eFactory.createFromString(dataType, valueLiteral);
            }
        } catch (Exception x) {
            if (EcorePackage.Literals.EINT == dataType || EcorePackage.Literals.EINTEGER_OBJECT == dataType) {
                try {
                    Double doubleValue = Double.parseDouble(valueLiteral);
                    int intValue = doubleValue.intValue();
                    if (doubleValue == intValue) {
                        return intValue;
                    }
                } catch (Exception e) {
                    // tried to parse double as an integer
                }
            }
        }
        if (value == null) {
            throw new ParseException("Cannot parse " + valueLiteral, 0);
        }
    }
    return value;
}

From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java

public Resolution directRequest() throws UnsupportedEncodingException, URISyntaxException, URIException,
        IOException, SAXException, ParserConfigurationException {
    Double x1 = x - offset;
    Double y1 = y - offset;/* ww  w .  j a  v  a2  s. c o m*/
    Double x2 = x + offset;
    Double y2 = y + offset;
    final String username = "B3_develop";
    final String password = "8ndj39";
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

    Coordinate coord = new Coordinate(x, y);
    Point point = geometryFactory.createPoint(coord);

    URL url2 = new URL(
            "https://atlas.cyclomedia.com/recordings/wfs?service=WFS&VERSION=1.1.0&maxFeatures=100&request=GetFeature&SRSNAME=EPSG:28992&typename=atlas:Recording"
                    + "&filter=<Filter><And><BBOX><gml:Envelope%20srsName=%27EPSG:28992%27>"
                    + "<gml:lowerCorner>" + x1.intValue() + "%20" + y1.intValue() + "</gml:lowerCorner>"
                    + "<gml:upperCorner>" + x2.intValue() + "%20" + y2.intValue()
                    + "</gml:upperCorner></gml:Envelope></BBOX><ogc:PropertyIsNull><ogc:PropertyName>expiredAt</ogc:PropertyName></ogc:PropertyIsNull></And></Filter>");

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });
    InputStream is = url2.openStream();

    // wrap the urlconnection in a bufferedreader
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

    String line;

    StringBuilder content = new StringBuilder();
    // read from the urlconnection via the bufferedreader
    while ((line = bufferedReader.readLine()) != null) {
        content.append(line + "\n");
    }
    bufferedReader.close();

    String s = content.toString();
    String tsString = "timeStamp=";
    int indexOfTimestamp = s.indexOf(tsString);
    int indexOfLastQuote = s.indexOf("\"", indexOfTimestamp + 2 + tsString.length());
    String contentString = s.substring(0, indexOfTimestamp - 2);
    contentString += s.substring(indexOfLastQuote);

    contentString = removeDates(contentString, "<atlas:recordedAt>", "</atlas:recordedAt>");

    Configuration configuration = new org.geotools.gml3.GMLConfiguration();
    configuration.getContext().registerComponentInstance(new GeometryFactory(new PrecisionModel(), 28992));

    Parser parser = new Parser(configuration);
    parser.setValidating(false);
    parser.setStrict(false);
    parser.setFailOnValidationError(false);

    ByteArrayInputStream bais = new ByteArrayInputStream(contentString.getBytes());
    Object obj = parser.parse(bais);

    SimpleFeatureCollection fc = (SimpleFeatureCollection) obj;

    SimpleFeatureIterator it = fc.features();
    SimpleFeature sf = null;
    List<SimpleFeature> fs = new ArrayList<SimpleFeature>();
    while (it.hasNext()) {
        sf = it.next();
        sf.getUserData().put(DISTANCE_KEY, point.distance((Geometry) sf.getDefaultGeometry()));
        fs.add(sf);
    }
    Collections.sort(fs, new Comparator<SimpleFeature>() {
        @Override
        public int compare(SimpleFeature o1, SimpleFeature o2) {
            Double d1 = (Double) o1.getUserData().get(DISTANCE_KEY);
            Double d2 = (Double) o2.getUserData().get(DISTANCE_KEY);
            return d1.compareTo(d2);
        }
    });
    SimpleFeature f = fs.get(0);
    imageId = (String) f.getAttribute("imageId");
    sign();
    return new ForwardResolution("/WEB-INF/jsp/app/globespotter.jsp");
}

From source file:com.wcna.calms.jpos.services.quote.JPOSQuickQuoteLoadService.java

private IJPOSApplicationAssetDataVO loadAssetSubProcess(IJPOSApplicationAssetDataVO assetDataVo, String appId,
        Map<String, Object> loadMap) {

    List<IRentACarBean> rentACarList = null;
    IJPOSQuickQuoteAssetInputForm assetForm = null;
    int modelVariantId = 0;
    if (!StringUtil.isEmpty(appId)) {
        Locale locale = getUserContainer().getLocale();
        assetDataVo = quickQuoteService.loadAsset(Long.valueOf(appId), locale, false);
        rentACarList = quickQuoteService.getRentACarList(Long.valueOf(appId));

        assetForm = new JPOSQuickQuoteAssetVO();
        if (assetDataVo != null) {
            JPOSQuickQuoteAssetVO screenVo = new JPOSQuickQuoteAssetVO();
            screenVo.setNewUsed(assetDataVo.getNewOrUsed());
            screenVo.setRegistrationCode(assetDataVo.getRegPlateId());
            screenVo.setFreeFormatFlag(assetDataVo.getFreeFormatFlag());
            screenVo.setMakeId(assetDataVo.getMakeId());
            screenVo.setModelId(assetDataVo.getModelId());
            screenVo.setModelVariantId(assetDataVo.getModelVariantId());

            if (!"on".equals(screenVo.getFreeFormatFlag())) {
                if (!StringUtil.isEmpty(screenVo.getModelVariantId())) {
                    modelVariantId = formatService.parseInteger(screenVo.getModelVariantId(), locale, false, 0);
                }//from  ww w. ja  va  2s  .c  o  m
            } else {
                if (!IClientConstants.EXECUTE.equals(projectProperties
                        .getProperty(IClientConstants.ONCHANGE_FFE_CHKBOX_IMPL_DISABLE_MAKE_TOGGLE))) {
                    screenVo.setMakeId(assetDataVo.getMakeDesc());
                }
                screenVo.setModelId(assetDataVo.getModelDesc());
                screenVo.setModelVariantId(assetDataVo.getModelVariantDesc());
            }

            screenVo.setTaxIncludingFlag(assetDataVo.getIsTaxable());
            screenVo.setRegistrationNumber(assetDataVo.getRegistrationNumber());
            Date d = assetDataVo.getRegistrationDate();
            if (d != null) {
                screenVo.setRegistrationDate(formatService.formatDate(d, locale));
            }

            screenVo.setAssetType(assetDataVo.getAssetType());

            Double meter = assetDataVo.getMeterValue();
            if (meter == null) {
                meter = new Double(0);
            }
            screenVo.setKilometrage(formatService.formatInteger(meter.intValue(), locale));
            screenVo.setVin(assetDataVo.getVin());

            screenVo.setManufactureDate(formatService.formatDate(assetDataVo.getManufactureDate(), locale));
            screenVo.setMortgageRegDate(formatService.formatDate(assetDataVo.getMortgageRegDate(), locale));

            screenVo.setAssetUsageCode(assetDataVo.getAssetUsageCode());
            screenVo.setApprovedUsedAssetCode(assetDataVo.getApprovedUsedAssetCode());
            screenVo.setEnviroImpactRatingCode(assetDataVo.getEnviroImpactRatingCode());
            screenVo.setEnviroImpactRatingAmount(
                    formatService.formatDouble(assetDataVo.getEnviroImpactRatingAmount(), locale));
            screenVo.setTaxHorsePowerRating(
                    formatService.formatDouble(assetDataVo.getTaxHorsePowerRating(), locale));

            screenVo.setSalePrice(formatService.formatDouble(assetDataVo.getSalePrice(), locale));
            screenVo.setTaxCode(assetDataVo.getTaxCode());
            screenVo.setTaxAmt(formatService.formatDouble(assetDataVo.getTaxAmt(), locale));
            screenVo.setGrossCost(formatService.formatDouble(assetDataVo.getGrossCost(), locale));

            screenVo.setExtraAmt(formatService.formatDouble(assetDataVo.getExtraAmount(), locale));
            screenVo.setExtraTaxCode(assetDataVo.getExtraTaxCode());
            screenVo.setExtraTaxAmt(formatService.formatDouble(assetDataVo.getExtraTaxAmount(), locale));
            screenVo.setExtraTotalCost(assetDataVo.getExtraTotalCost());

            screenVo.setTaxableDFOptionsGross(assetDataVo.getTaxableDFOptionsGross());
            screenVo.setTaxableDFOptionsNet(assetDataVo.getTaxableDFOptionsNet());
            String defaultZero = formatService.formatDouble(0d, locale);
            // this is to avoid validation issues if this is a rent-a-car deal
            if (StringUtils.isBlank(screenVo.getTaxableDFOptionsNet())) {
                screenVo.setTaxableDFOptionsNet(defaultZero);
            }
            if (StringUtils.isBlank(screenVo.getTaxableDFOptionsGross())) {
                screenVo.setTaxableDFOptionsGross(defaultZero);
            }

            screenVo.setTaxableDFOptionsVatAmt(assetDataVo.getTaxableDFOptionsVatAmt());
            screenVo.setTaxableDFOptionsVatRate(assetDataVo.getTaxableDFOptionsVatRate());

            screenVo.setNonTaxableDFOptionsGross(assetDataVo.getNonTaxableDFOptionsGross());
            screenVo.setNonTaxableDFOptionsNet(assetDataVo.getNonTaxableDFOptionsNet());
            if (StringUtils.isBlank(screenVo.getNonTaxableDFOptionsNet())) {
                screenVo.setNonTaxableDFOptionsNet(defaultZero);
            }
            if (StringUtils.isBlank(screenVo.getNonTaxableDFOptionsGross())) {
                screenVo.setNonTaxableDFOptionsGross(defaultZero);
            }

            screenVo.setNonTaxableDFOptionsVatAmt(assetDataVo.getNonTaxableDFOptionsVatAmt());
            screenVo.setNonTaxableDFOptionsVatRate(assetDataVo.getNonTaxableDFOptionsVatRate());

            screenVo.setRoadFundLicenseGross(assetDataVo.getRoadFundLicenseGross());
            screenVo.setRoadFundLicenseNet(assetDataVo.getRoadFundLicenseNet());
            screenVo.setRoadFundLicenseVatAmt(assetDataVo.getRoadFundLicenseVatAmt());
            screenVo.setRoadFundLicenseVatRate(assetDataVo.getRoadFundLicenseVatRate());

            screenVo.setFirstRegistrationGross(assetDataVo.getFirstRegistrationGross());
            screenVo.setFirstRegistrationNet(assetDataVo.getFirstRegistrationNet());
            screenVo.setFirstRegistrationVatAmt(assetDataVo.getFirstRegistrationVatAmt());
            screenVo.setFirstRegistrationVatRate(assetDataVo.getFirstRegistrationVatRate());

            screenVo.setTotalNet(assetDataVo.getTotalNet());
            screenVo.setTotalGross(formatService.formatDouble(assetDataVo.getTotalCost(), locale));
            screenVo.setTotalVatAmt(formatService.formatDouble(assetDataVo.getTotalVat(), locale));

            screenVo.setDiscountNet(assetDataVo.getDiscountNet());
            screenVo.setDiscountVatRate(assetDataVo.getDiscountVatRate());
            screenVo.setDiscountVatAmt(assetDataVo.getDiscountVatAmt());
            screenVo.setDiscountGross(assetDataVo.getDiscountGross());

            if (IConstants.FLAG_YES.equals(assetDataVo.getDiscountAmtIsPct())) {
                screenVo.setDiscountAmtIsPct(IConstants.FLAG_YES);
            } else {
                screenVo.setDiscountAmtIsPct("");
            }

            if (assetDataVo.getDiscountAmt() != null) {
                screenVo.setDiscountAmt(assetDataVo.getDiscountAmt());
            } else {
                screenVo.setDiscountAmt("");
            }

            if (assetDataVo.getDiscountPct() != null) {
                screenVo.setDiscountPct(assetDataVo.getDiscountPct());
            } else {
                screenVo.setDiscountPct("");
            }

            screenVo.setTaxPointDate(formatService.formatDate(assetDataVo.getTaxPointDate(), locale));
            screenVo.setTaxRateValue(formatService.formatDouble(assetDataVo.getTaxRateValue(), locale));

            // tfs demo
            screenVo.setLctSummary(formatService.formatDouble(assetDataVo.getLctSummary(), locale));
            screenVo.setGstSummary(formatService.formatDouble(assetDataVo.getGstSummary(), locale));
            screenVo.setLct(assetDataVo.getLct());
            if (StringUtils.isBlank(screenVo.getLct())) {
                screenVo.setLct(IJPOSQuickQuoteConstants.LCT_NONE);
            }
            // end tfs demo

            loadMap.put("assetDetails", screenVo);
            loadMap.put("vehicleOutline", quickQuoteService.getVehicleDescription(Long.valueOf(appId)));

            loadMap.put("rentACarList", rentACarList);

            List<IVehicleFFOBean> ffoList = assetDataVo.getFfoList();
            if (ffoList == null) {
                ffoList = new ArrayList<IVehicleFFOBean>();
            }
            loadMap.put("ffoList", ffoList);
            screenVo.setTotalRvUpliftPercentage(assetDataVo.getTotalRvUpliftPercentage());

            BeanUtils.copyProperties(screenVo, assetForm);
        }

        IAssetPartExchangeVO assetPartExchangeVO = (assetDataVo.getAssetPartExchange() == null)
                ? quickQuoteService.getDefaultPartExchange()
                : assetDataVo.getAssetPartExchange();
        this.quickQuoteService.setAssetDetailsToContainer(0, assetForm, assetDataVo.getFfoList(), rentACarList,
                assetPartExchangeVO);

    }
    return assetDataVo;
}

From source file:com.entertailion.java.caster.RampClient.java

public void onMessage(String message) {
    Log.d(LOG_TAG, "onMessage: message" + message);

    // http://code.google.com/p/json-simple/
    JSONParser parser = new JSONParser();
    try {//  w  w w. j a v  a2s.co m
        Object obj = parser.parse(new StringReader(message));
        JSONArray array = (JSONArray) obj;
        if (array.get(0).equals(PROTOCOL_CM)) {
            Log.d(LOG_TAG, PROTOCOL_CM);
            JSONObject body = (JSONObject) array.get(1);
            // ["cm",{"type":"ping"}]
            if (body.get(TYPE).equals(PING)) {
                rampWebSocketClient.send("[\"cm\",{\"type\":\"pong\"}]");
            }
        } else if (array.get(0).equals(PROTOCOL_RAMP)) {
            // ["ramp",{"cmd_id":0,"type":"STATUS","status":{"event_sequence":2,"state":0}}]
            Log.d(LOG_TAG, PROTOCOL_RAMP);
            JSONObject body = (JSONObject) array.get(1);
            if (body.get(TYPE).equals(STATUS)) {
                // Long cmd_id = (Long)body.get("cmd_id");
                // commandId = cmd_id.intValue();
                if (!gotStatus) {
                    gotStatus = true;
                    // rampWebSocketClient.send("[\"ramp\",{\"type\":\"LOAD\",\"cmd_id\":"+commandId+",\"autoplay\":true}] ");
                    // commandId++;
                }
            } else if (body.get(TYPE).equals(RESPONSE)) {
                // ["ramp",{"cmd_id":7,"type":"RESPONSE","status":{"event_sequence":38,"state":2,"content_id":"http://192.168.0.50:8080/video.mp4","current_time":6.465110778808594,
                // "duration":27.37066650390625,"volume":1,"muted":false,"time_progress":true,"title":"Video"}}]
                JSONObject status = (JSONObject) body.get(RESPONSE_STATUS);
                if (status.get(RESPONSE_CURRENT_TIME) instanceof Double) {
                    Double current_time = (Double) status.get(RESPONSE_CURRENT_TIME);
                    if (current_time != null) {
                        if (playbackListener != null) {
                            playbackListener.updateTime(playback, current_time.intValue());
                        }
                    }
                } else {
                    Long current_time = (Long) status.get(RESPONSE_CURRENT_TIME);
                    if (current_time != null) {
                        if (playbackListener != null) {
                            playbackListener.updateTime(playback, current_time.intValue());
                        }
                    }
                }
                if (status.get(RESPONSE_DURATION) instanceof Double) {
                    Double duration = (Double) status.get(RESPONSE_DURATION);
                    if (duration != null) {
                        if (playbackListener != null) {
                            playbackListener.updateDuration(playback, duration.intValue());
                        }
                    }
                } else {
                    Long duration = (Long) status.get(RESPONSE_DURATION);
                    if (duration != null) {
                        if (playbackListener != null) {
                            playbackListener.updateDuration(playback, duration.intValue());
                        }
                    }
                }
                Long state = (Long) status.get(RESPONSE_STATE);
                if (playbackListener != null) {
                    playbackListener.updateState(playback, state.intValue());
                }
            }
        } else if (array.get(0).equals(PROTOCOL_CV)) { // ChromeCast default
            // receiver events
            Log.d(LOG_TAG, PROTOCOL_CV);
            JSONObject body = (JSONObject) array.get(1);
            if (body.get(TYPE).equals(ACTIVITY)) {
                // ["cv",{"type":"activity","message":{"type":"timeupdate","activityId":"d82cede3-ec23-4f73-8abc-343dd9ca6dbb","state":{"mediaUrl":"http://192.168.0.50:8087/cast.webm","videoUrl":"http://192.168.0.50:8087/cast.webm",
                // "currentTime":20.985000610351562,"duration":null,"pause":false,"muted":false,"volume":1,"paused":false}}}]
                JSONObject activityMessage = (JSONObject) body.get(ACTIVITY_MESSAGE);
                if (activityMessage != null) {
                    JSONObject activityMessageType = (JSONObject) activityMessage.get(TYPE);
                    if (activityMessageType.equals(ACTIVITY_TIME_UPDATE)) {
                        JSONObject activityMessageTypeState = (JSONObject) activityMessage.get(ACTIVITY_STATE);
                        if (activityMessageTypeState.get(RESPONSE_CURRENT_TIME) instanceof Double) {
                            Double current_time = (Double) activityMessageTypeState.get(ACTIVITY_CURRENT_TIME);
                            Double duration = (Double) activityMessageTypeState.get(ACTIVITY_DURATION);
                            if (duration != null) {
                                if (playbackListener != null) {
                                    playbackListener.updateDuration(playback, duration.intValue());
                                }
                            }
                            if (current_time != null) {
                                if (playbackListener != null) {
                                    playbackListener.updateTime(playback, current_time.intValue());
                                }
                            }
                        } else {
                            Long current_time = (Long) activityMessageTypeState.get(ACTIVITY_CURRENT_TIME);
                            Double duration = (Double) activityMessageTypeState.get(ACTIVITY_DURATION);
                            if (duration != null) {
                                if (playbackListener != null) {
                                    playbackListener.updateDuration(playback, duration.intValue());
                                }
                            }
                            if (current_time != null) {
                                if (playbackListener != null) {
                                    playbackListener.updateTime(playback, current_time.intValue());
                                }
                            }
                        }
                    }
                }

            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "parse JSON", e);
    }
}

From source file:ru.codeinside.gses.manager.ManagerService.java

public ProcedureProcessDefinition createProcessDefination(String procedureId,
        ProcessDefinition processDefinition, String login, String processDefId) {
    ProcedureProcessDefinition ppd = new ProcedureProcessDefinition();
    ProcedureProcessDefinition processDefenition = StringUtils.isEmpty(processDefId) ? null
            : getProcessDefenition(processDefId);
    if (StringUtils.isEmpty(processDefId)) {
        Double newVersion = 0.00;
        if (getProcessDefenitionCountByProcedureId(procedureId) > 0) {
            newVersion = em.createQuery(
                    "select max(s.version) from procedure_process_definition s where s.procedure.id=:procedureId",
                    Number.class).setParameter("procedureId", Long.parseLong(procedureId)).getSingleResult()
                    .doubleValue();//from  www  . j  ava  2s. c o m
        }
        ppd.setVersion(newVersion.intValue() + 1.00);
        ppd.setStatus(DefinitionStatus.Created);
    } else {
        Double version = (processDefenition == null || processDefenition.getVersion() == null) ? 1.00
                : processDefenition.getVersion();
        ppd.setVersion(version + 0.01);
        ppd.setStatus(DefinitionStatus.Debugging);
    }
    Procedure procedure = getProcedure(procedureId);

    ppd.setProcedure(procedure);
    ppd.setCreator(em.find(Employee.class, login));
    ppd.setProcessDefinitionId(processDefinition.getId());
    ppd.setProcessDefinitionKey(processDefinition.getKey());
    em.persist(ppd);

    if (!StringUtils.isEmpty(processDefId) && processDefenition != null) {
        processDefenition.setStatus(DefinitionStatus.Archive);
        processDefenition.setChild(ppd);
        em.persist(processDefenition);
    }
    updateProcedureStatusAndVersion(procedureId);
    return ppd;
}

From source file:com.ichorpowered.guardian.common.check.movement.InvalidCheck.java

@Nonnull
@Override/*w  w w. j a  v  a2 s.c  om*/
public SequenceBlueprint<Event> getSequence(final Detection detection) {
    final Double analysisTime = detection.getContentContainer().get(ContentKeys.ANALYSIS_TIME)
            .orElse(GuardianSingleValue.empty()).getElement().orElse(0d) / 0.05;

    final Double minimumTickRate = detection.getContentContainer().get(ContentKeys.ANALYSIS_MINIMUM_TICK)
            .orElse(GuardianSingleValue.empty()).getElement().orElse(0d) * analysisTime;

    final Double maximumTickRate = detection.getContentContainer().get(ContentKeys.ANALYSIS_MAXIMUM_TICK)
            .orElse(GuardianSingleValue.empty()).getElement().orElse(0d) * analysisTime;

    return new GuardianSequenceBuilder()

            .capture(new PlayerControlCapture.Invalid(detection.getPlugin(), detection))

            // Trigger : Move Entity Event

            .observe(MoveEntityEvent.class)

            // Analysis : Move Entity Event

            .observe(MoveEntityEvent.class).delay(analysisTime.intValue()).expire(maximumTickRate.intValue())

            // TODO: Permission check.

            .condition(sequenceContext -> {
                final GuardianPlayerEntry<Player> entityEntry = sequenceContext
                        .get(CommonContextKeys.ENTITY_ENTRY);
                final Summary summary = sequenceContext.get(CommonContextKeys.SUMMARY);
                final GuardianCaptureRegistry captureRegistry = sequenceContext
                        .get(CommonContextKeys.CAPTURE_REGISTRY);
                final long lastActionTime = sequenceContext.get(CommonContextKeys.LAST_ACTION_TIME);

                summary.set(SequenceReport.class, new SequenceReport(false,
                        Origin.source(sequenceContext.getRoot()).owner(entityEntry).build()));

                if (!entityEntry.getEntity(Player.class).isPresent())
                    return false;
                Player player = entityEntry.getEntity(Player.class).get();

                /*
                 * Capture Collection
                 */

                final CaptureContainer captureContainer = captureRegistry.getContainer();

                Optional<Location> initial = captureContainer.get(GuardianSequence.INITIAL_LOCATION);
                Optional<Set> invalidControls = captureContainer
                        .get(PlayerControlCapture.Invalid.INVALID_MOVEMENT);

                /*
                 * Analysis
                 */

                if (!initial.isPresent() || !invalidControls.isPresent())
                    return false;

                long current = System.currentTimeMillis();

                // Finds the average between now and the last action.
                double averageClockRate = ((current - lastActionTime) / 1000) / 0.05;

                if (averageClockRate < minimumTickRate) {
                    detection.getLogger().warn("The server may be overloaded. A check could not be completed.");
                    return false;
                } else if (averageClockRate > maximumTickRate) {
                    return false;
                }

                if (invalidControls.get().isEmpty())
                    return false;

                // ------------------------- DEBUG -----------------------------
                System.out.println(player.getName() + " has been caught using invalid movement hacks.");
                // -------------------------------------------------------------

                SequenceReport report = new SequenceReport(true,
                        Origin.source(sequenceContext.getRoot()).owner(entityEntry).build());
                report.put("type", "Invalid Movement");

                report.put("information", Collections.singletonList("Received invalid controls of "
                        + StringUtils.join((Set<String>) invalidControls.get(), ", ") + "."));

                report.put("initial_location", initial.get());
                report.put("final_location", player.getLocation());
                report.put("severity", 1d);

                summary.set(SequenceReport.class, report);

                return true;
            }, ConditionType.NORMAL)

            .build(SequenceContext.builder().owner(detection).root(this).build());
}

From source file:edu.hawaii.soest.hioos.isus.ISUSSource.java

/**
 * A method that processes the data object passed and flushes the
 * data to the DataTurbine given the sensor properties in the XMLConfiguration
 * passed in.//from   w  w w.  j av  a 2s  .  c  o m
 *
 * @param xmlConfig - the XMLConfiguration object containing the list of
 *                    sensor properties
 * @param frameMap  - the parsed data as a HierarchicalMap object
 */
public boolean process(XMLConfiguration xmlConfig, HierarchicalMap frameMap) {

    logger.debug("ISUSSource.process() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean success = false;

    try {

        // add channels of data that will be pushed to the server.  
        // Each sample will be sent to the Data Turbine as an rbnb frame.  Information
        // on each channel is found in the XMLConfiguration file (email.account.properties.xml)
        // and the StorXParser object (to get the data string)
        ChannelMap rbnbChannelMap = new ChannelMap(); // used to flush channels
        ChannelMap registerChannelMap = new ChannelMap(); // used to register channels
        int channelIndex = 0;

        String sensorName = null;
        String sensorSerialNumber = null;
        String sensorDescription = null;
        boolean isImmersed = false;
        String[] calibrationURLs = null;
        String calibrationURL = null;
        String type = null;

        List sensorList = xmlConfig.configurationsAt("account.logger.sensor");

        for (Iterator sIterator = sensorList.iterator(); sIterator.hasNext();) {
            //  
            HierarchicalConfiguration sensorConfig = (HierarchicalConfiguration) sIterator.next();
            sensorSerialNumber = sensorConfig.getString("serialNumber");

            // find the correct sensor configuration properties
            if (sensorSerialNumber.equals(frameMap.get("serialNumber"))) {

                sensorName = sensorConfig.getString("name");
                sensorDescription = sensorConfig.getString("description");
                isImmersed = new Boolean(sensorConfig.getString("isImmersed")).booleanValue();
                calibrationURLs = sensorConfig.getStringArray("calibrationURL");
                type = (String) frameMap.get("type");

                // find the correct calibrationURL from the list given the type
                for (String url : calibrationURLs) {

                    if (url.indexOf(type) > 0) {
                        calibrationURL = url;
                        break;

                    } else {
                        logger.debug("There was no match for " + type);
                    }
                }

                // get a Calibration instance to interpret raw sensor values
                Calibration calibration = new Calibration();

                if (calibration.parse(calibrationURL)) {

                    // Build the RBNB channel map 

                    // get the sample date and convert it to seconds since the epoch
                    Date frameDate = (Date) frameMap.get("date");
                    Calendar frameDateTime = Calendar.getInstance();
                    frameDateTime.setTime(frameDate);
                    double sampleTimeAsSecondsSinceEpoch = (double) (frameDateTime.getTimeInMillis() / 1000);
                    // and create a string formatted date for the given time zone
                    DATE_FORMAT.setTimeZone(TZ);
                    String frameDateAsString = DATE_FORMAT.format(frameDate).toString();

                    // get the sample data from the frame map
                    ByteBuffer rawFrame = (ByteBuffer) frameMap.get("rawFrame");
                    ISUSFrame isusFrame = (ISUSFrame) frameMap.get("parsedFrameObject");
                    String serialNumber = isusFrame.getSerialNumber();
                    String sampleDate = isusFrame.getSampleDate();
                    String sampleTime = isusFrame.getSampleTime();
                    SimpleDateFormat dtFormat = new SimpleDateFormat();
                    Date sampleDateTime = isusFrame.getSampleDateTime();
                    dtFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                    dtFormat.applyPattern("MM/dd/yy");
                    String sampleDateUTC = dtFormat.format(sampleDateTime);
                    dtFormat.applyPattern("HH:mm:ss");
                    String sampleTimeUTC = dtFormat.format(sampleDateTime);
                    dtFormat.setTimeZone(TimeZone.getTimeZone("HST"));
                    dtFormat.applyPattern("MM/dd/yy");
                    String sampleDateHST = dtFormat.format(sampleDateTime);
                    dtFormat.applyPattern("HH:mm:ss");
                    String sampleTimeHST = dtFormat.format(sampleDateTime);
                    dtFormat.applyPattern("dd-MMM-yy HH:mm");
                    String sampleDateTimeHST = dtFormat.format(sampleDateTime);

                    double rawNitrogenConcentration = isusFrame.getNitrogenConcentration();
                    double rawAuxConcentration1 = isusFrame.getAuxConcentration1();
                    double rawAuxConcentration2 = isusFrame.getAuxConcentration2();
                    double rawAuxConcentration3 = isusFrame.getAuxConcentration3();
                    double rawRmsError = isusFrame.getRmsError();
                    double rawInsideTemperature = isusFrame.getInsideTemperature();
                    double rawSpectrometerTemperature = isusFrame.getSpectrometerTemperature();
                    double rawLampTemperature = isusFrame.getLampTemperature();
                    int rawLampTime = isusFrame.getLampTime();
                    double rawHumidity = isusFrame.getHumidity();
                    double rawLampVoltage12 = isusFrame.getLampVoltage12();
                    double rawInternalPowerVoltage5 = isusFrame.getInternalPowerVoltage5();
                    double rawMainPowerVoltage = isusFrame.getMainPowerVoltage();
                    double rawReferenceAverage = isusFrame.getReferenceAverage();
                    double rawReferenceVariance = isusFrame.getReferenceVariance();
                    double rawSeaWaterDarkCounts = isusFrame.getSeaWaterDarkCounts();
                    double rawSpectrometerAverage = isusFrame.getSpectrometerAverage();
                    int checksum = isusFrame.getChecksum();

                    //// apply calibrations to the observed data
                    double nitrogenConcentration = calibration.apply(rawNitrogenConcentration, isImmersed,
                            "NITRATE");
                    double auxConcentration1 = calibration.apply(rawAuxConcentration1, isImmersed, "AUX1");
                    double auxConcentration2 = calibration.apply(rawAuxConcentration2, isImmersed, "AUX2");
                    double auxConcentration3 = calibration.apply(rawAuxConcentration3, isImmersed, "AUX3");
                    double rmsError = calibration.apply(rawRmsError, isImmersed, "RMSe");
                    double insideTemperature = calibration.apply(rawInsideTemperature, isImmersed, "T_INT");
                    double spectrometerTemperature = calibration.apply(rawSpectrometerTemperature, isImmersed,
                            "T_SPEC");
                    double lampTemperature = calibration.apply(rawLampTemperature, isImmersed, "T_LAMP");
                    int lampTime = rawLampTime;
                    double humidity = calibration.apply(rawHumidity, isImmersed, "HUMIDITY");
                    double lampVoltage12 = calibration.apply(rawLampVoltage12, isImmersed, "VOLT_12");
                    double internalPowerVoltage5 = calibration.apply(rawInternalPowerVoltage5, isImmersed,
                            "VOLT_5");
                    double mainPowerVoltage = calibration.apply(rawMainPowerVoltage, isImmersed, "VOLT_MAIN");
                    double referenceAverage = calibration.apply(rawReferenceAverage, isImmersed, "REF_AVG");
                    double referenceVariance = calibration.apply(rawReferenceVariance, isImmersed, "REF_STD");
                    double seaWaterDarkCounts = calibration.apply(rawSeaWaterDarkCounts, isImmersed, "SW_DARK");
                    double spectrometerAverage = calibration.apply(rawSpectrometerAverage, isImmersed,
                            "SPEC_AVG");

                    // iterate through the individual wavelengths
                    List<String> variableNames = calibration.getVariableNames();
                    TreeMap<String, Double> wavelengthsMap = new TreeMap<String, Double>();
                    Collections.sort(variableNames);
                    int rawWavelengthCounts = 0;
                    int count = 1;

                    for (String name : variableNames) {

                        // just handle the wavelength channels
                        if (name.startsWith("UV_")) {
                            rawWavelengthCounts = isusFrame.getChannelWavelengthCounts(count);

                            double value = calibration.apply(rawWavelengthCounts, isImmersed, name);
                            count++;
                            wavelengthsMap.put(name, new Double(value));

                        }

                    }

                    String sampleString = "";
                    sampleString += sampleDate + "\t";
                    sampleString += sampleDateUTC + "\t";
                    sampleString += sampleTime + "\t";
                    sampleString += sampleTimeUTC + "\t";
                    sampleString += sampleDateHST + "\t";
                    sampleString += sampleTimeHST + "\t";
                    sampleString += sampleDateTimeHST + "\t";
                    sampleString += String.format("%-15.11f", nitrogenConcentration) + "\t";
                    //sampleString += String.format("%15.11f", auxConcentration1)     + "\t";
                    //sampleString += String.format("%15.11f", auxConcentration2)     + "\t";
                    //sampleString += String.format("%15.11f", auxConcentration3)     + "\t";
                    sampleString += String.format("%15.11f", rmsError) + "\t";
                    sampleString += String.format("%15.11f", insideTemperature) + "\t";
                    sampleString += String.format("%15.11f", spectrometerTemperature) + "\t";
                    sampleString += String.format("%15.11f", lampTemperature) + "\t";
                    sampleString += String.format("%6d", lampTime) + "\t";
                    sampleString += String.format("%15.11f", humidity) + "\t";
                    sampleString += String.format("%15.11f", lampVoltage12) + "\t";
                    sampleString += String.format("%15.11f", internalPowerVoltage5) + "\t";
                    sampleString += String.format("%15.11f", mainPowerVoltage) + "\t";
                    sampleString += String.format("%15.11f", referenceAverage) + "\t";
                    sampleString += String.format("%15.11f", referenceVariance) + "\t";
                    sampleString += String.format("%15.11f", seaWaterDarkCounts) + "\t";
                    sampleString += String.format("%15.11f", spectrometerAverage) + "\t";

                    Set<String> wavelengths = wavelengthsMap.keySet();
                    Iterator wIterator = wavelengths.iterator();

                    while (wIterator.hasNext()) {
                        String name = (String) wIterator.next();
                        Double wavelengthValue = (Double) wavelengthsMap.get(name);
                        sampleString += String.format("%6d", wavelengthValue.intValue()) + "\t";
                        channelIndex = registerChannelMap.Add(name);
                        registerChannelMap.PutUserInfo(channelIndex, "units=counts");
                        channelIndex = rbnbChannelMap.Add(name);
                        rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                        rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                new double[] { wavelengthValue.doubleValue() });

                    }

                    sampleString += String.format("%03d", checksum);
                    sampleString += "\n";

                    // add the sample timestamp to the rbnb channel map
                    //registerChannelMap.PutTime(sampleTimeAsSecondsSinceEpoch, 0d);
                    rbnbChannelMap.PutTime(sampleTimeAsSecondsSinceEpoch, 0d);

                    // add the BinaryRawSatlanticFrameData channel to the channelMap
                    channelIndex = registerChannelMap.Add("BinaryRawSatlanticFrameData");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("BinaryRawSatlanticFrameData");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsByteArray(channelIndex, rawFrame.array());

                    // add the DecimalASCIISampleData channel to the channelMap
                    channelIndex = registerChannelMap.Add(getRBNBChannelName());
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add(getRBNBChannelName());
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, sampleString);

                    // add the serialNumber channel to the channelMap
                    channelIndex = registerChannelMap.Add("serialNumber");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("serialNumber");
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, serialNumber);

                    // add the sampleDateUTC channel to the channelMap
                    channelIndex = registerChannelMap.Add("sampleDateUTC");
                    registerChannelMap.PutUserInfo(channelIndex, "units=YYYYDDD");
                    channelIndex = rbnbChannelMap.Add("sampleDateUTC");
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, sampleDate);

                    // add the sampleTimeUTC channel to the channelMap
                    channelIndex = registerChannelMap.Add("sampleTimeUTC");
                    registerChannelMap.PutUserInfo(channelIndex, "units=hh.hhhhhh");
                    channelIndex = rbnbChannelMap.Add("sampleTimeUTC");
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, sampleTimeUTC);

                    // add the nitrogenConcentration channel to the channelMap
                    channelIndex = registerChannelMap.Add("nitrogenConcentration");
                    registerChannelMap.PutUserInfo(channelIndex, "units=uM");
                    channelIndex = rbnbChannelMap.Add("nitrogenConcentration");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { nitrogenConcentration });

                    // add the auxConcentration1 channel to the channelMap
                    channelIndex = registerChannelMap.Add("auxConcentration1");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("auxConcentration1");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { auxConcentration1 });

                    // add the auxConcentration3 channel to the channelMap
                    channelIndex = registerChannelMap.Add("auxConcentration2");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("auxConcentration2");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { auxConcentration2 });

                    // add the serialNumber channel to the channelMap
                    channelIndex = registerChannelMap.Add("auxConcentration3");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("auxConcentration3");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { auxConcentration3 });

                    // add the rmsError channel to the channelMap
                    channelIndex = registerChannelMap.Add("rmsError");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("rmsError");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { rmsError });

                    // add the insideTemperature channel to the channelMap
                    channelIndex = registerChannelMap.Add("insideTemperature");
                    registerChannelMap.PutUserInfo(channelIndex, "units=Celsius");
                    channelIndex = rbnbChannelMap.Add("insideTemperature");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { insideTemperature });

                    // add the spectrometerTemperature channel to the channelMap
                    channelIndex = registerChannelMap.Add("spectrometerTemperature");
                    registerChannelMap.PutUserInfo(channelIndex, "units=Celsius");
                    channelIndex = rbnbChannelMap.Add("spectrometerTemperature");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { spectrometerTemperature });

                    // add the lampTemperature channel to the channelMap
                    channelIndex = registerChannelMap.Add("lampTemperature");
                    registerChannelMap.PutUserInfo(channelIndex, "units=Celsius");
                    channelIndex = rbnbChannelMap.Add("lampTemperature");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { lampTemperature });

                    // add the lampTime channel to the channelMap
                    channelIndex = registerChannelMap.Add("lampTime");
                    registerChannelMap.PutUserInfo(channelIndex, "units=seconds");
                    channelIndex = rbnbChannelMap.Add("lampTime");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { lampTime });

                    // add the humidity channel to the channelMap
                    channelIndex = registerChannelMap.Add("humidity");
                    registerChannelMap.PutUserInfo(channelIndex, "units=%");
                    channelIndex = rbnbChannelMap.Add("humidity");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { humidity });

                    // add the lampVoltage12 channel to the channelMap
                    channelIndex = registerChannelMap.Add("lampVoltage12");
                    registerChannelMap.PutUserInfo(channelIndex, "units=V");
                    channelIndex = rbnbChannelMap.Add("lampVoltage12");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { lampVoltage12 });

                    // add the internalPowerVoltage5 channel to the channelMap
                    channelIndex = registerChannelMap.Add("internalPowerVoltage5");
                    registerChannelMap.PutUserInfo(channelIndex, "units=V");
                    channelIndex = rbnbChannelMap.Add("internalPowerVoltage5");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { internalPowerVoltage5 });

                    // add the mainPowerVoltage channel to the channelMap
                    channelIndex = registerChannelMap.Add("mainPowerVoltage");
                    registerChannelMap.PutUserInfo(channelIndex, "units=V");
                    channelIndex = rbnbChannelMap.Add("mainPowerVoltage");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { mainPowerVoltage });

                    // add the referenceAverage channel to the channelMap
                    channelIndex = registerChannelMap.Add("referenceAverage");
                    registerChannelMap.PutUserInfo(channelIndex, "units=count");
                    channelIndex = rbnbChannelMap.Add("referenceAverage");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { referenceAverage });

                    // add the referenceVariance channel to the channelMap
                    channelIndex = registerChannelMap.Add("referenceVariance");
                    registerChannelMap.PutUserInfo(channelIndex, "units=count");
                    channelIndex = rbnbChannelMap.Add("referenceVariance");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { referenceVariance });

                    // add the seaWaterDarkCounts channel to the channelMap
                    channelIndex = registerChannelMap.Add("seaWaterDarkCounts");
                    registerChannelMap.PutUserInfo(channelIndex, "units=count");
                    channelIndex = rbnbChannelMap.Add("seaWaterDarkCounts");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { seaWaterDarkCounts });

                    // add the spectrometerAverage channel to the channelMap
                    channelIndex = registerChannelMap.Add("spectrometerAverage");
                    registerChannelMap.PutUserInfo(channelIndex, "units=count");
                    channelIndex = rbnbChannelMap.Add("averageWavelength");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { spectrometerAverage });

                    // Now register the RBNB channels, and flush the rbnbChannelMap to the
                    // DataTurbine
                    getSource().Register(registerChannelMap);
                    getSource().Flush(rbnbChannelMap);
                    logger.info(frameDateAsString + " " + "Sample sent to the DataTurbine: (" + serialNumber
                            + ") " + sampleString);

                    registerChannelMap.Clear();
                    rbnbChannelMap.Clear();

                } else {

                    logger.info("Couldn't apply the calibration coefficients. " + "Skipping this sample.");

                } // end if()

            } // end if()

        } // end for()                                             

        //getSource.Detach();

        success = true;
    } catch (ParseException pe) {
        // parsing of the calibration file failed.  Log the exception, return false
        success = false;
        logger.debug("There was a problem parsing the calibration file. The " + "error message was: "
                + pe.getMessage());
        return success;

    } catch (SAPIException sapie) {
        // In the event of an RBNB communication  exception, log the exception, 
        // and allow execute() to return false, which will prompt a retry.
        success = false;
        sapie.printStackTrace();
        return success;

    }

    return success;
}

From source file:org.apache.pig.builtin.Utf8StorageConverter.java

@Override
public Integer bytesToInteger(byte[] b) throws IOException {
    if (b == null || b.length == 0) {
        return null;
    }//from  ww  w.  java 2  s  .com

    String s = new String(b);
    s = s.trim();
    Integer ret = null;

    // See PIG-2835. Using exception handling to check if it's a double is very expensive.
    // So we write our sanity check.
    if (sanityCheckIntegerLong(s)) {
        try {
            ret = Integer.valueOf(s);
        } catch (NumberFormatException nfe) {
        }
    }
    if (ret == null) {
        // It's possible that this field can be interpreted as a double.
        // Unfortunately Java doesn't handle this in Integer.valueOf.  So
        // we need to try to convert it to a double and if that works then
        // go to an int.
        try {
            Double d = Double.valueOf(s);
            // Need to check for an overflow error
            if (Double.compare(d.doubleValue(), mMaxInt.doubleValue() + 1) >= 0
                    || Double.compare(d.doubleValue(), mMinInt.doubleValue() - 1) <= 0) {
                LogUtils.warn(this, "Value " + d + " too large for integer", PigWarning.TOO_LARGE_FOR_INT,
                        mLog);
                return null;
            }
            return Integer.valueOf(d.intValue());
        } catch (NumberFormatException nfe2) {
            LogUtils.warn(this,
                    "Unable to interpret value " + Arrays.toString(b) + " in field being "
                            + "converted to int, caught NumberFormatException <" + nfe2.getMessage()
                            + "> field discarded",
                    PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog);
            return null;
        }
    }
    return ret;
}

From source file:com.cognitivemedicine.nifi.http.PostAdvancedHTTP.java

@OnScheduled
public void onScheduled(final ProcessContext context) {
    final Double bytesPerSecond = context.getProperty(MAX_DATA_RATE).asDataSize(DataUnit.B);
    this.throttlerRef
            .set(bytesPerSecond == null ? null : new LeakyBucketStreamThrottler(bytesPerSecond.intValue()));
}