Example usage for org.apache.commons.lang StringUtils substringAfterLast

List of usage examples for org.apache.commons.lang StringUtils substringAfterLast

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringAfterLast.

Prototype

public static String substringAfterLast(String str, String separator) 

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:com.contrastsecurity.ide.eclipse.ui.internal.model.RecommendationTab.java

public void setRecommendationResource(RecommendationResource recommendationResource) {
    this.recommendationResource = recommendationResource;
    Composite control = getControl();
    Control[] children = control.getChildren();
    for (Control child : children) {
        child.dispose();//from  w  ww  . j a  v a  2s  . c  o  m
    }

    if (recommendationResource != null && recommendationResource.getRecommendation() != null
            && recommendationResource.getCustomRecommendation() != null
            && recommendationResource.getRuleReferences() != null
            && recommendationResource.getCustomRuleReferences() != null) {

        String formattedRecommendationText = recommendationResource.getRecommendation().getFormattedText();
        String openTag = null;
        String closeTag = null;

        if (formattedRecommendationText.contains(Constants.OPEN_TAG_C_SHARP_BLOCK)) {
            openTag = Constants.OPEN_TAG_C_SHARP_BLOCK;
            closeTag = Constants.CLOSE_TAG_C_SHARP_BLOCK;
        } else if (formattedRecommendationText.contains(Constants.OPEN_TAG_HTML_BLOCK)) {
            openTag = Constants.OPEN_TAG_HTML_BLOCK;
            closeTag = Constants.CLOSE_TAG_HTML_BLOCK;
        } else if (formattedRecommendationText.contains(Constants.OPEN_TAG_JAVA_BLOCK)) {
            openTag = Constants.OPEN_TAG_JAVA_BLOCK;
            closeTag = Constants.CLOSE_TAG_JAVA_BLOCK;
        } else if (formattedRecommendationText.contains(Constants.OPEN_TAG_XML_BLOCK)) {
            openTag = Constants.OPEN_TAG_XML_BLOCK;
            closeTag = Constants.CLOSE_TAG_XML_BLOCK;
        } else if (formattedRecommendationText.contains(Constants.OPEN_TAG_JAVASCRIPT_BLOCK)) {
            openTag = Constants.OPEN_TAG_JAVASCRIPT_BLOCK;
            closeTag = Constants.CLOSE_TAG_JAVASCRIPT_BLOCK;
        }

        String[] codeBlocks = StringUtils.substringsBetween(formattedRecommendationText, openTag, closeTag);
        String[] textBlocks = StringUtils.substringsBetween(formattedRecommendationText, closeTag, openTag);

        String textBlockFirst = StringUtils.substringBefore(formattedRecommendationText, openTag);
        String textBlockLast = StringUtils.substringAfterLast(formattedRecommendationText, closeTag);

        insertTextBlock(control, textBlockFirst);

        if (codeBlocks != null && codeBlocks.length > 0) {
            for (int i = 0; i < codeBlocks.length; i++) {

                String textToInsert = StringEscapeUtils.unescapeHtml(codeBlocks[i]);
                createStyledTextCodeBlock(control, textToInsert);

                if (textBlocks != null && textBlocks.length > 0 && i < codeBlocks.length - 1) {
                    insertTextBlock(control, textBlocks[i]);
                }
            }
        }

        insertTextBlock(control, textBlockLast);

        CustomRecommendation customRecommendation = recommendationResource.getCustomRecommendation();
        String customRecommendationText = customRecommendation.getText() == null ? Constants.BLANK
                : customRecommendation.getText();
        if (!customRecommendationText.isEmpty()) {
            customRecommendationText = parseMustache(customRecommendationText);

            createLabel(control, customRecommendationText);
        }

        Composite cweComposite = new Composite(control, SWT.NONE);
        cweComposite.setLayout(new RowLayout());

        Label cweHeaderLabel = createLabel(cweComposite, "CWE:");
        cweHeaderLabel.setLayoutData(new RowData(100, 15));
        Link cweLink = createLinkFromUrlString(cweComposite, recommendationResource.getCwe());
        cweLink.setLayoutData(new RowData());

        Composite owaspComposite = new Composite(control, SWT.NONE);
        owaspComposite.setLayout(new RowLayout());

        Label owaspHeaderLabel = createLabel(owaspComposite, "OWASP:");
        owaspHeaderLabel.setLayoutData(new RowData(100, 15));
        Link owaspLink = createLinkFromUrlString(owaspComposite, recommendationResource.getOwasp());
        owaspLink.setLayoutData(new RowData());

        RuleReferences ruleReferences = recommendationResource.getRuleReferences();
        String ruleReferencesText = ruleReferences.getText() == null ? Constants.BLANK
                : ruleReferences.getText();
        if (!ruleReferencesText.isEmpty()) {

            Composite referencesComposite = new Composite(control, SWT.NONE);
            referencesComposite.setLayout(new RowLayout());

            Label referencesHeaderLabel = createLabel(referencesComposite, "References:");
            referencesHeaderLabel.setLayoutData(new RowData(100, 15));

            String firstLink = StringUtils.substringBefore(ruleReferencesText, Constants.MUSTACHE_NL);
            Link referencesLink = createLinkFromUrlString(referencesComposite, firstLink);
            referencesLink.setLayoutData(new RowData());

            String[] links = StringUtils.substringsBetween(ruleReferencesText, Constants.MUSTACHE_NL,
                    Constants.MUSTACHE_NL);

            if (links != null && links.length > 0) {
                for (String link : links) {
                    Link linkObject = createLinkFromUrlString(referencesComposite, link);
                    linkObject.setLayoutData(new RowData());
                }
            }
        }
        CustomRuleReferences customRuleReferences = recommendationResource.getCustomRuleReferences();
        if (StringUtils.isNotEmpty(customRuleReferences.getText())) {
            String customRuleReferencesText = parseMustache(customRuleReferences.getText());
            createLabel(control, customRuleReferencesText);
        }
    }

    ScrolledComposite sc = (ScrolledComposite) control.getParent();

    Rectangle r = sc.getClientArea();
    Control content = sc.getContent();
    if (content != null && r != null) {
        Point minSize = content.computeSize(r.width, SWT.DEFAULT);
        sc.setMinSize(minSize);
        ScrollBar vBar = sc.getVerticalBar();
        vBar.setPageIncrement(r.height);
    }

}

