Builds the proper exception and throws it.
@throws PageMigratedException always
772857
private void throwPageMigratedException(String msg, int code, int subcode, String userTitle, String userMsg) {
		// This SUCKS ASS.  Messages look like:
		// (#21) Page ID 114267748588304 was migrated to page ID 111013272313096.  Please update your API calls to the new ID

		Matcher matcher = ID_PATTERN.matcher(msg);

		long oldId = this.extractNextId(matcher, msg);
		long newId = this.extractNextId(matcher, msg);

		throw new PageMigratedException(msg, code, subcode, userTitle, userMsg, oldId, newId);
	}
33387
public function build()
    {
        if ($this->builded) {
            return;
        }

        $collection = $this->processFilter(false);

        $data = $collection->toArray();

        $this->prependRowSelectorColumn();
        $this->appendActionsColumn();

        Column::setOriginalGridModels($collection);

        $this->columns->map(function (Column $column) use (&$data) {
            $data = $column->fill($data);

            $this->columnNames[] = $column->getName();
        });

        $this->buildRows($data);

        $this->builded = true;
    }
1365617
private void actionWrite() throws PageException {
	if (output == null) throw new ApplicationException("attribute output is not defined for tag file");
	checkFile(pageContext, securityManager, file, serverPassword, createPath, true, false, true);
	if (file.exists()) {
	    // Error
	    if (nameconflict == NAMECONFLICT_ERROR) throw new ApplicationException("destination file [" + file + "] already exist");
	    // SKIP
	    else if (nameconflict == NAMECONFLICT_SKIP) return;
	    // OVERWRITE
	    else if (nameconflict == NAMECONFLICT_OVERWRITE) file.delete();
	}

	setACL(pageContext, file, acl);
	try {
	    if (output instanceof InputStream) {
		IOUtil.copy((InputStream) output, file, false);
	    }
	    else if (Decision.isCastableToBinary(output, false)) {
		IOUtil.copy(new ByteArrayInputStream(Caster.toBinary(output)), file, true);
	    }
	    else {
		String content = Caster.toString(output);
		if (fixnewline) content = doFixNewLine(content);
		if (addnewline) content += SystemUtil.getOSSpecificLineSeparator();

		IOUtil.write(file, content, CharsetUtil.toCharset(charset), false);

	    }
	}
	catch (UnsupportedEncodingException e) {
	    throw new ApplicationException("Unsupported Charset Definition [" + charset + "]", e.getMessage());
	}
	catch (IOException e) {

	    throw new ApplicationException("can't write file " + file.getAbsolutePath(), e.getMessage());
	}
	setMode(file, mode);
	setAttributes(file, attributes);
    }
1360611
@Override
    public int doStartTag() throws PageException {
	try {
	    _doStartTag();
	}
	catch (IOException e) {
	    throw Caster.toPageException(e);
	}
	return SKIP_BODY;
    }
1313459
void init() throws MpJwtProcessingException {
        String methodName = "init";
        if (tc.isDebugEnabled()) {
            Tr.entry(tc, methodName);
        }
        setUpJsseHelper();
        if (this.jsseHelper == null) {
            if (tc.isDebugEnabled()) {
                Tr.exit(tc, methodName);
            }
            return;
        }
        Properties sslProps = null;
        try {
            sslProps = getSslPropertiesFromJsseHelper();
        } catch (Exception e) {
            String msg = Tr.formatMessage(tc, "ERROR_LOADING_SSL_PROPS", new Object[] { e.getLocalizedMessage() });
            Tr.error(tc, msg);
            throw new MpJwtProcessingException(msg, e);
        }
        setKeystoreAndTruststoreNames(sslProps);
        if (tc.isDebugEnabled()) {
            Tr.exit(tc, methodName);
        }
    }
