Writes response body into the stream.

@param nsContext name space context
@param input request body
@param depth lock depth
@param lockToken lock token key
@param lockOwner loco owner
@param timeout lock timeout
@return response body
326879
private StreamingOutput body(WebDavNamespaceContext nsContext, LockRequestEntity input, Depth depth,
      String lockToken, String lockOwner, String timeout)
   {
      return new LockResultResponseEntity(nsContext, lockToken, lockOwner, timeout);
   }
164353
@Override
    public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException {
        context.startSubsystemElement(JGroupsSchema.CURRENT.getNamespaceUri(), false);
        ModelNode model = context.getModelNode();

        if (model.isDefined()) {
            if (model.hasDefined(ChannelResourceDefinition.WILDCARD_PATH.getKey())) {
                writer.writeStartElement(Element.CHANNELS.getLocalName());
                JGroupsSubsystemResourceDefinition.DEFAULT_CHANNEL.marshallAsAttribute(model, writer);
                for (Property property: model.get(ChannelResourceDefinition.WILDCARD_PATH.getKey()).asPropertyList()) {
                    writer.writeStartElement(Element.CHANNEL.getLocalName());
                    writer.writeAttribute(Attribute.NAME.getLocalName(), property.getName());
                    ModelNode channel = property.getValue();
                    writeAttribute(writer, channel, ChannelResourceDefinition.STACK);
                    writeAttribute(writer, channel, ChannelResourceDefinition.MODULE);

                    if (channel.hasDefined(ForkResourceDefinition.WILDCARD_PATH.getKey())) {
                        for (Property forkProperty: channel.get(ForkResourceDefinition.WILDCARD_PATH.getKey()).asPropertyList()) {
                            writer.writeStartElement(Element.FORK.getLocalName());
                            writer.writeAttribute(Attribute.NAME.getLocalName(), forkProperty.getName());
                            ModelNode fork = forkProperty.getValue();
                            if (fork.hasDefined(ProtocolResourceDefinition.WILDCARD_PATH.getKey())) {
                                for (Property protocol: fork.get(ProtocolResourceDefinition.WILDCARD_PATH.getKey()).asPropertyList()) {
                                    writeProtocol(writer, protocol);
                                }
                            }
                            writer.writeEndElement();
                        }
                    }
                    writer.writeEndElement();
                }
                writer.writeEndElement();
            }
            if (model.hasDefined(StackResourceDefinition.WILDCARD_PATH.getKey())) {
                writer.writeStartElement(Element.STACKS.getLocalName());
                writeAttribute(writer, model, JGroupsSubsystemResourceDefinition.DEFAULT_STACK);
                for (Property property: model.get(StackResourceDefinition.WILDCARD_PATH.getKey()).asPropertyList()) {
                    writer.writeStartElement(Element.STACK.getLocalName());
                    writer.writeAttribute(Attribute.NAME.getLocalName(), property.getName());
                    ModelNode stack = property.getValue();
                    if (stack.hasDefined(TransportResourceDefinition.WILDCARD_PATH.getKey())) {
                        writeTransport(writer, stack.get(TransportResourceDefinition.WILDCARD_PATH.getKey()).asProperty());
                    }
                    if (stack.hasDefined(ProtocolResourceDefinition.WILDCARD_PATH.getKey())) {
                        for (Property protocol: stack.get(ProtocolResourceDefinition.WILDCARD_PATH.getKey()).asPropertyList()) {
                            writeProtocol(writer, protocol);
                        }
                    }
                    if (stack.get(RelayResourceDefinition.PATH.getKeyValuePair()).isDefined()) {
                        writeRelay(writer, stack.get(RelayResourceDefinition.PATH.getKeyValuePair()));
                    }
                    if (stack.get(SaslResourceDefinition.PATH.getKeyValuePair()).isDefined()) {
                        writeSasl(writer, stack.get(SaslResourceDefinition.PATH.getKeyValuePair()));
                    }
                    writer.writeEndElement();
                }
                writer.writeEndElement();
            }
        }
        writer.writeEndElement();
    }
735722
private <R> R doWithWriteLock(Action<K, V, R> action) {
        writeLock.lock();
        try {
            return action.doWith(commonCache);
        } finally {
            writeLock.unlock();
        }
    }
