Example usage for org.dom4j Element addAttribute

List of usage examples for org.dom4j Element addAttribute

Introduction

In this page you can find the example usage for org.dom4j Element addAttribute.

Prototype

Element addAttribute(QName qName, String value);

Source Link

Document

Adds the attribute value of the given fully qualified name.

Usage

From source file:com.devoteam.srit.xmlloader.core.operations.basic.OperationParameter.java

License:Open Source License

/**
 * Creates a new instance of OperationParameter
 *//*from ww w .java 2  s.  com*/
public OperationParameter(Element root) throws Exception {
    super(root, XMLElementTextOnlyParser.instance());

    this.resultantAttribute = root.attributeValue("name").trim();

    this.operatorAttribute = root.attributeValue("operation");
    if (null == this.operatorAttribute) {
        root.addAttribute("operation", "list.set");
        this.operatorAttribute = root.attributeValue("operation");
    }
    this.operatorAttribute = this.operatorAttribute.toLowerCase().trim();
    this._key[1] = this.operatorAttribute;

    this.parameterOperator = ParameterOperatorRegistry.getPluggableComponent(this.operatorAttribute);
    this.parameterOperatorName = ParameterOperatorRegistry.getPluggableName(this.operatorAttribute);

    if (null == this.parameterOperator) {
        throw new ParsingException("Could not find any <parameter> operation named " + this.operatorAttribute);
    }
}

From source file:com.devoteam.srit.xmlloader.diameter.MsgDiameterParser.java

License:Open Source License

