Example usage for java.lang StringBuffer insert

List of usage examples for java.lang StringBuffer insert

Introduction

In this page you can find the example usage for java.lang StringBuffer insert.

Prototype

@Override
public StringBuffer insert(int offset, double d) 

Source Link

Usage

From source file:org.tdod.ether.taimpl.telnet.InputStreamGobbler.java

public void run() {
    try {/*from w ww  . j  a v a 2  s.  c o m*/
        // list of previous entered lines
        final List<String> lines = new ArrayList<String>();
        // position within lines
        int lineNumber = -1;
        // line buffer
        final StringBuffer inputBuffer = new StringBuffer();
        // position within line buffer
        int cursor = 0;
        do {
            int c = _shellIo.read();
            if (_log.isDebugEnabled()) {
                _log.debug("STDIN> " + c + " " + (char) c);
            }
            switch (c) {
            case BasicTerminalIO.DELETE:
                /*_log.debug("STDIN> DELETE");
                if (cursor < inputBuffer.length()) {
                   inputBuffer.deleteCharAt(cursor);
                   _shellIo.write(_deleteChar);
                }
                break;*/
            case BasicTerminalIO.BACKSPACE:
                _log.debug("STDIN> BACKSPACE");
                if (cursor > 0) {
                    inputBuffer.deleteCharAt(cursor - 1);
                    cursor--;
                    _shellIo.write((char) TerminalIO.BS);
                    // shellIo.moveLeft(1);
                    _shellIo.write(_deleteChar);
                }
                break;
            case BasicTerminalIO.LEFT:
                _log.debug("STDIN> LEFT");
                if (cursor > 0) {
                    cursor--;
                    _shellIo.write((char) TerminalIO.BS);
                }
                break;
            case BasicTerminalIO.RIGHT:
                _log.debug("STDIN> RIGHT");
                if (cursor < inputBuffer.length()) {
                    _shellIo.moveRight(1);
                    // m_IO.write(inputBuffer.charAt(cursor));
                    cursor++;
                }
                break;
            case BasicTerminalIO.UP:
                _log.debug("STDIN> UP");
                if (lines.size() > 0 && lineNumber >= 0) {
                    if (inputBuffer.length() > cursor) {
                        // for (int i = cursor; i < inputBuffer.length(); i++) {
                        // shellIo.write(deleteChar);
                        // }
                        _shellIo.write(deleteChars(inputBuffer.length() - cursor));
                    }
                    for (int i = 0; i < cursor; i++) {
                        _shellIo.write((char) TerminalIO.BS);
                        _shellIo.write(_deleteChar);
                    }
                    final String line = (String) lines.get(lineNumber);
                    if (lineNumber > 0) {
                        lineNumber--;
                    }
                    _shellIo.write(line);
                    inputBuffer.setLength(0);
                    inputBuffer.append(line);
                    cursor = line.length();
                }
                break;
            case BasicTerminalIO.DOWN:
                _log.debug("STDIN> DOWN");
                if (lineNumber >= 0 && lineNumber < lines.size()) {
                    if (inputBuffer.length() > cursor) {
                        _shellIo.write(deleteChars(inputBuffer.length() - cursor));
                    }
                    for (int i = 0; i < cursor; i++) {
                        _shellIo.write((char) TerminalIO.BS);
                        _shellIo.write(_deleteChar);
                    }
                    final String line = (String) lines.get(lineNumber);
                    if (lineNumber + 1 < lines.size()) {
                        lineNumber++;
                    }
                    _shellIo.write(line);
                    inputBuffer.setLength(0);
                    inputBuffer.append(line);
                    cursor = line.length();
                }
                break;
            case BasicTerminalIO.ENTER:
                _log.debug("STDIN> ENTER");
                _shellIo.write(BasicTerminalIO.CRLF);
                cursor = 0;
                lines.add(inputBuffer.toString());
                PlayerInputManager.postPlayerInputEvent(PlayerInputEventId.General, _connection.getId(),
                        inputBuffer.toString());
                lineNumber = lines.size() - 1;
                inputBuffer.setLength(0);
                break;
            default:
                if (c < 256) {
                    _log.debug("STDIN> no special char");
                    if (!_hideInput) {
                        _shellIo.write(_insertChar);
                        _shellIo.write((char) c);
                    }
                    inputBuffer.insert(cursor, (char) c);
                    cursor++;
                } else {
                    _log.debug("STDIN> unknown char");
                }
            }
        } while (_connection.isActive());
    } catch (SocketException e) {
        _log.warn("SocketException -- connection closed");
        PlayerConnectedManager.postPlayerConnectedEvent(PlayerConnectedEventId.Disconnected, _taShell);
    } catch (IOException e) {
        _log.warn("IOException -- connection closed");
        PlayerConnectedManager.postPlayerConnectedEvent(PlayerConnectedEventId.Disconnected, _taShell);
    }
}

From source file:org.auraframework.test.util.WebDriverTestCase.java

/**
 * Gather up useful info to add to a test failure. try to get
 * <ul>//  ww  w .  j  ava  2 s . c  om
 * <li>any client js errors</li>
 * <li>last known js test function</li>
 * <li>running/waiting</li>
 * <li>a screenshot</li>
 * </ul>
 * 
 * @param originalErr the test failure
 * @throws Throwable a new AssertionFailedError or UnexpectedError with the original and additional info
 */
private Throwable addAuraInfoToTestFailure(Throwable originalErr) {
    StringBuffer description = new StringBuffer();
    if (originalErr != null) {
        String msg = originalErr.getMessage();
        if (msg != null) {
            description.append(msg);
        }
    }

    description.append(String.format("\nBrowser: %s", currentBrowserType));
    if (auraUITestingUtil != null) {
        description.append("\nUser-Agent: " + auraUITestingUtil.getUserAgent());
    }
    if (currentDriver == null) {
        description.append("\nTest failed before WebDriver was initialized");
    } else {

        if (this instanceof PerfExecutorTest) {
            JSONArray json = this.getLastCollectedMetrics();
            description.append("\nPerfMetrics: " + json + ';');
        }

        description.append("\nWebDriver: " + currentDriver);
        description.append("\nJS state: ");
        try {
            String dump = (String) auraUITestingUtil
                    .getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';");
            if (dump.isEmpty()) {
                description.append("no errors detected");
            } else {
                description.append(dump);
            }
        } catch (Throwable t) {
            description.append(t.getMessage());
        }

        String screenshotsDirectory = System.getProperty("screenshots.directory");
        if (screenshotsDirectory != null) {
            String img = getBase64EncodedScreenshot(originalErr, true);
            if (img == null) {
                description.append("\nScreenshot: {not available}");
            } else {
                String fileName = getClass().getName() + "." + getName() + "_" + currentBrowserType + ".png";
                File path = new File(screenshotsDirectory + "/" + fileName);
                try {
                    path.getParentFile().mkdirs();
                    byte[] bytes = Base64.decodeBase64(img.getBytes());
                    FileOutputStream fos = new FileOutputStream(path);
                    fos.write(bytes);
                    fos.close();
                    String baseUrl = System.getProperty("screenshots.baseurl");
                    description.append(String.format("%nScreenshot: %s/%s", baseUrl, fileName));
                } catch (Throwable t) {
                    description.append(String.format("%nScreenshot: {save error: %s}", t.getMessage()));
                }
            }
        }

        try {
            description.append("\nApplication cache status: ");
            description.append(auraUITestingUtil.getRawEval(
                    "var cache=window.applicationCache;return (cache===undefined || cache===null)?'undefined':cache.status;")
                    .toString());
        } catch (Exception ex) {
            description.append("error calculating status: " + ex);
        }
        description.append("\n");
        if (SauceUtil.areTestsRunningOnSauce()) {
            String linkToJob = SauceUtil.getLinkToPublicJobInSauce(currentDriver);
            description.append("\nSauceLabs-recording: ");
            description.append((linkToJob != null) ? linkToJob : "{not available}");
        }
    }

    // replace original exception with new exception with additional info
    Throwable newFailure;
    if (originalErr instanceof AssertionFailedError) {
        newFailure = new AssertionFailedError(description.toString());
    } else {
        description.insert(0, originalErr.getClass() + ": ");
        newFailure = new UnexpectedError(description.toString(), originalErr.getCause());
    }
    newFailure.setStackTrace(originalErr.getStackTrace());
    return newFailure;
}

From source file:org.infoglue.deliver.invokers.DecoratedComponentBasedHTMLPageInvoker.java

