Example usage for java.util Map equals

List of usage examples for java.util Map equals

Introduction

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

Prototype

boolean equals(Object o);

Source Link

Document

Compares the specified object with this map for equality.

Usage

From source file:org.apache.nifi.processors.attributes.UpdateAttribute.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();
    final Criteria criteria = criteriaCache.get();

    FlowFile incomingFlowFile = session.get();
    if (incomingFlowFile == null) {
        return;//from   w  ww .j  a v a 2 s. c o m
    }

    // record which rule should be applied to which flow file - when operating
    // in 'use clone' mode, this collection will contain a number of entries
    // that map to single element lists. this is because the original flowfile
    // is cloned for each matching rule. in 'use original' mode, this collection
    // will contain a single entry that maps a list of multiple rules. this is
    // because is the original flowfile is used for all matching rules. in this
    // case the order of the matching rules is preserved in the list
    final Map<FlowFile, List<Rule>> matchedRules = new HashMap<>();

    final Map<String, String> stateInitialAttributes;
    final Map<String, String> stateWorkingAttributes;
    StateMap stateMap = null;

    try {
        if (stateful) {
            stateMap = context.getStateManager().getState(Scope.LOCAL);
            stateInitialAttributes = stateMap.toMap();
            stateWorkingAttributes = new HashMap<>(stateMap.toMap());
        } else {
            stateInitialAttributes = null;
            stateWorkingAttributes = null;
        }
    } catch (IOException e) {
        logger.error(
                "Failed to get the initial state when processing {}; transferring FlowFile back to its incoming queue",
                new Object[] { incomingFlowFile }, e);
        session.transfer(incomingFlowFile);
        context.yield();
        return;
    }

    Map<String, Action> defaultActions = this.defaultActions;
    List<FlowFile> flowFilesToTransfer = new LinkedList<>();

    // if there is update criteria specified, evaluate it
    if (criteria != null && evaluateCriteria(session, context, criteria, incomingFlowFile, matchedRules,
            stateInitialAttributes)) {
        // apply the actions for each rule and transfer the flowfile
        for (final Map.Entry<FlowFile, List<Rule>> entry : matchedRules.entrySet()) {
            FlowFile match = entry.getKey();
            final List<Rule> rules = entry.getValue();
            boolean updateWorking = incomingFlowFile.equals(match);

            // execute each matching rule(s)
            match = executeActions(session, context, rules, defaultActions, match, stateInitialAttributes,
                    stateWorkingAttributes);

            if (updateWorking) {
                incomingFlowFile = match;
            }

            if (debugEnabled) {
                logger.debug("Updated attributes for {}; transferring to '{}'",
                        new Object[] { match, REL_SUCCESS.getName() });
            }

            // add the match to the list to transfer
            flowFilesToTransfer.add(match);
        }
    } else {
        // Either we're running without any rules or the FlowFile didn't match any
        incomingFlowFile = executeActions(session, context, null, defaultActions, incomingFlowFile,
                stateInitialAttributes, stateWorkingAttributes);

        if (debugEnabled) {
            logger.debug("Updated attributes for {}; transferring to '{}'",
                    new Object[] { incomingFlowFile, REL_SUCCESS.getName() });
        }

        // add the flowfile to the list to transfer
        flowFilesToTransfer.add(incomingFlowFile);
    }

    if (stateInitialAttributes != null) {
        try {
            // Able to use "equals()" since we're just checking if the map was modified at all
            if (!stateWorkingAttributes.equals(stateInitialAttributes)) {

                boolean setState = context.getStateManager().replace(stateMap, stateWorkingAttributes,
                        Scope.LOCAL);
                if (!setState) {
                    logger.warn(
                            "Failed to update the state after successfully processing {} due to having an old version of the StateMap. This is normally due to multiple threads running at "
                                    + "once; transferring to '{}'",
                            new Object[] { incomingFlowFile, REL_FAILED_SET_STATE.getName() });

                    flowFilesToTransfer.remove(incomingFlowFile);
                    if (flowFilesToTransfer.size() > 0) {
                        session.remove(flowFilesToTransfer);
                    }

                    session.transfer(incomingFlowFile, REL_FAILED_SET_STATE);
                    return;
                }
            }
        } catch (IOException e) {
            logger.error(
                    "Failed to set the state after successfully processing {} due a failure when setting the state. This is normally due to multiple threads running at "
                            + "once; transferring to '{}'",
                    new Object[] { incomingFlowFile, REL_FAILED_SET_STATE.getName() }, e);

            flowFilesToTransfer.remove(incomingFlowFile);
            if (flowFilesToTransfer.size() > 0) {
                session.remove(flowFilesToTransfer);
            }

            session.transfer(incomingFlowFile, REL_FAILED_SET_STATE);
            context.yield();
            return;
        }
    }

    for (FlowFile toTransfer : flowFilesToTransfer) {
        session.getProvenanceReporter().modifyAttributes(toTransfer);
    }
    session.transfer(flowFilesToTransfer, REL_SUCCESS);
}

From source file:org.apache.druid.indexing.kafka.supervisor.KafkaSupervisor.java

