/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.isup.ISUPMessageImpl#decodeMandatoryVariableBody(byte [], int)
357247
protected void decodeMandatoryVariableBody(ISUPParameterFactory parameterFactory, byte[] parameterBody, int parameterIndex)
            throws ParameterException {
        switch (parameterIndex) {
            case _INDEX_V_RangeAndStatus:

                RangeAndStatus ras = parameterFactory.createRangeAndStatus();
                ((AbstractISUPParameter) ras).decode(parameterBody);
                this.setRangeAndStatus(ras);
                break;
            case _INDEX_V_CircuitStateIndicator:
                CircuitStateIndicator csi = new CircuitStateIndicatorImpl(parameterBody);
                this.setCircuitStateIndicator(csi);
                break;

            default:
                throw new ParameterException("Unrecognized parameter index for mandatory variable part, index: "
                        + parameterIndex);

        }

    }
82294
@Override
	public CQVariables getVariables(PageContext pageContext) {
		log.trace("getBindings");

		CQVariablesImpl binding = new CQVariablesImpl();

		// Load all of the attributes from the current page context
		Enumeration<?> attrs = pageContext
				.getAttributeNamesInScope(PageContext.PAGE_SCOPE);
		while (attrs.hasMoreElements()) {
			String key = String.class.cast(attrs.nextElement());
			binding.put(key, pageContext.getAttribute(key));
		}

		// Put the request and response
		binding.put(SlingBindings.REQUEST, pageContext.getRequest());
		binding.put(SlingBindings.RESPONSE, pageContext.getResponse());

		if (pageContext.getAttribute("bindings") != null) {
			SlingBindings sb = SlingBindings.class.cast(pageContext
					.getAttribute("bindings"));
			for (String key : sb.keySet()) {
				binding.put(key, sb.get(key));
			}
		}

		return binding;
	}
1078263
private static JsJmsMessage decodeObjectBody(String body) throws MessageDecodeFailedException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "decodeObjectBody");
        JsJmsObjectMessage result = new JsJmsObjectMessageImpl(MfpConstants.CONSTRUCTOR_NO_OP);
        if (body != null)
            result.setSerializedObject(HexString.hexToBin(body, 0));
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "decodeObjectBody");
        return result;
    }
959774
public static VariableResolver getUpdateVariableResolver(ServletRequest request,
                                                             ServletResponse response,
                                                             boolean isHandlingPost) {
        Object form = ImplicitObjectUtil.unwrapForm(getActionForm(request));
        return new NetUIUpdateVariableResolver(form, request, response, isHandlingPost);
    }
570139
protected int decodeMandatoryVariableParameters(ISUPParameterFactory parameterFactory, byte[] b, int index)
            throws ParameterException {
        // FIXME: possibly this should also be per msg, since if msg lacks
        // proper parameter, decoding wotn pick this up and will throw
        // some bad output, which wont give a clue about reason...
        int readCount = 0;
        // int optionalOffset = 0;

        if (b.length - index > 0) {

            byte extPIndex = -1;
            try {
                int count = getNumberOfMandatoryVariableLengthParameters();
                readCount = count;
                for (int parameterIndex = 0; parameterIndex < count; parameterIndex++) {
                    int lengthPointerIndex = index + parameterIndex;
                    int parameterLengthIndex = b[lengthPointerIndex] + lengthPointerIndex;

                    int parameterLength = b[parameterLengthIndex];
                    byte[] parameterBody = new byte[parameterLength];
                    System.arraycopy(b, parameterLengthIndex + 1, parameterBody, 0, parameterLength);
                    decodeMandatoryVariableBody(parameterFactory, parameterBody, parameterIndex);

                }

                // optionalOffset = b[index + readCount];
            } catch (ArrayIndexOutOfBoundsException aioobe) {
                throw new ParameterException(
                        "Failed to read parameter, to few octets in buffer, parameter index: " + extPIndex, aioobe);
            } catch (IllegalArgumentException e) {
                throw new ParameterException("Failed to parse, paramet index: " + extPIndex, e);
            }
        } else {
            throw new ParameterException(
                    "To few bytes to decode mandatory variable part. There should be atleast on byte to indicate optional part.");
        }

        // return readCount + optionalOffset;
        return readCount;
    }
