Example usage for java.util Map containsValue

List of usage examples for java.util Map containsValue

Introduction

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

Prototype

boolean containsValue(Object value);

Source Link

Document

Returns true if this map maps one or more keys to the specified value.

Usage

From source file:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java

/**
 * Establish relationship with related domain class
 *
 * @param entity/*ww  w. ja va  2s .c  o  m*/
 * @param property Establishes a relationship between this class and the domain class property
 * @param context
 * @param hasOneMap
 */
private ToOne establishDomainClassRelationship(PersistentEntity entity, PropertyDescriptor property,
        MappingContext context, Map hasOneMap) {
    ToOne association = null;
    Class propType = property.getPropertyType();
    ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(propType);

    // establish relationship to type
    Map relatedClassRelationships = getAllAssociationMap(cpf);
    Map mappedBy = cpf.getStaticPropertyValue(MAPPED_BY, Map.class);
    if (mappedBy == null)
        mappedBy = Collections.emptyMap();

    Class<?> relatedClassPropertyType = null;

    // if there is a relationships map use that to find out
    // whether it is mapped to a Set
    String relatedClassPropertyName = null;

    if (!forceUnidirectional(property, mappedBy)) {
        if (relatedClassRelationships != null && !relatedClassRelationships.isEmpty()) {

            PropertyDescriptor[] descriptors = ReflectionUtils.getPropertiesOfType(entity.getJavaClass(),
                    propType);
            relatedClassPropertyName = findOneToManyThatMatchesType(entity, relatedClassRelationships);
            // if there is only one property on many-to-one side of the relationship then
            // try to establish if it is bidirectional
            if (descriptors.length == 1
                    && isNotMappedToDifferentProperty(property, relatedClassPropertyName, mappedBy)) {
                if (StringUtils.hasText(relatedClassPropertyName)) {
                    // get the type of the property
                    relatedClassPropertyType = cpf.getPropertyType(relatedClassPropertyName);
                }
            }
            // if there is more than one property on the many-to-one side then we need to either
            // find out if there is a mappedBy property or whether a convention is used to decide
            // on the mapping property
            else if (descriptors.length > 1) {
                if (mappedBy.containsValue(property.getName())) {
                    for (Object o : mappedBy.keySet()) {
                        String mappedByPropertyName = (String) o;
                        if (property.getName().equals(mappedBy.get(mappedByPropertyName))) {
                            Class<?> mappedByRelatedType = (Class<?>) relatedClassRelationships
                                    .get(mappedByPropertyName);
                            if (mappedByRelatedType != null && propType.isAssignableFrom(mappedByRelatedType))
                                relatedClassPropertyType = cpf.getPropertyType(mappedByPropertyName);
                        }
                    }
                } else {
                    String classNameAsProperty = Introspector.decapitalize(propType.getName());
                    if (property.getName().equals(classNameAsProperty)
                            && !mappedBy.containsKey(relatedClassPropertyName)) {
                        relatedClassPropertyType = cpf.getPropertyType(relatedClassPropertyName);
                    }
                }
            }
        }

        // otherwise retrieve all the properties of the type from the associated class
        if (relatedClassPropertyType == null) {
            PropertyDescriptor[] descriptors = ReflectionUtils.getPropertiesOfType(propType,
                    entity.getJavaClass());

            // if there is only one then the association is established
            if (descriptors.length == 1) {
                relatedClassPropertyType = descriptors[0].getPropertyType();
                relatedClassPropertyName = descriptors[0].getName();
            }
        }
    }

    //    establish relationship based on this type
    // uni-directional one-to-one

    final boolean isAssociationEntity = isPersistentEntity(relatedClassPropertyType);
    if (relatedClassPropertyType == null || isAssociationEntity) {
        association = propertyFactory.createOneToOne(entity, context, property);

        if (hasOneMap.containsKey(property.getName())) {
            association.setForeignKeyInChild(true);
        }
    }
    // bi-directional many-to-one
    else if (Collection.class.isAssignableFrom(relatedClassPropertyType)
            || Map.class.isAssignableFrom(relatedClassPropertyType)) {
        association = propertyFactory.createManyToOne(entity, context, property);
    }

    // bi-directional
    if (association != null) {
        PersistentEntity associatedEntity = getOrCreateAssociatedEntity(entity, context, propType);
        association.setAssociatedEntity(associatedEntity);
        boolean isNotCircular = entity != associatedEntity;
        if (relatedClassPropertyName != null && isNotCircular) {
            association.setReferencedPropertyName(relatedClassPropertyName);
        }
    }

    return association;
}

From source file:org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass.java

/**
 * Establish relationship with related domain class
 *
 * @param property Establishes a relationship between this class and the domain class property
 *///from   w  w w. j  av a  2s. c  o m
