/* (non-Javadoc)
@see com.emc.ecs.nfsclient.nfs.Nfs#makeCommitRequest(byte[], long, int)
505807
public Nfs3CommitRequest makeCommitRequest(byte[] fileHandle, long offsetToCommit, int dataSizeToCommit) throws FileNotFoundException {
        return new Nfs3CommitRequest(fileHandle, offsetToCommit, dataSizeToCommit, _credential);
    }
1276077
private <T> void submitCommand(CommandRequest request, CompletableFuture<T> future) {
    submit(new CommandAttempt<>(sequencer.nextRequest(), request, future));
  }
250484
public static void rcvXACommit(CommsByteBuffer request,
                                  Conversation conversation,
                                  int requestNumber,
                                  boolean allocatedFromBufferPool,
                                  boolean partOfExchange)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "rcvXACommit",
                                           new Object[]
                                           {
                                              request,
                                              conversation,
                                              ""+requestNumber,
                                              ""+allocatedFromBufferPool,
                                              ""+partOfExchange
                                            });

      ConversationState convState = (ConversationState) conversation.getAttachment();
      ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment();

      boolean onePhase = false;

      final boolean optimizedTx = CommsUtils.requiresOptimizedTransaction(conversation);

      try
      {
         int clientTransactionId = request.getInt();
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
         {
            SibTr.debug(tc, "XAResource Object ID", clientTransactionId);
         }

         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Getting Xid");
         XidProxy xid = (XidProxy) request.getXid();
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Completed:", xid);

         byte onePhaseByte = request.get();
         if (onePhaseByte == 1) onePhase = true;
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "One phase:", onePhase);

         boolean endRequired = false;
         int endFlags = 0;
         if (optimizedTx)
         {
            endRequired = request.get() == 0x01;
            endFlags = request.getInt();

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            {
               SibTr.debug(tc, "End Required:", ""+endRequired);
               SibTr.debug(tc, "End Flags:", ""+endFlags);
            }
         }

         boolean requiresMSResource = false;
         if (conversation.getHandshakeProperties().getFapLevel() >= JFapChannelConstants.FAP_VERSION_5)
         {
            requiresMSResource = request.get() == 0x01;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Requires MS Resource:", ""+requiresMSResource);
         }

         // Get the transaction out of the table
         IdToTransactionTable transactionTable = linkState.getTransactionTable();
         if (endRequired) transactionTable.endOptimizedGlobalTransactionBranch(clientTransactionId, endFlags);
         SITransaction tran = null;

         // As commits (for the same XAResource) can be scheduled concurrently by the receive listener
         // dispatcher - perform all updates to the IdToTransaction table inside a synchronized block.
         boolean isInvalidTransaction = false;
         boolean isUnitOfWorkInError = false;
         Throwable rollbackException = null;
         synchronized(transactionTable)
         {
            tran = transactionTable.getResourceForGlobalTransactionBranch(clientTransactionId, xid);
            if (tran != null)
            {
               isInvalidTransaction = tran == IdToTransactionTable.INVALID_TRANSACTION;
               if (!isInvalidTransaction)
               {
                  isUnitOfWorkInError =
                     transactionTable.isGlobalTransactionBranchRollbackOnly(clientTransactionId, xid);
               }

               if (isInvalidTransaction || isUnitOfWorkInError)
               {
                  rollbackException =
                     transactionTable.getExceptionForRollbackOnlyGlobalTransactionBranch(clientTransactionId, xid);
               }

               // Leave the invalid transaction in the table.  The only way to remove it is to
               // roll it back.
               if (!isInvalidTransaction)
               {
                  transactionTable.removeGlobalTransactionBranch(clientTransactionId, xid);
               }
            }
         }

         SIXAResource xaResource = getResourceFromTran(tran, convState, requiresMSResource);

         // If the UOW was never created (because we were running with the
         // optimization that gets an XAResource and enlists it as part of the
         // first piece of transacted work and this failed) then throw
         // an exception notifying the caller that the UOW has been rolled back.
         if (isInvalidTransaction)
         {
            String errorMsg =
               nls.getFormattedMessage("TRANSACTION_MARKED_AS_ERROR_SICO2029",
                     new Object[]{ rollbackException },
                     null);

            XAException xa = new XAException(errorMsg);
            xa.initCause(rollbackException);
            xa.errorCode = XAException.XA_RBOTHER;

            throw xa;
         }

         if (isUnitOfWorkInError)
         {
            // PK59276 Rollback the transaction, as after we throw a XA_RB* error the
            // transaction manager will not call us with xa_rollback.
            xaResource.rollback(xid);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "The transaction was marked as error due to",
                                                 rollbackException);

            // And respond with an error
            XAException xa = new XAException(
               nls.getFormattedMessage("TRANSACTION_MARKED_AS_ERROR_SICO2029",
                                       new Object[]{ rollbackException },
                                       null)
            );
            xa.initCause(rollbackException);
            xa.errorCode = XAException.XA_RBOTHER;

            throw xa;
         }

         // Now call the method on the XA resource
         xaResource.commit(xid, onePhase);

         try
         {
            conversation.send(poolManager.allocate(),
                              JFapChannelConstants.SEG_XACOMMIT_R,
                              requestNumber,
                              JFapChannelConstants.PRIORITY_MEDIUM,
                              true,
                              ThrottlingPolicy.BLOCK_THREAD,
                              null);
         }
         catch (SIException e)
         {
            FFDCFilter.processException(e,
                                        CLASS_NAME + ".rcvXACommit",
                                        CommsConstants.STATICCATXATRANSACTION_XACOMMIT_01);

            SibTr.error(tc, "COMMUNICATION_ERROR_SICO2027", e);
         }
      }
      catch (XAException e)
      {
         FFDCFilter.processException(e,
                                     CLASS_NAME + ".rcvXACommit",
                                     CommsConstants.STATICCATXATRANSACTION_XACOMMIT_02);

         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "XAException - RC: " + e.errorCode, e);

         StaticCATHelper.sendExceptionToClient(e,
                                               CommsConstants.STATICCATXATRANSACTION_XACOMMIT_02,     // d186970
                                               conversation, requestNumber);
      }

      request.release(allocatedFromBufferPool);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "rcvXACommit");
   }
476954
public void putTransaction(SipServletRequestImpl request) {
            final String txId = ((ViaHeader) request.getMessage().getHeader(ViaHeader.NAME)).getBranch();
            final TransactionApplicationData txData = request.getTransactionApplicationData();
            if(txData != null && this.transactionMap.put(txId, txData) == null) {
                    if(logger.isDebugEnabled()) {
                            logger.debug("Transaction "+txId+" added to proxy.");
                    }
            }                               
    }
229520
@Override
    public void actionCommit() {

        try {
            float age = (System.currentTimeMillis() - Long.parseLong(m_time)) / (60f * 60f * 1000f);
            OpenCms.fireCmsEvent(
                new CmsEvent(
                    I_CmsEventListener.EVENT_CLEAR_CACHES,
                    Collections.<String, Object> singletonMap(CmsImageLoader.PARAM_CLEAR_IMAGES_CACHE, "" + age)));
        } catch (Exception e) {
            setCommitErrors(Collections.singletonList((Throwable)e));
        }
    }
849698
@Override
    public PayCreatResponse create(final PayCreatRequest request) {
        request.checkVaild();
        final PayCreatResponse result = new PayCreatResponse();
        try {
            final WeixinPayElement element = elements.get(request.getAppid());
            if (element == null) return result.retcode(RETPAY_CONF_ERROR);
            final TreeMap<String, String> map = new TreeMap<>();
            if (request.getAttach() != null) map.putAll(request.getAttach());
            map.put("appid", element.appid);
            map.put("mch_id", element.merchno);
            map.put("nonce_str", Long.toHexString(System.currentTimeMillis()) + Long.toHexString(System.nanoTime()));
            map.put("body", request.getPaybody());
            //map.put("attach", "" + payid);
            map.put("out_trade_no", request.getPayno());
            map.put("total_fee", "" + request.getPaymoney());
            map.put("spbill_create_ip", request.getClientAddr());
            map.put("time_expire", String.format(format, System.currentTimeMillis() + request.getPaytimeout() * 1000));
            map.put("notify_url", element.notifyurl);
            map.put("sign", createSign(element, map));

            final String responseText = Utility.postHttpContent("https://api.mch.weixin.qq.com/pay/unifiedorder", formatMapToXML(map));
            result.setResponsetext(responseText);

            Map<String, String> resultmap = formatXMLToMap(responseText);
            if (!"SUCCESS".equals(resultmap.get("return_code"))) return result.retcode(RETPAY_PAY_ERROR);
            if (!checkSign(element, resultmap)) return result.retcode(RETPAY_FALSIFY_ERROR);
            /**
             * "appId" : "wx2421b1c4370ec43b", //公众号名称，由商户传入 "timeStamp":" 1395712654", //时间戳，自1970年以来的秒数 "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 "package" :
             * "prepay_id=u802345jgfjsdfgsdg888", "signType" : "MD5", //微信签名方式: "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名
             */
            final Map<String, String> rmap = new TreeMap<>();
            result.setResult(rmap);
            rmap.put("appId", element.appid);
            rmap.put("timeStamp", Long.toString(System.currentTimeMillis() / 1000));
            rmap.put("nonceStr", Long.toHexString(System.currentTimeMillis()) + Long.toHexString(System.nanoTime()));
            rmap.put("package", "prepay_id=" + resultmap.get("prepay_id"));
            rmap.put("signType", "MD5");
            rmap.put("paySign", createSign(element, rmap));
        } catch (Exception e) {
            result.setRetcode(RETPAY_PAY_ERROR);
            logger.log(Level.WARNING, "create_pay_error req=" + request + ", resp=" + result.responsetext, e);
        }
        return result;
    }
