read source file

@throws PageException
962633
public void actionUpload() throws PageException {
	FormItem item = getFormItem(pageContext, filefield);
	Struct cffile = _actionUpload(pageContext, securityManager, item, strDestination, nameconflict, accept, strict, mode, attributes, acl, serverPassword);
	if (StringUtil.isEmpty(result)) {
	    pageContext.undefinedScope().set(KeyConstants._file, cffile);
	    pageContext.undefinedScope().set("cffile", cffile);
	}
	else {
	    pageContext.setVariable(result, cffile);
	}
    }
341958
@Override
    public InputStream read()
        throws EFapsException
    {
        StoreResourceInputStream in = null;
        ConnectionResource res = null;
        try {
            res = Context.getThreadContext().getConnectionResource();

            final Statement stmt = res.createStatement();
            final StringBuffer cmd = new StringBuffer()
                .append("select ").append(JDBCStoreResource.COLNAME_FILECONTENT).append(" ")
                .append("from ").append(JDBCStoreResource.TABLENAME_STORE).append(" ")
                .append("where ID =").append(getGeneralID());
            final ResultSet resultSet = stmt.executeQuery(cmd.toString());
            if (resultSet.next()) {
                if (Context.getDbType().supportsBinaryInputStream())  {
                    in = new JDBCStoreResourceInputStream(this,
                                                          res,
                                                          resultSet.getBinaryStream(1));
                } else  {
                    in = new JDBCStoreResourceInputStream(this,
                                                          res,
                                                          resultSet.getBlob(1));
                }
            }
            resultSet.close();
            stmt.close();
        } catch (final IOException e) {
            JDBCStoreResource.LOG.error("read of content failed", e);
            throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e);
        } catch (final SQLException e) {
            JDBCStoreResource.LOG.error("read of content failed", e);
            throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e);
        }
        return in;
    }
367492
private Source readSource(String xmlDocument, String features) throws Exception {
        if (xmlDocument.startsWith(Constants.Inputs.HTTP_PREFIX_STRING) || xmlDocument.startsWith(Constants.Inputs.HTTPS_PREFIX_STRING)) {
            URL xmlUrl = new URL(xmlDocument);
            InputStream xmlStream = xmlUrl.openStream();
            XmlUtils.parseXmlInputStream(xmlStream, features);
            return new StreamSource(xmlStream);
        } else {
            if (new File(xmlDocument).exists()) {
                XmlUtils.parseXmlFile(xmlDocument, features);
                return new StreamSource(new FileInputStream(xmlDocument));
            }
            XmlUtils.parseXmlString(xmlDocument, features);
            return new StreamSource(new StringReader(xmlDocument));

        }
    }
259339
@Override
    public InputStream read()
        throws EFapsException
    {
        StoreResourceInputStream in = null;
        try  {
            final FileObject file = this.manager.resolveFile(this.storeFileName + VFSStoreResource.EXTENSION_NORMAL);
            if (!file.isReadable())  {
                VFSStoreResource.LOG.error("file for " + this.storeFileName + " not readable");
                throw new EFapsException(VFSStoreResource.class, "#####file not readable");
            }
            in = new VFSStoreResourceInputStream(this, file);
        } catch (final FileSystemException e)  {
            VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e);
            throw new EFapsException(VFSStoreResource.class, "read.Throwable", e);
        } catch (final IOException e) {
            VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e);
            throw new EFapsException(VFSStoreResource.class, "read.Throwable", e);
        }
        return in;
    }
1355979
@Override
  public P readPage(int pageID) {
    try {
      countRead();
      return byteBufferToPage(this.file.getRecordBuffer(pageID));
    } catch (IOException e) {
      throw new RuntimeException("IOException occurred during reading of page " + pageID, e);
    }
  }