private void establishDomainClassRelationship(DefaultGrailsDomainClassProperty property) {
    Class<?> propType = property.getType();
    if (embedded.contains(property.getName())) {
        property.setEmbedded(true);
        return;
    }

    // establish relationship to type
    Map relatedClassRelationships = GrailsDomainConfigurationUtil.getAssociationMap(propType);
    Map mappedBy = GrailsDomainConfigurationUtil.getMappedByMap(propType);

    Class<?> relatedClassPropertyType = null;

    if (mappedBy.containsKey(property.getName()) && mappedBy.get(property.getName()) == null)
        return;

    // if there is a relationships map use that to find out
    // whether it is mapped to a Set
    if (relatedClassRelationships != null && !relatedClassRelationships.isEmpty()) {

        String relatedClassPropertyName = findOneToManyThatMatchesType(property, relatedClassRelationships);
        PropertyDescriptor[] descriptors = GrailsClassUtils.getPropertiesOfType(getClazz(), property.getType());

        // if there is only one property on many-to-one side of the relationship then
        // try to establish if it is bidirectional
        if (descriptors.length == 1
                && isNotMappedToDifferentProperty(property, relatedClassPropertyName, mappedBy)) {
            if (!StringUtils.isBlank(relatedClassPropertyName)) {
                property.setReferencePropertyName(relatedClassPropertyName);
                // get the type of the property
                relatedClassPropertyType = GrailsClassUtils.getPropertyType(propType, relatedClassPropertyName);
            }
        }
        // if there is more than one property on the many-to-one side then we need to either
        // find out if there is a mappedBy property or whether a convention is used to decide
        // on the mapping property
        else if (descriptors.length > 1) {
            if (mappedBy.containsValue(property.getName())) {
                for (Object o : mappedBy.keySet()) {
                    String mappedByPropertyName = (String) o;
                    if (property.getName().equals(mappedBy.get(mappedByPropertyName))) {
                        Class<?> mappedByRelatedType = (Class<?>) relatedClassRelationships
                                .get(mappedByPropertyName);
                        if (mappedByRelatedType != null && propType.isAssignableFrom(mappedByRelatedType))
                            relatedClassPropertyType = GrailsClassUtils.getPropertyType(propType,
                                    mappedByPropertyName);
                    }
                }
            } else {
                String classNameAsProperty = GrailsNameUtils.getPropertyName(propType);
                if (property.getName().equals(classNameAsProperty)
                        && !mappedBy.containsKey(relatedClassPropertyName)) {
                    relatedClassPropertyType = GrailsClassUtils.getPropertyType(propType,
                            relatedClassPropertyName);
                }
            }
        }
    }
    // otherwise retrieve all the properties of the type from the associated class
    if (relatedClassPropertyType == null) {
        PropertyDescriptor[] descriptors = GrailsClassUtils.getPropertiesOfType(propType, getClazz());

        // if there is only one then the association is established
        if (descriptors.length == 1) {
            relatedClassPropertyType = descriptors[0].getPropertyType();
        }
    }

    //    establish relationship based on this type
    establishDomainClassRelationshipToType(property, relatedClassPropertyType);
}

From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java

/**
 * Save changed parameters in {@code nuxeo.conf} calculating templates if changedParameters contains a value for
 * {@link #PARAM_TEMPLATE_DBNAME}. If a parameter value is empty ("" or null), then the property is unset.
 * {@link #PARAM_WIZARD_DONE}, {@link #PARAM_TEMPLATES_NAME} and {@link #PARAM_FORCE_GENERATION} cannot be unset,
 * but their value can be changed.<br/>
 * This method does not check values in map: use {@link #saveFilteredConfiguration(Map)} for parameters filtering.
 *
 * @param changedParameters Map of modified parameters
 * @param setGenerationOnceToFalse If generation was on (true or once), then set it to false or not?
 * @param setGenerationFalseToOnce If generation was off (false), then set it to once?
 * @see #saveFilteredConfiguration(Map)//from   w w  w  . j a  va2 s  .  c  om
 * @since 5.5
 */
public void saveConfiguration(Map<String, String> changedParameters, boolean setGenerationOnceToFalse,
        boolean setGenerationFalseToOnce) throws ConfigurationException {
    setOnceToFalse = setGenerationOnceToFalse;
    setFalseToOnce = setGenerationFalseToOnce;
    updateStoredConfig();
    String newDbTemplate = changedParameters.remove(PARAM_TEMPLATE_DBNAME);
    if (newDbTemplate != null) {
        changedParameters.put(PARAM_TEMPLATES_NAME, rebuildTemplatesStr(newDbTemplate));
    }
    newDbTemplate = changedParameters.remove(PARAM_TEMPLATE_DBNOSQL_NAME);
    if (newDbTemplate != null) {
        changedParameters.put(PARAM_TEMPLATES_NAME, rebuildTemplatesStr(newDbTemplate));
    }
    if (changedParameters.containsValue(null) || changedParameters.containsValue("")) {
        // There are properties to unset
        Set<String> propertiesToUnset = new HashSet<>();
        for (String key : changedParameters.keySet()) {
            if (StringUtils.isEmpty(changedParameters.get(key))) {
                propertiesToUnset.add(key);
            }
        }
        for (String key : propertiesToUnset) {
            changedParameters.remove(key);
            userConfig.remove(key);
        }
    }
    userConfig.putAll(changedParameters);
    writeConfiguration();
    updateStoredConfig();
}

