Example usage for org.w3c.dom Element getFirstChild

List of usage examples for org.w3c.dom Element getFirstChild

Introduction

In this page you can find the example usage for org.w3c.dom Element getFirstChild.

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:com.icesoft.faces.component.selectinputdate.SelectInputDateRenderer.java

public void encodeEnd(FacesContext facesContext, UIComponent uiComponent) throws IOException {
    validateParameters(facesContext, uiComponent, SelectInputDate.class);
    DOMContext domContext = DOMContext.attachDOMContext(facesContext, uiComponent);
    SelectInputDate selectInputDate = (SelectInputDate) uiComponent;

    Date value;//from  w w  w.  j av a 2  s .  c o m
    boolean actuallyHaveTime = false;
    if (selectInputDate.isNavEvent()) {
        if (log.isTraceEnabled()) {
            log.trace("Rendering Nav Event");
        }
        value = selectInputDate.getNavDate();
        //System.out.println("navDate: " + value);
    } else if (selectInputDate.isRenderAsPopup() && !selectInputDate.isEnterKeyPressed(facesContext)) {
        value = selectInputDate.getPopupDate();
        if (value != null) {
            actuallyHaveTime = true;
        }
    } else {
        if (log.isTraceEnabled()) {
            log.trace("Logging non nav event");
        }
        value = CustomComponentUtils.getDateValue(selectInputDate);
        if (value != null) {
            actuallyHaveTime = true;
        }
        //System.out.println("CustomComponentUtils.getDateValue: " + value);
    }

    DateTimeConverter converter = selectInputDate.resolveDateTimeConverter(facesContext);
    TimeZone tz = selectInputDate.resolveTimeZone(facesContext);
    Locale currentLocale = selectInputDate.resolveLocale(facesContext);
    DateFormatSymbols symbols = new DateFormatSymbols(currentLocale);

    //System.out.println("SIDR.encodeEnd()  timezone: " + tz);
    //System.out.println("SIDR.encodeEnd()  locale: " + currentLocale);

    Calendar timeKeeper = Calendar.getInstance(tz, currentLocale);
    timeKeeper.setTime(value != null ? value : new Date());

    // get the parentForm
    UIComponent parentForm = findForm(selectInputDate);
    // if there is no parent form - ERROR
    if (parentForm == null) {
        log.error("SelectInputDate::must be in a FORM");
        return;
    }
    String clientId;
    if (!domContext.isInitialized()) {
        Element root = domContext.createRootElement(HTML.DIV_ELEM);
        boolean popupState = selectInputDate.isShowPopup();

        clientId = uiComponent.getClientId(facesContext);
        if (uiComponent.getId() != null)
            root.setAttribute("id", clientId + ROOT_DIV);

        Element table = domContext.createElement(HTML.TABLE_ELEM);
        if (selectInputDate.isRenderAsPopup()) {
            if (log.isTraceEnabled()) {
                log.trace("Render as popup");
            }
            // ICE-2492
            root.setAttribute(HTML.CLASS_ATTR,
                    Util.getQualifiedStyleClass(uiComponent, CSS_DEFAULT.DEFAULT_CALENDARPOPUP_CLASS, false));
            Element dateText = domContext.createElement(HTML.INPUT_ELEM);
            //System.out.println("value: " + selectInputDate.getValue());

            dateText.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_TEXT); // ICE-2302
            dateText.setAttribute(HTML.VALUE_ATTR, selectInputDate.getTextToRender());
            dateText.setAttribute(HTML.ID_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT);
            dateText.setAttribute(HTML.NAME_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT);
            dateText.setAttribute(HTML.CLASS_ATTR, selectInputDate.getCalendarInputClass());
            dateText.setAttribute(HTML.ONFOCUS_ATTR, "setFocus('');");
            dateText.setAttribute("onkeypress", this.ICESUBMIT);
            boolean withinSingleSubmit = org.icefaces.impl.util.Util.withinSingleSubmit(selectInputDate);
            if (withinSingleSubmit) {
                JavascriptContext.addJavascriptCall(facesContext,
                        "ice.cancelSingleSubmit('" + clientId + ROOT_DIV + "');");
            }
            String singleSubmitCall = "ice.fullSubmit('@this', '@all', event, this, function(p) { p('ice.submit.type', 'ice.se'); p('ice.submit.serialization', 'form');});";
            String onblur = combinedPassThru("setFocus('');",
                    selectInputDate.getPartialSubmit() ? ICESUBMITPARTIAL
                            : withinSingleSubmit ? singleSubmitCall : null);
            dateText.setAttribute(HTML.ONBLUR_ATTR, onblur);
            if (selectInputDate.getTabindex() != null) {
                dateText.setAttribute(HTML.TABINDEX_ATTR, selectInputDate.getTabindex());
            }
            if (selectInputDate.getAutocomplete() != null
                    && "off".equalsIgnoreCase(selectInputDate.getAutocomplete())) {
                dateText.setAttribute(HTML.AUTOCOMPLETE_ATTR, "off");
            }
            String tooltip = null;
            tooltip = selectInputDate.getInputTitle();
            if (tooltip == null || tooltip.length() == 0) {
                // extract the popupdate format and use it as a tooltip
                tooltip = getMessageWithParamFromResource(facesContext, INPUT_TEXT_TITLE,
                        selectInputDate.getSpecifiedPopupDateFormat());
            }
            if (tooltip != null && tooltip.length() > 0) {
                dateText.setAttribute(HTML.TITLE_ATTR, tooltip);
            }
            if (selectInputDate.isDisabled()) {
                dateText.setAttribute(HTML.DISABLED_ATTR, HTML.DISABLED_ATTR);
            }
            if (selectInputDate.isReadonly()) {
                dateText.setAttribute(HTML.READONLY_ATTR, HTML.READONLY_ATTR);
            }
            int maxlength = selectInputDate.getMaxlength();
            if (maxlength > 0) {
                dateText.setAttribute(HTML.MAXLENGTH_ATTR, String.valueOf(maxlength));
            }
            root.appendChild(dateText);
            Element calendarButton = domContext.createElement(HTML.INPUT_ELEM);
            calendarButton.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_BUTTON);
            calendarButton.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_BUTTON);
            calendarButton.setAttribute(HTML.TYPE_ATTR, "image");
            calendarButton.setAttribute(HTML.ONFOCUS_ATTR, "setFocus('');");
            calendarButton.setAttribute(HTML.ONMOUSEDOWN_ATTR,
                    "if (Event.isLeftClick(event)) this.selfClick = true;");
            calendarButton.setAttribute(HTML.ONKEYDOWN_ATTR,
                    "if (event.keyCode == 13 || event.keyCode == 32) this.selfClick = true;");
            // render onclick to set value of hidden field to true
            String formClientId = parentForm.getClientId(facesContext);
            String hiddenValue1 = "document.forms['" + formClientId + "']['"
                    + this.getLinkId(facesContext, uiComponent) + "'].value='";
            String hiddenValue2 = "document.forms['" + formClientId + "']['"
                    + getHiddenFieldName(facesContext, uiComponent) + "'].value='";
            String onClick = "if (!this.selfClick) return false; this.selfClick = false; " + hiddenValue1
                    + clientId + CALENDAR_BUTTON + "';" + hiddenValue2 + "toggle';"
                    + "iceSubmitPartial( document.forms['" + formClientId + "'], this,event);" + hiddenValue1
                    + "';" + hiddenValue2 + "';" + "Ice.Calendar.addCloseListener('" + clientId + "','"
                    + formClientId + "','" + this.getLinkId(facesContext, uiComponent) + "','"
                    + getHiddenFieldName(facesContext, uiComponent) + "');" + "return false;";
            calendarButton.setAttribute(HTML.ONCLICK_ATTR, onClick);
            if (selectInputDate.getTabindex() != null) {
                try {
                    int tabIndex = Integer.valueOf(selectInputDate.getTabindex()).intValue();
                    tabIndex += 1;
                    calendarButton.setAttribute(HTML.TABINDEX_ATTR, String.valueOf(tabIndex));
                } catch (NumberFormatException e) {
                    if (log.isInfoEnabled()) {
                        log.info("NumberFormatException on tabindex");
                    }
                }
            }

            if (selectInputDate.isDisabled()) {
                calendarButton.setAttribute(HTML.DISABLED_ATTR, HTML.DISABLED_ATTR);
            }
            if (selectInputDate.isReadonly()) {
                calendarButton.setAttribute(HTML.READONLY_ATTR, HTML.READONLY_ATTR);
            }
            root.appendChild(calendarButton);
            // render a hidden field to manage the popup state; visible || hidden
            FormRenderer.addHiddenField(facesContext, getHiddenFieldName(facesContext, uiComponent));
            String resolvedSrc;
            if (popupState) {
                JavascriptContext.addJavascriptCall(facesContext, "Ice.util.adjustMyPosition('" + clientId
                        + CALENDAR_TABLE + "', '" + clientId + ROOT_DIV + "');");
                if (selectInputDate.isImageDirSet()) {
                    resolvedSrc = CoreUtils.resolveResourceURL(facesContext,
                            selectInputDate.getImageDir() + selectInputDate.getClosePopupImage());
                } else {
                    // ICE-2127: allow override of button images via CSS
                    calendarButton.setAttribute(HTML.CLASS_ATTR, selectInputDate.getClosePopupClass());
                    // without this Firefox would display a default text on top of the image
                    resolvedSrc = CoreUtils.resolveResourceURL(facesContext,
                            selectInputDate.getImageDir() + "spacer.gif");
                }
                calendarButton.setAttribute(HTML.SRC_ATTR, resolvedSrc);
                addAttributeToElementFromResource(facesContext, CLOSE_POPUP_ALT, calendarButton, HTML.ALT_ATTR);
                addAttributeToElementFromResource(facesContext, CLOSE_POPUP_TITLE, calendarButton,
                        HTML.TITLE_ATTR);
            } else {
                if (selectInputDate.isImageDirSet()) {
                    resolvedSrc = CoreUtils.resolveResourceURL(facesContext,
                            selectInputDate.getImageDir() + selectInputDate.getOpenPopupImage());
                } else {
                    // ICE-2127: allow override of button images via CSS
                    calendarButton.setAttribute(HTML.CLASS_ATTR, selectInputDate.getOpenPopupClass());
                    // without this Firefox would display a default text on top of the image
                    resolvedSrc = CoreUtils.resolveResourceURL(facesContext,
                            selectInputDate.getImageDir() + "spacer.gif");
                }
                calendarButton.setAttribute(HTML.SRC_ATTR, resolvedSrc);
                addAttributeToElementFromResource(facesContext, OPEN_POPUP_ALT, calendarButton, HTML.ALT_ATTR);
                addAttributeToElementFromResource(facesContext, OPEN_POPUP_TITLE, calendarButton,
                        HTML.TITLE_ATTR);
                FormRenderer.addHiddenField(facesContext, formClientId
                        + UINamingContainer.getSeparatorChar(FacesContext.getCurrentInstance()) + "j_idcl");
                FormRenderer.addHiddenField(facesContext, clientId + CALENDAR_CLICK);
                PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent,
                        passThruAttributesWithoutTabindex);
                domContext.stepOver();
                return;
            }

            Text br = domContext.createTextNodeUnescaped("<br/>");
            root.appendChild(br);

            Element calendarDiv = domContext.createElement(HTML.DIV_ELEM);
            calendarDiv.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_POPUP);
            calendarDiv.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_POPUP);
            calendarDiv.setAttribute(HTML.STYLE_ELEM, "position:absolute;z-index:10;");
            addAttributeToElementFromResource(facesContext, POPUP_CALENDAR_TITLE, calendarDiv, HTML.TITLE_ATTR);
            table.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_TABLE);
            table.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_TABLE);
            table.setAttribute(HTML.CLASS_ATTR, selectInputDate.getStyleClass());
            table.setAttribute(HTML.STYLE_ATTR, "position:absolute;");
            table.setAttribute(HTML.CELLPADDING_ATTR, "0");
            table.setAttribute(HTML.CELLSPACING_ATTR, "0");
            // set mouse events on table bug 372
            String mouseOver = selectInputDate.getOnmouseover();
            table.setAttribute(HTML.ONMOUSEOVER_ATTR, mouseOver);
            String mouseOut = selectInputDate.getOnmouseout();
            table.setAttribute(HTML.ONMOUSEOUT_ATTR, mouseOut);
            String mouseMove = selectInputDate.getOnmousemove();
            table.setAttribute(HTML.ONMOUSEMOVE_ATTR, mouseMove);

            addAttributeToElementFromResource(facesContext, POPUP_CALENDAR_SUMMARY, table, HTML.SUMMARY_ATTR);
            Element positionDiv = domContext.createElement(HTML.DIV_ELEM);
            positionDiv.appendChild(table);
            calendarDiv.appendChild(positionDiv);
            Text iframe = domContext.createTextNodeUnescaped("<!--[if lte IE" + " 6.5]><iframe src='"
                    + CoreUtils.resolveResourceURL(FacesContext.getCurrentInstance(), "/xmlhttp/blank")
                    + "' class=\"iceSelInpDateIFrameFix\"></iframe><![endif]-->");
            calendarDiv.appendChild(iframe);
            root.appendChild(calendarDiv);

        } else {
            if (log.isTraceEnabled()) {
                log.trace("Select input Date Normal");
            }
            table.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_TABLE);
            table.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_TABLE);
            table.setAttribute(HTML.CLASS_ATTR, selectInputDate.getStyleClass());
            addAttributeToElementFromResource(facesContext, CALENDAR_TITLE, table, HTML.TITLE_ATTR);
            table.setAttribute(HTML.CELLPADDING_ATTR, "0");
            table.setAttribute(HTML.CELLSPACING_ATTR, "0");
            // set mouse events on table bug 372
            String mouseOver = selectInputDate.getOnmouseover();
            table.setAttribute(HTML.ONMOUSEOVER_ATTR, mouseOver);
            String mouseOut = selectInputDate.getOnmouseout();
            table.setAttribute(HTML.ONMOUSEOUT_ATTR, mouseOut);
            String mouseMove = selectInputDate.getOnmousemove();
            table.setAttribute(HTML.ONMOUSEMOVE_ATTR, mouseMove);
            addAttributeToElementFromResource(facesContext, CALENDAR_SUMMARY, table, HTML.SUMMARY_ATTR);
            root.appendChild(table);

            Element dateText = domContext.createElement(HTML.INPUT_ELEM);
            dateText.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_HIDDEN);
            dateText.setAttribute(HTML.VALUE_ATTR, selectInputDate.getTextToRender());
            dateText.setAttribute(HTML.ID_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT);
            dateText.setAttribute(HTML.NAME_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT);
            root.appendChild(dateText);
        }
    }
    clientId = uiComponent.getClientId(facesContext);

    String[] weekdays = mapWeekdays(symbols);
    String[] weekdaysLong = mapWeekdaysLong(symbols);
    String[] months = mapMonths(symbols);

    // use the currentDay to set focus - do not set
    int lastDayInMonth = timeKeeper.getActualMaximum(Calendar.DAY_OF_MONTH);
    int currentDay = timeKeeper.get(Calendar.DAY_OF_MONTH); // starts at 1

    if (currentDay > lastDayInMonth) {
        currentDay = lastDayInMonth;
    }

    timeKeeper.set(Calendar.DAY_OF_MONTH, 1);

    int weekDayOfFirstDayOfMonth = mapCalendarDayToCommonDay(timeKeeper.get(Calendar.DAY_OF_WEEK));

    int weekStartsAtDayIndex = mapCalendarDayToCommonDay(timeKeeper.getFirstDayOfWeek());

    // do not require a writer - clean out all methods that reference a writer
    ResponseWriter writer = facesContext.getResponseWriter();

    Element root = (Element) domContext.getRootNode();

    Element table = null;
    if (selectInputDate.isRenderAsPopup()) {
        if (log.isTraceEnabled()) {
            log.trace("SelectInputDate as Popup");
        }

        // assumption input text is first child
        Element dateText = (Element) root.getFirstChild();
        //System.out.println("dateText  currentValue: " + currentValue);
        dateText.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_TEXT); // ICE-2302
        dateText.setAttribute(HTML.VALUE_ATTR, selectInputDate.getTextToRender());
        int maxlength = selectInputDate.getMaxlength();
        if (maxlength > 0) {
            dateText.setAttribute(HTML.MAXLENGTH_ATTR, String.valueOf(maxlength));
        }

        // get tables , our table is the first and only one
        NodeList tables = root.getElementsByTagName(HTML.TABLE_ELEM);
        // assumption we want the first table in tables. there should only be one
        table = (Element) tables.item(0);

        PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent,
                passThruAttributesWithoutTabindex);

        Element tr1 = domContext.createElement(HTML.TR_ELEM);

        table.appendChild(tr1);
        writeMonthYearHeader(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay, tr1,
                selectInputDate.getMonthYearRowClass(), currentLocale, months, weekdays, weekdaysLong,
                converter);

        Element tr2 = domContext.createElement(HTML.TR_ELEM);
        table.appendChild(tr2);

        writeWeekDayNameHeader(domContext, weekStartsAtDayIndex, weekdays, facesContext, writer,
                selectInputDate, tr2, selectInputDate.getWeekRowClass(), timeKeeper, months, weekdaysLong,
                converter);

        writeDays(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay,
                weekStartsAtDayIndex, weekDayOfFirstDayOfMonth, lastDayInMonth, table, months, weekdays,
                weekdaysLong, converter, (actuallyHaveTime ? value : null));
    } else {
        if (log.isTraceEnabled()) {
            log.trace("renderNormal::endcodeEnd");
        }
        // assume table is the first child
        table = (Element) root.getFirstChild();

        PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent, passThruAttributes);

        Element tr1 = domContext.createElement(HTML.TR_ELEM);
        table.appendChild(tr1);

        writeMonthYearHeader(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay, tr1,
                selectInputDate.getMonthYearRowClass(), currentLocale, months, weekdays, weekdaysLong,
                converter);

        Element tr2 = domContext.createElement(HTML.TR_ELEM);

        writeWeekDayNameHeader(domContext, weekStartsAtDayIndex, weekdays, facesContext, writer,
                selectInputDate, tr2, selectInputDate.getWeekRowClass(), timeKeeper, months, weekdaysLong,
                converter);

        table.appendChild(tr2);

        writeDays(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay,
                weekStartsAtDayIndex, weekDayOfFirstDayOfMonth, lastDayInMonth, table, months, weekdays,
                weekdaysLong, converter, (actuallyHaveTime ? value : null));
    }

    //System.out.println("SIDR.encodeEnd()  isTime? " + SelectInputDate.isTime(converter));
    if (SelectInputDate.isTime(converter)) {
        Element tfoot = domContext.createElement(HTML.TFOOT_ELEM);
        Element tr = domContext.createElement(HTML.TR_ELEM);
        Element td = domContext.createElement(HTML.TD_ELEM);
        td.setAttribute(HTML.COLSPAN_ATTR, selectInputDate.isRenderWeekNumbers() ? "8" : "7");
        td.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeClass());
        Element tbl = domContext.createElement(HTML.TABLE_ELEM);
        Element tr2 = domContext.createElement(HTML.TR_ELEM);
        Element tdHours = domContext.createElement(HTML.TD_ELEM);
        Element hours = domContext.createElement(HTML.SELECT_ELEM);
        hours.setAttribute(HTML.ID_ATTR, clientId + SELECT_HOUR);
        hours.setAttribute(HTML.NAME_ATTR, clientId + SELECT_HOUR);
        hours.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass());
        hours.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL);

        // Convert from an hour to an index into the list of hours
        int hrs[] = selectInputDate.getHours(facesContext);
        //System.out.println("SIDR.encodeEnd()  hrs: " + hrs[0] + ", " + hrs[hrs.length-1]);
        int hourIndex;
        int min;
        int sec;
        int amPm;
        //System.out.println("SIDR.encodeEnd()  actuallyHaveTime: " + actuallyHaveTime);
        if (!actuallyHaveTime && selectInputDate.getHoursSubmittedValue() != null
                && selectInputDate.getMinutesSubmittedValue() != null) {
            //System.out.println("SIDR.encodeEnd()  Using submitted hours and minutes");
            hourIndex = selectInputDate.getHoursSubmittedValue().intValue();
            //System.out.println("SIDR.encodeEnd()  hour: " + hourIndex);
            min = selectInputDate.getMinutesSubmittedValue().intValue();
            //System.out.println("SIDR.encodeEnd()  min: " + min);
            String amPmStr = selectInputDate.getAmPmSubmittedValue();
            //System.out.println("SIDR.encodeEnd()  amPmStr: " + amPmStr);
            if (amPmStr != null) {
                amPm = amPmStr.equalsIgnoreCase("PM") ? 1 : 0;
            } else {
                amPm = (hourIndex >= 12) ? 1 : 0;
            }
            //System.out.println("SIDR.encodeEnd()  amPm: " + amPm);
            if (hrs[0] == 1) {
                hourIndex--;
                if (hourIndex < 0) {
                    hourIndex = hrs.length - 1;
                }
            }
            //System.out.println("SIDR.encodeEnd()  hourIndex: " + hourIndex);
        } else {
            if (hrs.length > 12) {
                hourIndex = timeKeeper.get(Calendar.HOUR_OF_DAY);
                //System.out.println("SIDR.encodeEnd()  hour 24: " + hourIndex);
            } else {
                hourIndex = timeKeeper.get(Calendar.HOUR);
                //System.out.println("SIDR.encodeEnd()  hour 12: " + hourIndex);
            }
            if (hrs[0] == 1) {
                hourIndex--;
                if (hourIndex < 0) {
                    hourIndex = hrs.length - 1;
                }
            }
            //System.out.println("SIDR.encodeEnd()  hourIndex: " + hourIndex);

            min = timeKeeper.get(Calendar.MINUTE);
            amPm = timeKeeper.get(Calendar.AM_PM);
            //System.out.println("SIDR.encodeEnd()  amPm: " + amPm);
        }
        if (!actuallyHaveTime && selectInputDate.getSecondsSubmittedValue() != null) {
            sec = selectInputDate.getSecondsSubmittedValue().intValue();
        } else {
            sec = timeKeeper.get(Calendar.SECOND);
        }
        for (int i = 0; i < hrs.length; i++) {
            Element hoursOption = domContext.createElement(HTML.OPTION_ELEM);
            hoursOption.setAttribute(HTML.VALUE_ATTR, String.valueOf(hrs[i]));
            Text hourText = domContext.createTextNode(String.valueOf(hrs[i]));
            hoursOption.appendChild(hourText);
            if (i == hourIndex) {
                hoursOption.setAttribute(HTML.SELECTED_ATTR, "true");
            }
            hours.appendChild(hoursOption);
        }
        Element tdColon = domContext.createElement(HTML.TD_ELEM);
        Element tdMinutes = domContext.createElement(HTML.TD_ELEM);
        Element minutes = domContext.createElement(HTML.SELECT_ELEM);
        minutes.setAttribute(HTML.ID_ATTR, clientId + SELECT_MIN);
        minutes.setAttribute(HTML.NAME_ATTR, clientId + SELECT_MIN);
        minutes.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass());
        minutes.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL);
        for (int i = 0; i < 60; i++) {
            Element minutesOption = domContext.createElement(HTML.OPTION_ELEM);
            minutesOption.setAttribute(HTML.VALUE_ATTR, String.valueOf(i));
            String digits = String.valueOf(i);
            if (i < 10) {
                digits = "0" + digits;
            }
            Text minuteText = domContext.createTextNode(digits);
            minutesOption.appendChild(minuteText);
            if (i == min) {
                minutesOption.setAttribute(HTML.SELECTED_ATTR, "true");
            }
            minutes.appendChild(minutesOption);
        }

        Text colon = domContext.createTextNode(":");
        tfoot.appendChild(tr);
        tr.appendChild(td);
        td.appendChild(tbl);
        tbl.appendChild(tr2);
        tdHours.appendChild(hours);
        tr2.appendChild(tdHours);
        tdColon.appendChild(colon);
        tdMinutes.appendChild(minutes);
        tr2.appendChild(tdColon);
        tr2.appendChild(tdMinutes);

        if (selectInputDate.isSecond(facesContext)) {
            Element tdSeconds = domContext.createElement(HTML.TD_ELEM);
            Element tdSecColon = domContext.createElement(HTML.TD_ELEM);
            Element seconds = domContext.createElement(HTML.SELECT_ELEM);
            seconds.setAttribute(HTML.ID_ATTR, clientId + SELECT_SEC);
            seconds.setAttribute(HTML.NAME_ATTR, clientId + SELECT_SEC);
            seconds.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass());
            seconds.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL);
            for (int i = 0; i < 60; i++) {
                Element secondsOption = domContext.createElement(HTML.OPTION_ELEM);
                secondsOption.setAttribute(HTML.VALUE_ATTR, String.valueOf(i));
                String digits = String.valueOf(i);
                if (i < 10) {
                    digits = "0" + digits;
                }
                Text secondText = domContext.createTextNode(digits);
                secondsOption.appendChild(secondText);
                if (i == sec) {
                    secondsOption.setAttribute(HTML.SELECTED_ATTR, "true");
                }
                seconds.appendChild(secondsOption);
            }
            Text secondColon = domContext.createTextNode(":");
            tdSecColon.appendChild(secondColon);
            tdSeconds.appendChild(seconds);
            tr2.appendChild(tdSecColon);
            tr2.appendChild(tdSeconds);
        }

        if (selectInputDate.isAmPm(facesContext)) {
            Element tdAamPm = domContext.createElement(HTML.TD_ELEM);
            Element amPmElement = domContext.createElement(HTML.SELECT_ELEM);
            amPmElement.setAttribute(HTML.ID_ATTR, clientId + SELECT_AM_PM);
            amPmElement.setAttribute(HTML.NAME_ATTR, clientId + SELECT_AM_PM);
            amPmElement.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass());
            amPmElement.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL);
            String[] symbolsAmPm = symbols.getAmPmStrings();

            Element amPmElementOption = domContext.createElement(HTML.OPTION_ELEM);
            amPmElementOption.setAttribute(HTML.VALUE_ATTR, "AM");
            Text amPmElementText = domContext.createTextNode(symbolsAmPm[0]);
            amPmElementOption.appendChild(amPmElementText);

            Element amPmElementOption2 = domContext.createElement(HTML.OPTION_ELEM);
            amPmElementOption2.setAttribute(HTML.VALUE_ATTR, "PM");
            Text amPmElementText2 = domContext.createTextNode(symbolsAmPm[1]);
            amPmElementOption2.appendChild(amPmElementText2);
            if (amPm == 0) {
                amPmElementOption.setAttribute(HTML.SELECTED_ATTR, "true");
            } else {
                amPmElementOption2.setAttribute(HTML.SELECTED_ATTR, "true");
            }
            amPmElement.appendChild(amPmElementOption);
            amPmElement.appendChild(amPmElementOption2);
            tdAamPm.appendChild(amPmElement);
            tr2.appendChild(tdAamPm);
        }
        table.appendChild(tfoot);
    }
    // purge child components as they have been encoded no need to keep them around
    selectInputDate.getChildren().clear();

    // steps to the position where the next sibling should be rendered
    domContext.stepOver();
}

