Example usage for java.util NavigableMap get

List of usage examples for java.util NavigableMap get

Introduction

In this page you can find the example usage for java.util NavigableMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.antsdb.saltedfish.storage.HBaseUtilMain.java

private byte[] getTypes(Result r) {
    NavigableMap<byte[], byte[]> sysFamily = r.getNoVersionMap().get(Helper.SYS_COLUMN_FAMILY_BYTES);
    if (sysFamily == null) {
        return null;
    }//  w ww.  jav a 2  s . co  m
    byte[] types = sysFamily.get(Helper.SYS_COLUMN_DATATYPE_BYTES);
    return types;
}

From source file:com.kylinolap.rest.service.AclService.java

private void genAces(List<Sid> sids, Result result, AclImpl acl) {
    List<AceInfo> aceInfos = new ArrayList<AceInfo>();
    if (null != sids) {
        // Just return aces in sids
        for (Sid sid : sids) {
            String sidName = null;
            if (sid instanceof PrincipalSid) {
                sidName = ((PrincipalSid) sid).getPrincipal();
            } else if (sid instanceof GrantedAuthoritySid) {
                sidName = ((GrantedAuthoritySid) sid).getGrantedAuthority();
            }// w ww  . ja v a 2s .  c o m

            AceInfo aceInfo = aceSerializer
                    .deserialize(result.getValue(Bytes.toBytes(ACL_ACES_FAMILY), Bytes.toBytes(sidName)));
            if (null != aceInfo) {
                aceInfos.add(aceInfo);
            }
        }
    } else {
        NavigableMap<byte[], byte[]> familyMap = result.getFamilyMap(Bytes.toBytes(ACL_ACES_FAMILY));
        for (byte[] qualifier : familyMap.keySet()) {
            AceInfo aceInfo = aceSerializer.deserialize(familyMap.get(qualifier));

            if (null != aceInfo) {
                aceInfos.add(aceInfo);
            }
        }
    }

    List<AccessControlEntry> newAces = new ArrayList<AccessControlEntry>();
    for (int i = 0; i < aceInfos.size(); i++) {
        AceInfo aceInfo = aceInfos.get(i);

        if (null != aceInfo) {
            Sid sid = aceInfo.getSidInfo().isPrincipal() ? new PrincipalSid(aceInfo.getSidInfo().getSid())
                    : new GrantedAuthoritySid(aceInfo.getSidInfo().getSid());
            AccessControlEntry ace = new AccessControlEntryImpl(Long.valueOf(i), acl, sid,
                    aclPermissionFactory.buildFromMask(aceInfo.getPermissionMask()), true, false, false);
            newAces.add(ace);
        }
    }

    this.setAces(acl, newAces);
}

From source file:com.alibaba.wasp.meta.TestFMetaStore.java