From source file:com.redhat.rhn.frontend.action.kickstart.KickstartHelper.java

/**
 * Parse a ks url and return a Map of options
 * Example:/*from w w w  .  ja v  a  2 s .  com*/
 *     "ks/org/3756992x3d9f6e2d5717e264c89b5ac18eb0c59e/label/kslabelfoo";
 *
 * NOTE: This method also updates the KickstartSession.state field
 * to "configuration_accessed"
 *
 * @param url to parse
 * @return Map of options.  Usually containing host, ksdata, label and org_id
 */
public Map<String, Object> parseKickstartUrl(String url) {
    Map<String, Object> retval = new HashMap<String, Object>();
    KickstartData ksdata = null;
    Map<String, String> options = new HashMap<String, String>();
    log.debug("url: " + url);
    List<String> rawopts = Arrays.asList(StringUtils.split(url, '/'));

    for (Iterator<String> iter = rawopts.iterator(); iter.hasNext();) {
        String name = iter.next();
        if (iter.hasNext()) {
            String value = iter.next();
            options.put(name, value);
        }
    }

    log.debug("Options: " + options);

    String remoteAddr = getClientIp();

    // Process the org
    if (options.containsKey(ORG)) {
        String id = options.get(ORG);
        retval.put(ORG_ID, id);
    } else {
        retval.put(ORG_ID, OrgFactory.getSatelliteOrg().getId().toString());
    }
    String mode = ORG_DEFAULT; // go ahead and make this the default profile
    // Process the session
    // /kickstart/ks/session/2xb7d56e8958b0425e762cc74e8705d8e7
    if (options.containsKey(SESSION)) {
        // update session
        String hashed = options.get(SESSION);
        String[] ids = SessionSwap.extractData(hashed);
        retval.put(SESSION_ID, ids[0]);
        Long kssid = new Long(ids[0]);
        log.debug("sessionid: " + kssid);
        KickstartSessionUpdateCommand cmd = new KickstartSessionUpdateCommand(kssid);
        ksdata = cmd.getKsdata();
        retval.put(SESSION, cmd.getKickstartSession());
        log.debug("session: " + retval.get(SESSION));
        cmd.setSessionState(KickstartFactory.SESSION_STATE_CONFIG_ACCESSED);
        cmd.store();
        mode = SESSION;
    }

    log.debug("org_id: " + retval.get(ORG_ID));

    //TODO: reconsider/cleanup this logic flow
    if (retval.get(ORG_ID) != null) {

        // Process label
        if (options.containsKey(LABEL)) {
            retval.put(LABEL, options.get(LABEL));
            mode = LABEL;
        } else if (options.containsKey(VIEW_LABEL)) {
            retval.put(VIEW_LABEL, options.get(VIEW_LABEL));
            retval.put(LABEL, options.get(VIEW_LABEL));
            mode = LABEL;
        } else if (options.containsValue(IP_RANGE)) {
            mode = IP_RANGE;
        }

        Org org = OrgFactory.lookupById(new Long((String) retval.get(ORG_ID)));
        if (mode.equals(LABEL)) {
            String label = (String) retval.get(LABEL);
            ksdata = KickstartFactory.lookupKickstartDataByLabelAndOrgId(label, org.getId());
        } else if (mode.equals(IP_RANGE)) {
            log.debug("Ip_range mode");
            IpAddress clientIp = new IpAddress(remoteAddr);
            ksdata = KickstartManager.getInstance().findProfileForIpAddress(clientIp, org);
        } else if (mode.equals(ORG_DEFAULT)) {
            //process org_default
            log.debug("Org_default mode.");
            ksdata = getOrgDefaultProfile(org);
        }

        if (log.isDebugEnabled()) {
            log.debug("session                        : " + retval.get(SESSION));
            log.debug("options.containsKey(VIEW_LABEL): " + options.containsKey(VIEW_LABEL));
            log.debug("ksdata                         : " + ksdata);
        }
    }
    // Add the host.
    retval.put(HOST, getKickstartHost());
    // Add ksdata
    retval.put(KSDATA, ksdata);

    if (retval.size() == 0) {
        retval = null;
    }
    return retval;
}

From source file:org.kepler.gui.MenuMapper.java