927764
protected void init() throws JspException {

        // initialize OpenCms access objects
        m_controller = CmsFlexController.getController(pageContext.getRequest());
        m_cms = m_controller.getCmsObject();

        try {
            // get the resource name from the selected container
            m_element = OpenCms.getADEManager().getCurrentElement(pageContext.getRequest());
            m_element.initResource(m_cms);
            if (m_cms.getRequestContext().getCurrentProject().isOnlineProject()
                && !m_element.isReleasedAndNotExpired()) {
                throw new CmsException(
                    Messages.get().container(
                        Messages.ERR_RESOURCE_IS_NOT_RELEASE_OR_EXPIRED_1,
                        m_element.getResource().getRootPath()));
            }
            if (m_locale == null) {
                // no locale set, use locale from users request context
                m_locale = m_cms.getRequestContext().getLocale();
            }

            // load content and store it
            CmsJspContentAccessBean bean;
            if ((m_element.isInMemoryOnly() || m_element.isTemporaryContent())
                && (m_element.getResource() instanceof CmsFile)) {
                I_CmsXmlDocument xmlContent = CmsXmlContentFactory.unmarshal(
                    m_cms,
                    m_element.getResource(),
                    pageContext.getRequest());
                bean = new CmsJspContentAccessBean(m_cms, m_locale, xmlContent);
            } else {
                bean = new CmsJspContentAccessBean(m_cms, m_locale, m_element.getResource());
            }
            storeAttribute(getVar(), bean);

            if (m_value != null) {
                // if the optional "val" parameter has been set, store the value map of the content in the page context scope
                storeAttribute(getVal(), bean.getValue());
            }

            if (m_rdfa != null) {
                // if the optional "rdfa" parameter has been set, store the rdfa map of the content in the page context scope
                storeAttribute(getRdfa(), bean.getRdfa());
            }

        } catch (CmsException e) {
            LOG.error(e.getLocalizedMessage(), e);
            m_controller.setThrowable(e, m_cms.getRequestContext().getUri());
            throw new JspException(e);
        }
    }
563729
private ProjectFile readFile(File file) throws MPXJException
   {
      try
      {
         String url = "jdbc:sqlite:" + file.getAbsolutePath();
         Properties props = new Properties();
         m_connection = org.sqlite.JDBC.createConnection(url, props);

         m_documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

         XPathFactory xPathfactory = XPathFactory.newInstance();
         XPath xpath = xPathfactory.newXPath();
         m_dayTimeIntervals = xpath.compile("/array/dayTimeInterval");
         m_entityMap = new HashMap<String, Integer>();
         return read();
      }

      catch (Exception ex)
      {
         throw new MPXJException(MPXJException.INVALID_FORMAT, ex);
      }

      finally
      {
         if (m_connection != null)
         {
            try
            {
               m_connection.close();
            }

            catch (SQLException ex)
            {
               // silently ignore exceptions when closing connection
            }
         }

         m_documentBuilder = null;
         m_dayTimeIntervals = null;
         m_entityMap = null;
      }
   }
707302
public function read() {
		
		$id = $this->getId();
		$path = $this->getPath($id);
		if (!is_readable($path)) {
			throw new Exception("Expected path $path is not readable");
		}

		return file_get_contents($path);
	}
1040030
static DataSource getDataSource(Object rawDataSource, PageContext pc)
            throws JspException {
	DataSource dataSource = null;

        if (rawDataSource == null) {
            rawDataSource = Config.find(pc, Config.SQL_DATA_SOURCE);
        }

	if (rawDataSource == null) {
	    return null;
	}

        /*
	 * If the 'dataSource' attribute's value resolves to a String
	 * after rtexpr/EL evaluation, use the string as JNDI path to
	 * a DataSource
	 */
        if (rawDataSource instanceof String) {
            try {
                Context ctx = new InitialContext();
                // relative to standard JNDI root for J2EE app
                Context envCtx = (Context) ctx.lookup("java:comp/env");
                dataSource = (DataSource) envCtx.lookup((String) rawDataSource);
            } catch (NamingException ex) {
                dataSource = getDataSource((String) rawDataSource);
            }
        } else if (rawDataSource instanceof DataSource) {
            dataSource = (DataSource) rawDataSource;
        } else {
	    throw new JspException(
                Resources.getMessage("SQL_DATASOURCE_INVALID_TYPE"));
	}

	return dataSource;
    }