@Test
public void testEntityGroup() throws MetaException, DeserializationException {
    FTable User = FMetaTestUtil.User;/*from w w w  .  j a v a  2  s .  com*/
    String tableName = User.getTableName();

    restoreAndInitFMETA();
    fMetaService.createTable(FMetaTestUtil.User);

    List<EntityGroupInfo> egis = getEntityGroup(tableName);
    // add EntityGroup
    fMetaService.addEntityGroup(egis);

    for (int i = 0; i < egis.size(); i++) {
        fMetaService.updateEntityGroupLocation(egis.get(i), egLocations[i]);
    }
    for (int i = 0; i < egis.size(); i++) {
        // getEntityGroupLocation
        ServerName sn = fMetaService.getEntityGroupLocation(egis.get(i));
        assertEquals(sn.compareTo(egLocations[i]), 0);
    }

    for (int i = 0; i < egis.size(); i++) {
        // getEntityGroupsAndLocations
        Pair<EntityGroupInfo, ServerName> pair = fMetaService
                .getEntityGroupAndLocation(egis.get(i).getEntityGroupName());
        assertEquals(pair.getFirst().compareTo(egis.get(i)), 0);
        assertEquals(pair.getSecond().compareTo(egLocations[i]), 0);
    }

    Set<String> disabledTables = new HashSet<String>();
    // fullScan
    Map<EntityGroupInfo, ServerName> entityGroups = fMetaService.fullScan(disabledTables, false);
    assertEquals(entityGroups.size(), egis.size());
    for (int i = 0; i < egis.size(); i++) {
        ServerName sn = entityGroups.get(egis.get(i));
        assertEquals(sn.compareTo(egLocations[i]), 0);
    }

    // getOfflineSplitParents
    Map<EntityGroupInfo, Result> offlineSplitParents = fMetaService.getOfflineSplitParents();
    assertEquals(offlineSplitParents.size(), 0);

    // getServerUserEntityGroups
    NavigableMap<EntityGroupInfo, Result> egR = fMetaService.getServerUserEntityGroups(egLocations[0]);
    assertEquals(1, egR.size());
    {
        Result r = egR.get(egis.get(0));
        byte[] infoValue = r.getValue(FConstants.CATALOG_FAMILY, FConstants.EGINFO);
        byte[] locationValue = r.getValue(FConstants.CATALOG_FAMILY, FConstants.EGLOCATION);
        EntityGroupInfo key = EntityGroupInfo.parseFromOrNull(infoValue);
        ServerName value = ServerName.convert(locationValue);
        assertEquals(key.compareTo(egis.get(0)), 0);
        assertEquals(value.compareTo(egLocations[0]), 0);
    }

    // getTableEntityGroupsAndLocations
    List<Pair<EntityGroupInfo, ServerName>> entityGroupInfos = fMetaService
            .getTableEntityGroupsAndLocations(Bytes.toBytes(tableName), false);
    entityGroups = new TreeMap<EntityGroupInfo, ServerName>();
    for (Pair<EntityGroupInfo, ServerName> pair : entityGroupInfos) {
        entityGroups.put(pair.getFirst(), pair.getSecond());
    }
    for (int i = 0; i < egis.size(); i++) {
        ServerName sn = entityGroups.get(egis.get(i));
        assertEquals(sn.compareTo(egLocations[i]), 0);
    }
    fMetaService.dropTable(FMetaTestUtil.User.getTableName());
}

From source file:eu.ggnet.dwoss.price.PriceCoreOperation.java

/**
 * Stores the supplied Prices to units and the manufacturerPartNoPriceFixeds
 *
 * @param pers     results to store/*  w  w w.  ja v a  2 s  . com*/
 * @param comment  a comment for the price history
 * @param arranger a arranger for the price history
 * @param monitor  an optional monitor
 */
public void store(final List<PriceEngineResult> pers, String comment, String arranger, IMonitor monitor) {
    final SubMonitor m = SubMonitor.convert(monitor, pers.size() + 27);
    UniqueUnitEao uniqueUnitEao = new UniqueUnitEao(uuEm);
    ProductEao productEao = new ProductEao(uuEm);
    // preload sopo and unique units
    m.message("Preloading UniqueUnits");
    NavigableMap<String, UniqueUnit> uniqueUnits = UniqueUnit.asMapByRefurbishId(
            uniqueUnitEao.findByIdentifiers(REFURBISHED_ID, PriceEngineResult.toRefurbishIds(pers)));
    m.worked(5);

    for (PriceEngineResult per : pers) {
        String msg = "Storing Unit " + per.getRefurbishedId() + " HP:" + per.getRetailerPrice() + " EP:"
                + per.getCustomerPrice() + " UnitFix:" + per.getUnitPriceFixed() + " ProductFix:"
                + per.getManufacturerPartPriceFixed();
        L.info(msg);
        m.worked(1, msg);
        update(uniqueUnits.get(per.getRefurbishedId()), per, arranger, comment);
    }
    //Inferenced filtering for fixprices
    Map<String, PriceEngineResult> fixPriceImports = new HashMap<>();
    for (PriceEngineResult per : pers) {
        if (per.getManufacturerPartPriceFixed() == NO_CHANGE)
            continue;
        fixPriceImports.put(per.getManufacturerPartNo(), per);
    }
    m.worked(1, "Perloading Products");
    NavigableMap<String, Product> products = Product
            .asMapByPartNos(productEao.findByPartNos(PriceEngineResult.toPartNos(pers)));
    m.worked(3);
    m.setWorkRemaining(fixPriceImports.size());
    for (PriceEngineResult per : fixPriceImports.values()) {
        update(products.get(per.getManufacturerPartNo()), per, arranger, comment);
        String msg = "Storing ProductDescription Fixed Price " + per.getProductName() + " Retailer:"
                + per.getRetailerPrice() + " Customer:" + per.getCustomerPrice() + " Manual:"
                + per.getManufacturerPartPriceFixed();
        L.info(msg);
        m.worked(1, msg);
    }
    m.finish();
}