/**
 * Recurse through all the submenu heirarchy beneath the passed JMenu
 * parameter, and for each "leaf node" (ie a menu item that is not a
 * container for other menu items), add the Action and its menu path to the
 * passed Map// ww  w. jav a  2s. c  o m
 * 
 * @param nextMenuItem
 *            the JMenu to recurse into
 * @param menuPathBuff
 *            a delimited String representation of the hierarchical "path"
 *            to this menu item. This will be used as the key in the
 *            actionsMap. For example, the "Graph Editor" menu item beneath
 *            the "New" item on the "File" menu would have a menuPath of
 *            File->New->Graph Editor. Delimeter is "->" (no quotes), and
 *            spaces are allowed within menu text strings, but not around
 *            the delimiters; i.e: New->Graph Editor is OK, but File ->New
 *            is not.
 * @param MENU_PATH_DELIMITER
 *            String
 * @param actionsMap
 *            the Map containing key => value pairs of the form: menuPath
 *            (as described above) => Action (the javax.swing.Action
 *            assigned to this menu item)
 */
public static void storePTIIMenuItems(JMenuItem nextMenuItem, StringBuffer menuPathBuff,
        final String MENU_PATH_DELIMITER, Map<String, Action> actionsMap) {

    menuPathBuff.append(MENU_PATH_DELIMITER);
    if (nextMenuItem != null && nextMenuItem.getText() != null) {
        String str = nextMenuItem.getText();
        // do not make the recent files menu item upper case since
        // it contains paths in the file system.
        if (menuPathBuff.toString().startsWith("FILE->RECENT FILES->")) {
            menuPathBuff = new StringBuffer("File->Recent Files->");
        } else {
            str = str.toUpperCase();
        }
        menuPathBuff.append(str);
    }

    if (isDebugging) {
        log.debug(menuPathBuff.toString());
    }
    // System.out.println(menuPathBuff.toString());

    if (nextMenuItem instanceof JMenu) {
        storePTIITopLevelMenus((JMenu) nextMenuItem, menuPathBuff.toString(), MENU_PATH_DELIMITER, actionsMap);
    } else {
        Action nextAction = nextMenuItem.getAction();
        // if there is no Action, look for an ActionListener
        // System.out.println("Processing menu " + nextMenuItem.getText());
        if (nextAction == null) {
            final ActionListener[] actionListeners = nextMenuItem.getActionListeners();
            // System.out.println("No Action for " + nextMenuItem.getText()
            // + "; found " + actionListeners.length
            // + " ActionListeners");
            if (actionListeners.length > 0) {
                if (isDebugging) {
                    log.debug(actionListeners[0].getClass().getName());
                }
                // ASSUMPTION: there is only one ActionListener
                nextAction = new AbstractAction() {
                    public void actionPerformed(ActionEvent a) {
                        actionListeners[0].actionPerformed(a);
                    }
                };
                // add all these values - @see diva.gui.GUIUtilities
                nextAction.putValue(Action.NAME, nextMenuItem.getText());
                // System.out.println("storing ptII action for menu " +
                // nextMenuItem.getText());
                nextAction.putValue(GUIUtilities.LARGE_ICON, nextMenuItem.getIcon());
                nextAction.putValue(GUIUtilities.MNEMONIC_KEY, new Integer(nextMenuItem.getMnemonic()));
                nextAction.putValue("tooltip", nextMenuItem.getToolTipText());
                nextAction.putValue(GUIUtilities.ACCELERATOR_KEY, nextMenuItem.getAccelerator());
                nextAction.putValue("menuItem", nextMenuItem);
            } else {
                if (isDebugging) {
                    log.warn("No Action or ActionListener found for " + nextMenuItem.getText());
                }
            }
        }
        if (!actionsMap.containsValue(nextAction)) {
            actionsMap.put(menuPathBuff.toString(), nextAction);
            if (isDebugging) {
                log.debug(menuPathBuff.toString() + " :: ACTION: " + nextAction);
            }
        }
    }
}

From source file:org.opentaps.domain.container.PojoGeneratorContainer.java