556524
@Override
    public int doEndTag() throws JspException {

        ServletRequest req = pageContext.getRequest();
        ServletResponse res = pageContext.getResponse();

        if (CmsFlexController.isCmsRequest(req)) {
            // this will always be true if the page is called through OpenCms
            CmsObject cms = CmsFlexController.getCmsObject(req);
            String target = null;

            // try to find out what to do
            if (m_target != null) {
                // option 1: target is set with "page" or "file" parameter
                target = m_target + getSuffix();
            } else if (m_property != null) {
                // option 2: target is set with "property" parameter
                try {
                    String prop = cms.readPropertyObject(cms.getRequestContext().getUri(), m_property, true).getValue();
                    if (prop != null) {
                        target = prop + getSuffix();
                    }
                } catch (RuntimeException e) {
                    // target must be null
                    target = null;
                } catch (Exception e) {
                    // target will be null
                    e = null;
                }
            } else if (m_attribute != null) {
                // option 3: target is set in "attribute" parameter
                try {
                    String attr = (String)req.getAttribute(m_attribute);
                    if (attr != null) {
                        target = attr + getSuffix();
                    }
                } catch (RuntimeException e) {
                    // target must be null
                    target = null;
                } catch (Exception e) {
                    // target will be null
                    e = null;
                }
            } else {
                // option 4: target might be set in body
                String body = null;
                if (getBodyContent() != null) {
                    body = getBodyContent().getString();
                    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(body)) {
                        // target IS set in body
                        target = body + getSuffix();
                    }
                    // else target is not set at all, default will be used
                }
            }

            // now perform the include action
            includeTagAction(
                pageContext,
                target,
                m_element,
                null,
                m_editable,
                m_cacheable,
                m_parameterMap,
                CmsRequestUtil.getAtrributeMap(req),
                req,
                res);

            release();
        }

        return EVAL_PAGE;
    }
732953
private void doGet() throws PageException {
	// "HKEY_LOCAL_MACHINE\\SOFTWARE\\Google\\NavClient","installtime"
	if (entry == null) throw new ApplicationException("attribute entry is required for tag registry, when action is [get]");
	if (variable == null) throw new ApplicationException("attribute variable is required for tag registry, when action is [get]");
	// if(type==-1)throw new ApplicationException("attribute type is required for tag registry, when
	// action is [get]");

	try {
	    RegistryEntry re = RegistryQuery.getValue(branch, entry, type);
	    if (re != null) pageContext.setVariable(variable, re.getValue());
	}
	catch (Exception e) {
	    throw Caster.toPageException(e);
	}

    }
250711
private void doGetDatasourceSetting() throws PageException {
	Struct sct = new StructImpl();
	pageContext.setVariable(getString("admin", action, "returnVariable"), sct);
	sct.set("psq", Caster.toBoolean(config.getPSQL()));
    }
578725
private Object init(Object[] arguments) throws PageException {
	object = Reflector.callConstructor(clazz, arguments);
	isInit = true;
	return object;
    }