From source file:com.hangum.tadpole.engine.sql.util.sqlscripts.scripts.MySqlDDLScript.java

@Override
public String getTriggerScript(TriggerDAO triggerDAO) throws Exception {
    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);

    StringBuilder result = new StringBuilder("");

    Map srcList = (HashMap) client.queryForObject("getTriggerScript", triggerDAO.getTrigger());
    String strSource = "" + srcList.get("SQL Original Statement");
    strSource = StringUtils.substringAfterLast(strSource, "TRIGGER");

    return "CREATE TRIGGER " + strSource;
}

From source file:info.magnolia.cms.servlets.RequestInterceptor.java

/**
 * Request and Response here is same as receivced by the original page so it includes all post/get data. Sub action
 * could be called from here once this action finishes, it will continue loading the requested page.
 *//*from w w w  .j  av a  2 s.c  o m*/
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    String action = request.getParameter(EntryServlet.INTERCEPT);
    String repository = request.getParameter(PARAM_REPOSITORY);
    if (repository == null) {
        repository = ContentRepository.WEBSITE;
    }
    HierarchyManager hm = MgnlContext.getHierarchyManager(repository);
    synchronized (ExclusiveWrite.getInstance()) {
        if (action.equals(ACTION_PREVIEW)) {
            // preview mode (button in main bar)
            String preview = request.getParameter(Resource.MGNL_PREVIEW_ATTRIBUTE);
            if (preview != null) {

                // @todo IMPORTANT remove use of http session
                HttpSession httpsession = request.getSession(true);
                if (BooleanUtils.toBoolean(preview)) {
                    httpsession.setAttribute(Resource.MGNL_PREVIEW_ATTRIBUTE, Boolean.TRUE);
                } else {
                    httpsession.removeAttribute(Resource.MGNL_PREVIEW_ATTRIBUTE);
                }
            }
        } else if (action.equals(ACTION_NODE_DELETE)) {
            // delete paragraph
            try {
                String path = request.getParameter(PARAM_PATH);
                // deactivate
                updatePageMetaData(request, hm);
                hm.delete(path);
                hm.save();
            } catch (RepositoryException e) {
                log.error("Exception caught: " + e.getMessage(), e); //$NON-NLS-1$
            }
        } else if (action.equals(ACTION_NODE_SORT)) {
            // sort paragrpahs
            try {
                String pathSelected = request.getParameter(PARAM_PATH_SELECTED);
                String pathSortAbove = request.getParameter(PARAM_PATH_SORT_ABOVE);
                String pathParent = StringUtils.substringBeforeLast(pathSelected, "/"); //$NON-NLS-1$
                String srcName = StringUtils.substringAfterLast(pathSelected, "/");
                String destName = StringUtils.substringAfterLast(pathSortAbove, "/");
                if (StringUtils.equalsIgnoreCase(destName, "mgnlNew")) {
                    destName = null;
                }
                hm.getContent(pathParent).orderBefore(srcName, destName);
                hm.save();
            } catch (RepositoryException e) {
                if (log.isDebugEnabled())
                    log.debug("Exception caught: " + e.getMessage(), e); //$NON-NLS-1$
            }
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.formatters.UIFormatterListEdtDlg.java

@Override
public void createUI() {
    super.createUI();

    CellConstraints cc = new CellConstraints();

    // get formatters for field
    List<UIFieldFormatterIFace> fmtrs = new Vector<UIFieldFormatterIFace>(uiFieldFormatterMgrCache
            .getFormatterList(fieldInfo.getTableInfo().getClassObj(), fieldInfo.getName()));
    Collections.sort(fmtrs, new Comparator<UIFieldFormatterIFace>() {
        public int compare(UIFieldFormatterIFace o1, UIFieldFormatterIFace o2) {
            return o1.getName().compareTo(o2.getName());
        }//www. jav  a  2s.  c  o m
    });

    // table and field titles
    PanelBuilder tblInfoPB = new PanelBuilder(
            new FormLayout("r:p,2px,f:p:g", "p,2px,p,2px,p,10px")/*, new FormDebugPanel()*/);

    String typeStr = fieldInfo.getType();
    typeStr = typeStr.indexOf('.') > -1 ? StringUtils.substringAfterLast(fieldInfo.getType(), ".") : typeStr;

    JLabel tableTitleLbl = createLabel(getResourceString("FFE_TABLE") + ":");
    JLabel tableTitleValueLbl = createLabel(fieldInfo.getTableInfo().getTitle());
    tableTitleValueLbl.setBackground(Color.WHITE);
    tableTitleValueLbl.setOpaque(true);

    JLabel fieldTitleLbl = createLabel(getResourceString("FFE_FIELD") + ":");
    JLabel fieldTitleValueLbl = createLabel(fieldInfo.getTitle());
    fieldTitleValueLbl.setBackground(Color.WHITE);
    fieldTitleValueLbl.setOpaque(true);

    //JLabel fieldTypeLbl = createLabel(getResourceString("FFE_TYPE") + ":");
    //JLabel fieldTypeValueLbl = createLabel(typeStr);
    //fieldTypeValueLbl.setBackground(Color.WHITE);
    //fieldTypeValueLbl.setOpaque(true);

    JLabel fieldLengthLbl = createLabel(getResourceString("FFE_LENGTH") + ":");
    JLabel fieldLengthValueLbl = createLabel(Integer.toString(fieldInfo.getLength()));
    fieldLengthValueLbl.setBackground(Color.WHITE);
    fieldLengthValueLbl.setOpaque(true);

    int y = 1;
    tblInfoPB.add(tableTitleLbl, cc.xy(1, y));
    tblInfoPB.add(tableTitleValueLbl, cc.xy(3, y));
    y += 2;
    tblInfoPB.add(fieldTitleLbl, cc.xy(1, y));
    tblInfoPB.add(fieldTitleValueLbl, cc.xy(3, y));
    y += 2;
    //tblInfoPB.add(fieldTypeLbl,        cc.xy(1, y));
    //tblInfoPB.add(fieldTypeValueLbl,   cc.xy(3, y)); y += 2;
    tblInfoPB.add(fieldLengthLbl, cc.xy(1, y));
    tblInfoPB.add(fieldLengthValueLbl, cc.xy(3, y));
    y += 2;

    DefaultListModel listModel = new DefaultListModel();

    // add available formatters
    for (UIFieldFormatterIFace format : fmtrs) {
        listModel.addElement(format);
    }

    formatList = createList(listModel);
    formatList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    //formatList.setCellRenderer(new FmtListRenderer());
    hookFormatListSelectionListener();
    hookFormatListMouseListener();

    ActionListener deleteListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            deleteFormatter();
        }
    };

    ActionListener editListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            editFormatter((UIFieldFormatter) formatList.getSelectedValue(), false);
        }
    };

    ActionListener addListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            addFormatter();
        }
    };

    ActionListener defListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setAsDefFormatter();
        }
    };

    dedaPanel = new DefEditDeleteAddPanel(defListener, editListener, deleteListener, addListener, "FFE_DEF",
            "FFE_EDT", "FFE_DEL", "FFE_ADD");
    dedaPanel.getAddBtn().setEnabled(true);

    PanelBuilder pb = new PanelBuilder(new FormLayout("f:max(250px;p):g", "p,4px,p,2px,f:p:g,4px,p"));

    y = 1;
    pb.add(tblInfoPB.getPanel(), cc.xy(1, y));
    y += 2;
    pb.add(createI18NLabel("FFE_AVAILABLE_FORMATS", SwingConstants.LEFT), cc.xy(1, y));
    y += 2;
    pb.add(createScrollPane(formatList), cc.xy(1, y));
    y += 2;
    pb.add(dedaPanel, cc.xy(1, y));
    y += 2;

    pb.setDefaultDialogBorder();

    //pb.getPanel().setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    contentPanel = pb.getPanel();
    mainPanel.add(contentPanel, BorderLayout.CENTER);

    okBtn.setEnabled(false);

    pack();

}