236287
public Nfs3WriteResponse sendWrite(NfsWriteRequest request) throws IOException {
        Nfs3WriteResponse response = new Nfs3WriteResponse();
        _rpcWrapper.callRpcNaked(request, response);
        return response;
    }
38684
public Nfs3MknodRequest makeMknodRequest(byte[] parentDirectoryFileHandle, String name, NfsType type,
            NfsSetAttributes attributes, long[] rdev) throws FileNotFoundException {
        return new Nfs3MknodRequest(parentDirectoryFileHandle, name, type, attributes, rdev, _credential);
    }
305929
public Nfs3RmdirResponse wrapped_sendRmdir(NfsRmdirRequest request) throws IOException {
        RpcResponseHandler<Nfs3RmdirResponse> responseHandler = new NfsResponseHandler<Nfs3RmdirResponse>() {

            /* (non-Javadoc)
             * @see com.emc.ecs.nfsclient.rpc.RpcResponseHandler#makeNewResponse()
             */
            protected Nfs3RmdirResponse makeNewResponse() {
                return new Nfs3RmdirResponse();
            }

        };
        _rpcWrapper.callRpcWrapped(request, responseHandler);
        return responseHandler.getResponse();
    }
551348
@Override
    public void sign ( byte[] data, int offset, int length, CommonServerMessageBlock request, CommonServerMessageBlock response ) {
        if ( log.isTraceEnabled() ) {
            log.trace("Signing with seq " + this.signSequence);
        }

        ( (ServerMessageBlock) request ).setSignSeq(this.signSequence);
        if ( response != null ) {
            ( (ServerMessageBlock) response ).setSignSeq(this.signSequence + 1);
        }

        try {
            update(this.macSigningKey, 0, this.macSigningKey.length);
            int index = offset + SmbConstants.SIGNATURE_OFFSET;
            for ( int i = 0; i < 8; i++ )
                data[ index + i ] = 0;
            SMBUtil.writeInt4(this.signSequence, data, index);
            update(data, offset, length);
            System.arraycopy(digest(), 0, data, index, 8);
            if ( this.bypass ) {
                this.bypass = false;
                System.arraycopy("BSRSPYL ".getBytes(), 0, data, index, 8);
            }
        }
        catch ( Exception ex ) {
            log.error("Signature failed", ex);
        }
        finally {
            if ( request instanceof SmbComNtCancel ) {
                this.signSequence++;
            }
            else {
                this.signSequence += 2;
            }
        }
    }