From source file:com.alibaba.wasp.meta.FMetaServicesImplWithoutRetry.java

public LinkedHashMap<String, Index> parseIndex(Result rs) {
    LinkedHashMap<String, Index> indexs = new LinkedHashMap<String, Index>();
    NavigableMap<byte[], NavigableMap<byte[], byte[]>> familyMap = rs.getNoVersionMap();

    if (familyMap == null) {
        return indexs;
    }/*from w  w  w.  j  av a  2  s .  c  om*/
    NavigableMap<byte[], byte[]> kvs = familyMap.get(FConstants.CATALOG_FAMILY);
    for (Map.Entry<byte[], byte[]> kv : kvs.entrySet()) {
        byte[] cq = kv.getKey();
        byte[] value = kv.getValue();
        if (Bytes.startsWith(cq, FConstants.INDEXQUALIFIER_PREFIX)) {
            Index index = Index.convert(value);
            indexs.put(index.getIndexName(), index);
        }
    }
    return indexs;
}

From source file:com.mirth.connect.client.ui.LoadedExtensions.java

public void initialize() {
    // Remove all existing extensions from the maps in case they are being
    // initialized again
    clearExtensionMaps();/*from   w  w  w .  j a va2  s.  c om*/

    // Order all the plugins by their weight before loading any of them.
    Map<String, String> pluginNameMap = new HashMap<String, String>();
    NavigableMap<Integer, List<String>> weightedPlugins = new TreeMap<Integer, List<String>>();
    for (PluginMetaData metaData : PlatformUI.MIRTH_FRAME.getPluginMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {
                extensionVersions.put(metaData.getName(), metaData.getPluginVersion());
                if (metaData.getClientClasses() != null) {
                    for (PluginClass pluginClass : metaData.getClientClasses()) {
                        String clazzName = pluginClass.getName();
                        int weight = pluginClass.getWeight();
                        pluginNameMap.put(clazzName, metaData.getName());

                        List<String> classList = weightedPlugins.get(weight);
                        if (classList == null) {
                            classList = new ArrayList<String>();
                            weightedPlugins.put(weight, classList);
                        }

                        classList.add(clazzName);
                    }
                }

                if (StringUtils.isNotEmpty(metaData.getTemplateClassName())) {
                    Class<?> clazz = Class.forName(metaData.getTemplateClassName());

                    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                        if (constructor.getParameterTypes().length == 1) {
                            CodeTemplatePlugin codeTemplatePlugin = (CodeTemplatePlugin) constructor
                                    .newInstance(new Object[] { metaData.getName() });
                            addPluginPoints(codeTemplatePlugin);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e);
        }
    }

    // Load connector code template plugins before anything else
    for (ConnectorMetaData metaData : PlatformUI.MIRTH_FRAME.getConnectorMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {
                extensionVersions.put(metaData.getName(), metaData.getPluginVersion());
                if (StringUtils.isNotEmpty(metaData.getTemplateClassName())) {
                    Class<?> clazz = Class.forName(metaData.getTemplateClassName());

                    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                        if (constructor.getParameterTypes().length == 1) {
                            CodeTemplatePlugin codeTemplatePlugin = (CodeTemplatePlugin) constructor
                                    .newInstance(new Object[] { metaData.getName() });
                            addPluginPoints(codeTemplatePlugin);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                    "Could not load code template plugin: " + metaData.getTemplateClassName());
        }
    }

    // Signal the reference list factory that code template plugins have been loaded
    ReferenceListFactory.getInstance().loadPluginReferences();

    // Load the plugins in order of their weight
    for (List<String> classList : weightedPlugins.descendingMap().values()) {
        for (String clazzName : classList) {
            try {
                String pluginName = pluginNameMap.get(clazzName);
                Class<?> clazz = Class.forName(clazzName);
                Constructor<?>[] constructors = clazz.getDeclaredConstructors();

                for (int i = 0; i < constructors.length; i++) {
                    Class<?> parameters[];
                    parameters = constructors[i].getParameterTypes();
                    // load plugin if the number of parameters
                    // in the constructor is 1.
                    if (parameters.length == 1) {
                        ClientPlugin clientPlugin = (ClientPlugin) constructors[i]
                                .newInstance(new Object[] { pluginName });
                        addPluginPoints(clientPlugin);
                        i = constructors.length;
                    }
                }
            } catch (Exception e) {
                PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                        "Could not load plugin class: " + clazzName);
            }
        }
    }

    for (ConnectorMetaData metaData : PlatformUI.MIRTH_FRAME.getConnectorMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {

                String connectorName = metaData.getName();
                ConnectorSettingsPanel connectorSettingsPanel = (ConnectorSettingsPanel) Class
                        .forName(metaData.getClientClassName()).newInstance();

                if (metaData.getType() == ConnectorMetaData.Type.SOURCE) {
                    connectors.put(connectorName, connectorSettingsPanel);
                    sourceConnectors.put(connectorName, connectorSettingsPanel);
                } else if (metaData.getType() == ConnectorMetaData.Type.DESTINATION) {
                    connectors.put(connectorName, connectorSettingsPanel);
                    destinationConnectors.put(connectorName, connectorSettingsPanel);
                } else {
                    // type must be SOURCE or DESTINATION
                    throw new Exception();
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                    "Could not load connector class: " + metaData.getClientClassName());
        }
    }

    // Signal the reference list factory that all other plugins have been loaded
    ReferenceListFactory.getInstance().loadReferencesAfterPlugins();
}

From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java

@SuppressWarnings("unchecked")
public <T> T objectFrom(final Result result, final Class<T> hBasePersistanceClass) {
    if (!annotatedClassToAnnotatedHBaseRowKey.containsKey(hBasePersistanceClass)) {
        throw new IllegalArgumentException(
                "Class passed to objectFrom(final Result result, final Class<T> hBasePersistanceClass) must be a correct HBase persistable class! If this class is annotaed with @HBasePersistance please see startup errors for why it might have been excluded. ");
    }//  w ww  .j av a 2 s .c om
    if (result.isEmpty()) {
        return null;
    }
    /*
     * Create new instance of our target class
     */
    final T type = Whitebox.newInstance(hBasePersistanceClass);
    final NavigableMap<byte[], NavigableMap<byte[], byte[]>> columnFamilyResultMap = result.getNoVersionMap();
    /*
     * Map results to fields annotated with @HBaseField
     */
    for (final Field field : annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethod
            .get(hBasePersistanceClass).keySet()) {
        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, type,
                TypeHandler.getTypedValue(field.getType(),
                        columnFamilyResultMap.get(columnFamilyNameFromHBaseFieldAnnotatedField(field))
                                .remove(Bytes.toBytes(field.getName()))));
    }
    /*
     * Map results to fields annotated with @HBaseObjectField
     */
    for (final Field field : annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethod
            .get(hBasePersistanceClass).keySet()) {
        ReflectionUtils.makeAccessible(field);
        try {
            /*
             * We may purposely not want to populate certain fields by not including the column family
             */
            final byte[] columnFamily = columnFamilyNameFromHBaseObjectFieldAnnotatedField(field);
            if (columnFamilyResultMap.containsKey(columnFamily)) {
                ReflectionUtils.setField(field, type,
                        field.getAnnotation(HBaseObjectField.class).serializationStategy().deserialize(
                                columnFamilyResultMap.get(columnFamily).remove(Bytes.toBytes(field.getName())),
                                field));
            }
        } catch (Exception e) {
            /*
             *  We serialized this we should be able to de-serialize it. Did the serialization change?
             *  
             *  TODO: store serialization type so we can better guarantee de-serialization
             */
            LOG.error("Could not deserialize " + field.getName() + " for family map name: "
                    + columnFamilyNameFromHBaseObjectFieldAnnotatedField(field)
                    + " Did the serialization (KRYO/JSON) OR field type change from when you serialized the object?",
                    e);
        }
    }
    /*
     * Map results to fields annotated with @HBaseMapField
     */
    mapFieldBlock: {
        if (annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod
                .get(hBasePersistanceClass) != null) {
            final Field field = annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod
                    .get(hBasePersistanceClass).keySet().iterator().next();
            Map<String, String> map;
            if (field.getType().equals(Map.class)) {
                /*
                 *  If the object just calls for a Map give them a TreeMap();
                 */
                map = new TreeMap<String, String>();
            } else {
                /*
                 *  else try to create an instance of the Map class they are using
                 */
                try {
                    map = (Map<String, String>) Whitebox.getConstructor(field.getType())
                            .newInstance((Object[]) null);
                } catch (Exception e) {
                    /*
                     *  Done our best to guard against this but still possible
                     */
                    LOG.error("Could not create new instance of map.", e);
                    break mapFieldBlock;
                }
            }
            for (final Entry<byte[], byte[]> entry : columnFamilyResultMap
                    .get(columnFamilyNameFromHBaseMapFieldAnnotatedField(field)).entrySet()) {
                map.put(Bytes.toString(entry.getKey()), Bytes.toString(entry.getValue()));
            }
            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, type, map);
        }
    }

    return type;

}