private ListenableFuture<Map<Integer, Long>> checkpointTaskGroup(final TaskGroup taskGroup,
        final boolean finalize) {
    if (finalize) {
        // 1) Check if any task completed (in which case we're done) and kill unassigned tasks
        Iterator<Entry<String, TaskData>> i = taskGroup.tasks.entrySet().iterator();
        while (i.hasNext()) {
            Entry<String, TaskData> taskEntry = i.next();
            String taskId = taskEntry.getKey();
            TaskData task = taskEntry.getValue();

            // task.status can be null if kafkaSupervisor is stopped gracefully before processing any runNotice.
            if (task.status != null) {
                if (task.status.isSuccess()) {
                    // If any task in this group has already completed, stop the rest of the tasks in the group and return.
                    // This will cause us to create a new set of tasks next cycle that will start from the offsets in
                    // metadata store (which will have advanced if we succeeded in publishing and will remain the same if
                    // publishing failed and we need to re-ingest)
                    return Futures.transform(stopTasksInGroup(taskGroup),
                            new Function<Object, Map<Integer, Long>>() {
                                @Nullable
                                @Override
                                public Map<Integer, Long> apply(@Nullable Object input) {
                                    return null;
                                }//ww  w.  j  ava  2  s  .c  o  m
                            });
                }

                if (task.status.isRunnable()) {
                    if (taskInfoProvider.getTaskLocation(taskId).equals(TaskLocation.unknown())) {
                        log.info("Killing task [%s] which hasn't been assigned to a worker", taskId);
                        killTask(taskId);
                        i.remove();
                    }
                }
            }
        }
    }

    // 2) Pause running tasks
    final List<ListenableFuture<Map<Integer, Long>>> pauseFutures = Lists.newArrayList();
    final List<String> pauseTaskIds = ImmutableList.copyOf(taskGroup.taskIds());
    for (final String taskId : pauseTaskIds) {
        pauseFutures.add(taskClient.pauseAsync(taskId));
    }

    return Futures.transform(Futures.successfulAsList(pauseFutures),
            new Function<List<Map<Integer, Long>>, Map<Integer, Long>>() {
                @Nullable
                @Override
                public Map<Integer, Long> apply(List<Map<Integer, Long>> input) {
                    // 3) Build a map of the highest offset read by any task in the group for each partition
                    final Map<Integer, Long> endOffsets = new HashMap<>();
                    for (int i = 0; i < input.size(); i++) {
                        Map<Integer, Long> result = input.get(i);

                        if (result == null || result.isEmpty()) { // kill tasks that didn't return a value
                            String taskId = pauseTaskIds.get(i);
                            log.warn("Task [%s] failed to respond to [pause] in a timely manner, killing task",
                                    taskId);
                            killTask(taskId);
                            taskGroup.tasks.remove(taskId);

                        } else { // otherwise build a map of the highest offsets seen
                            for (Entry<Integer, Long> offset : result.entrySet()) {
                                if (!endOffsets.containsKey(offset.getKey())
                                        || endOffsets.get(offset.getKey()).compareTo(offset.getValue()) < 0) {
                                    endOffsets.put(offset.getKey(), offset.getValue());
                                }
                            }
                        }
                    }

                    // 4) Set the end offsets for each task to the values from step 3 and resume the tasks. All the tasks should
                    //    finish reading and start publishing within a short period, depending on how in sync the tasks were.
                    final List<ListenableFuture<Boolean>> setEndOffsetFutures = Lists.newArrayList();
                    final List<String> setEndOffsetTaskIds = ImmutableList.copyOf(taskGroup.taskIds());

                    if (setEndOffsetTaskIds.isEmpty()) {
                        log.info("All tasks in taskGroup [%d] have failed, tasks will be re-created",
                                taskGroup.groupId);
                        return null;
                    }

                    try {

                        if (endOffsets.equals(taskGroup.sequenceOffsets.lastEntry().getValue())) {
                            log.warn(
                                    "Checkpoint [%s] is same as the start offsets [%s] of latest sequence for the task group [%d]",
                                    endOffsets, taskGroup.sequenceOffsets.lastEntry().getValue(),
                                    taskGroup.groupId);
                        }

                        log.info("Setting endOffsets for tasks in taskGroup [%d] to %s and resuming",
                                taskGroup.groupId, endOffsets);
                        for (final String taskId : setEndOffsetTaskIds) {
                            setEndOffsetFutures
                                    .add(taskClient.setEndOffsetsAsync(taskId, endOffsets, finalize));
                        }

                        List<Boolean> results = Futures.successfulAsList(setEndOffsetFutures)
                                .get(futureTimeoutInSeconds, TimeUnit.SECONDS);
                        for (int i = 0; i < results.size(); i++) {
                            if (results.get(i) == null || !results.get(i)) {
                                String taskId = setEndOffsetTaskIds.get(i);
                                log.warn(
                                        "Task [%s] failed to respond to [set end offsets] in a timely manner, killing task",
                                        taskId);
                                killTask(taskId);
                                taskGroup.tasks.remove(taskId);
                            }
                        }
                    } catch (Exception e) {
                        log.error("Something bad happened [%s]", e.getMessage());
                        Throwables.propagate(e);
                    }

                    if (taskGroup.tasks.isEmpty()) {
                        log.info("All tasks in taskGroup [%d] have failed, tasks will be re-created",
                                taskGroup.groupId);
                        return null;
                    }

                    return endOffsets;
                }
            }, workerExec);
}

From source file:org.jspresso.framework.application.frontend.controller.AbstractFrontendController.java

/**
 * Executes frontend actions and delegates backend actions execution to its
 * peer backend controller.// w  w  w .  j  a  va 2 s. c o  m
 * <p/>
 * {@inheritDoc}
 */
@SuppressWarnings({ "ThrowFromFinallyBlock", "ConstantConditions" })
@Override
public boolean execute(IAction action, Map<String, Object> context) {
    if (action == null) {
        return true;
    }
    Map<String, Object> actionContext = getInitialActionContext();
    // Retain only entries from the initial action context that are not in the
    // action context.
    actionContext.putAll(context);
    context.putAll(actionContext);
    // This is handled here since the selected module might have changed during
    // the action chain.
    context.put(ActionContextConstants.CURRENT_MODULE, getSelectedModule());
    boolean result;
    Map<String, Object> initialActionState = null;
    boolean savedExecuteDelayedActions = executeDelayedActions;
    boolean savedCheckActionChainTheadSafety = checkActionChainTheadSafety;
    try {
        if (executeDelayedActions) {
            executeDelayedActions = false;
            executeDelayedActions(this);
        }
        if (isCheckActionThreadSafety() && checkActionChainTheadSafety) {
            checkActionChainTheadSafety = false;
            try {
                initialActionState = extractInternalActionState(action);
            } catch (IllegalAccessException ex) {
                throw new ActionException(ex,
                        "Unable to extract internal action state for thread-safety checking of action : "
                                + action);
            }
        }
        // Should be handled before getting there.
        // checkAccess(action);
        actionStack.add(0, action);
        if (action.isBackend()) {
            result = executeBackend(action, context);
        } else {
            result = executeFrontend(action, context);
        }
        if (!actionStack.isEmpty()) {
            actionStack.remove(0);
        }
    } catch (Throwable ex) {
        Throwable refinedException = ex;
        while (!actionStack.isEmpty()) {
            IAction callingAction = actionStack.remove(0);
            if (callingAction != null) {
                boolean handled = false;
                try {
                    handled = callingAction.handleException(refinedException, context);
                } catch (Throwable reworkedException) {
                    if (!actionStack.isEmpty()) {
                        throw reworkedException;
                    }
                    refinedException = reworkedException;
                }
                if (handled) {
                    return true;
                }
            }
        }
        handleException(refinedException, context);
        result = false;
    } finally {
        executeDelayedActions = savedExecuteDelayedActions;
        checkActionChainTheadSafety = savedCheckActionChainTheadSafety;
        if (initialActionState != null) {
            Map<String, Object> finalActionState;
            try {
                finalActionState = extractInternalActionState(action);
            } catch (IllegalAccessException ex) {
                throw new ActionException(ex,
                        "Unable to extract internal action state for thread-safety checking of action : "
                                + action);
            }
            if (!initialActionState.equals(finalActionState)) {
                LOG.error("A coding problem has been detected that breaks action thread-safety.\n"
                        + "The action internal state has been modified during its execution which is strictly forbidden.\n"
                        + "The action chain started with : {}", action);
                logInternalStateDifferences("root", initialActionState, finalActionState);
                throw new ActionException(
                        "A coding problem has been detected that breaks action thread-safety.\n"
                                + "The action internal state has been modified during its execution which is strictly forbidden.\n"
                                + "The action chain started with : " + action);
            }
        }
    }
    return result;
}

From source file:org.span.manager.ChangeSettingsActivity.java