private String decorateComponent(InfoGlueComponent component, TemplateController templateController,
        Integer repositoryId, Integer siteNodeId, Integer languageId,
        Integer contentId/*, Integer metainfoContentId*/, int maxDepth, int currentDepth) throws Exception {
    if (currentDepth > maxDepth) {
        logger.error("A page with to many levels (possibly infinite loop) was found on "
                + templateController.getOriginalFullURL());
        return "";
    }//from w  w  w . jav  a2 s .co m

    String decoratedComponent = "";

    //logger.info("decorateComponent.contentId:" + contentId);

    //logger.info("decorateComponent:" + component.getName());

    String componentEditorUrl = CmsPropertyHandler.getComponentEditorUrl();

    Timer timer = new Timer();
    timer.setActive(false);

    try {
        String componentString = getComponentString(templateController, component.getContentId(), component);
        //System.out.println("componentString:" + componentString);

        if (component.getParentComponent() == null && templateController.getDeliveryContext().getShowSimple()) {
            templateController.getDeliveryContext().setContentType("text/html");
            templateController.getDeliveryContext().setDisablePageCache(true);
            componentString = "<html><head></head><body onload=\"toggleDiv('pageComponents');\" style=\"padding:4px;\">"
                    + componentString
                    + " <br/><a href='#' style=\"font-family: verdana, sans-serif; font-size:10px;\" onclick='if(parent && parent.closeInlineDiv) parent.closeInlineDiv(); else if(parent && parent.closeDialog) parent.closeDialog(); else window.close();'>Close</a></body></html>";
        }

        templateController.setComponentLogic(new DecoratedComponentLogic(templateController, component));
        Map context = super.getDefaultContext();
        context.put("templateLogic", templateController);
        context.put("model", component.getModel());
        StringWriter cacheString = new StringWriter();
        PrintWriter cachedStream = new PrintWriter(cacheString);
        new VelocityTemplateProcessor().renderTemplate(context, cachedStream, componentString, false,
                component);
        componentString = cacheString.toString();

        int bodyIndex = componentString.indexOf("<body");
        if (bodyIndex == -1)
            bodyIndex = componentString.indexOf("<BODY");

        if (component.getParentComponent() == null && bodyIndex > -1) {
            String onContextMenu = " id=\"base0_0Comp\" onload=\"javascript:setToolbarInitialPosition();\"";
            if (templateController.getDeliveryContext().getShowSimple())
                onContextMenu = " id=\"base0_0Comp\" onload=\"javascript:setToolbarInitialPosition();\"";

            StringBuffer sb = new StringBuffer(componentString);
            sb.insert(bodyIndex + 5, onContextMenu);
            componentString = sb.toString();

            Document componentPropertiesDocument = getComponentPropertiesDOM4JDocument(templateController,
                    siteNodeId, languageId, component.getContentId());
            this.propertiesDivs += getComponentPropertiesDiv(templateController, repositoryId, siteNodeId,
                    languageId, contentId, component.getId(), component.getContentId(),
                    componentPropertiesDocument, component);

            Document componentTasksDocument = getComponentTasksDOM4JDocument(templateController, siteNodeId,
                    languageId, component.getContentId());
            this.tasksDivs += getComponentTasksDiv(repositoryId, siteNodeId, languageId, contentId, component,
                    0, 1, componentTasksDocument, templateController);
        }

        int offset = 0;
        int slotStartIndex = componentString.indexOf("<ig:slot", offset);
        //logger.info("slotStartIndex:" + slotStartIndex);
        while (slotStartIndex > -1) {
            decoratedComponent += componentString.substring(offset, slotStartIndex);
            int slotStopIndex = componentString.indexOf("</ig:slot>", slotStartIndex);

            String slot = componentString.substring(slotStartIndex, slotStopIndex + 10);
            String id = slot.substring(slot.indexOf("id") + 4, slot.indexOf("\"", slot.indexOf("id") + 4));

            Slot slotBean = new Slot();
            slotBean.setId(id);

            int displayNameIndex = slot.indexOf(" displayName");
            if (displayNameIndex > -1) {
                String displayName = slot.substring(displayNameIndex + 14,
                        slot.indexOf("\"", displayNameIndex + 14));
                slotBean.setDisplayName(displayName);
            }

            String[] allowedComponentNamesArray = null;
            int allowedComponentNamesIndex = slot.indexOf(" allowedComponentNames");
            if (allowedComponentNamesIndex > -1) {
                String allowedComponentNames = slot.substring(allowedComponentNamesIndex + 24,
                        slot.indexOf("\"", allowedComponentNamesIndex + 24));
                allowedComponentNamesArray = allowedComponentNames.split(",");
                //logger.info("allowedComponentNamesArray:" + allowedComponentNamesArray.length);
                slotBean.setAllowedComponentsArray(allowedComponentNamesArray);
            }

            String[] disallowedComponentNamesArray = null;
            int disallowedComponentNamesIndex = slot.indexOf(" disallowedComponentNames");
            if (disallowedComponentNamesIndex > -1) {
                String disallowedComponentNames = slot.substring(disallowedComponentNamesIndex + 27,
                        slot.indexOf("\"", disallowedComponentNamesIndex + 27));
                disallowedComponentNamesArray = disallowedComponentNames.split(",");
                //logger.info("disallowedComponentNamesArray:" + disallowedComponentNamesArray.length);
                slotBean.setDisallowedComponentsArray(disallowedComponentNamesArray);
            }

            String[] allowedComponentGroupNamesArray = null;
            int allowedComponentGroupNamesIndex = slot.indexOf(" allowedComponentGroupNames");
            if (allowedComponentGroupNamesIndex > -1) {
                String allowedComponentGroupNames = slot.substring(allowedComponentGroupNamesIndex + 29,
                        slot.indexOf("\"", allowedComponentGroupNamesIndex + 29));
                allowedComponentGroupNamesArray = allowedComponentGroupNames.split(",");
                slotBean.setAllowedComponentGroupsArray(allowedComponentGroupNamesArray);
            }

            boolean inherit = true;
            int inheritIndex = slot.indexOf("inherit");
            if (inheritIndex > -1) {
                String inheritString = slot.substring(inheritIndex + 9, slot.indexOf("\"", inheritIndex + 9));
                inherit = Boolean.parseBoolean(inheritString);
            }
            slotBean.setInherit(inherit);

            boolean disableAccessControl = false;
            int disableAccessControlIndex = slot.indexOf("disableAccessControl");
            if (disableAccessControlIndex > -1) {
                String disableAccessControlString = slot.substring(
                        disableAccessControlIndex + "disableAccessControl".length() + 2,
                        slot.indexOf("\"", disableAccessControlIndex + "disableAccessControl".length() + 2));
                disableAccessControl = Boolean.parseBoolean(disableAccessControlString);
            }

            String addComponentText = null;
            int addComponentTextIndex = slot.indexOf("addComponentText");
            if (addComponentTextIndex > -1) {
                addComponentText = slot.substring(addComponentTextIndex + "addComponentText".length() + 2,
                        slot.indexOf("\"", addComponentTextIndex + "addComponentText".length() + 2));
            }

            String addComponentLinkHTML = null;
            int addComponentLinkHTMLIndex = slot.indexOf("addComponentLinkHTML");
            if (addComponentLinkHTMLIndex > -1) {
                addComponentLinkHTML = slot.substring(
                        addComponentLinkHTMLIndex + "addComponentLinkHTML".length() + 2,
                        slot.indexOf("\"", addComponentLinkHTMLIndex + "addComponentLinkHTML".length() + 2));
            }

            int allowedNumberOfComponentsInt = -1;
            int allowedNumberOfComponentsIndex = slot.indexOf("allowedNumberOfComponents");
            if (allowedNumberOfComponentsIndex > -1) {
                String allowedNumberOfComponents = slot.substring(
                        allowedNumberOfComponentsIndex + "allowedNumberOfComponents".length() + 2,
                        slot.indexOf("\"",
                                allowedNumberOfComponentsIndex + "allowedNumberOfComponents".length() + 2));
                try {
                    allowedNumberOfComponentsInt = new Integer(allowedNumberOfComponents);
                } catch (Exception e) {
                    allowedNumberOfComponentsInt = -1;
                }
            }

            int disableSlotDecorationIndex = slot.indexOf("disableSlotDecoration");
            Boolean disableSlotDecoration = false;
            if (disableSlotDecorationIndex > -1) {
                String disableSlotDecorationString = slot.substring(
                        disableSlotDecorationIndex + "disableSlotDecoration".length() + 2,
                        slot.indexOf("\"", disableSlotDecorationIndex + "disableSlotDecoration".length() + 2));
                if (disableSlotDecorationString.equalsIgnoreCase("true"))
                    disableSlotDecoration = true;
            }

            slotBean.setDisableAccessControl(disableAccessControl);
            slotBean.setAddComponentLinkHTML(addComponentLinkHTML);
            slotBean.setAddComponentText(addComponentText);
            slotBean.setAllowedNumberOfComponents(new Integer(allowedNumberOfComponentsInt));
            component.setContainerSlot(slotBean);

            String subComponentString = "";

            //TODO - test
            if (component.getIsInherited() && !disableSlotDecoration) {
                subComponentString += "<div id=\"Comp" + component.getId() + "_"
                        + id.replaceAll("[^0-9,a-z,A-Z]", "_") + "\" class=\"inheritedComponentDiv\");\">";
            } else if (!disableSlotDecoration) {
                subComponentString += "<div id=\"Comp" + component.getId() + "_"
                        + id.replaceAll("[^0-9,a-z,A-Z]", "_") + "\" class=\"componentDiv "
                        + slotBean.getLimitationClasses() + "\" onmouseup=\"javascript:assignComponent('"
                        + siteNodeId + "', '" + languageId + "', '" + contentId + "', '" + component.getId()
                        + "', '" + id + "', '" + false + "', '"
                        + slotBean.getAllowedComponentsArrayAsUrlEncodedString() + "', '"
                        + slotBean.getDisallowedComponentsArrayAsUrlEncodedString() + "', '"
                        + slotBean.getAllowedComponentGroupsArrayAsUrlEncodedString() + "', '');\">";
            }

            List subComponents = getInheritedComponents(getDatabase(), templateController, component,
                    templateController.getSiteNodeId(), id, inherit);

            InfoGluePrincipal principal = templateController.getPrincipal();
            String cmsUserName = (String) templateController.getHttpServletRequest().getSession()
                    .getAttribute("cmsUserName");
            if (cmsUserName != null) {
                InfoGluePrincipal newPrincipal = templateController.getPrincipal(cmsUserName);
                if (newPrincipal != null)
                    principal = newPrincipal;
            }

            String clickToAddHTML = "";
            boolean hasAccessToAddComponent = AccessRightController.getController().getIsPrincipalAuthorized(
                    templateController.getDatabase(), principal, "ComponentEditor.AddComponent",
                    "" + component.getContentId() + "_" + id);
            if (slotBean.getDisableAccessControl())
                hasAccessToAddComponent = true;

            boolean hasMaxComponents = false;
            if (component.getSlotList() != null) {
                Iterator slotListIterator = component.getSlotList().iterator();
                while (slotListIterator.hasNext()) {
                    Slot parentSlot = (Slot) slotListIterator.next();
                    if (parentSlot.getId().equalsIgnoreCase(id)) {
                        if (parentSlot.getAllowedNumberOfComponents() != -1 && parentSlot.getComponents()
                                .size() >= parentSlot.getAllowedNumberOfComponents())
                            hasMaxComponents = true;
                    }
                }
            }

            if (hasAccessToAddComponent && !hasMaxComponents) {
                if (slotBean.getAddComponentText() != null) {
                    clickToAddHTML = slotBean.getAddComponentText();
                } else {
                    Locale locale = templateController.getLocaleAvailableInTool(principal);
                    clickToAddHTML = getLocalizedString(locale, "deliver.editOnSight.slotInstructionHTML",
                            slotBean.getId(), slotBean.getDisplayName());
                }
            }

            //logger.info("subComponents for " + id + ":" + subComponents);
            if (subComponents != null && subComponents.size() > 0) {
                //logger.info("SUBCOMPONENTS:" + subComponents.size());
                int index = 0;
                List<Integer> handledComponents = new ArrayList<Integer>();

                Iterator subComponentsIterator = subComponents.iterator();
                while (subComponentsIterator.hasNext()) {
                    InfoGlueComponent subComponent = (InfoGlueComponent) subComponentsIterator.next();

                    if (subComponent != null) {
                        if (handledComponents.contains(subComponent.getId()))
                            continue;

                        handledComponents.add(subComponent.getId());

                        component.getComponents().put(subComponent.getSlotName(), subComponent);
                        if (subComponent.getIsInherited()) {
                            //logger.info("Inherited..." + contentId);
                            String childComponentsString = decorateComponent(subComponent, templateController,
                                    repositoryId, siteNodeId, languageId, contentId/*, metainfoContentId*/,
                                    maxDepth, currentDepth + 1);
                            if (!this.getTemplateController().getDeliveryContext().getShowSimple()
                                    && !disableSlotDecoration)
                                subComponentString += "<div style=\"display:inline;\" id=\"" + id + index
                                        + "Comp\" class=\"inheritedslot\">" + childComponentsString + "</div>";
                            else
                                subComponentString += childComponentsString;

                            Document componentPropertiesDocument = getComponentPropertiesDOM4JDocument(
                                    templateController, siteNodeId, languageId, component.getContentId());
                            this.propertiesDivs += getComponentPropertiesDiv(templateController, repositoryId,
                                    siteNodeId, languageId, contentId,
                                    new Integer(siteNodeId.intValue() * 100 + subComponent.getId().intValue()),
                                    subComponent.getContentId(), componentPropertiesDocument, subComponent);

                            Document componentTasksDocument = getComponentTasksDOM4JDocument(templateController,
                                    siteNodeId, languageId, subComponent.getContentId());
                            this.tasksDivs += getComponentTasksDiv(repositoryId, siteNodeId, languageId,
                                    contentId, subComponent, index, subComponents.size() - 1,
                                    componentTasksDocument, templateController);

                        } else {
                            //logger.info("Not inherited..." + contentId);
                            String childComponentsString = decorateComponent(subComponent, templateController,
                                    repositoryId, siteNodeId, languageId, contentId/*, metainfoContentId*/,
                                    maxDepth, currentDepth + 1);
                            //logger.info("childComponentsString:" + childComponentsString);

                            if (!this.getTemplateController().getDeliveryContext().getShowSimple()
                                    && !disableSlotDecoration) {
                                String allowedComponentNamesAsEncodedString = null;
                                String disallowedComponentNamesAsEncodedString = null;
                                String allowedComponentGroupNamesAsEncodedString = null;

                                for (int i = 0; i < subComponent.getParentComponent().getSlotList()
                                        .size(); i++) {
                                    Slot subSlotBean = (Slot) subComponent.getParentComponent().getSlotList()
                                            .get(i);

                                    if (subSlotBean.getId() != null
                                            && subSlotBean.getId().equals(subComponent.getSlotName())) {
                                        allowedComponentNamesAsEncodedString = subSlotBean
                                                .getAllowedComponentsArrayAsUrlEncodedString();
                                        disallowedComponentNamesAsEncodedString = subSlotBean
                                                .getDisallowedComponentsArrayAsUrlEncodedString();
                                        allowedComponentGroupNamesAsEncodedString = subSlotBean
                                                .getAllowedComponentGroupsArrayAsUrlEncodedString();
                                        subComponent.setContainerSlot(subSlotBean);
                                    }
                                }
                                //<div id=\"dropZone"+ id + index + "_" + subComponent.getId() + "Comp\" class=\"moveDropZone\"></div>
                                String changeUrl = componentEditorUrl
                                        + "ViewSiteNodePageComponents!listComponentsForChange.action?siteNodeId="
                                        + siteNodeId + "&amp;languageId=" + languageId + "&amp;contentId="
                                        + (contentId == null ? "-1" : contentId) + "&amp;componentId="
                                        + subComponent.getId() + "&amp;slotId=" + id + "&amp;showSimple="
                                        + this.getTemplateController().getDeliveryContext().getShowSimple()
                                        + ((allowedComponentNamesAsEncodedString != null)
                                                ? "&amp;" + allowedComponentNamesAsEncodedString
                                                : "")
                                        + ((disallowedComponentNamesAsEncodedString != null)
                                                ? "&amp;" + disallowedComponentNamesAsEncodedString
                                                : "")
                                        + ((allowedComponentGroupNamesAsEncodedString != null)
                                                ? "&amp;" + allowedComponentGroupNamesAsEncodedString
                                                : "");
                                String extraClass = "clearFix";
                                if (childComponentsString.contains("noclearfix")) {
                                    extraClass = "clearFixNoBreak";
                                }
                                /* The poor souls that has illegal characters in their ig:slot names, we have to remove them in order for the html to br correct */
                                String escapedDivId = id.replaceAll("[^a-zA-Z0-9]+", "_");
                                subComponentString += "<div style=\"position: relative;\" style=\"display:inline;\" id=\""
                                        + escapedDivId + "_" + index + "_" + subComponent.getId()
                                        + "Comp\" data-componentelementid=\"" + subComponent.getId()
                                        + "\" class=\"moveZone sortableComponent " + extraClass + "\">"
                                        + childComponentsString
                                        + "<script type=\"text/javascript\">initializeComponentEventHandler('"
                                        + escapedDivId + "_" + index + "_" + subComponent.getId() + "Comp', '"
                                        + subComponent.getId() + "', '" + componentEditorUrl
                                        + "ViewSiteNodePageComponents!listComponents.action?siteNodeId="
                                        + siteNodeId + "&amp;languageId=" + languageId + "&amp;contentId="
                                        + (contentId == null ? "-1" : contentId) + "&amp;parentComponentId="
                                        + component.getId() + "&amp;slotId=" + id + "&amp;showSimple="
                                        + this.getTemplateController().getDeliveryContext().getShowSimple()
                                        + ((allowedComponentNamesAsEncodedString != null)
                                                ? "&amp;" + allowedComponentNamesAsEncodedString
                                                : "")
                                        + ((disallowedComponentNamesAsEncodedString != null)
                                                ? "&amp;" + disallowedComponentNamesAsEncodedString
                                                : "")
                                        + ((allowedComponentGroupNamesAsEncodedString != null)
                                                ? "&amp;" + allowedComponentGroupNamesAsEncodedString
                                                : "")
                                        + "', '" + componentEditorUrl
                                        + "ViewSiteNodePageComponents!deleteComponent.action?siteNodeId="
                                        + siteNodeId + "&amp;languageId=" + languageId + "&amp;contentId="
                                        + contentId + "&amp;componentId=" + subComponent.getId()
                                        + "&amp;slotId=" + id + "&amp;showSimple="
                                        + this.getTemplateController().getDeliveryContext().getShowSimple()
                                        + "','" + changeUrl + "');</script></div>";
                            } else {
                                subComponentString += childComponentsString;
                            }

                            Document componentPropertiesDocument = getComponentPropertiesDOM4JDocument(
                                    templateController, siteNodeId, languageId, subComponent.getContentId());
                            this.propertiesDivs += getComponentPropertiesDiv(templateController, repositoryId,
                                    siteNodeId, languageId, contentId, subComponent.getId(),
                                    subComponent.getContentId(), componentPropertiesDocument, subComponent);

                            Document componentTasksDocument = getComponentTasksDOM4JDocument(templateController,
                                    siteNodeId, languageId, subComponent.getContentId());
                            this.tasksDivs += getComponentTasksDiv(repositoryId, siteNodeId, languageId,
                                    contentId, subComponent, index, subComponents.size() - 1,
                                    componentTasksDocument, templateController);
                        }
                    }
                    index++;
                }

                if (component.getContainerSlot().getAddComponentLinkHTML() != null
                        && !component.getIsInherited()) {
                    String allowedComponentNamesAsEncodedString = null;
                    String disallowedComponentNamesAsEncodedString = null;
                    String allowedComponentGroupNamesAsEncodedString = null;

                    for (int i = 0; i < component.getSlotList().size(); i++) {
                        Slot subSlotBean = (Slot) component.getSlotList().get(i);
                        if (subSlotBean.getId() != null && subSlotBean.getId().equals(id)) {
                            allowedComponentNamesAsEncodedString = subSlotBean
                                    .getAllowedComponentsArrayAsUrlEncodedString();
                            disallowedComponentNamesAsEncodedString = subSlotBean
                                    .getDisallowedComponentsArrayAsUrlEncodedString();
                            allowedComponentGroupNamesAsEncodedString = subSlotBean
                                    .getAllowedComponentGroupsArrayAsUrlEncodedString();
                        }
                    }

                    String linkUrl = componentEditorUrl
                            + "ViewSiteNodePageComponents!listComponents.action?siteNodeId=" + siteNodeId
                            + "&languageId=" + languageId + "&contentId="
                            + (contentId == null ? "-1" : contentId) + "&parentComponentId=" + component.getId()
                            + "&slotId=" + id + "&showSimple="
                            + this.getTemplateController().getDeliveryContext().getShowSimple()
                            + ((allowedComponentNamesAsEncodedString != null)
                                    ? "&" + allowedComponentNamesAsEncodedString
                                    : "")
                            + ((disallowedComponentNamesAsEncodedString != null)
                                    ? "&" + disallowedComponentNamesAsEncodedString
                                    : "")
                            + ((allowedComponentGroupNamesAsEncodedString != null)
                                    ? "&" + allowedComponentGroupNamesAsEncodedString
                                    : "");
                    subComponentString += "" + component.getContainerSlot().getAddComponentLinkHTML()
                            .replaceAll("\\$linkUrl", linkUrl);
                } else {
                    subComponentString += "" + clickToAddHTML;
                }
            } else {
                if (component.getContainerSlot().getAddComponentLinkHTML() != null
                        && !component.getIsInherited()) {
                    String allowedComponentNamesAsEncodedString = null;
                    String disallowedComponentNamesAsEncodedString = null;
                    String allowedComponentGroupNamesAsEncodedString = null;

                    for (int i = 0; i < component.getSlotList().size(); i++) {
                        Slot subSlotBean = (Slot) component.getSlotList().get(i);
                        if (subSlotBean.getId() != null && subSlotBean.getId().equals(id)) {
                            allowedComponentNamesAsEncodedString = subSlotBean
                                    .getAllowedComponentsArrayAsUrlEncodedString();
                            disallowedComponentNamesAsEncodedString = subSlotBean
                                    .getDisallowedComponentsArrayAsUrlEncodedString();
                            allowedComponentGroupNamesAsEncodedString = subSlotBean
                                    .getAllowedComponentGroupsArrayAsUrlEncodedString();
                        }
                    }

                    String linkUrl = componentEditorUrl
                            + "ViewSiteNodePageComponents!listComponents.action?siteNodeId=" + siteNodeId
                            + "&languageId=" + languageId + "&contentId="
                            + (contentId == null ? "-1" : contentId) + "&parentComponentId=" + component.getId()
                            + "&slotId=" + id + "&showSimple="
                            + this.getTemplateController().getDeliveryContext().getShowSimple()
                            + ((allowedComponentNamesAsEncodedString != null)
                                    ? "&" + allowedComponentNamesAsEncodedString
                                    : "")
                            + ((disallowedComponentNamesAsEncodedString != null)
                                    ? "&" + disallowedComponentNamesAsEncodedString
                                    : "")
                            + ((allowedComponentGroupNamesAsEncodedString != null)
                                    ? "&" + allowedComponentGroupNamesAsEncodedString
                                    : "");
                    subComponentString += "" + component.getContainerSlot().getAddComponentLinkHTML()
                            .replaceAll("\\$linkUrl", linkUrl);
                } else {
                    subComponentString += "" + clickToAddHTML;
                }
            }

            if (!disableSlotDecoration) {
                if (!component.getIsInherited()) {
                    String allowedComponentNamesAsEncodedString = null;
                    String disallowedComponentNamesAsEncodedString = null;
                    String allowedComponentGroupNamesAsEncodedString = null;

                    for (int i = 0; i < component.getSlotList().size(); i++) {
                        Slot subSlotBean = (Slot) component.getSlotList().get(i);
                        if (subSlotBean.getId() != null && subSlotBean.getId().equals(id)) {
                            allowedComponentNamesAsEncodedString = subSlotBean
                                    .getAllowedComponentsArrayAsUrlEncodedString();
                            disallowedComponentNamesAsEncodedString = subSlotBean
                                    .getDisallowedComponentsArrayAsUrlEncodedString();
                            allowedComponentGroupNamesAsEncodedString = subSlotBean
                                    .getAllowedComponentGroupsArrayAsUrlEncodedString();
                        }
                    }

                    subComponentString += "<script type=\"text/javascript\">setTimeout(function() {initializeSlotEventHandler('Comp"
                            + component.getId() + "_" + id.replaceAll("[^0-9,a-z,A-Z]", "_") + "', '"
                            + componentEditorUrl
                            + "ViewSiteNodePageComponents!listComponents.action?siteNodeId=" + siteNodeId
                            + "&amp;languageId=" + languageId + "&amp;contentId="
                            + (contentId == null ? "-1" : contentId) + "&amp;parentComponentId="
                            + component.getId() + "&amp;slotId=" + id + "&amp;showSimple="
                            + this.getTemplateController().getDeliveryContext().getShowSimple()
                            + ((allowedComponentNamesAsEncodedString != null)
                                    ? "&amp;" + allowedComponentNamesAsEncodedString
                                    : "")
                            + ((disallowedComponentNamesAsEncodedString != null)
                                    ? "&amp;" + disallowedComponentNamesAsEncodedString
                                    : "")
                            + ((allowedComponentGroupNamesAsEncodedString != null)
                                    ? "&amp;" + allowedComponentGroupNamesAsEncodedString
                                    : "")
                            + "', '', '', '" + id + "', '" + component.getContentId()
                            + "'); }, 100);</script></div>";
                } else
                    subComponentString += "</div>";
            }

            /**
             * 
             */

            boolean hasAccessToAccessRights = AccessRightController.getController().getIsPrincipalAuthorized(
                    templateController.getDatabase(), principal, "ComponentEditor.ChangeSlotAccess", "");
            boolean hasAccessToDeleteComponent = AccessRightController.getController().getIsPrincipalAuthorized(
                    templateController.getDatabase(), principal, "ComponentEditor.DeleteComponent",
                    "" + component.getContentId() + "_" + id);
            boolean hasAccessToChangeComponent = AccessRightController.getController().getIsPrincipalAuthorized(
                    templateController.getDatabase(), principal, "ComponentEditor.ChangeComponent",
                    "" + component.getContentId() + "_" + id);
            if (slotBean.getDisableAccessControl()) {
                hasAccessToDeleteComponent = true;
            }

            StringBuffer sb = new StringBuffer();
            sb.append("<script type=\"text/javascript\">");
            sb.append("window.hasAccessToAddComponentClickableDiv" + component.getId()
                    + id.replaceAll("[^0-9,a-z,A-Z]", "_") + " = " + hasAccessToAddComponent + ";");
            sb.append("window.hasAccessToChangeComponentClickableDiv" + component.getId()
                    + id.replaceAll("[^0-9,a-z,A-Z]", "_") + " = " + hasAccessToChangeComponent + ";");
            sb.append("window.hasAccessToDeleteComponentClickableDiv" + component.getId()
                    + id.replaceAll("[^0-9,a-z,A-Z]", "_") + " = " + hasAccessToDeleteComponent + ";");

            sb.append("window.hasAccessToAddComponent" + component.getId() + "_"
                    + id.replaceAll("[^0-9,a-z,A-Z]", "_") + " = " + hasAccessToAddComponent + ";");
            sb.append("window.hasAccessToChangeComponent" + component.getId() + "_"
                    + id.replaceAll("[^0-9,a-z,A-Z]", "_") + " = " + hasAccessToChangeComponent + ";");
            sb.append("window.hasAccessToAccessRights = " + hasAccessToAccessRights + ";");

            sb.append("window.hasAccessToAddComponentComp" + component.getId() + "_"
                    + id.replaceAll("[^0-9,a-z,A-Z]", "_") + " = " + hasAccessToAddComponent + ";");
            sb.append("window.hasAccessToChangeComponentComp" + component.getId() + "_"
                    + id.replaceAll("[^0-9,a-z,A-Z]", "_") + " = " + hasAccessToChangeComponent + ";");
            sb.append("window.hasAccessToDeleteComponentComp" + component.getId()
                    + id.replaceAll("[^0-9,a-z,A-Z]", "_") + " = " + hasAccessToDeleteComponent + ";");
            sb.append("window.hasAccessToAccessRights = " + hasAccessToAccessRights + ";");

            sb.append("</script>");

            subComponentString += sb.toString();
            /**
             * 
             */

            decoratedComponent += subComponentString;

            offset = slotStopIndex + 10;
            slotStartIndex = componentString.indexOf("<ig:slot", offset);
        }

        //logger.info("offset:" + offset);
        decoratedComponent += componentString.substring(offset);
    } catch (Exception e) {
        e.printStackTrace();
        logger.warn(
                "An component with either an empty template or with no template in the sitelanguages was found:"
                        + e.getMessage(),
                e);
    }

    return decoratedComponent;
}