202246
private void encodeBytesBody(StringBuffer result, JsJmsBytesMessage msg) {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "encodeBytesBody");
    byte[] body = msg.getBytes();
    if (body != null) {
      result.append('~');
      HexString.binToHex(body, 0, body.length, result);
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "encodeBytesBody");
  }
331
protected void decodeOptionalBody(ISUPParameterFactory parameterFactory, byte[] parameterBody, byte parameterCode)
            throws ParameterException {

        switch (parameterCode & 0xFF) {
            case CauseIndicators._PARAMETER_CODE:
                CauseIndicators cpn = parameterFactory.createCauseIndicators();
                ((AbstractISUPParameter) cpn).decode(parameterBody);
                this.setCauseIndicators(cpn);
                break;
            default:
                throw new ParameterException("Unrecognized parameter index for optional part: " + parameterCode);
        }

    }
315426
private void buildDecoding(Mode mode,
                               CodeAssembler a,
                               StorableProperty<S>[] properties,
                               Direction[] directions,
                               LocalVariable instanceVar,
                               Class<?> adapterInstanceClass,
                               boolean useWriteMethods,
                               int generation,
                               Label altGenerationHandler,
                               LocalVariable encodedVar)
        throws SupportException
    {
        if (a == null) {
            throw new IllegalArgumentException();
        }
        if (encodedVar == null || encodedVar.getType() != TypeDesc.forClass(byte[].class)) {
            throw new IllegalArgumentException();
        }

        // Decoding order is:
        //
        // 1. Prefix
        // 2. Generation prefix
        // 3. Property states (if Mode.SERIAL)
        // 4. Properties
        // 5. Suffix

        final int prefix;
        switch (mode) {
        default: 
            prefix = 0;
            break;
        case KEY:
            prefix = mKeyPrefixPadding;
            break;
        case DATA:
            prefix = mDataPrefixPadding;
            break;
        }

        decodeGeneration(a, encodedVar, prefix, generation, altGenerationHandler);

        final int generationPrefix;
        if (generation < 0) {
            generationPrefix = 0;
        } else if (generation < 128) {
            generationPrefix = 1;
        } else {
            generationPrefix = 4;
        }

        final int suffix;
        switch (mode) {
        default: 
            suffix = 0;
            break;
        case KEY:
            suffix = mKeySuffixPadding;
            break;
        case DATA:
            suffix = mDataSuffixPadding;
            extraDataDecoding(a, encodedVar, prefix + generationPrefix, suffix);
            break;
        }

        final TypeDesc byteArrayType = TypeDesc.forClass(byte[].class);

        StorablePropertyInfo[] infos = checkSupport(properties);

        if (properties.length == 1) {
            StorableProperty<S> property = properties[0];
            StorablePropertyInfo info = infos[0];

            if (mode != Mode.SERIAL && info.getStorageType().toClass() == byte[].class) {
                // Since there is only one property, and it is just a byte
                // array, it doesn't have any fancy encoding.

                // Push to stack in preparation for storing a property.
                pushDecodingInstanceVar(a, 0, instanceVar);

                a.loadLocal(encodedVar);

                boolean descending = mode == Mode.KEY
                    && directions != null && directions[0] == Direction.DESCENDING;

                TypeDesc[] params;
                if (prefix > 0 || generationPrefix > 0 || suffix > 0) {
                    a.loadConstant(prefix + generationPrefix);
                    a.loadConstant(suffix);
                    params = new TypeDesc[] {byteArrayType, TypeDesc.INT, TypeDesc.INT};
                } else {
                    params = new TypeDesc[] {byteArrayType};
                }

                if (property.isNullable()) {
                    if (descending) {
                        a.invokeStatic(KeyDecoder.class.getName(), "decodeSingleNullableDesc",
                                       byteArrayType, params);
                    } else {
                        a.invokeStatic(DataDecoder.class.getName(), "decodeSingleNullable",
                                       byteArrayType, params);
                    }
                } else if (descending) {
                    a.invokeStatic(KeyDecoder.class.getName(), "decodeSingleDesc",
                                   byteArrayType, params);
                } else if (prefix > 0 || generationPrefix > 0 || suffix > 0) {
                    a.invokeStatic(DataDecoder.class.getName(), "decodeSingle",
                                   byteArrayType, params);
                } else {
                    // Always clone the byte array as some implementations
                    // reuse the byte array (e.g. iterating using a cursor).
                    a.invokeVirtual(TypeDesc.OBJECT, "clone", TypeDesc.OBJECT, null);
                    a.checkCast(byteArrayType);
                }

                storePropertyValue(a, info, useWriteMethods, instanceVar, adapterInstanceClass);
                return;
            }
        }

        // Now decode properties from the byte array.

        int constantOffset = prefix + generationPrefix;
        LocalVariable offsetVar = null;

        // References to local variables which will hold references.
        LocalVariable[] stringRefRef = new LocalVariable[1];
        LocalVariable[] byteArrayRefRef = new LocalVariable[1];
        LocalVariable[] bigIntegerRefRef = new LocalVariable[1];
        LocalVariable[] bigDecimalRefRef = new LocalVariable[1];
        LocalVariable[] valueRefRef = new LocalVariable[1];

        // Used by SERIAL mode.
        List<LocalVariable> stateVars = null;

        if (mode == Mode.SERIAL) {
            stateVars = decodePropertyStates(a, encodedVar, constantOffset, properties);
            constantOffset += (properties.length + 3) / 4;

            // Some properties are skipped at runtime, so offset variable is required.
            offsetVar = a.createLocalVariable(null, TypeDesc.INT);
            a.loadConstant(constantOffset);
            a.storeLocal(offsetVar);

            // References need to be initialized early because some properties
            // are skipped at runtime.

            for (int i=0; i<properties.length; i++) {
                TypeDesc storageType = infos[i].getStorageType();

                if (storageType == TypeDesc.STRING) {
                    if (stringRefRef[0] == null) {
                        TypeDesc refType = TypeDesc.forClass(String[].class);
                        stringRefRef[0] = a.createLocalVariable(null, refType);
                        a.loadConstant(1);
                        a.newObject(refType);
                        a.storeLocal(stringRefRef[0]);
                    }
                } else if (storageType.toClass() == byte[].class) {
                    if (byteArrayRefRef[0] == null) {
                        TypeDesc refType = TypeDesc.forClass(byte[][].class);
                        byteArrayRefRef[0] = a.createLocalVariable(null, refType);
                        a.loadConstant(1);
                        a.newObject(refType);
                        a.storeLocal(byteArrayRefRef[0]);
                    }
                } else if (storageType.toClass() == BigInteger.class) {
                    if (bigIntegerRefRef[0] == null) {
                        TypeDesc refType = TypeDesc.forClass(BigInteger[].class);
                        bigIntegerRefRef[0] = a.createLocalVariable(null, refType);
                        a.loadConstant(1);
                        a.newObject(refType);
                        a.storeLocal(bigIntegerRefRef[0]);
                    }
                } else if (storageType.toClass() == BigDecimal.class) {
                    if (bigDecimalRefRef[0] == null) {
                        TypeDesc refType = TypeDesc.forClass(BigDecimal[].class);
                        bigDecimalRefRef[0] = a.createLocalVariable(null, refType);
                        a.loadConstant(1);
                        a.newObject(refType);
                        a.storeLocal(bigDecimalRefRef[0]);
                    }
                }
            }
        }

        for (int i=0; i<properties.length; i++) {
            StorableProperty<S> property = properties[i];
            StorablePropertyInfo info = infos[i];

            Label storePropertyLocation = a.createLabel();
            Label nextPropertyLocation = a.createLabel();

            // Push to stack in preparation for storing a property.
            pushDecodingInstanceVar(a, i, instanceVar);

            if (mode == Mode.SERIAL) {
                // Load property if initialized, else reset it.

                a.loadLocal(stateVars.get(property.getNumber() >> 4));
                a.loadConstant(PROPERTY_STATE_MASK << ((property.getNumber() & 0xf) * 2));
                a.math(Opcode.IAND);
                Label isInitialized = a.createLabel();
                a.ifZeroComparisonBranch(isInitialized, "!=");

                // Reset property value to zero, false, or null.
                loadBlankValue(a, TypeDesc.forClass(property.getType()));

                if (info.getToStorageAdapter() != null) {
                    // Bypass adapter.
                    a.storeField(info.getPropertyName(), info.getPropertyType());
                    a.branch(nextPropertyLocation);
                } else {
                    a.branch(storePropertyLocation);
                }

                isInitialized.setLocation();
            }

            TypeDesc storageType = info.getStorageType();

            if (info.isLob()) {
                // Need RawSupport instance for getting Lob from locator.
                pushRawSupport(a, instanceVar);

                // Also need to pass this stuff along when getting Lob.
                a.loadThis();
                a.loadConstant(info.getPropertyName());

                // Locator is encoded as a long.
                storageType = TypeDesc.LONG;
            }

            a.loadLocal(encodedVar);
            if (offsetVar == null) {
                a.loadConstant(constantOffset);
            } else {
                a.loadLocal(offsetVar);
            }

            boolean descending = mode == Mode.KEY
                && directions != null && directions[i] == Direction.DESCENDING;

            int amt = decodeProperty(a, info, storageType, mode, descending,
                                     // TODO: do something better for passing these refs
                                     stringRefRef, byteArrayRefRef,
                                     bigIntegerRefRef, bigDecimalRefRef,
                                     valueRefRef);

            if (info.isLob()) {
                getLobFromLocator(a, info);
            }

            if (amt != 0) {
                if (i + 1 < properties.length) {
                    // Only adjust offset if there are more properties.

                    if (amt > 0) {
                        if (offsetVar == null) {
                            constantOffset += amt;
                        } else {
                            a.loadConstant(amt);
                            a.loadLocal(offsetVar);
                            a.math(Opcode.IADD);
                            a.storeLocal(offsetVar);
                        }
                    } else {
                        // Offset adjust is one if returned object is null.
                        a.dup();
                        Label notNull = a.createLabel();
                        a.ifNullBranch(notNull, false);
                        a.loadConstant(1 + (offsetVar == null ? constantOffset : 0));
                        Label cont = a.createLabel();
                        a.branch(cont);
                        notNull.setLocation();
                        a.loadConstant(~amt + (offsetVar == null ? constantOffset : 0));
                        cont.setLocation();

                        if (offsetVar == null) {
                            offsetVar = a.createLocalVariable(null, TypeDesc.INT);
                        } else {
                            a.loadLocal(offsetVar);
                            a.math(Opcode.IADD);
                        }
                        a.storeLocal(offsetVar);
                    }
                }
            } else {
                if (i + 1 >= properties.length) {
                    // Don't need to keep track of offset anymore.
                    a.pop();
                } else {
                    // Only adjust offset if there are more properties.
                    if (offsetVar == null) {
                        if (constantOffset > 0) {
                            a.loadConstant(constantOffset);
                            a.math(Opcode.IADD);
                        }
                        offsetVar = a.createLocalVariable(null, TypeDesc.INT);
                    } else {
                        a.loadLocal(offsetVar);
                        a.math(Opcode.IADD);
                    }
                    a.storeLocal(offsetVar);
                }

                // Get the value out of the ref array so that it can be stored.
                a.loadLocal(valueRefRef[0]);
                a.loadConstant(0);
                a.loadFromArray(valueRefRef[0].getType());
            }

            storePropertyLocation.setLocation();

            storePropertyValue(a, info, useWriteMethods, instanceVar, adapterInstanceClass);

            nextPropertyLocation.setLocation();
        }

        if (stateVars != null) {
            for (int i=0; i<stateVars.size(); i++) {
                LocalVariable stateVar = stateVars.get(i);
                if (stateVar != null) {
                    a.loadThis();
                    a.loadLocal(stateVar);
                    a.storeField(PROPERTY_STATE_FIELD_NAME + i, TypeDesc.INT);
                }
            }
        }
    }
