/*
(non-Javadoc)

@see
javax.sip.SipProvider#getNewServerTransaction(javax.sip.message.Request)
189051
public ServerTransaction getNewServerTransaction(Request request)
			throws TransactionAlreadyExistsException,
			TransactionUnavailableException {

		checkState();
		// TODO: add checks for wrapper

		final SIPServerTransaction st = (SIPServerTransaction) provider.getNewServerTransaction(request);
		ServerTransactionWrapper stw = new ServerTransactionWrapper(st, ra);

		if (stw.getDialogWrapper() == null) {
			// SLEE 1.1 specs: D.4
			// ServerTransaction Activity objects are created automatically when
			// the resource adaptor receives an
			// incoming SIP request. The activity ends when a final response is
			// sent on the ServerTransaction.
			stw.setActivity(true);
			if (!ra.addSuspendedActivity(stw)) {
				throw new TransactionUnavailableException(
						"Failed to create activity.");
			}
		}

		return stw;
	}
1315302
@Benchmark
  @BenchmarkMode(Mode.SampleTime)
  @OutputTimeUnit(TimeUnit.NANOSECONDS)
  public String messageDecodePlain() {
    return Status.MESSAGE_KEY.parseBytes(
        "Unexpected RST in stream".getBytes(Charset.forName("US-ASCII")));
  }
1120908
public BoxRequestsFile.UploadNewVersion getUploadNewVersionRequest(File file, String destinationFileId) {
        try {
            BoxRequestsFile.UploadNewVersion request = getUploadNewVersionRequest(new FileInputStream(file), destinationFileId);
            request.setUploadSize(file.length());
            request.setModifiedDate(new Date(file.lastModified()));
            return request;
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException(e);
        }
    }
905159
private static void handleOrphanRequest(final SipProvider sipProvider,
			final SipServletRequestImpl sipServletRequest,
			String applicationId, final SipContext sipContext)
			throws DispatcherException {
		final String applicationName = sipContext.getApplicationName();
		final Request request = (Request) sipServletRequest.getMessage();
		
		// Making sure to nullify those ref so that if there is a race condition as in 
		// http://code.google.com/p/mobicents/issues/detail?id=2937
		// we return null instead of the invalidated sip application session
		sipServletRequest.setSipSession(null);
		sipServletRequest.setSipSessionKey(null);		
		sipServletRequest.setOrphan(true);
		sipServletRequest.setAppSessionId(applicationId);
		sipServletRequest.setCurrentApplicationName(applicationName);
		try {
			MessageDispatcher.callServletForOrphanRequest(sipContext, sipServletRequest);
			try {
				String transport = JainSipUtils.findTransport(request);
				SipConnector connector = StaticServiceHolder.sipStandardService.findSipConnector(transport);
				
				String branch = ((ViaHeader)sipServletRequest.getMessage().getHeader(ViaHeader.NAME)).getBranch();
				ViaHeader via = JainSipUtils.createViaHeader(sipContext.getSipApplicationDispatcher().getSipNetworkInterfaceManager(), request, 
						JainSipUtils.createBranch("orphan", 
								sipContext.getSipApplicationDispatcher().getHashFromApplicationName(applicationName),
								Integer.toString(branch.hashCode()) + branch.substring(branch.length()/2)), 
								null) ;
				if(connector.isUseStaticAddress()) {
					try {
						via.setHost(connector.getStaticServerAddress());
						via.setPort(connector.getStaticServerPort());
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
					
				}
				sipServletRequest.getMessage().addHeader(via);

				sipProvider.sendRequest((Request) sipServletRequest.getMessage());
				sipContext.getSipApplicationDispatcher().updateRequestsStatistics(request, false);
			} catch (SipException e) {
				logger.error("Error routing orphaned request" ,e);
			}
			return;
		} catch (ServletException e) {
			throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
		} catch (IOException e) {				
			throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
		}
	}
1107455
SubscriptionMessageHandler getMessageHandler()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "getMessageHandler");

    SubscriptionMessageHandler messageHandler =
      (SubscriptionMessageHandler) _subscriptionMessagePool.remove();

    if (messageHandler == null)
    {
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        SibTr.debug(
          tc,
          "doProxySubscribeOp",
          "Creating a new Message Handler as none available");

      messageHandler = new SubscriptionMessageHandler(this);
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "getMessageHandler", messageHandler);

    return messageHandler;
  }
1366439
protected Object getNewSelection(final Request request) {
		String paramValue = request.getParameter(getId());

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

		// Figure out which option has been selected.
		List<?> options = getOptions();

		if (options == null || options.isEmpty()) {
			if (!isEditable()) {
				// User could not have made a selection.
				return null;
			}

			options = Collections.EMPTY_LIST;
		}

		int optionIndex = 0;

		for (Object option : options) {
			if (option instanceof OptionGroup) {
				List<?> groupOptions = ((OptionGroup) option).getOptions();
				if (groupOptions != null) {
					for (Object nestedOption : groupOptions) {
						if (paramValue.equals(optionToCode(nestedOption, optionIndex++))) {
							return nestedOption;
						}
					}
				}
			} else if (paramValue.equals(optionToCode(option, optionIndex++))) {
				return option;
			}
		}

		// Option not found, but if editable, user entered text
		if (isEditable()) {
			return paramValue;
		}

		// Invalid option. Ignore and use the current selection
		LOG.warn(
				"Option \"" + paramValue + "\" on the request is not a valid option. Will be ignored.");
		Object currentOption = getValue();
		return currentOption;
	}
74104
@Override
    public UndeliverableReturnCode handleUndeliverableMessage(
                                                              SIMPMessage msg,
                                                              int exceptionReason,
                                                              String[] exceptionInserts,
                                                              TransactionCommon tran)
                    throws
                    SIResourceException
    {
        // F001333-14610
        // Delegate down onto the new method passing a null
        // subscription ID.
        return handleUndeliverableMessage(msg, exceptionReason, exceptionInserts, tran, null);
    }
522709
protected void logRequest(String logMessage, MessageContext messageContext, boolean incoming) throws TransformerException {
        if (messageContext.getRequest() instanceof SoapMessage) {
            logSoapMessage(logMessage, (SoapMessage) messageContext.getRequest(), incoming);
        } else {
            logWebServiceMessage(logMessage, messageContext.getRequest(), incoming);
        }
    }
903792
@Override
    public Optional<SipHeader> getHeader(final Buffer headerName) throws SipPacketParseException {
        return this.msg.getHeader(headerName);
    }
787969
public JsMessage transcribeToJmf() throws MessageCopyFailedException
                                          , IncorrectMessageTypeException
                                          , UnsupportedEncodingException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "transcribeToJmf");
    JsMsgObject newJmo = null;

    // Try/catch block in case we get an MFPUnsupportedEncodingRuntimeException because the
    // payload is in an unsupported codepage.   d252277.2
    try {

     if (this instanceof JsJmsMessageImpl) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Transcribing from JsJmsMessageImpl");
        newJmo = jmo.transcribeToJmf();
      }

      else {
        // Non-JMS messages are not supported - they should have been converted into JMS by now
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Non-JMS Messages are not yet supported");
        String exString = nls.getFormattedMessage("UNEXPECTED_MESSAGE_TYPE_CWSIF0102"
                                                 ,new Object[] {getJsMessageType(), MessageType.JMS}
                                                 ,"The Message can not be represented as a pure JMF Message");
        throw new IncorrectMessageTypeException(exString);

      }
    }
    catch (MFPUnsupportedEncodingRuntimeException e) {
      FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsMessageImpl.transcribeToJmf", "721");
      // Throw the original UnsupportedEncodingException
      throw (UnsupportedEncodingException)e.getCause();
    }

    JsMessage newMsg;
    // if we have a new jmo, create a new message from it
    if (newJmo != this.jmo) {
      newMsg = createNewGeneralized(newJmo);
    }
    // otherwise, just return ourself
    else {
      newMsg = this;
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "transcribeToJmf", newMsg);
    return newMsg;
  }
1310128
public void requestMsgs(int requestNumber, int receivedBytes, int requestedBytes)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "requestMsgs",
                                           new Object[]{requestNumber, receivedBytes, requestedBytes});

      SIErrorException e = new SIErrorException(
         nls.getFormattedMessage("PROTOCOL_ERROR_SICO2003", null,null)
      );

      FFDCFilter.processException(e, CLASS_NAME + ".requestMsgs",
                                  CommsConstants.CATCONSUMER_REQUESTMSGS_01,
                                  this);

      SibTr.error(tc, "PROTOCOL_ERROR_SICO2003", e);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "requestMsgs");

      // Re-throw this exception so that the client will informed if required
      throw e;
   }
109865
public BaseMessage sendMessageRequest(BaseMessage messageOut)
    {
        TrxMessageHeader trxMessageHeader = (TrxMessageHeader)messageOut.getMessageHeader();
        String strTrxID = (String)trxMessageHeader.get(TrxMessageHeader.LOG_TRX_ID);
        try {
            // Create a fake Incoming message with this message's external data
            String strMessageCode = (String)trxMessageHeader.get(LocalMessageTransport.LOCAL_PROCESSOR);
            TrxMessageHeader trxMessageHeaderIn = new TrxMessageHeader(null, null);
            trxMessageHeaderIn.put(TrxMessageHeader.MESSAGE_CODE, strMessageCode);

            BaseMessage messageIn = new TreeMessage(trxMessageHeaderIn, null);
            new ExternalMapTrxMessageIn(messageIn, messageOut.getExternalMessage().getRawData());
            // And fake send it by calling this:
            BaseMessage messageReply = this.processIncomingMessage(messageIn, null);
            this.logMessage(strTrxID, messageOut, MessageInfoTypeModel.REQUEST, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.SENT, null, null);

            this.setupReplyMessage(messageReply, null, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT);
            int iErrorCode = this.convertToExternal(messageReply, null);
            if (iErrorCode != DBConstants.NORMAL_RETURN)
            {
                String strMessageDescription = this.getTask().getLastError(iErrorCode);
                if ((strMessageDescription == null) || (strMessageDescription.length() == 0))
                    strMessageDescription = "Error converting to external format";
                messageReply = BaseMessageProcessor.processErrorMessage(this, messageOut, strMessageDescription);
            }

            return messageReply;
        } catch (Throwable ex)  {
            ex.printStackTrace();
            String strError = "Error in processing or replying to a message";
            Utility.getLogger().warning(strError);
            this.logMessage(strTrxID, null, MessageInfoTypeModel.REQUEST, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.ERROR, strError, null);
            return BaseMessageProcessor.processErrorMessage(this, messageOut, strError);
        }
    }
21221
@Override
    public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage request,
                                 Class<?> expectedResultType) throws Exception {
        if (expectedResultType == String.class ||
            expectedResultType == CharSequence.class) {
            final MediaType contentType = request.contentType();
            if (contentType != null && contentType.is(MediaType.ANY_TEXT_TYPE)) {
                return request.content(
                        contentType.charset().orElse(ArmeriaHttpUtil.HTTP_DEFAULT_CONTENT_CHARSET));
            }
        }
        return RequestConverterFunction.fallthrough();
    }
1164319
@Nullable
    public SharedElementCallback getExitTransitionCallback(@NonNull ViewGroup container, @Nullable View from, @Nullable View to, boolean isPush) {
        return null;
    }
1009677
@Override
  public TestSession getNewSession(Map<String, Object> requestedCapability) {
    if (down) {
      return null;
    }
    return super.getNewSession(requestedCapability);
  }
172131
protected InputStream getBase64DecodedMessage(HTTPInTransport transport) throws MessageDecodingException {
        log.debug("Getting Base64 encoded message from request");
        String encodedMessage = transport.getParameterValue("assertion");


        if (DatatypeHelper.isEmpty(encodedMessage)) {
            log.error("Request did not contain either a SAMLRequest or "
                          + "SAMLResponse paramter.  Invalid request for SAML 2 HTTP POST binding.");
            throw new MessageDecodingException("No SAML message present in request");
        }

        log.trace("Base64 decoding SAML message:\n{}", encodedMessage);
        byte[] decodedBytes = org.apache.commons.codec.binary.Base64.decodeBase64(encodedMessage.getBytes(StandardCharsets.UTF_8));
        if(decodedBytes == null){
            log.error("Unable to Base64 decode SAML message");
            throw new MessageDecodingException("Unable to Base64 decode SAML message");
        }

        log.trace("Decoded SAML message:\n{}", new String(decodedBytes));
        return new ByteArrayInputStream(decodedBytes);
    }
647416
private MessageEmitSvlt getMessageObj(final HttpServletRequest request,
                                        final MessageResources messages) {
    return (MessageEmitSvlt)StrutsUtil
            .getMessageObj(getId(), this, request,
                           messages,
                           getMessageObjAttrName(),
                           getErrorObjErrProp(),
                           clearMessages());
  }