135648
private RawGcsCreationToken put(final GcsRestCreationToken token, ByteBuffer chunk,
      final boolean isFinalChunk, long timeoutMillis) throws IOException {
    final int length = chunk.remaining();
    HTTPRequest req = createPutRequest(token, chunk, isFinalChunk, timeoutMillis, length);
    HTTPRequestInfo info = new HTTPRequestInfo(req);
    HTTPResponse response;
    try {
      response = urlfetch.fetch(req);
    } catch (IOException e) {
      throw createIOException(info, e);
    }
    return handlePutResponse(token, isFinalChunk, length, info, response);
  }
385122
public static base_responses flush(nitro_service client, nssimpleacl6 resources[]) throws Exception {
		base_responses result = null;
		if (resources != null && resources.length > 0) {
			nssimpleacl6 flushresources[] = new nssimpleacl6[resources.length];
			for (int i=0;i<resources.length;i++){
				flushresources[i] = new nssimpleacl6();
				flushresources[i].estsessions = resources[i].estsessions;
			}
			result = perform_operation_bulk_request(client, flushresources,"flush");
		}
		return result;
	}
942842
private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        boolean fair = transferer instanceof TransferQueue;
        if (fair) {
            qlock = new ReentrantLock(true);
            waitingProducers = new FifoWaitQueue();
            waitingConsumers = new FifoWaitQueue();
        }
        else {
            qlock = new ReentrantLock();
            waitingProducers = new LifoWaitQueue();
            waitingConsumers = new LifoWaitQueue();
        }
        s.defaultWriteObject();
    }
423982
private void writeObject(ObjectOutputStream out) throws IOException {

        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "writeObject: " + this);

        // Use v1 unless features are present that require v2.
        int version = Constants.TIMER_TASK_V1;
        if (parsedSchedule != null) {
            version = Constants.TIMER_TASK_V2;
        }

        out.defaultWriteObject();

        // Write out header information first.
        out.write(EYECATCHER);
        out.writeShort(PLATFORM);
        out.writeShort(version);

        // Write out the instance data.
        out.writeObject(j2eeName.getBytes());
        out.writeObject(userInfoBytes);

        switch (version) {

            case Constants.TIMER_TASK_V1:
                out.writeLong(expiration);
                out.writeLong(interval);
                break;

            case Constants.TIMER_TASK_V2:
                out.writeObject(parsedSchedule);
                out.writeInt(methodId);
                out.writeObject(automaticMethodName);
                out.writeObject(automaticClassName);
                break;

            default:
                // cannot occur since initialize above
                break;
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "writeObject");
    }
683354
private ByteBuf writeRequest(ByteBuf buffer, Object request, ThreadContext context) {
    context.serializer().writeObject(request, OUTPUT.get().setByteBuf(buffer));
    if (request instanceof ReferenceCounted) {
      ((ReferenceCounted) request).release();
    }
    return buffer;
  }