593601
private void actionRead(boolean isBinary) throws PageException {

	if (variable == null) throw new ApplicationException("attribute variable is not defined for tag file");

	// check if we can use cache
	if (StringUtil.isEmpty(cachedWithin)) {
	    Object tmp = ((PageContextImpl) pageContext).getCachedWithin(ConfigWeb.CACHEDWITHIN_FILE);
	    if (tmp != null) setCachedwithin(tmp);
	}

	String cacheId = createCacheId(isBinary);
	CacheHandler cacheHandler = null;

	if (cachedWithin != null) {

	    cacheHandler = pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_FILE, null).getInstanceMatchingObject(cachedWithin, null);

	    if (cacheHandler instanceof CacheHandlerPro) {

		CacheItem cacheItem = ((CacheHandlerPro) cacheHandler).get(pageContext, cacheId, cachedWithin);

		if (cacheItem instanceof FileCacheItem) {
		    pageContext.setVariable(variable, ((FileCacheItem) cacheItem).getData());
		    return;
		}
	    }
	    else if (cacheHandler != null) { // TODO this else block can be removed when all cache handlers implement CacheHandlerPro

		CacheItem cacheItem = cacheHandler.get(pageContext, cacheId);

		if (cacheItem instanceof FileCacheItem) {
		    pageContext.setVariable(variable, ((FileCacheItem) cacheItem).getData());
		    return;
		}
	    }
	}

	// cache not found, process and cache result if needed
	checkFile(pageContext, securityManager, file, serverPassword, false, false, true, false);

	try {
	    long start = System.nanoTime();
	    Object data = isBinary ? IOUtil.toBytes(file) : IOUtil.toString(file, CharsetUtil.toCharset(charset));
	    pageContext.setVariable(variable, data);

	    if (cacheHandler != null) cacheHandler.set(pageContext, cacheId, cachedWithin, FileCacheItem.getInstance(file.getAbsolutePath(), data, System.nanoTime() - start));

	}
	catch (IOException e) {
	    throw new ApplicationException("can't read file [" + file.toString() + "]", e.getMessage());
	}
    }
144810
private ProjectFile readTextFile(InputStream inputStream) throws MPXJException
   {
      ProjectReader reader = new AstaTextFileReader();
      addListeners(reader);
      return reader.read(inputStream);
   }
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);
	    }
	}
    }
539650
def read_file():
    """"""
    path = request.args.get("path")
    start_line = int(request.args.get("start_line"))
    end_line = int(request.args.get("end_line"))

    start_line = max(1, start_line)  # make sure it's not negative

    try:
        highlight = json.loads(request.args.get("highlight", "true"))
    except Exception as e:
        if app.debug:
            print("Raising exception since debug is on")
            raise e

        else:
            highlight = (
                True
            )  # highlight argument was invalid for some reason, default to true

    if path and os.path.isfile(path):
        try:
            last_modified = os.path.getmtime(path)
            with open(path, "r") as f:
                raw_source_code_list = f.read().split("\n")
                num_lines_in_file = len(raw_source_code_list)
                end_line = min(
                    num_lines_in_file, end_line
                )  # make sure we don't try to go too far

                # if leading lines are '', then the lexer will strip them out, but we want
                # to preserve blank lines. Insert a space whenever we find a blank line.
                for i in range((start_line - 1), (end_line)):
                    if raw_source_code_list[i] == "":
                        raw_source_code_list[i] = " "
                raw_source_code_lines_of_interest = raw_source_code_list[
                    (start_line - 1) : (end_line)
                ]
            try:
                lexer = get_lexer_for_filename(path)
            except Exception:
                lexer = None

            if lexer and highlight:
                highlighted = True
                # convert string into tokens
                tokens = lexer.get_tokens("\n".join(raw_source_code_lines_of_interest))
                # format tokens into nice, marked up list of html
                formatter = (
                    htmllistformatter.HtmlListFormatter()
                )  # Don't add newlines after each line
                source_code = formatter.get_marked_up_list(tokens)
            else:
                highlighted = False
                source_code = raw_source_code_lines_of_interest

            return jsonify(
                {
                    "source_code_array": source_code,
                    "path": path,
                    "last_modified_unix_sec": last_modified,
                    "highlighted": highlighted,
                    "start_line": start_line,
                    "end_line": end_line,
                    "num_lines_in_file": num_lines_in_file,
                }
            )

        except Exception as e:
            return client_error({"message": "%s" % e})

    else:
        return client_error({"message": "File not found: %s" % path})
