Search in sources :

Example 1 with ConverterException

use of lucee.runtime.converter.ConverterException in project Lucee by lucee.

the class HTTPClient method _callWithNamedValues.

private Object _callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException {
    // prepare request
    Map<String, String> formfields = new HashMap<String, String>();
    formfields.put("method", methodName.getString());
    formfields.put("returnformat", "cfml");
    String str;
    try {
        if (UDF.RETURN_FORMAT_JSON == argumentsCollectionFormat) {
            Charset cs = pc.getWebCharset();
            str = new JSONConverter(true, cs).serialize(pc, args, false);
            formfields.put("argumentCollectionFormat", "json");
        } else if (UDF.RETURN_FORMAT_SERIALIZE == argumentsCollectionFormat) {
            str = new ScriptConverter().serialize(args);
            formfields.put("argumentCollectionFormat", "cfml");
        } else {
            // Json interpreter also accepts cfscript
            str = new ScriptConverter().serialize(args);
        }
    } catch (ConverterException e) {
        throw Caster.toPageException(e);
    }
    // add aparams to request
    formfields.put("argumentCollection", str);
    /*
		Iterator<Entry<Key, Object>> it = args.entryIterator();
		Entry<Key, Object> e;
		while(it.hasNext()){
			e = it.next();
			formfields.put(e.getKey().getString(), Caster.toString(e.getValue()));
		}*/
    Map<String, String> headers = new HashMap<String, String>();
    // application/java disabled for the moment, it is not working when we have different lucee versions
    headers.put("accept", "application/cfml,application/json");
    HTTPResponse rsp = null;
    InputStream is = null;
    try {
        // call remote cfc
        rsp = HTTPEngine.post(url, username, password, -1, false, "UTF-8", createUserAgent(pc), proxyData, headers, formfields);
        // read result
        Header[] rspHeaders = rsp.getAllHeaders();
        MimeType mt = getMimeType(rspHeaders, null);
        int format = MimeType.toFormat(mt, -1);
        if (format == -1) {
            if (rsp.getStatusCode() != 200) {
                boolean hasMsg = false;
                String msg = rsp.getStatusText();
                for (int i = 0; i < rspHeaders.length; i++) {
                    if (rspHeaders[i].getName().equalsIgnoreCase("exception-message")) {
                        msg = rspHeaders[i].getValue();
                        hasMsg = true;
                    }
                }
                is = rsp.getContentAsStream();
                ApplicationException ae = new ApplicationException("remote component throws the following error:" + msg);
                if (!hasMsg)
                    ae.setAdditional(KeyImpl.init("respone-body"), IOUtil.toString(is, mt.getCharset()));
                throw ae;
            }
            throw new ApplicationException("cannot convert response with mime type [" + mt + "] to a CFML Object");
        }
        is = rsp.getContentAsStream();
        return ReqRspUtil.toObject(pc, IOUtil.toBytes(is, false), format, mt.getCharset(), null);
    } catch (IOException ioe) {
        throw Caster.toPageException(ioe);
    } finally {
        IOUtil.closeEL(is);
        HTTPEngine.closeEL(rsp);
    }
}
Also used : ConverterException(lucee.runtime.converter.ConverterException) HashMap(java.util.HashMap) InputStream(java.io.InputStream) HTTPResponse(lucee.commons.net.http.HTTPResponse) Charset(java.nio.charset.Charset) IOException(java.io.IOException) MimeType(lucee.commons.lang.mimetype.MimeType) ApplicationException(lucee.runtime.exp.ApplicationException) Header(lucee.commons.net.http.Header) ScriptConverter(lucee.runtime.converter.ScriptConverter) JSONConverter(lucee.runtime.converter.JSONConverter)

Example 2 with ConverterException

use of lucee.runtime.converter.ConverterException in project Lucee by lucee.

the class Trace method _doEndTag.

