Process a single asset.

@param FileAssetInterface $asset
@param Request            $request
@param Response           $response
488743
protected function processAsset(FileAssetInterface $asset, Request $request, Response $response)
    {
        $url = $this->packages->getUrl($asset->getPath(), $asset->getPackageName());
        $asset->setUrl($url);

        if ($asset->getZone() !== Zone::get($request)) {
            return;
        }

        if ($asset->isLate()) {
            if ($asset->getLocation() === null) {
                $location = Target::END_OF_BODY;
            } else {
                $location = $asset->getLocation();
            }
        } elseif ($asset->getLocation() !== null) {
            $location = $asset->getLocation();
        } else {
            $location = Target::END_OF_HEAD;
        }

        $this->injector->inject($asset, $location, $response);
    }
597675
public function filterLoad(AssetInterface $asset)
    {
        $inputFile = tempnam(sys_get_temp_dir(), 'csso');

        file_put_contents($inputFile, $asset->getContent());

        // Before we create our process builder we'll create the arguments to be given to the builder.
        // If we have a node bin supplied then we'll shift that to the beginning of the array.
        $builderArguments = array($this->cssoBin);

        if ( ! is_null($this->nodeBin))
        {
            array_unshift($builderArguments, $this->nodeBin);
        }

        $builder = $this->createProcessBuilder($builderArguments);

        $builder->add($inputFile);

        // Get the process from the builder and run the process.
        $process = $builder->getProcess();

        $code = $process->run();

        unlink($inputFile);

        if ($code !== 0)
        {
            throw FilterException::fromProcess($process)->setInput($asset->getContent());
        }

        $asset->setContent($process->getOutput());
    }
1152782
function loadAsset(asset, callback) {
        callback = callback || noop;

        function error(event) {
            event = event || win.event;

            // release event listeners
            ele.onload = ele.onreadystatechange = ele.onerror = null;

            // do callback
            callback();

            // need some more detailed error handling here
        }

        function process(event) {
            event = event || win.event;

            // IE 7/8 (2 events on 1st load)
            // 1) event.type = readystatechange, s.readyState = loading
            // 2) event.type = readystatechange, s.readyState = loaded

            // IE 7/8 (1 event on reload)
            // 1) event.type = readystatechange, s.readyState = complete

            // event.type === 'readystatechange' && /loaded|complete/.test(s.readyState)

            // IE 9 (3 events on 1st load)
            // 1) event.type = readystatechange, s.readyState = loading
            // 2) event.type = readystatechange, s.readyState = loaded
            // 3) event.type = load            , s.readyState = loaded

            // IE 9 (2 events on reload)
            // 1) event.type = readystatechange, s.readyState = complete
            // 2) event.type = load            , s.readyState = complete

            // event.type === 'load'             && /loaded|complete/.test(s.readyState)
            // event.type === 'readystatechange' && /loaded|complete/.test(s.readyState)

            // IE 10 (3 events on 1st load)
            // 1) event.type = readystatechange, s.readyState = loading
            // 2) event.type = load            , s.readyState = complete
            // 3) event.type = readystatechange, s.readyState = loaded

            // IE 10 (3 events on reload)
            // 1) event.type = readystatechange, s.readyState = loaded
            // 2) event.type = load            , s.readyState = complete
            // 3) event.type = readystatechange, s.readyState = complete

            // event.type === 'load'             && /loaded|complete/.test(s.readyState)
            // event.type === 'readystatechange' && /complete/.test(s.readyState)

            // Other Browsers (1 event on 1st load)
            // 1) event.type = load, s.readyState = undefined

            // Other Browsers (1 event on reload)
            // 1) event.type = load, s.readyState = undefined

            // event.type == 'load' && s.readyState = undefined

            // !doc.documentMode is for IE6/7, IE8+ have documentMode
            if (event.type === "load" || (/loaded|complete/.test(ele.readyState) && (!doc.documentMode || doc.documentMode < 9))) {
                // remove timeouts
                win.clearTimeout(asset.errorTimeout);
                win.clearTimeout(asset.cssTimeout);

                // release event listeners
                ele.onload = ele.onreadystatechange = ele.onerror = null;

                // do callback   
                callback();
            }
        }

        function isCssLoaded() {
            // should we test again ? 20 retries = 5secs ..after that, the callback will be triggered by the error handler at 7secs
            if (asset.state !== LOADED && asset.cssRetries <= 20) {

                // loop through stylesheets
                for (var i = 0, l = doc.styleSheets.length; i < l; i++) {
                    // do we have a match ?
                    // we need to tests agains ele.href and not asset.url, because a local file will be assigned the full http path on a link element
                    if (doc.styleSheets[i].href === ele.href) {
                        process({ "type": "load" });
                        return;
                    }
                }

                // increment & try again
                asset.cssRetries++;
                asset.cssTimeout = win.setTimeout(isCssLoaded, 250);
            }
        }

        var ele;
        var ext = getExtension(asset.url);

        if (ext === "css") {
            ele      = doc.createElement("link");
            ele.type = "text/" + (asset.type || "css");
            ele.rel  = "stylesheet";
            ele.href = asset.url;

            /* onload supported for CSS on unsupported browsers
             * Safari windows 5.1.7, FF < 10
             */

            // Set counter to zero
            asset.cssRetries = 0;
            asset.cssTimeout = win.setTimeout(isCssLoaded, 500);         
        }
        else {
            ele      = doc.createElement("script");
            ele.type = "text/" + (asset.type || "javascript");
            ele.src = asset.url;
        }

        ele.onload  = ele.onreadystatechange = process;
        ele.onerror = error;

        /* Good read, but doesn't give much hope !
         * http://blog.getify.com/on-script-loaders/
         * http://www.nczonline.net/blog/2010/12/21/thoughts-on-script-loaders/
         * https://hacks.mozilla.org/2009/06/defer/
         */

        // ASYNC: load in parallel and execute as soon as possible
        ele.async = false;
        // DEFER: load in parallel but maintain execution order
        ele.defer = false;

        // timout for asset loading
        asset.errorTimeout = win.setTimeout(function () {
            error({ type: "timeout" });
        }, 7e3);

        // use insertBefore to keep IE from throwing Operation Aborted (thx Bryan Forbes!)
        var head = doc.head || doc.getElementsByTagName("head")[0];

        // but insert at end of head, because otherwise if it is a stylesheet, it will not override values      
        head.insertBefore(ele, head.lastChild);
    }