610780
@SuppressWarnings("unchecked")
    protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String path = getRelativePath(req);

        // Check if webdav is set to read only
        if (m_readOnly) {

            resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0));
            }

            return;
        }

        // Check if resource is locked
        if (isLocked(req)) {

            resp.setStatus(CmsWebdavStatus.SC_LOCKED);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path));
            }

            return;
        }

        CmsRepositoryLockInfo lock = new CmsRepositoryLockInfo();

        // Parsing depth header
        String depthStr = req.getHeader(HEADER_DEPTH);
        if (depthStr == null) {
            lock.setDepth(CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE);
        } else {
            if (depthStr.equals("0")) {
                lock.setDepth(0);
            } else {
                lock.setDepth(CmsRepositoryLockInfo.DEPTH_INFINITY_VALUE);
            }
        }

        // Parsing timeout header
        int lockDuration = CmsRepositoryLockInfo.TIMEOUT_INFINITE_VALUE;
        lock.setExpiresAt(System.currentTimeMillis() + (lockDuration * 1000));

        int lockRequestType = LOCK_CREATION;

        Element lockInfoNode = null;

        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new InputSource(req.getInputStream()));

            // Get the root element of the document
            Element rootElement = document.getRootElement();
            lockInfoNode = rootElement;
        } catch (Exception e) {
            lockRequestType = LOCK_REFRESH;
        }

        if (lockInfoNode != null) {

            // Reading lock information
            Iterator<Element> iter = lockInfoNode.elementIterator();

            Element lockScopeNode = null;
            Element lockTypeNode = null;
            Element lockOwnerNode = null;

            while (iter.hasNext()) {
                Element currentElem = iter.next();
                switch (currentElem.getNodeType()) {
                    case Node.TEXT_NODE:
                        break;
                    case Node.ELEMENT_NODE:
                        String nodeName = currentElem.getName();
                        if (nodeName.endsWith(TAG_LOCKSCOPE)) {
                            lockScopeNode = currentElem;
                        }
                        if (nodeName.endsWith(TAG_LOCKTYPE)) {
                            lockTypeNode = currentElem;
                        }
                        if (nodeName.endsWith(TAG_OWNER)) {
                            lockOwnerNode = currentElem;
                        }
                        break;
                    default:
                        break;
                }
            }

            if (lockScopeNode != null) {

                iter = lockScopeNode.elementIterator();
                while (iter.hasNext()) {
                    Element currentElem = iter.next();
                    switch (currentElem.getNodeType()) {
                        case Node.TEXT_NODE:
                            break;
                        case Node.ELEMENT_NODE:
                            String tempScope = currentElem.getName();
                            if (tempScope.indexOf(':') != -1) {
                                lock.setScope(tempScope.substring(tempScope.indexOf(':') + 1));
                            } else {
                                lock.setScope(tempScope);
                            }
                            break;
                        default:
                            break;
                    }
                }

                if (lock.getScope() == null) {

                    // Bad request
                    resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
                }

            } else {

                // Bad request
                resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
            }

            if (lockTypeNode != null) {

                iter = lockTypeNode.elementIterator();
                while (iter.hasNext()) {
                    Element currentElem = iter.next();
                    switch (currentElem.getNodeType()) {
                        case Node.TEXT_NODE:
                            break;
                        case Node.ELEMENT_NODE:
                            String tempType = currentElem.getName();
                            if (tempType.indexOf(':') != -1) {
                                lock.setType(tempType.substring(tempType.indexOf(':') + 1));
                            } else {
                                lock.setType(tempType);
                            }
                            break;
                        default:
                            break;
                    }
                }

                if (lock.getType() == null) {

                    // Bad request
                    resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
                }

            } else {

                // Bad request
                resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
            }

            if (lockOwnerNode != null) {

                iter = lockOwnerNode.elementIterator();
                while (iter.hasNext()) {
                    Element currentElem = iter.next();
                    switch (currentElem.getNodeType()) {
                        case Node.TEXT_NODE:
                            lock.setOwner(lock.getOwner() + currentElem.getStringValue());
                            break;
                        case Node.ELEMENT_NODE:
                            lock.setOwner(lock.getOwner() + currentElem.getStringValue());
                            break;
                        default:
                            break;
                    }
                }

                if (lock.getOwner() == null) {

                    // Bad request
                    resp.setStatus(CmsWebdavStatus.SC_BAD_REQUEST);
                }

            } else {
                lock.setOwner("");
            }

        }

        lock.setPath(path);
        lock.setUsername(m_username);

        if (lockRequestType == LOCK_REFRESH) {

            CmsRepositoryLockInfo currentLock = m_session.getLock(path);
            if (currentLock == null) {
                lockRequestType = LOCK_CREATION;
            }
        }

        if (lockRequestType == LOCK_CREATION) {

            try {

                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOCK_ITEM_1, lock.getOwner()));
                }

                boolean result = m_session.lock(path, lock);
                if (result) {

                    // Add the Lock-Token header as by RFC 2518 8.10.1
                    // - only do this for newly created locks
                    resp.addHeader(HEADER_LOCKTOKEN, "<opaquelocktoken:" + generateLockToken(req, lock) + ">");

                    if (LOG.isDebugEnabled()) {
                        LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOCK_ITEM_FAILED_0));
                    }

                } else {

                    resp.setStatus(CmsWebdavStatus.SC_LOCKED);

                    if (LOG.isDebugEnabled()) {
                        LOG.debug(Messages.get().getBundle().key(Messages.LOG_LOCK_ITEM_SUCCESS_0));
                    }

                    return;
                }
            } catch (CmsVfsResourceNotFoundException rnfex) {
                resp.setStatus(CmsWebdavStatus.SC_NOT_FOUND);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_NOT_FOUND_1, path));
                }

                return;
            } catch (CmsSecurityException sex) {
                resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_NO_PERMISSION_0));
                }

                return;
            } catch (CmsException ex) {
                resp.setStatus(CmsWebdavStatus.SC_INTERNAL_SERVER_ERROR);

                if (LOG.isErrorEnabled()) {
                    LOG.error(Messages.get().getBundle().key(Messages.LOG_REPOSITORY_ERROR_2, "LOCK", path), ex);
                }

                return;
            }
        }

        // Set the status, then generate the XML response containing
        // the lock information
        Document doc = DocumentHelper.createDocument();
        Element propElem = doc.addElement(new QName(TAG_PROP, Namespace.get(DEFAULT_NAMESPACE)));

        Element lockElem = addElement(propElem, TAG_LOCKDISCOVERY);
        addLockElement(lock, lockElem, generateLockToken(req, lock));

        resp.setStatus(CmsWebdavStatus.SC_OK);
        resp.setContentType("text/xml; charset=UTF-8");

        Writer writer = resp.getWriter();
        doc.write(writer);
        writer.close();
    }