1212708
@Override
    public Object resolveVariable(QName variableName) {
        final Map<String, ?> variables = this.localVariables.get();
        if (variables == null) {
            return null;
        }

        final String localPart = variableName.getLocalPart();
        return variables.get(localPart);
    }
505545
public static String parseSessionVariables(String sessionVariable) {
    StringBuilder out = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    Parse state = Parse.Normal;
    boolean iskey = true;
    boolean singleQuotes = true;
    boolean first = true;
    String key = null;

    char[] chars = sessionVariable.toCharArray();

    for (char car : chars) {

      if (state == Parse.Escape) {
        sb.append(car);
        state = singleQuotes ? Parse.Quote : Parse.String;
        continue;
      }

      switch (car) {
        case '"':
          if (state == Parse.Normal) {
            state = Parse.String;
            singleQuotes = false;
          } else if (state == Parse.String && !singleQuotes) {
            state = Parse.Normal;
          }
          break;

        case '\'':
          if (state == Parse.Normal) {
            state = Parse.String;
            singleQuotes = true;
          } else if (state == Parse.String && singleQuotes) {
            state = Parse.Normal;
          }
          break;

        case '\\':
          if (state == Parse.String) {
            state = Parse.Escape;
          }
          break;

        case ';':
        case ',':
          if (state == Parse.Normal) {
            if (!iskey) {
              if (!first) {
                out.append(",");
              }
              out.append(key);
              out.append(sb.toString());
              first = false;
            } else {
              key = sb.toString().trim();
              if (!key.isEmpty()) {
                if (!first) {
                  out.append(",");
                }
                out.append(key);
                first = false;
              }
            }
            iskey = true;
            key = null;
            sb = new StringBuilder();
            continue;
          }
          break;

        case '=':
          if (state == Parse.Normal && iskey) {
            key = sb.toString().trim();
            iskey = false;
            sb = new StringBuilder();
          }
          break;

        default:
          //nothing
      }

      sb.append(car);
    }

    if (!iskey) {
      if (!first) {
        out.append(",");
      }
      out.append(key);
      out.append(sb.toString());
    } else {
      String tmpkey = sb.toString().trim();
      if (!tmpkey.isEmpty() && !first) {
        out.append(",");
      }
      out.append(tmpkey);
    }
    return out.toString();
  }