private boolean generateServices() throws ContainerException {

    // check the service template file
    File serviceTemplateFile = new File(serviceTemplate);
    if (!serviceTemplateFile.canRead()) {
        throw new ContainerException("Unable to read service template file: [" + serviceTemplate + "]");
    }/* w  ww  .  j  a va2s  .  co  m*/

    // get services list
    LocalDispatcher localDispatcher = GenericDispatcher.getLocalDispatcher("webtools", delegator);
    DispatchContext dispatchContext = localDispatcher.getDispatchContext();
    Set<String> serviceNames = dispatchContext.getAllServiceNames();

    // record errors for summary
    List<String> errorEntities = new LinkedList<String>();

    int totalGeneratedClasses = 0;
    if (serviceNames != null && serviceNames.size() > 0) {
        Debug.logImportant("=-=-=-=-=-=-= Generating the POJO services ...", MODULE);
        Map<String, String> generatedServices = new HashMap<String, String>();
        for (String serviceName : serviceNames) {
            ModelService modelService = null;
            try {
                modelService = dispatchContext.getModelService(serviceName);
            } catch (GenericServiceException e) {
                Debug.logError(e, MODULE);
            }

            if (modelService == null) {
                errorEntities.add(serviceName);
                Debug.logError("Error getting the service model for [" + serviceName + "]", MODULE);
                continue;
            }

            // service names can include characters which cannot be used in class names
            // and we also need to upper the first char to conform to the Java standard
            String serviceClassName = makeClassName(serviceName) + "Service";

            // check if we have a conflict after the name change
            if (generatedServices.containsKey(serviceClassName)) {
                Debug.logError("Service [" + serviceName + "] has conflicting class name with service ["
                        + generatedServices.get(serviceClassName) + "], both resolved to [" + serviceClassName
                        + "]", MODULE);
                errorEntities.add(serviceName);
                continue;
            }

            Map<String, Object> entityInfo = new HashMap<String, Object>();

            // distinct types for the import section
            Set<String> types = new TreeSet<String>();
            types.add("java.util.Map");
            types.add("java.util.Set");
            types.add("javolution.util.FastMap");
            types.add("javolution.util.FastSet");
            types.add("org.opentaps.foundation.infrastructure.User");
            // a type for each field during declarations
            Map<String, String> fieldTypes = new TreeMap<String, String>();
            Map<String, String> fieldRealTypes = new TreeMap<String, String>();
            // temporary, those are stored at the end of each param so we test duplicates
            Map<String, ModelParam> fieldModels = new TreeMap<String, ModelParam>();
            // map parameter names to valid java field names
            Map<String, String> inFieldNames = new TreeMap<String, String>();
            Map<String, String> outFieldNames = new TreeMap<String, String>();
            // read the service parameters
            Map<String, String> paramNames = new TreeMap<String, String>(); // for the enums
            Map<String, ModelParam> inParams = new TreeMap<String, ModelParam>();
            Map<String, ModelParam> outParams = new TreeMap<String, ModelParam>();
            // names of the get and set methods, we need two sets for In and Out parameters
            Map<String, String> inGetMethodNames = new TreeMap<String, String>();
            Map<String, String> inSetMethodNames = new TreeMap<String, String>();
            Map<String, String> outGetMethodNames = new TreeMap<String, String>();
            Map<String, String> outSetMethodNames = new TreeMap<String, String>();

            boolean hasError = false;
            for (ModelParam p : modelService.getModelParamList()) {
                // use the class name transform, we will append "in" or "out" to get the field name
                String fieldName = makeClassName(p.name);
                String shortFieldName = Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1);

                // check that two different parameter names did not translate into the same java field
                // eg: some.param and someParam
                if ((!paramNames.containsKey(p.name) && paramNames.containsValue(shortFieldName))) {
                    errorEntities.add(serviceName);
                    Debug.logError("Service [" + serviceName + "] has parameter [" + p.name
                            + "] which conflicts with another of its parameters that was translated to the same java field ["
                            + fieldName + "]", MODULE);
                    hasError = true;
                    break;
                }

                // for the enumeration
                paramNames.put(p.name, shortFieldName);

                try {
                    if (p.isIn()) {
                        inParams.put(p.name, p);
                        inGetMethodNames.put(p.name, accessorMethodName("getIn", fieldName));
                        inSetMethodNames.put(p.name, accessorMethodName("setIn", fieldName));
                        if (inFieldNames.containsKey(p.name)) {
                            Debug.logWarning("Service [" + serviceName + "] redefines IN parameter [" + p.name
                                    + "] (used attribute instead of override, or redefined an auto attribute)",
                                    MODULE);
                        }
                        inFieldNames.put(p.name, "in" + fieldName);
                    }
                    // no else, can be INOUT
                    if (p.isOut()) {
                        outParams.put(p.name, p);
                        outGetMethodNames.put(p.name, accessorMethodName("getOut", fieldName));
                        outSetMethodNames.put(p.name, accessorMethodName("setOut", fieldName));
                        if (outFieldNames.containsKey(p.name)) {
                            Debug.logWarning("Service [" + serviceName + "] redefines OUT parameter [" + p.name
                                    + "] (used attribute instead of override, or redefined an auto attribute)",
                                    MODULE);
                        }
                        outFieldNames.put(p.name, "out" + fieldName);
                    }
                } catch (IllegalArgumentException e) {
                    errorEntities.add(serviceName);
                    Debug.logError(e, MODULE);
                    hasError = true;
                    break;
                }
                // this is the short type: ie, java.lang.String -> String; java.util.HashMap -> HashMap, etc.
                String type = p.type;
                // replace $ with dot in some types that points to inner classes
                type = type.replaceAll("\\$", ".");
                String shortType = type;
                int idx = shortType.lastIndexOf(".");

                if (idx > 0) {
                    // need to work around some compilation issues for service that are using a type defined in their own
                    // application, fallback to the generic Object
                    if (shortType.startsWith("org.opentaps.") && !shortType.startsWith("org.opentaps.common")) {
                        Debug.logWarning("Service [" + serviceName + "] field [" + p.name + "] has type ["
                                + type + "] which is not available yet, falling back to 'Object'.", MODULE);
                        shortType = "Object";
                        fieldRealTypes.put(p.name, type);
                    } else {
                        shortType = shortType.substring(idx + 1);
                        types.add(type);
                    }
                } else {
                    // some short types also need to be imported
                    if (Arrays.asList("List", "Map", "Set", "Date").contains(type)) {
                        types.add("java.util." + type);
                    } else if (Arrays.asList("GenericValue", "GenericEntity", "GenericPK").contains(type)) {
                        types.add("org.ofbiz.entity." + type);
                    } else if (Arrays.asList("Timestamp").contains(type)) {
                        types.add("java.sql." + type);
                    } else if ("BigDecimal".equals(type)) {
                        types.add("java.math." + type);
                    }
                }

                // check that if a parameter is defined IN and OUT it has the same type
                if (fieldTypes.containsKey(p.name) && !shortType.equals(fieldTypes.get(p.name))) {
                    // this can happen if the service redefined an internal parameter
                    ModelParam p2 = fieldModels.get(p.name);
                    if (p2 != null && (p2.internal || p.internal)) {
                        Debug.logWarning("Service [" + serviceName + "] has parameter [" + p.name
                                + "] with type [" + shortType
                                + "] which conflicts with an internal service parameter of the same name and with type ["
                                + fieldTypes.get(p.name) + "]", MODULE);
                    } else {
                        errorEntities.add(serviceName);
                        Debug.logError("Service [" + serviceName + "] has parameter [" + p.name
                                + "] with type [" + shortType
                                + "] which conflicts with another definition of this parameter that has type ["
                                + fieldTypes.get(p.name) + "]", MODULE);
                        hasError = true;
                        break;
                    }
                }

                fieldTypes.put(p.name, shortType);
                fieldModels.put(p.name, p);
            }

            if (hasError) {
                continue;
            }

            entityInfo.put("name", serviceName);
            entityInfo.put("className", serviceClassName);
            entityInfo.put("types", types);
            entityInfo.put("fieldTypes", fieldTypes);
            entityInfo.put("fieldRealTypes", fieldRealTypes);
            entityInfo.put("inFieldNames", inFieldNames);
            entityInfo.put("outFieldNames", outFieldNames);
            entityInfo.put("inGetMethodNames", inGetMethodNames);
            entityInfo.put("inSetMethodNames", inSetMethodNames);
            entityInfo.put("outGetMethodNames", outGetMethodNames);
            entityInfo.put("outSetMethodNames", outSetMethodNames);
            entityInfo.put("paramNames", paramNames);
            entityInfo.put("inParams", inParams);
            entityInfo.put("outParams", outParams);
            entityInfo.put("requiresAuth", modelService.auth);
            entityInfo.put("requiresNewTransaction", modelService.requireNewTransaction);
            entityInfo.put("usesTransaction", modelService.useTransaction);
            entityInfo.put("serviceDescription", modelService.description);
            entityInfo.put("serviceEngine", modelService.engineName);
            entityInfo.put("serviceLocation", modelService.location);
            entityInfo.put("serviceInvoke", modelService.invoke);
            String serviceDefPath = null;
            try {
                serviceDefPath = UtilURL.getOfbizHomeRelativeLocation(new URL(modelService.definitionLocation));
            } catch (MalformedURLException e) {
                Debug.logError(e.getMessage(), MODULE);
            }
            entityInfo.put("serviceDefinition", serviceDefPath);

            // render it as FTL
            Writer writer = new StringWriter();
            try {
                FreeMarkerWorker.renderTemplateAtLocation(serviceTemplate, entityInfo, writer);
            } catch (MalformedURLException e) {
                Debug.logError(e, MODULE);
                errorEntities.add(serviceName);
                break;
            } catch (TemplateException e) {
                Debug.logError(e, MODULE);
                errorEntities.add(serviceName);
                break;
            } catch (IOException e) {
                Debug.logError(e, MODULE);
                errorEntities.add(serviceName);
                break;
            } catch (IllegalArgumentException e) {
                Debug.logError(e, MODULE);
                errorEntities.add(serviceName);
                break;
            }

            // write it as a Java file
            File file = new File(serviceOutputPath + serviceClassName + fileExtension);
            try {
                FileUtils.writeStringToFile(file, writer.toString(), "UTF-8");
            } catch (IOException e) {
                Debug.logError(e,
                        "Aborting, error writing file " + serviceOutputPath + serviceClassName + fileExtension,
                        MODULE);
                errorEntities.add(serviceName);
                break;
            }
            // increment counter
            generatedServices.put(serviceClassName, serviceName);
            totalGeneratedClasses++;
        }
    } else {
        Debug.logImportant("=-=-=-=-=-=-= No service found.", MODULE);
    }

    // error summary
    if (errorEntities.size() > 0) {
        Debug.logImportant("The following services could not be generated:", MODULE);
        for (String name : errorEntities) {
            Debug.logImportant(name, MODULE);
        }
    }

    Debug.logImportant("=-=-=-=-=-=-= Finished the POJO services generation with " + totalGeneratedClasses
            + " classes generated.", MODULE);

    if (errorEntities.size() > 0) {
        return false;
    }

    return true;
}