50708
public void init(PageContext pageContext, ComponentPageImpl componentPage, boolean executeConstr) throws PageException {
	this.pageSource = componentPage.getPageSource();

	// extends
	if (!StringUtil.isEmpty(properties.extend)) {
	    base = ComponentLoader.searchComponent(pageContext, componentPage.getPageSource(), properties.extend, Boolean.TRUE, null, true, executeConstr);
	}
	else {
	    CIPage p = ((ConfigWebImpl) pageContext.getConfig()).getBaseComponentPage(pageSource.getDialect(), pageContext);
	    if (!componentPage.getPageSource().equals(p.getPageSource())) {
		base = ComponentLoader.loadComponent(pageContext, p, "Component", false, false, true, executeConstr);
	    }
	}

	if (base != null) {
	    this.dataMemberDefaultAccess = base.dataMemberDefaultAccess;
	    this._static = new StaticScope(base._static, this, componentPage, dataMemberDefaultAccess);
	    // this._triggerDataMember=base._triggerDataMember;
	    this.absFin = base.absFin;
	    _data = base._data;
	    _udfs = new HashMapPro<Key, UDF>(base._udfs);
	    setTop(this, base);
	}
	else {
	    this.dataMemberDefaultAccess = pageContext.getCurrentTemplateDialect() == CFMLEngine.DIALECT_CFML ? pageContext.getConfig().getComponentDataMemberDefaultAccess()
		    : Component.ACCESS_PRIVATE;
	    this._static = new StaticScope(null, this, componentPage, dataMemberDefaultAccess);
	    // TODO get per CFC setting
	    // this._triggerDataMember=pageContext.getConfig().getTriggerComponentDataMember();
	    _udfs = new HashMapPro<Key, UDF>();
	    _data = MapFactory.getConcurrentMap();
	}
	// implements
	if (!StringUtil.isEmpty(properties.implement)) {
	    if (absFin == null) absFin = new AbstractFinal();
	    absFin.add(InterfaceImpl.loadInterfaces(pageContext, getPageSource(), properties.implement));
	    // abstrCollection.implement(pageContext,getPageSource(),properties.implement);
	}

	/*
	 * print.e("--------------------------------------"); print.e(_getPageSource().getDisplayPath());
	 * print.e(abstrCollection.getUdfs());
	 */

	// scope
	useShadow = base == null ? (pageSource.getDialect() == CFMLEngine.DIALECT_CFML ? pageContext.getConfig().useComponentShadow() : false) : base.useShadow;
	if (useShadow) {
	    if (base == null) scope = new ComponentScopeShadow(this, MapFactory.getConcurrentMap());
	    else scope = new ComponentScopeShadow(this, (ComponentScopeShadow) base.scope, false);
	}
	else {
	    scope = new ComponentScopeThis(this);
	}
	initProperties();

	// invoke static constructor
	if (!componentPage._static.isInit()) {
	    componentPage._static.setInit(true);// this needs to happen before the call
	    try {
		componentPage.staticConstructor(pageContext, this);
	    }
	    catch (Throwable t) {
		ExceptionUtil.rethrowIfNecessary(t);
		componentPage._static.setInit(false);
		throw Caster.toPageException(t);
	    }
	}
    }
671668
public function assertCanCreateSitePage(
        SiteEntity $site,
        $pageName,
        $pageType
    ) {
        $allowDuplicates = $this->allowDuplicates($pageType);

        if ($allowDuplicates) {
            return;
        }

        $pageExists = $this->sitePageExists(
            $site,
            $pageName,
            $pageType
        );

        if (!$pageExists) {
            return;
        }

        throw new PageException(
            "Cannot create page: ({$pageName}). " .
            "Duplicate page names not allowed for name: ({$pageName}) type: ({$pageType}) siteId: " .
            '(' . $site->getSiteId() . ')'
        );
    }
402735
public void run() throws Exception {

        CmsObject cms = getCmsObject();
        String seoFilePath = cms.getRequestContext().getUri();
        CmsResource seoFile = cms.readResource(seoFilePath);
        m_configuration = new CmsXmlSeoConfiguration();
        m_configuration.load(cms, seoFile);
        String mode = m_configuration.getMode();
        if (mode.equals(CmsXmlSeoConfiguration.MODE_ROBOTS_TXT)) {
            showRobotsTxt();
        } else {
            boolean updateCache = Boolean.parseBoolean(getRequest().getParameter("updateCache"));
            String value = "";
            if (updateCache && m_configuration.usesCache()) {
                // update request, and caching is configured -> update the cache
                CmsXmlSitemapGenerator generator = prepareSitemapGenerator(seoFile, m_configuration);
                value = generator.renderSitemap();
                CmsXmlSitemapCache.INSTANCE.put(seoFile.getRootPath(), value);
            } else if (!updateCache && m_configuration.usesCache()) {
                // normal request, and caching is configured -> look in the cache first, and if not found, calculate sitemap and store it in cache
                String cachedValue = CmsXmlSitemapCache.INSTANCE.get(seoFile.getRootPath());
                if (cachedValue != null) {
                    value = cachedValue;
                } else {
                    CmsXmlSitemapGenerator generator = prepareSitemapGenerator(seoFile, m_configuration);
                    value = generator.renderSitemap();
                    CmsXmlSitemapCache.INSTANCE.put(seoFile.getRootPath(), value);
                }
            } else if (!updateCache && !m_configuration.usesCache()) {
                // normal request, caching is not configured -> always generate a fresh sitemap
                CmsXmlSitemapGenerator generator = prepareSitemapGenerator(seoFile, m_configuration);
                value = generator.renderSitemap();
            } else if (updateCache && !m_configuration.usesCache()) {
                // update request with no caching configured -> ignore
            }
            getResponse().getWriter().print(value);
        }

    }
