Example usage for java.text DateFormat SHORT

List of usage examples for java.text DateFormat SHORT

Introduction

In this page you can find the example usage for java.text DateFormat SHORT.

Prototype

int SHORT

To view the source code for java.text DateFormat SHORT.

Click Source Link

Document

Constant for short style pattern.

Usage

From source file:org.sakaiproject.news.tool.NewsAction.java

/**
 * build the context for the Main (Layout) panel
 * //from w w w .  j  av a2s.c  o m
 * @return (optional) template name for this panel
 */
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata,
        SessionState state) {
    context.put("tlang", rb);

    String mode = (String) state.getAttribute(STATE_MODE);
    if (MODE_OPTIONS.equals(mode)) {
        return buildOptionsPanelContext(portlet, context, rundata, state);
    }

    context.put(GRAPHIC_VERSION_TEXT, state.getAttribute(GRAPHIC_VERSION_TEXT));
    context.put(FULL_STORY_TEXT, state.getAttribute(FULL_STORY_TEXT));

    // build the menu
    Menu bar = new MenuImpl(portlet, rundata, (String) state.getAttribute(STATE_ACTION));

    // add options if allowed
    addOptionsMenu(bar, (JetspeedRunData) rundata);
    if (!bar.getItems().isEmpty()) {
        context.put(Menu.CONTEXT_MENU, bar);
    }

    context.put(Menu.CONTEXT_ACTION, state.getAttribute(STATE_ACTION));
    context.put(GRAPHIC_VERSION_TEXT, state.getAttribute(GRAPHIC_VERSION_TEXT));
    context.put(FULL_STORY_TEXT, state.getAttribute(FULL_STORY_TEXT));

    String url = (String) state.getAttribute(STATE_CHANNEL_URL);

    NewsChannel channel = null;
    List items = new Vector();

    try {
        channel = NewsService.getChannel(url);
        items = NewsService.getNewsitems(url);
    } catch (NewsConnectionException e) {
        // display message
        addAlert(state, rb.getFormattedMessage("unavailable", new Object[] { e.getLocalizedMessage() }));
        if (log.isDebugEnabled()) {
            log.debug(e);
        }
    } catch (NewsFormatException e) {
        // display message
        addAlert(state, rb.getFormattedMessage("unavailable", new Object[] { e.getLocalizedMessage() }));
        if (log.isDebugEnabled()) {
            log.debug(e);
        }
    } catch (Exception e) {
        // display message
        addAlert(state, rb.getFormattedMessage("unavailable", new Object[] { e.getLocalizedMessage() }));
        if (log.isDebugEnabled()) {
            log.debug(e);
        }
    }

    context.put("channel", channel);
    context.put("news_items", items);
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT,
            new ResourceLoader().getLocale());
    df.setTimeZone(TimeService.getLocalTimeZone());
    context.put("dateFormat", df);
    try {
        // tracking event
        if (state.getAttribute(FEED_ACCESS) == null) {
            if (state.getAttribute(STATE_DETECT_REGISTERED_EVENT) == null) {
                // is News tool
                EventTrackingService.post(EventTrackingService.newEvent(FEED_ACCESS,
                        "/news/site/"
                                + SiteService.getSite(ToolManager.getCurrentPlacement().getContext()).getId()
                                + "/placement/" + SessionManager.getCurrentToolSession().getPlacementId(),
                        false));
            }
        } else {
            // extends News tool
            EventTrackingService.post(EventTrackingService.newEvent((String) state.getAttribute(FEED_ACCESS),
                    "/news/site/" + SiteService.getSite(ToolManager.getCurrentPlacement().getContext()).getId()
                            + "/placement/" + SessionManager.getCurrentToolSession().getPlacementId(),
                    false));
        }

    } catch (IdUnusedException e) {
        //should NEVER actually happen
        if (Log.getLogger("chef").isDebugEnabled()) {
            Log.debug("chef", "failed to log news access event due to invalid siteId");
        }
    }

    return (String) getContext(rundata).get("template") + "-Layout";

}

