Example usage for java.util Map clear

List of usage examples for java.util Map clear

Introduction

In this page you can find the example usage for java.util Map clear.

Prototype

void clear();

Source Link

Document

Removes all of the mappings from this map (optional operation).

Usage

From source file:com.linkedin.pinot.queries.QueriesSentinelTest.java

@Test
public void testAggregation() throws Exception {
    int counter = 0;
    final Map<ServerInstance, DataTable> instanceResponseMap = new HashMap<ServerInstance, DataTable>();
    final List<TestSimpleAggreationQuery> aggCalls = AVRO_QUERY_GENERATOR
            .giveMeNSimpleAggregationQueries(10000);
    for (final TestSimpleAggreationQuery aggCall : aggCalls) {
        LOGGER.info("running " + counter + " : " + aggCall.pql);
        final BrokerRequest brokerRequest = REQUEST_COMPILER.compileToBrokerRequest(aggCall.pql);
        InstanceRequest instanceRequest = new InstanceRequest(counter++, brokerRequest);
        instanceRequest.setSearchSegments(new ArrayList<String>());
        instanceRequest.getSearchSegments().add(segmentName);
        QueryRequest queryRequest = new QueryRequest(instanceRequest);
        final DataTable instanceResponse = QUERY_EXECUTOR.processQuery(queryRequest);
        instanceResponseMap.clear();
        instanceResponseMap.put(new ServerInstance("localhost:0000"), instanceResponse);
        final BrokerResponseNative brokerResponse = REDUCE_SERVICE.reduceOnDataTable(brokerRequest,
                instanceResponseMap);/*from  ww  w.ja v  a 2s  .c  om*/
        LOGGER.info("BrokerResponse is " + brokerResponse.getAggregationResults().get(0));
        LOGGER.info("Result from avro is : " + aggCall.result);
        Assert.assertEquals(
                Double.parseDouble(brokerResponse.getAggregationResults().get(0).getValue().toString()),
                aggCall.result);
    }
}

From source file:com.netsteadfast.greenstep.bsc.service.logic.impl.EmployeeLogicServiceImpl.java

@ServiceMethodAuthority(type = { ServiceMethodType.DELETE })
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { RuntimeException.class,
        IOException.class, Exception.class })
@Override/*from  www . ja v a 2s  .co m*/
public DefaultResult<Boolean> delete(EmployeeVO employee) throws ServiceException, Exception {
    if (employee == null || super.isBlank(employee.getOid())) {
        throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
    }
    employee = this.findEmployeeData(employee.getOid());
    AccountVO account = this.findAccountData(employee.getAccount());
    if (this.isAdministrator(account.getAccount())) {
        throw new ServiceException("Administrator cannot delete!");
    }

    // check account data for other table use.
    this.checkInformationRelated(account, employee);

    this.deleteEmployeeOrganization(employee);

    // delete user role
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("account", account.getAccount());
    List<TbUserRole> userRoles = this.getUserRoleService().findListByParams(params);
    for (int i = 0; userRoles != null && i < userRoles.size(); i++) {
        TbUserRole uRole = userRoles.get(i);
        this.getUserRoleService().delete(uRole);
    }

    // delete BB_REPORT_ROLE_VIEW
    params.clear();
    params.put("idName", account.getAccount());
    List<BbReportRoleView> reportRoleViews = this.reportRoleViewService.findListByParams(params);
    for (int i = 0; reportRoleViews != null && i < reportRoleViews.size(); i++) {
        BbReportRoleView reportRoleView = reportRoleViews.get(i);
        this.reportRoleViewService.delete(reportRoleView);
    }

    // delete from BB_MEASURE_DATA where EMP_ID = :empId
    this.measureDataService.deleteForEmpId(employee.getEmpId());

    this.monitorItemScoreService.deleteForEmpId(employee.getEmpId());

    this.deleteHierarchy(employee);

    this.getAccountService().deleteByPKng(account.getOid());
    return getEmployeeService().deleteObject(employee);
}

From source file:com.uber.stream.kafka.chaperone.collector.reporter.DbAuditReporter.java

public Map<String, Map<Integer, Long>> getOffsetsToStart() {
    Connection conn = null;/* ww w .j a va 2  s  .  c om*/
    PreparedStatement stmt = null;
    ResultSet rs = null;
    Map<String, Map<Integer, Long>> topicOffsetsMap = new HashMap<>();
    try {
        conn = getConnection();
        stmt = conn.prepareStatement(String.format(GET_OFFSETS_SQL, offsetTableName));
        rs = stmt.executeQuery();
        while (rs.next()) {
            String topicName = rs.getString("topic_name");
            Map<Integer, Long> offsets = topicOffsetsMap.get(topicName);
            if (offsets == null) {
                offsets = new HashMap<>();
                topicOffsetsMap.put(topicName, offsets);
            }
            offsets.put(rs.getInt("partition_id"), rs.getLong("offset"));
        }
    } catch (SQLException e) {
        logger.warn("Could not get offsets from database", e);
        topicOffsetsMap.clear();
    } finally {
        closeDbResource(rs, stmt, conn);
    }
    return topicOffsetsMap;
}