1184810
public void doTag()
            throws JspException
    {
        // First look for the exception in the pageflow/struts request attribute.  If it's not there,
        // look for it in the request attribute the container provides for web.xml-configured error
        // pages.
        InternalStringBuilder results = new InternalStringBuilder(128);
        PageContext pageContext = getPageContext();
        Throwable e = (Throwable) pageContext.getAttribute(Globals.EXCEPTION_KEY, PageContext.REQUEST_SCOPE);

        if (e == null) {
            ServletRequest req = pageContext.getRequest();
            e = (Throwable) req.getAttribute("javax.servlet.error.exception");
            if (e == null) {
                e = (Throwable) req.getAttribute("javax.servlet.jsp.jspException");
            }
        }

        if (!_showStackTrace && _showDevModeStackTrace) {
            boolean devMode = !AdapterManager.getServletContainerAdapter(pageContext.getServletContext()).isInProductionMode();
            if (devMode)
                _showStackTrace = true;
        }

        if (e != null) {
            if (_showMessage) {
                String msg = e.getMessage();
                // if we have message lets output the exception name and the name of the
                if ((msg != null) && (msg.length() > 0)) {
                    if (!_showStackTrace)
                        msg = e.getClass().getName() + ": " + msg;
                    results.append(HtmlExceptionFormatter.format(msg, e, _showStackTrace));
                }
                else {
                    results.append(HtmlExceptionFormatter.format(e.getClass().getName(), e, _showStackTrace));
                }
            }
            else {
                results.append(HtmlExceptionFormatter.format(null, e, _showStackTrace));
            }
            ResponseUtils.write(pageContext, results.toString());
        }
    }