private void updateConfig(String key) {

    boolean updateFlag = false;
    Map<String, String> oldcfgmap = new TreeMap<String, String>(manetcfg.toMap());

    if (key.equals("uidpref")) {
        String userId = sharedPreferences.getString("uidpref", ManetConfig.USER_ID_DEFAULT.toString());
        manetcfg.setUserId(userId);/*  w w w .j  av  a 2s .co m*/
    } else if (key.equals("encalgorithmpref")) {
        String encAlgorithm = sharedPreferences.getString("encalgorithmpref",
                ManetConfig.WIFI_ENCRYPTION_ALGORITHM_DEFAULT.toString());
        manetcfg.setWifiEncryptionAlgorithm(WifiEncryptionAlgorithmEnum.fromString(encAlgorithm));
        updateFlag = true;
    } else if (key.equals("encsetuppref")) {
        String encSetupMethod = sharedPreferences.getString("encsetuppref",
                ManetConfig.WIFI_ENCRYPTION_SETUP_METHOD_DEFAULT.toString());
        manetcfg.setWifiEncryptionSetupMethod(WifiEncryptionSetupMethodEnum.fromString(encSetupMethod));
    } else if (key.equals("passwordpref")) {
        String encPassword = sharedPreferences.getString("passwordpref",
                ManetConfig.WIFI_ENCRYPTION_PASSWORD_DEFAULT);
        manetcfg.setWifiEncryptionPassword(encPassword);
    } else if (key.equals("ssidpref")) {
        String wifiSsid = sharedPreferences.getString("ssidpref", ManetConfig.WIFI_ESSID_DEFAULT);
        manetcfg.setWifiSsid(wifiSsid);
    } else if (key.equals("channelpref")) {
        String wifiChannel = sharedPreferences.getString("channelpref",
                ManetConfig.WIFI_CHANNEL_DEFAULT.toString());
        manetcfg.setWifiChannel(WifiChannelEnum.fromString(wifiChannel));
    } else if (key.equals("txpowerpref")) {
        String wifiTxpower = sharedPreferences.getString("txpowerpref",
                ManetConfig.WIFI_TXPOWER_DEFAULT.toString());
        manetcfg.setWifiTxPower(WifiTxpowerEnum.fromString(wifiTxpower));
    } else if (key.equals("interfacepref")) {
        String wifiInterface = sharedPreferences.getString("interfacepref",
                ManetConfig.WIFI_INTERFACE_DEFAULT.toString());
        manetcfg.setWifiInterface(wifiInterface);
        updateFlag = true;
    } else if (key.equals("ippref")) {
        String ipAddress = sharedPreferences.getString("ippref", ManetConfig.IP_ADDRESS_DEFAULT);
        manetcfg.setIpAddress(ipAddress);
    } else if (key.equals("dnspref")) {
        String dnsServer = sharedPreferences.getString("dnspref", ManetConfig.DNS_SERVER_DEFAULT);
        manetcfg.setDnsServer(dnsServer);
    } else if (key.equals("bluetoothonpref")) {
        final Boolean bluetoothOn = sharedPreferences.getBoolean("bluetoothonpref",
                ManetConfig.ADHOC_MODE_DEFAULT == AdhocModeEnum.BLUETOOTH);
        if (bluetoothOn) {
            manetcfg.setAdhocMode(AdhocModeEnum.BLUETOOTH);
        } else {
            manetcfg.setAdhocMode(AdhocModeEnum.WIFI);
        }
        updateFlag = true;
    } else if (key.equals("bluetoothkeepwifipref")) {
        Boolean btKeepWifi = sharedPreferences.getBoolean("bluetoothkeepwifipref",
                !ManetConfig.BLUETOOTH_DISABLE_WIFI_DEFAULT);
        manetcfg.setDisableWifiWhenUsingBluetooth(!btKeepWifi);
    } else if (key.equals("bluetoothdiscoverablepref")) {
        Boolean btDiscoverable = sharedPreferences.getBoolean("bluetoothdiscoverablepref",
                ManetConfig.BLUETOOTH_DISCOVERABLE_DEFAULT);
        manetcfg.setBlutoothDiscoverableWhenInAdhocMode(btDiscoverable);
    } else if (key.equals("routingprotocolpref")) {
        String routingProtocol = sharedPreferences.getString("routingprotocolpref",
                ManetConfig.ROUTING_PROTOCOL_DEFAULT);
        manetcfg.setRoutingProtocol(routingProtocol);
    } else if (key.equals("ignorepref")) {
        List<String> ignoreList = new ArrayList<String>();
        try {
            JSONArray array = new JSONArray(sharedPreferences.getString("ignorepref", "[]"));
            for (int i = 0; i < array.length(); i++) {
                ignoreList.add(array.get(i).toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        manetcfg.setRoutingIgnoreList(ignoreList);
    } else if (key.equals("gatewaypref")) {
        String gatewayInterface = sharedPreferences.getString("gatewaypref",
                ManetConfig.GATEWAY_INTERFACE_DEFAULT.toString());
        manetcfg.setGatewayInterface(gatewayInterface);
        updateFlag = true;
    } else if (key.equals("screenonpref")) {
        Boolean screenOn = sharedPreferences.getBoolean("screenonpref", ManetConfig.SCREEN_ON_DEFAULT);
        manetcfg.setScreenOnWhenInAdhocMode(screenOn);
    }

    Map<String, String> newcfgmap = manetcfg.toMap();
    dirtyFlag |= !oldcfgmap.equals(newcfgmap);

    if (updateFlag) {
        updateView(); // selecting some options may change the available choices for other options
    }
}

From source file:org.ofbiz.order.shoppingcart.CheckOutHelper.java

public static Map<String, Object> processPayment(String orderId, BigDecimal orderTotal, String currencyUomId,
        GenericValue productStore, GenericValue userLogin, boolean faceToFace, boolean manualHold,
        LocalDispatcher dispatcher, Delegator delegator) throws GeneralException {
    // Get some payment related strings
    String DECLINE_MESSAGE = productStore.getString("authDeclinedMessage");
    String ERROR_MESSAGE = productStore.getString("authErrorMessage");
    String RETRY_ON_ERROR = productStore.getString("retryFailedAuths");
    if (RETRY_ON_ERROR == null) {
        RETRY_ON_ERROR = "Y";
    }/*from   w ww  . j  av a2  s.  co  m*/

    List<GenericValue> allPaymentPreferences = null;
    try {
        allPaymentPreferences = EntityQuery.use(delegator).from("OrderPaymentPreference")
                .where("orderId", orderId).queryList();
    } catch (GenericEntityException e) {
        throw new GeneralException("Problems getting payment preferences", e);
    }

    // filter out cancelled preferences
    List<EntityExpr> canExpr = UtilMisc
            .toList(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"));
    allPaymentPreferences = EntityUtil.filterByAnd(allPaymentPreferences, canExpr);

    // check for online payment methods or in-hand payment types with verbal or external refs
    List<EntityExpr> exprs = UtilMisc
            .toList(EntityCondition.makeCondition("manualRefNum", EntityOperator.NOT_EQUAL, null));
    List<GenericValue> manualRefPaymentPrefs = EntityUtil.filterByAnd(allPaymentPreferences, exprs);
    if (UtilValidate.isNotEmpty(manualRefPaymentPrefs)) {
        for (GenericValue opp : manualRefPaymentPrefs) {
            Map<String, Object> authCtx = new HashMap<String, Object>();
            authCtx.put("orderPaymentPreference", opp);
            if (opp.get("paymentMethodId") == null) {
                authCtx.put("serviceTypeEnum", "PRDS_PAY_EXTERNAL");
            }
            authCtx.put("processAmount", opp.getBigDecimal("maxAmount"));
            authCtx.put("authRefNum", opp.getString("manualRefNum"));
            authCtx.put("authResult", Boolean.TRUE);
            authCtx.put("userLogin", userLogin);
            authCtx.put("currencyUomId", currencyUomId);

            Map<String, Object> authResp = dispatcher.runSync("processAuthResult", authCtx);
            if (authResp != null && ServiceUtil.isError(authResp)) {
                throw new GeneralException(ServiceUtil.getErrorMessage(authResp));
            }

            // approve the order
            OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);

            if ("Y".equalsIgnoreCase(productStore.getString("manualAuthIsCapture"))) {
                Map<String, Object> captCtx = new HashMap<String, Object>();
                captCtx.put("orderPaymentPreference", opp);
                if (opp.get("paymentMethodId") == null) {
                    captCtx.put("serviceTypeEnum", "PRDS_PAY_EXTERNAL");
                }
                captCtx.put("payToPartyId", productStore.get("payToPartyId"));
                captCtx.put("captureResult", Boolean.TRUE);
                captCtx.put("captureAmount", opp.getBigDecimal("maxAmount"));
                captCtx.put("captureRefNum", opp.getString("manualRefNum"));
                captCtx.put("userLogin", userLogin);
                captCtx.put("currencyUomId", currencyUomId);

                Map<String, Object> capResp = dispatcher.runSync("processCaptureResult", captCtx);
                if (capResp != null && ServiceUtil.isError(capResp)) {
                    throw new GeneralException(ServiceUtil.getErrorMessage(capResp));
                }
            }
        }
    }

    // check for a paypal express checkout needing completion
    List<EntityExpr> payPalExprs = UtilMisc.toList(
            EntityCondition.makeCondition("paymentMethodId", EntityOperator.NOT_EQUAL, null),
            EntityCondition.makeCondition("paymentMethodTypeId", "EXT_PAYPAL"));
    List<GenericValue> payPalPaymentPrefs = EntityUtil.filterByAnd(allPaymentPreferences, payPalExprs);
    if (UtilValidate.isNotEmpty(payPalPaymentPrefs)) {
        GenericValue payPalPaymentPref = EntityUtil.getFirst(payPalPaymentPrefs);
        ExpressCheckoutEvents.doExpressCheckout(productStore.getString("productStoreId"), orderId,
                payPalPaymentPref, userLogin, delegator, dispatcher);
    }

    // check for online payment methods needing authorization
    Map<String, Object> paymentFields = UtilMisc.<String, Object>toMap("statusId", "PAYMENT_NOT_AUTH");
    List<GenericValue> onlinePaymentPrefs = EntityUtil.filterByAnd(allPaymentPreferences, paymentFields);

    // Check the payment preferences; if we have ANY w/ status PAYMENT_NOT_AUTH invoke payment service.
    // Invoke payment processing.
    if (UtilValidate.isNotEmpty(onlinePaymentPrefs)) {
        boolean autoApproveOrder = UtilValidate.isEmpty(productStore.get("autoApproveOrder"))
                || "Y".equalsIgnoreCase(productStore.getString("autoApproveOrder"));
        if (orderTotal.compareTo(BigDecimal.ZERO) == 0 && autoApproveOrder) {
            // if there is nothing to authorize; don't bother
            boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
            if (!ok) {
                throw new GeneralException("Problem with order change; see above error");
            }
        }

        // now there should be something to authorize; go ahead
        Map<String, Object> paymentResult = null;
        try {
            // invoke the payment gateway service.
            paymentResult = dispatcher.runSync("authOrderPayments",
                    UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin), 180, false);
        } catch (GenericServiceException e) {
            Debug.logWarning(e, module);
            throw new GeneralException("Error in authOrderPayments service: " + e.toString(), e.getNested());
        }
        if (Debug.verboseOn())
            Debug.logVerbose("Finished w/ Payment Service", module);

        if (paymentResult != null && ServiceUtil.isError(paymentResult)) {
            throw new GeneralException(ServiceUtil.getErrorMessage(paymentResult));
        }

        if (paymentResult != null && paymentResult.containsKey("processResult")) {
            // grab the customer messages -- only passed back in the case of an error or failure
            List<String> messages = UtilGenerics.checkList(paymentResult.get("authResultMsgs"));

            String authResp = (String) paymentResult.get("processResult");

            if (authResp.equals("FAILED")) {
                // order was NOT approved
                if (Debug.verboseOn())
                    Debug.logVerbose("Payment auth was NOT a success!", module);

                boolean ok = OrderChangeHelper.rejectOrder(dispatcher, userLogin, orderId);
                if (!ok) {
                    throw new GeneralException("Problem with order change; see above error");
                }
                if (UtilValidate.isEmpty(messages)) {
                    return ServiceUtil.returnError(DECLINE_MESSAGE);
                } else {
                    return ServiceUtil.returnError(messages);
                }
            } else if (authResp.equals("APPROVED")) {
                // order WAS approved
                if (Debug.verboseOn())
                    Debug.logVerbose("Payment auth was a success!", module);

                // set the order and item status to approved
                if (autoApproveOrder) {
                    List<GenericValue> productStorePaymentSettingList = EntityQuery.use(delegator)
                            .from("ProductStorePaymentSetting")
                            .where("productStoreId", productStore.getString("productStoreId"),
                                    "paymentMethodTypeId", "CREDIT_CARD", "paymentService", "cyberSourceCCAuth")
                            .queryList();
                    if (productStorePaymentSettingList.size() > 0) {
                        String decision = (String) paymentResult.get("authCode");
                        if (UtilValidate.isNotEmpty(decision)) {
                            if ("ACCEPT".equalsIgnoreCase(decision)) {
                                boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId,
                                        manualHold);
                                if (!ok) {
                                    throw new GeneralException("Problem with order change; see above error");
                                }
                            }
                        } else {
                            boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId,
                                    manualHold);
                            if (!ok) {
                                throw new GeneralException("Problem with order change; see above error");
                            }
                        }
                    } else {
                        boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
                        if (!ok) {
                            throw new GeneralException("Problem with order change; see above error");
                        }
                    }
                }
            } else if (authResp.equals("ERROR")) {
                // service failed
                if (Debug.verboseOn())
                    Debug.logVerbose("Payment auth failed due to processor trouble.", module);
                if (!faceToFace && "Y".equalsIgnoreCase(RETRY_ON_ERROR)) {
                    // never do this for a face to face purchase regardless of store setting
                    return ServiceUtil.returnSuccess(ERROR_MESSAGE);
                } else {
                    boolean ok = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
                    if (!ok) {
                        throw new GeneralException("Problem with order change; see above error");
                    }
                    if (UtilValidate.isEmpty(messages)) {
                        return ServiceUtil.returnError(ERROR_MESSAGE);
                    } else {
                        return ServiceUtil.returnError(messages);
                    }
                }
            } else {
                // should never happen
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                        "OrderPleaseContactCustomerServicePaymentReturnCodeUnknown", Locale.getDefault()));
            }
        } else {
            // result returned null == service failed
            if (Debug.verboseOn())
                Debug.logVerbose("Payment auth failed due to processor trouble.", module);
            if (!faceToFace && "Y".equalsIgnoreCase(RETRY_ON_ERROR)) {
                // never do this for a face to face purchase regardless of store setting
                return ServiceUtil.returnSuccess(ERROR_MESSAGE);
            } else {
                boolean ok = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
                if (!ok) {
                    throw new GeneralException("Problem with order change; see above error");
                }
                return ServiceUtil.returnError(ERROR_MESSAGE);
            }
        }
    } else {
        // Get the paymentMethodTypeIds - this will need to change when ecom supports multiple payments
        List<EntityExpr> cashCodPcBaExpr = UtilMisc.toList(
                EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "CASH"),
                EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EXT_COD"),
                EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "PERSONAL_CHECK"),
                EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EXT_BILLACT"));
        List<GenericValue> cashCodPcBaPaymentPreferences = EntityUtil.filterByOr(allPaymentPreferences,
                cashCodPcBaExpr);

        if (UtilValidate.isNotEmpty(cashCodPcBaPaymentPreferences)
                && UtilValidate.isNotEmpty(allPaymentPreferences)
                && cashCodPcBaPaymentPreferences.size() == allPaymentPreferences.size()) {

            //if there are Check type, approve the order only if it is face to face
            List<GenericValue> checkPreferences = EntityUtil.filterByAnd(cashCodPcBaPaymentPreferences,
                    UtilMisc.toMap("paymentMethodTypeId", "PERSONAL_CHECK"));
            if (UtilValidate.isNotEmpty(checkPreferences)) {
                if (faceToFace) {
                    boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
                    if (!ok) {
                        throw new GeneralException("Problem with order change; see above error");
                    }
                }
                // approve this as long as there are only CASH, COD and Billing Account types
            } else {
                boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
                if (!ok) {
                    throw new GeneralException("Problem with order change; see above error");
                }
            }

        } else {
            // There is nothing to do, we just treat this as a success
        }
    }

    // check to see if we should auto-invoice/bill
    if (faceToFace) {
        if (Debug.verboseOn())
            Debug.logVerbose("Face-To-Face Sale - " + orderId, module);
        CheckOutHelper.adjustFaceToFacePayment(orderId, orderTotal, allPaymentPreferences, userLogin,
                delegator);
        boolean ok = OrderChangeHelper.completeOrder(dispatcher, userLogin, orderId);
        if (Debug.verboseOn())
            Debug.logVerbose("Complete Order Result - " + ok, module);
        if (!ok) {
            throw new GeneralException("Problem with order change; see error logs");
        }
    }
    return ServiceUtil.returnSuccess();
}

