Example usage for org.dom4j Element getTextTrim

List of usage examples for org.dom4j Element getTextTrim

Introduction

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

Prototype

String getTextTrim();

Source Link

Document

DOCUMENT ME!

Usage

From source file:com.devoteam.srit.xmlloader.tls.StackTls.java

License:Open Source License

/** Creates a specific Msg */
@Override/*from  w  ww . j  av a  2 s  .c om*/
public Msg parseMsgFromXml(Boolean request, Element root, Runner runner) throws Exception {
    //
    // Parse all <data ... /> tags
    //
    List<Element> elements = root.elements("data");
    List<byte[]> datas = new LinkedList<byte[]>();
    ;
    try {
        for (Element element : elements) {
            if (element.attributeValue("format").equalsIgnoreCase("text")) {
                String text = element.getText();
                // change the \n caractre to \r\n caracteres because the dom librairy return only \n.
                // this could make some trouble when the length is calculated in the scenario
                text = Utils.replaceNoRegex(text, "\r\n", "\n");
                text = Utils.replaceNoRegex(text, "\n", "\r\n");
                datas.add(text.getBytes("UTF8"));
            } else if (element.attributeValue("format").equalsIgnoreCase("binary")) {
                String text = element.getTextTrim();
                datas.add(Utils.parseBinaryString(text));
            }
        }
    } catch (Exception e) {
        throw new ExecutionException(e);
    }

    //
    // Compute total length
    //
    int length = 0;
    for (byte[] data : datas) {
        length += data.length;
    }

    byte[] data = new byte[length];

    int i = 0;
    for (byte[] aData : datas) {
        for (int j = 0; j < aData.length; j++) {
            data[i] = aData[j];
            i++;
        }
    }

    MsgTls msgtls = new MsgTls(data);

    // instanciates the conn
    String channelName = root.attributeValue("channel");
    // deprecated part //
    if (channelName == null)
        channelName = root.attributeValue("connectionName");
    // deprecated part //
    Channel channel = getChannel(channelName);
    if (channel == null) {
        throw new ExecutionException("The channel <name=" + channelName + "> does not exist");
    }
    msgtls.setChannel(getChannel(channelName));

    return msgtls;
}

From source file:com.devoteam.srit.xmlloader.udp.MsgUdp.java

License:Open Source License

/** 
 * Parse the message from XML element /*ww  w.  ja v  a2  s  . c  om*/
 */
@Override
public void parseFromXml(Boolean request, Element root, Runner runner) throws Exception {
    List<Element> elements = root.elements("data");
    List<byte[]> datas = new LinkedList<byte[]>();

    try {
        for (Element element : elements) {
            if (element.attributeValue("format").equalsIgnoreCase("text")) {
                String text = element.getText();
                // change the \n caractre to \r\n caracteres because the dom librairy return only \n.
                // this could make some trouble when the length is calculated in the scenario
                text = Utils.replaceNoRegex(text, "\r\n", "\n");
                text = Utils.replaceNoRegex(text, "\n", "\r\n");
                datas.add(text.getBytes("UTF8"));
            } else if (element.attributeValue("format").equalsIgnoreCase("binary")) {
                String text = element.getTextTrim();
                datas.add(Utils.parseBinaryString(text));
            }
        }
    } catch (Exception e) {
        throw new ExecutionException("StackUDP: Error while parsing data", e);
    }

    //
    // Compute total length
    //
    int dataLength = 0;
    for (byte[] data : datas) {
        dataLength += data.length;
    }

    this.data = new byte[dataLength];
    int i = 0;
    for (byte[] aData : datas) {
        for (int j = 0; j < aData.length; j++) {
            this.data[i] = aData[j];
            i++;
        }
    }

    String length = root.attributeValue("length");
    if (length != null) {
        dataLength = Integer.parseInt(length);
        GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL,
                "fixed length of the datagramPacket to be sent:  ", dataLength);
        if (this.data.length != dataLength) {
            GlobalLogger.instance().getApplicationLogger().warn(TextEvent.Topic.PROTOCOL,
                    "data.length different from chosen fixed length");
        }
    }
}

