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:com.google.acre.script.HostEnv.java

@SuppressWarnings("unused")
@JSFunction/*  w w w .  j  av a 2 s . co m*/
public void urlOpenAsync(String url, String method, Object content, Scriptable headers, Double timeout_ms,
        boolean system, boolean log_to_user, String response_encoding, boolean no_redirect, Function callback) {

    //System.out.println((system ? "[system] " : "") + "async: " + url.split("\\?")[0] + " [reentries: " + req._reentries + "]");

    if (_async_fetch == null) {
        throw new JSConvertableException("Async Urlfetch not supported in this enviornment")
                .newJSException(this);
    }

    if (req._reentries > 1) {
        throw new JSConvertableException("Urlfetch is allowed to re-enter only once").newJSException(this);
    }

    if (LIMIT_EXECUTION_TIME && System.currentTimeMillis() > req._deadline) {
        throw new RuntimeException("Cannot call urlfetch, the script ran out of time");
    }

    // if execution is limited, give the subrequest a shorter deadline so this request can
    // handle any failure
    long timeout = (LIMIT_EXECUTION_TIME) ? req._deadline - NETWORK_DEADLINE_ADVANCE
            : System.currentTimeMillis() + ACRE_URLFETCH_TIMEOUT;

    if (!timeout_ms.isNaN() && timeout_ms.longValue() < timeout) {
        timeout = timeout_ms.longValue();
    }

    if (response_encoding == null)
        response_encoding = "ISO-8859-1";

    Map<String, String> header_map = new HashMap<String, String>();
    if (headers != null) {
        Object[] ids = headers.getIds();
        for (int i = 0; i < ids.length; i++) {
            String id = ids[i].toString();
            header_map.put(id, headers.get(id, headers).toString());
        }
    }

    try {
        new URL(url);
    } catch (MalformedURLException e) {
        throw new JSURLError("Malformed URL: " + url).newJSException(this);
    }

    long sub_deadline = (LIMIT_EXECUTION_TIME) ? req._deadline - HostEnv.SUBREQUEST_DEADLINE_ADVANCE
            : ACRE_URLFETCH_TIMEOUT;
    int reentrances = req._reentries + 1;
    header_map.put(HostEnv.ACRE_QUOTAS_HEADER, "td=" + sub_deadline + ",r=" + reentrances);

    try {
        _async_fetch.make_request(url, method, timeout, header_map, content, system, log_to_user,
                response_encoding, no_redirect, callback);
    } catch (Exception e) {
        throw new JSConvertableException(e.getMessage()).newJSException(this);
    }
}

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

@RequestMapping(value = "/energydata", method = RequestMethod.GET)
public void getEnergyForUser(@RequestParam(value = "userId") String userId,
        @RequestParam(value = "start", required = false) Double startMillis,
        @RequestParam(value = "end", required = false) Double endMillis, HttpServletResponse response)
        throws IOException {

    logger.debug("Serving request for user info for " + userId);

    // get first energy monitor for user
    List<Ted5000> teds = null;
    int retry = 3;
    while (true) {
        try {//from www  .  j av  a  2  s.c o m
            teds = dataService.getTEDIdsForUserId(userId, true);
            break;
        } catch (OAuthUnauthorizedException e) {
            throw new ClientAPIException("User " + userId
                    + " has not authorized use of their Stepgreen data by accessing and logging into "
                    + energyLabelerUrl + "t/controlpanel first", e);
        } catch (Exception e) {
            // retry
            if (retry-- == 0) {
                throw new RuntimeException(
                        "Could not access energy data for user id " + userId + " after 3 attempts", e);
            }
        }
    }

    // TODO - allow user to select the Ted / MTU combination that they want to use, put it in the path
    // right now, just select the first ted and mtu
    if (teds.size() > 0) {
        Ted5000 ted = teds.get(0);
        if (ted.getTed5000Mtu().size() > 0) {
            Mtu mtu = ted.getTed5000Mtu().get(0);

            EnergyMonitor energyMonitor = new Ted5000Monitor(-1, userId, ted.getId(), mtu.getId(), "test");

            Date start = null;
            Date end = null;

            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);
                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 {
                //  create a one day span
                if (energyMonitor != null) {
                    end = database.getLastMeasurementTimeForEnergyMonitor(energyMonitor);
                }

                if (end == null) {
                    end = new Date();
                }

                Calendar c = new GregorianCalendar();
                c.setTime(end);

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

            Calendar cal = new GregorianCalendar();
            cal.setTime(start);
            Date queryStart = dateUtils.getPreviousFiveMinuteIncrement(cal).getTime();

            cal = new GregorianCalendar();
            cal.setTime(end);
            Date queryEnd = dateUtils.getNextFiveMinuteIncrement(cal).getTime();

            Map<UserAppliance, List<EnergyTimestep>> predictedEnergyUsage = dataService
                    .getApplianceEnergyConsumptionForMonitor(energyMonitor, algorithm.getId(), queryStart,
                            queryEnd);

            Map<String, Double> result = new HashMap<String, Double>();

            for (UserAppliance app : predictedEnergyUsage.keySet()) {
                Double total = 0d;
                for (EnergyTimestep timestep : predictedEnergyUsage.get(app)) {
                    total += timestep.getEnergyConsumed();
                }
                result.put(app.getName(), total);
            }

            String dataJS = new GsonBuilder().create().toJson(result);

            response.getWriter().write(dataJS);

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

            return;
        }
    }

    throw new ClientAPIException("No ted monitors found for user " + userId);

}

From source file:se.sics.gvod.system.vod.Vod.java

private void triggerDataMsgRequest(VodDescriptor peerInfo, TimeoutId ackId, int piece, int subpiece,
        long delay) {
    if (ackId == null) {
        logger.debug(compName + "ACKID was null when requesting new piece");
    }//from  ww  w . j  a  v a  2 s  .com
    VodAddress des = peerInfo.getVodAddress();
    Double rto = rtos.get(des.getId());
    if (rto == null) {
        rto = (double) config.getDataRequestTimeout();
    }

    DataMsg.Request request = new DataMsg.Request(self.getAddress(), des, ackId, piece, subpiece, delay);
    ScheduleRetryTimeout st = new ScheduleRetryTimeout(rto.longValue(), 1);
    DataMsg.DataRequestTimeout t = new DataMsg.DataRequestTimeout(st, request);
    delegator.doRetry(t);

    peerInfo.getRequestPipeline().add(new Block(piece, subpiece, System.currentTimeMillis()));
    rttMsgs.put(t.getTimeoutId(), System.currentTimeMillis());

    logger.debug(compName + "Requesting subpiece {}:{} on {}", new Object[] { piece, subpiece, des.getId() });
}

From source file:com.ynyes.lyz.webservice.impl.CallWMSImpl.java