652128
private byte[] getBody(String method) {
        byte[] body = null;
    	String methodsWithInputEntity = HttpMethod.POST.name() + "|" + HttpMethod.PUT.name() + "|" + HttpMethod.DELETE.name();
    	if (method.matches(methodsWithInputEntity)) {
            if (isCompound()) {
                body = Utils.toBytes(getQueryInputEntity());
            }
            else {
                if (metadataJson.containsKey(INPUT_ENTITY)) {
                    JSONable data = (JSONable)commandParams.get(metadataJson.getString(INPUT_ENTITY));
                    if (data != null) {
                        body = Utils.toBytes(data.toJSON());
                    }
                }
            }
        }
        return body;
    }
173639
protected int decodeMandatoryParameters(ISUPParameterFactory parameterFactory, byte[] b, int index)
            throws ParameterException {
        int localIndex = index;
        if (b.length - index >= 3) {
            try {
                byte[] cic = new byte[2];
                cic[0] = b[index++];
                cic[1] = b[index++];
                this.cic = new CircuitIdentificationCodeImpl();
                ((AbstractISUPParameter) this.cic).decode(cic);

            } catch (Exception e) {
                // AIOOBE or IllegalArg
                throw new ParameterException("Failed to parse CircuitIdentificationCode due to: ", e);
            }
            try {
                // Message Type
                if (b[index] != this.getMessageType().getCode()) {
                    throw new ParameterException("Message code is not: " + this.getMessageType().getCode());
                }
            } catch (Exception e) {
                // AIOOBE or IllegalArg
                throw new ParameterException("Failed to parse MessageCode due to: ", e);
            }
            index++;

            // return 3;
            return index - localIndex;
        } else {
            throw new IllegalArgumentException("byte[] must have atleast three octets");
        }
    }