From source file:org.opencms.i18n.CmsMessages.java

/**
 * Returns a formated date String from a Date value,
 * the format being {@link DateFormat#SHORT} and the locale
 * based on this instance.<p>/*from  www  .j a v a 2  s. c  om*/
 * 
 * @param date the Date object to format as String
 * @return the formatted date 
 */
public String getDate(Date date) {

    return CmsDateUtil.getDate(date, DateFormat.SHORT, m_locale);
}

From source file:com.nttec.everychan.ui.presentation.PresentationModel.java

/**
 * ?/*from ww  w.j ava  2  s  .c  om*/
 * @param source ?? ? -  {@link SerializablePage}
 * @param localTime ?,   ???  ?  (? true),  ? ??  (? false)
 * @param reduceNames ? true,  ?   (. ?)   ??
 * @param spanClickListener  ?? URL  ?, ??   ?,   ??  e-mail (mailto)
 * @param imageGetter  , ???  ? ? (, ?)
 * @param theme ? 
 * @param floatingModels ??    ?  ?.  ? - ? 
 * ,  - ? ? ?     (gif, , ). 
 * ?  null, ?    .
 */
public PresentationModel(SerializablePage source, boolean localTime, boolean reduceNames,
        URLSpanClickListener spanClickListener, ImageGetter imageGetter, Theme theme,
        FloatingModel[] floatingModels) {
    if (source.pageModel.type == UrlPageModel.TYPE_OTHERPAGE)
        throw new IllegalArgumentException();
    this.source = source;
    this.spanClickListener = spanClickListener;
    this.imageGetter = imageGetter;
    this.theme = theme;
    this.floatingModels = floatingModels;
    this.reduceNames = reduceNames;
    Database database = MainApplication.getInstance().database;
    this.isHiddenDelegate = source.pageModel.type == UrlPageModel.TYPE_THREADPAGE
            ? database.getCachedIsHiddenDelegate(source.pageModel.chanName, source.pageModel.boardName,
                    source.pageModel.threadNumber)
            : database.getDefaultIsHiddenDelegate();
    this.autohideRules = new ArrayList<AutohideActivity.CompiledAutohideRule>();
    try {
        JSONArray autohideJson = new JSONArray(MainApplication.getInstance().settings.getAutohideRulesJson());
        for (int i = 0; i < autohideJson.length(); ++i) {
            AutohideActivity.AutohideRule rule = AutohideActivity.AutohideRule
                    .fromJson(autohideJson.getJSONObject(i));
            if (rule.matches(source.pageModel.chanName, source.pageModel.boardName,
                    source.pageModel.threadNumber)) {
                this.autohideRules.add(new AutohideActivity.CompiledAutohideRule(rule));
            }
        }
    } catch (Exception e) {
        Logger.e(TAG, "error while processing regex autohide rules", e);
    }
    AndroidDateFormat.initPattern();
    String datePattern = AndroidDateFormat.getPattern();
    DateFormat dateFormat = datePattern == null
            ? DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
            : new SimpleDateFormat(datePattern, Locale.US);
    dateFormat.setTimeZone(
            localTime ? TimeZone.getDefault() : TimeZone.getTimeZone(source.boardModel.timeZoneId));
    this.dateFormat = dateFormat;
    this.size = getSerializablePageSize(source);
}

From source file:net.sf.housekeeper.swing.FoodEditorView.java

/**
 * Creates a JSpinner which uses the current locale's short format for
 * displaying a date. It's default date date is set to today's date.
 * /*  ww  w .  j a  v  a 2s .co  m*/
 * @return The created spinner.
 */
private JSpinner createDateSpinner() {
    final SpinnerDateModel model = new SpinnerDateModel();

    //Need to truncate the current date for correct spinner operation
    model.setStart(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH));
    model.setCalendarField(Calendar.DAY_OF_MONTH);

    final JSpinner spinner = new JSpinner(model);

    //Set the spinner's editor to use the current locale's short date
    // format
    final SimpleDateFormat dateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.SHORT);
    final String formatPattern = dateFormat.toPattern();
    spinner.setEditor(new JSpinner.DateEditor(spinner, formatPattern));

    return spinner;
}