From source file:edu.ku.brc.specify.utilapps.ERDTable.java

/**
 * @param p/*from   w w w  . j  a  v  a  2 s .co  m*/
 * @param tbl
 * @param font
 * @param y
 * @param all
 */
public void build(final PanelBuilder p, final DBTableInfo tbl, final Font font, final int y, boolean all) {
    String typ = StringUtils.substringAfterLast(tbl.getIdType(), ".");
    if (StringUtils.isEmpty(typ)) {
        typ = tbl.getIdType();
    }
    CellConstraints cc = new CellConstraints();
    p.add(ERDVisualizer.mkLabel(font, tbl.getIdColumnName(), SwingConstants.LEFT), cc.xy(1, y));
    p.add(ERDVisualizer.mkLabel(font, typ, SwingConstants.CENTER), cc.xy(3, y));
    p.add(ERDVisualizer.mkLabel(font, "", SwingConstants.CENTER), cc.xy(5, y));
    if (all) {
        p.add(ERDVisualizer.mkLabel(font, yesStr, SwingConstants.CENTER), cc.xy(7, y));
        p.add(ERDVisualizer.mkLabel(font, yesStr, SwingConstants.CENTER), cc.xy(9, y));
    }

}

From source file:com.enitalk.opentok.CheckAvailabilityRunnable.java