793825
protected void encodeMandatoryParameters(Map<Integer, ISUPParameter> parameters, ByteArrayOutputStream bos)
            throws ParameterException {
        // 1.5 Mandatory fixed part
        // Those parameters that are mandatory and of fixed length for a
        // particular message type will be
        // contained in the mandatory fixed part. The position, length and order
        // of the parameters is uniquely
        // defined by the message type; thus, the names of the parameters and
        // the length indicators are not
        // included in the message.
        if (this.cic == null) {
            // this will be changed to different exception
            throw new ParameterException("CIC is not set!");
        }
        ((AbstractISUPParameter) this.cic).encode(bos);
        for (ISUPParameter p : parameters.values()) {
            ((AbstractISUPParameter) p).encode(bos);
        }
    }
401878
private void decodeMandatoryHeader() throws IOException {
        byte[] magicBytes = new byte[8];
        file.readFully(magicBytes);
        if (!Arrays.equals(SmjpegMagic.MANDATORY_HEADER, magicBytes)) {
            throw new SmjpegParsingException("This is not a SMJPEG file");
        }
        int version = file.readInt();
        if (version != 0) {
            throw new SmjpegParsingException("Unknow version " + version);
        }
        this.clipLengthInMilliseconds = file.readInt();
    }
1050149
public static void decodeUISelectOne(FacesContext facesContext, UIComponent component)
    {
        if (!(component instanceof EditableValueHolder))
        {
            throw new IllegalArgumentException("Component "
                    + component.getClientId(facesContext)
                    + " is not an EditableValueHolder");
        }
        if (isDisabledOrReadOnly(component))
        {
            return;
        }
        Map paramMap = facesContext.getExternalContext().getRequestParameterMap();
        String clientId = component.getClientId(facesContext);
        if (paramMap.containsKey(clientId))
        {
            //request parameter found, set submitted value
            ((EditableValueHolder) component).setSubmittedValue(paramMap.get(clientId));
        }
        else
        {
            //see reason for this action at decodeUISelectMany
            ((EditableValueHolder) component).setSubmittedValue(STR_EMPTY);
        }
    }