From source file:org.auraframework.integration.test.util.WebDriverTestCase.java

/**
 * Gather up useful info to add to a test failure. try to get
 * <ul>/*from   www.j a va  2s. c  o  m*/
 * <li>any client js errors</li>
 * <li>last known js test function</li>
 * <li>running/waiting</li>
 * <li>a screenshot</li>
 * </ul>
 *
 * @param originalErr the test failure
 * @throws Throwable a new AssertionFailedError or UnexpectedError with the original and additional info
 */
private Throwable addAuraInfoToTestFailure(Throwable originalErr) {
    StringBuffer description = new StringBuffer();
    if (originalErr != null) {
        String msg = originalErr.getMessage();
        if (msg != null) {
            description.append(msg);
        }
    }

    description.append(String.format("\nBrowser: %s", currentBrowserType));
    if (getAuraUITestingUtil() != null) {
        description.append("\nUser-Agent: " + getAuraUITestingUtil().getUserAgent());
    }
    if (currentDriver == null) {
        description.append("\nTest failed before WebDriver was initialized");
    } else {

        if (this instanceof PerfExecutorTestCase) {
            JSONArray json = this.getLastCollectedMetrics();
            description.append("\nPerfMetrics: " + json + ';');
        }

        description.append("\nWebDriver: " + currentDriver);
        description.append("\nJS state: ");
        try {
            String dump = (String) getAuraUITestingUtil()
                    .getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';");
            if (dump.isEmpty()) {
                description.append("no errors detected");
            } else {
                description.append(dump);
            }
        } catch (Throwable t) {
            description.append(t.getMessage());
        }

        String screenshotsDirectory = System.getProperty("screenshots.directory");
        if (screenshotsDirectory != null) {
            String screenshot = null;
            TakesScreenshot ts = (TakesScreenshot) currentDriver;
            try {
                screenshot = ts.getScreenshotAs(OutputType.BASE64);
            } catch (WebDriverException e) {
                description.append(String.format("%nScreenshot: {capture error: %s}", e.getMessage()));
            }

            if (screenshot != null) {
                String fileName = getClass().getName() + "." + getName() + "_" + currentBrowserType + ".png";
                try {
                    File path = new File(screenshotsDirectory + "/" + fileName);
                    path.getParentFile().mkdirs();
                    byte[] bytes = Base64.decodeBase64(screenshot.getBytes());
                    FileOutputStream fos = new FileOutputStream(path);
                    fos.write(bytes);
                    fos.close();
                    String baseUrl = System.getProperty("screenshots.baseurl");
                    description.append(String.format("%nScreenshot: %s/%s", baseUrl, fileName));
                } catch (Throwable t) {
                    description.append(String.format("%nScreenshot: {save error: %s}", t.getMessage()));
                }
            }
        }

        try {
            description.append("\nApplication cache status: ");
            description.append(getAuraUITestingUtil().getRawEval(
                    "var cache=window.applicationCache;return (cache===undefined || cache===null)?'undefined':cache.status;")
                    .toString());
        } catch (Exception ex) {
            description.append("error calculating status: " + ex);
        }
        description.append("\n");
        if (SauceUtil.areTestsRunningOnSauce()) {
            String linkToJob = SauceUtil.getLinkToPublicJobInSauce(currentDriver);
            description.append("\nSauceLabs-recording: ");
            description.append((linkToJob != null) ? linkToJob : "{not available}");
        }
    }

    // replace original exception with new exception with additional info
    Throwable newFailure;
    if (originalErr instanceof AssertionFailedError) {
        newFailure = new AssertionFailedError(description.toString());
    } else {
        description.insert(0, originalErr.getClass() + ": ");
        newFailure = new UnexpectedError(description.toString(), originalErr.getCause());
    }
    newFailure.setStackTrace(originalErr.getStackTrace());
    return newFailure;
}

