This method is overloaded so that the final target points to a URI using S3 protocol

{@inheritdoc}
489295
protected function getFinalTarget($uploadData)
    {
        // We cannot upload without a bucket
        if (null === $this->options['bucket']) {
            throw new MissingBucketException('No bucket was set when trying to upload a file to S3');
        }

        // Get the tmp file name and convert it to an S3 key
        $key = trim(str_replace('\\', '/', parent::getFinalTarget($uploadData)), '/');
        if (strpos($key, './') === 0) {
            $key = substr($key, 2);
        }

        return "s3://{$this->options['bucket']}/{$key}";
    }
608675
function handleResource( $tpl, &$resourceData, $method, &$extraParameters )
    {
        return $this->handleResourceData( $tpl, $this, $resourceData, $method, $extraParameters );
    }
708643
@Override
	protected Promise call(String name, Tree params, Options opts, PacketStream stream, Context parent, String targetID,
			int remaining) {
		EndpointKey endpointKey = null;
		ErrorCounter errorCounter = null;
		try {

			// Get the first recommended Endpoint and Error Counter
			ActionEndpoint action = (ActionEndpoint) serviceRegistry.getAction(name, targetID);
			String nodeID = action.getNodeID();
			endpointKey = new EndpointKey(nodeID, name);
			errorCounter = getErrorCounter(endpointKey);

			// Check availability of the Endpoint (if endpoint isn't targetted)
			if (targetID == null) {
				LinkedHashSet<String> nodeIDs = new LinkedHashSet<>(maxSameNodes * 2);
				int sameNodeCounter = 0;
				long now;
				if (errorCounter == null) {
					now = 0;
				} else {
					now = System.currentTimeMillis();
				}
				for (int i = 0; i < maxTries; i++) {
					if (errorCounter == null || errorCounter.isAvailable(now)) {

						// Endpoint is available
						break;
					}
					
					// Store nodeID
					if (!nodeIDs.add(nodeID)) {
						sameNodeCounter++;
						if (sameNodeCounter >= maxSameNodes) {

							// The "maxSameNodes" limit is reached
							break;
						}
					}

					// Try to choose another endpoint
					action = (ActionEndpoint) serviceRegistry.getAction(name, null);
					nodeID = action.getNodeID();
					endpointKey = new EndpointKey(nodeID, name);
					errorCounter = getErrorCounter(endpointKey);
				}
			}

			// Create new Context
			Context ctx = contextFactory.create(name, params, opts, stream, parent);

			// Invoke Endpoint
			final ErrorCounter currentCounter = errorCounter;
			final EndpointKey currentKey = endpointKey;
			return Promise.resolve(action.handler(ctx)).then(rsp -> {

				// Reset error counter
				if (currentCounter != null) {
					currentCounter.reset();
				}

				// Return response
				return rsp;

			}).catchError(cause -> {

				// Increment error counter
				increment(currentCounter, currentKey, cause, System.currentTimeMillis());

				// Retry
				return retry(cause, name, params, opts, stream, parent, targetID, remaining);
			});

		} catch (Throwable cause) {

			// Increment error counter
			increment(errorCounter, endpointKey, cause, System.currentTimeMillis());

			// Retry
			return retry(cause, name, params, opts, stream, parent, targetID, remaining);
		}
	}