From source file:com.mirth.connect.server.controllers.DefaultExtensionController.java

@Override
public void initPlugins() {
    // Order all the plugins by their weight before loading any of them.
    Map<String, String> pluginNameMap = new HashMap<String, String>();
    NavigableMap<Integer, List<String>> weightedPlugins = new TreeMap<Integer, List<String>>();
    for (PluginMetaData pmd : getPluginMetaData().values()) {
        if (isExtensionEnabled(pmd.getName())) {
            if (pmd.getServerClasses() != null) {
                for (PluginClass pluginClass : pmd.getServerClasses()) {
                    String clazzName = pluginClass.getName();
                    int weight = pluginClass.getWeight();
                    pluginNameMap.put(clazzName, pmd.getName());

                    List<String> classList = weightedPlugins.get(weight);
                    if (classList == null) {
                        classList = new ArrayList<String>();
                        weightedPlugins.put(weight, classList);
                    }/*from www. j  a v a 2  s . c o m*/

                    classList.add(clazzName);
                }
            }
        } else {
            logger.warn("Plugin \"" + pmd.getName() + "\" is not enabled.");
        }
    }

    // Load the plugins in order of their weight
    for (List<String> classList : weightedPlugins.descendingMap().values()) {
        for (String clazzName : classList) {
            String pluginName = pluginNameMap.get(clazzName);

            try {
                ServerPlugin serverPlugin = (ServerPlugin) Class.forName(clazzName).newInstance();

                if (serverPlugin instanceof ServicePlugin) {
                    ServicePlugin servicePlugin = (ServicePlugin) serverPlugin;
                    /*
                     * load any properties that may currently be in the database
                     */
                    Properties currentProperties = getPluginProperties(pluginName);
                    /* get the default properties for the plugin */
                    Properties defaultProperties = servicePlugin.getDefaultProperties();

                    /*
                     * if there are any properties that not currently set, set them to the the
                     * default
                     */
                    for (Object key : defaultProperties.keySet()) {
                        if (!currentProperties.containsKey(key)) {
                            currentProperties.put(key, defaultProperties.get(key));
                        }
                    }

                    /* save the properties to the database */
                    setPluginProperties(pluginName, currentProperties);

                    /*
                     * initialize the plugin with those properties and add it to the list of
                     * loaded plugins
                     */
                    servicePlugin.init(currentProperties);
                    servicePlugins.put(servicePlugin.getPluginPointName(), servicePlugin);
                    serverPlugins.add(servicePlugin);
                    logger.debug("sucessfully loaded server plugin: " + serverPlugin.getPluginPointName());
                }

                if (serverPlugin instanceof ChannelPlugin) {
                    ChannelPlugin channelPlugin = (ChannelPlugin) serverPlugin;
                    channelPlugins.put(channelPlugin.getPluginPointName(), channelPlugin);
                    serverPlugins.add(channelPlugin);
                    logger.debug(
                            "sucessfully loaded server channel plugin: " + serverPlugin.getPluginPointName());
                }

                if (serverPlugin instanceof CodeTemplateServerPlugin) {
                    CodeTemplateServerPlugin codeTemplateServerPlugin = (CodeTemplateServerPlugin) serverPlugin;
                    codeTemplateServerPlugins.put(codeTemplateServerPlugin.getPluginPointName(),
                            codeTemplateServerPlugin);
                    serverPlugins.add(codeTemplateServerPlugin);
                    logger.debug("sucessfully loaded server code template plugin: "
                            + serverPlugin.getPluginPointName());
                }

                if (serverPlugin instanceof DataTypeServerPlugin) {
                    DataTypeServerPlugin dataTypePlugin = (DataTypeServerPlugin) serverPlugin;
                    dataTypePlugins.put(dataTypePlugin.getPluginPointName(), dataTypePlugin);
                    serverPlugins.add(dataTypePlugin);
                    logger.debug(
                            "sucessfully loaded server data type plugin: " + serverPlugin.getPluginPointName());
                }

                if (serverPlugin instanceof ResourcePlugin) {
                    ResourcePlugin resourcePlugin = (ResourcePlugin) serverPlugin;
                    resourcePlugins.put(resourcePlugin.getPluginPointName(), resourcePlugin);
                    serverPlugins.add(resourcePlugin);
                    logger.debug("Successfully loaded resource plugin: " + resourcePlugin.getPluginPointName());
                }

                if (serverPlugin instanceof TransmissionModeProvider) {
                    TransmissionModeProvider transmissionModeProvider = (TransmissionModeProvider) serverPlugin;
                    transmissionModeProviders.put(transmissionModeProvider.getPluginPointName(),
                            transmissionModeProvider);
                    serverPlugins.add(transmissionModeProvider);
                    logger.debug("Successfully loaded transmission mode provider plugin: "
                            + transmissionModeProvider.getPluginPointName());
                }

                if (serverPlugin instanceof AuthorizationPlugin) {
                    AuthorizationPlugin authorizationPlugin = (AuthorizationPlugin) serverPlugin;

                    if (this.authorizationPlugin != null) {
                        throw new Exception("Multiple Authorization Plugins are not permitted.");
                    }

                    this.authorizationPlugin = authorizationPlugin;
                    serverPlugins.add(authorizationPlugin);
                    logger.debug("sucessfully loaded server authorization plugin: "
                            + serverPlugin.getPluginPointName());
                }
            } catch (Exception e) {
                logger.error("Error instantiating plugin: " + pluginName, e);
            }
        }
    }
}