From source file:com.radiusnetworks.scavengerhunt.ScavengerHuntApplication.java

@Override
public void didSync() {
    // Called when ProximityKit data are updated from the server
    Log.d(TAG, "proximityKit didSync.  kit is " + manager.getKit());
    if (ignoreSync) {
        Log.d(TAG, "ignoring sync");
        return;/*from   ww w .j  av  a2 s.  co m*/
    }
    ignoreSync = true;

    ArrayList<TargetItem> targets = new ArrayList<TargetItem>();
    Map<String, String> urlMap = new HashMap<String, String>();
    Map<String, String> customStartScreenData = new HashMap<String, String>();
    Map<String, String> customAssetUrlMap = new HashMap<String, String>();

    for (KitBeacon beacon : manager.getKit().getBeacons()) {
        String huntId = beacon.getAttributes().get("hunt_id");
        if (huntId != null) {
            TargetItem target = new TargetItem(huntId);

            String title = beacon.getAttributes().get("title");
            if (title != null) {
                target.setTitle(title);
                Log.d(TAG, "title = " + title);
            } else {
                Log.d(TAG, "title = null");
            }

            String description = beacon.getAttributes().get("description");
            if (description != null) {
                target.setDescription(description);
                Log.d(TAG, "description = " + description);
            } else {
                Log.d(TAG, "description = null");
            }

            targets.add(target);
            String imageUrl = beacon.getAttributes().get("image_url");
            if (imageUrl == null) {
                Log.e(TAG, "ERROR: No image_url specified in ProximityKit for item with hunt_id=" + huntId);
                loadingActivity.codeValidationFailed(new RuntimeException(
                        "No targets configured for the entered code.  At least one beacon must be configured in ProximityKit with a hunt_id key."));
                return;
            } else {
                urlMap.put("target" + huntId + "_found", variantTargetImageUrlForBaseUrlString(imageUrl, true));
                urlMap.put("target" + huntId, variantTargetImageUrlForBaseUrlString(imageUrl, false));
            }

            String splashUrl = beacon.getAttributes().get("splash_url");
            Log.e(TAG, "splashUrl = " + splashUrl);

            //custom splash screen and instructions screen metadata

            String instruction_background_color = beacon.getAttributes().get("instruction_background_color");

            if (instruction_background_color != null) {
                Log.d(TAG,
                        "------This hunt has a custom instruction screen because the instruction_background_color is set to "
                                + instruction_background_color);
                //save custom splash screen and instructions screen for later use

                try {
                    customStartScreenData.put("instruction_background_color",
                            beacon.getAttributes().get("instruction_background_color"));
                    customStartScreenData.put("instruction_image_url",
                            beacon.getAttributes().get("instruction_image_url"));
                    customStartScreenData.put("instruction_start_button_name",
                            beacon.getAttributes().get("instruction_start_button_name"));
                    customStartScreenData.put("instruction_text_1",
                            beacon.getAttributes().get("instruction_text_1"));
                    customStartScreenData.put("instruction_title",
                            beacon.getAttributes().get("instruction_title"));
                    customStartScreenData.put("splash_url", beacon.getAttributes().get("splash_url"));
                    customStartScreenData.put("finish_background_color",
                            beacon.getAttributes().get("finish_background_color"));
                    customStartScreenData.put("finish_image_url",
                            beacon.getAttributes().get("finish_image_url"));
                    customStartScreenData.put("finish_button_name",
                            beacon.getAttributes().get("finish_button_name"));
                    customStartScreenData.put("finish_text_1", beacon.getAttributes().get("finish_text_1"));

                    customAssetUrlMap.put("instruction_image",
                            beacon.getAttributes().get("instruction_image_url"));
                    customAssetUrlMap.put("finish_image", beacon.getAttributes().get("finish_image_url"));
                    customAssetUrlMap.put("splash", beacon.getAttributes().get("splash_url"));

                } catch (Exception e) {
                    e.printStackTrace();
                    customStartScreenData = null;
                }

            }
        }
    }

    if (targets.size() != 0) {
        if (loadingActivity != null && loadingActivity.isValidatingCode()) {
            loadingActivity.codeValidationPassed();
        }
    } else {
        if (loadingActivity != null && loadingActivity.isValidatingCode()) {
            loadingActivity.codeValidationFailed(new RuntimeException(
                    "No targets configured for the entered code.  At least one beacon must be configured in ProximityKit with a hunt_id key."));
            return;
        }
    }

    // load the saved state of the hunt from the phone's persistent
    // storage
    hunt = Hunt.loadFromPreferences(this);
    boolean targetListChanged = hunt.getTargetList().size() != targets.size();
    for (TargetItem target : hunt.getTargetList()) {
        boolean itemFound = false;
        for (TargetItem targetFromPk : targets) {
            if (targetFromPk.getId().equals(target.getId()))
                itemFound = true;
        }
        if (itemFound == false) {
            targetListChanged = true;
            Log.d(TAG,
                    "Target with hunt_id=" + target.getId() + " is no longer in PK.  Target list has changed.");
        }
    }
    if (customStartScreenData != null && customStartScreenData.equals(hunt.getCustomStartScreenData())) {
        targetListChanged = true;
        Log.d(TAG, "customStartScreenData.equals(savedCustomData)");
    } else {
        Log.d(TAG, "customStartScreenData DOES NOT EQUAL savedCustomData");
    }

    if (targetListChanged) {
        Log.w(TAG, "the targets in the hunt has changed from what we have in the settings.  starting over");
        this.hunt = (customStartScreenData == null) ? new Hunt(this, targets)
                : new Hunt(this, targets, customStartScreenData);
        this.hunt.saveToPreferences(this);
    }

    customAssetCache = new CustomAssetCache(this);
    customAssetCache.downloadCustomAssets(customAssetUrlMap, new AssetFetcherCallback() {
        @Override
        public void requestComplete() {
            Log.i(TAG, "custom assets downloaded successfully");
        }

        @Override
        public void requestFailed(Integer responseCode, Exception e) {
            Log.e(TAG, "Failed to download the custom assets.");
        }
    });
    // After we have all our data from ProximityKit, we need to download the images and cache them
    // for display in the app.  We do this every time, so that the app can update the images after
    // later, and have users get the update if they restart the app.  This takes time, so if you
    // don't want to do this, then only execute this code if validateRequiredImagesPresent()
    // returns false.
    remoteAssetCache = new RemoteAssetCache(this);
    remoteAssetCache.downloadAssets(urlMap, new AssetFetcherCallback() {
        @Override
        public void requestComplete() {
            dependencyLoadFinished();
        }

        @Override
        public void requestFailed(Integer responseCode, Exception e) {
            dependencyLoadFinished();
        }
    });
}

