Class for encoding javascript types to RESP messages.

Public methods throw an error on an attempt to encode
an invalid type.

Stream methods emit an error event.
170824
function Encoder(options) {
  options = options || {};
  Transform.call(this, {objectMode: true});

  // string length chunk for bulk strings, strings large than this amount
  // are broken over process ticks so as not to block the event loop
  // note this is character length, not byte length
  this.strlen = options.strlen || 4096;

  // maximum array length before iterating using
  // setImmediate
  this.arrlen = 512;

  // allow buffers to be passed through untouched
  this.buffers = options.buffers;

  // treat buffers as bulk strings
  this.return_buffers = options.return_buffers;
}
507725
function rethrowPostcssError(error: Object): WrappedError {
  error.message = `${chalk.yellow('PostCSS error:')} ${error.message}`;
  if (error.name === 'CssSyntaxError') {
    error.message = error.message + '\n' + error.showSourceCode();
  }
  const typedError = wrapError(error, errorTypes.CssCompilationError);
  throw typedError;
}
45560
function encode(data) {
  var encodedData = null;
  try {
    encodedData = JSON.stringify(data);
  } catch (err) {
    logger.warn('failed encoding data', data);
  }
  return encodedData;
}
1334758
private void encodeStreamBody(StringBuffer result, JsJmsStreamMessage msg) {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "encodeStreamBody");
    // Internal method to get the stream as a List
    try {
      List<Object> body = ((JsJmsStreamMessageImpl)msg).getBodyList();
      if (body.size() > 0) {
        result.append('~');
        for (int i = 0; i < body.size(); i++) {
          encodeObject(result, body.get(i));
          if (i < body.size()-1)
            result.append('&');
        }
      }
    }
    catch (UnsupportedEncodingException e) {
      FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.WebJsJmsMessageEncoderImpl.encodeStreamBody", "245");
      // Just treat it as null.
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "encodeStreamBody");
  }
872596
function (input, encoding) {
        var module = _gpfEncodings[encoding];
        if (undefined === module) {
            gpf.Error.encodingNotSupported();
        }
        return new EncoderStream(module[0], input);
    }