From source file:op.FrmMain.java

public FrmMain() {
    initPhase = true;/*from w ww  .j a  v a 2  s. c o m*/
    initComponents();

    if (OPDE.isTraining()) {
        pnlMainMessage.setBackground(SYSConst.mediumorchid2.brighter().brighter());
    }

    //        pbTimeout.setToolTipText(SYSTools.xx("opde.mainframe.pbTimeout.tooltip"));
    // for the timeout function
    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
        @Override
        public void eventDispatched(AWTEvent event) {
            if (OPDE.getLogin() != null) {
                displayManager.touch();
            }
        }
    }, AWTEvent.MOUSE_MOTION_EVENT_MASK);

    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
        @Override
        public void eventDispatched(AWTEvent event) {
            if (OPDE.getLogin() != null) {
                displayManager.touch();
            }
        }
    }, AWTEvent.KEY_EVENT_MASK);

    currentVisiblePanel = null;
    currentResident = null;
    lblWait.setText(SYSTools.xx("misc.msg.wait"));
    lblWait.setVisible(false);
    listOfNursingrecords = new ArrayList<CollapsiblePane>();
    btnHelp.setToolTipText(SYSTools.xx("opde.mainframe.btnHelp.tooltip"));

    iconPanels = Collections.synchronizedMap(new HashMap<Resident, JPanel>());

    if (OPDE.isDebug()) {
        setSize(1366, 768);
    } else {
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
    }

    setTitle(SYSTools.getWindowTitle(""));

    displayManager = new DisplayManager(pbMsg, lblMainMsg, lblSubMsg, pnlIcons, pbTimeout, new Closure() {
        @Override
        public void execute(Object o) {
            OPDE.debug("TIMEOUT");
            logout();
            showLogin();
        }
    });
    displayManager.start();

    printProcessor = new PrintProcessor();
    printProcessor.start();

    // StatusBar Setup
    final LabelStatusBarItem label = new LabelStatusBarItem("Line");
    label.setText(OPDE.getUrl() + " [Build " + OPDE.getAppInfo().getBuildnum() + "]" + " [JVM "
            + System.getProperty("java.version") + "]");
    if (OPDE.isCustomUrl()) {
        label.setForeground(Color.RED);
    }
    label.setFont(new Font("Arial", Font.PLAIN, 14));
    statusBar.add(label, JideBoxLayout.FLEXIBLE);
    labelUSER = new LabelStatusBarItem("Line");
    labelUSER.setText("--");
    labelUSER.setAlignment(JLabel.CENTER);
    labelUSER.setFont(new Font("Arial", Font.PLAIN, 14));
    statusBar.add(labelUSER, JideBoxLayout.FLEXIBLE);
    final TimeStatusBarItem time = new TimeStatusBarItem();
    time.setFont(new Font("Arial", Font.PLAIN, 14));
    time.setUpdateInterval(10000);
    time.setTextFormat(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT));
    time.setAlignment(JLabel.CENTER);
    statusBar.add(time, JideBoxLayout.FLEXIBLE);
    final MemoryStatusBarItem gc = new MemoryStatusBarItem();
    gc.setFont(new Font("Arial", Font.PLAIN, 14));
    statusBar.add(gc, JideBoxLayout.FLEXIBLE);

    btnResetSplitpane.setToolTipText(SYSTools.xx("opde.mainframe.btnSplitReset.tooltip"));

    initPhase = false;

    //        JDialog dlg = new JDialog(this, false);
    //
    //        JPanel pnl = new JPanel();
    //        pnl.setLayout(new VerticalLayout());
    //
    //        for (float f = 0.0f; f <= 1.0; f = f + 0.01f){
    //            JLabel lbl = new JLabel(Float.toString(f));
    //            lbl.setForeground(GUITools.blend(Color.red, Color.WHITE, f));
    //            pnl.add(lbl);
    //        }
    //
    //        dlg.setContentPane(new JScrollPane(pnl));
    //
    //        dlg.pack();
    //        dlg.setVisible(true);

}