354128
public IEntityLock newReadLock(Class entityType, String entityKey, String owner)
            throws LockingException {
        return lockService.newLock(entityType, entityKey, IEntityLockService.READ_LOCK, owner);
    }
506741
GcsRestCreationToken handlePutResponse(final GcsRestCreationToken token,
      final boolean isFinalChunk,
      final int length,
      final HTTPRequestInfo reqInfo,
      HTTPResponse resp) throws Error, IOException {
    switch (resp.getResponseCode()) {
      case 200:
        if (!isFinalChunk) {
          throw new RuntimeException("Unexpected response code 200 on non-final chunk. Request: \n"
              + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
        } else {
          return null;
        }
      case 308:
        if (isFinalChunk) {
          throw new RuntimeException("Unexpected response code 308 on final chunk: "
              + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
        } else {
          return new GcsRestCreationToken(token.filename, token.uploadId, token.offset + length);
        }
      default:
        throw HttpErrorHandler.error(resp.getResponseCode(),
            URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
    }
  }
848164
static void sendResponse(final ManagementRequestContext<ExecuteRequestContext> context, final byte responseType, final ModelNode response) throws IOException {

        // WFLY-3090 Protect the communication channel from getting closed due to administrative
        // cancellation of the management op by using a separate thread to send
        final CountDownLatch latch = new CountDownLatch(1);
        final IOExceptionHolder exceptionHolder = new IOExceptionHolder();
        boolean accepted = context.executeAsync(new AsyncTask<TransactionalProtocolOperationHandler.ExecuteRequestContext>() {

            @Override
            public void execute(final ManagementRequestContext<ExecuteRequestContext> context) throws Exception {
                FlushableDataOutput output = null;
                try {
                    MGMT_OP_LOGGER.tracef("Transmitting response for %d", context.getOperationId());
                    final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());
                    output = context.writeMessage(header);
                    // response type
                    output.writeByte(responseType);
                    // operation result
                    response.writeExternal(output);
                    // response end
                    output.writeByte(ManagementProtocol.RESPONSE_END);
                    output.close();
                } catch (IOException toCache) {
                    exceptionHolder.exception = toCache;
                } finally {
                    StreamUtils.safeClose(output);
                    latch.countDown();
                }
            }
        }, false);
        if (accepted) {
            try {
                latch.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            if (exceptionHolder.exception != null) {
                throw exceptionHolder.exception;
            }
        }
    }
761171
def _open_response(self, objects, namespace, pull_type, **params):
        
        max_obj_cnt = params['MaxObjectCount']
        if max_obj_cnt is None:
            max_obj_cnt = _DEFAULT_MAX_OBJECT_COUNT

        default_server_timeout = 40
        timeout = default_server_timeout if params['OperationTimeout'] is None \
            else params['OperationTimeout']

        if len(objects) <= max_obj_cnt:
            eos = u'TRUE'
            context_id = ""
            rtn_inst_names = objects
        else:
            eos = u'FALSE'
            context_id = self._create_contextid()
            # TODO:ks Future. Use the timeout along with response delay. Then
            # user could timeout pulls. This means adding timer test to
            # pulls and close. Timer should be used to close old contexts
            # also.
            self.enumeration_contexts[context_id] = {'pull_type': pull_type,
                                                     'data': objects,
                                                     'namespace': namespace,
                                                     'time': time.clock(),
                                                     'interoptimeout': timeout}
            rtn_inst_names = objects[0:max_obj_cnt]
            del objects[0: max_obj_cnt]

        return self._make_pull_imethod_resp(rtn_inst_names, eos, context_id)
176922
private synchronized void writeObject(java.io.ObjectOutputStream stream)
			throws java.io.IOException
	{
		ThreadState tmp = this.threadState;
		this.threadStateSerilizationHashedId = serilizationCache.store(this.threadState);
		this.threadState = null;
		stream.defaultWriteObject();
		this.threadState = tmp;
	}
1214839
protected void storeTimeout(Timeout t, XMLStreamWriter writer) throws Exception
   {
      writer.writeStartElement(XML.ELEMENT_TIMEOUT);

      if (t.getBlockingTimeoutMillis() != null)
      {
         writer.writeStartElement(XML.ELEMENT_BLOCKING_TIMEOUT_MILLIS);
         writer.writeCharacters(t.getValue(XML.ELEMENT_BLOCKING_TIMEOUT_MILLIS,
                                           t.getBlockingTimeoutMillis().toString()));
         writer.writeEndElement();
      }

      if (t.getIdleTimeoutMinutes() != null)
      {
         writer.writeStartElement(XML.ELEMENT_IDLE_TIMEOUT_MINUTES);
         writer.writeCharacters(t.getValue(XML.ELEMENT_IDLE_TIMEOUT_MINUTES, t.getIdleTimeoutMinutes().toString()));
         writer.writeEndElement();
      }

      if (t.isSetTxQueryTimeout() != null && Boolean.TRUE.equals(t.isSetTxQueryTimeout()))
      {
         writer.writeEmptyElement(XML.ELEMENT_SET_TX_QUERY_TIMEOUT);
      }

      if (t.getQueryTimeout() != null)
      {
         writer.writeStartElement(XML.ELEMENT_QUERY_TIMEOUT);
         writer.writeCharacters(t.getValue(XML.ELEMENT_QUERY_TIMEOUT, t.getQueryTimeout().toString()));
         writer.writeEndElement();
      }

      if (t.getUseTryLock() != null)
      {
         writer.writeStartElement(XML.ELEMENT_USE_TRY_LOCK);
         writer.writeCharacters(t.getValue(XML.ELEMENT_USE_TRY_LOCK, t.getUseTryLock().toString()));
         writer.writeEndElement();
      }

      if (t.getAllocationRetry() != null)
      {
         writer.writeStartElement(XML.ELEMENT_ALLOCATION_RETRY);
         writer.writeCharacters(t.getValue(XML.ELEMENT_ALLOCATION_RETRY, t.getAllocationRetry().toString()));
         writer.writeEndElement();
      }

      if (t.getAllocationRetryWaitMillis() != null)
      {
         writer.writeStartElement(XML.ELEMENT_ALLOCATION_RETRY_WAIT_MILLIS);
         writer.writeCharacters(t.getValue(XML.ELEMENT_ALLOCATION_RETRY_WAIT_MILLIS,
                                           t.getAllocationRetryWaitMillis().toString()));
         writer.writeEndElement();
      }

      if (t.getXaResourceTimeout() != null)
      {
         writer.writeStartElement(XML.ELEMENT_XA_RESOURCE_TIMEOUT);
         writer.writeCharacters(t.getValue(XML.ELEMENT_XA_RESOURCE_TIMEOUT, t.getXaResourceTimeout().toString()));
         writer.writeEndElement();
      }

      writer.writeEndElement();
   }
517815
void lockBucketsWrite(long i1, long i2) {
		int bucket1LockIdx = getBucketLock(i1);
		int bucket2LockIdx = getBucketLock(i2);
		// always lock segments in same order to avoid deadlocks
		if (bucket1LockIdx < bucket2LockIdx) {
			lockAry[bucket1LockIdx].writeLock();
			lockAry[bucket2LockIdx].writeLock();
		} else if (bucket1LockIdx > bucket2LockIdx) {
			lockAry[bucket2LockIdx].writeLock();
			lockAry[bucket1LockIdx].writeLock();
		}
		// if we get here both indexes are on same segment so only lock once!!!
		else {
			lockAry[bucket1LockIdx].writeLock();
		}
	}
548805
public static int lock(String name, long timeoutInMilli) {
        if (name.contains("/")) {
            throw new IllegalArgumentException("锁的名称不允许包含'/'，yourLockName= " + name);
        }
        LOG.debug("由于zk单个znode下如果存在过多children会出现zk客户端无法ls列表，和无法rmr的问题，因此加入日期子路径");
        //todo 缺点1、一天的锁数量日后太大时也会有children过多问题
        //todo 缺点2、跨天锁失效
        //todo 以上解决方案：使用一致性哈希将锁分配到固定子路径内去
        //todo 优点、临时解决了我们维护zk困难的问题
        InterProcessMutex lock = new InterProcessMutex(ZkConnection.client, LOCK_ROOT + "/" + DateUtil.getDateStr() + "/" + name);
        int innerId = innerIdGenerator.getAndIncrement();
        try {
            if (!lock.acquire(timeoutInMilli, TimeUnit.MILLISECONDS)) {
                LOG.info(String.format("获取锁%s超时,超时时间%sms", name, timeoutInMilli));
                return TIME_OUT_INNER_ID;
            } else {
                map.put(innerId, lock);
                return innerId;
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }