Example usage for org.dom4j Element elementTextTrim

List of usage examples for org.dom4j Element elementTextTrim

Introduction

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

Prototype

String elementTextTrim(QName qname);

Source Link

Usage

From source file:Tools.java

private static byte[] loadCert(Document cert) {
    if (null == cert)
        throw new RuntimeException("??");
    Element root = cert.getRootElement();
    if (null == root)
        throw new RuntimeException("???");
    String content = root.elementTextTrim("content");
    if (null == content)
        throw new RuntimeException("???");
    return content.getBytes();
}

From source file:Tools.java

public static Map<String, String> regAppLicense(String appLicense) {
    if (null == appLicense || "".equals(appLicense))
        throw new RuntimeException("License");
    BASE64Decoder decoder = new BASE64Decoder();
    try {/*from w w  w .ja v a 2s  .com*/
        Map<String, String> ret = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        reader.setEncoding("UTF-8");
        Document doc = reader.read(new ByteArrayInputStream(decoder.decodeBuffer(appLicense)));
        Element root = doc.getRootElement();
        String app = root.elementTextTrim("models");
        ret.put("app", app);
        String content = root.elementTextTrim("content");
        String appPath = FileSystemWrapper.instance().getRealPath(app);
        File fApp = new File(appPath);
        if (!fApp.exists())
            throw new RuntimeException("?\"" + app + "\"?");
        File fAppLicenseDir = new File(appPath + "/license");
        fAppLicenseDir.mkdirs();
        FileOutputStream fo = null;
        try {
            fo = new FileOutputStream(appPath + "/license/license");
            fo.write(content.getBytes());
            fo.flush();
        } finally {
            if (null != fo)
                fo.close();
        }
        String developer = root.elementTextTrim("developer");
        ret.put("developer", developer);
        String validDate = root.elementTextTrim("valid-date");
        ret.put("valid-date", !"0".equals(validDate) ? validDate : "??");
        String userCount = root.elementTextTrim("user-count");
        ret.put("user-count", !"0".equals(userCount) ? userCount : "??");

        return ret;
    } catch (IOException e) {
        throw new RuntimeException("License", e);
    } catch (DocumentException e) {
        throw new RuntimeException("License", e);
    }
}

From source file:au.com.centrumsystems.hudson.plugin.buildpipeline.BuildPipelineView.java

License:Open Source License