From source file:org.openregistry.core.service.DefaultPersonServiceIntegrationTests.java

/**
  * Test 2: Test of adding two new SoR Persons to an empty database (with no matches):
  * Expectations: 2 Sor Person rows/*  w  ww  .j a v  a 2  s .co m*/
  *               2 Calculated persons, two names, two identifiers
  */
@Test
public void testAddTwoDifferentPeople() throws ReconciliationException, SorPersonAlreadyExistsException {
    final ReconciliationCriteria reconciliationCriteria1 = constructReconciliationCriteria(RUDYARD, KIPLING,
            null, EMAIL_ADDRESS, PHONE_NUMBER, new Date(0), OR_WEBAPP_IDENTIFIER, null);
    final ServiceExecutionResult<Person> result1 = this.personService.addPerson(reconciliationCriteria1);

    final ReconciliationCriteria reconciliationCriteria2 = constructReconciliationCriteria("Foo", "Bar", null,
            "la@lao.com", "9085550987", new Date(0), OR_WEBAPP_IDENTIFIER, null);
    final ServiceExecutionResult<Person> result2 = this.personService.addPerson(reconciliationCriteria2);

    assertTrue(result2.succeeded());
    assertNotNull(result2.getTargetObject().getId());
    assertEquals(2, countRowsInTable("prc_persons"));
    assertEquals(2, countRowsInTable("prc_names"));
    assertEquals(2, countRowsInTable("prs_names"));
    assertEquals(2, countRowsInTable("prs_sor_persons"));

    final Person person2 = result2.getTargetObject();
    final SorPerson sorPerson2 = this.personService.findByPersonIdAndSorIdentifier(person2.getId(),
            OR_WEBAPP_IDENTIFIER);

    final Person person1 = result1.getTargetObject();
    final SorPerson sorPerson1 = this.personService.findByPersonIdAndSorIdentifier(person1.getId(),
            OR_WEBAPP_IDENTIFIER);

    // check birthdate is set correctly
    Date birthDate1 = this.simpleJdbcTemplate
            .queryForObject("select date_of_birth from prc_persons where id = ?", Date.class, person1.getId());
    DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT);
    assertEquals(formatter.format(birthDate1), formatter.format(person1.getDateOfBirth()));

    Date birthDate2 = this.simpleJdbcTemplate
            .queryForObject("select date_of_birth from prc_persons where id = ?", Date.class, person2.getId());
    assertEquals(formatter.format(birthDate2), formatter.format(person2.getDateOfBirth()));

    // check SOR source is set correctly
    String sourceSor1 = this.simpleJdbcTemplate.queryForObject(
            "select source_sor_id from prs_sor_persons where person_id = ?", String.class, person1.getId());
    assertEquals(sourceSor1, sorPerson1.getSourceSor());

    String sourceSor2 = this.simpleJdbcTemplate.queryForObject(
            "select source_sor_id from prs_sor_persons where person_id = ?", String.class, person2.getId());
    assertEquals(sourceSor2, sorPerson2.getSourceSor());

    // check names in prc_names
    String familyName1 = this.simpleJdbcTemplate.queryForObject(
            "select family_name from prc_names where person_id = ?", String.class, person1.getId());
    assertEquals(familyName1, KIPLING);

    String familyName2 = this.simpleJdbcTemplate.queryForObject(
            "select family_name from prc_names where person_id = ?", String.class, person2.getId());
    assertEquals(familyName2, "Bar");

    String givenName1 = this.simpleJdbcTemplate.queryForObject(
            "select given_name from prc_names where person_id = ?", String.class, person1.getId());
    assertEquals(givenName1, RUDYARD);

    String givenName2 = this.simpleJdbcTemplate.queryForObject(
            "select given_name from prc_names where person_id = ?", String.class, person2.getId());
    assertEquals(givenName2, "Foo");

    // check names in prs_names
    String prsFamilyName1 = this.simpleJdbcTemplate.queryForObject(
            "select family_name from prs_names where sor_person_id = ?", String.class, sorPerson1.getId());
    assertEquals(prsFamilyName1, KIPLING);

    String prsGivenName1 = this.simpleJdbcTemplate.queryForObject(
            "select given_name from prs_names where sor_person_id = ?", String.class, sorPerson1.getId());
    assertEquals(prsGivenName1, RUDYARD);

    String prsFamilyName2 = this.simpleJdbcTemplate.queryForObject(
            "select family_name from prs_names where sor_person_id = ?", String.class, sorPerson2.getId());
    assertEquals(prsFamilyName2, "Bar");

    String prsGivenName2 = this.simpleJdbcTemplate.queryForObject(
            "select given_name from prs_names where sor_person_id = ?", String.class, sorPerson2.getId());
    assertEquals(prsGivenName2, "Foo");

}