public void doDictionnary(Element root, String applicationId, boolean recurse) throws ParsingException {
    Application application = Dictionary.getInstance().getApplication(applicationId);

    if (null == application) {
        throw new ParsingException("Unknown \"applicationId\" attribute in header: " + applicationId);
    }//from  w  w w  . j  ava 2  s.co m

    Element unmodifiedRoot = root.createCopy();

    if (root.getName().equalsIgnoreCase("header")) {
        //
        // ApplicationId
        //
        String attributeValue;

        attributeValue = root.attributeValue("applicationId");
        if (!Utils.isInteger(attributeValue)) {
            root.attribute("applicationId").setValue(Integer.toString(application.get_id()));
        }

        //
        // CommandCode
        //
        attributeValue = root.attributeValue("command");
        if (!Utils.isInteger(attributeValue)) {
            CommandDef commandDef = Dictionary.getInstance().getCommandDefByName(attributeValue, applicationId);
            if (commandDef == null) {
                throw (new ParsingException(
                        "Unknown \"command\" attribute in header: " + attributeValue + "skipp it"));
            }
            root.attribute("command").setValue(Integer.toString(commandDef.get_code()));
        }

    } else if (root.getName().equalsIgnoreCase("avp")) {
        boolean isTypeAppId = false;
        boolean isTypeVendorId = false;
        String attributeValue;

        attributeValue = root.attributeValue("code");
        //
        // Set default values implied by code in XMLTree from dictionnary
        //
        if (null != attributeValue) {
            AvpDef avpDef;
            if (!Utils.isInteger(attributeValue)) {
                avpDef = Dictionary.getInstance().getAvpDefByName(attributeValue, applicationId);
            } else {
                avpDef = Dictionary.getInstance().getAvpDefByCode(Integer.parseInt(attributeValue),
                        applicationId);
            }

            if (null == avpDef) {
                //
                // If the code value is an integer, we don't necessary have to know it in the dictionnary.
                // However, if it isn't, we have to.
                //
            }

            //
            // Handle the code attribute
            //
            if (null != avpDef) {
                root.addAttribute("code", Integer.toString(avpDef.get_code()));
            }

            //
            // Handle the type attribute
            //
            if (null == root.attribute("type") && null != avpDef) {
                TypeDef typeDef = avpDef.get_type();
                if (null != typeDef) {
                    while (null != typeDef.get_type_parent()) {
                        if (typeDef.get_type_name().equalsIgnoreCase("AppId"))
                            isTypeAppId = true;
                        if (typeDef.get_type_name().equalsIgnoreCase("VendorId"))
                            isTypeVendorId = true;
                        typeDef = typeDef.get_type_parent();
                    }
                    root.addAttribute("type", typeDef.get_type_name());
                }
            }

            //
            // Handle the vendorId attribute
            //
            if (null == root.attribute("vendorId") && null != avpDef) {
                VendorDef vendorDef = avpDef.get_vendor_id();
                if (null != vendorDef) {
                    root.addAttribute("vendorId", Integer.toString(vendorDef.get_code()));
                }
            }

            //
            // Handle the mandatory attribute
            //
            if (null == root.attribute("mandatory")) {
                if (null != avpDef && null != avpDef.get_mandatory()
                        && avpDef.get_mandatory().equals("mustnot")) {
                    root.addAttribute("mandatory", "false");
                } else {
                    root.addAttribute("mandatory", "true");
                }
            }

            //
            // Handle the private attribute
            //
            if (null == root.attribute("private") && null != avpDef) {
                if (null != avpDef && null != avpDef.get_protected()
                        && avpDef.get_protected().equals("mustnot")) {
                    root.addAttribute("private", "false");
                } else {
                    root.addAttribute("private", "true");
                }
            }

            //
            // Parse the enumerated value that could be present in "value"
            //
            if (null != root.attribute("value") && null != avpDef) {
                String enumName = root.attributeValue("value");
                long enumValue = avpDef.getEnumCodeByName(enumName);
                if (enumValue != -1) {
                    root.attribute("value").setValue(Long.toString(enumValue));
                }
            }
        } else {
            throw new ParsingException(
                    "in element: " + unmodifiedRoot + "\n" + "code is a mandatory attribute");
        }

        //
        // Set the vendorId code (in case it isn't referenced by the avp Code via dictionnary, or overwritten).
        //
        attributeValue = root.attributeValue("vendorId");
        if (null != attributeValue) {
            if (!Utils.isInteger(attributeValue)) {
                VendorDef vendorDef = Dictionary.getInstance().getVendorDefByName(attributeValue,
                        applicationId);
                if (null != vendorDef) {
                    root.attribute("vendorId").setValue(Integer.toString(vendorDef.get_code()));
                } else {
                    throw new ParsingException("in element: " + unmodifiedRoot + "\n" + attributeValue
                            + " is not a valid vendor id in element");
                }
            }
        }

        //
        // Set the top-parent type (in case it isn't referenced by the avp Code via dictionnary, or overwritten).
        //
        if (root.elements().size() > 0) {
            root.addAttribute("type", "grouped");
        }

        attributeValue = root.attributeValue("type");
        if (null != attributeValue) {
            if (!attributeValue.equalsIgnoreCase("grouped")) {
                if (null != attributeValue) {
                    TypeDef typeDef = Dictionary.getInstance().getTypeDefByName(attributeValue, applicationId);
                    if (null != typeDef) {
                        while (null != typeDef && null != typeDef.get_type_parent()) {
                            if (typeDef.get_type_name().equalsIgnoreCase("AppId"))
                                isTypeAppId = true;
                            if (typeDef.get_type_name().equalsIgnoreCase("VendorId"))
                                isTypeVendorId = true;
                            typeDef = typeDef.get_type_parent();
                        }
                        root.attribute("type").setValue(typeDef.get_type_name());
                    } else {
                        throw new ParsingException("In element: " + unmodifiedRoot + "\n" + attributeValue
                                + " is not a valid type");
                    }
                }

            }
        }

        //
        // Handle the value in case it is an appId or vendorId avp, enum should have already been handled at this point
        //
        attributeValue = root.attributeValue("value");
        if (null != attributeValue) {
            if (isTypeAppId) {
                Application anApplication = Dictionary.getInstance().getApplication(attributeValue);
                if (null != anApplication) {
                    root.attribute("value").setValue(Integer.toString(anApplication.get_id()));
                }
            }
            if (isTypeVendorId) {
                VendorDef vendorDef = Dictionary.getInstance().getVendorDefByName(attributeValue,
                        applicationId);
                if (null != vendorDef) {
                    root.attribute("value").setValue(Integer.toString(vendorDef.get_code()));
                }
            }
        } else {
            if (!root.attributeValue("type").equalsIgnoreCase("grouped")) {
                throw new ParsingException("in element: " + unmodifiedRoot + "\n"
                        + "value is a mandatory attribute for element <avp .../> if it is not a grouped avp");
            }
        }
    }

    if (recurse) {
        List<Element> list = root.elements();
        for (Element element : list) {
            doDictionnary(element, applicationId, recurse);
        }
    }
}