From source file:com.amalto.workbench.utils.Util.java

private static void addImport(XSDSchema xsdSchema, List<XSDImport> imports) {
    Map<String, String> nsMap = xsdSchema.getQNamePrefixToNamespaceMap();
    int imp = 0;//ww  w .  j  a  va  2 s  .c o m
    for (XSDImport xsdImport : imports) {
        String ns = xsdImport.getNamespace();
        if (ns.equals("")) { //$NON-NLS-1$
            continue;
        }
        int last = ns.lastIndexOf("/");//$NON-NLS-1$
        if (!nsMap.containsValue(ns)) {
            if (ns.equals("http://www.w3.org/XML/1998/namespace")) {//$NON-NLS-1$
                nsMap.put("xml", ns);//$NON-NLS-1$
            } else {
                nsMap.put(ns.substring(last + 1).replaceAll("[\\W]", ""), ns);//$NON-NLS-1$//$NON-NLS-2$
            }
        }

        boolean exist = false;
        for (XSDSchemaContent cnt : xsdSchema.getContents()) {
            if (cnt instanceof XSDImportImpl) {
                XSDImportImpl cntImpl = (XSDImportImpl) cnt;
                if (cntImpl.getNamespace().equals(ns)) {
                    exist = true;
                    break;
                }
            }
        }
        if (!exist) {
            xsdSchema.getContents().add(imp++, xsdImport);
        }
    }
    xsdSchema.updateElement();
}