From source file:cz.zcu.kiv.eegdatabase.wui.ui.experiments.metadata.MetadataForm.java

public MetadataForm(String id, IModel<Section> model, final int experimentId) {
    super(id);/*from w  w  w . j  a  v a 2  s .co m*/

    this.model = new CompoundPropertyModel<Section>(model);
    setDefaultModel(this.model);
    setOutputMarkupId(true);

    wizardModel = new WizardModel();
    if (model.getObject() != null) {
        for (Section section : model.getObject().getSections()) {
            wizardModel.add(new MetadataWizardStep(new Model<Section>(section)));
        }
    } else {
        wizardModel.add(new WizardStep());
    }

    wizard = new Wizard("wizard", wizardModel, true) {

        private static final long serialVersionUID = 1L;

        @Override
        public void onFinish() {
            Section data = MetadataForm.this.model.getObject();
            Experiment experiment = expFacade.getExperimentForDetail(experimentId);
            experiment.getElasticExperiment().setMetadata(data);
            expFacade.update(experiment);
            setResponsePage(ExperimentsDetailPage.class,
                    PageParametersUtils.getDefaultPageParameters(experimentId));
        }

        @Override
        public void onCancel() {
            throw new RestartResponseAtInterceptPageException(MetadataForm.this.getPage().getPageClass(),
                    MetadataForm.this.getPage().getPageParameters());
        }

    };
    wizard.setOutputMarkupId(true);

    add(wizard.setVisible(model.getObject() != null));

    int personId = EEGDataBaseSession.get().getLoggedUser().getPersonId();
    List<Template> templatesByPerson = templateFacade.getTemplatesByPerson(personId);
    ChoiceRenderer<Template> templateChoiceRenderer = new ChoiceRenderer<Template>("name", "templateId");
    AjaxDropDownChoice<Template> templateSelection = new AjaxDropDownChoice<Template>("template-choice",
            new Model<Template>(), templatesByPerson, templateChoiceRenderer) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onSelectionChangeAjaxified(AjaxRequestTarget target, Template template) {

            try {
                Reader reader = new Reader();
                Section section = reader
                        .load(new ByteInputStream(template.getTemplate(), template.getTemplate().length));
                section.setName(template.getName());
                MetadataForm.this.model.setObject(section);

                wizardModel = new WizardModel();
                for (Section subsection : section.getSections()) {
                    wizardModel.add(new MetadataWizardStep(new Model<Section>(subsection)));
                }

                Wizard wiz = new Wizard("wizard", wizardModel, true) {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public void onFinish() {
                        Section data = MetadataForm.this.model.getObject();
                        Experiment experiment = expFacade.getExperimentForDetail(experimentId);
                        experiment.getElasticExperiment().setMetadata(data);
                        expFacade.update(experiment);
                        setResponsePage(ExperimentsDetailPage.class,
                                PageParametersUtils.getDefaultPageParameters(experimentId));
                    }

                    @Override
                    public void onCancel() {
                        throw new RestartResponseAtInterceptPageException(
                                MetadataForm.this.getPage().getPageClass(),
                                MetadataForm.this.getPage().getPageParameters());
                    }

                };

                wizard = (Wizard) wizard.replaceWith(wiz);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                error(ResourceUtils.getString("text.template.error.load"));
            }

            target.add(MetadataForm.this);
        }

    };

    add(templateSelection);

    AjaxLink<Void> saveAsTemplate = new AjaxLink<Void>("saveAsTemplate") {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {

            Section section = MetadataForm.this.model.getObject();
            String templateName = section.getName() != null ? section.getName() + "-savedFromWizard"
                    : "Template-savedFromWizard";
            Date now = new Date();
            templateName += "-"
                    + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now);

            Writer writer = new Writer(section, true, true);
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

            if (writer.write(byteStream)) {

                Template template = new Template();
                byte[] templateXML = byteStream.toByteArray();

                template.setTemplate(templateXML);
                template.setName(templateName);
                template.setPersonByPersonId(EEGDataBaseSession.get().getLoggedUser());
                templateFacade.create(template);

                setResponsePage(ListTemplatePage.class);
            } else {
                error(ResourceUtils.getString("text.template.error.save"));
            }
        }
    };

    add(saveAsTemplate);
}