public String GetWMSInfo(String STRTABLE, String STRTYPE, String XML) {
    System.out.println("MDJ:WMSInfo called" + STRTABLE);

    if (null == STRTABLE || STRTABLE.isEmpty() || STRTABLE.equals("?")) {
        return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>STRTABLE?</MESSAGE></STATUS></RESULTS>";
    }//from w w  w  .  ja v  a2 s .  co  m

    if (null == XML || XML.isEmpty() || XML.equals("?")) {
        return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>XML?</MESSAGE></STATUS></RESULTS>";
    }

    String XMLStr = XML.trim();

    XMLStr = XML.replace("\n", "");

    byte[] decoded = Base64.decode(XMLStr);

    String decodedXML = null;

    try {
        decodedXML = new String(decoded, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        System.out.println("UnsupportedEncodingException for decodedXML");
        e.printStackTrace();
    }

    if (null == decodedXML || decodedXML.isEmpty()) {
        return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>?XML?</MESSAGE></STATUS></RESULTS>";
    }

    System.out.println(decodedXML);

    // ?XML
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>?xml?</MESSAGE></STATUS></RESULTS>";
    }

    Document document = null;

    InputSource is = new InputSource(new StringReader(decodedXML));

    try {
        document = builder.parse(is);
    } catch (SAXException | IOException e) {
        e.printStackTrace();
        return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>?xml??</MESSAGE></STATUS></RESULTS>";
    }
    NodeList nodeList = document.getElementsByTagName("TABLE");

    if (STRTABLE.equalsIgnoreCase("tbw_send_task_m")) // ??
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            String c_task_no = null;//?
            String c_begin_dt = null;//
            String c_end_dt = null;//?
            String c_wh_no = null;//?
            String c_op_status = null;//??(?????)
            String c_op_user = null;//
            String c_modified_userno = null;//
            String c_owner_no = null;//
            String c_reserved1 = null;//??
            String c_Driver = null;//?
            Long cCompanyId = null;//?id
            String cTaskType = null;//

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();

            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);

                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    // ??
                    if (childNode.getNodeName().equalsIgnoreCase("c_task_no")) {
                        // 
                        if (null != childNode.getChildNodes().item(0)) {
                            c_task_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                        // 
                        else {
                            c_task_no = null;
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_begin_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_begin_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_end_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_end_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_wh_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_wh_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_op_status = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_user")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_op_user = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_modified_userno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_owner_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved1")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_reserved1 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_Driver")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_Driver = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_company_id")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cCompanyId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_task_type")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cTaskType = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                }
            }

            //? 
            TdDeliveryInfo tdDeliveryInfo = tdDeliveryInfoService.findByTaskNo(c_task_no);
            if (tdDeliveryInfo != null) {
                return "<RESULTS><STATUS><CODE>1</CODE>?:" + c_task_no
                        + " <MESSAGE></MESSAGE></STATUS></RESULTS>";
            }
            tdDeliveryInfo = new TdDeliveryInfo();
            tdDeliveryInfo.setTaskNo(c_task_no);
            tdDeliveryInfo.setWhNo(c_wh_no);
            tdDeliveryInfo.setDriver(c_Driver);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            if (c_begin_dt != null) {
                try {
                    Date startdate = sdf.parse(c_begin_dt);
                    tdDeliveryInfo.setBeginDt(startdate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (c_end_dt != null) {
                try {
                    Date enddate = sdf.parse(c_end_dt);
                    tdDeliveryInfo.setEndDt(enddate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            tdDeliveryInfo.setOrderNumber(c_reserved1);
            tdDeliveryInfo.setOpStatus(c_op_status);
            tdDeliveryInfo.setOpUser(c_op_user);
            tdDeliveryInfo.setModifiedUserno(c_modified_userno);
            tdDeliveryInfo.setOwnerNo(c_owner_no);
            tdDeliveryInfo.setcCompanyId(cCompanyId);
            tdDeliveryInfo.setcTaskType(cTaskType);
            if (cTaskType != null && cTaskType.contains("")) {
                if (cCompanyId == null) {
                    return "<RESULTS><STATUS><CODE>1</CODE>id?<MESSAGE></MESSAGE></STATUS></RESULTS>";
                }
                TdCity tdCity = tdCityService.findBySobIdCity(cCompanyId);
                if (tdCity == null) {
                    return "<RESULTS><STATUS><CODE>1</CODE>app?id:" + cCompanyId
                            + "<MESSAGE></MESSAGE></STATUS></RESULTS>";
                }
                List<TdDeliveryInfoDetail> infoDetails = tdDeliveryInfoDetailService.findByTaskNo(c_task_no);
                if (infoDetails == null || infoDetails.size() < 1) {
                    return "<RESULTS><STATUS><CODE>1</CODE>?" + c_task_no
                            + " <MESSAGE></MESSAGE></STATUS></RESULTS>";
                }
                for (TdDeliveryInfoDetail infoDetail : infoDetails) {
                    String cGcode = infoDetail.getgCode();
                    TdGoods tdGoods = tdGoodsService.findByCode(cGcode);
                    TdDiySiteInventory inventory = tdDiySiteInventoryService
                            .findByGoodsCodeAndRegionIdAndDiySiteIdIsNull(cGcode, cCompanyId);
                    if (inventory == null) {
                        inventory = new TdDiySiteInventory();
                        inventory.setGoodsCode(tdGoods.getCode());
                        inventory.setGoodsId(tdGoods.getId());
                        inventory.setCategoryId(tdGoods.getCategoryId());
                        inventory.setCategoryIdTree(tdGoods.getCategoryIdTree());
                        inventory.setCategoryTitle(tdGoods.getCategoryTitle());
                        inventory.setGoodsTitle(tdGoods.getTitle());
                        inventory.setRegionId(cCompanyId);
                        inventory.setRegionName(tdCity.getCityName());
                    }
                    Double doubleFromStr = infoDetail.getBackNumber();
                    doubleFromStr = doubleFromStr * 100;
                    Long cRecQty = doubleFromStr.longValue();
                    cRecQty = cRecQty / 100;
                    inventory.setInventory(inventory.getInventory() - cRecQty);
                    tdDiySiteInventoryService.save(inventory);
                    tdDiySiteInventoryLogService.saveChangeLog(inventory, -cRecQty, null, null,
                            TdDiySiteInventoryLog.CHANGETYPE_CITY_CG_SUB);
                }
            }

            tdDeliveryInfoService.save(tdDeliveryInfo);
        }
        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    }
    if (STRTABLE.equalsIgnoreCase("tbw_send_task_Driver")) // ????
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            String c_task_no = null;//?
            String c_begin_dt = null;//
            String c_end_dt = null;//?
            String c_wh_no = null;//?
            String c_op_status = null;//??(?????)
            String c_op_user = null;//
            String c_modified_userno = null;//
            String c_owner_no = null;//
            String c_reserved1 = null;//??
            String c_Driver = null;//?

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();

            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);

                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    // ??
                    if (childNode.getNodeName().equalsIgnoreCase("c_task_no")) {
                        // 
                        if (null != childNode.getChildNodes().item(0)) {
                            c_task_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                        // 
                        else {
                            c_task_no = null;
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_begin_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_begin_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_end_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_end_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_wh_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_wh_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_op_status = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_user")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_op_user = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_modified_userno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_owner_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved1")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_reserved1 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_Driver")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_Driver = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }

                }
            }

            //? 
            TdDeliveryInfo tdDeliveryInfo = tdDeliveryInfoService.findByTaskNo(c_task_no);
            if (tdDeliveryInfo == null) {
                tdDeliveryInfo = new TdDeliveryInfo();
            }
            tdDeliveryInfo.setTaskNo(c_task_no);
            tdDeliveryInfo.setWhNo(c_wh_no);
            tdDeliveryInfo.setDriver(c_Driver);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            if (c_begin_dt != null) {
                try {
                    Date startdate = sdf.parse(c_begin_dt);
                    tdDeliveryInfo.setBeginDt(startdate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (c_end_dt != null) {
                try {
                    Date enddate = sdf.parse(c_end_dt);
                    tdDeliveryInfo.setEndDt(enddate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            tdDeliveryInfo.setOrderNumber(c_reserved1);
            tdDeliveryInfo.setOpStatus(c_op_status);
            tdDeliveryInfo.setOpUser(c_op_user);
            tdDeliveryInfo.setModifiedUserno(c_modified_userno);
            tdDeliveryInfo.setOwnerNo(c_owner_no);
            tdDeliveryInfoService.save(tdDeliveryInfo);
        }
        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_send_task_d")) //??
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            String c_task_no = null;//?
            String c_begin_dt = null;//
            String c_end_dt = null;//?
            String c_wh_no = null;//?
            String c_op_status = null;//??(?????)
            String c_op_user = null;//
            String c_modified_userno = null;//
            String c_owner_no = null;//
            String c_gcode = null;//??
            Double c_d_ack_qty = null; //?
            Double c_d_request_qty = null;//?
            String c_reserved1 = null;//??

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();

            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);

                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    // ??
                    if (childNode.getNodeName().equalsIgnoreCase("c_task_no")) {
                        // 
                        if (null != childNode.getChildNodes().item(0)) {
                            c_task_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                        // 
                        else {
                            c_task_no = null;
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved1")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_reserved1 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_begin_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_begin_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_end_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_end_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_wh_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_wh_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_op_status = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_user")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_op_user = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_modified_userno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_owner_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_gcode")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_gcode = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_d_ack_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_d_ack_qty = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_d_request_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            String string = childNode.getChildNodes().item(0).getNodeValue();
                            c_d_request_qty = Double.parseDouble(string);
                        }
                    }

                }
            }
            //? 
            TdDeliveryInfoDetail infoDetail = new TdDeliveryInfoDetail();
            infoDetail.setTaskNo(c_task_no);
            infoDetail.setWhNo(c_wh_no);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            if (c_begin_dt != null) {
                try {
                    Date startdate = sdf.parse(c_begin_dt);
                    infoDetail.setBeginDt(startdate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (c_end_dt != null) {
                try {
                    Date enddate = sdf.parse(c_end_dt);
                    infoDetail.setEndDt(enddate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            infoDetail.setOpStatus(c_op_status);
            infoDetail.setOpUser(c_op_user);
            infoDetail.setModifiedUserno(c_modified_userno);
            infoDetail.setOwnerNo(c_owner_no);
            infoDetail.setgCode(c_gcode);
            infoDetail.setRequstNumber(c_d_request_qty);
            infoDetail.setBackNumber(c_d_ack_qty);
            infoDetail.setSubOrderNumber(c_reserved1);
            TdGoods tdGoods = tdGoodsService.findByCode(c_gcode);
            if (tdGoods == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>?" + c_gcode
                        + "??</MESSAGE></STATUS></RESULTS>";
            }
            tdDeliveryInfoDetailService.save(infoDetail);
            if (c_reserved1 != null) {
                TdOrder tdOrder = tdOrderService.findByOrderNumber(c_reserved1);
                if (tdOrder != null && tdOrder.getStatusId() != null && tdOrder.getStatusId() == 3L) {
                    tdOrder.setStatusId(4L);
                    tdOrder.setSendTime(new Date());
                    tdOrderService.save(tdOrder);
                }
            }
        }
        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_back_m"))// ? 
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            // ?
            String c_wh_no = null;
            // 
            String c_owner_no = null;
            // ???
            String c_rec_no = null;
            // ?
            Integer c_print_times = null;
            // ???
            String c_back_no = null;
            // ???
            String c_back_type = null;
            // ??(?)
            String c_back_class = null;
            // ?
            String c_customer_no = null;
            // ?
            String c_plat_no = null;
            // 
            String c_rec_user = null;
            // ?(?,pda,?)
            String c_op_tools = null;
            // ??(?????)
            String c_op_status = null;
            // 
            String c_note = null;
            // 
            String c_mk_userno = null;
            // 
            String c_modified_userno = null;
            // ?
            String c_po_no = null;
            // ?
            String c_begin_dt = null;
            // ??
            String c_end_dt = null;
            // 
            String c_mk_dt = null;
            // 
            String c_modified_dt = null;

            // ??
            String driver = null;

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();

            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);

                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    // ??
                    if (childNode.getNodeName().equalsIgnoreCase("c_wh_no")) {
                        // 
                        if (null != childNode.getChildNodes().item(0)) {
                            c_wh_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                        // 
                        else {
                            c_wh_no = null;
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_owner_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_driver")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            driver = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_rec_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_print_times")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_print_times = Integer.parseInt(childNode.getChildNodes().item(0).getNodeValue());
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_back_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_back_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_back_type")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_back_type = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_back_class")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_back_class = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_customer_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_customer_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_plat_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_plat_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_user")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_rec_user = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_tools")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_op_tools = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_note")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_note = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_mk_userno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_modified_userno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_po_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_po_no = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_begin_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_begin_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_end_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_end_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_mk_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_modified_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                }
            }

            //? 
            TdBackMain tdBackMain = tdBackMainService.findByRecNo(c_rec_no);
            if (tdBackMain == null) {
                tdBackMain = new TdBackMain();
                tdBackMain.setRecNo(c_rec_no);
            }
            tdBackMain.setOwnerNo(c_owner_no);
            tdBackMain.setWhNo(c_wh_no);
            tdBackMain.setPrintTimes(c_print_times);
            tdBackMain.setBackClass(c_back_class);
            tdBackMain.setBackNo(c_back_no);
            tdBackMain.setBackType(c_back_type);
            tdBackMain.setCustomerNo(c_customer_no);
            tdBackMain.setPlatNo(c_plat_no);
            tdBackMain.setRecUser(c_rec_user);
            tdBackMain.setOpTools(c_op_tools);
            tdBackMain.setOpStatus(c_op_status);
            tdBackMain.setNote(c_note);
            tdBackMain.setMkUserno(c_mk_userno);
            tdBackMain.setModifiedUserno(c_modified_userno);
            tdBackMain.setPoNo(c_po_no);
            tdBackMain.setDriver(driver);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            if (c_begin_dt != null) {
                try {
                    Date c_begin = sdf.parse(c_begin_dt);
                    tdBackMain.setBeginDt(c_begin);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (c_end_dt != null) {
                try {
                    Date enddate = sdf.parse(c_end_dt);
                    tdBackMain.setEndDt(enddate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (c_mk_dt != null) {
                try {
                    Date c_mk = sdf.parse(c_mk_dt);
                    tdBackMain.setMkDt(c_mk);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (c_modified_dt != null) {
                try {
                    Date c_modified = sdf.parse(c_modified_dt);
                    tdBackMain.setModifiedDt(c_modified);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            tdBackMainService.save(tdBackMain);

            TdReturnNote tdReturnNote = tdReturnNoteService.findByReturnNumber(c_po_no);
            if (tdReturnNote != null) {
                //               tdReturnNote.setStatusId(5L);
                //               
                //               TdOrder order = tdOrderService.findByOrderNumber(tdReturnNote.getOrderNumber());
                //               if (order != null)
                //               {
                //                  if (order.getStatusId() == 9 || order.getStatusId() == 10 || order.getStatusId() == 11 || order.getStatusId() == 12)
                //                  {
                //                     order.setStatusId(12L);
                //                     tdOrderService.save(order);
                //                  }
                //                  TdUser tdUser = tdUserService.findByUsername(order.getUsername());
                //                  tdPriceCountService.cashAndCouponBack(order, tdUser);
                //               }
                tdReturnNote.setDriver(driver);
                tdReturnNoteService.save(tdReturnNote);
            }

            //            if (c_reserved1 != null) 
            //            {
            //               TdOrder tdOrder = tdOrderService.findByOrderNumber(c_reserved1);
            //               if (tdOrder != null && tdOrder.getStatusId() != null && tdOrder.getStatusId() == 3L) {
            //                  tdOrder.setStatusId(4L);
            //                  tdOrderService.save(tdOrder);
            //               }
            //            }
        }
        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_back_d"))// ? 
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            //    
            String ownerNo = null;

            //  ?
            String recNo = null;

            // id
            String recId = null;

            // ??
            String gcode = null;

            // ?
            String packQty = null;

            // 
            String price = null;

            //??
            String giftQty = null;

            // ????
            String badQty = null;

            // ?
            String recQty = null;

            // 
            String recUser = null;

            //?
            String platNo = null;

            // ?(?,pda,?)
            String opTools = null;

            // ??????
            String opStatus = null;

            // 
            String reserved1 = null;

            // 
            String reserved2 = null;

            // 
            String reserved3 = null;

            // 
            String reserved4 = null;

            // 
            String reserved5 = null;

            // 
            String note = null;

            // 
            String mkUserno = null;

            // 
            String modifiedUserno = null;

            // 
            String c_mk_dt = null;

            // 
            String c_modified_dt = null;

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();

            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);

                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    // ??
                    if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                        // 
                        if (null != childNode.getChildNodes().item(0)) {
                            ownerNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                        // 
                        else {
                            ownerNo = null;
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            recNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_id")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            recId = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_gcode")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            gcode = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_pack_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            packQty = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_price")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            price = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_gift_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            giftQty = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_bad_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            badQty = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            recQty = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_user")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            recUser = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_plat_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            platNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_tools")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            opTools = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            opStatus = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved1")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved1 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved2")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved2 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved3")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved3 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved4")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved4 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved5")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved5 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_note")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            note = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            mkUserno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_mk_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_mk_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_modified_dt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                }
            }

            //? 
            TdBackDetail tdBackDetail = new TdBackDetail();
            tdBackDetail.setOwnerNo(ownerNo);
            tdBackDetail.setRecNo(recNo);
            tdBackDetail.setRecId(recId);
            tdBackDetail.setGcode(gcode);
            tdBackDetail.setPackQty(packQty);
            tdBackDetail.setPrice(price);
            tdBackDetail.setGiftQty(giftQty);
            tdBackDetail.setBadQty(badQty);
            tdBackDetail.setRecQty(recQty);
            tdBackDetail.setRecUser(recUser);
            tdBackDetail.setPlatNo(platNo);
            tdBackDetail.setOpTools(opTools);
            tdBackDetail.setOpStatus(opStatus);
            tdBackDetail.setReserved1(reserved1);
            tdBackDetail.setReserved2(reserved2);
            tdBackDetail.setReserved3(reserved3);
            tdBackDetail.setReserved4(reserved4);
            tdBackDetail.setReserved5(reserved5);
            tdBackDetail.setNote(note);
            tdBackDetail.setMkUserno(mkUserno);
            tdBackDetail.setMkDt(c_mk_dt);
            tdBackDetail.setModifiedUserno(modifiedUserno);
            tdBackDetail.setModifiedDt(c_modified_dt);
            tdBackDetailService.save(tdBackDetail);

        }
        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_rec_d")) //
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            //    
            String ownerNo = null;
            //  ?
            String recNo = null;
            // id
            Long recId = null;
            // ??
            String gcode = null;
            // ?
            Long packQty = null;
            // 
            String price = null;
            // ?(??????)
            String itemType = null;
            //??
            String giftQty = null;
            // ????
            String badQty = null;
            // ?(?)
            String recQty = null;
            // 
            String recUserno = null;
            //?
            String platNo = null;
            // ?(?,pda,?)
            String opTools = null;
            // ??????
            String opStatus = null;
            // 
            String reserved1 = null;
            // 
            String reserved2 = null;
            // 
            String reserved3 = null;
            // 
            String reserved4 = null;
            // 
            String reserved5 = null;
            // 
            String note = null;
            // 
            String mkUserno = null;
            // 
            String mkDt = null;
            // 
            String modifiedUserno = null;
            // 
            String modifiedDt = null;
            // ?
            String c_dps_qty = null;
            //            
            //            //sobId
            //            Long cCompanyId = null;//?Id

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();

            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);
                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            ownerNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_rec_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            recNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_rec_id")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            recId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_gcode")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            gcode = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_pack_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            packQty = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_price")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            price = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_item_type")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            recNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_gift_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            giftQty = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_bad_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            badQty = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_rec_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            recQty = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_rec_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            recUserno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_plat_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            platNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_op_tools")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            opTools = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            opStatus = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_reserved1")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved1 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_reserved2")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved2 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_reserved3")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved3 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_reserved4")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved4 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_reserved5")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            reserved5 = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_note")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            note = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_mk_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            mkUserno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_mk_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            mkDt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            modifiedUserno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_modified_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            modifiedDt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                    if (childNode.getNodeName().equalsIgnoreCase("c_dps_qty")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            c_dps_qty = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    }
                }
            }
            //? 
            TdTbwRecd recd = new TdTbwRecd();
            recd.setOwnerNo(ownerNo);
            recd.setRecNo(recNo);
            recd.setRecId(recId);
            recd.setGcode(gcode);
            recd.setPackQty(packQty);
            recd.setPrice(price);
            recd.setItemType(itemType);
            recd.setGiftQty(giftQty);
            recd.setBadQty(badQty);
            recd.setRecQty(recQty);
            recd.setMkUserno(mkUserno);
            recd.setRecUserno(recUserno);
            recd.setPlatNo(platNo);
            recd.setOpTools(opTools);
            recd.setOpStatus(opStatus);
            recd.setReserved1(reserved1);
            recd.setReserved2(reserved2);
            recd.setReserved3(reserved3);
            recd.setReserved4(reserved4);
            recd.setReserved5(reserved5);
            recd.setNote(note);
            recd.setMkUserno(mkUserno);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            if (mkDt != null) {
                try {
                    Date md_dt = sdf.parse(mkDt);
                    recd.setMkDt(md_dt);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            recd.setModifiedUserno(modifiedUserno);
            if (modifiedDt != null) {
                try {
                    Date modified_dt = sdf.parse(modifiedDt);
                    recd.setMkDt(modified_dt);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            recd.setDpsQty(c_dps_qty);
            recd.setInitTime(new Date());
            tdTbwRecdService.save(recd);
            TdGoods tdGoods = tdGoodsService.findByCodeAndStatus(gcode, 1l);
            if (StringUtils.isBlank(recQty)) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>???</MESSAGE></STATUS></RESULTS>";
            }
            if (tdGoods == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>??" + gcode
                        + "????</MESSAGE></STATUS></RESULTS>";
            }
        }
        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_rec_m"))//
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            // ?
            String cWhNo = null;
            // 
            String cOwnerNo = null;
            // ??(:??)
            String cRecNo = null;
            // ?
            Integer cPrintTimes = null;
            // 
            String cGatherRecNo = null;
            // 
            String cGatherNo = null;
            // ?(?)
            String cInClass = null;
            // ??(:??)
            String cInNo = null;
            // ?(??,)
            String cInType = null;
            // ?
            String cProviderNo = null;
            // ?
            String cPlatNo = null;
            // 
            String cRecUserno = null;
            // ?(?,pda,?)
            String cOpTools = null;
            // ??(?????)
            String cOpStatus = null;
            // ?
            String cBeginDt = null;
            // ??
            String cEndDt = null;
            // 
            String cNote = null;
            // 
            String cMkUserno = null;
            // 
            String cMkDt = null;
            // 
            String cModifiedUserno = null;
            // 
            String cModifiedDt = null;
            // ??
            String cPoNo = null;
            // sobId
            Long cCompanyId = null;//?Id

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();

            // ??TABLE
            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);

                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    if (childNode.getNodeName().equalsIgnoreCase("c_wh_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cWhNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cOwnerNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cRecNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_wh_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cWhNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_print_times")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cPrintTimes = Integer.parseInt(childNode.getChildNodes().item(0).getNodeValue());
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_gather_rec_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cGatherRecNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_gather_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cGatherNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_in_class")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cInClass = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_in_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cInNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_in_type")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cInType = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_provider_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cProviderNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_plat_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cPlatNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cRecUserno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_tools")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cOpTools = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cOpStatus = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_begin_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cBeginDt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_end_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cEndDt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_note")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cNote = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cMkUserno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cMkDt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cModifiedUserno = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_dt")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cModifiedDt = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_po_no")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cPoNo = childNode.getChildNodes().item(0).getNodeValue();
                        }
                    } else if (childNode.getNodeName().equalsIgnoreCase("c_company_id")) {
                        if (null != childNode.getChildNodes().item(0)) {
                            cCompanyId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                        }
                    }
                }
            }
            // ?
            TdTbwRecm recm = tdTbwRecmService.findByCRecNo(cRecNo);
            if (recm == null) {
                recm = new TdTbwRecm();
            }
            recm.setcWhNo(cWhNo);
            recm.setcOwnerNo(cOwnerNo);
            recm.setcRecNo(cRecNo);
            recm.setcPrintTimes(cPrintTimes);
            recm.setcGatherRecNo(cGatherRecNo);
            recm.setcGatherNo(cGatherNo);
            recm.setcInClass(cInClass);
            recm.setcInNo(cInNo);
            recm.setcInType(cInType);
            recm.setcProviderNo(cProviderNo);
            recm.setcPlatNo(cPlatNo);
            recm.setcRecUserno(cRecUserno);
            recm.setcOpTools(cOpTools);
            recm.setcOpStatus(cOpStatus);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            if (cBeginDt != null) {
                try {
                    Date c_beginDt = sdf.parse(cBeginDt);
                    recm.setcBeginDt(c_beginDt);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (cEndDt != null) {
                try {
                    Date c_endDt = sdf.parse(cEndDt);
                    recm.setcEndDt(c_endDt);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            recm.setcNote(cNote);
            recm.setcMkUserno(cMkUserno);
            if (cMkDt != null) {
                try {
                    Date c_mkD = sdf.parse(cMkDt);
                    recm.setcMkDt(c_mkD);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            recm.setcModifiedUserno(cModifiedUserno);
            if (cModifiedDt != null) {
                try {
                    Date c_modifi = sdf.parse(cModifiedDt);
                    recm.setcModifiedDt(c_modifi);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            recm.setcPoNo(cPoNo);
            recm.setcCompanyId(cCompanyId);
            recm.setInitTime(new Date());
            tdTbwRecmService.save(recm);
            if (cCompanyId == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>??</MESSAGE></STATUS></RESULTS>";
            }
            List<TdTbwRecd> tbwRecds = tdTbwRecdService.findByRecNo(cRecNo);
            if (tbwRecds == null || tbwRecds.size() < 1) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>" + cRecNo
                        + "</MESSAGE></STATUS></RESULTS>";
            }
            for (TdTbwRecd tdTbwRecd : tbwRecds) {
                String gcode = tdTbwRecd.getGcode();
                TdDiySiteInventory inventory = tdDiySiteInventoryService
                        .findByGoodsCodeAndRegionIdAndDiySiteIdIsNull(gcode, cCompanyId);
                if (inventory == null) {
                    return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>?" + cCompanyId
                            + "?</MESSAGE></STATUS></RESULTS>";
                }
                Double.parseDouble(tdTbwRecd.getRecQty());
                Double cRecQty = Double.parseDouble(tdTbwRecd.getRecQty());
                cRecQty = cRecQty * 100;
                Long recQtyFromDouble = cRecQty.longValue();
                recQtyFromDouble = recQtyFromDouble / 100;
                inventory.setInventory(inventory.getInventory() + recQtyFromDouble);
                tdDiySiteInventoryService.save(inventory);
                tdDiySiteInventoryLogService.saveChangeLog(inventory, recQtyFromDouble, null, null,
                        TdDiySiteInventoryLog.CHANGETYPE_CITY_ADD);
            }
        }

        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_back_rec_d"))//
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            String cOwnerNo = null;//
            String cRecNo = null;//?
            Long cRecId = null;//id
            String cGcode = null;//??
            String cPackQty = null;//? :long
            Double cPrice = null;// :long
            String cGiftQty = null;//?? :long
            String cBadQty = null;//???:long
            String cRecQty = null;//?:long
            String cRecUser = null;//
            String cPlatNo = null;//?
            String cOpTools = null;//?(?,pda,?)
            String cOpStatus = null;//??????)
            String cReserved1 = null;//1
            String cReserved2 = null;//2
            String cReserved3 = null;//3
            String cReserved4 = null;//4
            String cReserved5 = null;//5
            String cNote = null;//
            String cMkUserno = null;//
            String cMkDt = null;//
            String cModifiedUserno = null;//
            String cModifiedDt = null;//
            //            Long cCompanyId = null;//?Id

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();
            // ??TABLE
            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);
                if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOwnerNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cRecNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_id")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cRecId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_gcode")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cGcode = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_pack_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPackQty = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_price")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPrice = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_gift_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cGiftQty = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_bad_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cBadQty = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cRecQty = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_user")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cRecUser = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_plat_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPlatNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_op_tools")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOpTools = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOpStatus = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved1")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved1 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved2")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved2 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved3")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved3 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved4")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved4 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved5")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved5 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_note")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cNote = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                }
            }
            TdTbwBackRecD tbwBackRecD = new TdTbwBackRecD();
            tbwBackRecD.setcOwnerNo(cOwnerNo);
            tbwBackRecD.setcOwnerNo(cOwnerNo);
            tbwBackRecD.setcRecNo(cRecNo);
            tbwBackRecD.setcRecId(cRecId);
            tbwBackRecD.setcGcode(cGcode);
            tbwBackRecD.setcPackQty(cPackQty);
            tbwBackRecD.setcPrice(cPrice);
            tbwBackRecD.setcGiftQty(cGiftQty);
            tbwBackRecD.setcBadQty(cBadQty);
            tbwBackRecD.setcRecQty(cRecQty);
            tbwBackRecD.setcRecUser(cRecUser);
            tbwBackRecD.setcPlatNo(cPlatNo);
            tbwBackRecD.setcOpTools(cOpTools);
            tbwBackRecD.setcOpStatus(cOpStatus);
            tbwBackRecD.setcReserved1(cReserved1);
            tbwBackRecD.setcReserved2(cReserved2);
            tbwBackRecD.setcReserved3(cReserved3);
            tbwBackRecD.setcReserved4(cReserved4);
            tbwBackRecD.setcReserved5(cReserved5);
            tbwBackRecD.setcNote(cNote);
            tbwBackRecD.setcMkUserno(cMkUserno);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            if (cMkDt != null) {
                try {
                    Date c_MkDt = sdf.parse(cMkDt);
                    tbwBackRecD.setcMkDt(c_MkDt);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            tbwBackRecD.setcModifiedUserno(cModifiedUserno);
            if (cModifiedDt != null) {
                try {
                    Date c_ModifiedDt = sdf.parse(cModifiedDt);
                    tbwBackRecD.setcModifiedDt(c_ModifiedDt);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            TdTbwBackRecDService.save(tbwBackRecD);
            TdGoods tdGoods = tdGoodsService.findByCodeAndStatus(cGcode, 1l);
            if (cRecQty == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>???</MESSAGE></STATUS></RESULTS>";
            }
            if (tdGoods == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>??" + cGcode
                        + "????</MESSAGE></STATUS></RESULTS>";
            }

        }
        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_back_rec_m"))//
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            String cWhNo = null;//?
            String cOwnerNo = null;//
            String cRecNo = null;//???
            Long cPrintTimes = null;//?
            String cBackNo = null;//???
            String cBackType = null;//???
            String cBackClass = null;//??(?)
            String cCustomerNo = null;//?
            String cPlatNo = null;//?
            String cRecUser = null;//
            String cOpTools = null;//?(?,pda,?)
            String cOpStatus = null;//??(?????)
            String cBeginDt = null;//?
            String cEndDt = null;//??
            String cNote = null;//
            String cMkUserno = null;//
            String cMkDt = null;//
            String cModifiedUserno = null;//
            String cModifiedDt = null;//
            String cPoNo = null;//?
            Long cCompanyId = null;//?Id

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();
            // ??TABLE
            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);
                if (childNode.getNodeName().equalsIgnoreCase("c_wh_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cWhNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOwnerNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cRecNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_print_times")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPrintTimes = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_back_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cBackNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_back_type")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cBackType = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_back_class")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cBackClass = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_customer_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cCustomerNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_plat_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPlatNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_rec_user")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cRecUser = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_op_tools")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOpTools = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOpStatus = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_begin_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cBeginDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_end_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cEndDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_note")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cNote = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_po_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPoNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_company_id")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cCompanyId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                }
            }
            TdTbwBackRecM tbwBackRecM = tdTbwBackRecMService.findByCRecNo(cRecNo);
            if (tbwBackRecM == null) {
                tbwBackRecM = new TdTbwBackRecM();
            }
            tbwBackRecM.setcWhNo(cWhNo);
            tbwBackRecM.setcOwnerNo(cOwnerNo);
            tbwBackRecM.setcRecNo(cRecNo);
            tbwBackRecM.setcPrintTimes(cPrintTimes);
            tbwBackRecM.setcBackNo(cBackNo);
            tbwBackRecM.setcBackType(cBackType);
            tbwBackRecM.setcBackClass(cBackClass);
            tbwBackRecM.setcCustomerNo(cCustomerNo);
            tbwBackRecM.setcPlatNo(cPlatNo);
            tbwBackRecM.setcRecUser(cRecUser);
            tbwBackRecM.setcOpTools(cOpTools);
            tbwBackRecM.setcOpStatus(cOpStatus);
            tbwBackRecM.setcBeginDt(DateFromString(cBeginDt));
            tbwBackRecM.setcEndDt(DateFromString(cEndDt));
            tbwBackRecM.setcNote(cNote);
            tbwBackRecM.setcMkUserno(cMkUserno);
            tbwBackRecM.setcMkDt(DateFromString(cMkDt));
            tbwBackRecM.setcModifiedUserno(cModifiedUserno);
            tbwBackRecM.setcModifiedDt(DateFromString(cModifiedDt));
            tbwBackRecM.setcPoNo(cPoNo);
            tbwBackRecM.setcCompanyId(cCompanyId);
            tdTbwBackRecMService.save(tbwBackRecM);
            List<TdTbwBackRecD> tbwBackRecDs = TdTbwBackRecDService.findByCRecNo(cRecNo);
            for (TdTbwBackRecD tdTbwBackRecD : tbwBackRecDs) {
                String cGcode = tdTbwBackRecD.getcGcode();
                TdDiySiteInventory inventory = tdDiySiteInventoryService
                        .findByGoodsCodeAndRegionIdAndDiySiteIdIsNull(cGcode, cCompanyId);
                if (inventory == null) {
                    return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>?" + cCompanyId
                            + "?</MESSAGE></STATUS></RESULTS>";
                }

                Double doubleFromStr = Double.parseDouble(tdTbwBackRecD.getcRecQty());
                doubleFromStr = doubleFromStr * 100;
                Long cRecQty = doubleFromStr.longValue();
                cRecQty = cRecQty / 100;
                inventory.setInventory(inventory.getInventory() - cRecQty);
                tdDiySiteInventoryService.save(inventory);
                tdDiySiteInventoryLogService.saveChangeLog(inventory, -cRecQty, null, null,
                        TdDiySiteInventoryLog.CHANGETYPE_CITY_SUB);
            }

        }
        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_om_d"))//
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            String cOwnerNo = null;//
            String cOmNo = null;//??
            Long cOmId = null;//ID
            String cOmType = null;//?()
            String cGcode = null;//?
            String cOwnerGcode = null;//?
            Long cPackQty = null;//?
            Double cQty = null;//?
            Double cWaveQty = null;//??
            Double cAckQty = null;//?
            Double cCheckQty = null;//?
            Double cPrice = null;//??
            Double cTaxRate = null;//
            String cOpStatus = null;//?(?????)
            String cItemType = null;//???????
            String cReserved1 = null;//1
            String cReserved2 = null;//2
            String cReserved3 = null;//3
            String cReserved4 = null;//4
            String cReserved5 = null;//5
            String cNote = null;//
            String cOutUserno = null;//
            String cOutDt = null;//
            String cCheckUserno = null;//
            String cCheckDt = null;//
            String cProduceDt = null;//
            String cMkUserno = null;//
            String cMkDt = null;//
            String cModifiedUserno = null;//
            String cModifiedDt = null;//
            String cUploadStatus = null;//?
            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();
            // ??TABLE
            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);
                if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOwnerNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_om_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOmNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_om_id")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOmId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_om_type")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOmType = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_gcode")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cGcode = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_gcode")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOwnerGcode = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_pack_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPackQty = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cQty = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_wave_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cWaveQty = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_ack_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cAckQty = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_check_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cCheckQty = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_price")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPrice = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_tax_rate")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cTaxRate = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOpStatus = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_item_type")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cItemType = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved1")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved1 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved2")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved2 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved3")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved3 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved4")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved4 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved5")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved5 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_note")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cNote = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_out_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOutUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_out_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOutDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_check_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cCheckUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_check_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cCheckDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_produce_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cProduceDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_upload_status")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cUploadStatus = childNode.getChildNodes().item(0).getNodeValue();
                    }
                }
            }
            TdTbOmD tbOmD = new TdTbOmD();
            tbOmD.setcOwnerNo(cOwnerNo);
            tbOmD.setcOmNo(cOmNo);
            tbOmD.setcOmId(cOmId);
            tbOmD.setcOmType(cOmType);
            tbOmD.setcGcode(cGcode);
            tbOmD.setcOwnerGcode(cOwnerGcode);
            tbOmD.setcPackQty(cPackQty);
            tbOmD.setcQty(cQty);
            tbOmD.setcWaveQty(cWaveQty);
            tbOmD.setcAckQty(cAckQty);
            tbOmD.setcCheckQty(cCheckQty);
            tbOmD.setcPrice(cPrice);
            tbOmD.setcTaxRate(cTaxRate);
            tbOmD.setcOpStatus(cOpStatus);
            tbOmD.setcItemType(cItemType);
            tbOmD.setcReserved1(cReserved1);
            tbOmD.setcReserved2(cReserved2);
            tbOmD.setcReserved3(cReserved3);
            tbOmD.setcReserved4(cReserved4);
            tbOmD.setcReserved5(cReserved5);
            tbOmD.setcNote(cNote);
            tbOmD.setcOutUserno(cOutUserno);
            tbOmD.setcOutDt(DateFromString(cOutDt));
            tbOmD.setcCheckUserno(cCheckUserno);
            tbOmD.setcCheckDt(DateFromString(cCheckDt));
            tbOmD.setcProduceDt(DateFromString(cProduceDt));
            tbOmD.setcMkUserno(cMkUserno);
            tbOmD.setcMkDt(DateFromString(cMkDt));
            tbOmD.setcModifiedUserno(cModifiedUserno);
            tbOmD.setcModifiedDt(DateFromString(cModifiedDt));
            tbOmD.setcUploadStatus(cUploadStatus);
            TdGoods tdGoods = tdGoodsService.findByCodeAndStatus(cGcode, 1l);
            if (cWaveQty == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>???</MESSAGE></STATUS></RESULTS>";
            }
            if (tdGoods == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>??" + cGcode
                        + "????</MESSAGE></STATUS></RESULTS>";
            }
            try {
                tdTbOmDService.save(tbOmD);
            } catch (Exception e) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>" + e.getMessage()
                        + "</MESSAGE></STATUS></RESULTS>";
            }
        }

        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_om_m"))//
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            String cWhNo = null;//
            String cOwnerNo = null;//
            String cOmNo = null;//??
            String cOmType = null;//?()
            String cDWhNo = null;//
            String cPoType = null;//??()
            String cPoNo = null;//??
            String cAddress = null;//?
            String cPostCode = null;//
            Double cTotalMoney = null;//?
            Double cTotalTax = null;//?
            String cUmoutDt = null;//
            String cOpStatus = null;//?(?????)
            String cCreateFlag = null;//WMS,ERP
            String cNote = null;//
            String cMkUserno = null;//
            String cMkDt = null;//
            String cModifiedUserno = null;//
            String cModifiedDt = null;//
            String cUploadStatus = null;//?
            String cUploadFilename = null;//
            Long cCompanyId = null; //id

            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();
            // ??TABLE
            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);
                if (childNode.getNodeName().equalsIgnoreCase("c_wh_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cWhNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOwnerNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_om_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOmNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_om_type")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOmType = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_d_wh_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cDWhNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_po_type")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPoType = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_po_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPoNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_address")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cAddress = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_post_code")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPostCode = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_total_money")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cTotalMoney = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_total_tax")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cTotalTax = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_umout_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cUmoutDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOpStatus = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_create_flag")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cCreateFlag = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_note")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cNote = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_upload_status")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cUploadStatus = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_upload_filename")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cUploadFilename = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_company_id")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cCompanyId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                }
            }
            TdTbOmM tbOmM = tdTbOmMService.findByCOmNo(cOmNo);
            if (tbOmM == null) {
                tbOmM = new TdTbOmM();
            }
            tbOmM.setcWhNo(cWhNo);
            tbOmM.setcOwnerNo(cOwnerNo);
            tbOmM.setcOmNo(cOmNo);
            tbOmM.setcOmType(cOmType);
            tbOmM.setcDWhNo(cDWhNo);
            tbOmM.setcPoType(cPoType);
            tbOmM.setcPoNo(cPoNo);
            tbOmM.setcAddress(cAddress);
            tbOmM.setcPostCode(cPostCode);
            tbOmM.setcTotalMoney(cTotalMoney);
            tbOmM.setcTotalTax(cTotalTax);
            tbOmM.setcUmoutDt(DateFromString(cUmoutDt));
            tbOmM.setcOpStatus(cOpStatus);
            tbOmM.setcCreateFlag(cCreateFlag);
            tbOmM.setcNote(cNote);
            tbOmM.setcMkUserno(cMkUserno);
            tbOmM.setcMkDt(DateFromString(cMkDt));
            tbOmM.setcModifiedUserno(cModifiedUserno);
            tbOmM.setcModifiedDt(DateFromString(cModifiedDt));
            tbOmM.setcUploadStatus(cUploadStatus);
            tbOmM.setcUploadFilename(cUploadFilename);
            tbOmM.setcCompanyId(cCompanyId);
            tdTbOmMService.save(tbOmM);
            if (StringUtils.isBlank(cUploadStatus)
                    || (!cUploadStatus.equalsIgnoreCase("in") && !cUploadStatus.equalsIgnoreCase("out"))) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>c_upload_status" + cUploadStatus
                        + " ?\"in\"?\"out\"</MESSAGE></STATUS></RESULTS>";
            }
            List<TdTbOmD> tbOmDs = tdTbOmDService.findByCOmNo(cOmNo);
            for (TdTbOmD tdTbOmD : tbOmDs) {
                String cGcode = tdTbOmD.getcGcode();
                TdGoods tdGoods = tdGoodsService.findByCode(cGcode);
                if (tdGoods == null) {
                    return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>??" + cGcode
                            + "????</MESSAGE></STATUS></RESULTS>";
                }
                TdCity tdCity = tdCityService.findBySobIdCity(cCompanyId);
                if (tdCity == null) {
                    return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>?" + cCompanyId
                            + "?</MESSAGE></STATUS></RESULTS>";
                }
                TdDiySiteInventory inventory = tdDiySiteInventoryService
                        .findByGoodsCodeAndRegionIdAndDiySiteIdIsNull(cGcode, cCompanyId);
                if (inventory == null) {
                    inventory = new TdDiySiteInventory();
                    inventory.setGoodsCode(tdGoods.getCode());
                    inventory.setGoodsId(tdGoods.getId());
                    inventory.setCategoryId(tdGoods.getCategoryId());
                    inventory.setCategoryIdTree(tdGoods.getCategoryIdTree());
                    inventory.setCategoryTitle(tdGoods.getCategoryTitle());
                    inventory.setGoodsTitle(tdGoods.getTitle());
                    inventory.setRegionId(cCompanyId);
                    inventory.setRegionName(tdCity.getCityName());
                }

                Double doubleFromStr = tdTbOmD.getcWaveQty();
                doubleFromStr = doubleFromStr * 100;
                Long cRecQty = doubleFromStr.longValue();
                cRecQty = cRecQty / 100;
                if (cUploadStatus.equalsIgnoreCase("in")) {
                    inventory.setInventory(inventory.getInventory() + cRecQty);
                    tdDiySiteInventoryService.save(inventory);
                    tdDiySiteInventoryLogService.saveChangeLog(inventory, cRecQty, null, null,
                            TdDiySiteInventoryLog.CHANGETYPE_CITY_YC_ADD);
                } else if (cUploadStatus.equalsIgnoreCase("out")) {
                    inventory.setInventory(inventory.getInventory() - cRecQty);
                    tdDiySiteInventoryService.save(inventory);
                    tdDiySiteInventoryLogService.saveChangeLog(inventory, -cRecQty, null, null,
                            TdDiySiteInventoryLog.CHANGETYPE_CITY_BS_SUB);
                }
            }
        }

        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    } else if (STRTABLE.equalsIgnoreCase("tbw_waste_view"))//?
    {
        for (int i = 0; i < nodeList.getLength(); i++) {
            String cWhNo = null;//??
            String cOwnerNo = null;//
            String cWasteNo = null;//???
            Long cWasteId = null;//?ID
            String cWasteType = null;//??(??)
            String cGcode = null;//?
            String cOwnerGcode = null;//?
            String cLocationNo = null;//??
            Long cStockattrId = null;//?ID
            Long cPackQty = null;//?
            Double cQty = null;//?
            String cLotNo = null;//?
            String cSpec = null;//
            String cProduceDt = null;//
            String cExpireDt = null;//
            Double cWaveQty = null;//??
            String cItemType = null;//?(??????)
            Double cAckQty = null;//??
            Double cPrice = null;//??
            Double cTaxRate = null;//
            String cOpStatus = null;//?(?????)
            String cReserved1 = null;//1
            String cReserved2 = null;//2
            String cReserved3 = null;//3
            String cReserved4 = null;//4
            String cReserved5 = null;//5
            String cNote = null;//
            String cMkUserno = null;//
            String cMkDt = null;//
            String cModifiedUserno = null;//
            String cModifiedDt = null;//
            String cUploadStatus = null;//?
            Long cCompanyId = null;//?id
            Node node = nodeList.item(i);
            NodeList childNodeList = node.getChildNodes();
            // ??TABLE
            for (int idx = 0; idx < childNodeList.getLength(); idx++) {
                Node childNode = childNodeList.item(idx);
                if (childNode.getNodeName().equalsIgnoreCase("c_wh_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cWhNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOwnerNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_waste_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cWasteNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_waste_id")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cWasteId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_waste_type")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cWasteType = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_gcode")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cGcode = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_owner_gcode")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOwnerGcode = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_location_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cLocationNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_stockattr_id")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cStockattrId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_pack_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPackQty = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cQty = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_lot_no")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cLotNo = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_spec")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cSpec = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_produce_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cProduceDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_expire_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cExpireDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_wave_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cWaveQty = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_item_type")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cItemType = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_ack_qty")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cAckQty = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_price")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cPrice = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_tax_rate")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cTaxRate = Double.parseDouble(childNode.getChildNodes().item(0).getNodeValue());
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_op_status")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cOpStatus = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved1")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved1 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved2")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved2 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved3")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved3 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved4")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved4 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_reserved5")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cReserved5 = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_note")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cNote = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_mk_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cMkDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_userno")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedUserno = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_modified_dt")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cModifiedDt = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("c_upload_status")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cUploadStatus = childNode.getChildNodes().item(0).getNodeValue();
                    }
                } else if (childNode.getNodeName().equalsIgnoreCase("C_COMPANY_ID")) {
                    if (null != childNode.getChildNodes().item(0)) {
                        cCompanyId = Long.parseLong(childNode.getChildNodes().item(0).getNodeValue());
                    }
                }
            }
            if (cWasteNo == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>????</MESSAGE></STATUS></RESULTS>";
            }
            if (cWasteId == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>???id?</MESSAGE></STATUS></RESULTS>";
            }

            TdTbwWasted tbwWasted = tdTbwWastedService.findByCWasteNoAndCWasteId(cWasteNo, cWasteId);
            if (tbwWasted != null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>???" + cWasteNo
                        + " </MESSAGE></STATUS></RESULTS>";
            }
            tbwWasted = new TdTbwWasted();
            tbwWasted.setcWhNo(cWhNo);
            tbwWasted.setcOwnerNo(cOwnerNo);
            tbwWasted.setcWasteNo(cWasteNo);
            tbwWasted.setcWasteId(cWasteId);
            tbwWasted.setcWasteType(cWasteType);
            tbwWasted.setcGcode(cGcode);
            tbwWasted.setcOwnerGcode(cOwnerGcode);
            tbwWasted.setcLocationNo(cLocationNo);
            tbwWasted.setcStockattrId(cStockattrId);
            tbwWasted.setcPackQty(cPackQty);
            tbwWasted.setcQty(cQty);
            tbwWasted.setcLotNo(cLotNo);
            tbwWasted.setcSpec(cSpec);
            tbwWasted.setcProduceDt(DateFromString(cProduceDt));
            tbwWasted.setcExpireDt(DateFromString(cExpireDt));
            tbwWasted.setcWaveQty(cWaveQty);
            tbwWasted.setcItemType(cItemType);
            tbwWasted.setcAckQty(cAckQty);
            tbwWasted.setcPrice(cPrice);
            tbwWasted.setcTaxRate(cTaxRate);
            tbwWasted.setcOpStatus(cOpStatus);
            tbwWasted.setcReserved1(cReserved1);
            tbwWasted.setcReserved2(cReserved2);
            tbwWasted.setcReserved3(cReserved3);
            tbwWasted.setcReserved4(cReserved4);
            tbwWasted.setcReserved5(cReserved5);
            tbwWasted.setcNote(cNote);
            tbwWasted.setcMkUserno(cMkUserno);
            tbwWasted.setcMkDt(DateFromString(cMkDt));
            tbwWasted.setcModifiedUserno(cModifiedUserno);
            tbwWasted.setcModifiedDt(DateFromString(cModifiedDt));
            tbwWasted.setcUploadStatus(cUploadStatus);
            tbwWasted.setcCompanyId(cCompanyId);
            tdTbwWastedService.save(tbwWasted);
            TdGoods tdGoods = tdGoodsService.findByCode(cGcode);
            if (tdGoods == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>??" + cGcode
                        + "????</MESSAGE></STATUS></RESULTS>";
            }
            TdCity tdCity = tdCityService.findBySobIdCity(cCompanyId);
            if (tdCity == null) {
                return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>?" + cCompanyId
                        + "?</MESSAGE></STATUS></RESULTS>";
            }
            TdDiySiteInventory inventory = tdDiySiteInventoryService
                    .findByGoodsCodeAndRegionIdAndDiySiteIdIsNull(cGcode, cCompanyId);
            if (inventory == null) {
                inventory = new TdDiySiteInventory();
                inventory.setGoodsCode(tdGoods.getCode());
                inventory.setGoodsId(tdGoods.getId());
                inventory.setCategoryId(tdGoods.getCategoryId());
                inventory.setCategoryIdTree(tdGoods.getCategoryIdTree());
                inventory.setCategoryTitle(tdGoods.getCategoryTitle());
                inventory.setGoodsTitle(tdGoods.getTitle());
                inventory.setRegionId(cCompanyId);
                inventory.setRegionName(tdCity.getCityName());
            }
            Double doubleFromStr = tbwWasted.getcQty();
            doubleFromStr = doubleFromStr * 100;
            Long cRecQty = doubleFromStr.longValue();
            cRecQty = cRecQty / 100;
            if (cWasteType.contains("")) {
                inventory.setInventory(inventory.getInventory() + cRecQty);
                tdDiySiteInventoryService.save(inventory);
                tdDiySiteInventoryLogService.saveChangeLog(inventory, cRecQty, null, null,
                        TdDiySiteInventoryLog.CHANGETYPE_CITY_YC_ADD);
            } else {
                inventory.setInventory(inventory.getInventory() - cRecQty);
                tdDiySiteInventoryService.save(inventory);
                tdDiySiteInventoryLogService.saveChangeLog(inventory, -cRecQty, null, null,
                        TdDiySiteInventoryLog.CHANGETYPE_CITY_BS_SUB);
            }
        }

        return "<RESULTS><STATUS><CODE>0</CODE><MESSAGE></MESSAGE></STATUS></RESULTS>";
    }
    return "<RESULTS><STATUS><CODE>1</CODE><MESSAGE>???" + STRTABLE
            + "</MESSAGE></STATUS></RESULTS>";
}

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

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean();
    final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger();
    final String userAgent = context.getProperty(USER_AGENT).getValue();

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder// ww w.  j  a  v  a2  s .  co  m
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ProcessorLog logger = getLogger();

    final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B);
    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    DestinationAccepts destinationAccepts = null;
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final ObjectHolder<String> dnHolder = new ObjectHolder<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null || destinationAccepts == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.setUserAgent(userAgent);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final X509Certificate[] certChain = sslSession.getPeerCertificateChain();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        final X509Certificate cert = certChain[0];
                        dnHolder.set(cert.getSubjectDN().getName().trim());
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            final String username = context.getProperty(USERNAME).getValue();
            final String password = context.getProperty(PASSWORD).getValue();
            // set the credentials if appropriate
            if (username != null) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                if (password == null) {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username));
                } else {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
                }
                ;
                clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
            client = clientBuilder.build();

            // determine whether or not destination accepts flowfile/gzip
            destinationAccepts = config.getDestinationAccepts();
            if (destinationAccepts == null) {
                try {
                    if (sendAsFlowFile) {
                        destinationAccepts = getDestinationAcceptance(client, url, getLogger(), transactionId);
                    } else {
                        destinationAccepts = new DestinationAccepts(false, false, false, false, null);
                    }

                    config.setDestinationAccepts(destinationAccepts);
                } catch (IOException e) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                    logger.error(
                            "Unable to communicate with destination {} to determine whether or not it can accept flowfiles/gzip; routing {} to failure due to {}",
                            new Object[] { url, flowFile, e });
                    context.yield();
                    return;
                }
            }
        }

        // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format,
        // then only use a single FlowFile
        if (!sendAsFlowFile
                || (!destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted())) {
            break;
        }

        bytesToSend += flowFile.getSize();
        if (bytesToSend > maxBatchBytes.longValue()) {
            break;
        }
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;
    final DestinationAccepts accepts = destinationAccepts;
    final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null;

    final EntityTemplate entity = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream rawOut) throws IOException {
            final OutputStream throttled = (throttler == null) ? rawOut
                    : throttler.newThrottledOutputStream(rawOut);
            OutputStream wrappedOut = new BufferedOutputStream(throttled);
            if (compressionLevel > 0 && accepts.isGzipAccepted()) {
                wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel);
            }

            try (final OutputStream out = wrappedOut) {
                for (final FlowFile flowFile : flowFileList) {
                    session.read(flowFile, new InputStreamCallback() {
                        @Override
                        public void process(final InputStream rawIn) throws IOException {
                            try (final InputStream in = new BufferedInputStream(rawIn)) {

                                FlowFilePackager packager = null;
                                if (!sendAsFlowFile) {
                                    packager = null;
                                } else if (accepts.isFlowFileV3Accepted()) {
                                    packager = new FlowFilePackagerV3();
                                } else if (accepts.isFlowFileV2Accepted()) {
                                    packager = new FlowFilePackagerV2();
                                } else if (accepts.isFlowFileV1Accepted()) {
                                    packager = new FlowFilePackagerV1();
                                }

                                // if none of the above conditions is met, we should never get here, because
                                // we will have already verified that at least 1 of the FlowFile packaging
                                // formats is acceptable if sending as FlowFile.
                                if (packager == null) {
                                    StreamUtils.copy(in, out);
                                } else {
                                    final Map<String, String> flowFileAttributes;
                                    if (isDestinationLegacyNiFi) {
                                        // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path;
                                        // in order to maintain backward compatibility, we copy the filename & path to those attribute keys.
                                        flowFileAttributes = new HashMap<>(flowFile.getAttributes());
                                        flowFileAttributes.put("nf.file.name",
                                                flowFile.getAttribute(CoreAttributes.FILENAME.key()));
                                        flowFileAttributes.put("nf.file.path",
                                                flowFile.getAttribute(CoreAttributes.PATH.key()));
                                    } else {
                                        flowFileAttributes = flowFile.getAttributes();
                                    }

                                    packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize());
                                }
                            }
                        }
                    });
                }

                out.flush();
            }
        }
    });

    entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean());
    post.setEntity(entity);
    post.setConfig(requestConfig);

    final String contentType;
    if (sendAsFlowFile) {
        if (accepts.isFlowFileV3Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V3;
        } else if (accepts.isFlowFileV2Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V2;
        } else if (accepts.isFlowFileV1Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V1;
        } else {
            logger.error(
                    "Cannot send data to {} because the destination does not accept FlowFiles and this processor is configured to deliver FlowFiles; rolling back session",
                    new Object[] { url });
            session.rollback();
            context.yield();
            return;
        }
    } else {
        final String attributeValue = toSend.get(0).getAttribute(CoreAttributes.MIME_TYPE.key());
        contentType = (attributeValue == null) ? DEFAULT_CONTENT_TYPE : attributeValue;
    }

    final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue();
    if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) {
        final Pattern pattern = Pattern.compile(attributeHeaderRegex);

        final Map<String, String> attributes = flowFileList.get(0).getAttributes();
        for (final Map.Entry<String, String> entry : attributes.entrySet()) {
            final String key = entry.getKey();
            if (pattern.matcher(key).matches()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    post.setHeader(CONTENT_TYPE, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);
    if (compressionLevel > 0 && accepts.isGzipAccepted()) {
        post.setHeader(GZIPPED_HEADER, "true");
    }

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);

        // consume input stream entirely, ignoring its contents. If we
        // don't do this, the Connection will not be returned to the pool
        EntityUtils.consume(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (final FlowFile flowFile : toSend) {
            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }
        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            EntityUtils.consume(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (FlowFile flowFile : toSend) {
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

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

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean();
    final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger();
    final String userAgent = context.getProperty(USER_AGENT).getValue();

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder/* ww  w . j ava  2 s  .  c om*/
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ProcessorLog logger = getLogger();

    final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B);
    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    DestinationAccepts destinationAccepts = null;
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final ObjectHolder<String> dnHolder = new ObjectHolder<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null || destinationAccepts == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.setUserAgent(userAgent);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final X509Certificate[] certChain = sslSession.getPeerCertificateChain();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        final X509Certificate cert = certChain[0];
                        dnHolder.set(cert.getSubjectDN().getName().trim());
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            final String username = context.getProperty(USERNAME).getValue();
            final String password = context.getProperty(PASSWORD).getValue();
            // set the credentials if appropriate
            if (username != null) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                if (password == null) {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username));
                } else {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
                }
                ;
                clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
            client = clientBuilder.build();

            // determine whether or not destination accepts flowfile/gzip
            destinationAccepts = config.getDestinationAccepts();
            if (destinationAccepts == null) {
                try {
                    if (sendAsFlowFile) {
                        destinationAccepts = getDestinationAcceptance(client, url, getLogger(), transactionId);
                    } else {
                        destinationAccepts = new DestinationAccepts(false, false, false, false, null);
                    }

                    config.setDestinationAccepts(destinationAccepts);
                } catch (IOException e) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                    logger.error(
                            "Unable to communicate with destination {} to determine whether or not it can accept flowfiles/gzip; routing {} to failure due to {}",
                            new Object[] { url, flowFile, e });
                    context.yield();
                    return;
                }
            }
        }

        // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format,
        // then only use a single FlowFile
        if (!sendAsFlowFile
                || (!destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted())) {
            break;
        }

        bytesToSend += flowFile.getSize();
        if (bytesToSend > maxBatchBytes.longValue()) {
            break;
        }
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;
    final DestinationAccepts accepts = destinationAccepts;
    final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null;

    final EntityTemplate entity = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream rawOut) throws IOException {
            final OutputStream throttled = (throttler == null) ? rawOut
                    : throttler.newThrottledOutputStream(rawOut);
            OutputStream wrappedOut = new BufferedOutputStream(throttled);
            if (compressionLevel > 0 && accepts.isGzipAccepted()) {
                wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel);
            }

            try (final OutputStream out = wrappedOut) {
                for (final FlowFile flowFile : flowFileList) {
                    session.read(flowFile, new InputStreamCallback() {
                        @Override
                        public void process(final InputStream rawIn) throws IOException {
                            try (final InputStream in = new BufferedInputStream(rawIn)) {

                                FlowFilePackager packager = null;
                                if (!sendAsFlowFile) {
                                    packager = null;
                                } else if (accepts.isFlowFileV3Accepted()) {
                                    packager = new FlowFilePackagerV3();
                                } else if (accepts.isFlowFileV2Accepted()) {
                                    packager = new FlowFilePackagerV2();
                                } else if (accepts.isFlowFileV1Accepted()) {
                                    packager = new FlowFilePackagerV1();
                                }

                                // if none of the above conditions is met, we should never get here, because
                                // we will have already verified that at least 1 of the FlowFile packaging
                                // formats is acceptable if sending as FlowFile.
                                if (packager == null) {
                                    StreamUtils.copy(in, out);
                                } else {
                                    final Map<String, String> flowFileAttributes;
                                    if (isDestinationLegacyNiFi) {
                                        // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path;
                                        // in order to maintain backward compatibility, we copy the filename & path to those attribute keys.
                                        flowFileAttributes = new HashMap<>(flowFile.getAttributes());
                                        flowFileAttributes.put("nf.file.name",
                                                flowFile.getAttribute(CoreAttributes.FILENAME.key()));
                                        flowFileAttributes.put("nf.file.path",
                                                flowFile.getAttribute(CoreAttributes.PATH.key()));
                                    } else {
                                        flowFileAttributes = flowFile.getAttributes();
                                    }

                                    packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize());
                                }
                            }
                        }
                    });
                }

                out.flush();
            }
        }
    });

    entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean());
    post.setEntity(entity);
    post.setConfig(requestConfig);

    final String contentType;
    if (sendAsFlowFile) {
        if (accepts.isFlowFileV3Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V3;
        } else if (accepts.isFlowFileV2Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V2;
        } else if (accepts.isFlowFileV1Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V1;
        } else {
            logger.error(
                    "Cannot send data to {} because the destination does not accept FlowFiles and this processor is configured to deliver FlowFiles; rolling back session",
                    new Object[] { url });
            session.rollback();
            context.yield();
            return;
        }
    } else {
        final String attributeValue = toSend.get(0).getAttribute(CoreAttributes.MIME_TYPE.key());
        contentType = (attributeValue == null) ? DEFAULT_CONTENT_TYPE : attributeValue;
    }

    final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue();
    if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) {
        final Pattern pattern = Pattern.compile(attributeHeaderRegex);

        final Map<String, String> attributes = flowFileList.get(0).getAttributes();
        for (final Map.Entry<String, String> entry : attributes.entrySet()) {
            final String key = entry.getKey();
            if (pattern.matcher(key).matches()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    post.setHeader(CONTENT_TYPE, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);
    if (compressionLevel > 0 && accepts.isGzipAccepted()) {
        post.setHeader(GZIPPED_HEADER, "true");
    }

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    String responseContent;

    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);
        responseContent = EntityUtils.toString(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (FlowFile flowFile : toSend) {

            flowFile = this.setHttpPostResponse(context, session, responseContent, flowFile);

            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }

        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            responseContent = EntityUtils.toString(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (FlowFile flowFile : toSend) {
                flowFile = this.setHttpPostResponse(context, session, responseContent, flowFile);
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

From source file:org.apache.nifi.processors.standard.PostHTTP.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean();
    final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger();
    final String userAgent = context.getProperty(USER_AGENT).getValue();

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder//from   w  ww.  j  av a 2 s  .c  o m
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ComponentLog logger = getLogger();

    final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B);
    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    DestinationAccepts destinationAccepts = null;
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final AtomicReference<String> dnHolder = new AtomicReference<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null || destinationAccepts == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.setUserAgent(userAgent);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    final ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    final SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final Certificate[] certChain = sslSession.getPeerCertificates();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        try {
                            final X509Certificate cert = CertificateUtils
                                    .convertAbstractX509Certificate(certChain[0]);
                            dnHolder.set(cert.getSubjectDN().getName().trim());
                        } catch (CertificateException e) {
                            final String msg = "Could not extract subject DN from SSL session peer certificate";
                            logger.warn(msg);
                            throw new SSLPeerUnverifiedException(msg);
                        }
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            final String username = context.getProperty(USERNAME).getValue();
            final String password = context.getProperty(PASSWORD).getValue();
            // set the credentials if appropriate
            if (username != null) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                if (password == null) {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username));
                } else {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
                }
                clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }

            // Set the proxy if specified
            if (context.getProperty(PROXY_HOST).isSet() && context.getProperty(PROXY_PORT).isSet()) {
                final String host = context.getProperty(PROXY_HOST).getValue();
                final int port = context.getProperty(PROXY_PORT).asInteger();
                clientBuilder.setProxy(new HttpHost(host, port));
            }

            client = clientBuilder.build();

            // determine whether or not destination accepts flowfile/gzip
            destinationAccepts = config.getDestinationAccepts();
            if (destinationAccepts == null) {
                try {
                    destinationAccepts = getDestinationAcceptance(sendAsFlowFile, client, url, getLogger(),
                            transactionId);
                    config.setDestinationAccepts(destinationAccepts);
                } catch (final IOException e) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                    logger.error(
                            "Unable to communicate with destination {} to determine whether or not it can accept "
                                    + "flowfiles/gzip; routing {} to failure due to {}",
                            new Object[] { url, flowFile, e });
                    context.yield();
                    return;
                }
            }
        }

        bytesToSend += flowFile.getSize();
        if (bytesToSend > maxBatchBytes.longValue()) {
            break;
        }

        // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format,
        // then only use a single FlowFile
        if (!sendAsFlowFile
                || !destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted()) {
            break;
        }
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;
    final DestinationAccepts accepts = destinationAccepts;
    final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null;

    final EntityTemplate entity = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream rawOut) throws IOException {
            final OutputStream throttled = throttler == null ? rawOut
                    : throttler.newThrottledOutputStream(rawOut);
            OutputStream wrappedOut = new BufferedOutputStream(throttled);
            if (compressionLevel > 0 && accepts.isGzipAccepted()) {
                wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel);
            }

            try (final OutputStream out = wrappedOut) {
                for (final FlowFile flowFile : flowFileList) {
                    session.read(flowFile, new InputStreamCallback() {
                        @Override
                        public void process(final InputStream rawIn) throws IOException {
                            try (final InputStream in = new BufferedInputStream(rawIn)) {

                                FlowFilePackager packager = null;
                                if (!sendAsFlowFile) {
                                    packager = null;
                                } else if (accepts.isFlowFileV3Accepted()) {
                                    packager = new FlowFilePackagerV3();
                                } else if (accepts.isFlowFileV2Accepted()) {
                                    packager = new FlowFilePackagerV2();
                                } else if (accepts.isFlowFileV1Accepted()) {
                                    packager = new FlowFilePackagerV1();
                                }

                                // if none of the above conditions is met, we should never get here, because
                                // we will have already verified that at least 1 of the FlowFile packaging
                                // formats is acceptable if sending as FlowFile.
                                if (packager == null) {
                                    StreamUtils.copy(in, out);
                                } else {
                                    final Map<String, String> flowFileAttributes;
                                    if (isDestinationLegacyNiFi) {
                                        // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path;
                                        // in order to maintain backward compatibility, we copy the filename & path to those attribute keys.
                                        flowFileAttributes = new HashMap<>(flowFile.getAttributes());
                                        flowFileAttributes.put("nf.file.name",
                                                flowFile.getAttribute(CoreAttributes.FILENAME.key()));
                                        flowFileAttributes.put("nf.file.path",
                                                flowFile.getAttribute(CoreAttributes.PATH.key()));
                                    } else {
                                        flowFileAttributes = flowFile.getAttributes();
                                    }

                                    packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize());
                                }
                            }
                        }
                    });
                }

                out.flush();
            }
        }
    }) {

        @Override
        public long getContentLength() {
            if (compressionLevel == 0 && !sendAsFlowFile
                    && !context.getProperty(CHUNKED_ENCODING).asBoolean()) {
                return toSend.get(0).getSize();
            } else {
                return -1;
            }
        }
    };

    if (context.getProperty(CHUNKED_ENCODING).isSet()) {
        entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean());
    }
    post.setEntity(entity);
    post.setConfig(requestConfig);

    final String contentType;
    if (sendAsFlowFile) {
        if (accepts.isFlowFileV3Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V3;
        } else if (accepts.isFlowFileV2Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V2;
        } else if (accepts.isFlowFileV1Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V1;
        } else {
            logger.error(
                    "Cannot send data to {} because the destination does not accept FlowFiles and this processor is "
                            + "configured to deliver FlowFiles; rolling back session",
                    new Object[] { url });
            session.rollback();
            context.yield();
            IOUtils.closeQuietly(client);
            return;
        }
    } else {
        final String contentTypeValue = context.getProperty(CONTENT_TYPE)
                .evaluateAttributeExpressions(toSend.get(0)).getValue();
        contentType = StringUtils.isBlank(contentTypeValue) ? DEFAULT_CONTENT_TYPE : contentTypeValue;
    }

    final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue();
    if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) {
        final Pattern pattern = Pattern.compile(attributeHeaderRegex);

        final Map<String, String> attributes = flowFileList.get(0).getAttributes();
        for (final Map.Entry<String, String> entry : attributes.entrySet()) {
            final String key = entry.getKey();
            if (pattern.matcher(key).matches()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    post.setHeader(CONTENT_TYPE_HEADER, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);
    if (compressionLevel > 0 && accepts.isGzipAccepted()) {
        if (sendAsFlowFile) {
            post.setHeader(GZIPPED_HEADER, "true");
        } else {
            post.setHeader(CONTENT_ENCODING_HEADER, CONTENT_ENCODING_GZIP_VALUE);
        }
    }

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);

        // consume input stream entirely, ignoring its contents. If we
        // don't do this, the Connection will not be returned to the pool
        EntityUtils.consume(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (final IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, "
                                + "since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (final FlowFile flowFile : toSend) {
            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }
        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            EntityUtils.consume(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (final FlowFile flowFile : toSend) {
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

From source file:org.apache.solr.client.solrj.io.stream.StreamExpressionTest.java

@Test
public void testSubFacetStream() throws Exception {

    new UpdateRequest().add(id, "0", "level1_s", "hello0", "level2_s", "a", "a_i", "0", "a_f", "1")
            .add(id, "2", "level1_s", "hello0", "level2_s", "a", "a_i", "2", "a_f", "2")
            .add(id, "3", "level1_s", "hello3", "level2_s", "a", "a_i", "3", "a_f", "3")
            .add(id, "4", "level1_s", "hello4", "level2_s", "a", "a_i", "4", "a_f", "4")
            .add(id, "1", "level1_s", "hello0", "level2_s", "b", "a_i", "1", "a_f", "5")
            .add(id, "5", "level1_s", "hello3", "level2_s", "b", "a_i", "10", "a_f", "6")
            .add(id, "6", "level1_s", "hello4", "level2_s", "b", "a_i", "11", "a_f", "7")
            .add(id, "7", "level1_s", "hello3", "level2_s", "b", "a_i", "12", "a_f", "8")
            .add(id, "8", "level1_s", "hello3", "level2_s", "b", "a_i", "13", "a_f", "9")
            .add(id, "9", "level1_s", "hello0", "level2_s", "b", "a_i", "14", "a_f", "10")
            .commit(cluster.getSolrClient(), COLLECTIONORALIAS);

    String clause;/*from  www  .j a  va  2 s .  co  m*/
    TupleStream stream;
    List<Tuple> tuples;

    StreamFactory factory = new StreamFactory()
            .withCollectionZkHost("collection1", cluster.getZkServer().getZkAddress())
            .withFunctionName("facet", FacetStream.class).withFunctionName("sum", SumMetric.class)
            .withFunctionName("min", MinMetric.class).withFunctionName("max", MaxMetric.class)
            .withFunctionName("avg", MeanMetric.class).withFunctionName("count", CountMetric.class);

    // Basic test
    clause = "facet(" + "collection1, " + "q=\"*:*\", " + "buckets=\"level1_s, level2_s\", "
            + "bucketSorts=\"sum(a_i) desc, sum(a_i) desc)\", " + "bucketSizeLimit=100, " + "sum(a_i), count(*)"
            + ")";

    stream = factory.constructStream(clause);
    tuples = getTuples(stream);

    assert (tuples.size() == 6);

    Tuple tuple = tuples.get(0);
    String bucket1 = tuple.getString("level1_s");
    String bucket2 = tuple.getString("level2_s");
    Double sumi = tuple.getDouble("sum(a_i)");
    Double count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello3"));
    assertTrue(bucket2.equals("b"));
    assertTrue(sumi.longValue() == 35);
    assertTrue(count.doubleValue() == 3);

    tuple = tuples.get(1);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello0"));
    assertTrue(bucket2.equals("b"));
    assertTrue(sumi.longValue() == 15);
    assertTrue(count.doubleValue() == 2);

    tuple = tuples.get(2);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello4"));
    assertTrue(bucket2.equals("b"));
    assertTrue(sumi.longValue() == 11);
    assertTrue(count.doubleValue() == 1);

    tuple = tuples.get(3);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello4"));
    assertTrue(bucket2.equals("a"));
    assertTrue(sumi.longValue() == 4);
    assertTrue(count.doubleValue() == 1);

    tuple = tuples.get(4);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello3"));
    assertTrue(bucket2.equals("a"));
    assertTrue(sumi.longValue() == 3);
    assertTrue(count.doubleValue() == 1);

    tuple = tuples.get(5);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello0"));
    assertTrue(bucket2.equals("a"));
    assertTrue(sumi.longValue() == 2);
    assertTrue(count.doubleValue() == 2);

    clause = "facet(" + "collection1, " + "q=\"*:*\", " + "buckets=\"level1_s, level2_s\", "
            + "bucketSorts=\"level1_s desc, level2_s desc)\", " + "bucketSizeLimit=100, " + "sum(a_i), count(*)"
            + ")";

    stream = factory.constructStream(clause);
    tuples = getTuples(stream);

    assert (tuples.size() == 6);

    tuple = tuples.get(0);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello4"));
    assertTrue(bucket2.equals("b"));
    assertTrue(sumi.longValue() == 11);
    assertTrue(count.doubleValue() == 1);

    tuple = tuples.get(1);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello4"));
    assertTrue(bucket2.equals("a"));
    assertTrue(sumi.longValue() == 4);
    assertTrue(count.doubleValue() == 1);

    tuple = tuples.get(2);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello3"));
    assertTrue(bucket2.equals("b"));
    assertTrue(sumi.longValue() == 35);
    assertTrue(count.doubleValue() == 3);

    tuple = tuples.get(3);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello3"));
    assertTrue(bucket2.equals("a"));
    assertTrue(sumi.longValue() == 3);
    assertTrue(count.doubleValue() == 1);

    tuple = tuples.get(4);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello0"));
    assertTrue(bucket2.equals("b"));
    assertTrue(sumi.longValue() == 15);
    assertTrue(count.doubleValue() == 2);

    tuple = tuples.get(5);
    bucket1 = tuple.getString("level1_s");
    bucket2 = tuple.getString("level2_s");
    sumi = tuple.getDouble("sum(a_i)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket1.equals("hello0"));
    assertTrue(bucket2.equals("a"));
    assertTrue(sumi.longValue() == 2);
    assertTrue(count.doubleValue() == 2);
}

From source file:org.apache.solr.client.solrj.io.stream.StreamExpressionTest.java

@Test
public void testStatsStream() throws Exception {

    new UpdateRequest().add(id, "0", "a_s", "hello0", "a_i", "0", "a_f", "1")
            .add(id, "2", "a_s", "hello0", "a_i", "2", "a_f", "2")
            .add(id, "3", "a_s", "hello3", "a_i", "3", "a_f", "3")
            .add(id, "4", "a_s", "hello4", "a_i", "4", "a_f", "4")
            .add(id, "1", "a_s", "hello0", "a_i", "1", "a_f", "5")
            .add(id, "5", "a_s", "hello3", "a_i", "10", "a_f", "6")
            .add(id, "6", "a_s", "hello4", "a_i", "11", "a_f", "7")
            .add(id, "7", "a_s", "hello3", "a_i", "12", "a_f", "8")
            .add(id, "8", "a_s", "hello3", "a_i", "13", "a_f", "9")
            .add(id, "9", "a_s", "hello0", "a_i", "14", "a_f", "10")
            .commit(cluster.getSolrClient(), COLLECTIONORALIAS);

    StreamFactory factory = new StreamFactory()
            .withCollectionZkHost(COLLECTIONORALIAS, cluster.getZkServer().getZkAddress())
            .withFunctionName("stats", StatsStream.class).withFunctionName("sum", SumMetric.class)
            .withFunctionName("min", MinMetric.class).withFunctionName("max", MaxMetric.class)
            .withFunctionName("avg", MeanMetric.class).withFunctionName("count", CountMetric.class);

    StreamExpression expression;//  ww w  .  jav  a  2s.  co m
    TupleStream stream;
    List<Tuple> tuples;
    StreamContext streamContext = new StreamContext();
    SolrClientCache cache = new SolrClientCache();
    try {
        streamContext.setSolrClientCache(cache);
        String expr = "stats(" + COLLECTIONORALIAS
                + ", q=*:*, sum(a_i), sum(a_f), min(a_i), min(a_f), max(a_i), max(a_f), avg(a_i), avg(a_f), count(*))";
        expression = StreamExpressionParser.parse(expr);
        stream = factory.constructStream(expression);
        stream.setStreamContext(streamContext);

        tuples = getTuples(stream);

        assert (tuples.size() == 1);

        //Test Long and Double Sums

        Tuple tuple = tuples.get(0);

        Double sumi = tuple.getDouble("sum(a_i)");
        Double sumf = tuple.getDouble("sum(a_f)");
        Double mini = tuple.getDouble("min(a_i)");
        Double minf = tuple.getDouble("min(a_f)");
        Double maxi = tuple.getDouble("max(a_i)");
        Double maxf = tuple.getDouble("max(a_f)");
        Double avgi = tuple.getDouble("avg(a_i)");
        Double avgf = tuple.getDouble("avg(a_f)");
        Double count = tuple.getDouble("count(*)");

        assertTrue(sumi.longValue() == 70);
        assertTrue(sumf.doubleValue() == 55.0D);
        assertTrue(mini.doubleValue() == 0.0D);
        assertTrue(minf.doubleValue() == 1.0D);
        assertTrue(maxi.doubleValue() == 14.0D);
        assertTrue(maxf.doubleValue() == 10.0D);
        assertTrue(avgi.doubleValue() == 7.0D);
        assertTrue(avgf.doubleValue() == 5.5D);
        assertTrue(count.doubleValue() == 10);

        //Test with shards parameter
        List<String> shardUrls = TupleStream.getShards(cluster.getZkServer().getZkAddress(), COLLECTIONORALIAS,
                streamContext);
        expr = "stats(myCollection, q=*:*, sum(a_i), sum(a_f), min(a_i), min(a_f), max(a_i), max(a_f), avg(a_i), avg(a_f), count(*))";
        Map<String, List<String>> shardsMap = new HashMap();
        shardsMap.put("myCollection", shardUrls);
        StreamContext context = new StreamContext();
        context.put("shards", shardsMap);
        context.setSolrClientCache(cache);
        stream = factory.constructStream(expr);
        stream.setStreamContext(context);

        tuples = getTuples(stream);

        assert (tuples.size() == 1);

        //Test Long and Double Sums

        tuple = tuples.get(0);

        sumi = tuple.getDouble("sum(a_i)");
        sumf = tuple.getDouble("sum(a_f)");
        mini = tuple.getDouble("min(a_i)");
        minf = tuple.getDouble("min(a_f)");
        maxi = tuple.getDouble("max(a_i)");
        maxf = tuple.getDouble("max(a_f)");
        avgi = tuple.getDouble("avg(a_i)");
        avgf = tuple.getDouble("avg(a_f)");
        count = tuple.getDouble("count(*)");

        assertTrue(sumi.longValue() == 70);
        assertTrue(sumf.doubleValue() == 55.0D);
        assertTrue(mini.doubleValue() == 0.0D);
        assertTrue(minf.doubleValue() == 1.0D);
        assertTrue(maxi.doubleValue() == 14.0D);
        assertTrue(maxf.doubleValue() == 10.0D);
        assertTrue(avgi.doubleValue() == 7.0D);
        assertTrue(avgf.doubleValue() == 5.5D);
        assertTrue(count.doubleValue() == 10);

        //Execersise the /stream hander

        //Add the shards http parameter for the myCollection
        StringBuilder buf = new StringBuilder();
        for (String shardUrl : shardUrls) {
            if (buf.length() > 0) {
                buf.append(",");
            }
            buf.append(shardUrl);
        }

        ModifiableSolrParams solrParams = new ModifiableSolrParams();
        solrParams.add("qt", "/stream");
        solrParams.add("expr", expr);
        solrParams.add("myCollection.shards", buf.toString());
        SolrStream solrStream = new SolrStream(shardUrls.get(0), solrParams);
        tuples = getTuples(solrStream);
        assert (tuples.size() == 1);

        tuple = tuples.get(0);

        sumi = tuple.getDouble("sum(a_i)");
        sumf = tuple.getDouble("sum(a_f)");
        mini = tuple.getDouble("min(a_i)");
        minf = tuple.getDouble("min(a_f)");
        maxi = tuple.getDouble("max(a_i)");
        maxf = tuple.getDouble("max(a_f)");
        avgi = tuple.getDouble("avg(a_i)");
        avgf = tuple.getDouble("avg(a_f)");
        count = tuple.getDouble("count(*)");

        assertTrue(sumi.longValue() == 70);
        assertTrue(sumf.doubleValue() == 55.0D);
        assertTrue(mini.doubleValue() == 0.0D);
        assertTrue(minf.doubleValue() == 1.0D);
        assertTrue(maxi.doubleValue() == 14.0D);
        assertTrue(maxf.doubleValue() == 10.0D);
        assertTrue(avgi.doubleValue() == 7.0D);
        assertTrue(avgf.doubleValue() == 5.5D);
        assertTrue(count.doubleValue() == 10);
        //Add a negative test to prove that it cannot find slices if shards parameter is removed

        try {
            ModifiableSolrParams solrParamsBad = new ModifiableSolrParams();
            solrParamsBad.add("qt", "/stream");
            solrParamsBad.add("expr", expr);
            solrStream = new SolrStream(shardUrls.get(0), solrParamsBad);
            tuples = getTuples(solrStream);
            throw new Exception("Exception should have been thrown above");
        } catch (IOException e) {
            assertTrue(e.getMessage().contains("Collection not found: myCollection"));
        }
    } finally {
        cache.close();
    }
}

From source file:org.apache.solr.client.solrj.io.stream.StreamExpressionTest.java

@Test
public void testFacetStream() throws Exception {

    new UpdateRequest().add(id, "0", "a_s", "hello0", "a_i", "0", "a_f", "1")
            .add(id, "2", "a_s", "hello0", "a_i", "2", "a_f", "2")
            .add(id, "3", "a_s", "hello3", "a_i", "3", "a_f", "3")
            .add(id, "4", "a_s", "hello4", "a_i", "4", "a_f", "4")
            .add(id, "1", "a_s", "hello0", "a_i", "1", "a_f", "5")
            .add(id, "5", "a_s", "hello3", "a_i", "10", "a_f", "6")
            .add(id, "6", "a_s", "hello4", "a_i", "11", "a_f", "7")
            .add(id, "7", "a_s", "hello3", "a_i", "12", "a_f", "8")
            .add(id, "8", "a_s", "hello3", "a_i", "13", "a_f", "9")
            .add(id, "9", "a_s", "hello0", "a_i", "14", "a_f", "10")
            .commit(cluster.getSolrClient(), COLLECTIONORALIAS);

    String clause;/*from  w  ww  . ja v a 2  s.  co  m*/
    TupleStream stream;
    List<Tuple> tuples;

    StreamFactory factory = new StreamFactory()
            .withCollectionZkHost("collection1", cluster.getZkServer().getZkAddress())
            .withFunctionName("facet", FacetStream.class).withFunctionName("sum", SumMetric.class)
            .withFunctionName("min", MinMetric.class).withFunctionName("max", MaxMetric.class)
            .withFunctionName("avg", MeanMetric.class).withFunctionName("count", CountMetric.class);

    // Basic test
    clause = "facet(" + "collection1, " + "q=\"*:*\", " + "fl=\"a_s,a_i,a_f\", " + "sort=\"a_s asc\", "
            + "buckets=\"a_s\", " + "bucketSorts=\"sum(a_i) asc\", " + "bucketSizeLimit=100, "
            + "sum(a_i), sum(a_f), " + "min(a_i), min(a_f), " + "max(a_i), max(a_f), " + "avg(a_i), avg(a_f), "
            + "count(*)" + ")";

    stream = factory.constructStream(clause);
    tuples = getTuples(stream);

    assert (tuples.size() == 3);

    //Test Long and Double Sums

    Tuple tuple = tuples.get(0);
    String bucket = tuple.getString("a_s");
    Double sumi = tuple.getDouble("sum(a_i)");
    Double sumf = tuple.getDouble("sum(a_f)");
    Double mini = tuple.getDouble("min(a_i)");
    Double minf = tuple.getDouble("min(a_f)");
    Double maxi = tuple.getDouble("max(a_i)");
    Double maxf = tuple.getDouble("max(a_f)");
    Double avgi = tuple.getDouble("avg(a_i)");
    Double avgf = tuple.getDouble("avg(a_f)");
    Double count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello4"));
    assertTrue(sumi.longValue() == 15);
    assertTrue(sumf.doubleValue() == 11.0D);
    assertTrue(mini.doubleValue() == 4.0D);
    assertTrue(minf.doubleValue() == 4.0D);
    assertTrue(maxi.doubleValue() == 11.0D);
    assertTrue(maxf.doubleValue() == 7.0D);
    assertTrue(avgi.doubleValue() == 7.5D);
    assertTrue(avgf.doubleValue() == 5.5D);
    assertTrue(count.doubleValue() == 2);

    tuple = tuples.get(1);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello0"));
    assertTrue(sumi.doubleValue() == 17.0D);
    assertTrue(sumf.doubleValue() == 18.0D);
    assertTrue(mini.doubleValue() == 0.0D);
    assertTrue(minf.doubleValue() == 1.0D);
    assertTrue(maxi.doubleValue() == 14.0D);
    assertTrue(maxf.doubleValue() == 10.0D);
    assertTrue(avgi.doubleValue() == 4.25D);
    assertTrue(avgf.doubleValue() == 4.5D);
    assertTrue(count.doubleValue() == 4);

    tuple = tuples.get(2);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello3"));
    assertTrue(sumi.doubleValue() == 38.0D);
    assertTrue(sumf.doubleValue() == 26.0D);
    assertTrue(mini.doubleValue() == 3.0D);
    assertTrue(minf.doubleValue() == 3.0D);
    assertTrue(maxi.doubleValue() == 13.0D);
    assertTrue(maxf.doubleValue() == 9.0D);
    assertTrue(avgi.doubleValue() == 9.5D);
    assertTrue(avgf.doubleValue() == 6.5D);
    assertTrue(count.doubleValue() == 4);

    //Reverse the Sort.

    clause = "facet(" + "collection1, " + "q=\"*:*\", " + "fl=\"a_s,a_i,a_f\", " + "sort=\"a_s asc\", "
            + "buckets=\"a_s\", " + "bucketSorts=\"sum(a_i) desc\", " + "bucketSizeLimit=100, "
            + "sum(a_i), sum(a_f), " + "min(a_i), min(a_f), " + "max(a_i), max(a_f), " + "avg(a_i), avg(a_f), "
            + "count(*)" + ")";

    stream = factory.constructStream(clause);
    tuples = getTuples(stream);

    //Test Long and Double Sums

    tuple = tuples.get(0);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello3"));
    assertTrue(sumi.doubleValue() == 38.0D);
    assertTrue(sumf.doubleValue() == 26.0D);
    assertTrue(mini.doubleValue() == 3.0D);
    assertTrue(minf.doubleValue() == 3.0D);
    assertTrue(maxi.doubleValue() == 13.0D);
    assertTrue(maxf.doubleValue() == 9.0D);
    assertTrue(avgi.doubleValue() == 9.5D);
    assertTrue(avgf.doubleValue() == 6.5D);
    assertTrue(count.doubleValue() == 4);

    tuple = tuples.get(1);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello0"));
    assertTrue(sumi.doubleValue() == 17.0D);
    assertTrue(sumf.doubleValue() == 18.0D);
    assertTrue(mini.doubleValue() == 0.0D);
    assertTrue(minf.doubleValue() == 1.0D);
    assertTrue(maxi.doubleValue() == 14.0D);
    assertTrue(maxf.doubleValue() == 10.0D);
    assertTrue(avgi.doubleValue() == 4.25D);
    assertTrue(avgf.doubleValue() == 4.5D);
    assertTrue(count.doubleValue() == 4);

    tuple = tuples.get(2);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello4"));
    assertTrue(sumi.longValue() == 15);
    assertTrue(sumf.doubleValue() == 11.0D);
    assertTrue(mini.doubleValue() == 4.0D);
    assertTrue(minf.doubleValue() == 4.0D);
    assertTrue(maxi.doubleValue() == 11.0D);
    assertTrue(maxf.doubleValue() == 7.0D);
    assertTrue(avgi.doubleValue() == 7.5D);
    assertTrue(avgf.doubleValue() == 5.5D);
    assertTrue(count.doubleValue() == 2);

    //Test index sort
    clause = "facet(" + "collection1, " + "q=\"*:*\", " + "fl=\"a_s,a_i,a_f\", " + "sort=\"a_s asc\", "
            + "buckets=\"a_s\", " + "bucketSorts=\"a_s desc\", " + "bucketSizeLimit=100, "
            + "sum(a_i), sum(a_f), " + "min(a_i), min(a_f), " + "max(a_i), max(a_f), " + "avg(a_i), avg(a_f), "
            + "count(*)" + ")";

    stream = factory.constructStream(clause);
    tuples = getTuples(stream);

    assert (tuples.size() == 3);

    tuple = tuples.get(0);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello4"));
    assertTrue(sumi.longValue() == 15);
    assertTrue(sumf.doubleValue() == 11.0D);
    assertTrue(mini.doubleValue() == 4.0D);
    assertTrue(minf.doubleValue() == 4.0D);
    assertTrue(maxi.doubleValue() == 11.0D);
    assertTrue(maxf.doubleValue() == 7.0D);
    assertTrue(avgi.doubleValue() == 7.5D);
    assertTrue(avgf.doubleValue() == 5.5D);
    assertTrue(count.doubleValue() == 2);

    tuple = tuples.get(1);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello3"));
    assertTrue(sumi.doubleValue() == 38.0D);
    assertTrue(sumf.doubleValue() == 26.0D);
    assertTrue(mini.doubleValue() == 3.0D);
    assertTrue(minf.doubleValue() == 3.0D);
    assertTrue(maxi.doubleValue() == 13.0D);
    assertTrue(maxf.doubleValue() == 9.0D);
    assertTrue(avgi.doubleValue() == 9.5D);
    assertTrue(avgf.doubleValue() == 6.5D);
    assertTrue(count.doubleValue() == 4);

    tuple = tuples.get(2);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello0"));
    assertTrue(sumi.doubleValue() == 17.0D);
    assertTrue(sumf.doubleValue() == 18.0D);
    assertTrue(mini.doubleValue() == 0.0D);
    assertTrue(minf.doubleValue() == 1.0D);
    assertTrue(maxi.doubleValue() == 14.0D);
    assertTrue(maxf.doubleValue() == 10.0D);
    assertTrue(avgi.doubleValue() == 4.25D);
    assertTrue(avgf.doubleValue() == 4.5D);
    assertTrue(count.doubleValue() == 4);

    //Test index sort

    clause = "facet(" + "collection1, " + "q=\"*:*\", " + "fl=\"a_s,a_i,a_f\", " + "sort=\"a_s asc\", "
            + "buckets=\"a_s\", " + "bucketSorts=\"a_s asc\", " + "bucketSizeLimit=100, "
            + "sum(a_i), sum(a_f), " + "min(a_i), min(a_f), " + "max(a_i), max(a_f), " + "avg(a_i), avg(a_f), "
            + "count(*)" + ")";

    stream = factory.constructStream(clause);
    tuples = getTuples(stream);

    assert (tuples.size() == 3);

    tuple = tuples.get(0);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello0"));
    assertTrue(sumi.doubleValue() == 17.0D);
    assertTrue(sumf.doubleValue() == 18.0D);
    assertTrue(mini.doubleValue() == 0.0D);
    assertTrue(minf.doubleValue() == 1.0D);
    assertTrue(maxi.doubleValue() == 14.0D);
    assertTrue(maxf.doubleValue() == 10.0D);
    assertTrue(avgi.doubleValue() == 4.25D);
    assertTrue(avgf.doubleValue() == 4.5D);
    assertTrue(count.doubleValue() == 4);

    tuple = tuples.get(1);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello3"));
    assertTrue(sumi.doubleValue() == 38.0D);
    assertTrue(sumf.doubleValue() == 26.0D);
    assertTrue(mini.doubleValue() == 3.0D);
    assertTrue(minf.doubleValue() == 3.0D);
    assertTrue(maxi.doubleValue() == 13.0D);
    assertTrue(maxf.doubleValue() == 9.0D);
    assertTrue(avgi.doubleValue() == 9.5D);
    assertTrue(avgf.doubleValue() == 6.5D);
    assertTrue(count.doubleValue() == 4);

    tuple = tuples.get(2);
    bucket = tuple.getString("a_s");
    sumi = tuple.getDouble("sum(a_i)");
    sumf = tuple.getDouble("sum(a_f)");
    mini = tuple.getDouble("min(a_i)");
    minf = tuple.getDouble("min(a_f)");
    maxi = tuple.getDouble("max(a_i)");
    maxf = tuple.getDouble("max(a_f)");
    avgi = tuple.getDouble("avg(a_i)");
    avgf = tuple.getDouble("avg(a_f)");
    count = tuple.getDouble("count(*)");

    assertTrue(bucket.equals("hello4"));
    assertTrue(sumi.longValue() == 15);
    assertTrue(sumf.doubleValue() == 11.0D);
    assertTrue(mini.doubleValue() == 4.0D);
    assertTrue(minf.doubleValue() == 4.0D);
    assertTrue(maxi.doubleValue() == 11.0D);
    assertTrue(maxf.doubleValue() == 7.0D);
    assertTrue(avgi.doubleValue() == 7.5D);
    assertTrue(avgf.doubleValue() == 5.5D);
    assertTrue(count.doubleValue() == 2);

    //Test zero result facets
    clause = "facet(" + "collection1, " + "q=\"blahhh\", " + "fl=\"a_s,a_i,a_f\", " + "sort=\"a_s asc\", "
            + "buckets=\"a_s\", " + "bucketSorts=\"a_s asc\", " + "bucketSizeLimit=100, "
            + "sum(a_i), sum(a_f), " + "min(a_i), min(a_f), " + "max(a_i), max(a_f), " + "avg(a_i), avg(a_f), "
            + "count(*)" + ")";

    stream = factory.constructStream(clause);
    tuples = getTuples(stream);

    assert (tuples.size() == 0);

}