From source file:no.kantega.publishing.common.data.attributes.ListAttribute.java

@Override
public void setConfig(Element config, Map<String, String> model)
        throws InvalidTemplateException, SystemException {
    super.setConfig(config, model);

    if (config != null) {
        String multiple = config.getAttribute("multiple");
        if ("true".equalsIgnoreCase(multiple)) {
            this.multiple = true;
        }//from  ww  w. ja  v  a 2 s  .com

        key = StringUtils.defaultString(config.getAttribute("key"));

        options = new ArrayList<>();

        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList) xpath.evaluate("options/option", config, XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); i++) {
                Element elmOption = (Element) nodes.item(i);
                String optText = elmOption.getFirstChild().getNodeValue();
                String optVal = elmOption.getAttribute("value");
                String optSel = elmOption.getAttribute("selected");
                ListOption option = new ListOption();
                option.setText(optText);
                option.setValue(optVal);
                if ("true".equalsIgnoreCase(optSel)) {
                    option.setDefaultSelected(true);
                }
                options.add(option);
            }

        } catch (XPathExpressionException e) {
            log.error("Error getting list options", e);
        }
        ignoreVariant = Boolean.valueOf(config.getAttribute("ignorevariant"));
    }
}

From source file:no.sesat.search.query.analyser.AnalysisRuleFactory.java