324112
public NfsCommitResponse commit(long offsetToCommit, int dataSizeToCommit) throws IOException {
        return getNfs().wrapped_sendCommit(makeCommitRequest(offsetToCommit, dataSizeToCommit));
    }
634761
static void rcvCreateUCTransaction(CommsByteBuffer request, Conversation conversation,
                                      int requestNumber, boolean allocatedFromBufferPool,
                                      boolean partOfExchange)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "rcvCreateUCTransaction",
                                           new Object[]
                                           {
                                              request,
                                              conversation,
                                              ""+requestNumber,
                                              ""+allocatedFromBufferPool
                                            });

      ConversationState convState = (ConversationState) conversation.getAttachment();

      short connectionObjectId = request.getShort();  // BIT16 ConnectionObjectId
      int clientTransactionId = request.getInt();     // BIT32 Client transaction Id

      // By default subordinates are allowed - however, a FAP version 5 client may specifically
      // request that a local transaction does not support them.
      // see the ConnectionProxy.createUncoordinateTransaction(boolean) method javadoc comment
      // for more details.
      boolean allowSubordinates = true;
      if (conversation.getHandshakeProperties().getFapLevel() >= JFapChannelConstants.FAP_VERSION_5)
      {
         allowSubordinates = (request.get() & 0x01) == 0x01;
      }

      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
      {
         SibTr.debug(tc, "SICoreConnection Id:", connectionObjectId);
         SibTr.debug(tc, "Client transaction Id:", clientTransactionId);
      }

      CATConnection catConn = (CATConnection) convState.getObject(connectionObjectId);
      SICoreConnection connection = catConn.getSICoreConnection();

      ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment();
      SIUncoordinatedTransaction ucTran = null;
      try
      {
         ucTran = connection.createUncoordinatedTransaction(allowSubordinates);

      }
      // Don't bother with all the different types seeing as we don't throw them back
      catch (SIException e)
      {
         //No FFDC code needed
         //Only FFDC if we haven't received a meTerminated event.
         if(!convState.hasMETerminated())
         {
            FFDCFilter.processException(e,
                                        CLASS_NAME + ".rcvCreateUCTransaction",
                                        CommsConstants.STATICCATTRANSACTION_CREATE_01);
         }

         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Failed to create the transaction", e);

         // We have to mark this transaction as error now - so as to indicate to everyone that
         // it should not be used
         linkState.getTransactionTable().addLocalTran(clientTransactionId, conversation.getId(), IdToTransactionTable.INVALID_TRANSACTION);
         linkState.getTransactionTable().markAsRollbackOnly(clientTransactionId, e);
      }

      // If transaction creation succeeded then add it to the link level state table of
      // transactions.
      if (ucTran != null)
      {
         linkState.getTransactionTable().addLocalTran(clientTransactionId,
                                                      conversation.getId(),
                                                      ucTran);
      }

      request.release(allocatedFromBufferPool);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "rcvCreateUCTransaction");
   }