1141376
@Deprecated
    public byte[] getPostBody() throws AuthFailureError {
        // Note: For compatibility with legacy clients of volley, this implementation must remain
        // here instead of simply calling the getBody() function because this function must
        // call getPostParams() and getPostParamsEncoding() since legacy clients would have
        // overridden these two member functions for POST requests.
        Map<String, String> postParams = getPostParams();
        if (postParams != null && postParams.size() > 0) {
            return encodeParameters(postParams, getPostParamsEncoding());
        }
        return null;
    }
35331
static <T extends SAMLObject> MessageContext<T> toSamlObject(AggregatedHttpMessage msg, String name) {
        final SamlParameters parameters = new SamlParameters(msg);
        final byte[] decoded;
        try {
            decoded = Base64.getMimeDecoder().decode(parameters.getFirstValue(name));
        } catch (IllegalArgumentException e) {
            throw new SamlException("failed to decode a base64 string of the parameter: " + name, e);
        }

        @SuppressWarnings("unchecked")
        final T message = (T) deserialize(decoded);

        final MessageContext<T> messageContext = new MessageContext<>();
        messageContext.setMessage(message);

        final String relayState = parameters.getFirstValueOrNull(RELAY_STATE);
        if (relayState != null) {
            final SAMLBindingContext context = messageContext.getSubcontext(SAMLBindingContext.class, true);
            assert context != null;
            context.setRelayState(relayState);
        }

        return messageContext;
    }