Search in sources :

Example 11 with FlippingStrategy

use of org.ff4j.core.FlippingStrategy in project ff4j by ff4j.

the class XmlParser method parseFlipStrategy.

/**
 * Parsing strategy TAG.
 *
 * @param nnm
 *            current parend node
 * @param uid
 *            current feature uid
 * @return flipstrategy related to current feature.
 */
private FlippingStrategy parseFlipStrategy(Element flipStrategyTag, String uid) {
    NamedNodeMap nnm = flipStrategyTag.getAttributes();
    FlippingStrategy flipStrategy;
    if (nnm.getNamedItem(FLIPSTRATEGY_ATTCLASS) == null) {
        throw new IllegalArgumentException("Error syntax in configuration file : '" + FLIPSTRATEGY_ATTCLASS + "' is required for each flipstrategy (feature=" + uid + ")");
    }
    try {
        // Attribute CLASS
        String clazzName = nnm.getNamedItem(FLIPSTRATEGY_ATTCLASS).getNodeValue();
        flipStrategy = (FlippingStrategy) Class.forName(clazzName).newInstance();
        // LIST OF PARAMS
        Map<String, String> parameters = new LinkedHashMap<String, String>();
        NodeList initparamsNodes = flipStrategyTag.getElementsByTagName(FLIPSTRATEGY_PARAMTAG);
        for (int k = 0; k < initparamsNodes.getLength(); k++) {
            Element param = (Element) initparamsNodes.item(k);
            NamedNodeMap nnmap = param.getAttributes();
            // Check for required attribute name
            String currentParamName;
            if (nnmap.getNamedItem(FLIPSTRATEGY_PARAMNAME) == null) {
                throw new IllegalArgumentException(ERROR_SYNTAX_IN_CONFIGURATION_FILE + "'name' is required for each param in flipstrategy(check " + uid + ")");
            }
            currentParamName = nnmap.getNamedItem(FLIPSTRATEGY_PARAMNAME).getNodeValue();
            // Check for value attribute
            if (nnmap.getNamedItem(FLIPSTRATEGY_PARAMVALUE) != null) {
                parameters.put(currentParamName, nnmap.getNamedItem(FLIPSTRATEGY_PARAMVALUE).getNodeValue());
            } else if (param.getFirstChild() != null) {
                parameters.put(currentParamName, param.getFirstChild().getNodeValue());
            } else {
                throw new IllegalArgumentException("Parameter '" + currentParamName + "' in feature '" + uid + "' has no value, please check XML");
            }
        }
        flipStrategy.init(uid, parameters);
    } catch (Exception e) {
        throw new IllegalArgumentException("An error occurs during flipstrategy parsing TAG" + uid, e);
    }
    return flipStrategy;
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) FlippingStrategy(org.ff4j.core.FlippingStrategy) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) PropertyString(org.ff4j.property.PropertyString) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LinkedHashMap(java.util.LinkedHashMap)

Example 12 with FlippingStrategy

use of org.ff4j.core.FlippingStrategy in project ff4j by ff4j.

the class XmlParser method exportFeaturesPart.

/**
 * Export Features part of the XML.
 *
 * @param mapOfFeatures
 *      current map of feaures.
 *
 * @return
 *      all XML
 */