459037
public Nfs3WriteResponse wrapped_sendWrite(NfsWriteRequest request, final Long verifier) throws IOException {
        // for async write, all the writes and commit should be sent to
        // the same NFS server
        String ip = request.isSync() ? _rpcWrapper.chooseIP(request.getIpKey()) : _server;
        NfsResponseHandler<Nfs3WriteResponse> responseHandler = new NfsResponseHandler<Nfs3WriteResponse>() {

            protected Nfs3WriteResponse makeNewResponse() {
                return new Nfs3WriteResponse();
            }

            /* (non-Javadoc)
             * @see com.emc.ecs.nfsclient.nfs.NfsResponseHandler#checkResponse(com.emc.ecs.nfsclient.rpc.RpcRequest)
             */
            public void checkResponse(RpcRequest request) throws IOException {
                super.checkResponse(request);
                if (!((NfsWriteRequest)request).isSync() && verifier != null && getResponse().getVerf() != verifier) {
                    throw new NfsException(NfsStatus.NFS3ERR_SERVERFAULT, "server restart detected");
                }
            }

        };
        _rpcWrapper.callRpcWrapped(request, responseHandler, ip);
        return responseHandler.getResponse();
    }
797810
public String createFolder(CreateFolderRequest request) throws AbstractCosException {
		request.check_param();

		String url = buildUrl(request);
		long signExpired = System.currentTimeMillis() / 1000 + this.config.getSignExpired();
		String sign = Sign.getPeriodEffectiveSign(request.getBucketName(), request.getCosPath(), this.cred, signExpired);

		HttpRequest httpRequest = new HttpRequest();
		httpRequest.setUrl(url);
		httpRequest.addHeader(RequestHeaderKey.Authorization, sign);
		httpRequest.addHeader(RequestHeaderKey.Content_TYPE, RequestHeaderValue.ContentType.JSON);
		httpRequest.addHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent());
		httpRequest.addParam(RequestBodyKey.OP, RequestBodyValue.OP.CREATE);
		httpRequest.addParam(RequestBodyKey.BIZ_ATTR, request.getBizAttr());

		httpRequest.setMethod(HttpMethod.POST);
		httpRequest.setContentType(HttpContentType.APPLICATION_JSON);
		return httpClient.sendHttpRequest(httpRequest);
    }