From source file:com.devoteam.srit.xmlloader.genscript.genscriptCmd.java

License:Open Source License

/**
 * @param args the command line arguments
 *//*ww  w .jav  a2 s .  co m*/
public static void main(String[] args) {

    // Initialisation de MTS core
    ExceptionHandlerSingleton.setInstance(new TextExceptionHandler());
    SingletonFSInterface.setInstance(new LocalFSInterface());
    TextListenerProviderRegistry.instance().register(new FileTextListenerProvider());
    // set the storage location to FILE for logging
    PropertiesEnhanced properties = new PropertiesEnhanced();
    properties.addPropertiesEnhancedComplete("logs.STORAGE_LOCATION", "FILE");
    Config.overrideProperties("tester.properties", properties);

    // S'il n'y a pas d'arguments, on affiche la syntaxe  utiliser
    if (args.length < 3) {
        System.out.println("ERROR => At least two arguments are required : filtre and capture file");
        System.out.println("Usage : genscript <protocol>:<host>:<port> <capturefile> <generatedfile>");
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE,
                "ERROR => At least two arguments are required : filtre and capture file");
        System.exit(-1);
    }
    // Si le nombre d'argument est bon, on lance la convertion
    System.out.println("-------- GENSCRIPT -------------------------------------------------------");
    System.out.println("START => capture file: " + args[args.length - 2]);
    GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE,
            "START => capture file: " + args[args.length - 2]);

    List<FiltreGenerator> listeFiltre = new ArrayList<FiltreGenerator>();
    List<Probe> listeProbe = new ArrayList<Probe>();

    String src = "";
    URI srcURI = null;
    String out = "";
    URI outURI = null;
    String nomPcap = "";

    // Pour chaque lment pass en paramtre
    for (int i = 0; i < args.length; i++) {

        // Si l'argument est un filtre
        if (args[i].matches("[a-zA-Z0-9]+:[a-zA-Z0-9.]+:[0-9]+")) {
            String[] filtre = args[i].split(":");
            listeFiltre.add(new FiltreGenerator(filtre[0], filtre[1], Integer.parseInt(filtre[2])));
        }
    }

    // Cration des URI  partir des paramtres
    // URI du fichier pcap source
    src = args[args.length - 2];
    srcURI = new File(src).toURI();

    // URI du fichier de test  gnrer
    out = args[args.length - 1];
    outURI = new File(out).toURI();

    // On rcupre le nom du fichier pcap
    String[] nomPcapPath = args[args.length - 2].split("/");
    nomPcap = nomPcapPath[nomPcapPath.length - 1].replaceAll("[.]([0-9A-Za-z])+", "");

    // Creation du generateur de script
    ScriptGenerator generator = new ScriptGenerator(outURI);
    generator.setTestcaseName(nomPcap);

    try {
        // Chaque filtre est enregistr dans le gnrateur de script de test
        for (FiltreGenerator fg : listeFiltre) {
            generator.addFiltre(fg);
        }

        // Generation des fichiers de test
        //generator.generateTestFile();
        generator.generateTest();

        // Pour chaque filtre on crer l'objet Probe
        for (FiltreGenerator fg : listeFiltre) {
            System.out.println("CAPTURE filter: => " + fg);
            GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE,
                    "CAPTURE filter: => " + fg);
            // Cration de la stack du protocole que l'on souhaite filtrer
            Stack stack = StackFactory.getStack(fg.getProtocole());
            DOMDocument docProbe = new DOMDocument();
            Element root = docProbe.addElement("root");
            root.addAttribute("filename", src);
            // String captureFilter = "host " + fg.getHostName() + " and port " + fg.getHostPort().toString();
            String captureFilter = "host " + fg.getHostName() + " and (port " + fg.getHostPort().toString()
                    + " or not (ip[6:2] & 0x1FFF = 0)) and ip";
            root.addAttribute("captureFilter", captureFilter);

            // Cration de l'objet Probe
            Probe probe = new Probe(stack, root);
            listeProbe.add(probe);

            // On configure le probe pour la gnration de script
            probe.genScript(generator);

            stack.createProbe(probe, fg.getProtocole());
        }

        // Attente de la fin de la capture  partir du fichier
        while (!listeProbe.get(0).getProbeJpcapThread().getStopPossible()) {
        }

        generator.closeTest();

        System.out.println("END => test file: " + args[args.length - 1] + "(See application.log)");
        GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE,
                "END => test file: " + args[args.length - 1] + "(See application.log)");

        // On ferme proprement le programme                                      
        System.exit(0);
    } catch (Exception e) {
        System.out.println("EXCEPTION => " + e);
        e.printStackTrace();
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, e, "EXCEPTION => ");
        System.exit(-10);
    }
}