private String exportFeaturesPart(Map<String, Feature> mapOfFeatures) {
    // Create <features>
    StringBuilder sb = new StringBuilder(BEGIN_FEATURES);
    // Recreate Groups
    Map<String, List<Feature>> featuresPerGroup = new HashMap<String, List<Feature>>();
    if (mapOfFeatures != null && !mapOfFeatures.isEmpty()) {
        for (Feature feat : mapOfFeatures.values()) {
            String groupName = feat.getGroup();
            if (!featuresPerGroup.containsKey(groupName)) {
                featuresPerGroup.put(groupName, new ArrayList<Feature>());
            }
            featuresPerGroup.get(groupName).add(feat);
        }
    }
    for (Map.Entry<String, List<Feature>> groupName : featuresPerGroup.entrySet()) {
        // / Building featureGroup
        if (null != groupName.getKey() && !groupName.getKey().isEmpty()) {
            sb.append(" <" + FEATUREGROUP_TAG + " " + FEATUREGROUP_ATTNAME + "=\"" + groupName.getKey() + "\" >\n\n");
        }
        // Loop on feature
        for (Feature feat : groupName.getValue()) {
            sb.append(MessageFormat.format(XML_FEATURE, feat.getUid(), feat.getDescription(), feat.isEnable()));
            // <security>
            if (null != feat.getPermissions() && !feat.getPermissions().isEmpty()) {
                sb.append("   <" + SECURITY_TAG + ">\n");
                for (String auth : feat.getPermissions()) {
                    sb.append(MessageFormat.format(XML_AUTH, auth));
                }
                sb.append("   </" + SECURITY_TAG + ">\n");
            }
            // <flipstrategy>
            FlippingStrategy fs = feat.getFlippingStrategy();
            if (null != fs) {
                sb.append("   <" + FLIPSTRATEGY_TAG + " class=\"" + fs.getClass().getName() + "\" >\n");
                for (String p : fs.getInitParams().keySet()) {
                    sb.append("     <" + FLIPSTRATEGY_PARAMTAG + " " + FLIPSTRATEGY_PARAMNAME + "=\"");
                    sb.append(p);
                    sb.append("\" " + FLIPSTRATEGY_PARAMVALUE + "=\"");
                    // Escape special characters to build XML
                    // https://github.com/clun/ff4j/issues/63
                    String paramValue = fs.getInitParams().get(p);
                    sb.append(escapeXML(paramValue));
                    sb.append("\" />\n");
                }
                sb.append("   </" + FLIPSTRATEGY_TAG + ">\n");
            }
            // <custom-properties>
            Map<String, Property<?>> props = feat.getCustomProperties();
            if (props != null && !props.isEmpty()) {
                sb.append(BEGIN_CUSTOMPROPERTIES);
                sb.append(buildPropertiesPart(feat.getCustomProperties()));
                sb.append(END_CUSTOMPROPERTIES);
            }
            sb.append(END_FEATURE);
        }
        if (null != groupName.getKey() && !groupName.getKey().isEmpty()) {
            sb.append(" </" + FEATUREGROUP_TAG + ">\n\n");
        }
    }
    sb.append(END_FEATURES);
    return sb.toString();
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) FlippingStrategy(org.ff4j.core.FlippingStrategy) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) List(java.util.List) PropertyString(org.ff4j.property.PropertyString) Feature(org.ff4j.core.Feature) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) NamedNodeMap(org.w3c.dom.NamedNodeMap) Property(org.ff4j.property.Property)

Example 13 with FlippingStrategy

use of org.ff4j.core.FlippingStrategy in project ff4j by ff4j.

the class FeaturesController method renderPage.

/**
 * Both get and post operation will render the page.
 *
 * @param ctx
 *            current web context
 */
private void renderPage(WebContext ctx) {
    ctx.setVariable(KEY_TITLE, "Features");
    // Sort natural Order
    Map<String, Feature> mapOfFeatures = ff4j.getFeatureStore().readAll();
    List<String> featuresNames = Arrays.asList(mapOfFeatures.keySet().toArray(new String[0]));
    Collections.sort(featuresNames);
    List<Feature> orderedFeatures = new ArrayList<Feature>();
    List<FlippingStrategy> orderedStrategyUsed = new ArrayList<FlippingStrategy>();
    Map<String, FlippingStrategy> mapOfStrategyUsed = new HashMap<String, FlippingStrategy>();
    for (String featuName : featuresNames) {
        Feature feature = mapOfFeatures.get(featuName);
        orderedFeatures.add(feature);
        FlippingStrategy strategyTargered = feature.getFlippingStrategy();
        if (strategyTargered != null) {
            if (mapOfStrategyUsed.get(strategyTargered.getClass().getSimpleName()) != null) {
            } else {
                mapOfStrategyUsed.put(strategyTargered.getClass().getSimpleName(), strategyTargered);
                orderedStrategyUsed.add(strategyTargered);
            }
        }
    }
    ctx.setVariable("listOfFeatures", orderedFeatures);
    ctx.setVariable("listOfStrategyUsed", orderedStrategyUsed);
    // Get Group List
    List<String> myGroupList = new ArrayList<String>(ff4j.getFeatureStore().readAllGroups());
    Collections.sort(myGroupList);
    ctx.setVariable("groupList", myGroupList);
}
Also used : HashMap(java.util.HashMap) FlippingStrategy(org.ff4j.core.FlippingStrategy) ArrayList(java.util.ArrayList) Feature(org.ff4j.core.Feature)

Example 14 with FlippingStrategy

use of org.ff4j.core.FlippingStrategy in project ff4j by ff4j.

the class ConsoleOperations method createFeature.

/**
 * User action to create a new Feature.
 *
 * @param req
 *            http request containing operation parameters
 */