1159471
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);
        $code = $response->getStatusCode();
        $allowedCodes = array_keys($this->renderer) + array_keys($this->defaultErrors);
        if (in_array($code, $allowedCodes)) {
            if (!$response->getBody()->getSize()) {
                $format = FormatNegotiator::getPreferredFormat($request);

                if (isset($this->renderer[$code])) {
                    $content = $this->renderer[$code]($format);
                } else {
                    $content = $this->defaultRenderer($code, $format);
                }

                if (is_array($content)) {
                    $content = json_encode($content);
                }

                $body = $this->streamFactory->createStream($content);

                $response = $response->withBody($body);
                $response = $response->withStatus($code);

                if ($format === 'json') {
                    $response = $response->withHeader('content-type', 'application/json');
                } else {
                    $response = $response->withHeader('content-type', 'text/html; charset=utf-8');
                }
            }
        }

        return $response;
    }
668880
private void startAsset(final String path, final Asset asset) throws IOException {
        putNextEntry(outputStream, path, asset);
    }
28835
protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response) {
        parseRequest(request,
                     response);
        if (profile == null) {
            profile = _profileService.findProfile(request,
                                                  "jbpm");
        }
        Repository repository = profile.getRepository();
        if (!initialized) {
            try {
                initializeDefaultRepo(profile,
                                      repository,
                                      request);
                initialized = true;
            } catch (Exception e) {
                logger.error("Unable to initialize repository: " + e.getMessage());
            }
        }
        JSONObject returnJson = new JSONObject();
        try {
            Iterator<String> keys = requestParams.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
            }

            String cmd = (String) requestParams.get("cmd");
            if (cmd != null && cmd.equals("open")) {
                OpenCommand command = new OpenCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("mkdir")) {
                MakeDirCommand command = new MakeDirCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("mkfile")) {
                MakeFileCommand command = new MakeFileCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("rm")) {
                RemoveAssetCommand command = new RemoveAssetCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("rename")) {
                RenameCommand command = new RenameCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("paste")) {
                PasteCommand command = new PasteCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("upload")) {
                UploadCommand command = new UploadCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams,
                             listFiles,
                             listFileStreams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("getsvg")) {
                try {
                    Asset asset = profile.getRepository().loadAssetFromPath((String) requestParams.get("current"));
                    if (asset != null && asset.getAssetContent() != null) {
                        outputPlain(response,
                                    false,
                                    (String) asset.getAssetContent(),
                                    "image/svg+xml");
                    } else {
                        outputPlain(response,
                                    true,
                                    "<p><b>Process image not available.</p><p>You can generate the process image in the process editor.</b></p>",
                                    null);
                    }
                } catch (NoSuchFileException e) {
                    logger.warn("Error loading process image: " + e.getMessage());
                    outputPlain(response,
                                true,
                                "<p><b>Could not find process image.</p><p>You can generate the process image in the process editor.</b></p>",
                                null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            putResponse(returnJson,
                        "error",
                        e.getMessage());

            // output the error
            try {
                output(response,
                       false,
                       returnJson);
            } catch (Exception ee) {
                logger.error("",
                             ee);
            }
        }
    }
688331
function onAsset(output, asset) {
    var book = output.getBook();
    var options = output.getOptions();
    var bookFS = book.getContentFS();

    var outputFolder = options.get('root');
    var outputPath = path.resolve(outputFolder, asset);

    return fs.ensureFile(outputPath)
    .then(function() {
        return bookFS.readAsStream(asset)
        .then(function(stream) {
            return fs.writeStream(outputPath, stream);
        });
    })
    .thenResolve(output);
}
609868
public function viewAction(Request $request, SakonninFile $file, $access)
    {
        // TODO: Add access control.
        $path = $this->getFilePath();
        $response = new BinaryFileResponse($path . "/" . $file->getStoredAs());
        return $response;
    }
1105307
@Override
    protected void processNode(ArchivePath path, Node node) {
        // Get path to file
        final String assetFilePath = path.get();

        // Create a file for the asset
        final File assetFile = new File(outputDirectory, assetFilePath);

        // Get the assets parent parent directory and make sure it exists
        final File assetParent = assetFile.getParentFile();
        if (!assetParent.exists()) {
            if (!assetParent.mkdirs()) {
                throw new ArchiveExportException("Failed to write asset.  Unable to create parent directory.");
            }
        }

        // Handle Archive assets separately
        if (node != null && node.getAsset() instanceof ArchiveAsset) {
            ArchiveAsset nesteArchiveAsset = ArchiveAsset.class.cast(node.getAsset());
            processArchiveAsset(assetParent, nesteArchiveAsset);
            return;
        }

        // Handle directory assets separately
        try {
            final boolean isDirectory = (node.getAsset() == null);
            if (isDirectory) {
                // If doesn't already exist
                if (!assetFile.exists()) {
                    // Attempt a create
                    if (!assetFile.mkdirs()) {
                        // Some error in writing
                        throw new ArchiveExportException("Failed to write directory: " + assetFile.getAbsolutePath());
                    }
                }
            }
            // Only handle non-directory assets, otherwise the path is handled above
            else {
                try {
                    if (log.isLoggable(Level.FINE)) {
                        log.fine("Writing asset " + path.get() + " to " + assetFile.getAbsolutePath());
                    }
                    // Get the asset streams
                    final InputStream assetInputStream = node.getAsset().openStream();
                    final FileOutputStream assetFileOutputStream = new FileOutputStream(assetFile);
                    final BufferedOutputStream assetBufferedOutputStream = new BufferedOutputStream(
                        assetFileOutputStream, 8192);

                    // Write contents
                    IOUtil.copyWithClose(assetInputStream, assetBufferedOutputStream);
                } catch (final Exception e) {
                    // Provide a more detailed exception than the outer block
                    throw new ArchiveExportException("Failed to write asset " + path + " to " + assetFile, e);
                }
            }
        } catch (final Exception e) {
            throw new ArchiveExportException("Unexpected error encountered in export of " + node, e);
        }
    }
232494
private function parse_release_asset( $git, $request, $response ) {
		switch ( $git ) {
			case 'github':
				$download_link = isset( $response->assets[0] ) && ! is_wp_error( $response ) ? $response->assets[0]->browser_download_url : null;

				// Private repo.
				$response = ( null !== $download_link && ( property_exists( $this->type, 'is_private' ) && $this->type->is_private ) ) ? $response->assets[0]->url : $download_link;
				break;
			case 'bitbucket':
				$download_base = $this->get_api_url( $request, true );
				$response      = isset( $response->values[0] ) && ! is_wp_error( $response ) ? $download_base . '/' . $response->values[0]->name : null;
				break;
			case 'bbserver':
				// TODO: make work.
				break;
			case 'gitlab':
				$response = $this->get_api_url( $request );
				break;
			case 'gitea':
				break;
		}

		return $response;
	}
128866
private function handleRequest(RequestInterface $request, ResponseInterface $response): void
    {
        foreach ($this->routes as $route) {
            $routeMatch = $route->matches($request);

            if ($routeMatch === null) {
                continue;
            }

            $controllerClass = $routeMatch->getControllerClassName();
            $controller = new $controllerClass();

            /** @var ControllerInterface $controller */
            $controller->processRequest($this, $request, $response, $routeMatch->getAction(), $routeMatch->getParameters());

            return;
        }

        $response->setStatusCode(new StatusCode(StatusCode::NOT_FOUND));
    }
89893
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
	{
		if (($this->override || !$request->getParsedBody())
			&& \in_array($request->getMethod(), $this->methods, true)
		) {
			$contentType = \trim($request->getHeaderLine('Content-Type'));

			$parser = null;
			foreach ($this->parsers as $k => $v) {
				if (\stripos($k, $contentType) === 0) {
					$parser = $v;
					break;
				}
			}

			if ($parser !== null) {
				try {
					$data = $parser($request->getBody(), $contentType);

					if (isset($data['body'])) {
						$request = $request->withParsedBody($data['body']);
					}

					if (isset($data['files'])) {
						$request = $request->withUploadedFiles($data['files']);
					}
				} catch (\Exception $exception) {
					return Factory::response(400);
				}
			}
		}

		return $handler->handle($request);
	}
434302
protected function _deliverAsset(CakeResponse $response, $assetFile, $ext) {
		ob_start();
		$compressionEnabled = Configure::read('Asset.compress') && $response->compress();
		if ($response->type($ext) == $ext) {
			$contentType = 'application/octet-stream';
			$agent = env('HTTP_USER_AGENT');
			if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
				$contentType = 'application/octetstream';
			}
			$response->type($contentType);
		}
		if (!$compressionEnabled) {
			$response->header('Content-Length', filesize($assetFile));
		}
		$response->cache(filemtime($assetFile));
		$response->send();
		ob_clean();
		if ($ext === 'css' || $ext === 'js') {
			include $assetFile;
		} else {
			readfile($assetFile);
		}

		if ($compressionEnabled) {
			ob_end_flush();
		}
	}
684818
public function assetAction($path, $file, Request $request)
    {
        $filePath = $this->getAssetsDir() . '/' . $path . '/' . $file;

        if (!file_exists($filePath)) {
            return new Response($filePath . ' not found', 404);
        }

        $response = new Response();
        $response->setPublic();
        $response->headers->addCacheControlDirective('must-revalidate', true);

        $lastModified = filemtime($filePath);

        $response->setETag(md5($filePath . $lastModified));
        $response->setLastModified(new \DateTime('@' . $lastModified));

        if ($response->isNotModified($request)) {
            // return the 304 Response immediately
            return $response;
        }

        $mime = $this->getMime($filePath);
        if ($mime !== null) {
            $response->headers->set('Content-Type', $mime);
        }

        return $response->setContent(file_get_contents($filePath));
    }
1187462
public function resolveRequest(Request $request, $action = null)
    {
        $this->setDirPath($request->get('dir_path'));

        $this->setCurrentFile($this->getPath($this->getDirPath(), $request->get('filename'), true));

        if ($action === self::FILE_RENAME && !$this->getCurrentFile()->isDir()) {
            $extension = $this->getCurrentFile()->getExtension();
            $target_file = $request->get('target_file') . "." . $extension;
        } elseif ($action === self::FILE_PASTE) {

            $sources = $this->container->get('session')->get('copy');
            $this->setCurrentFile($sources['source_dir'] . FileManager::DS . $sources['source_file']);
            $target_file = $request->get('target_file') . FileManager::DS . $sources['source_file'];
        } else {
            $target_file = $request->get('target_file');
        }

        if (isset($target_file)) {
            $this->setTargetFile($target_file);
        }
    }
346834
public function filterLoad(AssetInterface $asset)
    {
        if ('' != ($sourceRoot = $asset->getSourceRoot()) && '' != ($sourcePath = $asset->getSourcePath())) {
            $input = $sourceRoot . '/' . $sourcePath;
            $remove = false;
        } else {
            $input = tempnam(sys_get_temp_dir(), 'assetic_jshint');
            file_put_contents($input, $asset->getContent());
            $remove = true;
        }

        $pb = $this->createProcessBuilder(array($this->jsHintBinary));
        $pb->add($input);
        $proc = $pb->getProcess();
        $code = $proc->run();

        if (true === $remove) {
            unlink($input);
        }

        if (0 !== $code) {
            throw FilterException::fromProcess($proc)->setInput($asset->getContent());
        }
    }
513127
public function tagAssetAction(Asset $asset, Tag $tag): void
    {
        $success = false;
        if ($asset->addTag($tag)) {
            $this->assetRepository->update($asset);
            $success = true;
        }
        $this->view->assign('value', $success);
    }