From source file:com.dockingsoftware.dockingpreference.PreferenceProcessor.java

License:Apache License

/**
 * Store user preference information to a specified file.
 * /*  www. j a  va  2  s  .  c  om*/
 * @param obj 
 * @param fullPath Specified the full path of the configuration file.
 */
public void store(Object obj, String fullPath) {
    try {
        FileWriter out;
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement(getName(obj.getClass()));
        root.addAttribute(GlobalConstant.CLASS, obj.getClass().getName());

        List<Field> pFields = getPreferenceFieldList(obj.getClass());
        for (int i = 0; i < pFields.size(); i++) {
            store(obj, pFields.get(i), root);
        }

        OutputFormat format = new OutputFormat("  ", true);
        out = new FileWriter(new File(fullPath));
        XMLWriter w = new XMLWriter(out, format);
        w.write(document);
        w.close();
        out.close();

    } catch (IOException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.dockingsoftware.dockingpreference.PreferenceProcessor.java

License:Apache License

/**
 * Store object tree into XML file.//w ww  . j a  v  a  2  s .  co m
 * 
 * @param fieldClass
 * @param fieldName
 * @param fieldValue
 * @param parent
 * @param adapterClass
 * @throws IllegalArgumentException
 * @throws IllegalAccessException 
 */
private void store(Class fieldClass, String fieldName, Object fieldValue, Element parent,
        Class<? extends PersistentAdapterIF> adapterClass)
        throws IllegalArgumentException, IllegalAccessException {

    if (fieldClass.isArray()) {

        if (fieldName.endsWith("[]")) {
            fieldName = fieldName.substring(0, fieldName.length() - 2);
        }
        Object[] array = (Object[]) fieldValue;
        Element arrayEle = parent.addElement(fieldName);
        String arryType = fieldClass.getName();
        arryType = arryType.substring(arryType.lastIndexOf("[") + 2, arryType.length() - 1);
        arrayEle.addAttribute(GlobalConstant.CLASS, GlobalConstant.ARRAY);
        arrayEle.addAttribute(GlobalConstant.ARRAY_TYPE, arryType);
        arrayEle.addAttribute(GlobalConstant.ARRAY_LENGTH, array.length + "");

        for (int i = 0; i < array.length; i++) {

            List<Field> arrFields = getPreferenceFieldList(array[i].getClass());
            if (arrFields.size() > 0) {

                Element child = arrayEle.addElement(getName(array[i].getClass()));
                child.addAttribute(GlobalConstant.CLASS, array[i].getClass().getName());
                for (int j = 0; j < arrFields.size(); j++) {
                    store(array[i], arrFields.get(j), child);
                }
            } else {
                store(array[i].getClass(), array[i].getClass().getSimpleName(), array[i], arrayEle,
                        adapterClass);
            }
        }

    } else if (fieldValue instanceof Collection) {
        Element lstEle = parent.addElement(fieldName);
        lstEle.addAttribute(GlobalConstant.CLASS, fieldValue.getClass().getName());

        Collection coll = (Collection) fieldValue;
        Iterator iter = coll.iterator();
        while (iter.hasNext()) {
            Object item = iter.next();
            List<Field> lstFields = getPreferenceFieldList(item.getClass());
            if (lstFields.size() > 0) {

                Element child = lstEle.addElement(getName(item.getClass()));
                child.addAttribute(GlobalConstant.CLASS, item.getClass().getName());
                for (int j = 0; j < lstFields.size(); j++) {
                    store(item, lstFields.get(j), child);
                }
            } else {
                store(item.getClass(), item.getClass().getSimpleName(), item, lstEle, adapterClass);
            }
        }

    } else if (fieldValue instanceof Map) {

        Element mapEle = parent.addElement(fieldName);
        mapEle.addAttribute(GlobalConstant.CLASS, fieldValue.getClass().getName());

        Map map = (Map) fieldValue;
        Iterator iter = map.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            Object value = map.get(key);
            Element keyEle = mapEle.addElement(GlobalConstant.KEY);
            keyEle.setText(key.toString());// Not suppert any adapter!
            keyEle.addAttribute(GlobalConstant.CLASS, key.getClass().getName());

            List<Field> vFields = getPreferenceFieldList(value.getClass());
            if (vFields.size() > 0) {

                Element valueEle = keyEle.addElement(getName(value.getClass()));
                valueEle.addAttribute(GlobalConstant.CLASS, value.getClass().getName());
                for (int j = 0; j < vFields.size(); j++) {
                    store(value, vFields.get(j), valueEle);
                }
            } else {
                store(value.getClass(), value.getClass().getSimpleName(), value, keyEle, adapterClass);
            }
        }

    } else {

        List<Field> pFields = getPreferenceFieldList(fieldValue.getClass());
        if (pFields.size() > 0) {
            Element child = parent.addElement(fieldName);
            child.addAttribute(GlobalConstant.CLASS, fieldValue.getClass().getName());

            for (int i = 0; i < pFields.size(); i++) {
                store(fieldValue, pFields.get(i), child);
            }
        } else {
            Element attrEle = parent.addElement(fieldName);
            attrEle.setText(getValue(fieldValue, adapterClass));
            attrEle.addAttribute(GlobalConstant.CLASS, fieldValue.getClass().getName());
            if (adapterClass != DefaultPersistentAdapter.class) {
                attrEle.addAttribute(GlobalConstant.ADAPTER, adapterClass.getName());
            }
        }
    }
}

From source file:com.doculibre.constellio.izpack.UsersToXmlFile.java

License:Open Source License

public static void run(AbstractUIProcessHandler handler, String[] args) {
    if (args.length != 3) {
        System.out.println("file login password");
        return;/*from w  ww  . java  2s .  c  o  m*/
    }

    String target = args[0];

    File xmlFile = new File(target);

    BufferedWriter writer;
    try {
        writer = new BufferedWriter(new FileWriter(xmlFile));
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    try {
        for (String line : Arrays.asList(emptyFileLines)) {
            writer.write(line + System.getProperty("line.separator"));
        }

        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    String login = args[1];

    String passwd = args[2];

    UsersToXmlFile elem = new UsersToXmlFile();

    ConstellioUser dataUser = elem.new ConstellioUser(login, passwd, null);
    dataUser.setFirstName("System");
    dataUser.setLastName("Administrator");
    dataUser.getRoles().add(Roles.ADMIN);

    Document xmlDocument;
    try {
        xmlDocument = new SAXReader().read(target);
        Element root = xmlDocument.getRootElement();

        BaseElement user = new BaseElement(USER);
        user.addAttribute(FIRST_NAME, dataUser.getFirstName());
        user.addAttribute(LAST_NAME, dataUser.getLastName());
        user.addAttribute(LOGIN, dataUser.getUsername());
        user.addAttribute(PASSWORD_HASH, dataUser.getPasswordHash());

        if (dataUser.getLocale() != null) {
            user.addAttribute(LOCALE, dataUser.getLocaleCode());
        }

        Set<String> constellioRoles = dataUser.getRoles();
        if (!constellioRoles.isEmpty()) {
            Element roles = user.addElement(ROLES);
            for (String constellioRole : constellioRoles) {
                Element role = roles.addElement(ROLE);
                role.addAttribute(VALUE, constellioRole);
            }
        }

        root.add(user);

        OutputFormat format = OutputFormat.createPrettyPrint();

        xmlFile = new File(target);
        // FIXME recrire la DTD
        // xmlDocument.addDocType(arg0, arg1, arg2)
        XMLWriter writer2 = new XMLWriter(new FileOutputStream(xmlFile), format);

        writer2.write(xmlDocument);
        writer2.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.doculibre.constellio.services.ConnectorManagerServicesImpl.java

License:Open Source License

private Element setConnectorConfig(ConnectorManager connectorManager, String connectorName,
        String connectorType, Map<String, String[]> requestParams, boolean update, Locale locale) {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement(ServletUtil.XMLTAG_CONNECTOR_CONFIG);

    root.addElement(ServletUtil.QUERY_PARAM_LANG).addText(locale.getLanguage());
    root.addElement(ServletUtil.XMLTAG_CONNECTOR_NAME).addText(connectorName);
    root.addElement(ServletUtil.XMLTAG_CONNECTOR_TYPE).addText(connectorType);
    root.addElement(ServletUtil.XMLTAG_UPDATE_CONNECTOR).addText(Boolean.toString(update));

    for (String paramName : requestParams.keySet()) {
        if (!paramName.startsWith("wicket:")) {
            String[] paramValues = requestParams.get(paramName);
            for (String paramValue : paramValues) {
                Element paramElement = root.addElement(ServletUtil.XMLTAG_PARAMETERS);
                paramElement.addAttribute("name", paramName);
                paramElement.addAttribute("value", paramValue);
            }/*from ww w. j  av  a2 s  .c om*/
        }
    }

    Element response = ConnectorManagerRequestUtils.sendPost(connectorManager, "/setConnectorConfig", document);
    Element statusIdElement = response.element(ServletUtil.XMLTAG_STATUSID);
    if (statusIdElement != null) {
        String statusId = statusIdElement.getTextTrim();
        if (!statusId.equals("" + ConnectorMessageCode.SUCCESS)) {
            return response;
        } else {
            BackupServices backupServices = ConstellioSpringUtils.getBackupServices();
            backupServices.backupConfig(connectorName, connectorType);
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.doculibre.constellio.services.ConnectorManagerServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from w w  w.  ja  va 2s . co  m
public List<Record> authorizeByConnector(List<Record> records, Collection<UserCredentials> userCredentialsList,
        ConnectorManager connectorManager) {
    List<Record> authorizedRecords = new ArrayList<Record>();

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement(ServletUtil.XMLTAG_AUTHZ_QUERY);
    Element connectorQueryElement = root.addElement(ServletUtil.XMLTAG_CONNECTOR_QUERY);

    Map<ConnectorInstance, UserCredentials> credentialsMap = new HashMap<ConnectorInstance, UserCredentials>();
    Set<ConnectorInstance> connectorsWithoutCredentials = new HashSet<ConnectorInstance>();
    Map<String, Record> recordsByURLMap = new HashMap<String, Record>();
    boolean recordToValidate = false;
    for (Record record : records) {
        // Use to accelerate the matching between response urls and actual entities
        recordsByURLMap.put(record.getUrl(), record);
        ConnectorInstance connectorInstance = record.getConnectorInstance();
        UserCredentials connectorCredentials = credentialsMap.get(connectorInstance);
        if (connectorCredentials == null && !connectorsWithoutCredentials.contains(connectorInstance)) {
            RecordCollection collection = connectorInstance.getRecordCollection();
            for (CredentialGroup credentialGroup : collection.getCredentialGroups()) {
                if (credentialGroup.getConnectorInstances().contains(connectorInstance)) {
                    for (UserCredentials userCredentials : userCredentialsList) {
                        if (userCredentials.getCredentialGroup().equals(credentialGroup)) {
                            connectorCredentials = userCredentials;
                            credentialsMap.put(connectorInstance, userCredentials);
                            break;
                        }
                    }
                    break;
                }
            }
        }
        if (connectorCredentials == null) {
            connectorsWithoutCredentials.add(connectorInstance);
            LOGGER.warning("Missing credentials for connector " + connectorInstance.getName());
        } else {
            String username = connectorCredentials.getUsername();
            if (StringUtils.isNotBlank(username)) {
                String password = EncryptionUtils.decrypt(connectorCredentials.getEncryptedPassword());
                String domain = connectorCredentials.getDomain();
                Element identityElement = connectorQueryElement.addElement(ServletUtil.XMLTAG_IDENTITY);
                identityElement.setText(username);
                if (StringUtils.isNotBlank(domain)) {
                    identityElement.addAttribute(ServletUtil.XMLTAG_DOMAIN_ATTRIBUTE, domain);
                }
                identityElement.addAttribute(ServletUtil.XMLTAG_PASSWORD_ATTRIBUTE, password);

                Element resourceElement = identityElement.addElement(ServletUtil.XMLTAG_RESOURCE);
                resourceElement.setText(record.getUrl());
                resourceElement.addAttribute(ServletUtil.XMLTAG_CONNECTOR_NAME_ATTRIBUTE,
                        connectorInstance.getName());
                recordToValidate = true;
            }
        }
    }

    if (recordToValidate) {
        Element response = ConnectorManagerRequestUtils.sendPost(connectorManager, "/authorization", document);
        Element authzResponseElement = response.element(ServletUtil.XMLTAG_AUTHZ_RESPONSE);
        List<Element> answerElements = authzResponseElement.elements(ServletUtil.XMLTAG_ANSWER);
        for (Element answerElement : answerElements) {
            Element decisionElement = answerElement.element(ServletUtil.XMLTAG_DECISION);
            boolean permit = decisionElement.getTextTrim().equals("Permit");
            if (permit) {
                Element resourceElement = answerElement.element(ServletUtil.XMLTAG_RESOURCE);
                String recordUrl = resourceElement.getTextTrim();
                Record record = recordsByURLMap.get(recordUrl);
                authorizedRecords.add(record);
            }
        }
    }
    return authorizedRecords;
}

From source file:com.doculibre.constellio.services.ElevateServicesImpl.java

License:Open Source License

private Element buildQueryElementFromCache(String queryText, String queryDisplayText, String collectionName) {
    Element queryElement;

    Map<String, List<String>> solrCoreElevationCache = elevationCache.get(collectionName);
    List<String> queryElevationCache = solrCoreElevationCache.get(queryText);

    Map<String, List<String>> solrCoreExclusionCache = exclusionCache.get(collectionName);
    List<String> queryExclusionCache = solrCoreExclusionCache.get(queryText);

    if ((queryElevationCache != null && !queryElevationCache.isEmpty())
            || (queryExclusionCache != null && !queryExclusionCache.isEmpty())) {
        queryElement = DocumentHelper.createElement("query");
        queryElement.addAttribute("text", queryText);
        queryElement.addAttribute("displayText", queryDisplayText);
        if (queryElevationCache != null) {
            for (String elevatedDocId : queryElevationCache) {
                Element docElement = DocumentHelper.createElement("doc");
                docElement.addAttribute("id", elevatedDocId);
                queryElement.add(docElement);
            }//from   www.  java 2s.  co m
        }

        if (queryExclusionCache != null) {
            for (String excludedDocId : queryExclusionCache) {
                Element docElement = DocumentHelper.createElement("doc");
                docElement.addAttribute("id", excludedDocId);
                docElement.addAttribute("exclude", "true");
                queryElement.add(docElement);
            }
        }
    } else {
        queryElement = null;
    }
    return queryElement;
}

From source file:com.doculibre.constellio.services.SolrServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
private void updateSchemaFields(RecordCollection collection, Document schemaDocument) {
    Element fieldsElement = schemaDocument.getRootElement().element("fields");
    List<Element> fieldElements = fieldsElement.elements("field");
    for (Iterator<Element> it = fieldElements.iterator(); it.hasNext();) {
        it.next();//  w w w  . j a  v  a2  s .  c  o m
        it.remove();
    }

    List<Element> copyFields = schemaDocument.getRootElement().elements("copyField");
    for (Iterator<Element> it = copyFields.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }

    List<Element> dynamicFieldElements = fieldsElement.elements("dynamicField");
    for (Iterator<Element> it = dynamicFieldElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }

    List<String> addedFieldNames = new ArrayList<String>();
    Collection<IndexField> indexFields = collection.getIndexFields();
    for (IndexField indexField : indexFields) {
        if (!addedFieldNames.contains(indexField.getName())) {
            addedFieldNames.add(indexField.getName());

            FieldType fieldType = indexField.getFieldType();
            Analyzer analyzer = indexField.getAnalyzer();
            if (fieldType == null) {
                throw new RuntimeException(indexField.getName() + " has no type");
            }
            Element fieldElement;
            if (indexField.isDynamicField()) {
                fieldElement = DocumentHelper.createElement("dynamicField");
            } else {
                fieldElement = DocumentHelper.createElement("field");
            }
            fieldsElement.add(fieldElement);
            addNotNullAttribute(fieldElement, "name", indexField.getName());
            addNotNullAttribute(fieldElement, "type", fieldType.getName());
            addNotNullAttribute(fieldElement, "indexed", indexField.isIndexed());
            addNotNullAttribute(fieldElement, "stored", true);
            addNotNullAttribute(fieldElement, "multiValued", indexField.isMultiValued());
            if (analyzer != null) {
                fieldElement.addAttribute("analyzer", analyzer.getAnalyzerClass().getClassName());
            }
        }
    }

    // used by solrcloud
    Element fieldElement = DocumentHelper.createElement("field");
    addNotNullAttribute(fieldElement, "name", "_version_");
    addNotNullAttribute(fieldElement, "type", "long");
    addNotNullAttribute(fieldElement, "indexed", true);
    addNotNullAttribute(fieldElement, "stored", true);
    fieldsElement.add(fieldElement);

    List<Element> uniqueKeyElements = schemaDocument.getRootElement().elements("uniqueKey");
    for (Iterator<Element> it = uniqueKeyElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    IndexField uniqueKeyField = collection.getUniqueKeyIndexField();
    if (uniqueKeyField != null) {
        Element uniqueKeyElement = DocumentHelper.createElement("uniqueKey");
        uniqueKeyElement.setText(uniqueKeyField.getName());
        schemaDocument.getRootElement().add(uniqueKeyElement);
    }

    List<Element> defaultSearchFieldElements = schemaDocument.getRootElement().elements("defaultSearchField");
    for (Iterator<Element> it = defaultSearchFieldElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    IndexField defaultSearchField = collection.getDefaultSearchIndexField();
    if (defaultSearchField != null) {
        Element defaultSearchFieldElement = DocumentHelper.createElement("defaultSearchField");
        defaultSearchFieldElement.setText(defaultSearchField.getName());
        schemaDocument.getRootElement().add(defaultSearchFieldElement);
    }

    List<Element> solrQueryParserElements = schemaDocument.getRootElement().elements("solrQueryParser");
    for (Iterator<Element> it = solrQueryParserElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    String queryParserOperator = collection.getQueryParserOperator();
    if (queryParserOperator != null) {
        Element solrQueryParserElement = DocumentHelper.createElement("solrQueryParser");
        solrQueryParserElement.addAttribute("defaultOperator", queryParserOperator);
        schemaDocument.getRootElement().add(solrQueryParserElement);
    }

    for (IndexField indexField : indexFields) {
        if (!indexField.isDynamicField()) {
            for (CopyField copyFieldDest : indexField.getCopyFieldsDest()) {
                Element copyFieldElement = DocumentHelper.createElement("copyField");
                String source;
                if (copyFieldDest.isSourceAllFields()) {
                    source = "*";
                } else {
                    IndexField indexFieldSource = copyFieldDest.getIndexFieldSource();
                    source = indexFieldSource.getName();
                }
                copyFieldElement.addAttribute("source", source);
                copyFieldElement.addAttribute("dest", copyFieldDest.getIndexFieldDest().getName());
                addNotNullAttribute(copyFieldElement, "maxChars", copyFieldDest);
                // Ajout Rida
                schemaDocument.getRootElement().add(copyFieldElement);
            }
        }
    }

    writeSchema(collection.getName(), schemaDocument);
}