From source file:com.nextep.designer.sqlgen.postgre.impl.PostgreSqlCapturer.java

@Override
public Collection<IProcedure> getProcedures(ICaptureContext context, IProgressMonitor m) {
    final IProgressMonitor monitor = new CustomProgressMonitor(SubMonitor.convert(m, 100), PROGRESS_RANGE);
    Map<String, IProcedure> procedures = new HashMap<String, IProcedure>();
    Map<String, String> typeOidMap = new HashMap<String, String>();

    final Connection conn = (Connection) context.getConnectionObject();
    ResultSet rset = null;/*w  w  w  .j  a v a 2  s  .c  o m*/
    long start = 0;
    long queryTime = 0;
    long fetchTime = 0;
    try {
        Statement typStmt = null;
        try {
            typStmt = conn.createStatement();

            if (LOGGER.isDebugEnabled())
                start = System.currentTimeMillis();
            rset = typStmt.executeQuery("select oid, typname from pg_type"); //$NON-NLS-1$
            if (LOGGER.isDebugEnabled())
                queryTime += System.currentTimeMillis() - start;

            if (LOGGER.isDebugEnabled())
                start = System.currentTimeMillis();
            while (rset.next()) {
                final String oid = rset.getString(1);
                final String typeName = rset.getString(2);
                typeOidMap.put(oid, convertType(typeName));
            }
            if (LOGGER.isDebugEnabled())
                fetchTime += System.currentTimeMillis() - start;
        } finally {
            CaptureHelper.safeClose(rset, typStmt);
        }

        PreparedStatement prepStmt = null;
        try {
            // Querying attributes that are common to all database versions
            prepStmt = conn.prepareStatement("SELECT " //$NON-NLS-1$
                    + "    p.oid AS proc_id " //$NON-NLS-1$
                    + "  , p.proname AS proc_name " //$NON-NLS-1$
                    + "  , t.typname AS return_type " //$NON-NLS-1$
                    + "  , p.proretset AS returns_set " //$NON-NLS-1$
                    + "  , l.lanname AS language_type " //$NON-NLS-1$
                    + "  , p.proisstrict AS is_strict " //$NON-NLS-1$
                    + "  , p.proallargtypes AS all_arg_types_oids " //$NON-NLS-1$
                    + "  , p.proargtypes AS argument_types_oids " //$NON-NLS-1$
                    + "  , p.proargmodes AS arg_modes" //$NON-NLS-1$
                    + "  , p.proargnames AS arg_names" //$NON-NLS-1$
                    + "  , p.provolatile AS volatile" //$NON-NLS-1$
                    + "  , p.prosrc AS proc_body " //$NON-NLS-1$
                    + "  , p.probin AS bin_dir " //$NON-NLS-1$
                    + "FROM pg_proc p " //$NON-NLS-1$
                    + "  LEFT JOIN pg_type t ON p.prorettype = t.oid " //$NON-NLS-1$
                    + "  JOIN pg_language l ON p.prolang = l.oid " //$NON-NLS-1$
                    + "  JOIN pg_namespace n ON p.pronamespace = n.oid " //$NON-NLS-1$
                    + "WHERE n.nspname = ? " //$NON-NLS-1$
                    + "  AND l.lanname != 'internal'"); //$NON-NLS-1$
            prepStmt.setString(1, context.getSchema());

            if (LOGGER.isDebugEnabled())
                start = System.currentTimeMillis();
            rset = prepStmt.executeQuery();
            if (LOGGER.isDebugEnabled())
                queryTime += System.currentTimeMillis() - start;

            if (LOGGER.isDebugEnabled())
                start = System.currentTimeMillis();
            while (rset.next()) {
                monitor.worked(1);
                final String procOid = rset.getString("proc_id"); //$NON-NLS-1$
                final String name = rset.getString("proc_name"); //$NON-NLS-1$
                final String returnedType = rset.getString("return_type"); //$NON-NLS-1$
                final boolean returnsSet = rset.getBoolean("returns_set"); //$NON-NLS-1$
                final String languageType = rset.getString("language_type"); //$NON-NLS-1$
                final boolean isStrict = rset.getBoolean("is_strict"); //$NON-NLS-1$
                final String allArgTypesString = rset.getString("all_arg_types_oids"); //$NON-NLS-1$
                String[] allTypes = new String[0];
                if (allArgTypesString != null) {
                    allTypes = allArgTypesString.substring(1, allArgTypesString.length() - 1).split(","); //$NON-NLS-1$
                }
                final String argTypesString = rset.getString("argument_types_oids"); //$NON-NLS-1$
                String[] types = argTypesString.split("(\\s)+"); //$NON-NLS-1$
                final String argModesString = rset.getString("arg_modes"); //$NON-NLS-1$
                String[] argModes = new String[0];
                if (argModesString != null) {
                    argModes = argModesString.substring(1, argModesString.length() - 1).split(","); //$NON-NLS-1$
                }
                final String argNamesString = rset.getString("arg_names"); //$NON-NLS-1$
                String[] argNames = new String[0];
                if (argNamesString != null) {
                    argNames = argNamesString.substring(1, argNamesString.length() - 1).split(","); //$NON-NLS-1$
                }
                final String volatil = rset.getString("volatile"); //$NON-NLS-1$
                final String body = rset.getString("proc_body"); //$NON-NLS-1$
                final String binDir = rset.getString("bin_dir"); //$NON-NLS-1$

                if (LOGGER.isDebugEnabled()) {
                    String logPrefix = "[" + name + "]"; //$NON-NLS-1$ //$NON-NLS-2$
                    // LOGGER.debug("== Retrieving procedure " + logPrefix +
                    // " =="); //$NON-NLS-1$ //$NON-NLS-2$
                    LOGGER.debug("= " + logPrefix + " procedure Metadata ="); //$NON-NLS-1$ //$NON-NLS-2$
                    LOGGER.debug(logPrefix + "[pg_proc.oid] " + procOid); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.prorettype] " + returnedType); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.proretset] " + returnsSet); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.prolang] " + languageType); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.proisstrict] " + isStrict); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.proallargtypes] " + allArgTypesString); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.proargtypes] " + argTypesString); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.proargmodes] " + argModesString); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.proargnames] " + argNamesString); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.provolatile] " + volatil); //$NON-NLS-1$
                    LOGGER.debug(logPrefix + "[pg_proc.probin] " + binDir); //$NON-NLS-1$
                }

                IVersionable<IProcedure> v = VersionableFactory.createVersionable(IProcedure.class);
                IProcedure proc = v.getVersionnedObject().getModel();
                proc.setLanguageType(LanguageType.STANDARD); // TODO generic
                // languages

                /*
                 * FIXME [BGA] This mechanism is currently not compatible with procedure name
                 * checking when editing procedure SQL definition.
                 */
                final StringBuffer args = (new StringBuffer(50)).append("("); //$NON-NLS-1$
                final StringBuffer returnedTable = new StringBuffer(50);

                /*
                 * The pg_proc.proallargtypes field contains data only if the mode of at least
                 * one function argument is different from IN, or if the return value of the
                 * function is a TABLE type. If pg_proc.proallargtypes is null, we fallback
                 * using pg_proc.proargtypes.
                 */
                if (allArgTypesString != null) {
                    int typeIndex = 0;
                    String argsSeparator = ""; //$NON-NLS-1$
                    String colsSeparator = ""; //$NON-NLS-1$
                    boolean isReturnValue = false;
                    for (String type : allTypes) {
                        /*
                         * Appends the mode of the function argument if it is not a return
                         * value, and sets the flag to differentiate arguments from return
                         * values.
                         */
                        String argMode = argModes[typeIndex];
                        if ("i".equals(argMode)) { //$NON-NLS-1$
                            isReturnValue = false;
                            args.append(argsSeparator).append("IN "); //$NON-NLS-1$
                        } else if ("o".equals(argMode)) { //$NON-NLS-1$
                            isReturnValue = false;
                            args.append(argsSeparator).append("OUT "); //$NON-NLS-1$
                        } else if ("b".equals(argMode)) { //$NON-NLS-1$
                            isReturnValue = false;
                            args.append(argsSeparator).append("INOUT "); //$NON-NLS-1$
                        } else if ("v".equals(argMode)) { //$NON-NLS-1$
                            isReturnValue = false;
                            args.append(argsSeparator).append("VARIADIC "); //$NON-NLS-1$
                        } else if ("t".equals(argMode)) { //$NON-NLS-1$
                            isReturnValue = true;
                            returnedTable.append(colsSeparator);
                        }

                        // Appends the name of the argument or return value
                        if (argNames.length > typeIndex) {
                            if (!isReturnValue) {
                                args.append(argNames[typeIndex]).append(" "); //$NON-NLS-1$
                            } else {
                                returnedTable.append(argNames[typeIndex]).append(" "); //$NON-NLS-1$
                            }
                        }

                        // Appends the type of the argument or return value
                        if (typeOidMap.get(type) != null) {
                            if (!isReturnValue) {
                                args.append(convertType(typeOidMap.get(type)));
                            } else {
                                returnedTable.append(convertType(typeOidMap.get(type)));
                            }
                        }

                        if (!isReturnValue) {
                            argsSeparator = ", "; //$NON-NLS-1$
                        } else {
                            colsSeparator = ", "; //$NON-NLS-1$
                            // colsCnt++;
                        }
                        typeIndex++;
                    }

                    if (!"".equals(returnedTable.toString())) { //$NON-NLS-1$
                        returnedTable.insert(0, "TABLE(").append(")"); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                } else {
                    String separator = ""; //$NON-NLS-1$
                    int typeIndex = 0;
                    for (String type : types) {
                        args.append(separator);

                        if (argNames.length > typeIndex) {
                            args.append(argNames[typeIndex]);
                            args.append(" "); //$NON-NLS-1$
                        }

                        if (typeOidMap.get(type) != null) {
                            args.append(convertType(typeOidMap.get(type)));
                        }

                        separator = ", "; //$NON-NLS-1$
                        typeIndex++;
                    }
                }

                args.append(")"); //$NON-NLS-1$

                /*
                 * The procedure arguments types are appended to the procedure name in order to
                 * uniquely identify overloaded procedures.
                 */
                proc.setName(name + args);

                final StringBuffer sqlText = new StringBuffer(200);
                sqlText.append("CREATE OR REPLACE "); //$NON-NLS-1$
                sqlText.append(returnedType == null ? "PROCEDURE" : "FUNCTION"); //$NON-NLS-1$ //$NON-NLS-2$
                sqlText.append(" ").append(name); //$NON-NLS-1$
                sqlText.append(args.toString()).append(NEWLINE);

                if (returnedType != null) {
                    sqlText.append("  RETURNS "); //$NON-NLS-1$

                    if (!"".equals(returnedTable.toString())) { //$NON-NLS-1$
                        sqlText.append(returnedTable);
                    } else {
                        if (returnsSet) {
                            sqlText.append("SETOF "); //$NON-NLS-1$
                        }
                        final String convertedType = convertType(returnedType.toLowerCase());
                        sqlText.append(convertedType);
                    }
                }

                sqlText.append(" AS").append(NEWLINE); //$NON-NLS-1$
                if (languageType.equalsIgnoreCase("c")) { //$NON-NLS-1$
                    sqlText.append("'").append(binDir).append("', '").append(body).append("'") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            .append(NEWLINE);
                } else {
                    if (body != null) {
                        sqlText.append("$BODY$").append(NEWLINE) //$NON-NLS-1$
                                .append(body.trim()).append(NEWLINE).append("$BODY$") //$NON-NLS-1$
                                .append(NEWLINE);
                    }
                }
                sqlText.append("  LANGUAGE '").append(languageType).append("'"); //$NON-NLS-1$ //$NON-NLS-2$

                if ("i".equals(volatil)) { //$NON-NLS-1$
                    sqlText.append(" IMMUTABLE"); //$NON-NLS-1$
                } else if ("s".equals(volatil)) { //$NON-NLS-1$
                    sqlText.append(" STABLE"); //$NON-NLS-1$
                } else if ("v".equals(volatil)) { //$NON-NLS-1$
                    sqlText.append(" VOLATILE"); //$NON-NLS-1$
                }

                if (isStrict) {
                    sqlText.append(" STRICT"); //$NON-NLS-1$
                }

                proc.setSQLSource(sqlText.toString());
                procedures.put(procOid, proc);
            }
            if (LOGGER.isDebugEnabled())
                fetchTime += System.currentTimeMillis() - start;

            // Querying additional attributes for database versions equal or
            // greater than 8.3
            try {
                prepStmt = conn.prepareStatement("SELECT " //$NON-NLS-1$
                        + "    p.oid AS proc_id " //$NON-NLS-1$
                        + "  , p.proname AS proc_name " //$NON-NLS-1$
                        + "  , p.procost AS cost " //$NON-NLS-1$
                        + "  , p.prorows AS result_rows " //$NON-NLS-1$
                        + "FROM pg_proc p " //$NON-NLS-1$
                        + "  LEFT JOIN pg_type t ON p.prorettype = t.oid " //$NON-NLS-1$
                        + "  JOIN pg_language l ON p.prolang = l.oid " //$NON-NLS-1$
                        + "  JOIN pg_namespace n ON p.pronamespace = n.oid " //$NON-NLS-1$
                        + "WHERE n.nspname = ? " //$NON-NLS-1$
                        + "  AND l.lanname != 'internal'"); //$NON-NLS-1$
                prepStmt.setString(1, context.getSchema());

                if (LOGGER.isDebugEnabled())
                    start = System.currentTimeMillis();
                rset = prepStmt.executeQuery();
                if (LOGGER.isDebugEnabled())
                    queryTime += System.currentTimeMillis() - start;

                if (LOGGER.isDebugEnabled())
                    start = System.currentTimeMillis();
                while (rset.next()) {
                    final String procOid = rset.getString("proc_id"); //$NON-NLS-1$
                    final String name = rset.getString("proc_name"); //$NON-NLS-1$
                    final String cost = rset.getString("cost"); //$NON-NLS-1$
                    final String resultRows = rset.getString("result_rows"); //$NON-NLS-1$

                    if (LOGGER.isDebugEnabled()) {
                        String logPrefix = "[" + name + "]"; //$NON-NLS-1$ //$NON-NLS-2$
                        LOGGER.debug("= " + logPrefix //$NON-NLS-1$
                                + " procedure Metadata (only for versions > 8.2) ="); //$NON-NLS-1$
                        LOGGER.debug(logPrefix + "[pg_proc.procost] " + cost); //$NON-NLS-1$
                        LOGGER.debug(logPrefix + "[pg_proc.prorows] " + resultRows); //$NON-NLS-1$
                    }

                    if (cost != null && !"".equals(cost.trim())) { //$NON-NLS-1$
                        IProcedure proc = procedures.get(procOid);
                        if (proc != null) {
                            proc.setSQLSource(proc.getSQLSource() + NEWLINE + "  COST " + cost); //$NON-NLS-1$
                        }
                        if (resultRows != null && Float.valueOf(resultRows) > 0) {
                            proc.setSQLSource(proc.getSQLSource() + NEWLINE + "  ROWS " //$NON-NLS-1$
                                    + resultRows);
                        }
                    }
                }
                if (LOGGER.isDebugEnabled())
                    fetchTime += System.currentTimeMillis() - start;
            } catch (SQLException sqle) {
                LOGGER.info(SQLGenMessages.getString("capturer.costInfoNotAvailable")); //$NON-NLS-1$
                LOGGER.debug(sqle.getMessage(), sqle);
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[Procedures] query time: " + queryTime + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
                LOGGER.debug("[Procedures] fetching time: " + fetchTime + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
            }
        } finally {
            CaptureHelper.safeClose(rset, prepStmt);
        }
    } catch (SQLException e) {
        LOGGER.warn(MessageFormat.format(SQLGenMessages.getString("capturer.error.genericCapturerError"), //$NON-NLS-1$
                context.getConnection().getDBVendor().toString()) + e.getMessage(), e);
    }

    return procedures.values();
}