From source file:com.devoteam.srit.xmlloader.udp.StackUdp.java

License:Open Source License

/** Creates a specific Msg */
@Override/*from  w ww. j  ava  2  s .com*/
public Msg parseMsgFromXml(Boolean request, Element root, Runner runner) throws Exception {
    //
    // Parse all <data ... /> tags
    //
    List<Element> elements = root.elements("data");
    List<byte[]> datas = new LinkedList<byte[]>();

    try {
        for (Element element : elements) {
            if (element.attributeValue("format").equalsIgnoreCase("text")) {
                String text = element.getText();
                // change the \n caractre to \r\n caracteres because the dom librairy return only \n.
                // this could make some trouble when the length is calculated in the scenario
                text = Utils.replaceNoRegex(text, "\r\n", "\n");
                text = Utils.replaceNoRegex(text, "\n", "\r\n");
                datas.add(text.getBytes("UTF8"));
            } else if (element.attributeValue("format").equalsIgnoreCase("binary")) {
                String text = element.getTextTrim();
                datas.add(Utils.parseBinaryString(text));
            }
        }
    } catch (Exception e) {
        throw new ExecutionException("StackUDP: Error while parsing data", e);
    }

    //
    // Compute total length
    //
    int dataLength = 0;
    for (byte[] data : datas) {
        dataLength += data.length;
    }

    byte[] data = new byte[dataLength];
    int i = 0;
    for (byte[] aData : datas) {
        for (int j = 0; j < aData.length; j++) {
            data[i] = aData[j];
            i++;
        }
    }

    String length = root.attributeValue("length");
    if (length != null) {
        dataLength = Integer.parseInt(length);
        GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL,
                "fixed length of the datagramPacket to be sent:  ", dataLength);
        if (data.length != dataLength) {
            GlobalLogger.instance().getApplicationLogger().warn(TextEvent.Topic.PROTOCOL,
                    "data.length different from chosen fixed length");
        }
    }

    MsgUdp msgUdp = new MsgUdp(data, dataLength);

    String remoteHost = root.attributeValue("remoteHost");
    String remotePort = root.attributeValue("remotePort");

    // deprecated part //
    String name = root.attributeValue("socketName");
    if (name != null) {
        Channel channel = getChannel(name);
        if (channel == null) {
            throw new ExecutionException("StackUDP: The connection <name=" + name + "> does not exist");
        }

        if (remoteHost != null) {
            channel.setRemoteHost(remoteHost);
        }
        if (remotePort != null) {
            channel.setRemotePort(new Integer(remotePort).intValue());
        }
        msgUdp.setChannel(channel);
    } // deprecated part //
    else {
        name = root.attributeValue("listenpoint");
        Listenpoint listenpoint = getListenpoint(name);
        if (listenpoint == null) {
            throw new ExecutionException("StackUDP: The listenpoint <name=" + name + "> does not exist");
        }

        if (remoteHost != null) {
            msgUdp.setRemoteHost(remoteHost);
        }
        if (remotePort != null) {
            msgUdp.setRemotePort(new Integer(remotePort).intValue());
        }
        msgUdp.setListenpoint(listenpoint);
    }

    return msgUdp;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  ww  w  . ja v  a2  s . c om*/
