jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
  protected URI addContentToRepo(MediaPackage mp, String elementId, URI uri) throws IOException {
    InputStream in = null;
    HttpResponse response = null;
    CloseableHttpClient externalHttpClient = null;
    try {
      if (uri.toString().startsWith("http")) {
        HttpGet get = new HttpGet(uri);
        List<String> clusterUrls = new LinkedList<>();
        try {
          // Note that we are not checking ports here.
          clusterUrls = organizationDirectoryService.getOrganization(uri.toURL()).getServers()
                          .keySet()
                          .stream()
                          .collect(Collectors.toUnmodifiableList());
        } catch (NotFoundException e) {
          logger.warn("Unable to determine cluster members, will not be able to authenticate any downloads from them", e);
        }

        if (uri.toString().matches(downloadSource)) {
          //NB: We're creating a new client here with *different* auth than the system auth creds
          externalHttpClient = getAuthedHttpClient();
          response = externalHttpClient.execute(get);
        } else if (clusterUrls.contains(uri.getScheme() + "://" + uri.getHost())) {
          // Only using the system-level httpclient and digest credentials against our own servers
          response = httpClient.execute(get);
        } else {
          //NB: No auth here at all
          externalHttpClient = getNoAuthHttpClient();
          response = externalHttpClient.execute(get);
        }

        if (null == response) {
          // If you get here then chances are you're using a mock httpClient which does not have appropriate
          // mocking to respond to the URL you are feeding it.  Try adding that URL to the mock and see if that works.
          throw new IOException("Null response object from the http client, refer to code for explanation");
        }

        int httpStatusCode = response.getStatusLine().getStatusCode();
        if (httpStatusCode != 200) {
          throw new IOException(uri + " returns http " + httpStatusCode);
        }
        in = response.getEntity().getContent();
        //If it does not start with file, or we're in test mode (ie, to allow arbitrary file:// access)
      } else if (!uri.toString().startsWith("file") || testMode) {
        in = uri.toURL().openStream();
      } else {
        throw new IOException("Refusing to fetch files from the local filesystem");
      }
      String fileName = FilenameUtils.getName(uri.getPath());
      if (isBlank(FilenameUtils.getExtension(fileName)))
        fileName = getContentDispositionFileName(response);

      if (isBlank(FilenameUtils.getExtension(fileName)))
        throw new IOException("No filename extension found: " + fileName);
      return addContentToRepo(mp, elementId, fileName, in);
    } finally {
      if (in != null) {
        in.close();
      }
      if (externalHttpClient != null) {
        externalHttpClient.close();
      }
      httpClient.close(response);
    }
  }
//  [java]
    protected int addFileNames(String[] file) { // This appears to only be used by unit tests
        for (String f : file) {
            addWorkUnit(new WorkUnit(f));
        }
        return size();
    }
//  [java]
    protected int addFileNames(String[] file) { // This appears to only be used by unit tests
        for (int i = 0; file != null && i < file.length; i++) {
            workUnitList.add(new WorkUnit(file[i]));
        }
        return size();
    }
//  [java]
    public int addFileName(String file) {
        return addWorkUnit(new WorkUnit(file));
    }
//  [java]
    public int addFileName(String file) {
        workUnitList.add(new WorkUnit(file));
        return size();
    }
//  [java]
    public int addWorkUnit(WorkUnit workUnit) {
        if (workUnitList.size() >= MAX_UNITS) {
            throw new IllegalStateException("WorkBundle may not contain more than " + MAX_UNITS + " WorkUnits.");
        }
        workUnitList.add(workUnit);
        return size();
    }
//  [java]
    public int addWorkUnit(WorkUnit workUnit, long fileModificationTimeInMillis, long fileSize) {
        workUnitList.add(workUnit);
        if (fileModificationTimeInMillis < oldestFileModificationTime) {
            oldestFileModificationTime = fileModificationTimeInMillis;
        }
        if (fileModificationTimeInMillis > youngestFileModificationTime) {
            youngestFileModificationTime = fileModificationTimeInMillis;
        }
        totalFileSize += fileSize;
        return size();
    }
//  [java]
    public void translate(GeyserSession session, SetLocalPlayerAsInitializedPacket packet) {
        if (session.getPlayerEntity().getGeyserId() == packet.getRuntimeEntityId()) {
            if (!session.getUpstream().isInitialized()) {
                session.getUpstream().setInitialized(true);
                session.login();

                for (PlayerEntity entity : session.getEntityCache().getEntitiesByType(PlayerEntity.class)) {
                    if (!entity.isValid()) {
                        SkinManager.requestAndHandleSkinAndCape(entity, session, null);
                        entity.sendPlayer(session);
                    }
                }

                // Send Skulls
                for (PlayerEntity entity : session.getSkullCache().values()) {
                    entity.spawnEntity(session);

                    SkullSkinManager.requestAndHandleSkin(entity, session, (skin) ->  {
                        entity.getMetadata().getFlags().setFlag(EntityFlag.INVISIBLE, false);
                        entity.updateBedrockMetadata(session);
                    });
                }
            }
        }
    }
//  [java]
    public void translate(SetLocalPlayerAsInitializedPacket packet, GeyserSession session) {
        if (session.getPlayerEntity().getGeyserId() == packet.getRuntimeEntityId()) {
            if (!session.getUpstream().isInitialized()) {
                session.getUpstream().setInitialized(true);
                session.login();

                for (PlayerEntity entity : session.getEntityCache().getEntitiesByType(PlayerEntity.class)) {
                    if (!entity.isValid()) {
                        SkinManager.requestAndHandleSkinAndCape(entity, session, null);
                        entity.sendPlayer(session);
                    }
                }

                // Send Skulls
                for (PlayerEntity entity : session.getSkullCache().values()) {
                    entity.spawnEntity(session);

                    SkullSkinManager.requestAndHandleSkin(entity, session, (skin) ->  {
                        entity.getMetadata().getFlags().setFlag(EntityFlag.INVISIBLE, false);
                        entity.updateBedrockMetadata(session);
                    });
                }
            }
        }
    }
//  [java]
    public void translate(GeyserSession session, EntityPickRequestPacket packet) {
        if (session.getGameMode() != GameMode.CREATIVE) return; // Apparently Java behavior
        Entity entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId());
        if (entity == null) return;

        // Get the corresponding item
        String itemName;
        switch (entity.getEntityType()) {
            case BOAT:
                // Include type of boat in the name
                int variant = entity.getMetadata().getInt(EntityData.VARIANT);
                String typeOfBoat;
                switch (variant) {
                    case 1:
                        typeOfBoat = "spruce";
                        break;
                    case 2:
                        typeOfBoat = "birch";
                        break;
                    case 3:
                        typeOfBoat = "jungle";
                        break;
                    case 4:
                        typeOfBoat = "acacia";
                        break;
                    case 5:
                        typeOfBoat = "dark_oak";
                        break;
                    default:
                        typeOfBoat = "oak";
                        break;
                }
                itemName = typeOfBoat + "_boat";
                break;
            case LEASH_KNOT:
                itemName = "lead";
                break;
            case MINECART_CHEST:
            case MINECART_COMMAND_BLOCK:
            case MINECART_FURNACE:
            case MINECART_HOPPER:
            case MINECART_TNT:
                // Move MINECART to the end of the name
                itemName = entity.getEntityType().toString().toLowerCase().replace("minecart_", "") + "_minecart";
                break;
            case MINECART_SPAWNER:
                // Turns into a normal minecart
                itemName = "minecart";
                break;
            case ARMOR_STAND:
            case END_CRYSTAL:
            //case ITEM_FRAME: Not an entity in Bedrock Edition
            //case GLOW_ITEM_FRAME:
            case MINECART:
            case PAINTING:
                // No spawn egg, just an item
                itemName = entity.getEntityType().toString().toLowerCase();
                break;
            default:
                itemName = entity.getEntityType().toString().toLowerCase() + "_spawn_egg";
                break;
        }

        String fullItemName = "minecraft:" + itemName;
        ItemMapping mapping = session.getItemMappings().getMapping(fullItemName);
        // Verify it is, indeed, an item
        if (mapping == null) return;

        InventoryUtils.findOrCreateItem(session, fullItemName);
    }
//  [java]
    public void translate(EntityPickRequestPacket packet, GeyserSession session) {
        if (session.getGameMode() != GameMode.CREATIVE) return; // Apparently Java behavior
        Entity entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId());
        if (entity == null) return;

        // Get the corresponding item
        String itemName;
        switch (entity.getEntityType()) {
            case BOAT:
                // Include type of boat in the name
                int variant = entity.getMetadata().getInt(EntityData.VARIANT);
                String typeOfBoat;
                switch (variant) {
                    case 1:
                        typeOfBoat = "spruce";
                        break;
                    case 2:
                        typeOfBoat = "birch";
                        break;
                    case 3:
                        typeOfBoat = "jungle";
                        break;
                    case 4:
                        typeOfBoat = "acacia";
                        break;
                    case 5:
                        typeOfBoat = "dark_oak";
                        break;
                    default:
                        typeOfBoat = "oak";
                        break;
                }
                itemName = typeOfBoat + "_boat";
                break;
            case LEASH_KNOT:
                itemName = "lead";
                break;
            case MINECART_CHEST:
            case MINECART_COMMAND_BLOCK:
            case MINECART_FURNACE:
            case MINECART_HOPPER:
            case MINECART_TNT:
                // Move MINECART to the end of the name
                itemName = entity.getEntityType().toString().toLowerCase().replace("minecart_", "") + "_minecart";
                break;
            case MINECART_SPAWNER:
                // Turns into a normal minecart
                itemName = "minecart";
                break;
            case ARMOR_STAND:
            case END_CRYSTAL:
            //case ITEM_FRAME: Not an entity in Bedrock Edition
            //case GLOW_ITEM_FRAME:
            case MINECART:
            case PAINTING:
                // No spawn egg, just an item
                itemName = entity.getEntityType().toString().toLowerCase();
                break;
            default:
                itemName = entity.getEntityType().toString().toLowerCase() + "_spawn_egg";
                break;
        }

        String fullItemName = "minecraft:" + itemName;
        ItemMapping mapping = session.getItemMappings().getMapping(fullItemName);
        // Verify it is, indeed, an item
        if (mapping == null) return;

        InventoryUtils.findOrCreateItem(session, fullItemName);
    }
//  [java]
    public void translate(GeyserSession session, ServerSetActionBarTextPacket 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.ACTIONBAR);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }
//  [java]
    public void translate(ServerSetActionBarTextPacket 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.ACTIONBAR);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }
//  [java]
    public void save(String comment, boolean minorEdit) throws XWikiException
    {
        if (hasAccessLevel("edit")) {
            // If the current author does not have PR don't let it set current user as author of the saved document
            // since it can lead to right escalation
            if (hasProgrammingRights() || !getConfiguration().getProperty("security.script.save.checkAuthor", true)) {
                saveDocument(comment, minorEdit);
            } else {
                saveAsAuthor(comment, minorEdit);
            }
        } else {
            java.lang.Object[] args = {getDefaultEntityReferenceSerializer().serialize(getDocumentReference())};
            throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
                "Access denied in edit mode on document {0}", null, args);
        }
    }
//  [java]
    public void save(String comment, boolean minorEdit) throws XWikiException
    {
        if (hasAccessLevel("edit")) {
            // If the current author does not have PR don't let it set current user as author of the saved document
            // since it can lead to right escalation
            if (hasProgrammingRights()) {
                saveDocument(comment, minorEdit);
            } else {
                saveAsAuthor(comment, minorEdit);
            }
        } else {
            java.lang.Object[] args = {getDefaultEntityReferenceSerializer().serialize(getDocumentReference())};
            throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
                "Access denied in edit mode on document {0}", null, args);
        }
    }
//  [java]
        void setPaths(final String s) {
            try {
                final DataInputStream dis = new DataInputStream(new ByteArrayInputStream(s.getBytes("8859_1")));
                this.paths = WorkBundle.readFromStream(dis);
            } catch (Exception e) {
                logger.error("Cannot deserialize WorkBundle using {} bytes", s.length(), e);
                throw new IllegalArgumentException("Cannot deserialize WorkBundle");
            }
        }
//  [java]
        void setPaths(final String s) {
            try {
                final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes("8859_1")));
                this.paths = (WorkBundle) ois.readObject();
            } catch (Exception e) {
                logger.error("Cannot deserialize WorkBundle using {} bytes", s.length(), e);
                throw new IllegalArgumentException("Cannot deserialize WorkBundle");
            }
        }
//  [java]
	public PlayerClock(String title, ISkinParam skinParam, TimingRuler ruler, int period, int pulse, int offset,
			boolean compact) {
		super(title, skinParam, ruler, compact, null);
		this.displayTitle = title.length() > 0;
		this.period = period;
		this.pulse = pulse;
		this.offset = offset;
		this.suggestedHeight = 30;
	}
//  [java]
	public PlayerClock(String title, ISkinParam skinParam, TimingRuler ruler, int period, int pulse, int offset,
			boolean compact) {
		super(title, skinParam, ruler, compact);
		this.displayTitle = title.length() > 0;
		this.period = period;
		this.pulse = pulse;
		this.offset = offset;
		this.suggestedHeight = 30;
	}
//  [java]
	public PlayerBinary(String code, ISkinParam skinParam, TimingRuler ruler, boolean compact, Stereotype stereotype) {
		super(code, skinParam, ruler, compact, stereotype);
		this.suggestedHeight = 30;
	}
//  [java]
	public PlayerBinary(String code, ISkinParam skinParam, TimingRuler ruler, boolean compact) {
		super(code, skinParam, ruler, compact);
		this.style = getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder());
		this.suggestedHeight = 30;
	}
//  [java]
    public void translate(GeyserSession session, ServerWindowPropertyPacket packet) {
        Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
        if (inventory == null)
            return;

        InventoryTranslator translator = session.getInventoryTranslator();
        if (translator != null) {
            translator.updateProperty(session, inventory, packet.getRawProperty(), packet.getValue());
        }
    }
//  [java]
    public void translate(ServerWindowPropertyPacket packet, GeyserSession session) {
        Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
        if (inventory == null)
            return;

        InventoryTranslator translator = session.getInventoryTranslator();
        if (translator != null) {
            translator.updateProperty(session, inventory, packet.getRawProperty(), packet.getValue());
        }
    }
//  [java]
    public void encodeByteArray() throws JSONException {
        Packet<JSONArray> packet = new Packet<>(Parser.BINARY_EVENT);
        packet.data = new JSONArray(asList("abc", "abc".getBytes(StandardCharsets.UTF_8)));
        packet.id = 23;
        packet.nsp = "/cool";
        Helpers.testBin(packet);
    }
//  [java]
    public void encodeByteArray() {
        Packet<byte[]> packet = new Packet<>(Parser.BINARY_EVENT);
        packet.data = "abc".getBytes(Charset.forName("UTF-8"));
        packet.id = 23;
        packet.nsp = "/cool";
        Helpers.testBin(packet);
    }
//  [java]
    public void encodeByteArray2() {
        Packet<JSONArray> packet = new Packet<>(Parser.BINARY_EVENT);
        packet.data = new JSONArray(asList("2", new byte[] { 0, 1 }));
        packet.id = 0;
        packet.nsp = "/";
        Helpers.testBin(packet);
    }
//  [java]
    public void encodeByteArray2() {
        Packet<byte[]> packet = new Packet<>(Parser.BINARY_EVENT);
        packet.data = new byte[2];
        packet.id = 0;
        packet.nsp = "/";
        Helpers.testBin(packet);
    }
//  [java]
    public void encodeByteArrayDeepInJson() throws JSONException {
        JSONArray data = new JSONArray("[{a: \"hi\", b: {}, c: {a: \"bye\", b: {}}}]");
        data.getJSONObject(0).getJSONObject("b").put("why", new byte[3]);
        data.getJSONObject(0).getJSONObject("c").getJSONObject("b").put("a", new byte[6]);

        Packet<JSONArray> packet = new Packet<>(Parser.BINARY_EVENT);
        packet.data = data;
        packet.id = 999;
        packet.nsp = "/deep";
        Helpers.testBin(packet);
    }
//  [java]
    public void encodeByteArrayDeepInJson() throws JSONException {
        JSONObject data = new JSONObject("{a: \"hi\", b: {}, c: {a: \"bye\", b: {}}}");
        data.getJSONObject("b").put("why", new byte[3]);
        data.getJSONObject("c").getJSONObject("b").put("a", new byte[6]);

        Packet<JSONObject> packet = new Packet<>(Parser.BINARY_EVENT);
        packet.data = data;
        packet.id = 999;
        packet.nsp = "/deep";
        Helpers.testBin(packet);
    }
//  [java]
    public void testPullCount() throws IOException {
        String url = RepoUtils.getRemoteRepoURL() + "/modules/info/" + orgName + "/" + moduleName + "/*/";
        HttpsURLConnection conn = createHttpsUrlConnection(convertToUrl(url), "", 0, "", "");
        conn.setInstanceFollowRedirects(false);
        setRequestMethod(conn, Utils.RequestMethod.GET);

        int statusCode = conn.getResponseCode();
        if (statusCode == 200) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                    Charset.defaultCharset()))) {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                Object payload = JSONParser.parse(result.toString());
                if (payload instanceof MapValue) {
                    long pullCount = ((MapValue) payload).getIntValue("totalPullCount");
                    Assert.assertEquals(pullCount, totalPullCount);
                } else {
                    Assert.fail("error: invalid response received");
                }
            }
        } else {
            Assert.fail("error: could not connect to remote repository to find the latest version of module");
        }
    }
//  [java]
    public void testPullCount() throws IOException {
        initializeSsl();
        String url = RepoUtils.getRemoteRepoURL() + "/modules/info/" + orgName + "/" + moduleName + "/*/";
        HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), "", 0, "", "");
        conn.setInstanceFollowRedirects(false);
        setRequestMethod(conn, Utils.RequestMethod.GET);

        int statusCode = conn.getResponseCode();
        if (statusCode == 200) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                    Charset.defaultCharset()))) {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                Object payload = JSONParser.parse(result.toString());
                if (payload instanceof MapValue) {
                    long pullCount = ((MapValue) payload).getIntValue("totalPullCount");
                    Assert.assertEquals(pullCount, totalPullCount);
                } else {
                    Assert.fail("error: invalid response received");
                }
            }
        } else {
            Assert.fail("error: could not connect to remote repository to find the latest version of module");
        }
    }
//  [java]
    public void encodeDeepBinaryJSONWithNullValue() throws JSONException {
        JSONArray data = new JSONArray("[{a: \"b\", c: 4, e: {g: null}, h: null}]");
        data.getJSONObject(0).put("h", new byte[9]);

        Packet<JSONArray> packet = new Packet<>(Parser.BINARY_EVENT);
        packet.data = data;
        packet.nsp = "/";
        packet.id = 600;
        Helpers.testBin(packet);
    }
//  [java]
    public void encodeDeepBinaryJSONWithNullValue() throws JSONException {
        JSONObject data = new JSONObject("{a: \"b\", c: 4, e: {g: null}, h: null}");
        data.put("h", new byte[9]);

        Packet<JSONObject> packet = new Packet<>(Parser.BINARY_EVENT);
        packet.data = data;
        packet.nsp = "/";
        packet.id = 600;
        Helpers.testBin(packet);
    }
//  [java]
	protected StyleSignature getStyleSignature() {
		return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.binary).withTOBECHANGED(stereotype);
	}
//  [java]
	protected StyleSignatureBasic getStyleSignature() {
		return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.binary);
	}
//  [java]
	public Object getResourceDataForKey(String key) {
		Object data = null;
		String dataString = null;
		Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(key);
		if (matcher.find()) {
			if (log.isDebugEnabled()) {
				log.debug(Messages.getMessage(
						Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key,
						dataString));
			}
			int dataStart = matcher.end();
			dataString = key.substring(dataStart);
			byte[] objectArray = null;
			byte[] dataArray;
			try {
				dataArray = dataString.getBytes("ISO-8859-1");
				objectArray = decrypt(dataArray);
			} catch (UnsupportedEncodingException e1) {
				// default encoding always presented.
			}
			if ("B".equals(matcher.group(1))) {
				data = objectArray;
			} else {
				try {
					ObjectInputStream in = new LookAheadObjectInputStream(new ByteArrayInputStream(objectArray));
					data = in.readObject();
				} catch (StreamCorruptedException e) {
					log.error(Messages
							.getMessage(Messages.STREAM_CORRUPTED_ERROR), e);
				} catch (IOException e) {
					log.error(Messages
							.getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR),
							e);
				} catch (ClassNotFoundException e) {
					log
							.error(
									Messages
											.getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR),
									e);
				}
			}
		}

		return data;
	}
//  [java]
	public Object getResourceDataForKey(String key) {
		Object data = null;
		String dataString = null;
		Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(key);
		if (matcher.find()) {
			if (log.isDebugEnabled()) {
				log.debug(Messages.getMessage(
						Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key,
						dataString));
			}
			int dataStart = matcher.end();
			dataString = key.substring(dataStart);
			byte[] objectArray = null;
			byte[] dataArray;
			try {
				dataArray = dataString.getBytes("ISO-8859-1");
				objectArray = decrypt(dataArray);
			} catch (UnsupportedEncodingException e1) {
				// default encoding always presented.
			}
			if ("B".equals(matcher.group(1))) {
				data = objectArray;
			} else {
				try {
					ObjectInputStream in = new ObjectInputStream(
							new ByteArrayInputStream(objectArray));
					data = in.readObject();
				} catch (StreamCorruptedException e) {
					log.error(Messages
							.getMessage(Messages.STREAM_CORRUPTED_ERROR), e);
				} catch (IOException e) {
					log.error(Messages
							.getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR),
							e);
				} catch (ClassNotFoundException e) {
					log
							.error(
									Messages
											.getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR),
									e);
				}
			}
		}

		return data;
	}
//  [java]
    public void translate(GeyserSession session, SetPlayerGameTypePacket packet) {
        // no
        SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket();
        playerGameTypePacket.setGamemode(session.getGameMode().ordinal());
        session.sendUpstreamPacket(playerGameTypePacket);
    }
//  [java]
    public void translate(SetPlayerGameTypePacket packet, GeyserSession session) {
        // no
        SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket();
        playerGameTypePacket.setGamemode(session.getGameMode().ordinal());
        session.sendUpstreamPacket(playerGameTypePacket);
    }
//  [java]
	public static String applySorting(String query, Sort sort, String alias) {

		Assert.hasText(query);

		if (null == sort || !sort.iterator().hasNext()) {
			return query;
		}

		StringBuilder builder = new StringBuilder(query);

		if (!ORDER_BY.matcher(query).matches()) {
			builder.append(" order by ");
		} else {
			builder.append(", ");
		}

		Set<String> aliases = getOuterJoinAliases(query);
		Set<String> functionAliases = getFunctionAliases(query);

		for (Order order : sort) {
			builder.append(getOrderClause(aliases, functionAliases, alias, order)).append(", ");
		}

		builder.delete(builder.length() - 2, builder.length());

		return builder.toString();
	}
//  [java]
	public static String applySorting(String query, Sort sort, String alias) {

		Assert.hasText(query);

		if (null == sort || !sort.iterator().hasNext()) {
			return query;
		}

		StringBuilder builder = new StringBuilder(query);

		if (!ORDER_BY.matcher(query).matches()) {
			builder.append(" order by ");
		} else {
			builder.append(", ");
		}

		Set<String> aliases = getOuterJoinAliases(query);

		for (Order order : sort) {
			builder.append(getOrderClause(aliases, alias, order)).append(", ");
		}

		builder.delete(builder.length() - 2, builder.length());

		return builder.toString();
	}
//  [java]
	private static String getOrderClause(Set<String> joinAliases, Set<String> functionAlias, String alias, Order order) {

		String property = order.getProperty();

		checkSortExpression(order);

		if (functionAlias.contains(property)) {
			return String.format("%s %s", property, toJpaDirection(order));
		}

		boolean qualifyReference = !property.contains("("); // ( indicates a function

		for (String joinAlias : joinAliases) {
			if (property.startsWith(joinAlias.concat("."))) {
				qualifyReference = false;
				break;
			}
		}

		String reference = qualifyReference && StringUtils.hasText(alias) ? String.format("%s.%s", alias, property)
				: property;
		String wrapped = order.isIgnoreCase() ? String.format("lower(%s)", reference) : reference;

		return String.format("%s %s", wrapped, toJpaDirection(order));
	}
//  [java]
	private static String getOrderClause(Set<String> joinAliases, String alias, Order order) {

		String property = order.getProperty();
		boolean qualifyReference = !property.contains("("); // ( indicates a function

		for (String joinAlias : joinAliases) {
			if (property.startsWith(joinAlias.concat("."))) {
				qualifyReference = false;
				break;
			}
		}

		String reference = qualifyReference && StringUtils.hasText(alias) ? String.format("%s.%s", alias, property)
				: property;
		String wrapped = order.isIgnoreCase() ? String.format("lower(%s)", reference) : reference;

		return String.format("%s %s", wrapped, toJpaDirection(order));
	}
//  [java]
    protected void deactivateConversationContext(HttpServletRequest request) {
        try {
            ConversationContext conversationContext = httpConversationContext();
            if (conversationContext.isActive()) {
                // Only deactivate the context if one is already active, otherwise we get Exceptions
                if (conversationContext instanceof LazyHttpConversationContextImpl) {
                    LazyHttpConversationContextImpl lazyConversationContext = (LazyHttpConversationContextImpl) conversationContext;
                    if (!lazyConversationContext.isInitialized()) {
                        // if this lazy conversation has not been touched yet, just deactivate it
                        lazyConversationContext.deactivate();
                        return;
                    }
                }
                boolean isTransient = conversationContext.getCurrentConversation().isTransient();
                if (ConversationLogger.LOG.isTraceEnabled()) {
                    if (isTransient) {
                        ConversationLogger.LOG.cleaningUpTransientConversation();
                    } else {
                        ConversationLogger.LOG.cleaningUpConversation(conversationContext.getCurrentConversation().getId());
                    }
                }
                conversationContext.invalidate();
                conversationContext.deactivate();
                if (isTransient) {
                    conversationDestroyedEvent.fire(request);
                }
            }
        } catch (Exception e) {
            ServletLogger.LOG.unableToDeactivateContext(httpConversationContext(), request);
            ServletLogger.LOG.catchingDebug(e);
        }
    }
//  [java]
    protected void deactivateConversationContext(HttpServletRequest request) {
        ConversationContext conversationContext = httpConversationContext();
        if (conversationContext.isActive()) {
            // Only deactivate the context if one is already active, otherwise we get Exceptions
            if (conversationContext instanceof LazyHttpConversationContextImpl) {
                LazyHttpConversationContextImpl lazyConversationContext = (LazyHttpConversationContextImpl) conversationContext;
                if (!lazyConversationContext.isInitialized()) {
                    // if this lazy conversation has not been touched yet, just deactivate it
                    lazyConversationContext.deactivate();
                    return;
                }
            }
            boolean isTransient = conversationContext.getCurrentConversation().isTransient();
            if (ConversationLogger.LOG.isTraceEnabled()) {
                if (isTransient) {
                    ConversationLogger.LOG.cleaningUpTransientConversation();
                } else {
                    ConversationLogger.LOG.cleaningUpConversation(conversationContext.getCurrentConversation().getId());
                }
            }
            conversationContext.invalidate();
            conversationContext.deactivate();
            if (isTransient) {
                conversationDestroyedEvent.fire(request);
            }
        }
    }
//  [java]
	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) {
		VFSContainer currentContainer = folderComponent.getCurrentContainer();

		status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
		if(status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
	
		FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());
		status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
		if(status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
		
		if(selection.getFiles().isEmpty()) {
			status = FolderCommandStatus.STATUS_FAILED;
			wControl.setWarning(trans.translate("warning.file.selection.empty22"));
			return null;
		}
		
		MediaResource mr = new ZipMediaResource(currentContainer, selection);
		ureq.getDispatchResult().setResultingMediaResource(mr);
		return null;
	}
//  [java]
	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) {
		VFSContainer currentContainer = folderComponent.getCurrentContainer();

		status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
		if(status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
	
		FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
		status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
		if(status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
		
		if(selection.getFiles().isEmpty()) {
			status = FolderCommandStatus.STATUS_FAILED;
			wControl.setWarning(trans.translate("warning.file.selection.empty"));
			return null;
		}
		
		MediaResource mr = new ZipMediaResource(currentContainer, selection);
		ureq.getDispatchResult().setResultingMediaResource(mr);
		return null;
	}
//  [java]
	protected IBaseResource addCommonParams(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
		final String serverId = theRequest.getServerIdWithDefault(myConfig);
		final String serverBase = theRequest.getServerBase(theServletRequest, myConfig);
		final String serverName = theRequest.getServerName(myConfig);
		final String apiKey = theRequest.getApiKey(theServletRequest, myConfig);
		theModel.put("serverId", sanitizeInput(serverId));
		theModel.put("base", sanitizeInput(serverBase));
		theModel.put("baseName", sanitizeInput(serverName));
		theModel.put("apiKey", sanitizeInput(apiKey));
		theModel.put("resourceName", sanitizeInput(defaultString(theRequest.getResource())));
		theModel.put("encoding", sanitizeInput(theRequest.getEncoding()));
		theModel.put("pretty", sanitizeInput(theRequest.getPretty()));
		theModel.put("_summary", sanitizeInput(theRequest.get_summary()));
		theModel.put("serverEntries", myConfig.getIdToServerName());

		return loadAndAddConf(theServletRequest, theRequest, theModel);
	}
//  [java]
	protected IBaseResource addCommonParams(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
		final String serverId = theRequest.getServerIdWithDefault(myConfig);
		final String serverBase = theRequest.getServerBase(theServletRequest, myConfig);
		final String serverName = theRequest.getServerName(myConfig);
		final String apiKey = theRequest.getApiKey(theServletRequest, myConfig);
		theModel.put("serverId", serverId);
		theModel.put("base", serverBase);
		theModel.put("baseName", serverName);
		theModel.put("apiKey", apiKey);
		theModel.put("resourceName", defaultString(theRequest.getResource()));
		theModel.put("encoding", theRequest.getEncoding());
		theModel.put("pretty", theRequest.getPretty());
		theModel.put("_summary", theRequest.get_summary());
		theModel.put("serverEntries", myConfig.getIdToServerName());

		return loadAndAddConf(theServletRequest, theRequest, theModel);
	}
//  [java]
    public RoutingResultBuilder rawParam(String name, String value) {
        pathParams().put(requireNonNull(name, "name"),
                         ArmeriaHttpUtil.decodePathParam(requireNonNull(value, "value")));
        return this;
    }
//  [java]
    public RoutingResultBuilder rawParam(String name, String value) {
        pathParams().put(requireNonNull(name, "name"),
                         ArmeriaHttpUtil.decodePath(requireNonNull(value, "value")));
        return this;
    }
//  [java]
    public void translate(GeyserSession session, TextPacket packet) {
        String message = packet.getMessage();

        if (MessageTranslator.isTooLong(message, session)) {
            return;
        }

        ClientChatPacket chatPacket = new ClientChatPacket(message);
        session.sendDownstreamPacket(chatPacket);
    }
//  [java]
    public void translate(TextPacket packet, GeyserSession session) {
        String message = packet.getMessage();

        if (MessageTranslator.isTooLong(message, session)) {
            return;
        }

        ClientChatPacket chatPacket = new ClientChatPacket(message);
        session.sendDownstreamPacket(chatPacket);
    }
//  [java]
	final protected CommandExecutionResult executeArg(TimingDiagram diagram, LineLocation location, RegexResult arg) {
		final String compact = arg.get("COMPACT", 0);
		final String code = arg.get("CODE", 0);
		String full = arg.get("FULL", 0);
		if (full == null)
			full = code;

		Stereotype stereotype = null;
		if (arg.get("STEREOTYPE", 0) != null)
			stereotype = Stereotype.build(arg.get("STEREOTYPE", 0));
		else if (arg.get("STEREOTYPE2", 0) != null)
			stereotype = Stereotype.build(arg.get("STEREOTYPE2", 0));

		final TimingStyle type = TimingStyle.valueOf(arg.get("TYPE", 0).toUpperCase());
		return diagram.createRobustConcise(code, full, type, compact != null, stereotype);
	}
//  [java]
	final protected CommandExecutionResult executeArg(TimingDiagram diagram, LineLocation location, RegexResult arg) {
		final String compact = arg.get("COMPACT", 0);
		final String code = arg.get("CODE", 0);
		String full = arg.get("FULL", 0);
		if (full == null) {
			full = code;
		}
		final TimingStyle type = TimingStyle.valueOf(arg.get("TYPE", 0).toUpperCase());
		return diagram.createRobustConcise(code, full, type, compact != null);
	}
//  [java]
    public void translate(GeyserSession session, ServerPlayerAbilitiesPacket packet) {
        session.setCanFly(packet.isCanFly());
        session.setFlying(packet.isFlying());
        session.sendAdventureSettings();
    }
//  [java]
    public void translate(ServerPlayerAbilitiesPacket packet, GeyserSession session) {
        session.setCanFly(packet.isCanFly());
        session.setFlying(packet.isFlying());
        session.sendAdventureSettings();
    }
//  [java]
    private List<Gadget> prepareGadgets(List<BaseObject> objects, Syntax sourceSyntax,
        MacroTransformationContext context) throws Exception
    {
        List<Gadget> gadgets = new ArrayList<>();

        // prepare velocity tools to render title
        VelocityContext velocityContext = velocityManager.getVelocityContext();
        // Use the Transformation id as the name passed to the Velocity Engine. This name is used internally
        // by Velocity as a cache index key for caching macros.
        String key = context.getTransformationContext().getId();
        if (key == null) {
            key = "unknown namespace";
        }
        VelocityEngine velocityEngine = velocityManager.getVelocityEngine();

        for (BaseObject xObject : objects) {
            if (xObject != null) {
                this.progress.startStep(this, "dashboard.progress.prepareGadget", "Prepare gadget [{}:{}]",
                    xObject.getDocumentReference(), xObject.getNumber());

                // get the data about the gadget from the object
                // TODO: filter for dashboard name when that field will be in
                String title = xObject.getStringValue("title");
                String content = xObject.getLargeStringValue("content");
                String position = xObject.getStringValue("position");
                String id = xObject.getNumber() + "";

                String gadgetTitle;

                XWikiDocument ownerDocument = xObject.getOwnerDocument();
                if (this.authorizationManager.hasAccess(Right.SCRIPT, ownerDocument.getAuthorReference(), ownerDocument.getDocumentReference())) {
                    gadgetTitle =
                        this.evaluateVelocityTitle(velocityContext, velocityEngine, key, title, ownerDocument);
                } else {
                    gadgetTitle = title;
                }

                // parse both the title and content in the syntax of the transformation context
                List<Block> titleBlocks =
                    renderGadgetProperty(gadgetTitle, sourceSyntax, xObject.getDocumentReference(),
                        ownerDocument, context);
                List<Block> contentBlocks =
                    renderGadgetProperty(content, sourceSyntax, xObject.getDocumentReference(),
                        ownerDocument, context);

                // create a gadget will all these and add the gadget to the container of gadgets
                Gadget gadget = new Gadget(id, titleBlocks, contentBlocks, position);
                gadget.setTitleSource(title);
                gadgets.add(gadget);
            } else {
                this.progress.startStep(this, "dashboard.progress.skipNullGadget", "Null gadget object");
            }

            this.progress.endStep(this);
        }

        return gadgets;
    }
//  [java]
    private List<Gadget> prepareGadgets(List<BaseObject> objects, Syntax sourceSyntax,
        MacroTransformationContext context) throws Exception
    {
        List<Gadget> gadgets = new ArrayList<>();

        // prepare velocity tools to render title
        VelocityContext velocityContext = velocityManager.getVelocityContext();
        // Use the Transformation id as the name passed to the Velocity Engine. This name is used internally
        // by Velocity as a cache index key for caching macros.
        String key = context.getTransformationContext().getId();
        if (key == null) {
            key = "unknown namespace";
        }
        VelocityEngine velocityEngine = velocityManager.getVelocityEngine();

        for (BaseObject xObject : objects) {
            if (xObject != null) {
                this.progress.startStep(this, "dashboard.progress.prepareGadget", "Prepare gadget [{}:{}]",
                    xObject.getDocumentReference(), xObject.getNumber());

                // get the data about the gadget from the object
                // TODO: filter for dashboard name when that field will be in
                String title = xObject.getStringValue("title");
                String content = xObject.getLargeStringValue("content");
                String position = xObject.getStringValue("position");
                String id = xObject.getNumber() + "";

                // render title with velocity
                StringWriter writer = new StringWriter();
                // FIXME: the engine has an issue with $ and # as last character. To test and fix if it happens
                velocityEngine.evaluate(velocityContext, writer, key, title);
                String gadgetTitle = writer.toString();

                // parse both the title and content in the syntax of the transformation context
                List<Block> titleBlocks =
                    renderGadgetProperty(gadgetTitle, sourceSyntax, xObject.getDocumentReference(),
                        xObject.getOwnerDocument(), context);
                List<Block> contentBlocks =
                    renderGadgetProperty(content, sourceSyntax, xObject.getDocumentReference(),
                        xObject.getOwnerDocument(), context);

                // create a gadget will all these and add the gadget to the container of gadgets
                Gadget gadget = new Gadget(id, titleBlocks, contentBlocks, position);
                gadget.setTitleSource(title);
                gadgets.add(gadget);
            } else {
                this.progress.startStep(this, "dashboard.progress.skipNullGadget", "Null gadget object");
            }

            this.progress.endStep(this);
        }

        return gadgets;
    }
//  [java]
    public String getStringParameterSQL(String param) {
        // DASHBUILDE-113: SQL Injection on data set lookup filters
        String escapedParam = param.replaceAll("'", "''");
        return "'" + escapedParam + "'";
    }
//  [java]
    public String getStringParameterSQL(String param) {
        return "'" + param + "'";
    }
//  [java]
    public static void fillArticleInfo(Log data, HttpServletRequest request, String suffix) {
        data.put("alias", data.get("alias") + suffix);
        data.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + data.get("alias"));
        data.put("noSchemeUrl", WebTools.getHomeUrlWithHost(request) + Constants.getArticleUri() + data.get("alias"));
        data.put("typeUrl", WebTools.getHomeUrl(request) + Constants.getArticleUri() + "sort/" + data.get("typeAlias") + suffix);
        Log lastLog = data.get("lastLog");
        Log nextLog = data.get("nextLog");
        nextLog.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + nextLog.get("alias") + suffix);
        lastLog.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + lastLog.get("alias") + suffix);
        //没有使用md的toc目录的文章才尝试使用系统提取的目录
        if (data.getStr("markdown") != null && !data.getStr("markdown").toLowerCase().contains("[toc]")
                && !data.getStr("markdown").toLowerCase().contains("[tocm]")) {
            //最基础的实现方式，若需要更强大的实现方式建议使用JavaScript完成（页面输入toc对象）
            OutlineVO outlineVO = OutlineUtil.extractOutline(data.getStr("content"));
            if (outlineVO.size() > 0) {
                data.put("tocHtml", OutlineUtil.buildTocHtml(outlineVO, ""));
            }
            data.put("toc", outlineVO);
        }
        if (!new CommentService().isAllowComment()) {
            data.set("canComment", false);
        }
    }