From source file:com.osafe.services.OsafePayPalServices.java

public static Map<String, Object> getExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();

    ShoppingCart cart = (ShoppingCart) context.get("cart");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
        /*            return ServiceUtil.returnError(UtilProperties.getMessage(resource, 
            "AccountingPayPalPaymentGatewayConfigCannotFind", locale));*/
        return ServiceUtil.returnError(
                "Couldn't retrieve a PaymentGatewayConfigPayPal record for Express Checkout, cannot continue.");
    }//from w w w. j ava 2s. com

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "GetExpressCheckoutDetails");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
        encoder.add("TOKEN", token);
    } else {
        /*            return ServiceUtil.returnError(UtilProperties.getMessage(resource, 
            "AccountingPayPalTokenNotFound", locale));*/
        return ServiceUtil
                .returnError("Express Checkout token not present in cart, cannot get checkout details.");
    }

    NVPDecoder decoder;
    try {
        decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    if (UtilValidate.isNotEmpty(decoder.get("NOTE"))) {
        cart.addOrderNote(decoder.get("NOTE"));
    }

    if (cart.getUserLogin() == null) {
        try {
            GenericValue userLogin = delegator.findOne("UserLogin", false, "userLoginId", "anonymous");
            try {
                cart.setUserLogin(userLogin, dispatcher);
            } catch (CartItemModifyException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    boolean anon = "anonymous".equals(cart.getUserLogin().getString("userLoginId"));
    // Even if anon, a party could already have been created
    String partyId = cart.getOrderPartyId();
    if (partyId == null && anon) {
        // Check nothing has been set on the anon userLogin either
        partyId = cart.getUserLogin() != null ? cart.getUserLogin().getString("partyId") : null;
        cart.setOrderPartyId(partyId);
    }
    if (partyId != null) {
        GenericValue party = null;
        try {
            party = delegator.findOne("Party", false, "partyId", partyId);
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (party == null) {
            partyId = null;
        }
    }

    Map<String, Object> inMap = FastMap.newInstance();
    Map<String, Object> outMap = null;
    // Create the person if necessary
    boolean newParty = false;
    if (partyId == null) {
        newParty = true;
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("personalTitle", decoder.get("SALUTATION"));
        inMap.put("firstName", decoder.get("FIRSTNAME"));
        inMap.put("middleName", decoder.get("MIDDLENAME"));
        inMap.put("lastName", decoder.get("LASTNAME"));
        inMap.put("suffix", decoder.get("SUFFIX"));
        try {
            outMap = dispatcher.runSync("createPerson", inMap);
            partyId = (String) outMap.get("partyId");
            cart.setOrderPartyId(partyId);
            cart.getUserLogin().setString("partyId", partyId);
            inMap.clear();
            inMap.put("userLogin", cart.getUserLogin());
            inMap.put("partyId", partyId);
            inMap.put("roleTypeId", "CUSTOMER");
            dispatcher.runSync("createPartyRole", inMap);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    // Create a new email address if necessary
    String emailContactMechId = null;
    String emailContactPurposeTypeId = "PRIMARY_EMAIL";
    String emailAddress = decoder.get("EMAIL");
    if (!newParty) {
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(
                EntityCondition.makeCondition(
                        UtilMisc.toMap("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS")),
                EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"),
                        EntityComparisonOperator.EQUALS, EntityFunction.UPPER(emailAddress)),
                EntityUtil.getFilterByDateExpr()

        ));
        try {
            GenericValue matchingEmail = EntityUtil.getFirst(delegator.findList("PartyAndContactMech", cond,
                    null, UtilMisc.toList("fromDate"), null, false));
            if (matchingEmail != null) {
                emailContactMechId = matchingEmail.getString("contactMechId");
            } else {
                // No email found so we'll need to create one but first check if it should be PRIMARY or just BILLING
                cond = EntityCondition.makeCondition(UtilMisc.toList(
                        EntityCondition.makeCondition(UtilMisc.toMap("partyId", partyId, "contactMechTypeId",
                                "EMAIL_ADDRESS", "contactMechPurposeTypeId", "PRIMARY_EMAIL")),
                        EntityCondition.makeConditionDate("contactFromDate", "contactThruDate"),
                        EntityCondition.makeConditionDate("purposeFromDate", "purposeThruDate")));
                List<GenericValue> primaryEmails = delegator.findList("PartyContactWithPurpose", cond, null,
                        null, null, false);
                if (UtilValidate.isNotEmpty(primaryEmails))
                    emailContactPurposeTypeId = "BILLING_EMAIL";
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (emailContactMechId == null) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechPurposeTypeId", emailContactPurposeTypeId);
        inMap.put("emailAddress", emailAddress);
        inMap.put("partyId", partyId);
        inMap.put("roleTypeId", "CUSTOMER");
        inMap.put("verified", "Y"); // Going to assume PayPal has taken care of this for us
        inMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyEmailAddress", inMap);
            emailContactMechId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    cart.addContactMech("ORDER_EMAIL", emailContactMechId);

    // Phone number
    String phoneNumber = decoder.get("PHONENUM");
    String phoneContactId = null;
    if (phoneNumber != null) {
        inMap.clear();
        if (phoneNumber.startsWith("+")) {
            // International, format is +XXX XXXXXXXX which we'll split into countryCode + contactNumber
            String[] phoneNumbers = phoneNumber.split(" ");
            inMap.put("countryCode", StringUtil.removeNonNumeric(phoneNumbers[0]));
            inMap.put("contactNumber", phoneNumbers[1]);
        } else {
            // U.S., format is XXX-XXX-XXXX which we'll split into areaCode + contactNumber
            inMap.put("countryCode", "1");
            String[] phoneNumbers = phoneNumber.split("-");
            inMap.put("areaCode", phoneNumbers[0]);
            inMap.put("contactNumber", phoneNumbers[1] + phoneNumbers[2]);
        }
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("partyId", partyId);
        try {
            outMap = dispatcher.runSync("createUpdatePartyTelecomNumber", inMap);
            phoneContactId = (String) outMap.get("contactMechId");
            cart.addContactMech("PHONE_BILLING", phoneContactId);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
        }
    }
    // Create a new Postal Address if necessary
    String postalContactId = null;
    boolean needsShippingPurpose = true;
    // if the cart for some reason already has a billing address, we'll leave it be
    boolean needsBillingPurpose = (cart.getContactMech("BILLING_LOCATION") == null);
    Map<String, Object> postalMap = FastMap.newInstance();
    postalMap.put("toName", decoder.get("SHIPTONAME"));
    postalMap.put("address1", decoder.get("SHIPTOSTREET"));
    postalMap.put("address2", decoder.get("SHIPTOSTREET2"));
    postalMap.put("city", decoder.get("SHIPTOCITY"));
    String countryGeoId = OsafePayPalServices.getCountryGeoIdFromGeoCode(decoder.get("SHIPTOCOUNTRYCODE"),
            delegator);
    postalMap.put("countryGeoId", countryGeoId);
    postalMap.put("stateProvinceGeoId",
            parseStateProvinceGeoId(decoder.get("SHIPTOSTATE"), countryGeoId, delegator));
    postalMap.put("postalCode", decoder.get("SHIPTOZIP"));
    if (!newParty) {
        // We want an exact match only
        EntityCondition cond = EntityCondition
                .makeCondition(UtilMisc.toList(EntityCondition.makeCondition(postalMap),
                        EntityCondition.makeCondition(UtilMisc.toMap("attnName", null, "directions", null,
                                "postalCodeExt", null, "postalCodeGeoId", null)),
                        EntityUtil.getFilterByDateExpr(), EntityCondition.makeCondition("partyId", partyId)));
        try {
            GenericValue postalMatch = EntityUtil.getFirst(delegator.findList("PartyAndPostalAddress", cond,
                    null, UtilMisc.toList("fromDate"), null, false));
            if (postalMatch != null) {
                postalContactId = postalMatch.getString("contactMechId");
                EntityCondition purposeCond = EntityCondition.makeCondition(UtilMisc.toList(
                        EntityCondition.makeCondition(
                                UtilMisc.toMap("partyId", partyId, "contactMechId", postalContactId)),
                        EntityUtil.getFilterByDateExpr()));
                List<GenericValue> postalPurposes = delegator.findList("PartyContactMechPurpose", purposeCond,
                        null, null, null, false);
                List<Object> purposeStrings = EntityUtil.getFieldListFromEntityList(postalPurposes,
                        "contactMechPurposeTypeId", false);
                if (UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("SHIPPING_LOCATION")) {
                    needsShippingPurpose = false;
                }
                if (needsBillingPurpose && UtilValidate.isNotEmpty(purposeStrings)
                        && purposeStrings.contains("BILLING_LOCATION")) {
                    needsBillingPurpose = false;
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (postalContactId == null) {
        postalMap.put("userLogin", cart.getUserLogin());
        postalMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyPostalAddress", postalMap);
            postalContactId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    if (needsShippingPurpose || needsBillingPurpose) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechId", postalContactId);
        inMap.put("partyId", partyId);
        try {
            if (needsShippingPurpose) {
                inMap.put("contactMechPurposeTypeId", "SHIPPING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
            if (needsBillingPurpose) {
                inMap.put("contactMechPurposeTypeId", "BILLING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
        } catch (GenericServiceException e) {
            // Not the end of the world, we'll carry on
            Debug.logInfo(e.getMessage(), module);
        }
    }

    // Load the selected shipping method - thanks to PayPal's less than sane API all we've to work with is the shipping option label
    // that was shown to the customer
    String shipMethod = decoder.get("SHIPPINGOPTIONNAME");
    Debug.log("gotPayPalShipMethod" + shipMethod, module);
    if (UtilValidate.isNotEmpty(shipMethod)) {
        if ("Calculated Offline".equals(shipMethod)) {
            cart.setCarrierPartyId("_NA_");
            cart.setShipmentMethodTypeId("NO_SHIPPING");
        } else {
            String[] shipMethodSplit = shipMethod.split(" - ");
            cart.setCarrierPartyId(shipMethodSplit[0]);
            String shippingMethodTypeDesc = StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length);
            try {
                EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toMap("productStoreId",
                        cart.getProductStoreId(), "partyId", shipMethodSplit[0], "roleTypeId", "CARRIER",
                        "description", shippingMethodTypeDesc));
                GenericValue shipmentMethod = EntityUtil.getFirst(
                        delegator.findList("ProductStoreShipmentMethView", cond, null, null, null, false));
                cart.setShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId"));
            } catch (GenericEntityException e1) {
                Debug.logError(e1, module);
            }
        }
        Debug.log("gotShipMethod" + shipMethod, module);
    }
    //Get rid of any excess ship groups
    List<CartShipInfo> shipGroups = cart.getShipGroups();
    for (int i = 1; i < shipGroups.size(); i++) {
        Map<ShoppingCartItem, BigDecimal> items = cart.getShipGroupItems(i);
        for (Map.Entry<ShoppingCartItem, BigDecimal> entry : items.entrySet()) {
            cart.positionItemToGroup(entry.getKey(), entry.getValue(), i, 0, false);
        }
    }
    cart.cleanUpShipGroups();
    cart.setShippingContactMechId(postalContactId);
    Map<String, Object> result = ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0);
    if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
        return ServiceUtil.returnError((String) result.get(ModelService.ERROR_MESSAGE));
    }

    BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
    if (shippingTotal == null) {
        shippingTotal = BigDecimal.ZERO;
    }
    cart.setItemShipGroupEstimate(shippingTotal, 0);
    CheckOutHelper cho = new CheckOutHelper(dispatcher, delegator, cart);
    try {
        cho.calcAndAddTax();
    } catch (GeneralException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    // Create the PayPal payment method
    inMap.clear();
    inMap.put("userLogin", cart.getUserLogin());
    inMap.put("partyId", partyId);
    inMap.put("contactMechId", postalContactId);
    inMap.put("fromDate", UtilDateTime.nowTimestamp());
    inMap.put("payerId", decoder.get("PAYERID"));
    inMap.put("expressCheckoutToken", token);
    inMap.put("payerStatus", decoder.get("PAYERSTATUS"));

    try {
        outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    String paymentMethodId = (String) outMap.get("paymentMethodId");

    cart.clearPayments();
    BigDecimal maxAmount = cart.getGrandTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    cart.addPaymentAmount(paymentMethodId, maxAmount, true);

    return ServiceUtil.returnSuccess();

}

From source file:com.zimbra.cs.zimlet.ZimletUtil.java

/**
 *
 * Load all the Zimlets found in the directory.
 *
 * @param zimlets - Zimlet cache/*  w w  w  .  j a  va2s. com*/
 * @param dir - directory
 */
private static void loadZimletsFromDir(Map<String, ZimletFile> zimlets, String dir) {
    File zimletRootDir = new File(dir);
    if (zimletRootDir == null || !zimletRootDir.exists() || !zimletRootDir.isDirectory()) {
        return;
    }

    ZimbraLog.zimlet.debug("Loading zimlets from " + zimletRootDir.getPath());

    synchronized (zimlets) {
        zimlets.clear();
        String[] zimletNames = zimletRootDir.list();
        assert (zimletNames != null);
        for (int i = 0; i < zimletNames.length; i++) {
            if (zimletNames[i].equals(ZIMLET_DEV_DIR)) {
                continue;
            }
            try {
                zimlets.put(zimletNames[i], new ZimletFile(zimletRootDir, zimletNames[i]));
            } catch (Exception e) {
                ZimbraLog.zimlet.warn("error loading zimlet " + zimletNames[i], e);
            }
        }
    }
}

From source file:io.cloudslang.lang.runtime.steps.ExecutableSteps.java

public void startExecutable(@Param(ScoreLangConstants.EXECUTABLE_INPUTS_KEY) List<Input> executableInputs,
        @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv,
        @Param(ScoreLangConstants.USER_INPUTS_KEY) Map<String, ? extends Serializable> userInputs,
        @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices,
        @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName,
        @Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId) {
    try {//from  ww w  .j ava 2s.  com
        //         runEnv.getExecutionPath().forward(); // Start with 1 for consistency
        Map<String, Serializable> callArguments = runEnv.removeCallArguments();

        if (userInputs != null) {
            callArguments.putAll(userInputs);
        }
        Map<String, Serializable> executableContext = inputsBinding.bindInputs(executableInputs, callArguments,
                runEnv.getSystemProperties());

        Map<String, Serializable> actionArguments = new HashMap<>();

        //todo: clone action context before updating
        actionArguments.putAll(executableContext);

        //done with the user inputs, don't want it to be available in next startExecutable steps..
        if (userInputs != null) {
            userInputs.clear();
        }

        //todo: hook

        updateCallArgumentsAndPushContextToStack(runEnv, new Context(executableContext), actionArguments);

        sendBindingInputsEvent(executableInputs, executableContext, runEnv, executionRuntimeServices,
                "Post Input binding for operation/flow", nodeName, LanguageEventData.levelName.EXECUTABLE_NAME);

        // put the next step position for the navigation
        runEnv.putNextStepPosition(nextStepId);
        runEnv.getExecutionPath().down();
    } catch (RuntimeException e) {
        logger.error("There was an error running the start executable execution step of: \'" + nodeName
                + "\'.\n\tError is: " + e.getMessage());
        throw new RuntimeException("Error running: \'" + nodeName + "\'.\n\t " + e.getMessage(), e);
    }
}

From source file:com.cy.driver.service.impl.DriverUserCargoInfoServiceImpl.java

public String cargoInfoRemind(Map<String, String> mapPar) {
    JSONObject json = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    String driverId = mapPar.get("driverId");
    Map<String, Object> nearByMap;
    Map<String, Object> businessMap;
    Map<String, Object> lineMap;

    Map<String, Object> locationMap = driverUserCargoInfoDao.selectDriverLastLocation(driverId);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("nearByModifyTime", mapPar.get("nearByModifyTime"));
    if (locationMap != null) {
        if (locationMap.containsKey("province")) {
            map.put("startProvince", locationMap.get("province"));
        }/* w w w  .jav  a2s. c o m*/
        if (locationMap.containsKey("city")) {
            map.put("startCity", locationMap.get("city"));
        }
    }
    nearByMap = orderCargoInfoDao.selectNearByCargoRemid(map);
    String nearByNum = nearByMap.get("nearByNum").toString();
    String nearByTime = nearByMap.get("nearByTime") == null ? "" : nearByMap.get("nearByTime").toString();

    json.accumulate("nearByNum", nearByNum);
    json.accumulate("nearByTime", nearByTime);

    jsonArray.add(json);
    json.clear();

    map.clear();
    map.put("businesslineModifyTime", mapPar.get("businesslineModifyTime"));
    List<DriverBusinessLineInfoDomain> list = driverBusinessLineInfoService
            .selectDriverBusinessLineInfoList(driverId);
    String currDate = DateUtil.getNowStr();
    if (list != null) {
        for (int i = 0; i < list.size(); i++) {
            DriverBusinessLineInfoDomain e = list.get(i);
            map.put("startProvice" + (i + 1), e.getStartProvince());
            map.put("startCity" + (i + 1), e.getStartCity());
            map.put("endProvince" + (i + 1), e.getEndProvince());
            map.put("endCity" + (i + 1), e.getEndCity());
            String st = e.getStartTime();
            if (DateUtil.isEarly(st, currDate)) {
                st = currDate;
            }
            map.put("startTime" + (i + 1), st);
            map.put("endTime" + (i + 1), e.getEndTime());
        }
    }

    businessMap = orderCargoInfoDao.selectBusinesslineCargoRemid(map);
    String businesslineNum = businessMap.get("businesslineNum").toString();
    String businesslineTime = businessMap.get("businesslineTime") == null ? ""
            : businessMap.get("businesslineTime").toString();

    json.accumulate("businesslineNum", businesslineNum);
    json.accumulate("businesslineTime", businesslineTime);

    jsonArray.add(json);
    json.clear();

    map.clear();
    map.put("driverLineModifyTime", mapPar.get("driverLineModifyTime"));
    @SuppressWarnings("unchecked")
    List<DriverLineInfoDomain> listLine = (List<DriverLineInfoDomain>) driverLineInfoService
            .selectDriverLineInfoList(driverId);
    if (listLine != null) {
        for (int i = 0; i < listLine.size(); i++) {
            DriverLineInfoDomain e = listLine.get(i);
            map.put("startProvice" + (i + 1), e.getStartProvince());
            map.put("startCity" + (i + 1), e.getStartCity());
            map.put("endProvince" + (i + 1), e.getEndProvince());
            map.put("endCity" + (i + 1), e.getEndCity());
        }
    }
    lineMap = orderCargoInfoDao.selectNeededCargoRemid(map);
    String driverLineNum = lineMap.get("driverLineNum").toString();
    String driverLineTime = lineMap.get("driverLineTime") == null ? ""
            : lineMap.get("driverLineTime").toString();

    json.accumulate("driverLineNum", driverLineNum);
    json.accumulate("driverLineTime", driverLineTime);

    jsonArray.add(json);
    json.clear();

    return jsonArray.toString();
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * /*  w w w.  j  a va 2s. c  o  m*/
 */
public Agent(String propFileName) throws Exception {

    //------------
    //-- ??
    //------------

    //???
    AgentProperties.init(propFileName);

    // ?IP????
    getAgentInfo();
    m_log.info(getAgentStr());

    // log4j???
    String log4jFileName = System.getProperty("hinemos.agent.conf.dir") + File.separator + "log4j.properties";
    m_log.info("log4j.properties = " + log4jFileName);
    m_log4jFileName = log4jFileName;

    int connectTimeout = DEFAULT_CONNECT_TIMEOUT;
    int requestTimeout = DEFAULT_REQUEST_TIMEOUT;

    // 
    String proxyHost = DEFAULT_PROXY_HOST;
    int proxyPort = DEFAULT_PROXY_PORT;
    String proxyUser = DEFAULT_PROXY_USER;
    String proxyPassword = DEFAULT_PROXY_PASSWORD;

    // ???hostnameVerifier?HTTPS????
    try {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, javax.net.ssl.SSLSession session) {
                return true;
            }
        };

        // Create the trust manager.
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        class AllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                    throws java.security.cert.CertificateException {
                return;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                    throws java.security.cert.CertificateException {
                return;
            }
        }
        javax.net.ssl.TrustManager tm = new AllTrustManager();
        trustAllCerts[0] = tm;
        // Create the SSL context
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        // Create the session context
        javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
        // Initialize the contexts; the session context takes the
        // trust manager.
        sslsc.setSessionTimeout(0);
        sc.init(null, trustAllCerts, null);
        // Use the default socket factory to create the socket for
        // the secure
        // connection
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Set the default host name verifier to enable the connection.
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

    } catch (Throwable e) {
        m_log.warn("hostname verifier (all trust) disable : " + e.getMessage(), e);
    }

    try {
        String strConnect = AgentProperties.getProperty("connect.timeout");
        if (strConnect != null) {
            connectTimeout = Integer.parseInt(strConnect);
        }
        String strRequest = AgentProperties.getProperty("request.timeout");
        if (strRequest != null) {
            requestTimeout = Integer.parseInt(strRequest);
        }
        String strProxyHost = AgentProperties.getProperty("http.proxy.host");
        if (strProxyHost != null) {
            proxyHost = strProxyHost;
        }
        String strProxyPort = AgentProperties.getProperty("http.proxy.port");
        if (strProxyPort != null) {
            proxyPort = Integer.parseInt(strProxyPort);
        }
        String strProxyUser = AgentProperties.getProperty("http.proxy.user");
        if (strProxyUser != null) {
            proxyUser = strProxyUser;
        }
        String strProxyPassword = AgentProperties.getProperty("http.proxy.password");
        if (strProxyPassword != null) {
            proxyPassword = strProxyPassword;
        }
    } catch (Exception e) {
        m_log.warn(e.getMessage());
    }

    if (!"".equals(proxyHost)) {
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", Integer.toString(proxyPort));
        BasicAuth basicAuth = new BasicAuth(proxyUser, proxyPassword);
        Authenticator.setDefault(basicAuth);
        m_log.info("proxy.host=" + System.getProperty("http.proxyHost") + ", proxy.port="
                + System.getProperty("http.proxyPort") + ", proxy.user=" + proxyUser);
    }

    // ?? ${ManagerIP} ?????????????
    // ??PING????????IP????FacilityID??????
    String managerAddress = AgentProperties.getProperty("managerAddress");
    URL url = new URL(managerAddress);
    boolean replacePropFileSuccess = true;
    String errMsg = "";
    if (REPLACE_VALUE_MANAGER_IP.equals((url.getHost()))) {
        try {

            // ???PING?????PING???????
            Map<String, String> discoveryInfoMap = new HashMap<String, String>();
            while (true) {
                m_log.info("waiting for manager connection...");
                String recvMsg = receiveManagerDiscoveryInfo();

                // ????key=value,key=value ??????Map??
                try {
                    discoveryInfoMap.clear();
                    String[] commaSplittedRecvMsgArray = recvMsg.split(",");
                    for (String keyvalueset : commaSplittedRecvMsgArray) {
                        String key = keyvalueset.split("=")[0];
                        String value = keyvalueset.split("=")[1];
                        discoveryInfoMap.put(key, value);
                    }
                } catch (Exception e) {
                    m_log.error("can't parse receive message : " + e.toString());
                    continue;
                }
                if (discoveryInfoMap.containsKey("agentFacilityId")
                        && discoveryInfoMap.containsKey("managerIp")) {
                    break;
                } else {
                    m_log.error("receive message is invalid");
                }
            }
            // Agent.properties?????????????
            {
                String managerIp = discoveryInfoMap.get("managerIp");
                String key = "managerAddress";
                String value = url.getProtocol() + "://" + managerIp + ":" + url.getPort() + "/HinemosWS/";
                m_log.info("Rewrite property. key : " + key + ", value : " + value);
                PropertiesFileUtil.replacePropertyFile(propFileName, key, managerAddress, value);
                AgentProperties.setProperty(key, value);
            }

            // Agent.properties?ID??????????
            {
                String key = "facilityId";
                String value = discoveryInfoMap.get("agentFacilityId");
                m_log.info("Rewrite property. key : " + key + ", value : " + value);
                PropertiesFileUtil.replacePropertyFile(propFileName, key, "", value);
                AgentProperties.setProperty(key, value);
            }

            // log4j.properties?????Windows??
            {
                String managerIp = discoveryInfoMap.get("managerIp");
                String key = "log4j.appender.syslog.SyslogHost";
                PropertiesFileUtil.replacePropertyFile(log4jFileName, "log4j.appender.syslog.SyslogHost",
                        REPLACE_VALUE_MANAGER_IP, managerIp);
                if (REPLACE_VALUE_MANAGER_IP.equals(AgentProperties.getProperty(key))) {
                    m_log.info("Rewrite property. key : " + key + ", value : " + managerIp);
                    PropertiesFileUtil.replacePropertyFile(log4jFileName, key, REPLACE_VALUE_MANAGER_IP,
                            managerIp);
                }
            }
        } catch (HinemosUnknown e) {
            // ????????????
            errMsg = e.getMessage();
            m_log.warn(errMsg, e);
            replacePropFileSuccess = false;
        } catch (Exception e) {
            m_log.warn(e.getMessage(), e);
            throw e;
        }
    }

    try {
        EndpointManager.init(AgentProperties.getProperty("user"), AgentProperties.getProperty("password"),
                AgentProperties.getProperty("managerAddress"), connectTimeout, requestTimeout);
    } catch (Exception e) {
        m_log.error("EndpointManager.init error : " + e.getMessage(), e);
        m_log.error("current-dir=" + (new File(".")).getAbsoluteFile().getParent());
        throw e;
    }

    if (!replacePropFileSuccess) {
        OutputBasicInfo output = new OutputBasicInfo();
        output.setPluginId("AGT_UPDATE_CONFFILE");
        output.setPriority(PriorityConstant.TYPE_WARNING);
        output.setApplication(MessageConstant.AGENT.getMessage());
        String[] args = { errMsg };
        output.setMessage(MessageConstant.MESSAGE_AGENT_REPLACE_FILE_FAULURE_NOTIFY_MSG.getMessage());
        output.setMessageOrg(
                MessageConstant.MESSAGE_AGENT_REPLACE_FILE_FAULURE_NOTIFY_ORIGMSG.getMessage(args));
        output.setGenerationDate(HinemosTime.getDateInstance().getTime());
        output.setMonitorId("SYS");
        output.setFacilityId(""); // ???
        output.setScopeText(""); // ???
        m_sendQueue.put(output);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            terminate();
            m_log.info("Hinemos agent stopped");
        }
    });
}

From source file:fll.web.playoff.JsonBracketDataTests.java

/**
 * Test score repression, aka not showing unverified scores and not showing
 * finals info./*from   ww  w  . j a va  2s .  c om*/
 */
@Test
public void testScoreRepression() throws SQLException, ParseException, IOException, InstantiationException,
        ClassNotFoundException, IllegalAccessException {
    final PlayoffContainer playoff = makePlayoffs();

    /*
     * Initial bracket order:
     * 
     * 1A
     * BYE
     * 
     * 4D
     * 5E
     * 
     * 3C
     * 6F
     * 
     * BYE
     * 2B
     */

    // Start with adding some scores
    insertScore(playoff.getConnection(), 4, 1, false, 5D);
    // See what json tells us
    Map<Integer, Integer> query = new HashMap<Integer, Integer>();
    // Ask for round 1 leaf 1
    int row = playoff.getBracketData().getRowNumberForLine(1, 3);
    query.put(row, 1);
    final ObjectMapper jsonMapper = new ObjectMapper();

    String jsonOut = JsonUtilities.generateJsonBracketInfo(playoff.getDivision(), query,
            playoff.getConnection(), playoff.getDescription().getPerformance(), playoff.getBracketData(),
            SHOW_ONLY_VERIFIED, SHOW_FINAL_ROUNDS);
    List<BracketLeafResultSet> result = jsonMapper.readValue(jsonOut,
            BracketLeafResultSetTypeInformation.INSTANCE);

    // assert score is -1, indicating no score
    Assert.assertEquals(result.get(0).score, -1.0D, 0.0);

    // test to make sure 2 unverified scores for opposing teams produces no
    // result
    // give opponent a score
    insertScore(playoff.getConnection(), 5, 1, false, 20D);
    query.clear();

    // ask for round we just entered score for
    row = playoff.getBracketData().getRowNumberForLine(2, 2);
    query.put(row, 2);
    jsonOut = JsonUtilities.generateJsonBracketInfo(playoff.getDivision(), query, playoff.getConnection(),
            playoff.getDescription().getPerformance(), playoff.getBracketData(), SHOW_ONLY_VERIFIED,
            SHOW_FINAL_ROUNDS);
    result = jsonMapper.readValue(jsonOut, BracketLeafResultSetTypeInformation.INSTANCE);
    Assert.assertEquals(result.get(0).leaf.getTeam().getTeamNumber(), Team.NULL_TEAM_NUMBER);

    // verify a score that has been entered as unverified and make sure we
    // get data from it
    // verify 4,1 and 5,1
    verifyScore(playoff.getConnection(), 4, 1);
    verifyScore(playoff.getConnection(), 5, 1);

    row = playoff.getBracketData().getRowNumberForLine(1, 3);
    query.put(row, 1);
    jsonOut = JsonUtilities.generateJsonBracketInfo(playoff.getDivision(), query, playoff.getConnection(),
            playoff.getDescription().getPerformance(), playoff.getBracketData(), SHOW_ONLY_VERIFIED,
            SHOW_FINAL_ROUNDS);
    result = jsonMapper.readValue(jsonOut, BracketLeafResultSetTypeInformation.INSTANCE);
    Assert.assertEquals(result.get(0).score, 5D, 0.0);

    // advance 1 and 6 all the way to finals
    insertScore(playoff.getConnection(), 3, 1, true, 5D);
    insertScore(playoff.getConnection(), 6, 1, true, 50D);

    insertScore(playoff.getConnection(), 5, 2, true, 5D);
    insertScore(playoff.getConnection(), 1, 2, true, 10D);

    insertScore(playoff.getConnection(), 2, 2, true, 5D);
    insertScore(playoff.getConnection(), 6, 2, true, 10D);

    // score finals bit
    insertScore(playoff.getConnection(), 1, 3, true, 99D);
    insertScore(playoff.getConnection(), 6, 3, true, 5D);

    // json shouldn't tell us the score for the finals round
    query.clear();
    final int finalsRound = playoff.getBracketData().getFinalsRound();
    row = playoff.getBracketData().getRowNumberForLine(finalsRound + 1, 1);
    query.put(row, finalsRound + 1);
    jsonOut = JsonUtilities.generateJsonBracketInfo(playoff.getDivision(), query, playoff.getConnection(),
            playoff.getDescription().getPerformance(), playoff.getBracketData(), SHOW_ONLY_VERIFIED,
            SHOW_FINAL_ROUNDS);
    result = jsonMapper.readValue(jsonOut, BracketLeafResultSetTypeInformation.INSTANCE);
    Assert.assertEquals(result.get(0).score, -1.0D, 0.0);

    SQLFunctions.close(playoff.getConnection());
}

From source file:com.adaptris.http.HttpRequest.java

/**
 * <p>/*from  w  w  w .j  ava2  s.  c o  m*/
 * Returns a <code>Map</code> of the query parameters.  This implementation 
 * doesn't handle URL encoding (e.g. spaces) due to lack of time.
 * </p>
 * @return a <code>Map</code> of the query parameters
 */
public Map getParameters() {
    Map result = new HashMap();

    if (uri.indexOf("?") > -1) { // uri contains params
        int start = uri.indexOf("?") + 1;
        int end = uri.indexOf("#");

        if (end == -1) { // uri doesn't contain reference
            end = uri.length();
        }

        StringTokenizer params = new StringTokenizer(uri.substring(start, end), "&");

        while (params.hasMoreTokens()) {
            String param = params.nextToken();

            // at least three chars... 
            if (param.length() > 2) {
                // and contain equals but not first or last char
                if (param.indexOf("=") > -1 && param.indexOf("=") != 0
                        && param.indexOf("=") != param.length() - 1) {

                    String key = param.substring(0, param.indexOf("="));
                    String value = param.substring(param.indexOf("=") + 1);

                    result.put(key, value);
                }
            } else { // no equals return empty Map
                result.clear();
                break;
            }
        }
    }

    return result;
}