private void init() {

    if (!init) {/* w w w .  j av  a 2s . c o m*/
        loader.abut();
        LOG.info("Parsing " + ANALYSIS_RULES_XMLFILE + " started for " + context.getSite());

        final Document doc = loader.getDocument();
        assert null != doc : "No document loaded for " + context.getSite().getName();

        final Element root = doc.getDocumentElement();

        final Map<String, Predicate> inheritedPredicates = getInheritedPredicates();

        if (null != root) {

            // initialise anonymous predicate
            final String evaluatorTypes = root.getAttribute("evaluators");
            if (null != evaluatorTypes && 0 < evaluatorTypes.length()) {
                for (String name : evaluatorTypes.split(",")) {

                    final String factoryName = name;

                    AbstractEvaluatorFactory.instanceOf(ContextWrapper
                            .wrap(AbstractEvaluatorFactory.Context.class, context, new BaseContext() {
                                public String getEvaluatorFactoryClassName() {
                                    return factoryName;
                                }

                                public String getUniqueId() {
                                    return context.getUniqueId();
                                }
                            }, new QueryStringContext() {
                                public String getQueryString() {
                                    return "*";
                                }
                            }));
                }
            }

            readPredicates(root, globalPredicates, inheritedPredicates);

            // ruleList
            final NodeList ruleList = root.getElementsByTagName("rule");
            for (int i = 0; i < ruleList.getLength(); ++i) {

                final Element rule = (Element) ruleList.item(i);
                final String id = rule.getAttribute("id");
                final AnalysisRule analysisRule = new AnalysisRule();
                LOG.info(DEBUG_STARTING_RULE + id + " " + analysisRule);

                // private predicates
                final Map<String, Predicate> privatePredicates = new HashMap<String, Predicate>(
                        globalPredicates);

                readPredicates(rule, privatePredicates, inheritedPredicates);

                // scores
                final NodeList scores = rule.getElementsByTagName("score");
                for (int j = 0; j < scores.getLength(); ++j) {
                    final Element score = (Element) scores.item(j);
                    final String predicateName = score.getAttribute("predicate");
                    final Predicate predicate = findPredicate(predicateName, privatePredicates,
                            inheritedPredicates);
                    final int scoreValue = Integer.parseInt(score.getFirstChild().getNodeValue());

                    analysisRule.addPredicateScore(predicate, scoreValue);
                    final Map<Predicate, String> predicateToNameMap = new HashMap<Predicate, String>();
                    for (String key : inheritedPredicates.keySet()) {
                        predicateToNameMap.put(inheritedPredicates.get(key), key);
                    }
                    for (String key : privatePredicates.keySet()) {
                        predicateToNameMap.put(privatePredicates.get(key), key);
                    }
                    analysisRule.setPredicateNameMap(Collections.unmodifiableMap(predicateToNameMap));
                }
                try {
                    rulesLock.writeLock().lock();
                    rules.put(id, analysisRule);
                } finally {
                    rulesLock.writeLock().unlock();
                }
                LOG.info(DEBUG_FINISHED_RULE + id + " " + analysisRule);
            }
        }
        LOG.info("Parsing " + ANALYSIS_RULES_XMLFILE + " finished");
    }
    init = true;
}