From source file:com.wavemaker.runtime.data.util.QueryHandler.java

public String modifySQL(Object o, String fieldName, int tid) {
    // String qryStr = o.toString();
    List<String> words = parseSQL(o.toString());

    /*/* w  w  w. j a  v a2 s.co  m*/
     * ArrayList<String> words = new ArrayList<String>();
     * 
     * //First, break the query into word elements
     * 
     * StringBuffer token = new StringBuffer(); String twoLetters = null; boolean holdIt = false;
     * 
     * for (int i=0; i<qryStr.length(); i++) { String aLetter = qryStr.substring(i, i+1); if (holdIt) { if
     * ((twoLetters.equals("<") && (aLetter.equals("=") || aLetter.equals(">"))) || (twoLetters.equals(">") &&
     * aLetter.equals("=")) || (twoLetters.equals("|") && aLetter.equals("|")) || (twoLetters.equals("\r") &&
     * aLetter.equals("\n"))) { twoLetters = twoLetters + aLetter; words.add(twoLetters); } else { if
     * (isDelimiter(aLetter)) { words.add(twoLetters); words.add(aLetter); } else if (aLetter.equals(" ")) {
     * words.add(twoLetters); } } holdIt = false; } else { if (aLetter.equals("<") || aLetter.equals(">") ||
     * aLetter.equals("|") || aLetter.equals("\r")) { holdIt = true; twoLetters = aLetter; if (token.length() > 0) {
     * words.add(token.toString()); token.setLength(0); } } else if (isDelimiter(aLetter)) { if (token.length() > 0)
     * { words.add(token.toString()); token.setLength(0); } words.add(aLetter); } else if (aLetter.equals(" ")) { if
     * (token.length() > 0) { words.add(token.toString()); token.setLength(0); } } else { token.append(aLetter); } }
     * }
     * 
     * if (token.length() > 0) words.add(token.toString());
     */

    // Process the array of words

    int len = words.size();

    String word;
    int qid = -1;
    HashMap<Integer, SingleQuery> tm = new HashMap<Integer, SingleQuery>();

    String aliasName;
    int tidInsertPosition = 0;
    int openingInsertPosition = 0;

    boolean queryEndProcessed = false; // to catch a case that a single query is enclosed with multiple parenthesis
    boolean fieldInserted = false;
    boolean valueInserted = false;
    boolean addTIDValueForInsert = false;
    boolean inInsertFldList = false;
    boolean inInsertValueList = false;
    boolean firstStatement = true;

    StringBuffer sb = new StringBuffer();
    SingleQuery sq = null;

    for (int i = 0; i < len; i++) {
        word = words.get(i);
        if (byPassChar(word)) {
            sb.append(word);
            continue;
        } else if (word.equalsIgnoreCase("select")) {
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            if (qid > -1) {
                tm.put(qid, sq);
            }
            qid++;
            sq = new SingleQuery("select", qid, true);
            queryEndProcessed = false;
            if (inInsertFldList) {
                tidInsertPosition = sb.length() + 1;
                inInsertFldList = false;
                addTIDValueForInsert = true;
            }

        } else if (word.equalsIgnoreCase("from")) {
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            if (sq == null || !sq.inQuery) {
                if (qid > -1) {
                    tm.put(qid, sq);
                }
                qid++;
                sq = new SingleQuery("select", qid, true);
            }
            sq.inFrom = true;
            queryEndProcessed = false;
            sq.aliasNum = 0;

        } else if (word.equalsIgnoreCase("update") && firstStatement) {
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            qid++;
            sq = new SingleQuery("update", qid, true);
            queryEndProcessed = false;
            sq.inUpdate = true;
            sq.aliasNum = 0;

        } else if (word.equalsIgnoreCase("set")) {
            sb = sq.appendTableAlias(sb, words, i, fieldName);
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            sq.inSet = true;
            sq.inUpdate = false;

        } else if (word.equalsIgnoreCase("delete") && firstStatement) {
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            qid++;
            sq = new SingleQuery("delete", qid, true);
            queryEndProcessed = false;
            sq.inDelete = true;
            sq.aliasNum = 0;

        } else if (word.equalsIgnoreCase("insert") && words.get(i + 1).equalsIgnoreCase("into") && i == 0) {
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            qid++;
            sq = new SingleQuery("insert", qid, true);
            queryEndProcessed = false;

        } else if (word.equalsIgnoreCase("into") && words.get(i - 1).equalsIgnoreCase("insert")) {
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            sq.inInsert = true;
            sq.aliasNum = 0;

        } else if (word.equalsIgnoreCase("where")) {
            sb = sq.appendTableAlias(sb, words, i, fieldName);
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            openingInsertPosition = sb.length() + 1;
            if (tidInsertPosition >= openingInsertPosition) {
                tidInsertPosition++;
            }
            sq.inWhere = true;
            sq.inFrom = false;
            sq.inUpdate = false;
            sq.inSet = false;
            sq.inDelete = false;

        } else if ((word.equalsIgnoreCase("group") || word.equalsIgnoreCase("order")) // group by / order by
                && words.get(i + 1).equalsIgnoreCase("by")) {
            if (!sq.tenantProcessed) {
                if (sq.tableAliases.size() > 0) {
                    if (sq.inWhere) {
                        sb.insert(openingInsertPosition, "(");
                        if (tidInsertPosition >= openingInsertPosition) {
                            tidInsertPosition++;
                        }
                        sb.append(") and (");
                        sb.append(insertTenantID(sq, fieldName));
                        sb.append(")");
                    } else {
                        sb.append(" where ");
                        sb.append(insertTenantID(sq, fieldName));
                    }
                }
                sq.tenantProcessed = true;
            }
            sb = sq.appendTableAlias(sb, words, i, fieldName);
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            sq.inFrom = false;
            sq.inWhere = false;
            sq.inSet = false;

        } else if (word.equalsIgnoreCase("(")) {
            if (sq.inInsert && !inInsertFldList && !inInsertValueList) {
                sq.inInsert = false;
                inInsertFldList = true;
            }
            sq.openings = sq.openings + 1;
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);

        } else if (word.equalsIgnoreCase(")")) { // end of the current query statement
            if (sq.openings <= 0) {
                if (!queryEndProcessed) {
                    sb = sq.appendTableAlias(sb, words, i, fieldName);
                    if (!sq.tenantProcessed) {
                        if (sq.tableAliases.size() > 0) {
                            if (sq.inWhere) {
                                sb.insert(openingInsertPosition, "(");
                                if (tidInsertPosition >= openingInsertPosition) {
                                    tidInsertPosition++;
                                }
                                sb.append(") and (");
                                sb.append(insertTenantID(sq, fieldName));
                                sb.append(")");
                            } else {
                                sb.append(" where ");
                                sb.append(insertTenantID(sq, fieldName));
                            }
                        }
                        sq.tenantProcessed = true;
                    }

                    sq.inFrom = false;
                    sq.inWhere = false;
                    sq.inUpdate = false;
                    sq.inSet = false;
                    sq.inDelete = false;
                    sq.inInsert = false;
                    sq.inQuery = false;

                    qid--;

                    sq = tm.get(qid); // get parent sql object
                    queryEndProcessed = true;
                }
            } else {
                sq.openings = sq.openings - 1;
            }
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);

        } else if (word.equalsIgnoreCase("values")) {
            if (inInsertFldList) {
                inInsertFldList = false;
                inInsertValueList = true;
            }
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
        } else if (word.equalsIgnoreCase("inner") || // misc key words that must turn off inForm flag
                word.equalsIgnoreCase("left") || word.equalsIgnoreCase("right") || word.equalsIgnoreCase("full")
                || word.equalsIgnoreCase("join") || word.equalsIgnoreCase("fetch")) {
            sb = sq.appendTableAlias(sb, words, i, fieldName);
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
            sq.inFrom = false;

        } else if (sq.queryType.equalsIgnoreCase("select") && sq.inFrom
                || sq.queryType.equalsIgnoreCase("update") && sq.inUpdate
                || sq.queryType.equalsIgnoreCase("delete") && sq.inDelete) { // populate table names array
            if (!word.equalsIgnoreCase("as") && !word.equalsIgnoreCase("\r\n") && !word.equalsIgnoreCase("\n")
                    && !word.equalsIgnoreCase(",")) {
                if (sq.alias) {
                    sq.addAliasNames(words, i, fieldName, word);
                    sq.alias = false;
                    sq.qryIncludeAlias = true;
                } else {
                    sq.alias = true;
                }
            }

            if (word.equalsIgnoreCase(",")) {
                sb = sq.appendTableAlias(sb, words, i, fieldName);
            }

            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
        } else if (inInsertFldList && !fieldInserted) { // add tid in the field list
            sb.append(fieldName);
            sb.append(", ");
            fieldInserted = true;
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
        } else if (inInsertValueList && !valueInserted) {
            sb.append(tid);
            sb.append(", ");
            valueInserted = true;
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
        } else {
            if (appendSpace(sb.toString(), word)) {
                sb.append(" ");
            }
            sb.append(word);
        }
        firstStatement = false;
    }

    if (sq.inFrom && !sq.qryIncludeAlias) {
        aliasName = "table" + sq.aliasNum++;
        if (appendSpace(sb.toString(), aliasName)) {
            sb.append(" ");
        }
        sb.append(aliasName);
        sq.addAliasNames(words, len - 1, fieldName, aliasName);
    }

    if (!sq.tenantProcessed) {
        if (sq.tableAliases.size() > 0) {
            if (sq.inWhere) {
                sb.insert(openingInsertPosition, "(");
                if (tidInsertPosition >= openingInsertPosition) {
                    tidInsertPosition++;
                }
                sb.append(") and (");
                sb.append(insertTenantID(sq, fieldName));
                sb.append(")");
            } else {
                sb.append(" where ");
                sb.append(insertTenantID(sq, fieldName));
            }
        }
        sq.tenantProcessed = true;
    }

    if (addTIDValueForInsert) { // add tid value in the field list
        String tidfld = sq.tableAliases.get(0) + "." + fieldName + ", ";
        sb.insert(tidInsertPosition, tidfld);
    }

    return sb.toString();
}