1209727
protected function execute()
    {
        $this->bootstrap();

        // get the migration path from the config
        $path = $this->getMigrationPath();

        if (!file_exists($path) && $this->getPrompter()->confirm('Create migrations directory?', true)) {
            mkdir($path, 0755, true);
        }

        $this->verifyMigrationDirectory($path);

        $config = $this->getConfig();
        $namespace = $config->getMigrationNamespaceByPath($path);

        $path = realpath($path);
        $className = $this->getArgument('name');

        if (!Util::isValidPhinxClassName($className)) {
            throw new \InvalidArgumentException(sprintf(
                'The migration class name "%s" is invalid. Please use CamelCase format.',
                $className
            ));
        }

        if (!Util::isUniqueMigrationClassName($className, $path)) {
            throw new \InvalidArgumentException(sprintf(
                'The migration class name "%s%s" already exists',
                $namespace ? ($namespace . '\\') : '',
                $className
            ));
        }

        // Compute the file path
        $fileName = Util::mapClassNameToFileName($className);
        $filePath = $path . DIRECTORY_SEPARATOR . $fileName;

        if (is_file($filePath)) {
            throw new \InvalidArgumentException(sprintf(
                'The file "%s" already exists',
                $filePath
            ));
        }

        // Get the alternative template and static class options from the config, but only allow one of them.
        $defaultAltTemplate = $this->getConfig()->getTemplateFile();
        $defaultCreationClassName = $this->getConfig()->getTemplateClass();
        if ($defaultAltTemplate && $defaultCreationClassName) {
            throw new \InvalidArgumentException('Cannot define template:class and template:file at the same time');
        }

        // Get the alternative template and static class options from the command line, but only allow one of them.
        $altTemplate = $this->getOption('template');
        $creationClassName = $this->getOption('class');
        if ($altTemplate && $creationClassName) {
            throw new \InvalidArgumentException('Cannot use --template and --class at the same time');
        }

        // If no commandline options then use the defaults.
        if (!$altTemplate && !$creationClassName) {
            $altTemplate = $defaultAltTemplate;
            $creationClassName = $defaultCreationClassName;
        }

        // Verify the alternative template file's existence.
        if ($altTemplate && !is_file($altTemplate)) {
            throw new \InvalidArgumentException(sprintf(
                'The alternative template file "%s" does not exist',
                $altTemplate
            ));
        }

        // Verify that the template creation class (or the aliased class) exists and that it implements the required interface.
        $aliasedClassName = null;
        if ($creationClassName) {
            // Supplied class does not exist, is it aliased?
            if (!class_exists($creationClassName)) {
                $aliasedClassName = $this->getConfig()->getAlias($creationClassName);
                if ($aliasedClassName && !class_exists($aliasedClassName)) {
                    throw new \InvalidArgumentException(sprintf(
                        'The class "%s" via the alias "%s" does not exist',
                        $aliasedClassName,
                        $creationClassName
                    ));
                }

                if (!$aliasedClassName) {
                    throw new \InvalidArgumentException(sprintf(
                        'The class "%s" does not exist',
                        $creationClassName
                    ));
                }
            }

            // Does the class implement the required interface?
            if (!$aliasedClassName && !is_subclass_of($creationClassName, self::CREATION_INTERFACE)) {
                throw new \InvalidArgumentException(sprintf(
                    'The class "%s" does not implement the required interface "%s"',
                    $creationClassName,
                    self::CREATION_INTERFACE
                ));
            }

            if ($aliasedClassName && !is_subclass_of($aliasedClassName, self::CREATION_INTERFACE)) {
                throw new \InvalidArgumentException(sprintf(
                    'The class "%s" via the alias "%s" does not implement the required interface "%s"',
                    $aliasedClassName,
                    $creationClassName,
                    self::CREATION_INTERFACE
                ));
            }
        }

        // Use the aliased class.
        $creationClassName = $aliasedClassName ?: $creationClassName;

        // Determine the appropriate mechanism to get the template
        if ($creationClassName) {
            // Get the template from the creation class
            /** @var CreationInterface $creationClass */
            $creationClass = new $creationClassName($this);
            $contents = $creationClass->getMigrationTemplate();
        } else {
            // Load the alternative template if it is defined.
            $contents = file_get_contents($altTemplate ?: $this->getMigrationTemplateFilename());
        }

        // inject the class names appropriate to this migration
        $classes = [
            '$namespaceDefinition' => null !== $namespace ? ('namespace ' . $namespace . ';') : '',
            '$namespace' => $namespace,
            '$useClassName' => $this->getConfig()->getMigrationBaseClassName(false),
            '$className' => $className,
            '$version' => Util::getVersionFromFileName($fileName),
            '$baseClassName' => $this->getConfig()->getMigrationBaseClassName(true),
        ];
        $contents = strtr($contents, $classes);

        if (false === file_put_contents($filePath, $contents)) {
            throw new \RuntimeException(sprintf(
                'The file "%s" could not be written to',
                $path
            ));
        }

        // Do we need to do the post creation call to the creation class?
        if (isset($creationClass)) {
            $creationClass->postMigrationCreation($filePath, $className,
                $this->getConfig()->getMigrationBaseClassName());
        }

        $output = $this->getOutput();
        $output->write('using migration base class ', 'info');
        $output->writeln($classes['$useClassName']);

        if (!empty($altTemplate)) {
            $output->write('using alternative template ', 'info');
            $output->writeln($altTemplate);
        } elseif (!empty($creationClassName)) {
            $output->write('using template creation class ', 'info');
            $output->writeln($creationClassName);
        } else {
            $output->writeln('using default template', 'info');
        }

        $output->write('created ', 'info');
        $output->writeln(str_replace(getcwd() . DIRECTORY_SEPARATOR, '', $filePath));
    }
