jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    public void onTaskSelectionEvent(@Observes TaskSelectionEvent event){
        selectedTaskId = event.getTaskId();
        selectedTaskName = event.getTaskName();
        
        view.getTaskIdAndName().setText(String.valueOf(selectedTaskId) + " - "+selectedTaskName);
        
        view.getContent().clear();
        
        String placeToGo;
        if(event.getPlace() != null && !event.getPlace().equals("")){
            placeToGo = event.getPlace();
        }else{
            placeToGo = "Task Details";
        }
        
        

        DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo);
        //Set Parameters here: 
        defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId));
        defaultPlaceRequest.addParameter("taskName", selectedTaskName);

        Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest);
        AbstractWorkbenchScreenActivity activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next());
        
        activitiesMap.put(placeToGo, activity);
        
        IsWidget widget = activity.getWidget();
        activity.launch(place, null);
        activity.onStartup(defaultPlaceRequest);
        view.getContent().add(widget);
        activity.onOpen();
    }
//  [java]
    public BourneShell( boolean isLoginShell )
    {
        setUnconditionalQuoting( true );
        setShellCommand( "/bin/sh" );
        setArgumentQuoteDelimiter( '\'' );
        setExecutableQuoteDelimiter( '\'' );
        setSingleQuotedArgumentEscaped( true );
        setSingleQuotedExecutableEscaped( false );
        setQuotedExecutableEnabled( true );
        setArgumentEscapePattern("'\\%s'");

        if ( isLoginShell )
        {
            addShellArg( "-l" );
        }
    }
//  [java]
    public BourneShell( boolean isLoginShell )
    {
        setShellCommand( "/bin/sh" );
        setArgumentQuoteDelimiter( '\'' );
        setExecutableQuoteDelimiter( '\"' );
        setSingleQuotedArgumentEscaped( true );
        setSingleQuotedExecutableEscaped( false );
        setQuotedExecutableEnabled( true );
        setArgumentEscapePattern("'\\%s'");

        if ( isLoginShell )
        {
            addShellArg( "-l" );
        }
    }
//  [java]
    private static boolean appendOneByte(Bytes buf, int cp, boolean wasSlash, boolean isPath) {
        if (cp == 0x7F) {
            // Reject the control character: 0x7F
            return false;
        }

        if (cp >>> 5 == 0) {
            // Reject the control characters: 0x00..0x1F
            if (isPath) {
                return false;
            } else if (cp != 0x0A && cp != 0x0D && cp != 0x09) {
                // .. except 0x0A (LF), 0x0D (CR) and 0x09 (TAB) because they are used in a form.
                return false;
            }
        }

        if (cp == '/' && isPath) {
            if (!wasSlash) {
                buf.ensure(1);
                buf.add((byte) '/');
            } else {
                // Remove the consecutive slashes: '/path//with///consecutive////slashes'.
            }
        } else {
            final BitSet allowedChars = isPath ? ALLOWED_PATH_CHARS : ALLOWED_QUERY_CHARS;
            buf.ensure(1);
            if (allowedChars.get(cp)) {
                buf.add((byte) cp);
            } else {
                buf.addEncoded((byte) cp);
            }
        }

        return true;
    }
//  [java]
    private static boolean appendOneByte(Bytes buf, int cp, boolean wasSlash, boolean isPath) {
        if (cp == 0x7F) {
            // Reject the control character: 0x7F
            return false;
        }

        if (cp >>> 5 == 0) {
            // Reject the control characters: 0x00..0x1F
            if (isPath) {
                return false;
            } else if (cp != 0x0A && cp != 0x0D && cp != 0x09) {
                // .. except 0x0A (LF), 0x0D (CR) and 0x09 (TAB) because they are used in a form.
                return false;
            }
        }

        if (cp == '/' && isPath) {
            if (!wasSlash) {
                buf.ensure(1);
                buf.add((byte) '/');
            } else {
                // Remove the consecutive slashes: '/path//with///consecutive////slashes'.
            }
        } else {
            buf.ensure(1);
            buf.add((byte) cp);
        }

        return true;
    }
//  [java]
    public String toString() {
        if (query == null) {
            return path;
        }
        return path + '?' + query;
    }
//  [java]
    public String toString() {
        if (query == null) {
            return path;
        }
        return path + "?" + query;
    }
//  [java]
        for (int i = 0; i < reservedChars.length(); i++) {
            RESERVED_CHARS.set(reservedChars.charAt(i));
        }
//  [java]
        for (final ReservedChar reservedChar : ReservedChar.values()) {
            RAW_CHAR_TO_MARKER[reservedChar.rawChar] = reservedChar.marker;
            MARKER_TO_PERCENT_ENCODED_CHAR[reservedChar.marker] = reservedChar.percentEncodedChar;
        }
