Search in sources :

Example 6 with HTTPResponse

use of lucee.commons.net.http.HTTPResponse in project Lucee by lucee.

the class ExecutionThread method execute.

public static void execute(Config config, ScheduleTask task, String charset) {
    Log log = getLog(config);
    boolean hasError = false;
    String logName = "schedule task:" + task.getTask();
    // init
    // HttpClient client = new HttpClient();
    // client.setStrictMode(false);
    // HttpState state = client.getState();
    String url;
    if (task.getUrl().getQuery() == null)
        url = task.getUrl().toExternalForm() + "?RequestTimeout=" + (task.getTimeout() / 1000);
    else if (StringUtil.isEmpty(task.getUrl().getQuery()))
        url = task.getUrl().toExternalForm() + "RequestTimeout=" + (task.getTimeout() / 1000);
    else {
        if (StringUtil.indexOfIgnoreCase(task.getUrl().getQuery() + "", "RequestTimeout") != -1)
            url = task.getUrl().toExternalForm();
        else
            url = task.getUrl().toExternalForm() + "&RequestTimeout=" + (task.getTimeout() / 1000);
    }
    // HttpMethod method = new GetMethod(url);
    // HostConfiguration hostConfiguration = client.getHostConfiguration();
    Header[] headers = new Header[] { HTTPEngine.header("User-Agent", "CFSCHEDULE") };
    // method.setRequestHeader("User-Agent","CFSCHEDULE");
    // Userame / Password
    Credentials credentials = task.getCredentials();
    String user = null, pass = null;
    if (credentials != null) {
        user = credentials.getUsername();
        pass = credentials.getPassword();
    // get.addRequestHeader("Authorization","Basic admin:spwwn1p");
    }
    // Proxy
    ProxyData proxy = task.getProxyData();
    if (!ProxyDataImpl.isValid(proxy) && config.isProxyEnableFor(task.getUrl().getHost())) {
        proxy = config.getProxyData();
    }
    HTTPResponse rsp = null;
    // execute
    try {
        rsp = HTTPEngine.get(new URL(url), user, pass, task.getTimeout(), true, charset, null, proxy, headers);
    } catch (Exception e) {
        LogUtil.log(log, Log.LEVEL_ERROR, logName, e);
        hasError = true;
    }
    // write file
    Resource file = task.getResource();
    if (!hasError && file != null && task.isPublish()) {
        String n = file.getName();
        if (n.indexOf("{id}") != -1) {
            n = StringUtil.replace(n, "{id}", CreateUUID.invoke(), false);
            file = file.getParentResource().getRealResource(n);
        }
        if (isText(rsp) && task.isResolveURL()) {
            String str;
            try {
                InputStream stream = rsp.getContentAsStream();
                str = stream == null ? "" : IOUtil.toString(stream, (Charset) null);
                if (str == null)
                    str = "";
            } catch (IOException e) {
                str = e.getMessage();
            }
            try {
                str = new URLResolver().transform(str, task.getUrl(), false);
            } catch (PageException e) {
                LogUtil.log(log, Log.LEVEL_ERROR, logName, e);
                hasError = true;
            }
            try {
                IOUtil.write(file, str, charset, false);
            } catch (IOException e) {
                LogUtil.log(log, Log.LEVEL_ERROR, logName, e);
                hasError = true;
            }
        } else {
            try {
                IOUtil.copy(rsp.getContentAsStream(), file, true);
            } catch (IOException e) {
                LogUtil.log(log, Log.LEVEL_ERROR, logName, e);
                hasError = true;
            }
        }
        HTTPEngine.closeEL(rsp);
    }
    if (!hasError)
        log.log(Log.LEVEL_INFO, logName, "executed");
}
Also used : PageException(lucee.runtime.exp.PageException) Log(lucee.commons.io.log.Log) InputStream(java.io.InputStream) HTTPResponse(lucee.commons.net.http.HTTPResponse) Resource(lucee.commons.io.res.Resource) IOException(java.io.IOException) URL(java.net.URL) IOException(java.io.IOException) PageException(lucee.runtime.exp.PageException) ProxyData(lucee.runtime.net.proxy.ProxyData) Header(lucee.commons.net.http.Header) URLResolver(lucee.runtime.util.URLResolver) Credentials(lucee.commons.security.Credentials)

Example 7 with HTTPResponse

use of lucee.commons.net.http.HTTPResponse in project Lucee by lucee.

the class SpoolerTaskHTTPCall method execute.