767120
private void mergePageFiles() throws CmsXmlException, CmsImportExportException {

        try {
            // check if the template property exists. If not, create it.
            try {
                m_cms.readPropertyDefinition(CmsPropertyDefinition.PROPERTY_TEMPLATE);
            } catch (CmsException e) {
                // the template propertydefintion does not exist. So create it.
                m_cms.createPropertyDefinition(CmsPropertyDefinition.PROPERTY_TEMPLATE);
            }

            // copy all propertydefinitions of the old page to the new page
            List<CmsPropertyDefinition> definitions = m_cms.readAllPropertyDefinitions();

            Iterator<CmsPropertyDefinition> j = definitions.iterator();
            while (j.hasNext()) {
                CmsPropertyDefinition definition = j.next();
                // check if this propertydef already exits
                try {
                    m_cms.readPropertyDefinition(definition.getName());
                } catch (Exception e) {
                    m_cms.createPropertyDefinition(definition.getName());
                }
            }
        } catch (CmsException e) {

            CmsMessageContainer message = Messages.get().container(
                Messages.ERR_IMPORTEXPORT_ERROR_COPYING_PROPERTY_DEFINITIONS_0);
            if (LOG.isDebugEnabled()) {
                LOG.debug(message.key(), e);
            }

            throw new CmsImportExportException(message);
        }

        // iterate through the list of all page controlfiles found during the import process
        int size = m_pageStorage.size();
        m_report.println(Messages.get().container(Messages.RPT_MERGE_START_0), I_CmsReport.FORMAT_HEADLINE);
        Iterator<String> i = m_pageStorage.iterator();
        int counter = 1;
        while (i.hasNext()) {
            String resname = i.next();
            // adjust the resourcename if nescessary
            if (!resname.startsWith("/")) {
                resname = "/" + resname;
            }

            m_report.print(
                org.opencms.report.Messages.get().container(
                    org.opencms.report.Messages.RPT_SUCCESSION_2,
                    String.valueOf(counter),
                    String.valueOf(size)),
                I_CmsReport.FORMAT_NOTE);
            m_report.print(Messages.get().container(Messages.RPT_MERGE_0), I_CmsReport.FORMAT_NOTE);
            m_report.print(
                org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_ARGUMENT_1, resname));

            mergePageFile(resname);
            if (LOG.isInfoEnabled()) {
                LOG.info(
                    Messages.get().getBundle().key(
                        Messages.LOG_MERGING_3,
                        String.valueOf(counter),
                        String.valueOf(size),
                        resname));
            }

            counter++;

        }
        // free mem
        m_pageStorage.clear();

    }
10785
public function createPage(
        SiteEntity $site,
        $pageData,
        $publishPage = false,
        $doFlush = true
    ) {
        if (empty($pageData['createdByUserId'])) {
            throw new PageException('CreatedByUserId is required to create a page.');
        }
        if (empty($pageData['createdReason'])) {
            $pageData['createdReason'] = Tracking::UNKNOWN_REASON;
        }
        if (empty($pageData['author'])) {
            throw new PageException('Author is required to create a page.');
        }
        $revision = new Revision(
            $pageData['createdByUserId'],
            $pageData['createdReason']
        );
        $revision->setAuthor($pageData['author']);

        // we should not have an Id on page create
        unset($pageData['pageId']);

        $page = new PageEntity(
            $pageData['createdByUserId'],
            $pageData['createdReason']
        );
        $page->populate($pageData);

        $page->setSite($site);

        $this->assertCanCreateSitePage(
            $page->getSite(),
            $page->getName(),
            $page->getPageType()
        );

        if (!$publishPage) {
            $page->setStagedRevision($revision);
        } else {
            $page->setPublishedRevision($revision);
        }

        $page->addRevision($revision);

        $this->_em->persist($revision);
        $this->_em->persist($page);

        if ($doFlush) {
            $this->_em->flush(
                [
                    $revision,
                    $page
                ]
            );
        }

        return $page;
    }
345684
public void buildAndWrite() {

		try {
			RouterController routerController = RequestContextUtils
					.findWebApplicationContext(this.request)
					.getBean(RouterController.class);

			routerController.writeJsonResponse(this.request, this.response,
					this.extDirectResponse, this.jsonView);

		}
		catch (IOException e) {
			LogFactory.getLog(getClass()).error("buildAndWrite", e);
			throw new RuntimeException(e);
		}

	}