From source file:io.warp10.continuum.gts.GTSHelper.java

public static GTSEncoder parseJSON(GTSEncoder encoder, String str, Map<String, String> extraLabels, Long now)
        throws IOException, ParseException {

    JsonParser parser = jpf.createFastParser();

    //Gson gson = new Gson();
    //Map<String,Object> o = gson.fromJson(str, GSON_MAP_TYPE);
    Map<String, Object> o = (Map<String, Object>) parser.parse(str);

    String name = (String) o.get("c");
    Map<String, String> labels = (Map<String, String>) o.get("l");

    ///*from w w  w.j a  v  a  2 s . c o m*/
    // Add any provided extra labels
    //

    if (null != extraLabels) {
        labels.putAll(extraLabels);

        //
        // Remove labels with null values
        //
        // FIXME(hbs): may be removed when dummy tokens have disappeared
        //

        if (extraLabels.containsValue(null)) {
            Set<Entry<String, String>> entries = extraLabels.entrySet();

            while (labels.containsValue(null)) {
                for (Entry<String, String> entry : entries) {
                    if (null == entry.getValue()) {
                        labels.remove(entry.getKey());
                    }
                }
            }
        }
    }

    Object ots = o.get("t");

    long ts = (null != ots ? ((Number) ots).longValue() : (null != now ? (long) now : TimeSource.getTime()));

    long location = GeoTimeSerie.NO_LOCATION;

    if (o.containsKey("lat") && o.containsKey("lon")) {
        double lat = (double) o.get("lat");
        double lon = (double) o.get("lon");

        location = GeoXPLib.toGeoXPPoint(lat, lon);
    }

    long elevation = GeoTimeSerie.NO_ELEVATION;

    if (o.containsKey("elev")) {
        elevation = ((Number) o.get("elev")).longValue();
    }

    Object v = o.get("v");

    // Allocate a new Encoder if need be, with a base timestamp of 0L.
    if (null == encoder || !name.equals(encoder.getName()) || !labels.equals(encoder.getLabels())) {
        encoder = new GTSEncoder(0L);
        encoder.setName(name);
        encoder.setLabels(labels);
    }

    if (v instanceof Long || v instanceof Integer || v instanceof Short || v instanceof Byte
            || v instanceof BigInteger) {
        encoder.addValue(ts, location, elevation, ((Number) v).longValue());
    } else if (v instanceof Double || v instanceof Float) {
        encoder.addValue(ts, location, elevation, ((Number) v).doubleValue());
    } else if (v instanceof BigDecimal) {
        encoder.addValue(ts, location, elevation, v);
    } else if (v instanceof Boolean || v instanceof String) {
        encoder.addValue(ts, location, elevation, v);
    } else {
        throw new ParseException("Invalid value.", 0);
    }

    return encoder;
}