@JavaScriptMethod
public Set<String> getAllFirstJobsName(String url) {
    Jenkins jk = Jenkins.getInstance();/*  ww w.ja  va2  s .  c o m*/
    Collection<View> views = jk.getViews();
    Set<String> firstJobNameSet = new HashSet<String>();
    String shortUrl = getViewShortUrlFromURL(url);
    StringBuilder sb = null;
    Document configXmlDoc = null;
    String viewName = null;
    for (View view : views) {
        sb = new StringBuilder(shortUrl);
        viewName = view.getViewName();
        if ("ALL".equals(viewName)) {
            continue;
        }
        sb.append(viewName).append("/");
        String viewConfigXml = fetchViewConfig(sb.toString());
        try {
            configXmlDoc = DocumentHelper.parseText(viewConfigXml);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        Iterator iter = configXmlDoc.getRootElement().elementIterator("gridBuilder");
        while (iter.hasNext()) {
            Element elt = (Element) iter.next();
            firstJobNameSet.add(elt.elementTextTrim("firstJob"));
        }
    }

    return firstJobNameSet;
}

From source file:com.ah.be.performance.db.TablePartitionProcessor.java

private void init() {
    try {//ww w.  j av a 2 s  .c o  m
        File f = new File(TABLE_PARTITION_CONF_FILE);
        SAXReader reader = new SAXReader();
        Document doc = reader.read(f);
        Element root = doc.getRootElement();
        Element cata = null;

        int catalog = 1;
        for (Iterator<?> i = root.elementIterator(); i.hasNext();) {
            //for catalog
            cata = (Element) i.next();
            String enable = cata.elementText("enable");
            if (enable != null && enable.equalsIgnoreCase("false"))
                continue;
            int default_maxtime = Integer.parseInt(cata.elementTextTrim("default_maxtime"));
            int default_interval = Integer.parseInt(cata.elementTextTrim("default_interval"));
            int table_partition_number = Integer.parseInt(cata.elementTextTrim("table_partition_number"));
            int default_max_record = Integer.parseInt(cata.elementTextTrim("default_max_record"));
            int default_max_record_per_partition = Integer
                    .parseInt(cata.elementTextTrim("default_max_record_per_partition"));
            int maxtime_policy = Integer.parseInt(cata.elementTextTrim("maxtime_policy"));
            int interval_policy = Integer.parseInt(cata.elementTextTrim("interval_policy"));
            int max_record_policy = Integer.parseInt(cata.elementTextTrim("max_record_policy"));

            addTableCatalogInfo(catalog, default_maxtime, default_interval, table_partition_number,
                    default_max_record, default_max_record_per_partition, maxtime_policy, interval_policy,
                    max_record_policy);

            List<?> tableElements = cata.elements("table");
            //for table in catalog
            for (int j = 0; j < tableElements.size(); j++) {
                Element table = (Element) tableElements.get(j);
                String tableName = table.attributeValue("name");
                String schemaName = table.elementTextTrim("schemaname");
                String timeField = table.elementTextTrim("timefield");
                addTableInfo(schemaName, tableName, timeField, catalog);
            }

            catalog++;
        }
    } catch (Exception e) {
        BeLogTools.error(HmLogConst.M_PERFORMANCE_TABLEPARTITION, "Fail to init table partition configure file",
                e);
    }
}

From source file:com.aliyun.odps.ogg.handler.datahub.ConfigureReader.java

License:Apache License

public static Configure reader(String configueFileName) throws DocumentException {
    logger.info("Begin read configure[" + configueFileName + "]");

    Configure configure = new Configure();
    SAXReader reader = new SAXReader();
    File file = new File(configueFileName);

    Document document = reader.read(file);
    Element root = document.getRootElement();

    String elementText = root.elementTextTrim("batchSize");
    if (StringUtils.isNotBlank(elementText)) {
        configure.setBatchSize(Integer.parseInt(elementText));
    }/*from w ww . j a va  2 s  .  c om*/

    elementText = root.elementTextTrim("dirtyDataContinue");
    if (StringUtils.isNotBlank(elementText)) {
        configure.setDirtyDataContinue(Boolean.parseBoolean(elementText));
    }

    elementText = root.elementTextTrim("dirtyDataFile");
    if (StringUtils.isNotBlank(elementText)) {
        configure.setDirtyDataFile(elementText);
    }

    elementText = root.elementTextTrim("dirtyDataFileMaxSize");
    if (StringUtils.isNotBlank(elementText)) {
        configure.setDirtyDataFileMaxSize(Integer.parseInt(elementText));
    }

    elementText = root.elementTextTrim("retryTimes");
    if (StringUtils.isNotBlank(elementText)) {
        configure.setRetryTimes(Integer.parseInt(elementText));
    }

    elementText = root.elementTextTrim("retryInterval");
    if (StringUtils.isNotBlank(elementText)) {
        configure.setRetryInterval(Integer.parseInt(elementText));
    }

    elementText = root.elementTextTrim("disableCheckPointFile");
    if (StringUtils.isNotBlank(elementText)) {
        configure.setDisableCheckPointFile(Boolean.parseBoolean(elementText));
    }

    elementText = root.elementTextTrim("checkPointFileName");
    if (StringUtils.isNotBlank(elementText)) {
        configure.setCheckPointFileName(elementText);
    }

    Element element = root.element("defaultOracleConfigure");
    if (element == null) {
        throw new RuntimeException("defaultOracleConfigure is null");
    }

    elementText = element.elementTextTrim("sid");
    if (StringUtils.isBlank(elementText)) {
        throw new RuntimeException("defaultOracleConfigure.sid is null");
    }
    configure.setSid(elementText);

    String defaultOracleSchema = element.elementTextTrim("schema");

    SimpleDateFormat defaultSimpleDateFormat;
    elementText = element.elementTextTrim("dateFormat");
    if (StringUtils.isNotBlank(elementText)) {
        defaultSimpleDateFormat = new SimpleDateFormat(elementText);
    } else {
        defaultSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    element = root.element("defalutDatahubConfigure");
    if (element == null) {
        throw new RuntimeException("defalutDatahubConfigure is null");
    }

    String endPoint = element.elementText("endPoint");
    if (StringUtils.isBlank(endPoint)) {
        throw new RuntimeException("defalutDatahubConfigure.endPoint is null");

    }

    String defaultDatahubProject = element.elementText("project");
    String defaultDatahubAccessID = element.elementText("accessId");
    String defaultDatahubAccessKey = element.elementText("accessKey");

    Field defaultCTypeField = null;
    String defaultCTypeColumn = element.elementText("ctypeColumn");
    if (StringUtils.isNotBlank(defaultCTypeColumn)) {
        defaultCTypeField = new Field(defaultCTypeColumn, FieldType.STRING);
    }
    Field defaultCTimeField = null;
    String defaultCTimeColumn = element.elementText("ctimeColumn");
    if (StringUtils.isNotBlank(defaultCTimeColumn)) {
        defaultCTimeField = new Field(defaultCTimeColumn, FieldType.STRING);
    }
    Field defaultCidField = null;
    String defaultCidColumn = element.elementText("cidColumn");
    if (StringUtils.isNotBlank(defaultCidColumn)) {
        defaultCidField = new Field(defaultCidColumn, FieldType.STRING);
    }

    String defaultConstColumnMapStr = element.elementText("constColumnMap");
    Map<String, String> defalutConstColumnMappings = Maps.newHashMap();
    Map<String, Field> defaultConstColumnFieldMappings = Maps.newHashMap();
    parseConstColumnMap(defaultConstColumnMapStr, defalutConstColumnMappings, defaultConstColumnFieldMappings);

    element = root.element("mappings");
    if (element == null) {
        throw new RuntimeException("mappings is null");
    }

    List<Element> mappingElements = element.elements("mapping");
    if (mappingElements == null || mappingElements.size() == 0) {
        throw new RuntimeException("mappings.mapping is null");
    }

    //init table mapping
    for (Element e : mappingElements) {
        String oracleSchema = e.elementTextTrim("oracleSchema");
        if (StringUtils.isNotBlank(oracleSchema)) {
            //nothing
        } else if (StringUtils.isNotBlank(defaultOracleSchema)) {
            oracleSchema = defaultOracleSchema;
        } else {
            throw new RuntimeException(
                    "both mappings.mapping.oracleSchema and defaultOracleConfigure.schema is null");
        }

        String oracleTable = e.elementTextTrim("oracleTable");
        if (StringUtils.isBlank(oracleTable)) {
            throw new RuntimeException("mappings.mapping.oracleTable is null");
        }

        String datahubProject = e.elementTextTrim("datahubProject");
        if (StringUtils.isNotBlank(datahubProject)) {
            //nothing
        } else if (StringUtils.isNotBlank(defaultOracleSchema)) {
            datahubProject = defaultDatahubProject;
        } else {
            throw new RuntimeException(
                    "both mappings.mapping.datahubProject and defalutDatahubConfigure.project is null");
        }

        String datahubAccessId = e.elementTextTrim("datahubAccessId");
        if (StringUtils.isNotBlank(datahubAccessId)) {
            //nothing
        } else if (StringUtils.isNotBlank(defaultDatahubAccessID)) {
            datahubAccessId = defaultDatahubAccessID;
        } else {
            throw new RuntimeException(
                    "both mappings.mapping.datahubAccessId and defalutDatahubConfigure.accessId is null");
        }

        String datahubAccessKey = e.elementTextTrim("datahubAccessKey");
        if (StringUtils.isNotBlank(datahubAccessKey)) {
            //nothing
        } else if (StringUtils.isNotBlank(defaultDatahubAccessKey)) {
            datahubAccessKey = defaultDatahubAccessKey;
        } else {
            throw new RuntimeException(
                    "both mappings.mapping.datahubAccessKey and defalutDatahubConfigure.accessKey is null");
        }

        String topicName = e.elementTextTrim("datahubTopic");
        if (topicName == null) {
            throw new RuntimeException("mappings.mapping.datahubTopic is null");
        }

        String ctypeColumn = e.elementText("ctypeColumn");
        String ctimeColumn = e.elementText("ctimeColumn");
        String cidColumn = e.elementText("cidColumn");

        DatahubConfiguration datahubConfiguration = new DatahubConfiguration(
                new AliyunAccount(datahubAccessId, datahubAccessKey), endPoint);
        Project project = Project.Builder.build(datahubProject, datahubConfiguration);
        Topic topic = project.getTopic(topicName);
        if (topic == null) {
            throw new RuntimeException("Can not find datahub topic[" + topicName + "]");
        } else {
            logger.info(
                    "topic name: " + topicName + ", topic schema: " + topic.getRecordSchema().toJsonString());
        }

        TableMapping tableMapping = new TableMapping();
        tableMapping.setTopic(topic);
        tableMapping.setOracleSchema(oracleSchema.toLowerCase());
        tableMapping.setOracleTableName(oracleTable.toLowerCase());
        tableMapping.setOracleFullTableName(
                tableMapping.getOracleSchema() + "." + tableMapping.getOracleTableName());
        tableMapping
                .setCtypeField(StringUtils.isNotBlank(ctypeColumn) ? new Field(ctypeColumn, FieldType.STRING)
                        : defaultCTypeField);
        tableMapping
                .setCtimeField(StringUtils.isNotBlank(ctimeColumn) ? new Field(ctimeColumn, FieldType.STRING)
                        : defaultCTimeField);
        tableMapping.setCidField(
                StringUtils.isNotBlank(cidColumn) ? new Field(cidColumn, FieldType.STRING) : defaultCidField);

        String constColumnMapStr = e.elementText("constColumnMap");
        Map<String, String> constColumnMappings = Maps.newHashMap();
        Map<String, Field> constColumnFieldMappings = Maps.newHashMap();
        parseConstColumnMap(constColumnMapStr, constColumnMappings, constColumnFieldMappings);

        tableMapping.setConstColumnMappings(
                constColumnMappings.isEmpty() ? defalutConstColumnMappings : constColumnMappings);
        tableMapping.setConstFieldMappings(constColumnFieldMappings.isEmpty() ? defaultConstColumnFieldMappings
                : constColumnFieldMappings);

        Map<String, ColumnMapping> columnMappings = Maps.newHashMap();
        tableMapping.setColumnMappings(columnMappings);

        elementText = e.elementTextTrim("shardId");
        if (StringUtils.isNotBlank(elementText)) {
            tableMapping.setShardId(elementText);
        }

        configure.addTableMapping(tableMapping);

        RecordSchema recordSchema = topic.getRecordSchema();

        Element columnMappingElement = e.element("columnMapping");
        List<Element> columns = columnMappingElement.elements("column");
        for (Element columnElement : columns) {
            String oracleColumnName = columnElement.attributeValue("src");
            if (StringUtils.isBlank(oracleColumnName)) {
                throw new RuntimeException("Topic[" + topicName + "] src attribute is null");
            }

            oracleColumnName = oracleColumnName.toLowerCase();
            ColumnMapping columnMapping = new ColumnMapping();
            columnMappings.put(oracleColumnName, columnMapping);
            columnMapping.setOracleColumnName(oracleColumnName);

            String datahubFieldName = columnElement.attributeValue("dest");
            if (datahubFieldName == null) {
                throw new RuntimeException("Topic[" + topicName + "] dest attribute is null");
            }

            Field field = recordSchema.getField(datahubFieldName.toLowerCase());
            if (field == null) {
                throw new RuntimeException(
                        "Topic[" + topicName + "] Field[" + datahubFieldName + "] is not exist");
            }

            columnMapping.setField(field);

            String datahubOldFieldName = columnElement.attributeValue("destOld");
            if (StringUtils.isNotBlank(datahubOldFieldName)) {
                Field oldField = recordSchema.getField(datahubOldFieldName);

                if (field == null) {
                    throw new RuntimeException(
                            "Topic[" + topicName + "] Field[" + datahubOldFieldName + "] is not exist");
                }
                columnMapping.setOldFiled(oldField);
            }

            String isShardColumn = columnElement.attributeValue("isShardColumn");
            if (StringUtils.isNotBlank(isShardColumn) && Boolean.TRUE.equals(Boolean.valueOf(isShardColumn))) {
                tableMapping.setIsShardHash(true);
                columnMapping.setIsShardColumn(true);
            } else {
                columnMapping.setIsShardColumn(false);
            }

            String isKeyColumn = columnElement.attributeValue("isKeyColumn");
            if (StringUtils.isNotBlank(isKeyColumn) && Boolean.TRUE.equals(Boolean.valueOf(isKeyColumn))) {
                columnMapping.setIsKeyColumn(true);
            } else {
                columnMapping.setIsKeyColumn(false);
            }

            String dateFormat = columnElement.attributeValue("dateFormat");

            if (StringUtils.isNotBlank(dateFormat)) {
                columnMapping.setSimpleDateFormat(new SimpleDateFormat(dateFormat));
            } else {
                columnMapping.setSimpleDateFormat(defaultSimpleDateFormat);
            }

            String isDateFormat = columnElement.attributeValue("isDateFormat");

            if (StringUtils.isNotBlank(isDateFormat) && Boolean.FALSE.equals(Boolean.valueOf(isDateFormat))) {
                columnMapping.setIsDateFormat(false);
            } else {
                columnMapping.setIsDateFormat(true);
            }
        }
    }

    logger.info("Read configure success: " + JsonHelper.beanToJson(configure));
    return configure;
}

From source file:com.bluexml.side.framework.alfresco.sharePortalExtension.PresetsManagerExtension.java

License:Open Source License

/**
 * Construct the model objects for a given preset.
 * Objects persist to the default store for the appropriate object type.
 * //w  w w  .  ja  va 2 s. co  m
 * @param id
 *            Preset ID to use
 * @param tokens
 *            Name value pair tokens to replace in preset definition
 */
public void constructPreset(String id, Map<String, String> tokens) {
    if (id == null) {
        throw new IllegalArgumentException("Preset ID is mandatory.");
    }

    // perform one time init - this cannot be perform in an app handler or by the
    // framework init - as it requires the Alfresco server to be started...
    synchronized (this) {
        if (this.documents == null) {
            init();
        }
    }

    for (Document doc : this.documents) {
        for (Element preset : (List<Element>) doc.getRootElement().elements("preset")) {
            // found preset with matching id?
            if (id.equals(preset.attributeValue("id"))) {
                // any components in the preset?
                Element components = preset.element("components");
                if (components != null) {
                    for (Element c : (List<Element>) components.elements("component")) {
                        // apply token replacement to each value as it is retrieved
                        String title = replace(c.elementTextTrim(Component.PROP_TITLE), tokens);
                        String titleId = replace(c.elementTextTrim(Component.PROP_TITLE_ID), tokens);
                        String description = replace(c.elementTextTrim(Component.PROP_DESCRIPTION), tokens);
                        String descriptionId = replace(c.elementTextTrim(Component.PROP_DESCRIPTION_ID),
                                tokens);
                        String typeId = replace(c.elementTextTrim(Component.PROP_COMPONENT_TYPE_ID), tokens);
                        String scope = replace(c.elementTextTrim(Component.PROP_SCOPE), tokens);
                        String regionId = replace(c.elementTextTrim(Component.PROP_REGION_ID), tokens);
                        String sourceId = replace(c.elementTextTrim(Component.PROP_SOURCE_ID), tokens);
                        String url = replace(c.elementTextTrim(Component.PROP_URL), tokens);
                        String chrome = replace(c.elementTextTrim(Component.PROP_CHROME), tokens);

                        // validate mandatory values
                        if (scope == null || scope.length() == 0) {
                            throw new IllegalArgumentException(
                                    "Scope is a mandatory property for a component preset.");
                        }
                        if (regionId == null || regionId.length() == 0) {
                            throw new IllegalArgumentException(
                                    "RegionID is a mandatory property for a component preset.");
                        }
                        if (sourceId == null || sourceId.length() == 0) {
                            throw new IllegalArgumentException(
                                    "SourceID is a mandatory property for a component preset.");
                        }

                        // generate component
                        Component component = modelObjectService.newComponent(scope, regionId, sourceId);
                        component.setComponentTypeId(typeId);
                        component.setTitle(title);
                        component.setTitleId(titleId);
                        component.setDescription(description);
                        component.setDescriptionId(descriptionId);
                        component.setURL(url);
                        component.setChrome(chrome);

                        // apply arbituary custom properties
                        if (c.element("properties") != null) {
                            for (Element prop : (List<Element>) c.element("properties").elements()) {
                                String propName = replace(prop.getName(), tokens);
                                String propValue = replace(prop.getTextTrim(), tokens);
                                component.setCustomProperty(propName, propValue);
                            }
                        }

                        // persist the object
                        modelObjectService.saveObject(component);
                    }
                }

                // any pages in the preset?
                Element pages = preset.element("pages");
                if (pages != null) {
                    for (Element p : (List<Element>) pages.elements("page")) {
                        // apply token replacement to each value as it is retrieved
                        String pageId = replace(p.attributeValue(Page.PROP_ID), tokens);
                        String title = replace(p.elementTextTrim(Page.PROP_TITLE), tokens);
                        String titleId = replace(p.elementTextTrim(Page.PROP_TITLE_ID), tokens);
                        String description = replace(p.elementTextTrim(Page.PROP_DESCRIPTION), tokens);
                        String descriptionId = replace(p.elementTextTrim(Page.PROP_DESCRIPTION_ID), tokens);
                        String typeId = replace(p.elementTextTrim(Page.PROP_PAGE_TYPE_ID), tokens);
                        String auth = replace(p.elementTextTrim(Page.PROP_AUTHENTICATION), tokens);
                        String template = replace(p.elementTextTrim(Page.PROP_TEMPLATE_INSTANCE), tokens);

                        // validate mandatory values
                        if (pageId == null || pageId.length() == 0) {
                            throw new IllegalArgumentException(
                                    "ID is a mandatory attribute for a page preset.");
                        }
                        if (template == null || template.length() == 0) {
                            throw new IllegalArgumentException(
                                    "Template is a mandatory property for a page preset.");
                        }

                        // generate page
                        Page page = modelObjectService.newPage(pageId);
                        page.setPageTypeId(typeId);
                        page.setTitle(title);
                        page.setTitleId(titleId);
                        page.setDescription(description);
                        page.setDescriptionId(descriptionId);
                        page.setAuthentication(auth);
                        page.setTemplateId(template);

                        // apply arbituary custom properties
                        if (p.element("properties") != null) {
                            for (Element prop : (List<Element>) p.element("properties").elements()) {
                                String propName = replace(prop.getName(), tokens);
                                String propValue = replace(prop.getTextTrim(), tokens);
                                page.setCustomProperty(propName, propValue);
                            }
                        }

                        // persist the object
                        modelObjectService.saveObject(page);
                    }
                }

                // any template instances in the preset?
                Element templates = preset.element("template-instances");
                if (templates != null) {
                    for (Element t : (List<Element>) templates.elements("template-instance")) {
                        // apply token replacement to each value as it is retrieved
                        String templateId = replace(t.attributeValue(TemplateInstance.PROP_ID), tokens);
                        String title = replace(t.elementTextTrim(TemplateInstance.PROP_TITLE), tokens);
                        String titleId = replace(t.elementTextTrim(TemplateInstance.PROP_TITLE_ID), tokens);
                        String description = replace(t.elementTextTrim(TemplateInstance.PROP_DESCRIPTION),
                                tokens);
                        String descriptionId = replace(t.elementTextTrim(TemplateInstance.PROP_DESCRIPTION_ID),
                                tokens);
                        String templateType = replace(t.elementTextTrim(TemplateInstance.PROP_TEMPLATE_TYPE),
                                tokens);

                        // validate mandatory values
                        if (templateId == null || templateId.length() == 0) {
                            throw new IllegalArgumentException(
                                    "ID is a mandatory attribute for a template-instance preset.");
                        }
                        if (templateType == null || templateType.length() == 0) {
                            throw new IllegalArgumentException(
                                    "Template is a mandatory property for a page preset.");
                        }

                        // generate template-instance
                        TemplateInstance template = modelObjectService.newTemplate(templateId);
                        template.setTitle(title);
                        template.setTitleId(titleId);
                        template.setDescription(description);
                        template.setDescriptionId(descriptionId);
                        template.setTemplateTypeId(templateType);

                        // apply arbituary custom properties
                        if (t.element("properties") != null) {
                            for (Element prop : (List<Element>) t.element("properties").elements()) {
                                String propName = replace(prop.getName(), tokens);
                                String propValue = replace(prop.getTextTrim(), tokens);
                                template.setCustomProperty(propName, propValue);
                            }
                        }

                        // persist the object
                        modelObjectService.saveObject(template);
                    }
                }

                // TODO: any chrome, associations, types, themes etc. in the preset...

                // found our preset - no need to process further
                break;
            }
        }
    }
}

From source file:com.daoke.mobileserver.carinsurance.controller.CarInsuranceController.java

/**
 * //from  w w w  .  jav a 2s .co m
 * 
 * @param car
 * @return
 */
@ResponseBody
@RequestMapping("/queryCarType")
public String queryCarType(Car car) {
    String result = null;
    Document doc = null;
    try {
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>" + "<PackageList>" + "<Package>" + "<Header>"
                + "<version>2</version>" + "<ordertype>3</ordertype>" + "<username>" + car.getUsername()
                + "</username>" + "<password>" + car.getPassword() + "</password>" + "</Header>" + "<Request>"
                + "<AreaInfo>" + "<companyno>" + car.getCompanyno() + "</companyno>" + "<citycode>"
                + car.getCitycode() + "</citycode>" + "</AreaInfo>" + "<CarmoduleInfo>" + "<callback>"
                + car.getCallback() + "</callback>" + "</CarmoduleInfo>" + "<VehicleInfo>" + "<licenseno>"
                + car.getLicenseno() + "</licenseno>" + "<nolicenseflag>" + car.isNolicenseflag()
                + "</nolicenseflag>" + "<ownername>" + car.getOwnername() + "</ownername>" + "</VehicleInfo>"
                + "</Request>" + "</Package>" + "</PackageList>";
        result = carInsuranceService.queryCarType(xml, carApi);
        doc = DocumentHelper.parseText(result);
        Element rootElement = doc.getRootElement();
        Element element = rootElement.element("Package");
        Element header = element.element("Header");
        String statuscode = header.elementTextTrim("statuscode");
        if (("0").equals(statuscode)) {
            Element response = element.element("Response");
            Element carmoduleInfo = response.element("CarmoduleInfo");
            String page = carmoduleInfo.elementTextTrim("page");
        } else {
            String message = header.elementTextTrim("message");
        }
        logger.info(result);
    } catch (Exception e) {
        result = JsonPuserUtil.jsonToString(ConstantsUtil.ERRORCODE_SERVICE_ERROR,
                ConstantsUtil.RESULT_SERVICE_ERROR);
        logger.error(JsonPuserUtil.jsonToString(ConstantsUtil.ERRORCODE_SERVICE_ERROR, e.toString()));
    }
    return result;
}

From source file:com.daoke.mobileserver.carinsurance.controller.CarInsuranceController.java

/**
 * ?????/*  w  w  w.  j  a  v a2 s  .c  om*/
 * 
 * @param elementInsurance
 * @return
 */
@ResponseBody
@RequestMapping("/getElementAndInsurance")
public String getElementAndInsurance(ElementInsurance elementInsurance) {
    String result = null;
    Document doc = null;
    try {
        String type = elementInsurance.getSubType();
        if (StringUtils.isNotEmpty(type)) {
            type = "<TagsCarSubjList>" + "<Tag>" + "<Definition name=\"type\">" + elementInsurance.getSubType()
                    + "</ Definition>" + "<Definition name=\"key\">" + elementInsurance.getSubKey()
                    + "</ Definition>" + "<Definition name=\"label\">" + elementInsurance.getSubLabel()
                    + "</Definition>" + "<Definition name=\"value\"/>" + "<Definition name=\"premium\"/>"
                    + "<Definition name=\"disable\"/>"
                    + "<Definition name=\"data\"> <![CDATA:1;?: 0]]> </ Definition>" + "</Tag>"
                    + "</TagsCarSubjList>" + "<TagsCarRiskList>" + "<Tag>" + "<Definition name=\"type\">"
                    + elementInsurance.getRiskType() + "</Definition>" + "<Definition name=\"key\">"
                    + elementInsurance.getRiskKey() + "</Definition>" + "<Definition name=\"label\">"
                    + elementInsurance.getRiskLabel() + "</Definition>" + "<Definition name=\"value\">"
                    + elementInsurance.getRiskValue() + "</Definition>" + "<Definition name=\"premium\">"
                    + elementInsurance.getRiskPremium() + "</Definition>" + "<Definition name=\"disable\"/>"
                    + "<Definition name=\"data\"><![CDATA[?:1]]></Definition>" + "</Tag>"
                    + "</TagsCarRiskList>";
        } else {
            type = "";
        }
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>" + "<PackageList>" + "<Package>" + "<Header>"
                + "<version>2</version>" + "<ordertype>3</ordertype>" + "<username>"
                + elementInsurance.getUsername() + "</username>" + "<password>" + elementInsurance.getPassword()
                + "</password>" + "</Header>" + "<Request>" + "<AreaInfo>" + "<companyno>"
                + elementInsurance.getCompanyno() + "</companyno>" + "<citycode>"
                + elementInsurance.getCitycode() + "</citycode>" + "</AreaInfo>" + "<PlcInfo>"
                + "<plcstartdate>" + elementInsurance.getPlcstartdate() + "</plcstartdate>" + "<plcenddate>"
                + elementInsurance.getPlcenddate() + "</plcenddate>" + "</PlcInfo>" + "<VehicleInfo>"
                + "<licenseno>" + elementInsurance.getLicenseno() + "</licenseno>" + "<nolicenseflag>"
                + elementInsurance.isNolicenseflag() + "</nolicenseflag>" + "<ownername>"
                + elementInsurance.getOwnername() + "</ownername>" + "<ownercerttype>"
                + elementInsurance.getOwnercerttype() + "</ownercerttype>" + "<ownercertno>"
                + elementInsurance.getOwnercertno() + "</ownercertno>" + "</VehicleInfo>" + "<InsurInfo>"
                + "<name>" + elementInsurance.getName() + "</name>" + "</InsurInfo>" + type + "</Request>"
                + "</Package>" + "</PackageList>";
        result = carInsuranceService.getElementAndInsurance(xml, carApi);
        doc = DocumentHelper.parseText(result);
        Element rootElement = doc.getRootElement();
        Element element = rootElement.element("Package");
        Element header = element.element("Header");
        String statuscode = header.elementTextTrim("statuscode");
        if (("2").equals(statuscode)) {
            //?
        }
    } catch (Exception e) {
        result = JsonPuserUtil.jsonToString(ConstantsUtil.ERRORCODE_SERVICE_ERROR,
                ConstantsUtil.RESULT_SERVICE_ERROR);
        logger.error(JsonPuserUtil.jsonToString(ConstantsUtil.ERRORCODE_SERVICE_ERROR, e.toString()));
    }
    return result;
}

From source file:com.eurelis.opencms.admin.xmltransformation.ui.CmsXmlTransformationDialog.java

License:Open Source License

public List<String> processRequest(CmsXmlTransformation cmsXmlTransformation) {
    CmsJspActionElement jsp = this.getJsp();
    CmsObject cmsObject = this.getCms();

    String uri = CmsEncoder.decode(jsp.getRequest().getParameter(CmsDialog.PARAM_RESOURCE));

    boolean contentTypeValid = false;

    List<String> errorList = new ArrayList<String>();
    XMLTransformationBuilder xmlTransformationBuilder = XMLTransformationBuilder.newInstance();

    try {/*from  ww  w  . ja va2  s . c o m*/
        CmsFile cmsFile = cmsObject.readFile(uri);

        CmsXmlContent xmlTransformationContent = CmsXmlContentFactory.unmarshal(cmsObject, cmsFile);
        List<Locale> localeList = xmlTransformationContent.getLocales();

        String contentType = null;

        if (localeList.size() == 1) {
            Locale locale = localeList.get(0);

            I_CmsXmlContentValue fileTypeContentValue = xmlTransformationContent.getValue("ContentType",
                    locale);
            contentType = fileTypeContentValue.getStringValue(cmsObject);

            I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(contentType);

            if (resourceType != null) {
                contentTypeValid = true;
                cmsXmlTransformation.setContentType(resourceType.getTypeId());
            }

            if (!contentTypeValid) {
                errorList.add(String.format(
                        Messages.getLbl(Messages.GUI_XMLTRANSFORMATION_BADCONTENTTYPE_FORMAT_0, getLocale()),
                        contentType));
                cmsXmlTransformation.setContentType(-1);
            }

            List<I_CmsXmlContentValue> unitaryTransformationList = xmlTransformationContent
                    .getValues("UnitaryTransformation", locale);

            int unitaryTransformationIndex = 0;
            for (I_CmsXmlContentValue unitaryTransformation : unitaryTransformationList) {
                unitaryTransformationIndex++; // indice a 1

                UnitaryTransformationBuilder unitaryTransformationBuilder = xmlTransformationBuilder
                        .newUnitaryTransformationBuilder();

                boolean validSource = false;

                String sourcePath = String.format("UnitaryTransformation[%d]/Source",
                        unitaryTransformationIndex);
                String destinationXPath = String.format("UnitaryTransformation[%d]/Destination/XPath",
                        unitaryTransformationIndex);
                String destinationSXPath = String.format("UnitaryTransformation[%d]/Destination/SXPath",
                        unitaryTransformationIndex);
                String destinationPosition = String.format("UnitaryTransformation[%d]/Destination/Position",
                        unitaryTransformationIndex);
                String templatePath = String.format("UnitaryTransformation[%d]/Template",
                        unitaryTransformationIndex);

                String sourceContentString = null;

                I_CmsXmlContentValue sourceContentValue = xmlTransformationContent.getValue(sourcePath, locale);

                if (sourceContentValue != null) {
                    sourceContentString = sourceContentValue.getStringValue(cmsObject);

                    if (sourceContentString != null && !sourceContentString.isEmpty()) {
                        try {
                            XPath sourceXPath = DocumentFactory.getInstance().createXPath(sourceContentString);

                            unitaryTransformationBuilder.setSource(sourceXPath);

                            validSource = true;

                        } catch (InvalidXPathException e) {

                        }

                    }

                }

                if (!validSource) {
                    errorList.add(String.format(
                            Messages.getLbl(Messages.GUI_UNITARYTRANSFORMATION_BADSOURCE_FORMAT_0, getLocale()),
                            sourceContentString, sourcePath));
                }

                // destination
                I_CmsXmlContentValue xPathContentValue = xmlTransformationContent.getValue(destinationXPath,
                        locale);
                I_CmsXmlContentValue sxPathContentValue = xmlTransformationContent.getValue(destinationSXPath,
                        locale);
                I_CmsXmlContentValue positionContentValue = xmlTransformationContent
                        .getValue(destinationPosition, locale);

                if (xPathContentValue != null && sxPathContentValue != null) {
                    String destinationXPathString = xPathContentValue.getStringValue(cmsObject);
                    String sxPathString = sxPathContentValue.getStringValue(cmsObject);

                    String position = positionContentValue.getStringValue(cmsObject);

                    Position pos = Position.LAST;

                    if (position != null) {
                        if ("FIRST".equalsIgnoreCase(position)) {
                            pos = Position.FIRST;
                        } else if ("LAST".equalsIgnoreCase(position)) {
                            pos = Position.LAST;
                        } else if ("BEFORE".equalsIgnoreCase(position)) {
                            pos = Position.BEFORE;
                        } else if ("AFTER".equalsIgnoreCase(position)) {
                            pos = Position.AFTER;
                        }
                    }

                    String xPathTestString = null;

                    if (destinationXPathString.charAt(destinationXPathString.length() - 1) == '/') {
                        xPathTestString = destinationXPathString.substring(0,
                                destinationXPathString.length() - 1);
                    } else {
                        xPathTestString = destinationXPathString;
                    }

                    boolean isSimplified = Boolean.valueOf(sxPathString);
                    boolean isValidPosition = true;

                    if (isSimplified) {
                        if (pos == Position.BEFORE || pos == Position.AFTER) {
                            isValidPosition = false;
                        }
                    }

                    if (!isValidPosition) {
                        errorList.add(String.format(
                                Messages.getLbl(Messages.GUI_UNITARYTRANSFORMATION_BADSXPATH_POSITION_FORMAT_0,
                                        getLocale()),
                                position, destinationPosition));
                    }

                    boolean validXPath = false;

                    try {
                        DocumentFactory.getInstance().createXPath(xPathTestString);
                        validXPath = true;
                    } catch (InvalidXPathException e) {

                    }

                    if (validXPath && isSimplified) {

                        try {
                            XPATHParser.getInstance().parseFailOverPath(destinationXPathString, pos);
                        } catch (java.lang.IllegalArgumentException e) {
                            validXPath = false;
                        }

                    }

                    if (!validXPath) {
                        errorList.add(String.format(
                                Messages.getLbl(Messages.GUI_UNITARYTRANSFORMATION_BADDESTINATION_FORMAT_0,
                                        getLocale()),
                                isSimplified ? 1 : 0, destinationXPathString, destinationXPath));

                    } else {
                        if (isSimplified) {
                            unitaryTransformationBuilder.setSXPathDestination(destinationXPathString, pos);
                        } else {
                            unitaryTransformationBuilder.setXPathDestination(destinationXPathString, pos);
                        }

                    }

                }

                // template
                I_CmsXmlContentValue templateContentValue = xmlTransformationContent.getValue(templatePath,
                        locale);
                if (templateContentValue != null) {
                    Element templateElement = templateContentValue.getElement();

                    boolean isValidTemplateString = false;
                    String templateString = templateElement.selectSingleNode("Template").getText().trim();

                    TemplateTransformationBuilder templateTransformationBuilder = unitaryTransformationBuilder
                            .getTemplateTransformationBuilder();

                    try {
                        templateTransformationBuilder.setTemplate(templateString);
                        isValidTemplateString = true;
                    } catch (DocumentException e) {

                    }

                    if (!isValidTemplateString) {
                        errorList.add(String.format(Messages
                                .getLbl(Messages.GUI_TEMPLATETRANSFORMATION_BADTEMPLATE_FORMAT_0, getLocale()),
                                templateString, templatePath));
                    }

                    int templateParameterIndex = 0;
                    @SuppressWarnings("unchecked")
                    List<Element> templateParameterList = templateElement.selectNodes("Parameters");

                    for (Element templateParameterElement : templateParameterList) {
                        templateParameterIndex++;
                        String templateParameterPath = String.format(
                                "UnitaryTransformation[%d]/Template/Parameters[%d]/",
                                unitaryTransformationIndex, templateParameterIndex);

                        String templateParameterName = templateParameterElement
                                .elementTextTrim("ParameterName");
                        String templateParameterXPathValue = templateParameterElement
                                .elementTextTrim("ParameterXPathValue");

                        boolean templateParameterIsValid = false;

                        if (!templateParameterName.isEmpty() && !templateParameterXPathValue.isEmpty()) {
                            try {
                                templateTransformationBuilder.addParameter(templateParameterName,
                                        DocumentFactory.getInstance().createXPath(templateParameterXPathValue));
                                templateParameterIsValid = true;
                            } catch (InvalidXPathException e) {

                            }

                        }

                        if (!templateParameterIsValid) {
                            errorList.add(String.format(
                                    Messages.getLbl(Messages.GUI_TEMPLATETRANSFORMATION_BADPARAMETER_FORMAT_0,
                                            getLocale()),
                                    templateParameterName, templateParameterXPathValue, templateParameterPath));
                        }

                    }

                }

            }

        }

    } catch (CmsException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("processRequest " + e);
        }
        LOG.error("processRequest " + e.getMessage());
        e.printStackTrace();
    }

    if (errorList.isEmpty()) {
        cmsXmlTransformation.setXmlTransformation(xmlTransformationBuilder.build());
        cmsXmlTransformation.setXmlTransformationProcessingErrors(null);
    } else {
        cmsXmlTransformation.setXmlTransformation(null);
        cmsXmlTransformation.setXmlTransformationProcessingErrors(errorList);
    }

    return errorList;

}

From source file:com.glaf.activiti.extension.xml.ExtensionReader.java

License:Apache License

public List<ExtensionEntity> readTasks(java.io.InputStream inputStream) {
    List<ExtensionEntity> extensions = new java.util.ArrayList<ExtensionEntity>();
    SAXReader xmlReader = new SAXReader();
    try {//from   ww  w  . j av a 2  s  .c o  m
        Document doc = xmlReader.read(inputStream);
        Element root = doc.getRootElement();
        String x_type = root.attributeValue("type");
        List<?> rows = root.elements("taskmgr");
        Iterator<?> iterator = rows.iterator();
        while (iterator.hasNext()) {
            Element element = (Element) iterator.next();
            ExtensionEntity extension = new ExtensionEntity();
            extension.setProcessName(element.attributeValue("processName"));
            extension.setTaskName(element.attributeValue("taskName"));
            extension.setType(x_type);
            if (element.elementTextTrim("taskMgmtType") != null) {
                ExtensionFieldEntity extensionField = new ExtensionFieldEntity();
                extensionField.setName("taskMgmtType");
                extensionField.setValue(element.elementTextTrim("taskMgmtType"));
                extension.addField(extensionField);
            }
            Element propertiesE = element.element("properties");
            if (propertiesE != null) {
                List<?> properties = propertiesE.elements("property");
                Iterator<?> iter = properties.iterator();
                while (iter.hasNext()) {
                    Element elem = (Element) iter.next();
                    String propertyName = elem.attributeValue("key");
                    String propertyValue = null;
                    if (elem.attribute("value") != null) {
                        propertyValue = elem.attributeValue("value");
                    } else {
                        propertyValue = elem.getTextTrim();
                    }
                    if (StringUtils.isNotEmpty(propertyName) && StringUtils.isNotEmpty(propertyValue)) {
                        ExtensionFieldEntity extensionField = new ExtensionFieldEntity();
                        extensionField.setName(propertyName.trim());
                        extensionField.setValue(propertyValue.trim());
                        extension.addField(extensionField);
                    }
                }
            }
            if (element.elementText("handlers") != null) {
                ExtensionFieldEntity extensionField = new ExtensionFieldEntity();
                extensionField.setName("handlers");
                extensionField.setValue(element.elementTextTrim("handlers"));
                extension.addField(extensionField);
            }
            extensions.add(extension);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    return extensions;
}