617159
public CreateTransactionResult createTransaction(
            final long connectionId,
            final long txnId,
            final long uniqueId,
            final StoredProcedureInvocation invocation,
            final boolean isReadOnly,
            final boolean isSinglePartition,
            final boolean isEveryPartition,
            final int[] partitions,
            final int messageSize,
            long nowNanos,
            final boolean isForReplay)
    {
        assert(!isSinglePartition || (partitions.length == 1));
        final ClientInterfaceHandleManager cihm = m_cihm.get(connectionId);
        if (cihm == null) {
            hostLog.rateLimitedLog(60, Level.WARN, null,
                    "InvocationDispatcher.createTransaction request rejected. "
                    + "This is likely due to VoltDB ceasing client communication as it "
                    + "shuts down.");
            return CreateTransactionResult.NO_CLIENT_HANDLER;
        }

        Long initiatorHSId = null;
        boolean isShortCircuitRead = false;
        /*
         * Send the read to the partition leader only
         * @MigratePartitionLeader always goes to partition leader
         */
        if (isSinglePartition && !isEveryPartition) {
            initiatorHSId = m_cartographer.getHSIdForSinglePartitionMaster(partitions[0]);
        } else {
            // Multi-part transactions go to the multi-part coordinator
            initiatorHSId = m_cartographer.getHSIdForMultiPartitionInitiator();

            // Treat all MP reads as short-circuit since they can run out-of-order
            // from their arrival order due to the MP Read-only execution pool
            if (isReadOnly) {
                isShortCircuitRead = true;
            }
        }

        if (initiatorHSId == null) {
            hostLog.rateLimitedLog(60, Level.INFO, null,
                    "InvocationDispatcher.createTransaction request rejected. "
                    + "This is likely due to parition leader being removed during elastic shrink.");
            return CreateTransactionResult.PARTITION_REMOVED;
        }

        long handle = cihm.getHandle(isSinglePartition, isSinglePartition ? partitions[0] : -1, invocation.getClientHandle(),
                messageSize, nowNanos, invocation.getProcName(), initiatorHSId, isShortCircuitRead);

        Iv2InitiateTaskMessage workRequest =
            new Iv2InitiateTaskMessage(m_siteId,
                    initiatorHSId,
                    Iv2InitiateTaskMessage.UNUSED_TRUNC_HANDLE,
                    txnId,
                    uniqueId,
                    isReadOnly,
                    isSinglePartition,
                    (partitions == null) || (partitions.length < 2) ? null : partitions,
                    invocation,
                    handle,
                    connectionId,
                    isForReplay);

        Long finalInitiatorHSId = initiatorHSId;
        final VoltTrace.TraceEventBatch traceLog = VoltTrace.log(VoltTrace.Category.CI);
        if (traceLog != null) {
            traceLog.add(() -> VoltTrace.instantAsync("inittxn",
                                                      invocation.getClientHandle(),
                                                      "clientHandle", Long.toString(invocation.getClientHandle()),
                                                      "ciHandle", Long.toString(handle),
                                                      "partitions", partitions.toString(),
                                                      "dest", CoreUtils.hsIdToString(finalInitiatorHSId)));
        }

        Iv2Trace.logCreateTransaction(workRequest);
        m_mailbox.send(initiatorHSId, workRequest);
        return CreateTransactionResult.SUCCESS;
    }
1216084
public Nfs3CreateRequest makeCreateRequest(NfsCreateMode createMode, byte[] parentDirectoryFileHandle, String name,
            NfsSetAttributes attributes, byte[] verifier) throws FileNotFoundException {
        return new Nfs3CreateRequest(createMode, parentDirectoryFileHandle, name, attributes, verifier, _credential);
    }
503144
public NfsReaddirplusRequest makeReaddirplusRequest(byte[] directoryFileHandle, long cookie, long cookieverf,
            int dircount, int maxcount) throws FileNotFoundException {
        return new Nfs3ReaddirplusRequest(directoryFileHandle, cookie, cookieverf, dircount, maxcount, _credential);
    }