@Override
@RabbitListener(queues = "youtube_check")
public void onMessage(Message msg) {
    try {/*ww w  .  j a v  a2 s  . c o  m*/
        JsonNode event = jackson.readTree(msg.getBody());
        String ii = event.path("ii").asText();
        logger.info("Check youtube came {}", ii);

        List<String> videos = jackson.convertValue(event.path("yt"), List.class);
        List<String> parts = new ArrayList<>();
        videos.stream().forEach((String link) -> {
            parts.add(StringUtils.substringAfterLast(link, "/"));
        });

        Credential credential = flow.loadCredential("yt");
        YouTube youtube = new YouTube.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
                credential).setApplicationName("enitalk").build();
        boolean refreshed = credential.refreshToken();
        logger.info("Yt refreshed {}", refreshed);

        HttpResponse rs = youtube.videos().list("processingDetails").setId(StringUtils.join(parts, ','))
                .executeUnparsed();
        InputStream is = rs.getContent();
        byte[] b = IOUtils.toByteArray(is);
        IOUtils.closeQuietly(is);

        JsonNode listTree = jackson.readTree(b);
        logger.info("List tree {}", listTree);

        List<JsonNode> items = listTree.path("items").findParents("id");
        long finished = items.stream().filter((JsonNode j) -> {
            return j.at("/processingDetails/processingStatus").asText().equals("succeeded");
        }).count();

        Query q = Query.query(Criteria.where("ii").is(ii));
        if (finished == parts.size()) {
            logger.info("Processing finished {}", ii);

            //send notification and email
            ObjectNode tree = (ObjectNode) jackson
                    .readTree(new ClassPathResource("emails/videoUploaded.json").getInputStream());
            tree.put("To", event.at("/student/email").asText());
            //                String text = tree.path("HtmlBody").asText() + StringUtils.join(videos, "\n");

            StringWriter writer = new StringWriter(29 * 1024);
            Template t = engine.getTemplate("video.html");
            VelocityContext context = new VelocityContext();
            context.put("video", videos.iterator().next());
            t.merge(context, writer);

            tree.put("HtmlBody", writer.toString());

            //make chat and attach it
            String chatTxt = makeChat(event);
            if (StringUtils.isNotBlank(chatTxt)) {
                ArrayNode attachments = jackson.createArrayNode();
                ObjectNode a = attachments.addObject();
                a.put("Name", "chat.txt");
                a.put("ContentType", "text/plain");
                a.put("Content", chatTxt.getBytes("UTF-8"));

                tree.set("Attachments", attachments);
            } else {
                logger.info("No chat available for {}", event.path("ii").asText());
            }

            logger.info("Sending video and chat {} to student", ii);

            org.apache.http.HttpResponse response = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r = EntityUtils.toByteArray(response.getEntity());
            JsonNode emailResp = jackson.readTree(r);

            Update u = new Update().set("video", 4);
            if (StringUtils.isNotBlank(chatTxt)) {
                u.set("chat", chatTxt);
            }

            u.set("student.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("student.uploader.rs", jackson.convertValue(emailResp, HashMap.class));

            tree.put("To", event.at("/teacher/email").asText());
            logger.info("Sending video and chat {} to teacher", ii);

            org.apache.http.HttpResponse response2 = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r2 = EntityUtils.toByteArray(response2.getEntity());
            JsonNode emailResp2 = jackson.readTree(r2);

            u.set("teacher.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("teacher.uploader.rs", jackson.convertValue(emailResp2, HashMap.class));
            u.set("f", 1);

            mongo.updateFirst(q, u, "events");

            //                JsonNode dest = event.at("/student/dest");
            //
            //                ArrayNode msgs = jackson.createArrayNode();
            //                ObjectNode o = msgs.addObject();
            //                o.set("dest", dest);
            //                ObjectNode m = jackson.createObjectNode();
            //                o.set("message", m);
            //                m.put("text", "0x1f3a5 We have uploaded your lesson to Youtube. It is available to you and the teacher only. \n"
            //                        + "Please, do not share it with anyone\n Also, we sent the video link and the text chat to your email.");
            //
            //                ArrayNode buttons = jackson.createArrayNode();
            //                m.set("buttons", buttons);
            //                m.put("buttonsPerRow", 1);
            //
            //                if (videos.size() == 1) {
            //                    botController.makeButtonHref(buttons, "Watch on Youtube", videos.get(0));
            //                } else {
            //                    AtomicInteger cc = new AtomicInteger(1);
            //                    videos.stream().forEach((String y) -> {
            //                        botController.makeButtonHref(buttons, "Watch on Youtube, part " + cc.getAndIncrement(), y);
            //                    });
            //                }
            //
            //                botController.sendMessages(msgs);
            //
            //                sendFeedback(dest, event);

        } else {
            logger.info("{} parts only finished for {}", finished, ii);
            mongo.updateFirst(q,
                    new Update().inc("check", 1).set("checkDate", new DateTime().plusMinutes(12).toDate()),
                    "events");
        }

    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:info.magnolia.jcr.util.PropertiesImportExport.java

/**
 * Transforms the keys to the following inner notation: <code>/some/path/node.prop</code> or
 * <code>/some/path/node.@type</code>.
 *///w  ww.ja v a2s.  c om
private Properties keysToInnerFormat(Properties properties) {
    Properties cleaned = new OrderedProperties();

    for (Object o : properties.keySet()) {
        String orgKey = (String) o;
        // explicitly enforce certain syntax
        if (!orgKey.startsWith("/")) {
            throw new IllegalArgumentException("Missing trailing '/' for key: " + orgKey);
        }
        if (StringUtils.countMatches(orgKey, ".") > 1) {
            throw new IllegalArgumentException("Key must not contain more than one '.': " + orgKey);
        }
        if (orgKey.contains("@") && !orgKey.contains(".@")) {
            throw new IllegalArgumentException("Key containing '@' must be preceded by a '.': " + orgKey);
        }
        // if this is a node definition (no property)
        String newKey = orgKey;

        String propertyName = StringUtils.substringAfterLast(newKey, ".");
        String keySuffix = StringUtils.substringBeforeLast(newKey, ".");
        String path = StringUtils.removeStart(keySuffix, "/");

        // if this is a path (no property)
        if (StringUtils.isEmpty(propertyName)) {
            // no value --> is a node
            if (StringUtils.isEmpty(properties.getProperty(orgKey))) {
                // make this the type property if not defined otherwise
                if (!properties.containsKey(orgKey + ".@type")) {
                    cleaned.put(path + ".@type", NodeTypes.ContentNode.NAME);
                }
                continue;
            }
            throw new IllegalArgumentException(
                    "Key for a path (everything without a '.' is considered to be a path) must not contain a value ('='): "
                            + orgKey);
        }
        cleaned.put(path + "." + propertyName, properties.get(orgKey));
    }
    return cleaned;
}

From source file:com.haulmont.yarg.reporting.Reporting.java

protected void generateReport(Report report, ReportTemplate reportTemplate, OutputStream outputStream,
        Map<String, Object> handledParams, BandData rootBand) {
    String extension = StringUtils.substringAfterLast(reportTemplate.getDocumentName(), ".");
    if (reportTemplate.isCustom()) {
        try {//from w  w w . j a v a  2  s .c  om
            byte[] bytes = reportTemplate.getCustomReport().createReport(report, rootBand, handledParams);
            IOUtils.write(bytes, outputStream);
        } catch (IOException e) {
            throw new ReportingException(format("An error occurred while processing custom template [%s].",
                    reportTemplate.getDocumentName()), e);
        }
    } else {
        FormatterFactoryInput factoryInput = new FormatterFactoryInput(extension, rootBand, reportTemplate,
                outputStream);
        ReportFormatter formatter = formatterFactory.createFormatter(factoryInput);
        formatter.renderDocument();
    }
}

From source file:info.magnolia.cms.module.ModuleUtil.java

public static void bootstrap(String[] resourceNames) throws IOException, RegisterException {

    HierarchyManager hm = MgnlContext.getHierarchyManager(ContentRepository.CONFIG);

    // sort by length --> import parent node first
    List list = new ArrayList(Arrays.asList(resourceNames));

    Collections.sort(list, new Comparator() {

        public int compare(Object name1, Object name2) {
            return ((String) name1).length() - ((String) name2).length();
        }/*from   w  w w . j ava 2 s . c  o m*/
    });

    for (Iterator iter = list.iterator(); iter.hasNext();) {
        String resourceName = (String) iter.next();

        // windows again
        resourceName = StringUtils.replace(resourceName, "\\", "/");

        String name = StringUtils.removeEnd(StringUtils.substringAfterLast(resourceName, "/"), ".xml");

        String repository = StringUtils.substringBefore(name, ".");
        String pathName = StringUtils.substringAfter(StringUtils.substringBeforeLast(name, "."), "."); //$NON-NLS-1$
        String nodeName = StringUtils.substringAfterLast(name, ".");
        String fullPath;
        if (StringUtils.isEmpty(pathName)) {
            pathName = "/";
            fullPath = "/" + nodeName;
        } else {
            pathName = "/" + StringUtils.replace(pathName, ".", "/");
            fullPath = pathName + "/" + nodeName;
        }

        // if the path already exists --> delete it
        try {
            if (hm.isExist(fullPath)) {
                hm.delete(fullPath);
                if (log.isDebugEnabled())
                    log.debug("already existing node [{}] deleted", fullPath);
            }

            // if the parent path not exists just create it
            if (!pathName.equals("/")) {
                ContentUtil.createPath(hm, pathName, ItemType.CONTENT);
            }
        } catch (Exception e) {
            throw new RegisterException("can't register bootstrap file: [" + name + "]", e);
        }
        InputStream stream = ModuleUtil.class.getResourceAsStream(resourceName);
        DataTransporter.executeImport(pathName, repository, stream, name, false,
                ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING, true, true);
    }
}

From source file:com.amalto.core.storage.record.XmlDOMDataRecordReader.java

private void _read(MetadataRepository repository, DataRecord dataRecord, ComplexTypeMetadata type,
        Element element) {//from www .java  2 s.  co m
    // TODO Don't use getChildNodes() but getNextSibling() calls (but cause regressions -> see TMDM-5410).
    String tagName = element.getTagName();
    NodeList children = element.getChildNodes();
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (!type.hasField(attribute.getNodeName())) {
            continue;
        }
        FieldMetadata field = type.getField(attribute.getNodeName());
        dataRecord.set(field, StorageMetadataUtils.convert(attribute.getNodeValue(), field));
    }
    for (int i = 0; i < children.getLength(); i++) {
        Node currentChild = children.item(i);
        if (currentChild instanceof Element) {
            Element child = (Element) currentChild;
            if (METADATA_NAMESPACE.equals(child.getNamespaceURI())) {
                DataRecordMetadataHelper.setMetadataValue(dataRecord.getRecordMetadata(), child.getLocalName(),
                        child.getTextContent());
            } else {
                if (!type.hasField(child.getTagName())) {
                    continue;
                }
                FieldMetadata field = type.getField(child.getTagName());
                if (field.getType() instanceof ContainedComplexTypeMetadata) {
                    ComplexTypeMetadata containedType = (ComplexTypeMetadata) field.getType();
                    String xsiType = child.getAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); //$NON-NLS-1$
                    if (xsiType.startsWith("java:")) { //$NON-NLS-1$
                        // Special format for 'java:' type names (used in Castor XML to indicate actual class name)
                        xsiType = ClassRepository.format(StringUtils
                                .substringAfterLast(StringUtils.substringAfter(xsiType, "java:"), ".")); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    if (!xsiType.isEmpty()) {
                        for (ComplexTypeMetadata subType : containedType.getSubTypes()) {
                            if (subType.getName().equals(xsiType)) {
                                containedType = subType;
                                break;
                            }
                        }
                    }
                    DataRecord containedRecord = new DataRecord(containedType,
                            UnsupportedDataRecordMetadata.INSTANCE);
                    dataRecord.set(field, containedRecord);
                    _read(repository, containedRecord, containedType, child);
                } else if (ClassRepository.EMBEDDED_XML.equals(field.getType().getName())) {
                    try {
                        dataRecord.set(field, Util.nodeToString(element));
                    } catch (TransformerException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    _read(repository, dataRecord, type, child);
                }
            }
        } else if (currentChild instanceof Text) {
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < element.getChildNodes().getLength(); j++) {
                String nodeValue = element.getChildNodes().item(j).getNodeValue();
                if (nodeValue != null) {
                    builder.append(nodeValue.trim());
                }
            }
            String textContent = builder.toString();
            if (!textContent.isEmpty()) {
                FieldMetadata field = type.getField(tagName);
                if (field instanceof ReferenceFieldMetadata) {
                    ComplexTypeMetadata actualType = ((ReferenceFieldMetadata) field).getReferencedType();
                    String mdmType = element.getAttributeNS(SkipAttributeDocumentBuilder.TALEND_NAMESPACE,
                            "type"); //$NON-NLS-1$
                    if (!mdmType.isEmpty()) {
                        actualType = repository.getComplexType(mdmType);
                    }
                    if (actualType == null) {
                        throw new IllegalArgumentException("Type '" + mdmType + "' does not exist.");
                    }
                    dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, actualType));
                } else {
                    dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, type));
                }
            }
        }
    }
}