From source file:io.warp10.continuum.gts.GTSHelper.java

public static GTSEncoder parse_regexp(GTSEncoder encoder, String str, Map<String, String> extraLabels)
        throws ParseException, IOException {
    Matcher matcher = MEASUREMENT_RE.matcher(str);

    if (!matcher.matches()) {
        throw new ParseException(str, 0);
    }/*from   w  w w. j a  v  a  2  s.  c o  m*/

    //
    // Check name
    //

    String name = matcher.group(6);

    if (name.contains("%")) {
        try {
            name = URLDecoder.decode(name, "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            // Can't happen, we're using UTF-8
        }
    }

    //
    // Parse labels
    //

    Map<String, String> labels = parseLabels(matcher.group(7));

    //
    // Add any provided extra labels
    //

    if (null != extraLabels) {
        labels.putAll(extraLabels);
    }

    //
    // Extract timestamp, optional location and elevation
    //

    long timestamp;
    long location = GeoTimeSerie.NO_LOCATION;
    long elevation = GeoTimeSerie.NO_ELEVATION;

    try {

        if (null != matcher.group(1)) {
            //timestamp = Long.valueOf(matcher.group(1));
            timestamp = Long.parseLong(matcher.group(1));
        } else {
            // No timestamp provided, use 'now'
            timestamp = TimeSource.getTime();
            ;
        }

        if (null != matcher.group(2)) {
            //location = GeoXPLib.toGeoXPPoint(Double.valueOf(matcher.group(3)), Double.valueOf(matcher.group(4)));
            location = GeoXPLib.toGeoXPPoint(Double.parseDouble(matcher.group(3)),
                    Double.parseDouble(matcher.group(4)));
        }

        if (null != matcher.group(5)) {
            //elevation = Long.valueOf(matcher.group(5));
            elevation = Long.parseLong(matcher.group(5));
        }
    } catch (NumberFormatException nfe) {
        throw new ParseException("", 0);
    }

    //
    // Extract value
    //

    String valuestr = matcher.group(8);

    Object value = parseValue_regexp(valuestr);

    if (null == value) {
        throw new ParseException("Unable to parse value '" + valuestr + "'", 0);
    }

    // Allocate a new Encoder if need be, with a base timestamp of 0L.
    if (null == encoder || !name.equals(encoder.getName()) || !labels.equals(encoder.getLabels())) {
        encoder = new GTSEncoder(0L);
        encoder.setName(name);
        encoder.setLabels(labels);
    }

    encoder.addValue(timestamp, location, elevation, value);

    /*
    GeoTimeSerie gts = new GeoTimeSerie(1);
            
    gts.setName(name);
    gts.setLabels(labels);
    GTSHelper.setValue(gts, timestamp, location, elevation, value, false);
                
    return gts;
    */
    return encoder;
}

From source file:io.warp10.continuum.gts.GTSHelper.java

public static GTSEncoder parse(GTSEncoder encoder, String str, Map<String, String> extraLabels, Long now,
        long maxValueSize, boolean parseAttributes) throws ParseException, IOException {

    int idx = 0;/*  w  w  w.  j a v  a2 s  .co  m*/

    int tsoffset = 0;

    if ('=' == str.charAt(0)) {
        if (null == encoder) {
            throw new ParseException("Invalid continuation.", 0);
        }
        tsoffset = 1;
    }

    //idx = str.indexOf("/");
    idx = UnsafeString.indexOf(str, '/');

    if (-1 == idx) {
        throw new ParseException("Missing timestamp separator.", idx);
    }

    long timestamp;

    if (tsoffset == idx) {
        // No timestamp provided, use 'now'
        timestamp = null != now ? (long) now : TimeSource.getTime();
    } else {
        if ('T' == str.charAt(tsoffset)) {
            // Support T-XXX to record timestamps which are relative to 'now', useful for
            // devices with no time reference but only relative timestamps
            //timestamp = (null != now ? (long) now : TimeSource.getTime()) + Long.valueOf(str.substring(1 + tsoffset, idx));
            timestamp = (null != now ? (long) now : TimeSource.getTime())
                    + Long.parseLong(str.substring(1 + tsoffset, idx));
        } else {
            //timestamp = Long.valueOf(str.substring(tsoffset,  idx));
            timestamp = Long.parseLong(str.substring(tsoffset, idx));
        }
    }

    // Advance past the '/'
    idx++;

    //int idx2 = str.indexOf("/", idx);
    int idx2 = UnsafeString.indexOf(str, '/', idx);

    if (-1 == idx2) {
        throw new ParseException("Missing location/elevation separator.", idx);
    }

    long location = GeoTimeSerie.NO_LOCATION;

    if (idx != idx2) {
        // We have a location (lat:lon)
        String latlon = str.substring(idx, idx2);
        // Advance past the second '/'    
        idx = idx2 + 1;
        //idx2 = latlon.indexOf(":");
        idx2 = UnsafeString.indexOf(latlon, ':');

        //location = GeoXPLib.toGeoXPPoint(Double.valueOf(latlon.substring(0, idx2)), Double.valueOf(latlon.substring(idx2 + 1)));
        location = GeoXPLib.toGeoXPPoint(Double.parseDouble(latlon.substring(0, idx2)),
                Double.parseDouble(latlon.substring(idx2 + 1)));
    } else {
        // Advance past the second '/'    
        idx = idx2 + 1;
    }

    //idx2 = str.indexOf(" ", idx);
    idx2 = UnsafeString.indexOf(str, ' ', idx);

    if (-1 == idx2) {
        throw new ParseException(str, idx);
    }

    long elevation = GeoTimeSerie.NO_ELEVATION;

    if (idx != idx2) {
        // We have an elevation
        //elevation = Long.valueOf(str.substring(idx, idx2));
        elevation = Long.parseLong(str.substring(idx, idx2));
    }

    // Advance past the ' '    
    idx = idx2 + 1;

    while (idx < str.length() && str.charAt(idx) == ' ') {
        idx++;
    }

    // If line started with '=', assume there is no class+labels component
    if (tsoffset > 0) {
        idx2 = -1;
    } else {
        //idx2 = str.indexOf("{", idx);
        idx2 = UnsafeString.indexOf(str, '{', idx);
    }

    String name = null;
    Map<String, String> labels = null;
    Map<String, String> attributes = null;

    boolean reuseLabels = false;

    if (-1 == idx2) {
        // If we are over the end of the string, we're missing a value
        if (idx >= str.length()) {
            throw new ParseException("Missing value", idx);
        }
        // No class+labels, assume same class+labels as those in encoder, except
        // if encoder is null in which case we throw a parse exception
        if (null == encoder) {
            throw new ParseException(str, idx);
        }
        name = encoder.getMetadata().getName();
        labels = encoder.getMetadata().getLabels();
        reuseLabels = true;
    } else {
        name = str.substring(idx, idx2);

        //if (name.contains("%")) {
        if (-1 != UnsafeString.indexOf(name, '%')) {
            try {
                name = URLDecoder.decode(name, "UTF-8");
            } catch (UnsupportedEncodingException uee) {
                // Can't happen, we're using UTF-8
            }
        }

        // Advance past the '{'
        idx = idx2 + 1;

        //idx2 = str.indexOf("}", idx);
        idx2 = UnsafeString.indexOf(str, '}', idx);

        if (-1 == idx2) {
            throw new ParseException(str, idx);
        }

        //
        // Parse labels
        //

        labels = parseLabels(null != extraLabels ? extraLabels.size() : 0, str.substring(idx, idx2));

        //
        // FIXME(hbs): parse attributes????
        //

        // Advance past the '}' and over spaces

        idx = idx2 + 1;

        // FIXME(hbs): should we skip over attributes if they are present?
        if (idx < str.length() && str.charAt(idx) == '{') {
            idx++;
            int attrstart = idx;
            while (idx < str.length() && str.charAt(idx) != '}') {
                idx++;
            }
            if (parseAttributes) {
                if (idx >= str.length()) {
                    throw new ParseException("Missing attributes.", idx2);
                }
                attributes = parseLabels(str.substring(attrstart, idx));
            }
            idx++;
        }

        while (idx < str.length() && str.charAt(idx) == ' ') {
            idx++;
        }

        if (idx >= str.length()) {
            throw new ParseException("Missing value.", idx2);
        }
    }

    //
    // Add any provided extra labels
    //
    // WARNING(hbs): as we check reuseLabels, note that extraLabels won't be pushed onto the GTS labels
    // if reuseLabels is 'true', this means that if you call parse on a continuation line with different extraLabels
    // than for previous lines, the new extra labels won't be set. But this is not something that should be done anyway,
    // so it should not be considered a problem...
    //

    if (!reuseLabels && null != extraLabels) {
        labels.putAll(extraLabels);

        //
        // Remove labels with null values
        //
        // FIXME(hbs): may be removed when dummy tokens have disappeared
        //

        if (extraLabels.containsValue(null)) {
            Set<Entry<String, String>> entries = extraLabels.entrySet();

            while (labels.containsValue(null)) {
                for (Entry<String, String> entry : entries) {
                    if (null == entry.getValue()) {
                        labels.remove(entry.getKey());
                    }
                }
            }
        }
    }

    //
    // Extract value
    //

    String valuestr = str.substring(idx);

    if (valuestr.length() > maxValueSize) {
        throw new ParseException("Value too large at for GTS "
                + (null != encoder ? GTSHelper.buildSelector(encoder.getMetadata()) : ""), 0);
    }

    Object value = parseValue(valuestr);

    if (null == value) {
        throw new ParseException("Unable to parse value '" + valuestr + "'", 0);
    }

    // Allocate a new Encoder if need be, with a base timestamp of 0L.
    if (null == encoder || !name.equals(encoder.getName())
            || !labels.equals(encoder.getMetadata().getLabels())) {
        encoder = new GTSEncoder(0L);
        encoder.setName(name);
        //encoder.setLabels(labels);
        encoder.getMetadata().setLabels(labels);
        if (null != attributes) {
            encoder.getMetadata().setAttributes(attributes);
        }
    }

    encoder.addValue(timestamp, location, elevation, value);

    return encoder;
}

From source file:org.apache.ambari.view.slider.SliderAppsViewControllerImpl.java

@Override
public ViewStatus getViewStatus() {
    ViewStatus status = new ViewStatus();
    Map<String, String> newHadoopConfigs = new HashMap<String, String>();
    status.setVersion(SliderAppsConfiguration.INSTANCE.getVersion());
    String ambariCluster = getViewParameterValue(PARAM_AMBARI_CLUSTER_API);
    String ambariUsername = getViewParameterValue(PARAM_AMBARI_USERNAME);
    String ambariPassword = getViewParameterValue(PARAM_AMBARI_PASSWORD);
    if (ambariCluster != null && ambariUsername != null && ambariPassword != null
            && ambariCluster.trim().length() > 0 && ambariUsername.trim().length() > 0
            && ambariPassword.trim().length() > 0) {
        String APIPREFIX = "/api/v1/clusters/";
        int index = ambariCluster.indexOf(APIPREFIX);
        if (index > 0) {
            String ambariUrl = ambariCluster.substring(0, index);
            String clusterName = ambariCluster.substring(index + APIPREFIX.length());
            if (clusterName.endsWith("/")) {
                clusterName = clusterName.substring(0, clusterName.length() - 1);
            }/*from   w w w. ja v a2  s  . c o m*/
            AmbariHttpClient ambariClient = new AmbariHttpClient(ambariUrl, ambariUsername, ambariPassword);
            try {
                AmbariClusterInfo clusterInfo = ambariClient.getClusterInfo();
                if (clusterInfo != null && clusterName.equals(clusterInfo.getName())) {
                    AmbariCluster cluster = ambariClient.getCluster(clusterInfo);
                    AmbariServiceInfo hdfsServiceInfo = null;
                    AmbariServiceInfo yarnServiceInfo = null;
                    // Validate stack-version
                    Validation validateStackVersion = validateStackVersion(clusterInfo.getVersion());
                    if (validateStackVersion != null) {
                        status.getValidations().add(validateStackVersion);
                    }
                    for (AmbariServiceInfo svc : cluster.getServices()) {
                        if ("HDFS".equals(svc.getId())) {
                            hdfsServiceInfo = svc;
                        } else if ("YARN".equals(svc.getId())) {
                            yarnServiceInfo = svc;
                        }
                    }
                    // HDFS
                    if (hdfsServiceInfo != null) {
                        if (!hdfsServiceInfo.isStarted()) {
                            status.getValidations()
                                    .add(new ViewStatus.Validation("HDFS service is not started"));
                        }
                    } else {
                        status.getValidations().add(new ViewStatus.Validation("HDFS service is not installed"));
                    }
                    // YARN
                    if (yarnServiceInfo != null) {
                        if (!yarnServiceInfo.isStarted()) {
                            status.getValidations()
                                    .add(new ViewStatus.Validation("YARN service is not started"));
                        }
                    } else {
                        status.getValidations().add(new ViewStatus.Validation("YARN service is not installed"));
                    }
                    // JAVA_HOME
                    Map<String, String> ambariServerConfigs = ambariClient.getAmbariServerConfigs();
                    if (ambariServerConfigs.containsKey("java.home")) {
                        newHadoopConfigs.put("java.home", ambariServerConfigs.get("java.home"));
                        status.getParameters().put(PROPERTY_JAVA_HOME, ambariServerConfigs.get("java.home"));
                    }
                    // Configs
                    if (cluster.getDesiredConfigs().containsKey("core-site")) {
                        Map<String, String> coreSiteConfigs = ambariClient.getConfiguration(cluster,
                                "core-site", cluster.getDesiredConfigs().get("core-site"));
                        newHadoopConfigs.putAll(coreSiteConfigs);
                    }
                    if (cluster.getDesiredConfigs().containsKey("cluster-env")) {
                        Map<String, String> clusterEnvConfigs = ambariClient.getConfiguration(cluster,
                                "cluster-env", cluster.getDesiredConfigs().get("cluster-env"));
                        newHadoopConfigs.put("security_enabled", clusterEnvConfigs.get("security_enabled"));
                    }
                    if (cluster.getDesiredConfigs().containsKey("hdfs-site")) {
                        Map<String, String> hdfsSiteConfigs = ambariClient.getConfiguration(cluster,
                                "hdfs-site", cluster.getDesiredConfigs().get("hdfs-site"));
                        newHadoopConfigs.putAll(hdfsSiteConfigs);
                    }
                    if (cluster.getDesiredConfigs().containsKey("yarn-site")) {
                        Map<String, String> yarnSiteConfigs = ambariClient.getConfiguration(cluster,
                                "yarn-site", cluster.getDesiredConfigs().get("yarn-site"));
                        newHadoopConfigs.putAll(yarnSiteConfigs);
                        status.getParameters().put(PROPERTY_YARN_RM_WEBAPP_URL,
                                newHadoopConfigs.get("yarn.resourcemanager.webapp.address"));
                    }
                    if (cluster.getDesiredConfigs().containsKey("yarn-env")) {
                        Map<String, String> yarnEnvConfigs = ambariClient.getConfiguration(cluster, "yarn-env",
                                cluster.getDesiredConfigs().get("yarn-env"));
                        String yarnUser = yarnEnvConfigs.get("yarn_user");
                        if (yarnUser == null || yarnUser.trim().length() < 1) {
                            yarnUser = "yarn";
                        }
                        newHadoopConfigs.put("yarn_user", yarnUser); // YARN service user
                    }
                    newHadoopConfigs.put("slider.user", getUserToRunAs(newHadoopConfigs)); // Slider user
                    status.getParameters().put(PROPERTY_SLIDER_USER, newHadoopConfigs.get("slider.user"));
                    if (newHadoopConfigs.containsKey("security_enabled")) {
                        boolean securityEnabled = Boolean.valueOf(newHadoopConfigs.get("security_enabled"));
                        if (securityEnabled) {
                            String yarnUser = newHadoopConfigs.get("yarn_user");
                            if (yarnUser != null && yarnUser.equals(newHadoopConfigs.get("slider.user"))) {
                                status.getValidations().add(new ViewStatus.Validation(
                                        "Slider view does not support accessing secured YARN cluster as YARN superuser ("
                                                + yarnUser + ")"));
                            }
                        }
                    }
                    if (cluster.getDesiredConfigs().containsKey("zoo.cfg")) {
                        Map<String, String> zkEnvConfigs = ambariClient.getConfiguration(cluster, "zoo.cfg",
                                cluster.getDesiredConfigs().get("zoo.cfg"));
                        StringBuilder zkQuorumBuilder = new StringBuilder();
                        String port = zkEnvConfigs.get("clientPort");
                        AmbariService zkService = ambariClient.getService(cluster, "ZOOKEEPER");
                        if (zkService != null) {
                            List<AmbariHostComponent> hostsList = zkService.getComponentsToHostComponentsMap()
                                    .get("ZOOKEEPER_SERVER");
                            int count = 1;
                            for (AmbariHostComponent host : hostsList) {
                                zkQuorumBuilder.append(host.getHostName() + ":" + port);
                                if (count++ < hostsList.size()) {
                                    zkQuorumBuilder.append(",");
                                }
                            }
                            newHadoopConfigs.put(PROPERTY_SLIDER_ZK_QUORUM, zkQuorumBuilder.toString());
                        } else {
                            status.getValidations()
                                    .add(new ViewStatus.Validation("ZooKeeper service is not installed"));
                        }
                    } else {
                        status.getValidations()
                                .add(new ViewStatus.Validation("ZooKeeper service is not installed"));
                    }
                    if (cluster.getDesiredConfigs().containsKey("ams-site")) {
                        Map<String, String> amsConfigs = ambariClient.getConfiguration(cluster, "ams-site",
                                cluster.getDesiredConfigs().get("ams-site"));
                        AmbariService amsService = ambariClient.getService(cluster, "AMBARI_METRICS");
                        List<AmbariHostComponent> hostsList = amsService.getComponentsToHostComponentsMap()
                                .get("METRICS_COLLECTOR");
                        if (hostsList != null && hostsList.size() > 0) {
                            String collectorHostName = hostsList.get(0).getHostName();
                            newHadoopConfigs.put(PROPERTY_METRICS_SERVER_HOSTNAME, collectorHostName);
                            status.getParameters().put(PROPERTY_METRICS_SERVER_HOSTNAME, collectorHostName);
                        }
                        if (amsConfigs != null
                                && amsConfigs.containsKey("timeline.metrics.service.webapp.address")) {
                            String portString = amsConfigs.get("timeline.metrics.service.webapp.address");
                            int sepIndex = portString.indexOf(':');
                            if (sepIndex > -1) {
                                portString = portString.substring(sepIndex + 1);
                            }
                            newHadoopConfigs.put(PROPERTY_METRICS_SERVER_PORT, portString);
                            status.getParameters().put(PROPERTY_METRICS_SERVER_PORT, portString);
                        }
                        newHadoopConfigs.put(PROPERTY_METRICS_LIBRARY_PATH,
                                "file:///usr/lib/ambari-metrics-hadoop-sink/ambari-metrics-hadoop-sink.jar");
                        status.getParameters().put(PROPERTY_METRICS_LIBRARY_PATH,
                                "file:///usr/lib/ambari-metrics-hadoop-sink/ambari-metrics-hadoop-sink.jar");
                    }
                    Validation validateHDFSAccess = validateHDFSAccess(newHadoopConfigs, hdfsServiceInfo);
                    if (validateHDFSAccess != null) {
                        status.getValidations().add(validateHDFSAccess);
                    }
                } else {
                    status.getValidations().add(new ViewStatus.Validation(
                            "Ambari cluster with ID [" + clusterName + "] was not found on Ambari server"));
                }
            } catch (Throwable e) {
                logger.warn("Exception determining view status", e);
                String message = e.getClass().getName() + ": " + e.getMessage();
                if (e instanceof RuntimeException && e.getCause() != null) {
                    message = e.getCause().getClass().getName() + ": " + e.getMessage();
                }
                message = String.format("Unable to initialize Slider view: %s", message);
                status.getValidations().add(new ViewStatus.Validation(message));
            }
        } else {
            status.getValidations().add(new ViewStatus.Validation(
                    "Ambari server cluster API URL should include cluster name, for example http://ambari.server:8080/api/v1/clusters/c1"));
        }
    } else {
        status.getValidations()
                .add(new ViewStatus.Validation("View parameters specifying Ambari details required"));
    }
    synchronized (viewContext) {
        if (!newHadoopConfigs.equals(viewContext.getInstanceData())) {
            Set<String> removeKeys = new HashSet<String>(viewContext.getInstanceData().keySet());
            for (Entry<String, String> e : newHadoopConfigs.entrySet()) {
                viewContext.putInstanceData(e.getKey(), e.getValue());
                removeKeys.remove(e.getKey());
            }
            for (String key : removeKeys) {
                viewContext.removeInstanceData(key);
            }
        }
    }
    return status;
}