public static void createFeature(FF4j ff4j, HttpServletRequest req) {
    // uid
    final String featureId = req.getParameter(FEATID);
    if (featureId != null && !featureId.isEmpty()) {
        Feature fp = new Feature(featureId, false);
        // Description
        final String featureDesc = req.getParameter(DESCRIPTION);
        if (null != featureDesc && !featureDesc.isEmpty()) {
            fp.setDescription(featureDesc);
        }
        // GroupName
        final String groupName = req.getParameter(GROUPNAME);
        if (null != groupName && !groupName.isEmpty()) {
            fp.setGroup(groupName);
        }
        // Strategy
        final String strategy = req.getParameter(STRATEGY);
        if (null != strategy && !strategy.isEmpty()) {
            try {
                Class<?> strategyClass = Class.forName(strategy);
                FlippingStrategy fstrategy = (FlippingStrategy) strategyClass.newInstance();
                final String strategyParams = req.getParameter(STRATEGY_INIT);
                if (null != strategyParams && !strategyParams.isEmpty()) {
                    Map<String, String> initParams = new HashMap<String, String>();
                    String[] params = strategyParams.split(";");
                    for (String currentP : params) {
                        String[] cur = currentP.split("=");
                        if (cur.length < 2) {
                            throw new IllegalArgumentException("Invalid Syntax : param1=val1,val2;param2=val3,val4");
                        }
                        initParams.put(cur[0], cur[1]);
                    }
                    fstrategy.init(featureId, initParams);
                }
                fp.setFlippingStrategy(fstrategy);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("Cannot find strategy class", e);
            } catch (InstantiationException e) {
                throw new IllegalArgumentException("Cannot instantiate strategy", e);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException("Cannot instantiate : no public constructor", e);
            }
        }
        // Permissions
        final String permission = req.getParameter(PERMISSION);
        if (null != permission && PERMISSION_RESTRICTED.equals(permission)) {
            @SuppressWarnings("unchecked") Map<String, Object> parameters = req.getParameterMap();
            Set<String> permissions = new HashSet<String>();
            for (String key : parameters.keySet()) {
                if (key.startsWith(PREFIX_CHECKBOX)) {
                    permissions.add(key.replace(PREFIX_CHECKBOX, ""));
                }
            }
            fp.setPermissions(permissions);
        }
        // Creation
        ff4j.getFeatureStore().create(fp);
        LOGGER.info(featureId + " has been created");
    }
}
Also used : HashMap(java.util.HashMap) Feature(org.ff4j.core.Feature) FlippingStrategy(org.ff4j.core.FlippingStrategy) HashSet(java.util.HashSet)

Example 15 with FlippingStrategy

use of org.ff4j.core.FlippingStrategy in project ff4j by ff4j.

the class FeatureStoreTestSupport method testUpdateFeatureCoreData.

/**
 * TDD.
 */
@Test
public void testUpdateFeatureCoreData() {
    // Parameters
    String newDescription = "new-description";
    FlippingStrategy newStrategy = new PonderationStrategy(0.12);
    // Given
    assertFf4j.assertThatFeatureExist(F1);
    Assert.assertFalse(newDescription.equals(testedStore.read(F1).getDescription()));
    // When
    Feature fpBis = testedStore.read(F1);
    fpBis.setDescription(newDescription);
    fpBis.setFlippingStrategy(newStrategy);
    testedStore.update(fpBis);
    // Then
    Feature updatedFeature = testedStore.read(F1);
    Assert.assertTrue(newDescription.equals(updatedFeature.getDescription()));
    Assert.assertNotNull(updatedFeature.getFlippingStrategy());
    Assert.assertEquals(newStrategy.toString(), updatedFeature.getFlippingStrategy().toString());
}
Also used : PonderationStrategy(org.ff4j.strategy.PonderationStrategy) FlippingStrategy(org.ff4j.core.FlippingStrategy) PropertyString(org.ff4j.property.PropertyString) Feature(org.ff4j.core.Feature) Test(org.junit.Test)

Aggregations

FlippingStrategy (org.ff4j.core.FlippingStrategy)18 Feature (org.ff4j.core.Feature)9 PropertyString (org.ff4j.property.PropertyString)7 Test (org.junit.Test)7 HashMap (java.util.HashMap)6 FlippingExecutionContext (org.ff4j.core.FlippingExecutionContext)4 PonderationStrategy (org.ff4j.strategy.PonderationStrategy)4 Map (java.util.Map)3 ArrayList (java.util.ArrayList)2 LinkedHashMap (java.util.LinkedHashMap)2 InMemoryFeatureStore (org.ff4j.store.InMemoryFeatureStore)2 AbstractFf4jTest (org.ff4j.test.AbstractFf4jTest)2 NamedNodeMap (org.w3c.dom.NamedNodeMap)2 NodeList (org.w3c.dom.NodeList)2 IOException (java.io.IOException)1 HashSet (java.util.HashSet)1 List (java.util.List)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 FeatureStore (org.ff4j.core.FeatureStore)1 FeatureAccessException (org.ff4j.exception.FeatureAccessException)1