230171
public void readExternal(java.io.ObjectInput in) throws java.io.IOException, ClassNotFoundException
    {
        setContextPath((String)in.readObject());
        setVirtualHosts((String[])in.readObject());
        Object o= in.readObject();

        while (o instanceof HttpHandler)
        {
            addHandler((HttpHandler)o);
            o= in.readObject();
        }
        setAttributes((Map)o);
        setRedirectNullPath(in.readBoolean());
        setMaxCachedFileSize(in.readInt());
        setMaxCacheSize(in.readInt());
        setStatsOn(in.readBoolean());
        setPermissions((PermissionCollection)in.readObject());
        setClassLoaderJava2Compliant(in.readBoolean());

        _defaultsDescriptor= (String)in.readObject();
        _war= (String)in.readObject();
        _extract= in.readBoolean();
        _ignorewebjetty= in.readBoolean();
        _distributable= in.readBoolean();
        _configurationClassNames=(String[])in.readObject();
    }
256983
def read(files)
      files.map do |page|
        @unfiltered_content << Page.new(@site, @site.source, @dir, page)
      end
      @unfiltered_content.select { |page| site.publisher.publish?(page) }
    end
392013
public int read() throws IOException {
        if (end == endFilled) {
            switch (pages.read(endPageIdx, endFilled)) {
                case -1:
                    eof = true;
                    return Scanner.EOF;
                case 0:
                    endFilled = pages.getFilled(endPageIdx);
                    break;
                case 1:
                    endPageIdx++;
                    end = 0;
                    endPage = pages.get(endPageIdx);
                    endFilled = pages.getFilled(endPageIdx);
                    break;
                default:
                    throw new RuntimeException();
            }
        }
        return endPage[end++];
    }
1172725
private Page loadPhysical(PageContext pc, Page page) throws TemplateException {
	if (!mapping.hasPhysical()) return null;

	ConfigWeb config = pc.getConfig();
	PageContextImpl pci = (PageContextImpl) pc;
	if ((mapping.getInspectTemplate() == Config.INSPECT_NEVER || pci.isTrusted(page)) && isLoad(LOAD_PHYSICAL)) return page;
	Resource srcFile = getPhyscalFile();

	long srcLastModified = srcFile.lastModified();
	if (srcLastModified == 0L) return null;

	// Page exists
	if (page != null) {
	    // if(page!=null && !recompileAlways) {
	    if (srcLastModified != page.getSourceLastModified()) {

		// same size, maybe the content has not changed?
		boolean same = false;
		if (page instanceof PagePro && ((PagePro) page).getSourceLength() == srcFile.length()) {
		    PagePro pp = (PagePro) page;
		    try {
			same = pp.getHash() == PageSourceCode.toString(this, config.getTemplateCharset()).hashCode();
		    }
		    catch (IOException e) {/*
					    * in case this exception happen, the following compile process will fail as well and report the
					    * error
					    */}

		}
		if (!same) {
		    this.page = page = compile(config, mapping.getClassRootDirectory(), page, false, pc.ignoreScopes());
		    page.setPageSource(this);
		    page.setLoadType(LOAD_PHYSICAL);
		}
	    }

	}
	// page doesn't exist
	else {
	    Resource classRootDir = mapping.getClassRootDirectory();
	    Resource classFile = classRootDir.getRealResource(getJavaName() + ".class");
	    boolean isNew = false;
	    // new class
	    if (flush || !classFile.exists()) {
		this.page = page = compile(config, classRootDir, null, false, pc.ignoreScopes());
		flush = false;
		isNew = true;
	    }
	    // load page
	    else {
		try {
		    this.page = page = newInstance(mapping.getPhysicalClass(this.getClassName()));
		}
		catch (Throwable t) {
		    ExceptionUtil.rethrowIfNecessary(t);
		    this.page = page = null;
		}
		if (page == null) this.page = page = compile(config, classRootDir, null, false, pc.ignoreScopes());
	    }

	    // check if version changed or lasMod
	    if (!isNew && (srcLastModified != page.getSourceLastModified() || page.getVersion() != pc.getConfig().getFactory().getEngine().getInfo().getFullVersionInfo())) {
		isNew = true;
		this.page = page = compile(config, classRootDir, page, false, pc.ignoreScopes());
	    }
	    page.setPageSource(this);
	    page.setLoadType(LOAD_PHYSICAL);
	}
	pci.setPageUsed(page);
	return page;
    }