211813
S3Response invoke(@Nullable String bucket, @Nullable String object, @Nullable String temporaryEndpoint) throws S3Exception, CloudException, InternalException {
        if( wire.isDebugEnabled() ) {
            wire.debug("");
            wire.debug("----------------------------------------------------------------------------------");
        }
        HttpClient client = null;
        boolean leaveOpen = false;
        try {
            StringBuilder url = new StringBuilder();
            HttpRequestBase method;
            int status;

            // Sanitise the parameters as they may have spaces and who knows what else
            if( bucket != null ) {
                bucket = AWSCloud.encode(bucket, false);
            }
            if( object != null && !"?location".equalsIgnoreCase( object ) && !"?acl".equalsIgnoreCase( object ) && !"?tagging".equalsIgnoreCase( object )) {
                object = AWSCloud.encode(object, false);
            }
            if( temporaryEndpoint != null ) {
                temporaryEndpoint = AWSCloud.encode(temporaryEndpoint, false);
            }
            if( provider.getEC2Provider().isAWS() ) {
                url.append("https://");
                String regionId = provider.getContext().getRegionId();

                if( temporaryEndpoint == null ) {
                    boolean validDomainName = isValidDomainName(bucket);

                    if( bucket != null && validDomainName ) {
                        url.append(bucket);
                        if (regionId != null && !regionId.isEmpty() && !"us-east-1".equals(regionId)) {
                            url.append(".s3-");
                            url.append(regionId);
                            url.append(AWSCloud.getRegionSuffix(regionId) + "/");
                        }
                        else {
                            url.append(".s3" + AWSCloud.getRegionSuffix(provider.getContext().getRegionId()) + "/");
                        }
                    }
                    else {
                        if (regionId != null && !regionId.isEmpty() && !"us-east-1".equals(regionId)) {
                            url.append("s3-");
                            url.append(regionId);
                            url.append(AWSCloud.getRegionSuffix(regionId) + "/");
                        }
                        else {
                            url.append("s3" + AWSCloud.getRegionSuffix(provider.getContext().getRegionId()) + "/");
                        }
                    }
                    if ( bucket != null && !validDomainName) {
                        url.append(bucket);
                        url.append("/");
                    }
                }
                else {
                    url.append(temporaryEndpoint);
                    url.append("/");
                }
            }
            else if( provider.getEC2Provider().isStorage() && "google".equalsIgnoreCase(provider.getProviderName()) ) {
                url.append("https://");
                if( temporaryEndpoint == null ) {
                    if( bucket != null ) {
                        url.append(bucket);
                        url.append(".");
                    }
                    url.append("commondatastorage.googleapis.com/");
                }
                else {
                    url.append(temporaryEndpoint);
                    url.append("/");
                }
            }
            else {
                int idx = 0;
                
                if( !provider.getContext().getEndpoint().startsWith("http") ) {
                    url.append("https://");
                }
                else {
                    idx = provider.getContext().getEndpoint().indexOf("https://");
                    if( idx == -1 ) {
                        idx = "http://".length();
                        url.append("http://");
                    }
                    else {
                        idx = "https://".length();
                        url.append("https://");
                    }
                }
                String service = "";
                if( provider.getEC2Provider().isEucalyptus() ) {
                    service = "Walrus/";
                }

                if( temporaryEndpoint == null ) {
                    url.append(provider.getContext().getEndpoint().substring(idx));
                    if( !provider.getContext().getEndpoint().endsWith("/") ) {
                        url.append("/").append(service);
                    }
                    else {
                        url.append(service);
                    }
                }
                else {
                    url.append(temporaryEndpoint);
                    url.append("/");
                    url.append(service);
                }
                if( bucket != null ) {
                    url.append(bucket);
                    url.append("/");
                }
            }
            if( object != null ) {
                url.append(object);
            }
            else if( parameters != null ) {
                boolean first = true;

                if( object != null && object.indexOf('?') != -1 ) {
                    first = false;
                }
                for( Map.Entry<String,String> entry : parameters.entrySet() ) {
                    String key = entry.getKey();
                    String val = entry.getValue();

                    if( first ) {
                        url.append("?");
                        first = false;
                    }
                    else {
                        url.append("&");
                    }
                    if( val != null ) {
                        url.append(AWSCloud.encode(key, false));
                        url.append("=");
                        url.append(AWSCloud.encode(val, false));
                    }
                    else {
                        url.append(AWSCloud.encode(key, false));
                    }
                }
            }

            if( provider.getEC2Provider().isStorage() && provider.getProviderName().equalsIgnoreCase("Google") ) {
                headers.put(AWSCloud.P_GOOG_DATE, getDate());
            }
            else {
                headers.put(AWSCloud.P_AWS_DATE, provider.getV4HeaderDate(null));
            }
            if( contentType == null && body != null ) {
                contentType = "application/xml";
                headers.put("Content-Type", contentType);
            }
            else if( contentType != null ) {
                headers.put("Content-Type", contentType);
            }

            method = action.getMethod(url.toString());
            String host = method.getURI().getHost();
            headers.put("host", host);

            if(action.equals(S3Action.PUT_BUCKET_TAG))
            	try {
            		headers.put("Content-MD5", toBase64(computeMD5Hash(body)));
            	} catch (NoSuchAlgorithmException e) {
            		logger.error(e);
            	} catch (IOException e) {
            		logger.error(e);
            	}
            
            if( headers != null ) {
                for( Map.Entry<String, String> entry : headers.entrySet() ) {
                    method.addHeader(entry.getKey(), entry.getValue());
                }
            }

            if( body != null ) {
                ((HttpEntityEnclosingRequestBase)method).setEntity(new StringEntity(body, APPLICATION_XML));
            }
            else if( uploadFile != null ) {
                ((HttpEntityEnclosingRequestBase)method).setEntity(new FileEntity(uploadFile, contentType));
            }
            try {
                String hash = null;
                if( method instanceof HttpEntityEnclosingRequestBase ) {
                    try {
                        hash = provider.getRequestBodyHash(EntityUtils.toString(((HttpEntityEnclosingRequestBase)method).getEntity()));
                    }
                    catch( IOException e ) {
                        throw new InternalException(e);
                    }
                }
                else {
                    hash = provider.getRequestBodyHash("");
                }

                String signature;
                if( provider.getEC2Provider().isAWS() ) {
                    // Sign v4 for AWS
                    signature = provider.getV4Authorization(
                            new String(provider.getAccessKey()[0]),
                            new String(provider.getAccessKey()[1]),
                            method.getMethod(),
                            url.toString(),
                            SERVICE_ID,
                            headers,
                            hash);
                    if( hash != null ) {
                        method.addHeader(AWSCloud.P_AWS_CONTENT_SHA256, hash);
                    }
                }
                else {
                    // Eucalyptus et al use v2
                    signature = provider.signS3(
                            new String(provider.getAccessKey()[0], "utf-8"),
                            provider.getAccessKey()[1],
                            method.getMethod(),
                            null,
                            contentType,
                            headers,
                            bucket,
                            object);
                }
                method.addHeader(AWSCloud.P_CFAUTH, signature);
            }
            catch (UnsupportedEncodingException e) {
                logger.error(e);
            }

            if( wire.isDebugEnabled() ) {
                wire.debug("[" + url.toString() + "]");
                wire.debug(method.getRequestLine().toString());
                for( Header header : method.getAllHeaders() ) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
                if( body != null ) {
                    try { wire.debug(EntityUtils.toString(((HttpEntityEnclosingRequestBase)method).getEntity())); }
                    catch( IOException ignore ) { }

                    wire.debug("");
                }
                else if( uploadFile != null ) {
                    wire.debug("-- file upload --");
                    wire.debug("");
                }
            }

            attempts++;
            client = provider.getClient(body == null && uploadFile == null);
            
            S3Response response = new S3Response();
            HttpResponse httpResponse;
            
            try {
                APITrace.trace(provider, action.toString());
                httpResponse = client.execute(method);
                if( wire.isDebugEnabled() ) {
                    wire.debug(httpResponse.getStatusLine().toString());
                    for( Header header : httpResponse.getAllHeaders() ) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }             
                    wire.debug("");
                }
                status = httpResponse.getStatusLine().getStatusCode();
            } 
            catch( IOException e ) {
                logger.error(url + ": " + e.getMessage());
                throw new InternalException(e);
            }
            response.headers = httpResponse.getAllHeaders();
    
            HttpEntity entity = httpResponse.getEntity();
            InputStream input = null;

            if( entity != null ) {
                try {
                    input = entity.getContent();
                }
                catch( IOException e ) {
                    throw new CloudException(e);
                }
            }
            try {
                if( status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_ACCEPTED ) {
                    Header clen = httpResponse.getFirstHeader("Content-Length");
                    long len = -1L;
                    
                    if( clen != null ) {
                        len = Long.parseLong(clen.getValue());
                    }
                    if( len != 0L ) {
                        try {
                            Header ct = httpResponse.getFirstHeader("Content-Type");
    
                            if( (ct != null && (ct.getValue().startsWith("application/xml") || ct.getValue().startsWith("text/xml"))) || ( action.equals(S3Action.GET_BUCKET_TAG) && input != null )) {
                                try {
                                    response.document = parseResponse(input);
                                    return response;
                                }
                                finally {
                                    input.close();
                                }
                            }
                            else if( ct != null && ct.getValue().startsWith("application/octet-stream") && len < 1 ) {
                                return null;
                            }
                            else {
                                response.contentLength = len;
                                if( ct != null ) {
                                    response.contentType = ct.getValue();
                                }
                                response.input = input;
                                response.method = method;
                                leaveOpen = true;
                                return response;
                            }
                        }
                        catch( IOException e ) {
                            logger.error(e);
                            throw new CloudException(e);
                        }
                    }
                    else {
                        return response;
                    }
                }
                else if( status == HttpStatus.SC_NO_CONTENT ) {
                    return response;
                }
                if( status == HttpStatus.SC_FORBIDDEN ) {
                    throw new S3Exception(status, "", "AccessForbidden", "Access was denied : " + (url != null ? url.toString() : "" ));
                }
                else if( status == HttpStatus.SC_NOT_FOUND ) {
                    throw new S3Exception(status, null, null, "Object not found.");
                }
                else {
                    if( status == HttpStatus.SC_SERVICE_UNAVAILABLE || status == HttpStatus.SC_INTERNAL_SERVER_ERROR ) {
                        if( attempts >= 5 ) {
                            String msg;
                            
                            if( status == HttpStatus.SC_SERVICE_UNAVAILABLE ) {
                                msg = "Cloud service is currently unavailable.";
                            }
                            else {
                                msg = "The cloud service encountered a server error while processing your request.";
                            }
                            logger.error(msg);
                            throw new CloudException(msg);
                        }
                        else {
                            leaveOpen = true;
                            if( input != null ) {
                                try { input.close(); }
                                catch( IOException ignore ) { }
                            }
                            try { Thread.sleep(5000L); }
                            catch( InterruptedException ignore ) { }
                            return invoke(bucket, object);
                        }
                    }
                    try {
                        Document doc;
                        
                        try {
                            logger.warn("Received error code: " + status);
                            doc = parseResponse(input);
                        }
                        finally {
                            if( input != null ) {
                                input.close();
                            }
                        }
                        if( doc != null ) {
                            String endpoint = null, code = null, message = null, requestId = null;
                            NodeList blocks = doc.getElementsByTagName("Error");
        
                            if( blocks.getLength() > 0 ) {
                                Node error = blocks.item(0);
                                NodeList attrs;
                                
                                attrs = error.getChildNodes();
                                for( int i=0; i<attrs.getLength(); i++ ) {
                                    Node attr = attrs.item(i);
                                    
                                    if( attr.getNodeName().equals("Code") && attr.hasChildNodes() ) {
                                        code = attr.getFirstChild().getNodeValue().trim();
                                    }
                                    else if( attr.getNodeName().equals("Message") && attr.hasChildNodes() ) {
                                        message = attr.getFirstChild().getNodeValue().trim();
                                    }
                                    else if( attr.getNodeName().equals("RequestId") && attr.hasChildNodes() ) {
                                        requestId = attr.getFirstChild().getNodeValue().trim();
                                    }
                                    else if( attr.getNodeName().equals("Endpoint") && attr.hasChildNodes() ) {
                                        endpoint = attr.getFirstChild().getNodeValue().trim();
                                    }
                                }
                                
                            }
                            if( endpoint != null && code.equals("TemporaryRedirect") ) {
                                if( temporaryEndpoint != null ) {
                                    throw new CloudException("Too deep redirect to " + endpoint);
                                }
                                else {
                                    return invoke(bucket, object, endpoint);
                                }
                            }
                            else {
                                if( message == null ) {
                                    throw new CloudException("Unable to identify error condition: " + status + "/" + requestId + "/" + code);
                                }
                                throw new S3Exception(status, requestId, code, message);
                            }
                        }
                        else {
                            throw new CloudException("Unable to parse error.");
                        }
                    }
                    catch( IOException e ) {
                        if( status == HttpStatus.SC_FORBIDDEN ) {
                            throw new S3Exception(status, "", "AccessForbidden", "Access was denied without explanation.");
                        }                              
                        throw new CloudException(e);
                    }
                    catch( RuntimeException e ) {
                        throw new CloudException(e);
                    }
                    catch( Error e ) {
                        throw new CloudException(e);
                    }					
                }
            }
            finally {
                if( !leaveOpen ) {
                    if( input != null ) {
                        try { input.close(); }
                        catch( IOException ignore ) { }
                    }
                }
            }
        }
        finally {
            if (!leaveOpen && client != null) {
                client.getConnectionManager().shutdown();
            }
            if( wire.isDebugEnabled() ) {
                wire.debug("----------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    }
376770
public function withBaseUri(string $uri): self
    {
        return tap($this, function ($request) use ($uri) {
            return $this->options = array_merge_recursive($this->options, [
                'base_uri' => $uri,
            ]);
        });
    }
334537
@Override
  public String getVersion(URI uri) throws IOException
  {
    try {
      final S3Coords coords = new S3Coords(checkURI(uri));
      final S3ObjectSummary objectSummary = S3Utils.getSingleObjectSummary(s3Client, coords.bucket, coords.path);
      return StringUtils.format("%d", objectSummary.getLastModified().getTime());
    }
    catch (AmazonServiceException e) {
      if (S3Utils.isServiceExceptionRecoverable(e)) {
        // The recoverable logic is always true for IOException, so we want to only pass IOException if it is recoverable
        throw new IOE(e, "Could not fetch last modified timestamp from URI [%s]", uri);
      } else {
        throw new RE(e, "Error fetching last modified timestamp from URI [%s]", uri);
      }
    }
  }
801527
public URI call() throws Exception {
		// Save original time stamp for dependency list
		long lastModifiedDep = treeNode.lastModifiedDep();
		long lastModified = resource.lastModified();
		// Parse the javascript code
		Compiler compiler = new Compiler();
		CompilerOptions options = CompilerUtil.getDefaultOptions();
		if (compilerOptionsMap != null) {
			CompilerUtil.applyCompilerOptionsFromMap(options, compilerOptionsMap);
		}
		options.setWarningLevel(DiagnosticGroups.NON_STANDARD_JSDOC,
				CheckLevel.OFF);

		compiler.initOptions(options);
		InputStream in = resource.getInputStream();
		Node node = null;
		try {
			node = compiler.parse(JSSourceFile.fromInputStream(resource.getURI().toString(), in));
			if (compiler.hasErrors()) {
				if (log.isLoggable(Level.WARNING)) {
					JSError[] errors = compiler.getErrors();
					for (JSError error : errors) {
						log.log(Level.WARNING, error.toString());
					}
				}
			}
		} catch (Throwable e) {
			if (log.isLoggable(Level.WARNING)) {
				log.log(Level.WARNING, "Error occurred parsing " + resource.getURI().toString() + ": " + e.getMessage(), e); //$NON-NLS-1$ //$NON-NLS-2$
			}
		} finally {
			in.close();
		}
		if (node != null) {
			// walk the AST for the node looking for define calls
			// and pull out the required dependency list.
			Set<String> features = new HashSet<String>();
			ParseResult parseResult = DepUtils.parseDependencies(node, features);
			Collection<String> defineDeps = parseResult.getDefineDependencies();
			Collection<String> requireDeps = parseResult.getRequireDependencies();
			String[] defineDepArray = (defineDeps == null) ?
					new String[0] : defineDeps.toArray(new String[defineDeps.size()]);
			String[] requireDepArray = (requireDeps == null) ?
					new String[0] : requireDeps.toArray(new String[requireDeps.size()]);
			String[] featureArray = (features == null) ?
					new String[0] : features.toArray(new String[features.size()]);
			/*
			 * Determine if the dependency list has changed.  We keep track of
			 * dependency list changes separate from code changes in general
			 * because a dependency list change necessitates invalidating all
			 * cached responses for the configs that reference this file, and
			 * we want to do this only when necessary.
			 */
			if (lastModifiedDep ==  -1 ||
					!Arrays.equals(defineDepArray, treeNode.getDefineDepArray()) ||
					!Arrays.equals(requireDepArray, treeNode.getRequireDepArray()) ||
					!Arrays.equals(featureArray, treeNode.getDependentFeatures())) {
				lastModifiedDep = lastModified;
			}
			// update the dependency info in the node
			treeNode.setDependencies(defineDepArray, requireDepArray, featureArray,
					lastModified, lastModifiedDep);
		}
		return resource.getURI();
	}
1300804
public function setTargetUri(string $target_uri) : self
    {
        $this->target_uri           = $target_uri;
        $this->addHeader('location', $target_uri);
        $this->setBody(new Stream('php://temp', 'w+b'))->getBody()->write(sprintf('
            <!DOCTYPE html>
            <html>
                <head>
                    <meta charset="UTF-8" />
                    <meta http-equiv="refresh" content="0;url=%1$s" />

                    <title>Redirecting to %1$s</title>
                </head>
                <body>
                    Redirecting to <a href="%1$s">%1$s</a>.
                </body>
            </html>',
            htmlspecialchars($target_uri, ENT_QUOTES, 'UTF-8')
        ));
        $this->getBody()->rewind();
        return $this;
    }
1123605
function (request, options) {
    var action, target, method, emitter;

    while (this._actions.length) {
      action = this._actions.shift();
      target = action.target;
      method = action.method;
      emitter = new ActionEmitter;

      if (!(method in target)) {
        throw new Error("Can't call action " + method + ' on target for uri ' + request.uri);
      }

      this._emitters.push(emitter);

      target[method].call(target, request, options, emitter);
    }
  }
687490
public static function setBucketRedirect($bucket = NULL, $location = NULL)
	{
		$rest = new S3Request('PUT', $bucket, '', self::$endpoint);

		if( empty($bucket) || empty($location) ) {
			self::__triggerError("S3::setBucketRedirect({$bucket}, {$location}): Empty parameter.", __FILE__, __LINE__);
			return false;
		}

		$dom = new DOMDocument;
		$websiteConfiguration = $dom->createElement('WebsiteConfiguration');
		$redirectAllRequestsTo = $dom->createElement('RedirectAllRequestsTo');
		$hostName = $dom->createElement('HostName', $location);
		$redirectAllRequestsTo->appendChild($hostName);
		$websiteConfiguration->appendChild($redirectAllRequestsTo);
		$dom->appendChild($websiteConfiguration);
		$rest->setParameter('website', null);
		$rest->data = $dom->saveXML();
		$rest->size = strlen($rest->data);
		$rest->setHeader('Content-Type', 'application/xml');
		$rest = $rest->getResponse();

		if ($rest->error === false && $rest->code !== 200)
			$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
		if ($rest->error !== false)
		{
			self::__triggerError(sprintf("S3::setBucketRedirect({$bucket}, {$location}): [%s] %s",
			$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
			return false;
		}
		return true;
	}
642312
function requestURI( $uri )
    {
        $parsed = parse_url( $uri );

        $return = '';
        if ( isset( $parsed['user'] ) )
        {
            $return .= $parsed['user'] . '@' . $parsed['pass'];
        }
        $params = ( $this->Verb == 'GET' || $this->Verb == 'HEAD' || $this->Verb == 'TRACE' ) ? $this->Parameters : array();
        if ( $this->NameVar == null )
        {
            $return .= rtrim( $parsed['path'], '/' ) . '/' . ltrim( $this->Name, '/' );
        }
        else
        {
            $return .= $parsed['path'];
            if ( $this->Verb == 'GET' || $this->Verb == 'HEAD' )
            {
                $params[$this->NameVar] = $this->Name;
            }
        }

        if ( isset( $parsed['query'] ) )
        {
            $return  .= '?' . $parsed['query'];
            $next = '&';
        }
        else
        {
            $next = '?';
        }
        if ( count( $params ) )
        {
            $return .= $next . $this->_payload( $params );
        }
        if ( isset( $parsed['fragment'] ) )
        {
            $return .= '#' . $parsed['fragment'];
        }

        return $return;
    }
110642
private function getPathOperation(bool $v3, string $operationName, array $operation, string $method, string $operationType, string $resourceClass, ResourceMetadata $resourceMetadata, array $mimeTypes, \ArrayObject $definitions, \ArrayObject $links): \ArrayObject
    {
        $pathOperation = new \ArrayObject($operation[$v3 ? 'openapi_context' : 'swagger_context'] ?? []);
        $resourceShortName = $resourceMetadata->getShortName();
        $pathOperation['tags'] ?? $pathOperation['tags'] = [$resourceShortName];
        $pathOperation['operationId'] ?? $pathOperation['operationId'] = lcfirst($operationName).ucfirst($resourceShortName).ucfirst($operationType);
        if ($v3 && 'GET' === $method && OperationType::ITEM === $operationType && $link = $this->getLinkObject($resourceClass, $pathOperation['operationId'], $this->getPath($resourceShortName, $operationName, $operation, $operationType))) {
            $links[$pathOperation['operationId']] = $link;
        }
        if ($resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'deprecation_reason', null, true)) {
            $pathOperation['deprecated'] = true;
        }
        if (null !== $this->formatsProvider) {
            $responseFormats = $this->formatsProvider->getFormatsFromOperation($resourceClass, $operationName, $operationType);
            $responseMimeTypes = $this->extractMimeTypes($responseFormats);
        }
        switch ($method) {
            case 'GET':
                return $this->updateGetOperation($v3, $pathOperation, $responseMimeTypes ?? $mimeTypes, $operationType, $resourceMetadata, $resourceClass, $resourceShortName, $operationName, $definitions);
            case 'POST':
                return $this->updatePostOperation($v3, $pathOperation, $responseMimeTypes ?? $mimeTypes, $operationType, $resourceMetadata, $resourceClass, $resourceShortName, $operationName, $definitions, $links);
            case 'PATCH':
                $pathOperation['summary'] ?? $pathOperation['summary'] = sprintf('Updates the %s resource.', $resourceShortName);
            // no break
            case 'PUT':
                return $this->updatePutOperation($v3, $pathOperation, $responseMimeTypes ?? $mimeTypes, $operationType, $resourceMetadata, $resourceClass, $resourceShortName, $operationName, $definitions);
            case 'DELETE':
                return $this->updateDeleteOperation($v3, $pathOperation, $resourceShortName, $operationType, $operationName, $resourceMetadata);
        }

        return $pathOperation;
    }
859348
public static function getObjectInfo($bucket, $uri, $returnInfo = true)
	{
		$rest = new S3Request('HEAD', $bucket, $uri, self::$endpoint);
		$rest = $rest->getResponse();
		if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
			$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
		if ($rest->error !== false)
		{
			self::__triggerError(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s",
			$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
			return false;
		}
		return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false;
	}
533213
public static URI toUri(String endpoint, Protocol protocol) {
        if (endpoint == null) {
            throw new IllegalArgumentException("endpoint cannot be null");
        }

        /*
         * If the endpoint doesn't explicitly specify a protocol to use, then
         * we'll defer to the default protocol specified in the client
         * configuration.
         */
        if (!endpoint.contains("://")) {
            endpoint = protocol.toString() + "://" + endpoint;
        }

        try {
            return new URI(endpoint);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
    }
1226975
function loadURIRoot( $uri, $displayErrors = true, &$extraParameters )
    {
        $res = "";
        $template = "";
        $resobj = $this->resourceFor( $uri, $res, $template );

        if ( !is_object( $resobj ) )
        {
            if ( $displayErrors )
                $this->warning( "", "No resource handler for \"$res\" and no default resource handler, aborting." );
            return null;
        }

        $canCache = true;
        if ( !$resobj->servesStaticData() )
            $canCache = false;
        if ( !$this->isCachingAllowed() )
            $canCache = false;

        $resourceData = $this->loadURIData( $resobj, $uri, $res, $template, $extraParameters, $displayErrors );

        if ( $resourceData )
        {
            eZTemplate::appendTemplateToStatisticsIfNeeded( $resourceData['template-name'], $resourceData['template-filename'] );
            $this->appendTemplateFetch( $resourceData['template-filename'] );

            if ( !$resourceData['compiled-template'] and
                 $resourceData['root-node'] === null )
            {
                $resourceData['root-node'] = array( eZTemplate::NODE_ROOT, false );
                $templateText = $resourceData["text"];
                $keyData = $resourceData['key-data'];
                $this->setIncludeText( $uri, $templateText );
                $rootNamespace = '';
                $this->parse( $templateText, $resourceData['root-node'], $rootNamespace, $resourceData );

                if ( eZTemplate::isDebugEnabled() )
                {
                    $this->appendDebugNodes( $resourceData['root-node'], $resourceData );
                }

                if ( $canCache )
                    $resobj->setCachedTemplateTree( $keyData, $uri, $res, $template, $extraParameters, $resourceData['root-node'] );
            }
            if ( !$resourceData['compiled-template'] and
                 $canCache and
                 $this->canCompileTemplate( $resourceData, $extraParameters ) )
            {
                $generateStatus = $this->compileTemplate( $resourceData, $extraParameters );
                if ( $generateStatus )
                    $resourceData['compiled-template'] = true;
            }
        }

        return $resourceData;
    }
477910
public static function call($method, $params, $url, $publickey, $oRemoteApp = null)
        {

            $response = "";
            try {
                $sOldErrorhandler = set_error_handler('Slashworks\AppBundle\Services\Api::errorHandler');

                if(!self::$_container){
                    throw new \InvalidArgumentException("Container not given...");
                }


                if (!is_scalar($method)) {
                    throw new \Exception('Method name has no scalar value');
                }

                // check
                if (is_array($params)) {
                    // no keys
                    $params = array_values($params);
                } else {
                    throw new \Exception('Params must be given as array');
                }

                // prepares the request
                $request = array(
                    'method' => $method,
                    'params' => $params,
                    'id'     => rand(1, 999)
                );
                $request = json_encode($request);


                $rsa = new \Crypt_RSA();
                $rsa->loadKey($publickey);



                $sAppPath = self::$_container->get('kernel')->getRootDir();
                $sVendorPath = $sAppPath."/../vendor/slashworks/control-bundle/src/Slashworks/";
                $sKeyPath = $sVendorPath."AppBundle/Resources/private/api/keys/server/";

                $conairKey = file_get_contents($sKeyPath . "public.key");
                $aRequest  = array(
                    'pkey' => $conairKey,
                    'data' => base64_encode($rsa->encrypt($request))
                );

                $sRequest = json_encode($aRequest);

                $headers = array(
                    'Content-Type: application/json'
                );

                if ($oRemoteApp->getApiAuthType() == "http-basic") {
                    $sUsername = $oRemoteApp->getApiAuthHttpUser();
                    $sPassword = $oRemoteApp->getApiAuthHttpPassword();
                    if (!empty($sUsername) && !empty($sPassword)) {
                        $headers[] = "Authorization: Basic " . base64_encode($oRemoteApp->getApiAuthHttpUser() . ":" . $oRemoteApp->getApiAuthHttpPassword());
                    }
                }
                $oRequest = curl_init($url);
                curl_setopt($oRequest, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($oRequest, CURLOPT_TIMEOUT, 5);
                curl_setopt($oRequest, CURLOPT_POST, 1);
                curl_setopt($oRequest, CURLOPT_POSTFIELDS, $sRequest);
                curl_setopt($oRequest, CURLOPT_RETURNTRANSFER, true);
                $response    = curl_exec($oRequest);
                $iHttpStatus = curl_getinfo($oRequest, CURLINFO_HTTP_CODE);
                $error = curl_error($oRequest);
                curl_close($oRequest);

                $rawResponse = $response;

                if ($response == "") {
                    throw new \Exception("No content received for call on: ".$url);
                }
                if ($iHttpStatus === 200) {
                    $response = json_decode($response, true);

                    if (!isset($response['data'])) {
                        throw new \Exception("Invalid response format: ".htmlentities($rawResponse));
                    }

                    $privateKey = file_get_contents(__DIR__ . "/../Resources/private/api/keys/server/private.key");
                    $rsa->loadKey($privateKey);
                    $data             = base64_decode($response['data']);
                    $decoded          = $rsa->decrypt($data);
                    $response['data'] = json_decode($decoded, true);
                    if (!is_array($response['data'])) {
                        throw new \Exception("Invalid response format: ".htmlentities($rawResponse));
                    }

                    $response['data']['statuscode'] = $iHttpStatus;
                    if($iHttpStatus !== 200){
                        $response['error'] = true;
                    }


                    ApiLog::create($iHttpStatus, $oRemoteApp->getId(), $decoded);


                    restore_error_handler();

                    return $response['data'];
                } else {

                    ApiLog::create($iHttpStatus, $oRemoteApp->getId(), $response);

                    restore_error_handler();

                    return array(
                        "statuscode" => $iHttpStatus,
                        "result"     => json_encode(array(
                                                        "status"     => false,
                                                        "error"     => true,
                                                        "statuscode" => $iHttpStatus,
                                                        "message"    => $response
                                                    )
                        )
                    );
                }


            } catch (ContextErrorException $e) {

                restore_error_handler();
                ApiLog::create(-1, $oRemoteApp->getId(), $e->getMessage());


                return array(
                    "statuscode" => $iHttpStatus,
                    "result"     => json_encode(array(
                                                    "status"     => false,
                                                    "error"     => true,
                                                    "statuscode" => -1,
                                                    "message"    => $e->getMessage()
                                                )
                    )
                );
            } catch (\Exception $e) {


                restore_error_handler();
                ApiLog::create(-1, $oRemoteApp->getId(), $e->getMessage());

                return array(
                    "statuscode" => 500,
                    "result"     => json_encode(array(
                                                    "status"     => false,
                                                    "error"     => true,
                                                    "statuscode" => -1,
                                                    "message"    => $e->getMessage()
                                                )
                    )
                );
            }
        }
528352
protected function _buildCloudFrontDistributionUrl($protocol, $image, $bucket, $bucketPrefix = null, $cfDist = null) {
		$path = $protocol . '://';
		if (is_string($cfDist)) {
			$path .= $cfDist;
		} else {
			if ($bucketPrefix) {
				$path .= $bucket . '.s3.amazonaws.com';
			} else {
				$path .= 's3.amazonaws.com/' . $bucket;
			}
		}
		$path .= $image;

		return $path;
	}