public void _doEndTag() throws IOException, PageException {
    PageSource ps = pageContext.getCurrentTemplatePageSource();
    // var
    String varValue = null;
    Object value = null, traceValue = null;
    if (!StringUtil.isEmpty(var)) {
        try {
            if (caller instanceof Scope)
                value = VariableInterpreter.getVariable(pageContext, var, (Scope) caller);
            else
                value = pageContext.getVariable(var);
        } catch (PageException e) {
            varValue = "(undefined)";
            follow = false;
        }
        if (follow) {
            // print.o(1);
            if (StringUtil.isEmpty(text, true))
                text = var;
            // print.o(2);
            traceValue = TraceObjectSupport.toTraceObject(pageContext.getDebugger(), value, type, category, text);
            if (caller instanceof Scope)
                VariableInterpreter.setVariable(pageContext, var, traceValue, (Scope) caller);
            else
                pageContext.setVariable(var, traceValue);
        }
        try {
            varValue = new ScriptConverter().serialize(value);
        } catch (ConverterException e) {
            if (value != null)
                varValue = "(" + Caster.toTypeName(value) + ")";
        }
    }
    DebugTrace trace = ((DebuggerImpl) pageContext.getDebugger()).addTrace(type, category, text, ps, var, varValue);
    DebugTrace[] traces = pageContext.getDebugger().getTraces(pageContext);
    String total = "(1st trace)";
    if (traces.length > 1) {
        long t = 0;
        for (int i = 0; i < traces.length; i++) {
            t += traces[i].getTime();
        }
        total = "(" + t + ")";
    }
    boolean hasCat = !StringUtil.isEmpty(trace.getCategory());
    boolean hasText = !StringUtil.isEmpty(trace.getText());
    boolean hasVar = !StringUtil.isEmpty(var);
    // inline
    if (inline) {
        lucee.runtime.format.TimeFormat tf = new lucee.runtime.format.TimeFormat(pageContext.getConfig().getLocale());
        StringBuffer sb = new StringBuffer();
        sb.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"white\">");
        sb.append("<tr>");
        // sb.append("<td><img src=\"/CFIDE/debug/images/Error_16x16.gif\" alt=\"Error type\">");
        sb.append("<td>");
        sb.append("<font color=\"orange\">");
        sb.append("<b>");
        sb.append(DebugTraceImpl.toType(trace.getType(), "INFO") + " - ");
        sb.append("[CFTRACE " + tf.format(new DateTimeImpl(pageContext.getConfig()), "hh:mm:ss:l") + "]");
        sb.append("[" + trace.getTime() + " ms " + total + "]");
        sb.append("[" + trace.getTemplate() + " @ line: " + trace.getLine() + "]");
        if (hasCat || hasText)
            sb.append(" -");
        if (hasCat)
            sb.append("  [" + trace.getCategory() + "]");
        if (hasText)
            sb.append(" <i>" + trace.getText() + "&nbsp;</i>");
        sb.append("</b>");
        sb.append("</font>");
        sb.append("</td>");
        sb.append("</tr>");
        sb.append("</table>");
        pageContext.forceWrite(sb.toString());
        if (hasVar)
            Dump.call(pageContext, value, var);
    }
    // log
    Log log = ((ConfigImpl) pageContext.getConfig()).getLog("trace");
    StringBuffer msg = new StringBuffer();
    msg.append("[" + trace.getTime() + " ms " + total + "] ");
    msg.append("[" + trace.getTemplate() + " @ line: " + trace.getLine() + "]");
    if (hasCat || hasText || hasVar)
        msg.append("- ");
    if (hasCat)
        msg.append("[" + trace.getCategory() + "] ");
    if (hasVar)
        msg.append("[" + var + "=" + varValue + "] ");
    if (hasText)
        msg.append(" " + trace.getText() + " ");
    log.log(trace.getType(), "cftrace", msg.toString());
    // abort
    if (abort)
        throw new Abort(Abort.SCOPE_REQUEST);
}
Also used : PageException(lucee.runtime.exp.PageException) ConverterException(lucee.runtime.converter.ConverterException) Log(lucee.commons.io.log.Log) DebuggerImpl(lucee.runtime.debug.DebuggerImpl) PageSource(lucee.runtime.PageSource) Abort(lucee.runtime.exp.Abort) Scope(lucee.runtime.type.scope.Scope) DebugTrace(lucee.runtime.debug.DebugTrace) ScriptConverter(lucee.runtime.converter.ScriptConverter) DateTimeImpl(lucee.runtime.type.dt.DateTimeImpl) ConfigImpl(lucee.runtime.config.ConfigImpl)