From source file:org.mifos.framework.util.helpers.DateUtils.java

public static String getCurrentDate(Locale locale) throws InvalidDateException {
    // the following line is for 1.1 release and will be removed when date
    // is localized
    locale = internalLocale;//from  w w  w .ja  v  a  2 s. c  om
    Calendar currentCalendar = getCurrentDateCalendar();
    java.sql.Date currentDate = new java.sql.Date(currentCalendar.getTimeInMillis());
    SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
    String userfmt = convertToCurrentDateFormat(format.toPattern());
    return convertDbToUserFmt(currentDate.toString(), userfmt);
}

From source file:org.gridgain.grid.tools.license.GridLicenseGeneratorV2.java

/**
 * Gets arguments map from program arguments.
 *
 * @param args Program arguments.//from w w  w. j ava  2s  .c  o m
 * @return Arguments map.
 * @throws GridException If any program argument is invalid.
 */
private static Map<String, String> getArgumentsMap(String[] args) throws GridException {
    assert args != null;

    Map<String, String> map = new HashMap<String, String>();

    // Put defaults in (EVAL license).
    map.put("type", "EVL");
    map.put("issue-org", "GridGain Systems");
    map.put("user-org", "GridGain Evaluation");
    map.put("license-note", "Internal Evaluation Only");
    map.put("issue-date", DateFormat.getDateInstance(DateFormat.SHORT, Locale.US).format(new Date()));
    map.put("maintenance-time", "12");
    map.put("max-nodes", "3");
    map.put("max-cpus", "12");

    if (!F.isEmpty(args)) {
        Collection<String> usedKeys = new HashSet<String>();

        for (String s : args) {
            int idx = s.indexOf(SEPARATOR);

            if (idx <= 0)
                throw new GridException("Invalid key-value argument [arg=" + s + "]");

            String key = s.substring(0, idx);

            if (!params.containsKey(key))
                throw new GridException("Unknown argument: " + key);

            if (usedKeys.contains(key))
                throw new GridException("Duplicate argument: " + key);

            usedKeys.add(key);

            String val = s.substring(idx + 1);

            if (val.isEmpty())
                throw new GridException("Argument value can't be empty [key=" + key + "]");

            map.put(key, val);
        }
    }

    return map;
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageWritable.java

/**
 * Writes the template to the specified Writer
 *
 * @param out The Writer to write to, normally the HttpServletResponse
 * @return Returns the passed Writer/*from  w  ww.j  a  v a 2s.c  om*/
 * @throws IOException
 */
public Writer writeTo(Writer out) throws IOException {
    if (showSource) {
        // Set it to TEXT
        response.setContentType(GROOVY_SOURCE_CONTENT_TYPE); // must come before response.getOutputStream()
        writeGroovySourceToResponse(metaInfo, out);
    } else {
        // Set it to HTML by default
        if (metaInfo.getCompilationException() != null) {
            throw metaInfo.getCompilationException();
        }

        // Set up the script context
        GroovyPageBinding parentBinding = null;
        boolean hasRequest = request != null;
        boolean newParentCreated = false;

        if (hasRequest) {
            parentBinding = (GroovyPageBinding) request.getAttribute(GrailsApplicationAttributes.PAGE_SCOPE);
            if (parentBinding == null) {
                if (webRequest != null) {
                    parentBinding = new GroovyPageBinding(new GroovyPageRequestBinding(webRequest));
                    parentBinding.setRoot(true);
                    newParentCreated = true;
                }
            }
        }

        if (allowSettingContentType && response != null) {
            // only try to set content type when evaluating top level GSP
            boolean contentTypeAlreadySet = response.isCommitted() || response.getContentType() != null;
            if (!contentTypeAlreadySet) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Writing response to [" + response.getClass() + "] with content type: "
                            + metaInfo.getContentType());
                }
                response.setContentType(metaInfo.getContentType()); // must come before response.getWriter()
            }
        }

        GroovyPageBinding binding = createBinding(parentBinding);
        String previousGspCode = GSP_NONE_CODEC_NAME;
        if (hasRequest) {
            request.setAttribute(GrailsApplicationAttributes.PAGE_SCOPE, binding);
            previousGspCode = (String) request.getAttribute(GrailsApplicationAttributes.GSP_CODEC);
        }

        makeLegacyCodecVariablesAvailable(hasRequest, binding);

        binding.setVariableDirectly(GroovyPage.RESPONSE, response);
        binding.setVariableDirectly(GroovyPage.REQUEST, request);
        // support development mode's evaluate (so that doesn't search for missing variable in parent bindings)

        GroovyPage page = null;
        try {
            page = (GroovyPage) metaInfo.getPageClass().newInstance();
        } catch (Exception e) {
            throw new GroovyPagesException("Problem instantiating page class", e);
        }
        page.setBinding(binding);
        binding.setOwner(page);

        page.initRun(out, webRequest, metaInfo);

        int debugId = 0;
        long debugStartTimeMs = 0;
        if (debugTemplates) {
            debugId = debugTemplatesIdCounter.incrementAndGet();
            out.write("<!-- GSP #");
            out.write(String.valueOf(debugId));
            out.write(" START template: ");
            out.write(page.getGroovyPageFileName());
            out.write(" precompiled: ");
            out.write(String.valueOf(metaInfo.isPrecompiledMode()));
            out.write(" lastmodified: ");
            out.write(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                    .format(new Date(metaInfo.getLastModified())));
            out.write(" -->");
            debugStartTimeMs = System.currentTimeMillis();
        }
        try {
            page.run();
        } finally {
            page.cleanup();
            if (hasRequest) {
                if (newParentCreated) {
                    request.removeAttribute(GrailsApplicationAttributes.PAGE_SCOPE);
                } else {
                    request.setAttribute(GrailsApplicationAttributes.PAGE_SCOPE, parentBinding);
                }
                request.setAttribute(GrailsApplicationAttributes.GSP_CODEC,
                        previousGspCode != null ? previousGspCode : GSP_NONE_CODEC_NAME);
            }
        }
        if (debugTemplates) {
            out.write("<!-- GSP #");
            out.write(String.valueOf(debugId));
            out.write(" END template: ");
            out.write(page.getGroovyPageFileName());
            out.write(" rendering time: ");
            out.write(String.valueOf(System.currentTimeMillis() - debugStartTimeMs));
            out.write(" ms -->");
        }
    }
    return out;
}