From source file:org.openbravo.client.kernel.StaticResourceComponent.java

/**
 * @return all static resources needed by the application and placed in the top of the application
 *         page, in order based on module dependencies and using an unique version string to force
 *         client side reload or caching.
 *///www  .  j  av a  2 s.  c  o  m
public String getStaticResourceFileName() {
    final List<Module> modules = KernelUtils.getInstance().getModulesOrderedByDependency();
    final ServletContext context = (ServletContext) getParameters().get(KernelConstants.SERVLET_CONTEXT);
    final StringBuffer sb = new StringBuffer();

    final String skinParam;
    if (getParameters().containsKey(KernelConstants.SKIN_PARAMETER)) {
        skinParam = (String) getParameters().get(KernelConstants.SKIN_PARAMETER);
    } else {
        skinParam = KernelConstants.SKIN_DEFAULT;
    }

    int cntDynamicScripts = 0;
    final String appName = getApplicationName();

    for (Module module : modules) {
        for (ComponentProvider provider : componentProviders) {
            final List<ComponentResource> resources = provider.getGlobalComponentResources();
            if (resources == null || resources.size() == 0) {
                continue;
            }

            if (provider.getModule().getId().equals(module.getId())) {
                for (ComponentResource resource : resources) {

                    if (!resource.isValidForApp(appName)) {
                        continue;
                    }

                    log.debug("Processing resource: " + resource);
                    String resourcePath = resource.getPath();
                    if (resource.getType() == ComponentResourceType.Stylesheet) {
                        // do these differently...
                    } else if (resource.getType() == ComponentResourceType.Static) {
                        if (resourcePath.startsWith(KernelConstants.KERNEL_JAVA_PACKAGE)) {
                            final String[] pathParts = WebServiceUtil.getInstance().getSegments(
                                    resourcePath.substring(KernelConstants.KERNEL_JAVA_PACKAGE.length()));
                            final Component component = provider.getComponent(pathParts[1], getParameters());
                            sb.append(ComponentGenerator.getInstance().generate(component)).append("\n");
                        } else {

                            // Skin version handling
                            if (resourcePath.contains(KernelConstants.SKIN_PARAMETER)) {
                                resourcePath = resourcePath.replaceAll(KernelConstants.SKIN_PARAMETER,
                                        skinParam);
                            }

                            try {
                                final File file = new File(context.getRealPath(resourcePath));
                                if (!file.exists() || !file.canRead()) {
                                    log.error(file.getAbsolutePath() + " cannot be read");
                                    continue;
                                }
                                String resourceContents = FileUtils.readFileToString(file, "UTF-8");
                                sb.append(resourceContents).append("\n");
                            } catch (Exception e) {
                                log.error("Error reading file: " + resource, e);
                            }
                        }
                    } else if (resource.getType() == ComponentResourceType.Dynamic) {
                        if (resourcePath.startsWith("/") && getContextUrl().length() > 0) {
                            resourcePath = getContextUrl() + resourcePath.substring(1);
                        } else {
                            resourcePath = getContextUrl() + resourcePath;
                        }

                        sb.append("$LAB.script('" + resourcePath + "').wait(function(){var _exception; try{\n");
                        cntDynamicScripts++;
                    } else {
                        log.error("Resource " + resource + " not supported");
                    }
                }
            }
        }
    }

    if (!"".equals(sb.toString())) {
        /*
         * If a module is in development or the application is running the tests, add the isDebug
         * variable to the generated javascript file.
         * 
         * If the isDebug variable is present in the javascript files, the code that calls
         * OB.UTIL.Debug will not be executed
         * 
         * This option is intended to run additional code (checks, etc) that will not be run while in
         * production.
         * 
         * This improves performance at the same time that the developer have a tool to improve
         * stability.
         * 
         * TODO: add an algorithm to remove the OB.UTIL.Debug code and calls from the generated
         * javacript file
         * 
         * TODO: don't load the ob-debug.js file if not in use
         */
        if (isInDevelopment() || OBPropertiesProvider.getInstance().getBooleanProperty("test.environment")) {
            // append a global isDebug var and the causes that provoked the application to enter Debug mode
            sb.insert(0, String.format(
                    "var isDebug = true;\nvar debugCauses = {\n  isInDevelopment: %s,\n  isTestEnvironment: %s\n};\n\n",
                    isInDevelopment(),
                    OBPropertiesProvider.getInstance().getBooleanProperty("test.environment")));
        }
        sb.append("if (window.onerror && window.onerror.name === '"
                + KernelConstants.BOOTSTRAP_ERROR_HANDLER_NAME + "') { window.onerror = null; }");
        sb.append(
                "if (typeof OBStartApplication !== 'undefined' && Object.prototype.toString.call(OBStartApplication) === '[object Function]') { OBStartApplication(); }");
    }

    for (int i = 0; i < cntDynamicScripts; i++) {
        // add extra exception handling code otherwise exceptions occuring in
        // the Labs wait function are not visible.
        sb.append("\n} catch (_exception) {");
        sb.append(
                "if (isc) { isc.Log.logError(_exception + ' ' + _exception.message + ' ' + _exception.stack); }");
        sb.append("if (console && console.trace) { console.trace();}");
        sb.append("}\n});");
    }

    // note compress, note that modules are cached in memory
    // when changing development status, system needs to be restarted.
    final String output;
    // in classicmode the isc combined is included, compressing that gives errors
    if (!isInDevelopment() && !isClassicMode()
            && !OBPropertiesProvider.getInstance().getBooleanProperty("test.environment")) {
        output = JSCompressor.getInstance().compress(sb.toString());
    } else {
        output = sb.toString();
    }
    final String md5 = DigestUtils.md5Hex(output);
    final File dir = new File(context.getRealPath(GEN_TARGET_LOCATION));
    if (!dir.exists()) {
        dir.mkdir();
    }
    File outFile = new File(context.getRealPath(GEN_TARGET_LOCATION + "/" + md5 + ".js"));
    if (!outFile.exists()) {
        try {
            log.debug("Writing file: " + outFile.getAbsolutePath());
            FileUtils.writeStringToFile(outFile, output, "UTF-8");
        } catch (Exception e) {
            log.error("Error writing file: " + e.getMessage(), e);
        }
    }
    return md5;
}

From source file:org.eclipse.mdht.uml.cda.core.util.CDAModelUtil.java

private static String computeCustomConformanceMessage(Constraint constraint, boolean markup) {
    StringBuffer message = new StringBuffer();
    String strucTextBody = null;/*w  ww  . j a  v a 2  s  . c  om*/
    String analysisBody = null;
    Map<String, String> langBodyMap = new HashMap<String, String>();

    CDAProfileUtil.getLogicalConstraint(constraint);

    ValueSpecification spec = constraint.getSpecification();
    if (spec instanceof OpaqueExpression) {
        for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {
            String lang = ((OpaqueExpression) spec).getLanguages().get(i);
            String body = ((OpaqueExpression) spec).getBodies().get(i);

            if ("StrucText".equals(lang)) {
                strucTextBody = body;
            } else if ("Analysis".equals(lang)) {
                analysisBody = body;
            } else {
                langBodyMap.put(lang, body);
            }
        }
    }

    String displayBody = null;
    if (strucTextBody != null && strucTextBody.trim().length() > 0) {
        // TODO if markup, parse strucTextBody and insert DITA markup
        displayBody = strucTextBody;
    } else if (analysisBody != null && analysisBody.trim().length() > 0) {
        Boolean ditaEnabled = false;
        try {
            Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(constraint,
                    ICDAProfileConstants.CONSTRAINT_VALIDATION);
            ditaEnabled = (Boolean) constraint.getValue(stereotype,
                    ICDAProfileConstants.CONSTRAINT_DITA_ENABLED);
        } catch (IllegalArgumentException e) { /* Swallow this */
        }
        if (markup && !ditaEnabled) {
            // escape non-dita markup in analysis text
            displayBody = escapeMarkupCharacters(analysisBody);
            // change severity words to bold text
            displayBody = replaceSeverityWithBold(displayBody);
        } else {
            displayBody = analysisBody;
        }
    }

    if (displayBody == null) {
        List<Stereotype> stereotypes = constraint.getAppliedStereotypes();
        if (stereotypes.isEmpty()) {
            // This should never happen but in case it does we deal with it appropriately
            // by bypassing custom constraint message additions
            return "";
        }
    }

    if (!markup) {
        message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
    }

    if (displayBody == null || !containsSeverityWord(displayBody)) {
        String keyword = getValidationKeyword(constraint);
        if (keyword == null) {
            keyword = "SHALL";
        }

        message.append(markup ? "<b>" : "");
        message.append(keyword);
        message.append(markup ? "</b>" : "");
        message.append(" satisfy: ");
    }

    if (displayBody == null) {
        message.append(constraint.getName());
    } else {
        message.append(displayBody);
    }
    appendConformanceRuleIds(constraint, message, markup);

    if (!markup) {
        // remove line feeds
        int index;
        while ((index = message.indexOf("\r")) >= 0) {
            message.deleteCharAt(index);
        }
        while ((index = message.indexOf("\n")) >= 0) {
            message.deleteCharAt(index);
            if (message.charAt(index) != ' ') {
                message.insert(index, " ");
            }
        }
    }

    return message.toString();
}

From source file:com.alkacon.opencms.formgenerator.database.CmsFormDataAccess.java

/**
 * Build the whole sql statement for the given form filter.<p>
 * //from   ww w.  j a  v a 2s.  c o  m
 * @param filter the filter
 * @param params the parameter values (return parameter)
 * @param count if true it selects no row, just the number of rows
 * 
 * @return the sql statement string
 */
private String getReadQuery(CmsFormDatabaseFilter filter, List<Object> params, boolean count) {

    StringBuffer sql = new StringBuffer(128);
    params.clear(); // be sure the parameters list is clear

    if (count) {
        sql.append(getQuery("COUNT_FORM_ENTRIES"));
    } else {
        if (filter.isHeadersOnly()) {
            sql.append(getQuery("READ_FORM_ENTRY"));
        } else {
            sql.append(getQuery("READ_FORM_DATA"));
        }
    }
    StringBuffer where = new StringBuffer(128);
    if (!filter.getFields().isEmpty()) {
        int fields = filter.getFields().size();
        for (int i = 0; i < fields; i++) {
            sql.append(",").append(getQuery("COND_FIELD_FROM", "" + i));
        }
    }
    if (!filter.isHeadersOnly()) {
        where.append(getQuery("COND_JOIN"));
    }
    if (filter.getEntryId() > 0) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_ENTRY_ID"));
        params.add(new Integer(filter.getEntryId()));
    }
    if (filter.getFormId() != null) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_FORM_ID"));
        params.add(filter.getFormId());
    }
    if (filter.getDateEnd() != CmsFormDatabaseFilter.DATE_IGNORE_TO) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_DATE_END"));
        params.add(new Long(filter.getDateEnd()));
    }
    if (filter.getStartDate() != CmsFormDatabaseFilter.DATE_IGNORE_FROM) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_DATE_START"));
        params.add(new Long(filter.getStartDate()));
    }
    if (filter.getResourceId() != null) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_RESOURCE_ID"));
        params.add(filter.getResourceId().toString());
    }

    // states filter
    Set<Integer> states = filter.getStates();
    if (!states.isEmpty()) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        String ph = "";
        for (int i = 0; i < states.size(); i++) {
            ph += "?";
            if (i < states.size() - 1) {
                ph += ", ";
            }
        }
        where.append(getQuery("FILTER_STATES", ph));
        Iterator<Integer> it = states.iterator();
        while (it.hasNext()) {
            Integer state = it.next();
            params.add(state);
        }
    }
    // fields filter
    Map<String, String> fields = filter.getFields();
    if (!fields.isEmpty()) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        int i = 0;
        Iterator<Entry<String, String>> it = fields.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> field = it.next();
            where.append(getQuery("FILTER_FIELD", "" + i));
            params.add(field.getKey());
            params.add(field.getValue());
            if (it.hasNext()) {
                where.append(" ").append(getQuery("COND_AND")).append(" ");
            }
            i++;
        }
    }
    if (where.length() > 0) {
        sql.append(" ").append(getQuery("COND_WHERE")).append(" ").append(where);
    }
    if (!count) {
        if (filter.isOrderAsc()) {
            sql.append(" ").append(getQuery("COND_ORDER_ASC"));
        } else {
            sql.append(" ").append(getQuery("COND_ORDER_DESC"));
        }
    }
    if ((filter.getIndexFrom() != CmsFormDatabaseFilter.INDEX_IGNORE_FROM)
            || (filter.getIndexTo() != CmsFormDatabaseFilter.INDEX_IGNORE_TO)) {
        int rows = filter.getIndexTo() - filter.getIndexFrom();
        if (m_db.equals(DB_ORACLE)) {
            rows = filter.getIndexTo();
        }
        sql.insert(0, " ").insert(0, getQuery("FILTER_LIMIT_PREFIX"));
        sql.append(" ").append(getQuery("FILTER_LIMIT_POSTFIX")).append(" ");
        sql.append(" ").append(getQuery("FILTER_LIMIT", "" + rows));
        if (filter.getIndexFrom() != 0) {
            sql.append(" ").append(getQuery("FILTER_OFFSET", "" + filter.getIndexFrom()));
        }
    }
    return sql.toString();
}

From source file:com.alkacon.opencms.v8.formgenerator.database.CmsFormDataAccess.java

/**
 * Build the whole sql statement for the given form filter.<p>
 * //  w  w w. j ava 2 s.co m
 * @param filter the filter
 * @param params the parameter values (return parameter)
 * @param count if true it selects no row, just the number of rows
 * 
 * @return the sql statement string
 */
private String getReadQuery(CmsFormDatabaseFilter filter, List<Object> params, boolean count) {

    StringBuffer sql = new StringBuffer(128);
    params.clear(); // be sure the parameters list is clear

    if (count) {
        sql.append(getQuery("COUNT_FORM_ENTRIES"));
    } else {
        if (filter.isHeadersOnly()) {
            sql.append(getQuery("READ_FORM_ENTRY"));
        } else {
            sql.append(getQuery("READ_FORM_DATA"));
        }
    }
    StringBuffer where = new StringBuffer(128);
    if (!filter.getFields().isEmpty()) {
        int fields = filter.getFields().size();
        for (int i = 0; i < fields; i++) {
            sql.append(",").append(getQuery("COND_FIELD_FROM", "" + i));
        }
    }
    if (!filter.isHeadersOnly()) {
        where.append(getQuery("COND_JOIN"));
    }
    if (filter.getEntryId() > 0) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_ENTRY_ID"));
        params.add(new Integer(filter.getEntryId()));
    }
    if (filter.getFormId() != null) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_FORM_ID"));
        params.add(filter.getFormId());
    }
    if (filter.getDateEnd() != CmsFormDatabaseFilter.DATE_IGNORE_TO) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_DATE_END"));
        params.add(new Long(filter.getDateEnd()));
    }
    if (filter.getStartDate() != CmsFormDatabaseFilter.DATE_IGNORE_FROM) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_DATE_START"));
        params.add(new Long(filter.getStartDate()));
    }
    if (filter.getResourceId() != null) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        where.append(getQuery("FILTER_RESOURCE_ID"));
        params.add(filter.getResourceId().toString());
    }

    // states filter
    Set<Integer> states = filter.getStates();
    if (!states.isEmpty()) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        String ph = "";
        for (int i = 0; i < states.size(); i++) {
            ph += "?";
            if (i < (states.size() - 1)) {
                ph += ", ";
            }
        }
        where.append(getQuery("FILTER_STATES", ph));
        Iterator<Integer> it = states.iterator();
        while (it.hasNext()) {
            Integer state = it.next();
            params.add(state);
        }
    }
    // fields filter
    Map<String, String> fields = filter.getFields();
    if (!fields.isEmpty()) {
        if (where.length() > 0) {
            where.append(" ").append(getQuery("COND_AND")).append(" ");
        }
        int i = 0;
        Iterator<Entry<String, String>> it = fields.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> field = it.next();
            where.append(getQuery("FILTER_FIELD", "" + i));
            params.add(field.getKey());
            params.add(field.getValue());
            if (it.hasNext()) {
                where.append(" ").append(getQuery("COND_AND")).append(" ");
            }
            i++;
        }
    }
    if (where.length() > 0) {
        sql.append(" ").append(getQuery("COND_WHERE")).append(" ").append(where);
    }
    if (!count) {
        if (filter.isOrderAsc()) {
            sql.append(" ").append(getQuery("COND_ORDER_ASC"));
        } else {
            sql.append(" ").append(getQuery("COND_ORDER_DESC"));
        }
    }
    if ((filter.getIndexFrom() != CmsFormDatabaseFilter.INDEX_IGNORE_FROM)
            || (filter.getIndexTo() != CmsFormDatabaseFilter.INDEX_IGNORE_TO)) {
        int rows = filter.getIndexTo() - filter.getIndexFrom();
        if (m_db.equals(DB_ORACLE)) {
            rows = filter.getIndexTo();
        }
        sql.insert(0, " ").insert(0, getQuery("FILTER_LIMIT_PREFIX"));
        sql.append(" ").append(getQuery("FILTER_LIMIT_POSTFIX")).append(" ");
        sql.append(" ").append(getQuery("FILTER_LIMIT", "" + rows));
        if (filter.getIndexFrom() != 0) {
            sql.append(" ").append(getQuery("FILTER_OFFSET", "" + filter.getIndexFrom()));
        }
    }
    return sql.toString();
}