Search in sources :

Example 1 with JSONConverter

use of lucee.runtime.converter.JSONConverter 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 JSONConverter

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

the class Props method _writeOut.

private static void _writeOut(PageContext pc, Props props, Object queryFormat, Object rtn, Charset cs, boolean setFormat) throws ConverterException, PageException, IOException {
    // return type XML ignore WDDX
    if (props.type == CFTypes.TYPE_XML) {
        // if(UDF.RETURN_FORMAT_WDDX==format) format=UDF.RETURN_FORMAT_PLAIN;
        rtn = Caster.toString(Caster.toXML(rtn));
    } else
        // function does no real cast, only check it
        rtn = Caster.castTo(pc, (short) props.type, props.strType, rtn);
    if (setFormat)
        setFormat(pc.getHttpServletResponse(), props.format, cs);
    // WDDX
    if (UDF.RETURN_FORMAT_WDDX == props.format) {
        WDDXConverter converter = new WDDXConverter(pc.getTimeZone(), false, false);
        converter.setTimeZone(pc.getTimeZone());
        pc.forceWrite(converter.serialize(rtn));
    } else // JSON
    if (UDF.RETURN_FORMAT_JSON == props.format) {
        boolean byColumn = false;
        if (queryFormat instanceof String) {
            String strQF = ((String) queryFormat).trim();
            if (strQF.equalsIgnoreCase("row"))
                ;
            else if (strQF.equalsIgnoreCase("column"))
                byColumn = true;
            else
                throw new ApplicationException("invalid queryformat definition [" + strQF + "], valid formats are [row,column]");
        }
        JSONConverter converter = new JSONConverter(false, cs);
        String prefix = "";
        if (props.secureJson) {
            prefix = pc.getApplicationContext().getSecureJsonPrefix();
            if (prefix == null)
                prefix = "";
        }
        pc.forceWrite(prefix + converter.serialize(pc, rtn, byColumn));
    } else // CFML
    if (UDF.RETURN_FORMAT_SERIALIZE == props.format) {
        ScriptConverter converter = new ScriptConverter(false);
        pc.forceWrite(converter.serialize(rtn));
    } else // XML
    if (UDF.RETURN_FORMAT_XML == props.format) {
        XMLConverter converter = new XMLConverter(pc.getTimeZone(), false);
        converter.setTimeZone(pc.getTimeZone());
        pc.forceWrite(converter.serialize(rtn));
    } else // Plain
    if (UDF.RETURN_FORMAT_PLAIN == props.format) {
        pc.forceWrite(Caster.toString(rtn));
    } else // JAVA
    if (UDF.RETURN_FORMAT_JAVA == props.format) {
        writeOut(pc, rtn, MimeType.APPLICATION_JAVA, new JavaConverter());
    } else
        throw new IOException("invalid return format defintion:" + props.format);
}
Also used : WDDXConverter(lucee.runtime.converter.WDDXConverter) ApplicationException(lucee.runtime.exp.ApplicationException) ScriptConverter(lucee.runtime.converter.ScriptConverter) XMLConverter(lucee.runtime.converter.XMLConverter) JavaConverter(lucee.runtime.converter.JavaConverter) IOException(java.io.IOException) JSONConverter(lucee.runtime.converter.JSONConverter)

Example 3 with JSONConverter

use of lucee.runtime.converter.JSONConverter 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 JSONConverter

use of lucee.runtime.converter.JSONConverter 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 JSONConverter

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

the class Props method callCFCMetaData.