Example 3 with ConverterException

use of lucee.runtime.converter.ConverterException in project Lucee by lucee.

the class SerializeJSON method _call.

private static String _call(PageContext pc, Object var, Object options, Charset charset) throws PageException {
    try {
        JSONConverter json = new JSONConverter(true, charset);
        if (Decision.isBoolean(options))
            return json.serialize(pc, var, Caster.toBoolean(options));
        if (Decision.isQuery(var)) {
            if (Decision.isSimpleValue(options)) {
                String opt = Caster.toString(options);
                if ("struct".equalsIgnoreCase(opt)) {
                    Array arr = new ArrayImpl();
                    ForEachQueryIterator it = new ForEachQueryIterator((Query) var, pc.getId());
                    try {
                        while (it.hasNext()) {
                            // append each record from the query as a struct
                            arr.append(it.next());
                        }
                    } finally {
                        it.reset();
                    }
                    return json.serialize(pc, arr, false);
                }
            } else if (Decision.isBoolean(options)) {
                return json.serialize(pc, var, Caster.toBoolean(options));
            } else
                throw new FunctionException(pc, SerializeJSON.class.getSimpleName(), 2, "options", "When var is a Query, argument [options] must be either a boolean value or a string with the value of [struct]");
        }
        // var is not a query so options doesn't make a difference here
        return json.serialize(pc, var, false);
    } catch (ConverterException e) {
        throw Caster.toPageException(e);
    }
}
Also used : Array(lucee.runtime.type.Array) ForEachQueryIterator(lucee.runtime.type.it.ForEachQueryIterator) ConverterException(lucee.runtime.converter.ConverterException) ArrayImpl(lucee.runtime.type.ArrayImpl) FunctionException(lucee.runtime.exp.FunctionException) JSONConverter(lucee.runtime.converter.JSONConverter)

Example 4 with ConverterException

use of lucee.runtime.converter.ConverterException 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 5 with ConverterException

use of lucee.runtime.converter.ConverterException in project Lucee by lucee.

the class ImageConverter method writeOut.

@Override
public void writeOut(PageContext pc, Object source, OutputStream os) throws ConverterException, IOException {
    try {
        Image img = Image.createImage(pc, source, false, true, true, format);
        img.writeOut(os, format, 1, false);
    } catch (IOException ioe) {
        throw ioe;
    } catch (Exception e) {
        throw ConverterSupport.toConverterException(e);
    }
}
Also used : IOException(java.io.IOException) Image(lucee.runtime.img.Image) ConverterException(lucee.runtime.converter.ConverterException) IOException(java.io.IOException)

Aggregations

ConverterException (lucee.runtime.converter.ConverterException)6 IOException (java.io.IOException)3 JSONConverter (lucee.runtime.converter.JSONConverter)3 Charset (java.nio.charset.Charset)2 HashMap (java.util.HashMap)2 HTTPResponse (lucee.commons.net.http.HTTPResponse)2 ScriptConverter (lucee.runtime.converter.ScriptConverter)2 InputStream (java.io.InputStream)1 Log (lucee.commons.io.log.Log)1 MimeType (lucee.commons.lang.mimetype.MimeType)1 Header (lucee.commons.net.http.Header)1 PageContext (lucee.runtime.PageContext)1 PageSource (lucee.runtime.PageSource)1 ConfigImpl (lucee.runtime.config.ConfigImpl)1 JSConverter (lucee.runtime.converter.JSConverter)1 DebugTrace (lucee.runtime.debug.DebugTrace)1 DebuggerImpl (lucee.runtime.debug.DebuggerImpl)1 ThreadLocalPageContext (lucee.runtime.engine.ThreadLocalPageContext)1 Abort (lucee.runtime.exp.Abort)1 ApplicationException (lucee.runtime.exp.ApplicationException)1