public static final Object execute(RemoteClient client, Config config, String methodName, Struct args) throws PageException {
    // return rpc.callWithNamedValues(config, getMethodName(), getArguments());
    PageContext pc = ThreadLocalPageContext.get();
    // remove wsdl if necessary
    String url = client.getUrl();
    if (StringUtil.endsWithIgnoreCase(url, "?wsdl"))
        url = url.substring(0, url.length() - 5);
    // Params
    Map<String, String> params = new HashMap<String, String>();
    params.put("method", methodName);
    params.put("returnFormat", "json");
    try {
        Charset cs = pc.getWebCharset();
        params.put("argumentCollection", new JSONConverter(true, cs).serialize(pc, args, false));
        HTTPResponse res = HTTPEngine4Impl.post(HTTPUtil.toURL(url, true), client.getServerUsername(), client.getServerPassword(), -1L, true, pc.getWebCharset().name(), Constants.NAME + " Remote Invocation", client.getProxyData(), null, params);
        return new JSONExpressionInterpreter().interpret(pc, res.getContentAsString());
    } catch (IOException ioe) {
        throw Caster.toPageException(ioe);
    } catch (ConverterException ce) {
        throw Caster.toPageException(ce);
    }
}
Also used : ConverterException(lucee.runtime.converter.ConverterException) HashMap(java.util.HashMap) JSONExpressionInterpreter(lucee.runtime.interpreter.JSONExpressionInterpreter) HTTPResponse(lucee.commons.net.http.HTTPResponse) Charset(java.nio.charset.Charset) PageContext(lucee.runtime.PageContext) ThreadLocalPageContext(lucee.runtime.engine.ThreadLocalPageContext) IOException(java.io.IOException) JSONConverter(lucee.runtime.converter.JSONConverter)

Example 8 with HTTPResponse

use of lucee.commons.net.http.HTTPResponse in project Lucee by lucee.

the class XMLConfigAdmin method verifyExtensionProvider.

public void verifyExtensionProvider(String strUrl) throws PageException {
    HTTPResponse method = null;
    try {
        URL url = HTTPUtil.toURL(strUrl + "?wsdl", true);
        method = HTTPEngine.get(url, null, null, 2000, true, null, null, null, null);
    } catch (MalformedURLException e) {
        throw new ApplicationException("url defintion [" + strUrl + "] is invalid");
    } catch (IOException e) {
        throw new ApplicationException("can't invoke [" + strUrl + "]", e.getMessage());
    }
    if (method.getStatusCode() != 200) {
        int code = method.getStatusCode();
        String text = method.getStatusText();
        String msg = code + " " + text;
        throw new HTTPException(msg, null, code, text, method.getURL());
    }
    // Object o =
    CreateObject.doWebService(null, strUrl + "?wsdl");
    HTTPEngine.closeEL(method);
}
Also used : MalformedURLException(java.net.MalformedURLException) ApplicationException(lucee.runtime.exp.ApplicationException) HTTPException(lucee.runtime.exp.HTTPException) HTTPResponse(lucee.commons.net.http.HTTPResponse) IOException(java.io.IOException) URL(java.net.URL)

Example 9 with HTTPResponse

use of lucee.commons.net.http.HTTPResponse in project Lucee by lucee.

the class DeployHandler method deployExtension.

/**
 * install a extension based on the given id and version
 * @param config
 * @param id the id of the extension
 * @param version pass null if you don't need a specific version
 * @return
 * @throws IOException
 * @throws PageException
 */