public List<String> getConnectorTypes(ConnectorManager connectorManager) {
    // On utilise le connectorManager par dfaut.
    Element xml = ConnectorManagerRequestUtils.sendGet(connectorManager, "/getConnectorList", null);
    List<Element> connectorTypeElements = xml.element(ServletUtil.XMLTAG_CONNECTOR_TYPES)
            .elements(ServletUtil.XMLTAG_CONNECTOR_TYPE);
    List<String> connectorTypes = new ArrayList<String>();
    for (Iterator<Element> it = connectorTypeElements.iterator(); it.hasNext();) {
        Element connectorTypeElement = (Element) it.next();
        connectorTypes.add(connectorTypeElement.getTextTrim());
    }
    return connectorTypes;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/* www. j  a  v  a2  s  .c  om*/
public List<String> getConnectorInstanceNames(ConnectorManager connectorManager, String collectionName) {
    List<String> connectorInstanceNames = new ArrayList<String>();
    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection collection = collectionServices.get(collectionName);
    if (collection != null) {
        Element xml = ConnectorManagerRequestUtils.sendGet(connectorManager, "/getConnectorInstanceList", null);
        // ConnectorInstances / ConnectorInstance / ConnectorName
        if (xml.element(ServletUtil.XMLTAG_CONNECTOR_INSTANCES) != null) {
            List<Element> connectorIntanceElements = xml.element(ServletUtil.XMLTAG_CONNECTOR_INSTANCES)
                    .elements(ServletUtil.XMLTAG_CONNECTOR_INSTANCE);
            for (Iterator<Element> it = connectorIntanceElements.iterator(); it.hasNext();) {
                Element connectorInstanceElement = (Element) it.next();
                Element connectorInstanceNameElement = connectorInstanceElement
                        .element(ServletUtil.XMLTAG_CONNECTOR_NAME);
                String connectorInstanceName = connectorInstanceNameElement.getTextTrim();
                if (collection.getConnectorInstance(connectorInstanceName) != null) {
                    connectorInstanceNames.add(connectorInstanceName);
                }
            }
        }
    }
    return connectorInstanceNames;
}

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

License:Open Source License

@Override
public String getConnectorType(ConnectorManager connectorManager, String connectorName) {
    Map<String, String> paramsMap = new HashMap<String, String>();
    paramsMap.put(ServletUtil.XMLTAG_CONNECTOR_NAME, connectorName.toLowerCase());
    Element xml = ConnectorManagerRequestUtils.sendGet(connectorManager, "/getConnectorStatus", paramsMap);
    Element connectorTypeElement = xml.element(ServletUtil.XMLTAG_CONNECTOR_STATUS)
            .element(ServletUtil.XMLTAG_CONNECTOR_TYPE);
    String connectoryType = connectorTypeElement.getTextTrim();
    return connectoryType;
}

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);
            }//w w w. ja  v a  2 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

@Override
public Schedule getSchedule(ConnectorManager connectorManager, String connectorName) {
    Schedule schedule;//from w  ww . j a va  2 s.c o  m

    Map<String, String> paramsMap = new HashMap<String, String>();
    paramsMap.put(ServletUtil.XMLTAG_CONNECTOR_NAME, connectorName);
    try {
        Element xml = ConnectorManagerRequestUtils.sendGet(connectorManager, "/getSchedule", paramsMap);
        Element connectorStatusElement = xml.element(ServletUtil.XMLTAG_CONNECTOR_STATUS);
        Element connectorScheduleElement = connectorStatusElement
                .element(ServletUtil.XMLTAG_CONNECTOR_SCHEDULES);

        String scheduleTxt = connectorScheduleElement.getTextTrim();
        if (!StringUtils.isEmpty(scheduleTxt)) {
            schedule = new Schedule(scheduleTxt);
        } else {
            schedule = null;
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Error while trying to get schedule", e);
        schedule = null;
    }
    return schedule;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/* w  w  w .  j av  a2 s  .c om*/
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.example.sample.pMainActivity.java

License:Apache License

public void listNodes(Element node) {
    System.out.println("" + node.getName());
    List<Attribute> list = node.attributes();
    for (Attribute attr : list) {
        Log.d(TAG, "listNodes: " + attr.getText() + "-----" + attr.getName() + "---" + attr.getValue());
    }//from   w  w  w. java 2 s.c  o m

    if (!(node.getTextTrim().equals(""))) {
        Log.d(TAG, "getText: " + node.getText());
        node.setText("getText: ");
        saveDocument(document);
        Log.d(TAG, "saveDocument: " + node.getText());
    }
    Iterator<Element> it = node.elementIterator();
    while (it.hasNext()) {
        Element e = it.next();
        listNodes(e);
    }
}