From source file:it.doqui.index.ecmengine.business.job.move.MoveAggregationJob.java

/**
 * Copies the child associations onto the destiantion node reference.
 * <p>/*from   w ww .  j  a  va2 s . c o  m*/
 * If copyChildren is true then the nodes at the end of a primary assoc will be copied before they
 * are associated.
 *
 * @param sourceNodeRef         the source node reference
 * @param destinationNodeRef   the destination node reference
 * @param copyChildren         indicates whether to copy the primary children
 * @throws AuthenticationRuntimeException
 * @throws PermissionRuntimeException
 * @throws NodeRuntimeException
 */
private void copyChildAssociations(NodeRef sourceNodeRef, NodeRef destinationNodeRef, boolean copyChildren,
        Map<NodeRef, NodeRef> copiedChildren, String sourceRepo, String destRepo)
        throws NodeRuntimeException, PermissionRuntimeException, AuthenticationRuntimeException {

    try {
        logger.debug("[MoveAggregationJob::copyChildAssociations] BEGIN");

        UserTransaction userTxSource = transactionService.getNonPropagatingUserTransaction();

        UserTransaction userTxDest = transactionService.getNonPropagatingUserTransaction();

        userTxSource.begin();

        RepositoryManager.setCurrentRepository(sourceRepo);

        //authenticate as the system user
        authenticationComponent.setSystemUserAsCurrentUser();

        List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(sourceNodeRef);

        userTxSource.commit();

        if (childAssocs != null) {
            logger.debug(
                    "[MoveAggregationJob::copyChildAssociations] Nodi figli da ricreare in Repo Secondary: "
                            + childAssocs.size());
            for (ChildAssociationRef childAssoc : childAssocs) {
                if (copyChildren == true) {
                    if (childAssoc.isPrimary() == true) {
                        logger.debug("[MoveAggregationJob::copyChildAssociations]"
                                + " Nodo figlio primario da ricreare in Repo Secondary.");
                        // Do not recurse further, if we've already copied this node
                        if (copiedChildren.containsKey(childAssoc.getChildRef()) == false
                                && copiedChildren.containsValue(childAssoc.getChildRef()) == false) {
                            // Copy the child
                            recursiveCopy(childAssoc.getChildRef(), childAssoc.getParentRef(),
                                    destinationNodeRef, childAssoc.getTypeQName(), childAssoc.getQName(),
                                    copyChildren, copiedChildren, sourceRepo, destRepo);
                        }
                    } else {
                        logger.debug(
                                "[MoveAggregationJob::copyChildAssociations] Nodo figlio Non Primario da ricreare.");

                        //Add the child (I figli non primari non vengono ricreati nel deposito)Cosa fare??
                        //TODO: NB i figli secondari non vengono ricreati, ma solo viene creata la relazione
                        //tra padre e figlio( e il figlio si trova nel deposito)
                        NodeRef childRef = childAssoc.getChildRef();

                        userTxDest.begin();

                        RepositoryManager.setCurrentRepository(destRepo);

                        // authenticate as the system user
                        authenticationComponent.setSystemUserAsCurrentUser();

                        nodeService.addChild(destinationNodeRef, childRef, childAssoc.getTypeQName(),
                                childAssoc.getQName());

                        userTxDest.commit();
                    }
                }
            }
        }
    } catch (NotSupportedException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (SystemException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (SecurityException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (IllegalStateException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (RollbackException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (HeuristicRollbackException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } finally {
        logger.debug("[MoveAggregationJob::copyChildAssociations] END");
    }
}

From source file:com.flexive.faces.components.content.FxContentList.java

@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
private void process(FacesContext context, PhaseId phase) {
    final Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
    final String resultVar = getVar() + "_result";
    try {//w ww . j  a  v a2  s.  c om
        final FxResultSet result = getResult(context);
        final FxContentView contentView;
        if (phase == PhaseId.RENDER_RESPONSE
                && (getChildCount() == 0 || !(getChildren().get(0) instanceof FxContentView))) {
            // create content view, attach our children
            contentView = new FxContentView();
            contentView.setVar(getVar());
            contentView.setExplode(isExplode());
            // attach our children to the content view
            contentView.getChildren().addAll(getChildren());
            // set content view as our only child
            this.getChildren().clear();
            this.getChildren().add(contentView);
        } else if (getChildCount() > 1 && getChildren().get(0) instanceof FxContentView) {
            // move all other children that got appended by facelets (TODO: investigate why)
            contentView = (FxContentView) getChildren().get(0);
            contentView.getChildren().clear();
            while (getChildren().size() > 1) {
                contentView.getChildren().add(getChildren().remove(1));
            }
        } else {
            // get contentview child
            contentView = (FxContentView) getChildren().get(0);
        }
        if (result.getRowCount() == 0) {
            if (getFacet("empty") != null) {
                applyPhase(context, getFacet("empty"), phase);
            }
            return;
        }
        // process result
        setIndex(context, 0);
        if (result.getRowCount() > 0) {
            // initialize data
            provideContent();
        }
        requestMap.put(resultVar, getResult(context));
        if (getFacet("header") != null) {
            applyPhase(context, getFacet("header"), phase);
        }
        for (int i = 0; i < result.getRowCount(); i++) {
            setIndex(context, i);
            applyPhase(context, contentView, phase);
        }
    } catch (FxApplicationException e) {
        throw e.asRuntimeException();
    } catch (IOException e) {
        throw new FxUpdateException("ex.jsf.contentView.render", e).asRuntimeException();
    } finally {
        if (requestMap.containsKey(resultVar)) {
            requestMap.remove(resultVar);
        }
        if (StringUtils.isNotBlank(getIndexVar()) && requestMap.containsValue(getIndexVar())) {
            requestMap.remove(getIndexVar());
        }
    }
}

From source file:de.mpg.escidoc.pubman.easySubmission.EasySubmission.java

/**
 * localized creation of SelectItems for the source genres available
 * //  w ww  .  j av  a  2 s  .co m
 * @return SelectItem[] with Strings representing source genres
 */
public SelectItem[] getSourceGenreOptions() {
    InternationalizationHelper i18nHelper = (InternationalizationHelper) FacesContext.getCurrentInstance()
            .getApplication().getVariableResolver()
            .resolveVariable(FacesContext.getCurrentInstance(), InternationalizationHelper.BEAN_NAME);
    ResourceBundle bundleLabel = ResourceBundle.getBundle(i18nHelper.getSelectedLabelBundle());

    ApplicationBean appBean = (ApplicationBean) getApplicationBean(ApplicationBean.class);
    Map<String, String> excludedSourceGenres = appBean.getExcludedSourceGenreMap();
    List<SelectItem> sourceGenres = new ArrayList<SelectItem>();
    sourceGenres.add(new SelectItem("", bundleLabel.getString("EditItem_NO_ITEM_SET")));
    for (SourceVO.Genre value : SourceVO.Genre.values()) {
        sourceGenres.add(new SelectItem(value, bundleLabel.getString("ENUM_GENRE_" + value.name())));
    }

    String uri = "";
    int i = 0;
    while (i < sourceGenres.size()) {
        if (sourceGenres.get(i).getValue() != null && !("").equals(sourceGenres.get(i).getValue())) {
            uri = ((SourceVO.Genre) sourceGenres.get(i).getValue()).getUri();
        }

        if (excludedSourceGenres.containsValue(uri)) {
            sourceGenres.remove(i);
        } else {
            i++;
        }
    }
    return sourceGenres.toArray(new SelectItem[sourceGenres.size()]);
}