From source file:org.ajax4jsf.webapp.tidy.TidyParser.java

public Document parseHtmlByTidy(Object input, Writer output) throws IOException {
    Document document = tidy.parseDOM(input, null);
    if (null != document) {
        Element documentElement = document.getDocumentElement();
        if (null != documentElement) {
            NodeVisitor nodeVisitor = new NodeVisitor();
            nodeVisitor.traverse(documentElement);
            // Replace state elements with real stored.

            List<org.w3c.dom.Node> viewStateSpans = nodeVisitor.viewStateSpans;
            for (org.w3c.dom.Node node : viewStateSpans) {
                // State marker - replace with real.
                org.w3c.dom.Node parentNode = node.getParentNode();
                if (null != _viewState) {
                    parentNode.replaceChild(document.createCDATASection(_viewState), node);
                } else {
                    // Remove marker element, but keep it content.
                    if (node.hasChildNodes()) {
                        org.w3c.dom.Node nextSibling = node.getNextSibling();
                        NodeList childNodes = node.getChildNodes();
                        // Copy all nodes by temporary array ( since
                        // moving nodes in iteration
                        // modify NodeList with side effects.
                        org.w3c.dom.Node[] childArray = new org.w3c.dom.Node[childNodes.getLength()];
                        for (int j = 0; j < childArray.length; j++) {
                            childArray[j] = childNodes.item(j);
                        }//from   w w w  .  j a  v a 2  s.  c om
                        for (int j = 0; j < childArray.length; j++) {
                            parentNode.insertBefore(childArray[j], nextSibling);
                        }
                    }
                    parentNode.removeChild(node);
                }
            }

            // Inserts scripts and styles to head.
            if ((null != headEvents && headEvents.length > 0) || null != _viewState) {
                // find head
                org.w3c.dom.Node head = nodeVisitor.head;
                // Insert empty if not found
                if (null == head) {
                    head = document.createElement("head");
                    documentElement.insertBefore(head, documentElement.getFirstChild());
                }
                org.w3c.dom.Node child = head.getFirstChild();
                while (child != null) {
                    if (child instanceof Element) {
                        String nodeName = ((Element) child).getNodeName();
                        if (!("title".equalsIgnoreCase(nodeName) || "base".equalsIgnoreCase(nodeName))) {
                            break;
                        }
                    }

                    child = child.getNextSibling();
                }

                if (headEvents != null) {
                    for (org.w3c.dom.Node node : headEvents) {
                        head.insertBefore(importNode(document, node, true), child);
                    }
                }
            }
        }

        if (null != output) {
            tidy.pprint(document, output);
        }
    }
    return document;
}

