Example usage for org.apache.commons.lang.text StrSubstitutor replace

List of usage examples for org.apache.commons.lang.text StrSubstitutor replace

Introduction

In this page you can find the example usage for org.apache.commons.lang.text StrSubstitutor replace.

Prototype

public static String replace(Object source, Map valueMap) 

Source Link

Document

Replaces all the occurrences of variables in the given source object with their matching values from the map.

Usage

From source file:org.xmlactions.pager.actions.mapping.JSONToPresentationAction.java

private String processMapping(IExecContext execContext)
        throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, NestedActionException, BadXMLException {

    JSONObject jsonObject = null;/*from w w w  . ja va2s. com*/
    String presentationForm = null;
    try {
        if (StringUtils.isNotEmpty(getJson_filename())) {
            String fileName = ResourceCommon.buildFileName(path, execContext.replace(getJson_filename()));
            String data = ResourceUtils.loadFile(fileName);
            jsonObject = new JSONObject(data);
        } else {
            String data = execContext.replace(getJson_data());
            try {
                jsonObject = new JSONObject(data);
            } catch (JSONException ex) {
                throw new IllegalArgumentException(
                        "Unable to get data  for " + getJson_filename() + " or " + getJson_data(), ex);
            }
        }
    } catch (IOException ex) {
        throw new IllegalArgumentException(
                "Unable to get data  for " + getJson_filename() + " or " + getJson_data(), ex);
    }

    if (getForm() != null) {
        presentationForm = XmlCData.removeCData(getForm().getContent());
    } else {
        try {
            String name = execContext.replace(getPresentation_form());
            String fileName = ResourceCommon.buildFileName(path, name);
            presentationForm = ResourceUtils.loadFile(fileName);
        } catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load " + getPresentation_form(), ex);
        }
    }
    StringBuilder sb = new StringBuilder();
    int rowCount = 0;
    for (rowCount = 0;; rowCount++) {
        try {
            Map<String, Object> map = JSONUtils.toMap(jsonObject, getJson_path(), rowCount);
            if (map != null) {
                execContext.addNamedMap(getRow_map_name(), map);
                String form = copyForm(presentationForm);
                String populatedForm = StrSubstitutor.replace(form, map);
                populatedForm = new Action().processPage(execContext, populatedForm);
                populatedForm = execContext.replace(populatedForm);
                populatedForm = new Html().removeOuterJsonOrXmlOrHtml(populatedForm);
                if (StringUtils.isNotBlank(populatedForm)) {
                    sb.append(populatedForm);
                }
            } else {
                // completed iteration through all path elements
                break;
            }
        } catch (Exception ex) {
            log.info(ex.getMessage());
            break;
        }
    }
    execContext.put(ActionConst.ROW_TOTAL_COUNT, rowCount);
    return sb.toString();
}

From source file:org.xmlactions.pager.actions.mapping.XmlToPresentationAction.java

private String getData(IExecContext execContext, XMLObject child, int rowCount, String presentationForm)
        throws IOException, NestedActionException, ClassNotFoundException, InstantiationException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, BadXMLException {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("row_index", rowCount + 1);
    if (StringUtils.isNotBlank(child.getContent())) {
        map.put(child.getElementName(), child.getContent());
    }/*w  w w  . jav a 2  s . co m*/
    for (XMLAttribute att : child.getAttributes()) {
        map.put(att.getKey(), att.getValue());
    }
    execContext.addNamedMap(getRow_map_name(), map);
    String form = copyForm(presentationForm);
    form = StrSubstitutor.replace(form, map);
    String populatedForm = new Action().processPage(execContext, form);
    populatedForm = execContext.replace(form);

    populatedForm = new Html().removeOuterJsonOrXmlOrHtml(populatedForm);

    return populatedForm;

}

From source file:org.xmlactions.pager.actions.Param.java

public Object getResolvedValue(IExecContext execContext) {
    Object obj;/*from w  w  w .  j a va  2  s  .c  o  m*/

    obj = execContext.get(getValue());
    if (obj == null) {
        obj = StrSubstitutor.replace(getValue(), execContext);
    }
    if (obj == null) {
        obj = getValue();
    }
    if (getType() != null && !TypeOption._String.type.equals(getType())) {
        // need to convert
        TypeOption typeOption = TypeOption._String.getTypeOption(getType());
        if (typeOption == null) {
            throw new IllegalArgumentException("Invalid type [" + getType()
                    + "] for param.   Refer to schema 'param_converter_types' for a list of options.");
        }
        // now double check that the obj class is not the same as the converter class
        if (obj.getClass() != typeOption.getClazz()) {
            // must convert
            obj = ConvertUtils.convert(obj, typeOption.getClazz());
        }
    }
    return obj;
}

From source file:org.xmlactions.web.conceal.HttpPager.java

public void processPage(ServletRequest request, ServletResponse response, String page)
        throws ServletException, IOException {
    IExecContext execContext = null;/*from w w w . java2s .  c  o m*/
    if (response instanceof HttpServletResponse && request instanceof HttpServletRequest) {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            execContext = setupExecContext(httpServletRequest, httpServletResponse);

            String pageName = httpServletRequest.getServletPath();

            if (pageName.indexOf("axelconfig") > 0) {
                PrintWriter out = response.getWriter();
                out.print(buildInfo(httpServletRequest, httpServletResponse));
                out.close();
                return;
            }

            if (!pageName.endsWith(".ajax")) {

                String alternatePage = processPrePages(execContext, httpServletRequest, httpServletResponse);
                if ("stop".equals(execContext.getString("pre.page.stop"))) {
                    execContext.put("pre.page.stop", "");
                    response.setContentType("text/html;charset=UTF-8");

                    PrintWriter out = response.getWriter();
                    out.print(alternatePage);
                    out.close();
                }
            }

            log.debug("contextPath:" + httpServletRequest.getContextPath());
            log.debug("URI:" + httpServletRequest.getRequestURI());
            log.debug("root:" + realPath + " page:" + pageName + " wrapperPage:" + wrapperPage);
            log.debug(HttpSessionInfo.sysInfo(httpServletRequest));
            Action action;
            if (pageName.endsWith(".ajax")) {
                page = processAjaxCall(httpServletRequest, httpServletResponse,
                        pageName.substring(1, pageName.length() - ".ajax".length()), execContext);
                page = StrSubstitutor.replace(page, execContext);
            } else if (pageName.endsWith(".bin") || pageName.endsWith(".pdfbin")) {
                String pn = null;
                if (pageName.endsWith(".pdfbin")) {
                    pn = pageName.substring(1, pageName.length() - ".pdfbin".length());
                } else {
                    pn = pageName.substring(1, pageName.length() - ".bin".length());
                }
                page = processAjaxCall(httpServletRequest, httpServletResponse, pn, execContext);

                if (page.startsWith("EX:")) {
                    PrintWriter out = response.getWriter();
                    out.print(page);
                    out.close();
                } else {
                    byte[] image = (byte[]) execContext.get("image");
                    if (pageName.endsWith(".pdfbin")) {
                        String outputPdfFileName = execContext.getString("outputFileName");
                        String ex = serviceJasperPdfRequest(httpServletResponse, image, outputPdfFileName);
                        if (ex != null) {
                            PrintWriter out = response.getWriter();
                            out.print(page);
                            out.close();
                        }
                        return;
                    } else {

                        String responseType = execContext.getString("response_type");
                        if (StringUtils.isEmpty(responseType)) {
                            responseType = "image/png";
                        }
                        response.setContentType(responseType);

                        processPostPages(execContext, httpServletRequest, httpServletResponse);

                        InputStream in = new ByteArrayInputStream(image);
                        OutputStream out = response.getOutputStream();

                        // Copy the contents of the file to the output
                        // stream
                        byte[] buf = new byte[1024];
                        int count = 0;
                        while ((count = in.read(buf)) >= 0) {
                            out.write(buf, 0, count);
                        }
                        in.close();
                        out.close();
                    }
                    return;
                }
            } else {
                if (pageName.startsWith("/:")) {
                    String wrapperPageName = null;
                    int secondColon = pageName.indexOf(':', 2);
                    if (secondColon >= 0) {
                        wrapperPageName = pageName.substring(2, secondColon);
                        execContext.put("inner_page", "/" + pageName.substring(secondColon + 1));
                    } else {
                        if (StringUtils.isEmpty(wrapperPage)) {
                            throw new ServletException("No wrapper page set, why use :");
                        }
                        wrapperPageName = wrapperPage;
                        execContext.put("inner_page", "/" + pageName.substring(2));
                    }
                    // insert the requested page into the wrapper page
                    action = new Action(realPath, wrapperPageName, nameSpace);
                } else {
                    if (StringUtils.isNotEmpty(wrapperPage)) {
                        // we have a base wrapper page defined
                        execContext.put("inner_page", "/" + pageName);
                        action = new Action(realPath, wrapperPage, nameSpace);
                    } else {
                        if (pageName.indexOf("show_axel_config") >= 0) {
                            page = AxelConfig.getAxelConfig(execContext);
                            log.info(page);
                            page = "Config Copied to Log";
                            action = null;
                        } else {
                            // if we don't have a wrapper page we show the requested page
                            action = new Action(realPath, pageName, nameSpace);
                        }
                    }
                }
                if (action != null) {
                    if (StringUtils.isNotEmpty(page)) {
                        page = action.processPage(execContext, page);
                    } else {
                        page = action.processPage(execContext);
                    }
                }
            }

            log.debug("URI:" + httpServletRequest.getRequestURI());
            // log.debug("page:" + page);
            Object object = execContext.get(ActionConst.NO_STR_SUBST);
            // log.debug(ActionConst.NO_STR_SUBST + ":[" + object + "]");
            execContext.put(ActionConst.NO_STR_SUBST, null);

            if (pageName.toLowerCase().endsWith("soap")) {
                response.setContentType(IExecContext.CONTENT_TYPE_XML);

            } else if (pageName.toLowerCase().endsWith("json")) {
                response.setContentType(IExecContext.CONTENT_TYPE_JSON);

            } else {
                response.setContentType(IExecContext.CONTENT_TYPE_HTML);
            }

            processPostPages(execContext, httpServletRequest, httpServletResponse);

            // = = =
            // check if there is a contentType value stored in the execContext.  This could have been set by one of the actions such as an action that wants to return a JSON data.
            // = = =
            String contentType = execContext.getString(IExecContext.CONTENT_TYPE_KEY);
            if (StringUtils.isNotBlank(contentType)) {
                response.setContentType(contentType);
                //               if (contentType.equals(IExecContext.CONTENT_TYPE_JSON) || contentType.equals(IExecContext.CONTENT_TYPE_XML)) {
                //                  if (response instanceof HttpServletResponse) {
                //                     ((HttpServletResponse)response).setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
                //                     ((HttpServletResponse)response).setHeader("Pragma", "no-cache"); // HTTP 1.0
                //                     ((HttpServletResponse)response).setDateHeader("Expires", 0); // Proxies.
                //                  }
                //               }
            }
            execContext.remove("content_type");
            PrintWriter out = response.getWriter();
            out.print(page);
            out.close();

        } catch (Throwable t) {
            // TODO review this, use a better way for reporting the error.
            log.info(t.getMessage(), t);
            throw new ServletException(t);
        } finally {
            if (execContext != null) {
                execContext.saveToPersistence();
                RequestExecContext.remove();
            }
        }
    } else {
        String msg = "Not processing page. Must be HttpServletRequest not [" + request.getClass().getName()
                + "] and HttpServletResponse not [" + response.getClass().getName() + "]";

        log.info(msg);
        throw new ServletException(msg);
    }
}