1278390
function writeError(code, res, msg) {
	try{
		if (res.headerSent) {
			logger.error("header Sent:", res.req.method, res.req.originalUrl);
		}
		if (httpCodeMapping) {
			code = mapHttpStatusCode(code);
		}
		msg = msg instanceof Error ? msg.message : msg;
		addStrictTransportHeaders(res);
		setResponseNoCache(res);
		if (typeof msg === 'string') {
			var err = JSON.stringify({Severity: "Error", Message: msg});
			res.setHeader('Content-Type', 'application/json');
			res.setHeader('Content-Length', err.length);
			res.writeHead(code);
			res.end(err);
		} else {
			res.writeHead(code);
			res.end();
		}
	}catch(err){
		logger.error(res.req.originalUrl , err.message);
		throw err;
	}
}
708310
static void encode(Environment environment, LocalFunctionRegistry registry, Class returnType, Object result, OutputStream output) throws IOException {
        if (ClassUtils.isJavaLangType(returnType)) {
            if (result instanceof Byte) {
                output.write((Byte) result);
            } else if (result instanceof Boolean) {
                output.write(((Boolean) result) ? 1 : 0);
            } else if (result instanceof byte[]) {
                output.write((byte[]) result);
            } else {
                byte[] bytes = environment
                    .convert(result.toString(), byte[].class)
                    .orElseThrow(() -> new InvocationException("Unable to convert result [" + result + "] for output stream"));
                output.write(bytes);
            }
        }
775293
function ShiftJISEncoder(options) {
    var fatal = options.fatal;
    /**
     * @param {Stream} stream Input stream.
     * @param {number} code_point Next code point read from the stream.
     * @return {(number|!Array.<number>)} Byte(s) to emit.
     */
    this.handler = function(stream, code_point) {
      // 1. If code point is end-of-stream, return finished.
      if (code_point === end_of_stream)
        return finished;

      // 2. If code point is an ASCII code point or U+0080, return a
      // byte whose value is code point.
      if (isASCIICodePoint(code_point) || code_point === 0x0080)
        return code_point;

      // 3. If code point is U+00A5, return byte 0x5C.
      if (code_point === 0x00A5)
        return 0x5C;

      // 4. If code point is U+203E, return byte 0x7E.
      if (code_point === 0x203E)
        return 0x7E;

      // 5. If code point is in the range U+FF61 to U+FF9F, return a
      // byte whose value is code point − 0xFF61 + 0xA1.
      if (inRange(code_point, 0xFF61, 0xFF9F))
        return code_point - 0xFF61 + 0xA1;

      // 6. If code point is U+2212, set it to U+FF0D.
      if (code_point === 0x2212)
        code_point = 0xFF0D;

      // 7. Let pointer be the index shift_jis pointer for code point.
      var pointer = indexShiftJISPointerFor(code_point);

      // 8. If pointer is null, return error with code point.
      if (pointer === null)
        return encoderError(code_point);

      // 9. Let lead be floor(pointer / 188).
      var lead = floor(pointer / 188);

      // 10. Let lead offset be 0x81, if lead is less than 0x1F, and
      // 0xC1 otherwise.
      var lead_offset = (lead < 0x1F) ? 0x81 : 0xC1;

      // 11. Let trail be pointer % 188.
      var trail = pointer % 188;

      // 12. Let offset be 0x40, if trail is less than 0x3F, and 0x41
      // otherwise.
      var offset = (trail < 0x3F) ? 0x40 : 0x41;

      // 13. Return two bytes whose values are lead + lead offset and
      // trail + offset.
      return [lead + lead_offset, trail + offset];
    };
  }
1225565
function serialize(type, source, options) {
  var codec = type.codec
  if (!codec)
    return postEncode(new Buffer([ type.byte ]), options)

  var buffer = codec.encode(source, bytewise)

  if (options && options.nested && codec.escape)
    buffer = codec.escape(buffer)

  var hint = typeof codec.length === 'number' ? (codec.length + 1) : void 0 
  var buffers = [ new Buffer([ type.byte ]), buffer ]
  return postEncode(Buffer.concat(buffers, hint), options)
}
853157
public void encode(AsnOutputStream aos) throws EncodeException {

        if (type == null)
            throw new EncodeException("Error encoding AbortSource: No type set");

        try {
            aos.writeInteger(Tag.CLASS_CONTEXT_SPECIFIC, _TAG, type.getType());

        } catch (IOException e) {
            throw new EncodeException("IOException while encoding AbortSource: " + e.getMessage(), e);
        } catch (AsnException e) {
            throw new EncodeException("AsnException while encoding AbortSource: " + e.getMessage(), e);
        }
    }
318803
function (types) {

    that.logger.logEnter('callback in loadEventTypes, types:\n' + JSON.stringify(types));

    // The "raw" event type data has a deeply-nested structure and it
    // contains a bunch of stuff we're not interested in.  We'll just
    // store the names of each type's properties.
    Object.keys(types).forEach(function (typeName) {
      if (types[typeName].properties) {
        eventTypes[typeName] = Object.keys(types[typeName].properties);
      }
    });

    that.logger.log('eventTypes:\n' + JSON.stringify(eventTypes));

    if (process.env.TESTONLY_EMIT_INTERNAL_EVENTS) {
      that.emit(that.CONSTANT.internal_event_load_types_done);
    }

    // Now the event buffer can begin processing events.
    eventBuffer.ready();

    that.logger.logExit('callback in loadEventTypes');
  }
160793
function createStreamTransport(req, res) {
    // A transport object.
    var self = createBaseTransport(req, res);
    // Any error on request-response should propagate to transport.
    req.on("error", function(error) {
        self.emit("error", error);
    });
    res.on("error", function(error) {
        self.emit("error", error);
    });
    // When the underlying connection was terminated abnormally.
    res.on("close", function() {
        self.emit("close");
    });
    // When the complete response has been sent.
    res.on("finish", function() {
        self.emit("close");
    });

    // The response body should be formatted in the [event stream
    // format](http://www.w3.org/TR/eventsource/#parsing-an-event-stream).
    self.write = function(data) {
        // `data` should be either a `Buffer` or a string.
        if (typeof data === "string") {
            // A text message should be prefixed with `1`.
            data = "1" + data;
        } else {
            // A binary message should be encoded in Base64 and prefixed with
            // `2`.
            data = "2" + data.toString("base64");
        }
        // According to the format, data should be broken up by `\r`, `\n`, or
        // `\r\n`.
        var payload = data.split(/\r\n|[\r\n]/).map(function(line) {
            // Each line should be prefixed with 'data: ' and postfixed with
            // `\n`.
            return "data: " + line + "\n";
        })
        // Prints `\n` as the last character of a message.
        .join("") + "\n";
        // Writes it to response with `utf-8` encoding.
        res.write(payload, "utf-8");
    };
    // Ends the response. Accordingly, `res`'s `finish` event will be fired.
    self.close = function() {
        res.end();
        return this;
    };

    // The content-type headers should be `text/event-stream` for Server-Sent
    // Events and `text/plain` for others. Also the response should be encoded in `utf-8`.
    res.setHeader("content-type", "text/" + 
        // If it's Server-Sent Events, `sse` param is `true`.
        (req.params.sse === "true" ? "event-stream" : "plain") + "; charset=utf-8");
    // The padding is required, which makes the client-side transport on old
    // browsers be aware of change of the response. It should be greater
    // than 1KB, be composed of white space character and end with `\n`.
    var text2KB = Array(2048).join(" ");
    // Some host objects which are used to perform streaming transport can't or
    // don't allow to read response headers as well as write request headers.
    // That's why we uses the first message as a handshake output. The handshake
    // result should be formatted in URI. And transport id should be added as
    // `id` param.
    var uri = url.format({query: {id: self.id}});
    // Likewise some host objects in old browsers, junk data is needed to make
    // themselves be aware of change of response. Prints the padding and the
    // first message following `text/event-stream` with `utf-8` encoding.
    res.write(text2KB + "\ndata: " + uri + "\n\n", "utf-8");
    return self;    
}
581031
function handleStream(target, encoding, cb) {
		if (target.isNull()) {
			return cb(null, target);
		}

		if (target.isStream()) {
			return cb(error(target.path + ': Streams not supported for target templates!'));
		}

		try {
			const tagsRegExp = getRegExpTags(opt, null);
			target.contents = processContent(target, opt, tagsRegExp, [target.path]);
			this.push(target);
			return cb();
		} catch (err) {
			this.emit('error', err);
			return cb();
		}
	}
1272876
function encode(params) {
        var data, property, className;

        if(params === null){
            return params;
        }

        className = Object.prototype.toString.call(params).replace('[object ', '').replace(']', '');

        if ( className == 'Object' ) {
            data = {};

            Object.keys(params).forEach(function (property) {
                if ( (typeof params[property] !== 'undefined') && (typeof params[property] !== 'function') ) {
                    data[property.toString().underscore()] = this.encode(params[property]);
                }
            }, this);

        } else if (className == 'Array') {

            data = params.map(function (value) {
                return this.encode(value);
            }, this);

        } else {
            data = params;
        }

        return data;
    }
915759
function RawDecoder(schema, opts) {
  opts = opts || {};

  var noDecode = !!opts.noDecode;
  stream.Duplex.call(this, {
    readableObjectMode: !noDecode,
    allowHalfOpen: false
  });

  this._type = types.createType(files.load(schema));
  this._tap = new Tap(new Buffer(0));
  this._writeCb = null;
  this._needPush = false;
  this._readValue = createReader(noDecode, this._type);
  this._finished = false;

  this.on('finish', function () {
    this._finished = true;
    this._read();
  });
}
1273727
@SuppressWarnings({"unchecked", "rawtypes"})
    public U encode(Object value) {
        requireNonNull(value, "Value for encoding can not be null");

        TypeEncoder encoder = classMapping.get(value.getClass());
        if (encoder != null)
            return (U) encoder.encode(value);

        throw new TypeEncodingException("An unknown type [" + value.getClass() + "] was encountered");
    }
532782
function clientError(err, res) {
  log('error', err.message, { stack: err.stack });
  // They know it's a 400 already, we don't need to repeat the fact that its an error.
  const message = removePrefix(err.message, ':'),
    code = 400;

  sendDefaultResponseForCode(code, message, res);
}