public static boolean deployExtension(Config config, ExtensionDefintion ed, Log log, boolean reload) {
    ConfigImpl ci = (ConfigImpl) config;
    // is the extension already installed
    try {
        if (XMLConfigAdmin.hasRHExtensions(ci, ed) != null)
            return false;
    } catch (Throwable t) {
        ExceptionUtil.rethrowIfNecessary(t);
    }
    // check if a local extension is matching our id
    Iterator<ExtensionDefintion> it = getLocalExtensions(config).iterator();
    ExtensionDefintion ext = null, tmp;
    log.info("extension", "installing the extension " + ed);
    while (it.hasNext()) {
        tmp = it.next();
        if (ed.equals(tmp)) {
            ext = tmp;
            break;
        }
    }
    // if we have one and also the defined version matches, there is no need to check online
    if (ext != null && ed.getVersion() != null) {
        try {
            log.info("extension", "installing the extension " + ed + " from local provider");
            Resource res = SystemUtil.getTempDirectory().getRealResource(ed.getId() + "-" + ed.getVersion() + ".lex");
            ResourceUtil.touch(res);
            IOUtil.copy(ext.getSource(), res);
            XMLConfigAdmin._updateRHExtension((ConfigImpl) config, res, reload);
            return true;
        } catch (Exception e) {
            ext = null;
            SystemOut.printDate(e);
        }
    }
    String apiKey = config.getIdentification().getApiKey();
    RHExtensionProvider[] providers = ci.getRHExtensionProviders();
    URL url;
    // if we have a local version, we look if there is a newer remote version
    if (ext != null) {
        String content;
        for (int i = 0; i < providers.length; i++) {
            HTTPResponse rsp = null;
            try {
                url = providers[i].getURL();
                StringBuilder qs = new StringBuilder();
                qs.append("?withLogo=false");
                if (ed.getVersion() != null)
                    qs.append("&version=").append(ed.getVersion());
                if (apiKey != null)
                    qs.append("&ioid=").append(apiKey);
                url = new URL(url, "/rest/extension/provider/info/" + ed.getId() + qs);
                rsp = HTTPEngine.get(url, null, null, -1, false, "UTF-8", "", null, new Header[] { new HeaderImpl("accept", "application/json") });
                if (rsp.getStatusCode() != 200)
                    continue;
                content = rsp.getContentAsString();
                Struct sct = Caster.toStruct(DeserializeJSON.call(null, content));
                String remoteVersion = Caster.toString(sct.get(KeyConstants._version));
                // the local version is as good as the remote
                if (remoteVersion != null && remoteVersion.compareTo(ext.getVersion()) <= 0) {
                    log.info("extension", "installing the extension " + ed + " from local provider");
                    // avoid that the exzension from provider get removed
                    Resource res = SystemUtil.getTempDirectory().getRealResource(ed.getId() + "-" + ed.getVersion() + ".lex");
                    ResourceUtil.touch(res);
                    IOUtil.copy(ext.getSource(), res);
                    XMLConfigAdmin._updateRHExtension((ConfigImpl) config, res, reload);
                    return true;
                }
            } catch (Throwable t) {
                ExceptionUtil.rethrowIfNecessary(t);
            } finally {
                HTTPEngine.closeEL(rsp);
            }
        }
    }
    // if we have an ext at this stage this mean the remote providers was not acessible or have not this extension
    if (ext != null) {
        try {
            log.info("extension", "installing the extension " + ed + " from local provider");
            Resource res = SystemUtil.getTempDirectory().getRealResource(ext.getSource().getName());
            ResourceUtil.touch(res);
            IOUtil.copy(ext.getSource(), res);
            XMLConfigAdmin._updateRHExtension((ConfigImpl) config, res, reload);
            return true;
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
        }
    }
    // if not we try to download it
    log.info("extension", "installing the extension " + ed + " from remote extension provider");
    Resource res = downloadExtension(ci, ed, log);
    if (res != null) {
        try {
            XMLConfigAdmin._updateRHExtension((ConfigImpl) config, res, reload);
            return true;
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
            log.error("extension", t);
        }
    }
    return false;
}
Also used : HeaderImpl(lucee.commons.net.http.httpclient.HeaderImpl) HTTPResponse(lucee.commons.net.http.HTTPResponse) Resource(lucee.commons.io.res.Resource) PageException(lucee.runtime.exp.PageException) IOException(java.io.IOException) URL(java.net.URL) RHExtensionProvider(lucee.runtime.extension.RHExtensionProvider) Struct(lucee.runtime.type.Struct) Header(lucee.commons.net.http.Header) ExtensionDefintion(lucee.runtime.extension.ExtensionDefintion)

Example 10 with HTTPResponse

use of lucee.commons.net.http.HTTPResponse in project Lucee by lucee.

the class HTTPResource method lastModified.

@Override
public long lastModified() {
    int last = 0;
    HTTPResponse rsp = null;
    try {
        Header cl = (rsp = getHTTPResponse(false)).getLastHeaderIgnoreCase("last-modified");
        if (cl != null && exists())
            last = Caster.toIntValue(cl.getValue(), 0);
    } catch (IOException e) {
    } finally {
        HTTPEngine.closeEL(rsp);
    }
    return last;
}
Also used : Header(lucee.commons.net.http.Header) HTTPResponse(lucee.commons.net.http.HTTPResponse) IOException(java.io.IOException)

Aggregations

HTTPResponse (lucee.commons.net.http.HTTPResponse)10 IOException (java.io.IOException)8 Header (lucee.commons.net.http.Header)5 URL (java.net.URL)4 InputStream (java.io.InputStream)3 Resource (lucee.commons.io.res.Resource)3 ApplicationException (lucee.runtime.exp.ApplicationException)3 Charset (java.nio.charset.Charset)2 HashMap (java.util.HashMap)2 MimeType (lucee.commons.lang.mimetype.MimeType)2 HeaderImpl (lucee.commons.net.http.httpclient.HeaderImpl)2 ConverterException (lucee.runtime.converter.ConverterException)2 JSONConverter (lucee.runtime.converter.JSONConverter)2 PageException (lucee.runtime.exp.PageException)2 RHExtensionProvider (lucee.runtime.extension.RHExtensionProvider)2 Struct (lucee.runtime.type.Struct)2 MalformedURLException (java.net.MalformedURLException)1 Log (lucee.commons.io.log.Log)1 Credentials (lucee.commons.security.Credentials)1 PageContext (lucee.runtime.PageContext)1