private void callCFCMetaData(PageContext pc, Component cfc, int format) throws IOException, PageException, ConverterException {
    ComponentSpecificAccess cw = new ComponentSpecificAccess(Component.ACCESS_REMOTE, cfc);
    ComponentScope scope = cw.getComponentScope();
    Struct udfs = new StructImpl(), sctUDF, sctArg;
    Array arrArg;
    Iterator<Object> it = scope.valueIterator();
    Object v;
    UDF udf;
    FunctionArgument[] args;
    while (it.hasNext()) {
        v = it.next();
        // UDF
        if (v instanceof UDF) {
            udf = (UDF) v;
            sctUDF = new StructImpl();
            arrArg = new ArrayImpl();
            udfs.setEL(udf.getFunctionName(), sctUDF);
            args = udf.getFunctionArguments();
            for (int i = 0; i < args.length; i++) {
                sctArg = new StructImpl();
                arrArg.appendEL(sctArg);
                sctArg.setEL(KeyConstants._name, args[i].getName().getString());
                sctArg.setEL(KeyConstants._type, args[i].getTypeAsString());
                sctArg.setEL(KeyConstants._required, args[i].isRequired());
                if (!StringUtil.isEmpty(args[i].getHint()))
                    sctArg.setEL(KeyConstants._hint, args[i].getHint());
            }
            sctUDF.set(KeyConstants._arguments, arrArg);
            sctUDF.set(KeyConstants._returntype, udf.getReturnTypeAsString());
        }
    }
    Struct rtn = new StructImpl();
    rtn.set(KeyConstants._functions, udfs);
    rtn.set(ACCEPT_ARG_COLL_FORMATS, "cfml,json");
    InputStream is;
    Charset cs = null;
    // WDDX
    if (UDF.RETURN_FORMAT_WDDX == format) {
        WDDXConverter converter = new WDDXConverter(pc.getTimeZone(), false, false);
        converter.setTimeZone(pc.getTimeZone());
        String str = converter.serialize(rtn);
        cs = getCharset(pc);
        is = new ByteArrayInputStream(str.getBytes(cs));
    } else // JSON
    if (UDF.RETURN_FORMAT_JSON == format) {
        boolean byColumn = false;
        cs = getCharset(pc);
        JSONConverter converter = new JSONConverter(false, cs);
        String str = converter.serialize(pc, rtn, byColumn);
        is = new ByteArrayInputStream(str.getBytes(cs));
    } else // CFML
    if (UDF.RETURN_FORMAT_SERIALIZE == format) {
        ScriptConverter converter = new ScriptConverter(false);
        String str = converter.serialize(rtn);
        cs = getCharset(pc);
        is = new ByteArrayInputStream(str.getBytes(cs));
    } else // XML
    if (UDF.RETURN_FORMAT_XML == format) {
        XMLConverter converter = new XMLConverter(pc.getTimeZone(), false);
        converter.setTimeZone(pc.getTimeZone());
        String str = converter.serialize(rtn);
        cs = getCharset(pc);
        is = new ByteArrayInputStream(str.getBytes(cs));
    } else // Plain
    if (UDF.RETURN_FORMAT_PLAIN == format) {
        String str = Caster.toString(rtn);
        cs = getCharset(pc);
        is = new ByteArrayInputStream(str.getBytes(cs));
    } else // Java
    if (UDF.RETURN_FORMAT_JAVA == format) {
        byte[] bytes = JavaConverter.serializeAsBinary(rtn);
        is = new ByteArrayInputStream(bytes);
    } else
        throw new IOException("invalid format defintion:" + format);
    OutputStream os = null;
    try {
        os = pc.getResponseStream();
        setFormat(pc.getHttpServletResponse(), format, cs);
        IOUtil.copy(is, os, false, false);
    } finally {
        IOUtil.flushEL(os);
        IOUtil.closeEL(os);
        ((PageContextImpl) pc).getRootOut().setClosed(true);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayImpl(lucee.runtime.type.ArrayImpl) OutputStream(java.io.OutputStream) XMLConverter(lucee.runtime.converter.XMLConverter) Charset(java.nio.charset.Charset) IOException(java.io.IOException) StaticStruct(lucee.runtime.component.StaticStruct) Struct(lucee.runtime.type.Struct) Array(lucee.runtime.type.Array) WDDXConverter(lucee.runtime.converter.WDDXConverter) StructImpl(lucee.runtime.type.StructImpl) ByteArrayInputStream(java.io.ByteArrayInputStream) UDF(lucee.runtime.type.UDF) ScriptConverter(lucee.runtime.converter.ScriptConverter) FunctionArgument(lucee.runtime.type.FunctionArgument) JSONConverter(lucee.runtime.converter.JSONConverter)

Aggregations

JSONConverter (lucee.runtime.converter.JSONConverter)6 IOException (java.io.IOException)4 Charset (java.nio.charset.Charset)3 ConverterException (lucee.runtime.converter.ConverterException)3 ScriptConverter (lucee.runtime.converter.ScriptConverter)3 Array (lucee.runtime.type.Array)3 InputStream (java.io.InputStream)2 HashMap (java.util.HashMap)2 HTTPResponse (lucee.commons.net.http.HTTPResponse)2 WDDXConverter (lucee.runtime.converter.WDDXConverter)2 XMLConverter (lucee.runtime.converter.XMLConverter)2 ApplicationException (lucee.runtime.exp.ApplicationException)2 FunctionException (lucee.runtime.exp.FunctionException)2 ArrayImpl (lucee.runtime.type.ArrayImpl)2 Struct (lucee.runtime.type.Struct)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 OutputStream (java.io.OutputStream)1 Iterator (java.util.Iterator)1 MimeType (lucee.commons.lang.mimetype.MimeType)1 Header (lucee.commons.net.http.Header)1