From source file:de.hybris.platform.acceleratorcms.services.impl.RankingCMSRestrictionService.java

@Override
public Collection<AbstractPageModel> evaluatePages(final Collection<AbstractPageModel> pages,
        final RestrictionData data) {
    final NavigableMap<Integer, List<AbstractPageModel>> allowedPages = new TreeMap<>();

    final Collection<AbstractPageModel> defaultPages = getDefaultPages(pages);
    for (final AbstractPageModel page : pages) {
        if (defaultPages.contains(page)) {
            continue;
        }//from  w  w w  .j a  va  2 s .  c om

        final List<AbstractRestrictionModel> restrictions = page.getRestrictions();
        if (restrictions == null || restrictions.isEmpty()) {
            LOG.debug("Page [" + page.getName()
                    + "] is not default page and contains no restrictions. Skipping this page.");
        } else {
            LOG.debug("Evaluating restrictions for page [" + page.getName() + "].");
            final boolean onlyOneRestrictionMustApply = page.isOnlyOneRestrictionMustApply();
            final boolean allowed = evaluate(restrictions, data, onlyOneRestrictionMustApply);
            if (allowed) {
                LOG.debug("Adding page [" + page.getName() + "] to allowed pages");
                final Integer countOfMatchingRestrictions = Integer
                        .valueOf(onlyOneRestrictionMustApply ? 1 : restrictions.size());

                if (allowedPages.containsKey(countOfMatchingRestrictions)) {
                    // Add to existing list
                    allowedPages.get(countOfMatchingRestrictions).add(page);
                } else {
                    // Add a new entry
                    final List<AbstractPageModel> list = new ArrayList<>();
                    list.add(page);
                    allowedPages.put(countOfMatchingRestrictions, list);
                }
            }
        }
    }

    final List<AbstractPageModel> result = new ArrayList<>();

    if (MapUtils.isNotEmpty(allowedPages)) {
        // Take the highest match count
        result.addAll(allowedPages.lastEntry().getValue());
    } else {
        if (defaultPages.size() > 1) {
            LOG.warn(createMoreThanOneDefaultPageWarning(defaultPages));
        }
        if (CollectionUtils.isNotEmpty(defaultPages)) {
            LOG.debug("Returning default page");
            result.add(defaultPages.iterator().next());
        }
    }

    return result;
}

From source file:com.infochimps.hadoop.pig.hbase.StaticFamilyStorage.java

@Override
public Tuple getNext() throws IOException {
    try {/*from   ww  w  . j  ava  2s.c  o m*/
        if (!initialized) {
            Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass(),
                    new String[] { contextSignature });

            String projectedFields = p.getProperty(contextSignature + "_projectedFields");
            if (projectedFields != null) {
                requiredFieldList = (RequiredFieldList) ObjectSerializer.deserialize(projectedFields);
                pushProjection(requiredFieldList);
            }
            initialized = true;
        }
        if (reader.nextKeyValue()) {
            ImmutableBytesWritable rowKey = (ImmutableBytesWritable) reader.getCurrentKey();
            Result result = (Result) reader.getCurrentValue();

            int tupleSize = columnInfo_.size();

            // use a map of families -> qualifiers with the most recent
            // version of the cell. Fetching multiple vesions could be a
            // useful feature.
            NavigableMap<byte[], NavigableMap<byte[], byte[]>> resultsMap = result.getNoVersionMap();

            if (loadRowKey_) {
                tupleSize++;
            }
            Tuple tuple = TupleFactory.getInstance().newTuple(tupleSize);

            int startIndex = 0;
            if (loadRowKey_) {
                tuple.set(0, new DataByteArray(rowKey.get()));
                startIndex++;
            }

            for (int i = 0; i < columnInfo_.size(); ++i) {
                int currentIndex = startIndex + i;

                ColumnInfo columnInfo = columnInfo_.get(i);
                if (columnInfo.isColumnMap()) {
                    // It's a column family so we need to iterate and set all
                    // values found
                    NavigableMap<byte[], byte[]> cfResults = resultsMap.get(columnInfo.getColumnFamily());
                    DataBag bagged_family = BagFactory.getInstance().newDefaultBag();

                    if (cfResults != null) {
                        for (byte[] quantifier : cfResults.keySet()) {
                            // We need to check against the prefix filter to
                            // see if this value should be included. We can't
                            // just rely on the server-side filter, since a
                            // user could specify multiple CF filters for the
                            // same CF.
                            if (columnInfo.getColumnPrefix() == null || columnInfo.hasPrefixMatch(quantifier)) {

                                byte[] cell = cfResults.get(quantifier);
                                DataByteArray value = cell == null ? null : new DataByteArray(cell);

                                Tuple entry = TupleFactory.getInstance().newTuple(2);
                                entry.set(0, Bytes.toString(quantifier));
                                entry.set(1, value);
                                bagged_family.add(entry);
                            }
                        }
                    }
                    tuple.set(currentIndex, bagged_family);
                } else {
                    // It's a column so set the value                      
                    if (result.containsColumn(columnInfo.getColumnFamily(), columnInfo.getColumnName())) {
                        byte[] cell = result.getValue(columnInfo.getColumnFamily(), columnInfo.getColumnName());
                        DataByteArray value = (cell == null || cell.length == 0) ? new DataByteArray(ONE)
                                : new DataByteArray(cell);
                        tuple.set(currentIndex, value);
                    } else {
                        tuple.set(currentIndex, null);
                    }
                }
            }

            if (LOG.isDebugEnabled()) {
                for (int i = 0; i < tuple.size(); i++) {
                    LOG.debug("tuple value:" + tuple.get(i));
                }
            }
            return tuple;
        }
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
    return null;
}