//  [java]
error_t nicSendPacket(NetInterface *interface, const NetBuffer *buffer,
   size_t offset, NetTxAncillary *ancillary)
{
   error_t error;
   bool_t status;

#if (TRACE_LEVEL >= TRACE_LEVEL_DEBUG)
   //Retrieve the length of the packet
   size_t length = netBufferGetLength(buffer) - offset;

   //Debug message
   TRACE_DEBUG("Sending packet (%" PRIuSIZE " bytes)...\r\n", length);
   TRACE_DEBUG_NET_BUFFER("  ", buffer, offset, length);
#endif

   //Gather entropy
   netContext.entropy += netGetSystemTickCount();

   //Check whether the interface is enabled for operation
   if(interface->configured && interface->nicDriver != NULL)
   {
      //Loopback interface?
      if(interface->nicDriver->type == NIC_TYPE_LOOPBACK)
      {
         //The loopback interface is always available
         status = TRUE;
      }
      else
      {
         //Wait for the transmitter to be ready to send
         status = osWaitForEvent(&interface->nicTxEvent, NIC_MAX_BLOCKING_TIME);
      }

      //Check whether the specified event is in signaled state
      if(status)
      {
         //Disable interrupts
         interface->nicDriver->disableIrq(interface);

         //Send the packet
         error = interface->nicDriver->sendPacket(interface, buffer, offset,
            ancillary);

         //Re-enable interrupts if necessary
         if(interface->configured)
         {
            interface->nicDriver->enableIrq(interface);
         }
      }
      else
      {
         //If the transmitter is busy, then drop the packet
         error = NO_ERROR;
      }
   }
   else
   {
      //Report an error
      error = ERROR_INVALID_INTERFACE;
   }

   //Return status code
   return error;
}
//  [java]
error_t nicSendPacket(NetInterface *interface, const NetBuffer *buffer,
   size_t offset, NetTxAncillary *ancillary)
{
   error_t error;
   bool_t status;

   //Gather entropy
   netContext.entropy += netGetSystemTickCount();

#if (TRACE_LEVEL >= TRACE_LEVEL_DEBUG)
   //Retrieve the length of the packet
   size_t length = netBufferGetLength(buffer) - offset;

   //Debug message
   TRACE_DEBUG("Sending packet (%" PRIuSIZE " bytes)...\r\n", length);
   TRACE_DEBUG_NET_BUFFER("  ", buffer, offset, length);
#endif

   //Check whether the interface is enabled for operation
   if(interface->configured && interface->nicDriver != NULL)
   {
      //Loopback interface?
      if(interface->nicDriver->type == NIC_TYPE_LOOPBACK)
      {
         //The loopback interface is always available
         status = TRUE;
      }
      else
      {
         //Wait for the transmitter to be ready to send
         status = osWaitForEvent(&interface->nicTxEvent, NIC_MAX_BLOCKING_TIME);
      }

      //Check whether the specified event is in signaled state
      if(status)
      {
         //Disable interrupts
         interface->nicDriver->disableIrq(interface);

         //Send the packet
         error = interface->nicDriver->sendPacket(interface, buffer, offset,
            ancillary);

         //Re-enable interrupts if necessary
         if(interface->configured)
         {
            interface->nicDriver->enableIrq(interface);
         }
      }
      else
      {
         //If the transmitter is busy, then drop the packet
         error = NO_ERROR;
      }
   }
   else
   {
      //Report an error
      error = ERROR_INVALID_INTERFACE;
   }

   //Return status code
   return error;
}
//  [java]
    private static boolean pathContainsDoubleDots(Bytes path) {
        final int length = path.length;
        byte b0 = 0;
        byte b1 = 0;
        byte b2 = '/';
        for (int i = 1; i < length; i++) {
            final byte b3 = path.data[i];
            // Flag if the last four bytes are `/../`.
            if (b1 == '.' && b2 == '.' && isSlash(b0) && isSlash(b3)) {
                return true;
            }
            b0 = b1;
            b1 = b2;
            b2 = b3;
        }

        // Flag if the last three bytes are `/..`.
        return b1 == '.' && b2 == '.' && isSlash(b0);
    }
//  [java]
    private static boolean pathContainsDoubleDots(Bytes path) {
        final int length = path.length;
        byte b0 = 0;
        byte b1 = 0;
        byte b2 = '/';
        for (int i = 1; i < length; i++) {
            final byte b3 = path.data[i];
            if (b3 == '/' && b2 == '.' && b1 == '.' && b0 == '/') {
                return true;
            }
            b0 = b1;
            b1 = b2;
            b2 = b3;
        }

        return b0 == '/' && b1 == '.' && b2 == '.';
    }
//  [java]
    public void translate(GeyserSession session, ServerSetSubtitleTextPacket packet) {
        String text;
        if (packet.getText() == null) { //TODO 1.17 can this happen?
            text = " ";
        } else {
            text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
        }

        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.SUBTITLE);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }
//  [java]
    public void translate(ServerSetSubtitleTextPacket packet, GeyserSession session) {
        String text;
        if (packet.getText() == null) { //TODO 1.17 can this happen?
            text = " ";
        } else {
            text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
        }

        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.SUBTITLE);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }
//  [java]
    private static PathAndQuery splitPathAndQuery(@Nullable final String pathAndQuery) {
        final Bytes path;
        final Bytes query;

        if (pathAndQuery == null) {
            return ROOT_PATH_QUERY;
        }

        // Split by the first '?'.
        final int queryPos = pathAndQuery.indexOf('?');
        if (queryPos >= 0) {
            if ((path = decodePercentsAndEncodeToUtf8(
                    pathAndQuery, 0, queryPos, true)) == null) {
                return null;
            }
            if ((query = decodePercentsAndEncodeToUtf8(
                    pathAndQuery, queryPos + 1, pathAndQuery.length(), false)) == null) {
                return null;
            }
        } else {
            if ((path = decodePercentsAndEncodeToUtf8(
                    pathAndQuery, 0, pathAndQuery.length(), true)) == null) {
                return null;
            }
            query = null;
        }

        if (path.data[0] != '/' || path.isEncoded(0)) {
            // Do not accept a relative path.
            return null;
        }

        // Reject the prohibited patterns.
        if (pathContainsDoubleDots(path) || queryContainsDoubleDots(query)) {
            return null;
        }

        return new PathAndQuery(encodePathToPercents(path), encodeQueryToPercents(query));
    }
//  [java]
    private static PathAndQuery splitPathAndQuery(@Nullable final String pathAndQuery) {
        final Bytes path;
        final Bytes query;

        if (pathAndQuery == null) {
            return ROOT_PATH_QUERY;
        }

        // Split by the first '?'.
        final int queryPos = pathAndQuery.indexOf('?');
        if (queryPos >= 0) {
            if ((path = decodePercentsAndEncodeToUtf8(
                    pathAndQuery, 0, queryPos, true)) == null) {
                return null;
            }
            if ((query = decodePercentsAndEncodeToUtf8(
                    pathAndQuery, queryPos + 1, pathAndQuery.length(), false)) == null) {
                return null;
            }
        } else {
            if ((path = decodePercentsAndEncodeToUtf8(
                    pathAndQuery, 0, pathAndQuery.length(), true)) == null) {
                return null;
            }
            query = null;
        }

        if (path.data[0] != '/') {
            // Do not accept a relative path.
            return null;
        }

        // Reject the prohibited patterns.
        if (pathContainsDoubleDots(path)) {
            return null;
        }

        return new PathAndQuery(encodeToPercents(path, true),
                                query != null ? encodeToPercents(query, false) : null);
    }
//  [java]
    public void cleanup() {
    }
//  [java]
    public void translate(GeyserSession session, ServerRespawnPacket packet) {
        SessionPlayerEntity entity = session.getPlayerEntity();

        entity.setHealth(entity.getMaxHealth());
        entity.getAttributes().put(GeyserAttributeType.HEALTH, entity.createHealthAttribute());

        session.setInventoryTranslator(InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR);
        session.setOpenInventory(null);
        session.setClosingInventory(false);

        SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket();
        playerGameTypePacket.setGamemode(packet.getGamemode().ordinal());
        session.sendUpstreamPacket(playerGameTypePacket);
        session.setGameMode(packet.getGamemode());

        if (session.isRaining()) {
            LevelEventPacket stopRainPacket = new LevelEventPacket();
            stopRainPacket.setType(LevelEventType.STOP_RAINING);
            stopRainPacket.setData(0);
            stopRainPacket.setPosition(Vector3f.ZERO);
            session.sendUpstreamPacket(stopRainPacket);
            session.setRaining(false);
        }

        if (session.isThunder()) {
            LevelEventPacket stopThunderPacket = new LevelEventPacket();
            stopThunderPacket.setType(LevelEventType.STOP_THUNDERSTORM);
            stopThunderPacket.setData(0);
            stopThunderPacket.setPosition(Vector3f.ZERO);
            session.sendUpstreamPacket(stopThunderPacket);
            session.setThunder(false);
        }

        String newDimension = DimensionUtils.getNewDimension(packet.getDimension());
        if (!session.getDimension().equals(newDimension) || !packet.getWorldName().equals(session.getWorldName())) {
            // Switching to a new world (based off the world name change); send a fake dimension change
            if (!packet.getWorldName().equals(session.getWorldName()) && (session.getDimension().equals(newDimension)
                    // Ensure that the player never ever dimension switches to the same dimension - BAD
                    // Can likely be removed if the Above Bedrock Nether Building option can be removed
                    || DimensionUtils.javaToBedrock(session.getDimension()) == DimensionUtils.javaToBedrock(newDimension))) {
                String fakeDim = DimensionUtils.getTemporaryDimension(session.getDimension(), newDimension);
                DimensionUtils.switchDimension(session, fakeDim);
            }
            session.setWorldName(packet.getWorldName());
            DimensionUtils.switchDimension(session, newDimension);
        }

        ChunkUtils.applyDimensionHeight(session, packet.getDimension());
    }
//  [java]
    public void translate(ServerRespawnPacket packet, GeyserSession session) {
        SessionPlayerEntity entity = session.getPlayerEntity();

        entity.setHealth(entity.getMaxHealth());
        entity.getAttributes().put(GeyserAttributeType.HEALTH, entity.createHealthAttribute());

        session.setInventoryTranslator(InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR);
        session.setOpenInventory(null);
        session.setClosingInventory(false);

        SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket();
        playerGameTypePacket.setGamemode(packet.getGamemode().ordinal());
        session.sendUpstreamPacket(playerGameTypePacket);
        session.setGameMode(packet.getGamemode());

        if (session.isRaining()) {
            LevelEventPacket stopRainPacket = new LevelEventPacket();
            stopRainPacket.setType(LevelEventType.STOP_RAINING);
            stopRainPacket.setData(0);
            stopRainPacket.setPosition(Vector3f.ZERO);
            session.sendUpstreamPacket(stopRainPacket);
            session.setRaining(false);
        }

        if (session.isThunder()) {
            LevelEventPacket stopThunderPacket = new LevelEventPacket();
            stopThunderPacket.setType(LevelEventType.STOP_THUNDERSTORM);
            stopThunderPacket.setData(0);
            stopThunderPacket.setPosition(Vector3f.ZERO);
            session.sendUpstreamPacket(stopThunderPacket);
            session.setThunder(false);
        }

        String newDimension = DimensionUtils.getNewDimension(packet.getDimension());
        if (!session.getDimension().equals(newDimension) || !packet.getWorldName().equals(session.getWorldName())) {
            // Switching to a new world (based off the world name change); send a fake dimension change
            if (!packet.getWorldName().equals(session.getWorldName()) && (session.getDimension().equals(newDimension)
                    // Ensure that the player never ever dimension switches to the same dimension - BAD
                    // Can likely be removed if the Above Bedrock Nether Building option can be removed
                    || DimensionUtils.javaToBedrock(session.getDimension()) == DimensionUtils.javaToBedrock(newDimension))) {
                String fakeDim = DimensionUtils.getTemporaryDimension(session.getDimension(), newDimension);
                DimensionUtils.switchDimension(session, fakeDim);
            }
            session.setWorldName(packet.getWorldName());
            DimensionUtils.switchDimension(session, newDimension);
        }

        ChunkUtils.applyDimensionHeight(session, packet.getDimension());
    }
//  [java]
    public void requestDestroyed(HttpServletRequest request) {
        if (isRequestDestroyed(request)) {
            return;
        }
        if (nestedInvocationGuardEnabled) {
            Counter counter = nestedInvocationGuard.get();
            if (counter != null) {
                counter.value--;
                if (counter.value > 0) {
                    return; // this is a nested invocation, ignore it
                } else {
                    nestedInvocationGuard.remove(); // this is the outer invocation
                    request.removeAttribute(GUARD_PARAMETER_NAME);
                }
            } else {
                ServletLogger.LOG.guardNotSet();
                return;
            }
        }
        if (ignoreForwards && isForwardedRequest(request)) {
            return;
        }
        if (ignoreIncludes && isIncludedRequest(request)) {
            return;
        }
        if (!contextActivationFilter.accepts(request)) {
            return;
        }

        ServletLogger.LOG.requestDestroyed(request);

        try {
            conversationContextActivator.deactivateConversationContext(request);
            /*
             * if this request has been switched to async then do not invalidate the context now
             * as it will be invalidated at the end of the async operation.
             */
            if (!servletApi.isAsyncSupported() || !servletApi.isAsyncStarted(request)) {
                getRequestContext().invalidate();
            }

            safelyDeactivate(getRequestContext(),  request);
            // fire @Destroyed(RequestScoped.class)
            requestDestroyedEvent.fire(request);

            safelyDeactivate(getSessionContext(), request);
            // fire @Destroyed(SessionScoped.class)
            if (!getSessionContext().isValid()) {
                sessionDestroyedEvent.fire((HttpSession) request.getAttribute(HTTP_SESSION));
            }
        } finally {
            safelyDissociate(getRequestContext(), request);
            // WFLY-1533 Underlying HTTP session may be invalid
            safelyDissociate(getSessionContext(), request);

            // Catch block is inside the activator method so that we're able to log the context
            conversationContextActivator.disassociateConversationContext(request);

            SessionHolder.clear();
        }
    }
//  [java]
    public void requestDestroyed(HttpServletRequest request) {
        if (isRequestDestroyed(request)) {
            return;
        }
        if (nestedInvocationGuardEnabled) {
            Counter counter = nestedInvocationGuard.get();
            if (counter != null) {
                counter.value--;
                if (counter.value > 0) {
                    return; // this is a nested invocation, ignore it
                } else {
                    nestedInvocationGuard.remove(); // this is the outer invocation
                    request.removeAttribute(GUARD_PARAMETER_NAME);
                }
            } else {
                ServletLogger.LOG.guardNotSet();
                return;
            }
        }
        if (ignoreForwards && isForwardedRequest(request)) {
            return;
        }
        if (ignoreIncludes && isIncludedRequest(request)) {
            return;
        }
        if (!contextActivationFilter.accepts(request)) {
            return;
        }

        ServletLogger.LOG.requestDestroyed(request);

        try {
            conversationContextActivator.deactivateConversationContext(request);
            /*
             * if this request has been switched to async then do not invalidate the context now
             * as it will be invalidated at the end of the async operation.
             */
            if (!servletApi.isAsyncSupported() || !servletApi.isAsyncStarted(request)) {
                getRequestContext().invalidate();
            }
            getRequestContext().deactivate();
            // fire @Destroyed(RequestScoped.class)
            requestDestroyedEvent.fire(request);
            getSessionContext().deactivate();
            // fire @Destroyed(SessionScoped.class)
            if (!getSessionContext().isValid()) {
                sessionDestroyedEvent.fire((HttpSession) request.getAttribute(HTTP_SESSION));
            }
        } finally {
            getRequestContext().dissociate(request);

            // WFLY-1533 Underlying HTTP session may be invalid
            try {
                getSessionContext().dissociate(request);
            } catch (Exception e) {
                ServletLogger.LOG.unableToDissociateContext(getSessionContext(), request);
                ServletLogger.LOG.catchingDebug(e);
            }
            // Catch block is inside the activator method so that we're able to log the context
            conversationContextActivator.disassociateConversationContext(request);

            SessionHolder.clear();
        }
    }
//  [java]
	public Collection<StyleSignatureBasic> toSignatures() {
		List<StyleSignatureBasic> results = new ArrayList<>(Collections.singletonList(StyleSignatureBasic.empty()));
		boolean star = false;
		for (Iterator<String> it = data.iterator(); it.hasNext();) {
			String s = it.next();
			if (s.endsWith("*")) {
				star = true;
				s = s.substring(0, s.length() - 1);
			}
			final String[] names = s.split(",");
			final List<StyleSignatureBasic> tmp = new ArrayList<>();
			for (StyleSignatureBasic ss : results)
				for (String name : names)
					tmp.add(ss.add(name.trim()));
			results = tmp;
		}

		if (star)
			for (ListIterator<StyleSignatureBasic> it = results.listIterator(); it.hasNext();) {
				final StyleSignatureBasic tmp = it.next().addStar();
				it.set(tmp);
			}

		return Collections.unmodifiableCollection(results);
	}
//  [java]
	public Collection<StyleSignatureBasic> toSignatures() {
		List<StyleSignatureBasic> results = new ArrayList<>(Collections.singletonList(StyleSignatureBasic.empty()));
		boolean star = false;
		for (Iterator<String> it = data.iterator(); it.hasNext();) {
			String s = it.next();
			if (s.endsWith("*")) {
				star = true;
				s = s.substring(0, s.length() - 1);
			}
			final String[] names = s.split(",");
			final List<StyleSignatureBasic> tmp = new ArrayList<>();
			for (StyleSignatureBasic ss : results)
				for (String name : names)
					tmp.add(ss.add(name));
			results = tmp;
		}

		if (star)
			for (ListIterator<StyleSignatureBasic> it = results.listIterator(); it.hasNext();) {
				final StyleSignatureBasic tmp = it.next().addStar();
				it.set(tmp);
			}

		return Collections.unmodifiableCollection(results);
	}
//  [java]
    public void translate(GeyserSession session, ServerSetTitleTextPacket packet) {
        String text;
        if (packet.getText() == null) { //TODO 1.17 can this happen?
            text = " ";
        } else {
            text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
        }

        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.TITLE);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }
//  [java]
    public void translate(ServerSetTitleTextPacket packet, GeyserSession session) {
        String text;
        if (packet.getText() == null) { //TODO 1.17 can this happen?
            text = " ";
        } else {
            text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
        }

        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.TITLE);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }
//  [java]
    public void translate(GeyserSession session, ServerEntityAttachPacket packet) {

        Entity holderId;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            holderId = session.getPlayerEntity();
        } else {
            holderId = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
            if (holderId == null) {
                return;
            }
        }

        Entity attachedToId;
        if (packet.getAttachedToId() == session.getPlayerEntity().getEntityId()) {
            attachedToId = session.getPlayerEntity();
        } else {
            attachedToId = session.getEntityCache().getEntityByJavaId(packet.getAttachedToId());
            if ((attachedToId == null || packet.getAttachedToId() == 0)) {
                // Is not being leashed
                holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, false);
                holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, -1L);
                holderId.updateBedrockMetadata(session);
                EntityEventPacket eventPacket = new EntityEventPacket();
                eventPacket.setRuntimeEntityId(holderId.getGeyserId());
                eventPacket.setType(EntityEventType.REMOVE_LEASH);
                eventPacket.setData(0);
                session.sendUpstreamPacket(eventPacket);
                return;
            }
        }

        holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, true);
        holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, attachedToId.getGeyserId());
        holderId.updateBedrockMetadata(session);
    }
//  [java]
    public void translate(ServerEntityAttachPacket packet, GeyserSession session) {

        Entity holderId;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            holderId = session.getPlayerEntity();
        } else {
            holderId = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
            if (holderId == null) {
                return;
            }
        }

        Entity attachedToId;
        if (packet.getAttachedToId() == session.getPlayerEntity().getEntityId()) {
            attachedToId = session.getPlayerEntity();
        } else {
            attachedToId = session.getEntityCache().getEntityByJavaId(packet.getAttachedToId());
            if ((attachedToId == null || packet.getAttachedToId() == 0)) {
                // Is not being leashed
                holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, false);
                holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, -1L);
                holderId.updateBedrockMetadata(session);
                EntityEventPacket eventPacket = new EntityEventPacket();
                eventPacket.setRuntimeEntityId(holderId.getGeyserId());
                eventPacket.setType(EntityEventType.REMOVE_LEASH);
                eventPacket.setData(0);
                session.sendUpstreamPacket(eventPacket);
                return;
            }
        }

        holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, true);
        holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, attachedToId.getGeyserId());
        holderId.updateBedrockMetadata(session);
    }
//  [java]
	public void renderHead(IHeaderResponse response) {
		super.renderHead(response);
		response.render(JavaScriptHeaderItem.forReference(new MarkdownResourceReference()));
		
		String actionCallback = actionBehavior.getCallbackFunction(explicit("action"), explicit("param1"), explicit("param2"), 
				explicit("param3")).toString();
		String attachmentUploadUrl = attachmentUploadBehavior.getCallbackUrl().toString();
		
		String autosaveKey = getAutosaveKey();
		if (autosaveKey != null)
			autosaveKey = "'" + JavaScriptEscape.escapeJavaScript(autosaveKey) + "'";
		else
			autosaveKey = "undefined";
		
		String script = String.format("onedev.server.markdown.onDomReady('%s', %s, %d, %s, %d, %b, %b, '%s', %s);", 
				container.getMarkupId(), 
				actionCallback, 
				ATWHO_LIMIT, 
				getAttachmentSupport()!=null? "'" + attachmentUploadUrl + "'": "undefined", 
				getAttachmentSupport()!=null? getAttachmentSupport().getAttachmentMaxSize(): 0,
				getUserMentionSupport() != null,
				getReferenceSupport() != null, 
				JavaScriptEscape.escapeJavaScript(ProjectNameValidator.PATTERN.pattern()),
				autosaveKey);
		response.render(OnDomReadyHeaderItem.forScript(script));
		
		script = String.format("onedev.server.markdown.onLoad('%s');", container.getMarkupId());
		response.render(OnLoadHeaderItem.forScript(script));
	}
//  [java]
	public void renderHead(IHeaderResponse response) {
		super.renderHead(response);
		response.render(JavaScriptHeaderItem.forReference(new MarkdownResourceReference()));
		
		String encodedAttachmentSupport;
		if (getAttachmentSupport() != null) {
			encodedAttachmentSupport = Base64.encodeBase64String(SerializationUtils.serialize(getAttachmentSupport()));
			encodedAttachmentSupport = StringUtils.deleteWhitespace(encodedAttachmentSupport);
			encodedAttachmentSupport = StringEscapeUtils.escapeEcmaScript(encodedAttachmentSupport);
			encodedAttachmentSupport = "'" + encodedAttachmentSupport + "'";
		} else {
			encodedAttachmentSupport = "undefined";
		}
		
		String callback = ajaxBehavior.getCallbackFunction(explicit("action"), explicit("param1"), explicit("param2"), 
				explicit("param3")).toString();
		
		String autosaveKey = getAutosaveKey();
		if (autosaveKey != null)
			autosaveKey = "'" + JavaScriptEscape.escapeJavaScript(autosaveKey) + "'";
		else
			autosaveKey = "undefined";
		
		String script = String.format("onedev.server.markdown.onDomReady('%s', %s, %d, %s, %d, %b, %b, '%s', %s);", 
				container.getMarkupId(), 
				callback, 
				ATWHO_LIMIT, 
				encodedAttachmentSupport, 
				getAttachmentSupport()!=null?getAttachmentSupport().getAttachmentMaxSize():0,
				getUserMentionSupport() != null,
				getReferenceSupport() != null, 
				JavaScriptEscape.escapeJavaScript(ProjectNameValidator.PATTERN.pattern()),
				autosaveKey);
		response.render(OnDomReadyHeaderItem.forScript(script));
		
		script = String.format("onedev.server.markdown.onLoad('%s');", container.getMarkupId());
		response.render(OnLoadHeaderItem.forScript(script));
	}
//  [java]
  public static CharSequence createOptimized(String value) {
    HttpUtils.validateHeader(value);
    return new AsciiString(value);
  }
//  [java]
  public static CharSequence createOptimized(String value) {
    return io.netty.handler.codec.http.HttpHeaders.newEntity(value);
  }
//  [java]
	public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl wContr, Translator trans) {
		this.translator = trans;
		this.folderComponent = fc;
		this.fileSelection = new FileSelection(ureq, fc.getCurrentContainer(), fc.getCurrentContainerPath());

		VFSContainer currentContainer = folderComponent.getCurrentContainer();
		List<String> lockedFiles = hasLockedFiles(currentContainer, fileSelection);
		if (lockedFiles.isEmpty()) {
			String msg = trans.translate("del.confirm") + "<p>" + fileSelection.renderAsHtml() + "</p>";		
			// create dialog controller
			dialogCtr = activateYesNoDialog(ureq, trans.translate("del.header"), msg, dialogCtr);
		} else {
			String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles);
			List<String> buttonLabels = Collections.singletonList(trans.translate("ok"));
			lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr);
		}
		return this;
	}
//  [java]
	public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl wContr, Translator trans) {
		this.translator = trans;
		this.folderComponent = fc;
		this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath());

		VFSContainer currentContainer = folderComponent.getCurrentContainer();
		List<String> lockedFiles = hasLockedFiles(currentContainer, fileSelection);
		if (lockedFiles.isEmpty()) {
			String msg = trans.translate("del.confirm") + "<p>" + fileSelection.renderAsHtml() + "</p>";		
			// create dialog controller
			dialogCtr = activateYesNoDialog(ureq, trans.translate("del.header"), msg, dialogCtr);
		} else {
			String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles);
			List<String> buttonLabels = Collections.singletonList(trans.translate("ok"));
			lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr);
		}
		return this;
	}
//  [java]
    public String extractCorsOrigin(String pOrigin) {
        if (pOrigin != null) {
            // Prevent HTTP response splitting attacks
            String origin  = pOrigin.replaceAll("[\\n\\r]*","");
            if (backendManager.isOriginAllowed(origin,false)) {
                return "null".equals(origin) ? "*" : origin;
            } else {
                return null;
            }
        }
        return null;
    }
//  [java]
    public String extractCorsOrigin(String pOrigin) {
        if (pOrigin != null) {
            // Prevent HTTP response splitting attacks
            String origin  = pOrigin.replaceAll("[\\n\\r]*","");
            if (backendManager.isCorsAccessAllowed(origin)) {
                return "null".equals(origin) ? "*" : origin;
            } else {
                return null;
            }
        }
        return null;
    }
//  [java]
        public int getPosition()
        {
            if ( realPos == -1 )
            {
                realPos = ( getLiteralExecutable() == null ? 0 : 1 );
                for ( int i = 0; i < position; i++ )
                {
                    Arg arg = (Arg) arguments.elementAt( i );
                    realPos += arg.getParts().length;
                }
            }
            return realPos;
        }
//  [java]
        public int getPosition()
        {
            if ( realPos == -1 )
            {
                realPos = ( getExecutable() == null ? 0 : 1 );
                for ( int i = 0; i < position; i++ )
                {
                    Arg arg = (Arg) arguments.elementAt( i );
                    realPos += arg.getParts().length;
                }
            }
            return realPos;
        }
//  [java]
    public void translate(GeyserSession session, ServerAdvancementTabPacket packet) {
        AdvancementsCache advancementsCache = session.getAdvancementsCache();
        advancementsCache.setCurrentAdvancementCategoryId(packet.getTabId());
        advancementsCache.buildAndShowListForm();
    }
//  [java]
    public void translate(ServerAdvancementTabPacket packet, GeyserSession session) {
        AdvancementsCache advancementsCache = session.getAdvancementsCache();
        advancementsCache.setCurrentAdvancementCategoryId(packet.getTabId());
        advancementsCache.buildAndShowListForm();
    }
//  [java]
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            HttpServletRequest httpReq = (HttpServletRequest) request;
            HttpServletResponse httpResp = (HttpServletResponse) response;

            if ("GET".equals(httpReq.getMethod())) {
                String pushSessionId = httpReq.getParameter(PUSH_SESSION_ID_PARAM);

                Session session = null;

                if (pushSessionId != null) {
                    ensureServletContextAvailable(request);
                    PushContext pushContext = (PushContext) servletContext.getAttribute(PushContext.INSTANCE_KEY_NAME);
                    session = pushContext.getSessionManager().getPushSession(pushSessionId);
                }

                if (session == null) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(MessageFormat.format("Session {0} was not found", pushSessionId));
                    }
                    httpResp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }

                httpResp.setContentType("text/plain");

                Meteor meteor = Meteor.build(httpReq, SCOPE.REQUEST, Collections.<BroadcastFilter>emptyList(), null);

                try {
                    Request pushRequest = new RequestImpl(meteor, session);

                    httpReq.setAttribute(SESSION_ATTRIBUTE_NAME, session);
                    httpReq.setAttribute(REQUEST_ATTRIBUTE_NAME, pushRequest);

                    pushRequest.suspend();
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }

                return;
            }
        }
    }
//  [java]
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            HttpServletRequest httpReq = (HttpServletRequest) request;
            HttpServletResponse httpResp = (HttpServletResponse) response;

            if ("GET".equals(httpReq.getMethod())) {
                Meteor meteor = Meteor.build(httpReq, SCOPE.REQUEST, Collections.<BroadcastFilter>emptyList(), null);

                String pushSessionId = httpReq.getParameter(PUSH_SESSION_ID_PARAM);

                Session session = null;

                if (pushSessionId != null) {
                    ensureServletContextAvailable(request);
                    PushContext pushContext = (PushContext) servletContext.getAttribute(PushContext.INSTANCE_KEY_NAME);
                    session = pushContext.getSessionManager().getPushSession(pushSessionId);
                }

                if (session == null) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(MessageFormat.format("Session {0} was not found", pushSessionId));
                    }
                    httpResp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }

                httpResp.setContentType("text/plain");

                try {
                    Request pushRequest = new RequestImpl(meteor, session);

                    httpReq.setAttribute(SESSION_ATTRIBUTE_NAME, session);
                    httpReq.setAttribute(REQUEST_ATTRIBUTE_NAME, pushRequest);

                    pushRequest.suspend();
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }

                return;
            }
        }
    }
//  [java]
    public Process execute()
        throws CommandLineException
    {
        // TODO: Provided only for backward compat. with <= 1.4
        verifyShellState();

        Process process;

        //addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );

        String[] environment = getEnvironmentVariables();

        File workingDir = shell.getWorkingDirectory();

        try
        {
            if ( workingDir == null )
            {
                process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir );
            }
            else
            {
                if ( !workingDir.exists() )
                {
                    throw new CommandLineException( "Working directory \"" + workingDir.getPath()
                        + "\" does not exist!" );
                }
                else if ( !workingDir.isDirectory() )
                {
                    throw new CommandLineException( "Path \"" + workingDir.getPath()
                        + "\" does not specify a directory." );
                }

                process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir );
            }
        }
        catch ( IOException ex )
        {
            throw new CommandLineException( "Error while executing process.", ex );
        }

        return process;
    }
//  [java]
    public Process execute()
        throws CommandLineException
    {
        // TODO: Provided only for backward compat. with <= 1.4
        verifyShellState();

        Process process;

        //addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );

        String[] environment = getEnvironmentVariables();

        File workingDir = shell.getWorkingDirectory();

        try
        {
            if ( workingDir == null )
            {
                process = Runtime.getRuntime().exec( getShellCommandline(), environment );
            }
            else
            {
                if ( !workingDir.exists() )
                {
                    throw new CommandLineException( "Working directory \"" + workingDir.getPath()
                        + "\" does not exist!" );
                }
                else if ( !workingDir.isDirectory() )
                {
                    throw new CommandLineException( "Path \"" + workingDir.getPath()
                        + "\" does not specify a directory." );
                }

                process = Runtime.getRuntime().exec( getShellCommandline(), environment, workingDir );
            }
        }
        catch ( IOException ex )
        {
            throw new CommandLineException( "Error while executing process.", ex );
        }

        return process;
    }
//  [java]
    public Map<String, String> handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) {
        Map<String,String> ret = new HashMap<String, String>();
        if (pOrigin != null && backendManager.isOriginAllowed(pOrigin,false)) {
            // CORS is allowed, we set exactly the origin in the header, so there are no problems with authentication
            ret.put("Access-Control-Allow-Origin","null".equals(pOrigin) ? "*" : pOrigin);
            if (pRequestHeaders != null) {
                ret.put("Access-Control-Allow-Headers",pRequestHeaders);
            }
            // Fix for CORS with authentication (#104)
            ret.put("Access-Control-Allow-Credentials","true");
            // Allow for one year. Changes in access.xml are reflected directly in the  cors request itself
            ret.put("Access-Control-Allow-Max-Age","" + 3600 * 24 * 365);
        }
        return ret;
    }
//  [java]
    public Map<String, String> handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) {
        Map<String,String> ret = new HashMap<String, String>();
        if (pOrigin != null && backendManager.isCorsAccessAllowed(pOrigin)) {
            // CORS is allowed, we set exactly the origin in the header, so there are no problems with authentication
            ret.put("Access-Control-Allow-Origin","null".equals(pOrigin) ? "*" : pOrigin);
            if (pRequestHeaders != null) {
                ret.put("Access-Control-Allow-Headers",pRequestHeaders);
            }
            // Fix for CORS with authentication (#104)
            ret.put("Access-Control-Allow-Credentials","true");
            // Allow for one year. Changes in access.xml are reflected directly in the  cors request itself
            ret.put("Access-Control-Allow-Max-Age","" + 3600 * 24 * 365);
        }
        return ret;
    }
//  [java]
    public String[] getCommandline()
    {
        final String[] args = getArguments();
        String executable = getLiteralExecutable();

        if ( executable == null )
        {
            return args;
        }
        final String[] result = new String[args.length + 1];
        result[0] = executable;
        System.arraycopy( args, 0, result, 1, args.length );
        return result;
    }
//  [java]
    public String[] getCommandline()
    {
        final String[] args = getArguments();
        String executable = getExecutable();

        if ( executable == null )
        {
            return args;
        }
        final String[] result = new String[args.length + 1];
        result[0] = executable;
        System.arraycopy( args, 0, result, 1, args.length );
        return result;
    }
//  [java]
    private void verifyShellState()
    {
        if ( shell.getWorkingDirectory() == null )
        {
            shell.setWorkingDirectory( workingDir );
        }

        if ( shell.getOriginalExecutable() == null )
        {
            shell.setExecutable( executable );
        }
    }
//  [java]
    private void verifyShellState()
    {
        if ( shell.getWorkingDirectory() == null )
        {
            shell.setWorkingDirectory( workingDir );
        }

        if ( shell.getExecutable() == null )
        {
            shell.setExecutable( executable );
        }
    }
//  [java]
    protected void afterFeaturesReceived() throws NotConnectedException, InterruptedException {
        StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
        if (startTlsFeature != null) {
            if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
                notifyConnectionError(new SecurityRequiredByServerException());
                return;
            }

            if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
                sendNonza(new StartTls());
            }
        }

        if (getSASLAuthentication().authenticationSuccessful()) {
            // If we have received features after the SASL has been successfully completed, then we
            // have also *maybe* received, as it is an optional feature, the compression feature
            // from the server.
            maybeCompressFeaturesReceived.reportSuccess();
        }
    }