From source file:org.alfresco.repo.web.scripts.bean.ADMRemoteStore.java

/**
 * Creates multiple XML documents encapsulated in a single one. 
 * /*from   w  w  w .j  ava 2s. c  om*/
 * @param res       WebScriptResponse
 * @param store       String
 * @param in       XML document containing multiple document contents to write
 */
@Override
protected void createDocuments(WebScriptResponse res, String store, InputStream in) {
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document;
        document = documentBuilder.parse(in);
        Element docEl = document.getDocumentElement();
        Transformer transformer = ADMRemoteStore.this.transformer.get();
        for (Node n = docEl.getFirstChild(); n != null; n = n.getNextSibling()) {
            if (!(n instanceof Element)) {
                continue;
            }
            final String path = ((Element) n).getAttribute("path");

            // Turn the first element child into a document
            Document doc = documentBuilder.newDocument();
            Node child;
            for (child = n.getFirstChild(); child != null; child = child.getNextSibling()) {
                if (child instanceof Element) {
                    doc.appendChild(doc.importNode(child, true));
                    break;
                }
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream(512);
            transformer.transform(new DOMSource(doc), new StreamResult(out));
            out.close();

            writeDocument(path, new ByteArrayInputStream(out.toByteArray()));
        }
    } catch (AccessDeniedException ae) {
        res.setStatus(Status.STATUS_UNAUTHORIZED);
        throw ae;
    } catch (FileExistsException feeErr) {
        res.setStatus(Status.STATUS_CONFLICT);
        throw feeErr;
    } catch (Exception e) {
        // various annoying checked SAX/IO exceptions related to XML processing can be thrown
        // none of them should occur if the XML document is well formed
        logger.error(e);
        res.setStatus(Status.STATUS_INTERNAL_SERVER_ERROR);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    }
}

From source file:org.alfresco.web.forms.XSLTRenderingEngine.java

/**
 * Adds the specified parameters to the xsl template as variables within the 
 * alfresco namespace.//from   www .j  a  v  a2  s .c  om
 *
 * @param model the variables to place within the xsl template
 * @param xslTemplate the xsl template
 */
protected void addParameters(final Map<QName, Object> model, final Document xslTemplate) {
    final Element docEl = xslTemplate.getDocumentElement();
    final String XSL_NS = docEl.getNamespaceURI();
    final String XSL_NS_PREFIX = docEl.getPrefix();

    for (Map.Entry<QName, Object> e : model.entrySet()) {
        if (RenderingEngine.ROOT_NAMESPACE.equals(e.getKey())) {
            continue;
        }
        final Element el = xslTemplate.createElementNS(XSL_NS, XSL_NS_PREFIX + ":variable");
        el.setAttribute("name", e.getKey().toPrefixString());
        final Object o = e.getValue();
        if (o instanceof String || o instanceof Number || o instanceof Boolean) {
            el.appendChild(xslTemplate.createTextNode(o.toString()));
            docEl.insertBefore(el, docEl.getFirstChild());
        }
    }
}

From source file:org.apache.axis.handlers.MD5AttachHandler.java

public void invoke(MessageContext msgContext) throws AxisFault {
    log.debug("Enter: MD5AttachHandler::invoke");
    try {//ww  w .  jav  a 2  s . c  o m
        // log.debug("IN MD5");        
        Message msg = msgContext.getRequestMessage();
        SOAPConstants soapConstants = msgContext.getSOAPConstants();
        org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope();
        org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody();//env.getBodyByName("ns1", "addedfile");
        org.w3c.dom.Element sbElement = sbe.getAsDOM();
        //get the first level accessor  ie parameter
        org.w3c.dom.Node n = sbElement.getFirstChild();

        for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling())
            ;
        org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n;
        //Get the href associated with the attachment.
        String href = paramElement.getAttribute(soapConstants.getAttrHref());
        org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href);
        javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils
                .getActivationDataHandler(ap);
        org.w3c.dom.Node timeNode = paramElement.getFirstChild();
        long startTime = -1;

        if (timeNode != null && timeNode instanceof org.w3c.dom.Text) {
            String startTimeStr = ((org.w3c.dom.Text) timeNode).getData();

            startTime = Long.parseLong(startTimeStr);
        }
        // log.debug("GOTIT");

        long receivedTime = System.currentTimeMillis();
        long elapsedTime = -1;

        // log.debug("startTime=" + startTime);
        // log.debug("receivedTime=" + receivedTime);            
        if (startTime > 0)
            elapsedTime = receivedTime - startTime;
        String elapsedTimeStr = elapsedTime + "";
        // log.debug("elapsedTimeStr=" + elapsedTimeStr);            

        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        java.io.InputStream attachmentStream = dh.getInputStream();
        int bread = 0;
        byte[] buf = new byte[64 * 1024];

        do {
            bread = attachmentStream.read(buf);
            if (bread > 0) {
                md.update(buf, 0, bread);
            }
        } while (bread > -1);
        attachmentStream.close();
        buf = null;
        //Add the mime type to the digest.
        String contentType = dh.getContentType();

        if (contentType != null && contentType.length() != 0) {
            md.update(contentType.getBytes("US-ASCII"));
        }

        sbe = env.getFirstBody();
        sbElement = sbe.getAsDOM();
        //get the first level accessor  ie parameter
        n = sbElement.getFirstChild();
        for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling())
            ;
        paramElement = (org.w3c.dom.Element) n;
        // paramElement.setAttribute(soapConstants.getAttrHref(), respHref);
        String MD5String = org.apache.axis.encoding.Base64.encode(md.digest());
        String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String;

        // log.debug("senddata=" + senddata);            
        paramElement.appendChild(paramElement.getOwnerDocument().createTextNode(senddata));

        sbe = new org.apache.axis.message.SOAPBodyElement(sbElement);
        env.clearBody();
        env.addBodyElement(sbe);
        msg = new Message(env);

        msgContext.setResponseMessage(msg);
    } catch (Exception e) {
        log.error(Messages.getMessage("exception00"), e);
        throw AxisFault.makeFault(e);
    }

    log.debug("Exit: MD5AttachHandler::invoke");
}

From source file:org.apache.axis.message.MessageElement.java

protected String getValueDOM() {
    try {//from  ww  w  .  ja va 2  s . co m
        Element element = getAsDOM();
        if (element.hasChildNodes()) {
            Node node = element.getFirstChild();
            if (node.getNodeType() == Node.TEXT_NODE) {
                return node.getNodeValue();
            }
        }
    } catch (Exception t) {
        log.debug("getValue()", t);
    }
    return null;
}

From source file:org.apache.axis.utils.Admin.java

protected static Document processWSDD(MessageContext msgContext, AxisEngine engine, Element root)
        throws Exception {
    Document doc = null;/* ww  w .  j av a 2 s  . c  o  m*/

    String action = root.getLocalName();
    if (action.equals("passwd")) {
        String newPassword = root.getFirstChild().getNodeValue();
        engine.setAdminPassword(newPassword);
        doc = XMLUtils.newDocument();
        doc.appendChild(root = doc.createElementNS("", "Admin"));
        root.appendChild(doc.createTextNode(Messages.getMessage("done00")));
        return doc;
    }

    if (action.equals("quit")) {
        log.error(Messages.getMessage("quitRequest00"));
        if (msgContext != null) {
            // put a flag into message context so listener will exit after
            // sending response
            msgContext.setProperty(MessageContext.QUIT_REQUESTED, "true");
        }
        doc = XMLUtils.newDocument();
        doc.appendChild(root = doc.createElementNS("", "Admin"));
        root.appendChild(doc.createTextNode(Messages.getMessage("quit00", "")));
        return doc;
    }

    if (action.equals("list")) {
        return listConfig(engine);
    }

    if (action.equals("clientdeploy")) {
        // set engine to client engine
        engine = engine.getClientEngine();
    }

    WSDDDocument wsddDoc = new WSDDDocument(root);
    EngineConfiguration config = engine.getConfig();
    if (config instanceof WSDDEngineConfiguration) {
        WSDDDeployment deployment = ((WSDDEngineConfiguration) config).getDeployment();
        wsddDoc.deploy(deployment);
    }
    engine.refreshGlobalOptions();

    engine.saveConfiguration();

    doc = XMLUtils.newDocument();
    doc.appendChild(root = doc.createElementNS("", "Admin"));
    root.appendChild(doc.createTextNode(Messages.getMessage("done00")));

    return doc;
}

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Inserts the type fragment into the given wsdl document and ensures
 * that definitions from each embedded schema are allowed to reference
 * schema components from the other sibling schemas.
 * @param doc/* w w w.  j  a v a  2  s.com*/
 */
public void insertTypesFragment(Document doc) {

    updateNamespaces();

    if (wsdlTypesElem == null)
        return;

    // Make sure that definitions from each embedded schema are allowed
    // to reference schema components from the other sibling schemas.
    Element schemaElem = null;
    String tns = null;
    NodeList nl = wsdlTypesElem.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        NamedNodeMap attrs = nl.item(i).getAttributes();
        if (attrs == null)
            continue; // Should never happen.
        for (int n = 0; n < attrs.getLength(); n++) {
            Attr a = (Attr) attrs.item(n);
            if (a.getName().equals("targetNamespace")) {
                tns = a.getValue();
                schemaElem = (Element) nl.item(i);
                break;
            }
        }

        // Ignore what appears to be a not namespace-qualified
        // schema definition.
        if (tns != null && !"".equals(tns.trim())) {
            // By now we know that an import element might be necessary
            // for some sibling schemas. However, in the absence of
            // a symbol table proper, the best we can do is add one
            // for each sibling schema.
            Iterator it = schemaTypes.keySet().iterator();
            String otherTns;
            Element importElem;
            while (it.hasNext()) {
                if (!tns.equals(otherTns = (String) it.next())) {
                    importElem = docHolder.createElement("import");
                    importElem.setAttribute("namespace", otherTns);
                    schemaElem.insertBefore(importElem, schemaElem.getFirstChild());
                }
            }
        }
        schemaElem = null;
        tns = null;
    }

    // Import the wsdlTypesElement into the doc.
    org.w3c.dom.Node node = doc.importNode(wsdlTypesElem, true);
    // Insert the imported element at the beginning of the document
    doc.getDocumentElement().insertBefore(node, doc.getDocumentElement().getFirstChild());
}