jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
	public FromSkinparamToStyle(String key) {

		if (key.contains("<<")) {
			final StringTokenizer st = new StringTokenizer(key, "<>");
			this.key = st.nextToken();
			this.stereo = st.hasMoreTokens() ? st.nextToken() : null;
		} else {
			this.key = key;
			this.stereo = null;
		}

	}
//  [java]
    public void translate(GeyserSession session, LecternUpdatePacket packet) {
        if (packet.isDroppingBook()) {
            // Bedrock drops the book outside of the GUI. Java drops it in the GUI
            // So, we enter the GUI and then drop it! :)
            session.setDroppingLecternBook(true);

            // Emulate an interact packet
            ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket(
                    new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),
                    BlockFace.DOWN,
                    Hand.MAIN_HAND,
                    0, 0, 0, // Java doesn't care about these when dealing with a lectern
                    false);
            session.sendDownstreamPacket(blockPacket);
        } else {
            // Bedrock wants to either move a page or exit
            if (!(session.getOpenInventory() instanceof LecternContainer)) {
                session.getConnector().getLogger().debug("Expected lectern but it wasn't open!");
                return;
            }

            LecternContainer lecternContainer = (LecternContainer) session.getOpenInventory();
            if (lecternContainer.getCurrentBedrockPage() == packet.getPage()) {
                // The same page means Bedrock is closing the window
                ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(lecternContainer.getId());
                session.sendDownstreamPacket(closeWindowPacket);
                InventoryUtils.closeInventory(session, lecternContainer.getId(), false);
            } else {
                // Each "page" Bedrock gives to us actually represents two pages (think opening a book and seeing two pages)
                // Each "page" on Java is just one page (think a spiral notebook folded back to only show one page)
                int newJavaPage = (packet.getPage() * 2);
                int currentJavaPage = (lecternContainer.getCurrentBedrockPage() * 2);

                // Send as many click button packets as we need to
                // Java has the option to specify exact page numbers by adding 100 to the number, but buttonId variable
                // is a byte when transmitted over the network and therefore this stops us at 128
                if (newJavaPage > currentJavaPage) {
                    for (int i = currentJavaPage; i < newJavaPage; i++) {
                        ClientClickWindowButtonPacket clickButtonPacket = new ClientClickWindowButtonPacket(session.getOpenInventory().getId(), 2);
                        session.sendDownstreamPacket(clickButtonPacket);
                    }
                } else {
                    for (int i = currentJavaPage; i > newJavaPage; i--) {
                        ClientClickWindowButtonPacket clickButtonPacket = new ClientClickWindowButtonPacket(session.getOpenInventory().getId(), 1);
                        session.sendDownstreamPacket(clickButtonPacket);
                    }
                }
            }
        }
    }
//  [java]
    public void translate(LecternUpdatePacket packet, GeyserSession session) {
        if (packet.isDroppingBook()) {
            // Bedrock drops the book outside of the GUI. Java drops it in the GUI
            // So, we enter the GUI and then drop it! :)
            session.setDroppingLecternBook(true);

            // Emulate an interact packet
            ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket(
                    new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),
                    BlockFace.DOWN,
                    Hand.MAIN_HAND,
                    0, 0, 0, // Java doesn't care about these when dealing with a lectern
                    false);
            session.sendDownstreamPacket(blockPacket);
        } else {
            // Bedrock wants to either move a page or exit
            if (!(session.getOpenInventory() instanceof LecternContainer)) {
                session.getConnector().getLogger().debug("Expected lectern but it wasn't open!");
                return;
            }

            LecternContainer lecternContainer = (LecternContainer) session.getOpenInventory();
            if (lecternContainer.getCurrentBedrockPage() == packet.getPage()) {
                // The same page means Bedrock is closing the window
                ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(lecternContainer.getId());
                session.sendDownstreamPacket(closeWindowPacket);
                InventoryUtils.closeInventory(session, lecternContainer.getId(), false);
            } else {
                // Each "page" Bedrock gives to us actually represents two pages (think opening a book and seeing two pages)
                // Each "page" on Java is just one page (think a spiral notebook folded back to only show one page)
                int newJavaPage = (packet.getPage() * 2);
                int currentJavaPage = (lecternContainer.getCurrentBedrockPage() * 2);

                // Send as many click button packets as we need to
                // Java has the option to specify exact page numbers by adding 100 to the number, but buttonId variable
                // is a byte when transmitted over the network and therefore this stops us at 128
                if (newJavaPage > currentJavaPage) {
                    for (int i = currentJavaPage; i < newJavaPage; i++) {
                        ClientClickWindowButtonPacket clickButtonPacket = new ClientClickWindowButtonPacket(session.getOpenInventory().getId(), 2);
                        session.sendDownstreamPacket(clickButtonPacket);
                    }
                } else {
                    for (int i = currentJavaPage; i > newJavaPage; i--) {
                        ClientClickWindowButtonPacket clickButtonPacket = new ClientClickWindowButtonPacket(session.getOpenInventory().getId(), 1);
                        session.sendDownstreamPacket(clickButtonPacket);
                    }
                }
            }
        }
    }
//  [java]
	public CommandExecutionResult createRobustConcise(String code, String full, TimingStyle type, boolean compact,
			Stereotype stereotype) {
		final Player player = new PlayerRobustConcise(type, full, getSkinParam(), ruler, compactByDefault || compact,
				stereotype);
		players.put(code, player);
		lastPlayer = player;
		return CommandExecutionResult.ok();
	}
//  [java]
	public CommandExecutionResult createRobustConcise(String code, String full, TimingStyle type, boolean compact) {
		final Player player = new PlayerRobustConcise(type, full, getSkinParam(), ruler, compactByDefault || compact);
		players.put(code, player);
		lastPlayer = player;
		return CommandExecutionResult.ok();
	}
//  [java]
	private static void addMagic(SName sname) {
		final String cleanName = sname.name().replace("_", "");
		addConvert(cleanName + "BackgroundColor", PName.BackGroundColor, sname);
		addConvert(cleanName + "BorderColor", PName.LineColor, sname);
		addConvert(cleanName + "BorderThickness", PName.LineThickness, sname);
		addConvert(cleanName + "RoundCorner", PName.RoundCorner, sname);
		addConvert(cleanName + "DiagonalCorner", PName.DiagonalCorner, sname);
		addConvert(cleanName + "BorderStyle", PName.LineStyle, sname);
		addConFont(cleanName, sname);
		addConvert(cleanName + "Shadowing", PName.Shadowing, sname);
		
		addConvert(cleanName + "StereotypeFontSize", PName.FontSize, SName.stereotype, sname);
		addConvert(cleanName + "StereotypeFontStyle", PName.FontStyle, SName.stereotype, sname);
		addConvert(cleanName + "StereotypeFontColor", PName.FontColor, SName.stereotype, sname);
		addConvert(cleanName + "StereotypeFontName", PName.FontName, SName.stereotype, sname);

	}
//  [java]
	private static void addMagic(SName sname) {
		final String cleanName = sname.name().replace("_", "");
		addConvert(cleanName + "BackgroundColor", PName.BackGroundColor, sname);
		addConvert(cleanName + "BorderColor", PName.LineColor, sname);
		addConvert(cleanName + "BorderThickness", PName.LineThickness, sname);
		addConvert(cleanName + "RoundCorner", PName.RoundCorner, sname);
		addConvert(cleanName + "DiagonalCorner", PName.DiagonalCorner, sname);
		addConvert(cleanName + "BorderStyle", PName.LineStyle, sname);
		addConvert(cleanName + "StereotypeFontColor", PName.FontColor, SName.stereotype, sname);
		addConFont(cleanName, sname);
	}
//  [java]
    CreateCommentResponse saveComment() {
        CreateCommentRequest createCommentRequest = ZrLogUtil.convertRequestParam(getRequest().getParameterMap(), CreateCommentRequest.class);
        createCommentRequest.setIp(WebTools.getRealIp(getRequest()));
        createCommentRequest.setUserAgent(Jsoup.clean(getHeader("User-Agent"), Whitelist.basic()));
        return commentService.save(createCommentRequest);
    }
//  [java]
    CreateCommentResponse saveComment() {
        CreateCommentRequest createCommentRequest = ZrLogUtil.convertRequestParam(getRequest().getParameterMap(), CreateCommentRequest.class);
        createCommentRequest.setIp(WebTools.getRealIp(getRequest()));
        createCommentRequest.setUserAgent(getHeader("User-Agent"));
        return commentService.save(createCommentRequest);
    }
//  [java]
	public boolean checkUrlParameter(String url)
	{
		if (url != null)
		{
			try
			{
				URL parsedUrl = new URL(url);
				String protocol = parsedUrl.getProtocol();
				String host = parsedUrl.getHost();
				InetAddress address = InetAddress.getByName(host);
				String hostAddress = address.getHostAddress();
				host = host.toLowerCase();

				return (protocol.equals("http") || protocol.equals("https"))
						&& !address.isAnyLocalAddress()
						&& !address.isLoopbackAddress()
						&& !host.endsWith(".internal") // Redundant
						&& !host.endsWith(".local") // Redundant
						&& !host.contains("localhost") // Redundant
						&& !hostAddress.startsWith("0.") // 0.0.0.0/8 
						&& !hostAddress.startsWith("10.") // 10.0.0.0/8
						&& !hostAddress.startsWith("127.") // 127.0.0.0/8
						&& !hostAddress.startsWith("169.254.") // 169.254.0.0/16
						&& !hostAddress.startsWith("172.16.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.17.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.18.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.19.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.20.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.21.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.22.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.23.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.24.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.25.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.26.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.27.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.28.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.29.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.30.") // 172.16.0.0/12
						&& !hostAddress.startsWith("172.31.") // 172.16.0.0/12
						&& !hostAddress.startsWith("192.0.0.") // 192.0.0.0/24
						&& !hostAddress.startsWith("192.168.") // 192.168.0.0/16
						&& !hostAddress.startsWith("198.18.") // 198.18.0.0/15
						&& !hostAddress.startsWith("198.19.") // 198.18.0.0/15
						&& !host.endsWith(".arpa"); // reverse domain (needed?)
			}
			catch (MalformedURLException e)
			{
				return false;
			}
			catch (UnknownHostException e)
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
//  [java]
	public boolean checkUrlParameter(String url)
	{
		if (url != null)
		{
			try
			{
				URL parsedUrl = new URL(url);
				String protocol = parsedUrl.getProtocol();
				String host = parsedUrl.getHost().toLowerCase();

				return (protocol.equals("http") || protocol.equals("https"))
						&& !host.endsWith(".internal")
						&& !host.endsWith(".local")
						&& !host.contains("localhost")
						&& !host.startsWith("0.") // 0.0.0.0/8
						&& !host.startsWith("10.") // 10.0.0.0/8
						&& !host.startsWith("127.") // 127.0.0.0/8
						&& !host.startsWith("169.254.") // 169.254.0.0/16
						&& !host.startsWith("172.16.") // 172.16.0.0/12
						&& !host.startsWith("172.17.") // 172.16.0.0/12
						&& !host.startsWith("172.18.") // 172.16.0.0/12
						&& !host.startsWith("172.19.") // 172.16.0.0/12
						&& !host.startsWith("172.20.") // 172.16.0.0/12
						&& !host.startsWith("172.21.") // 172.16.0.0/12
						&& !host.startsWith("172.22.") // 172.16.0.0/12
						&& !host.startsWith("172.23.") // 172.16.0.0/12
						&& !host.startsWith("172.24.") // 172.16.0.0/12
						&& !host.startsWith("172.25.") // 172.16.0.0/12
						&& !host.startsWith("172.26.") // 172.16.0.0/12
						&& !host.startsWith("172.27.") // 172.16.0.0/12
						&& !host.startsWith("172.28.") // 172.16.0.0/12
						&& !host.startsWith("172.29.") // 172.16.0.0/12
						&& !host.startsWith("172.30.") // 172.16.0.0/12
						&& !host.startsWith("172.31.") // 172.16.0.0/12
						&& !host.startsWith("192.0.0.") // 192.0.0.0/24
						&& !host.startsWith("192.168.") // 192.168.0.0/16
						&& !host.startsWith("198.18.") // 198.18.0.0/15
						&& !host.startsWith("198.19.") // 198.18.0.0/15
						&& !host.endsWith(".arpa"); // reverse domain (needed?)
			}
			catch (MalformedURLException e)
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
//  [java]
    public void translate(GeyserSession session, RiderJumpPacket packet) {
        Entity vehicle = session.getRidingVehicleEntity();
        if (vehicle instanceof AbstractHorseEntity) {
            ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(),  PlayerState.START_HORSE_JUMP, packet.getJumpStrength());
            session.sendDownstreamPacket(playerStatePacket);
        }
    }
//  [java]
    public void translate(RiderJumpPacket packet, GeyserSession session) {
        Entity vehicle = session.getRidingVehicleEntity();
        if (vehicle instanceof AbstractHorseEntity) {
            ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(),  PlayerState.START_HORSE_JUMP, packet.getJumpStrength());
            session.sendDownstreamPacket(playerStatePacket);
        }
    }
//  [java]
    protected void afterFeaturesReceived() throws NotConnectedException {
        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) {
                send(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();
        }
    }
//  [java]
    protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException {
        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) {
                send(new StartTls());
            }
        }
        // If TLS is required but the server doesn't offer it, disconnect
        // from the server and throw an error. First check if we've already negotiated TLS
        // and are secure, however (features get parsed a second time after TLS is established).
        if (!isSecureConnection() && startTlsFeature == null
                        && getConfiguration().getSecurityMode() == SecurityMode.required) {
            throw new SecurityRequiredByClientException();
        }

        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();
        }
    }
//  [java]
	public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
			byte[] ciphertext, int ciphertextOffset, int length)
			throws ShortBufferException {
		int space;
		if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length)
			throw new IllegalArgumentException();
		if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length)
			throw new IllegalArgumentException();
		space = ciphertext.length - ciphertextOffset;
		if (keySpec == null) {
			// The key is not set yet - return the plaintext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
			return length;
		}
		if (space < 16 || length > (space - 16))
			throw new ShortBufferException();
		try {
			setup(ad);
			int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);
			cipher.doFinal(ciphertext, ciphertextOffset + result);
		} catch (InvalidKeyException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (InvalidAlgorithmParameterException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (IllegalBlockSizeException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (BadPaddingException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		}
		ghash.update(ciphertext, ciphertextOffset, length);
		ghash.pad(ad != null ? ad.length : 0, length);
		ghash.finish(ciphertext, ciphertextOffset + length, 16);
		for (int index = 0; index < 16; ++index)
			ciphertext[ciphertextOffset + length + index] ^= hashKey[index];
		return length + 16;
	}
//  [java]
	public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
			byte[] ciphertext, int ciphertextOffset, int length)
			throws ShortBufferException {
		int space;
		if (ciphertextOffset > ciphertext.length)
			space = 0;
		else
			space = ciphertext.length - ciphertextOffset;
		if (keySpec == null) {
			// The key is not set yet - return the plaintext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
			return length;
		}
		if (space < 16 || length > (space - 16))
			throw new ShortBufferException();
		try {
			setup(ad);
			int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);
			cipher.doFinal(ciphertext, ciphertextOffset + result);
		} catch (InvalidKeyException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (InvalidAlgorithmParameterException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (IllegalBlockSizeException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (BadPaddingException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		}
		ghash.update(ciphertext, ciphertextOffset, length);
		ghash.pad(ad != null ? ad.length : 0, length);
		ghash.finish(ciphertext, ciphertextOffset + length, 16);
		for (int index = 0; index < 16; ++index)
			ciphertext[ciphertextOffset + length + index] ^= hashKey[index];
		return length + 16;
	}
//  [java]
    void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception {
        P4MaterialConfig materialConfig = p4("", "");
        materialConfig.setPassword("notSecret");
        Map<String, String> map = new HashMap<>();
        map.put(P4MaterialConfig.PASSWORD, "secret");
        map.put(P4MaterialConfig.PASSWORD_CHANGED, "1");

        materialConfig.setConfigAttributes(map);
        assertThat(ReflectionUtil.getField(materialConfig, "password")).isNull();
        assertThat(materialConfig.getPassword()).isEqualTo("secret");
        assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret"));

        //Dont change
        map.put(P4MaterialConfig.PASSWORD, "Hehehe");
        map.put(P4MaterialConfig.PASSWORD_CHANGED, "0");
        materialConfig.setConfigAttributes(map);

        assertThat(ReflectionUtil.getField(materialConfig, "password")).isNull();
        assertThat(materialConfig.getPassword()).isEqualTo("secret");
        assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret"));

        //Dont change
        map.put(P4MaterialConfig.PASSWORD, "");
        map.put(P4MaterialConfig.PASSWORD_CHANGED, "1");
        materialConfig.setConfigAttributes(map);

        assertThat(materialConfig.getPassword()).isNull();
        assertThat(materialConfig.getEncryptedPassword()).isNull();
    }
//  [java]
    void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception {
        P4MaterialConfig materialConfig = p4("", "");
        materialConfig.setPassword("notSecret");
        Map<String, String> map = new HashMap<>();
        map.put(P4MaterialConfig.PASSWORD, "secret");
        map.put(P4MaterialConfig.PASSWORD_CHANGED, "1");

        materialConfig.setConfigAttributes(map);
        assertThat(ReflectionUtil.getField(materialConfig, "password")).isNull();
        assertThat(materialConfig.getPassword()).isEqualTo("secret");
        assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret"));

        //Dont change
        map.put(SvnMaterialConfig.PASSWORD, "Hehehe");
        map.put(SvnMaterialConfig.PASSWORD_CHANGED, "0");
        materialConfig.setConfigAttributes(map);

        assertThat(ReflectionUtil.getField(materialConfig, "password")).isNull();
        assertThat(materialConfig.getPassword()).isEqualTo("secret");
        assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret"));

        //Dont change
        map.put(SvnMaterialConfig.PASSWORD, "");
        map.put(SvnMaterialConfig.PASSWORD_CHANGED, "1");
        materialConfig.setConfigAttributes(map);

        assertThat(materialConfig.getPassword()).isNull();
        assertThat(materialConfig.getEncryptedPassword()).isNull();
    }
//  [java]
    public void translate(GeyserSession session, LoginDisconnectPacket packet) {
        // The client doesn't manually get disconnected so we have to do it ourselves
        session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale()));
    }
//  [java]
    public void translate(LoginDisconnectPacket packet, GeyserSession session) {
        // The client doesn't manually get disconnected so we have to do it ourselves
        session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale()));
    }
//  [java]
    public void translate(GeyserSession session, ServerOpenHorseWindowPacket packet) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (entity == null) {
            return;
        }

        UpdateEquipPacket updateEquipPacket = new UpdateEquipPacket();
        updateEquipPacket.setWindowId((short) packet.getWindowId());
        updateEquipPacket.setWindowType((short) ContainerType.HORSE.getId());
        updateEquipPacket.setUniqueEntityId(entity.getGeyserId());

        NbtMapBuilder builder = NbtMap.builder();
        List<NbtMap> slots = new ArrayList<>();

        InventoryTranslator inventoryTranslator;
        if (entity instanceof LlamaEntity) {
            inventoryTranslator = new LlamaInventoryTranslator(packet.getNumberOfSlots());
            slots.add(CARPET_SLOT);
        } else if (entity instanceof ChestedHorseEntity) {
            inventoryTranslator = new DonkeyInventoryTranslator(packet.getNumberOfSlots());
            slots.add(SADDLE_SLOT);
        } else {
            inventoryTranslator = new HorseInventoryTranslator(packet.getNumberOfSlots());
            slots.add(SADDLE_SLOT);
            slots.add(ARMOR_SLOT);
        }

        // Build the NbtMap that sets the icons for Bedrock (e.g. sets the saddle outline on the saddle slot)
        builder.putList("slots", NbtType.COMPOUND, slots);

        updateEquipPacket.setTag(builder.build());
        session.sendUpstreamPacket(updateEquipPacket);

        session.setInventoryTranslator(inventoryTranslator);
        InventoryUtils.openInventory(session, new Container(entity.getMetadata().getString(EntityData.NAMETAG), packet.getWindowId(), packet.getNumberOfSlots(), null, session.getPlayerInventory()));
    }
//  [java]
    public void translate(ServerOpenHorseWindowPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (entity == null) {
            return;
        }

        UpdateEquipPacket updateEquipPacket = new UpdateEquipPacket();
        updateEquipPacket.setWindowId((short) packet.getWindowId());
        updateEquipPacket.setWindowType((short) ContainerType.HORSE.getId());
        updateEquipPacket.setUniqueEntityId(entity.getGeyserId());

        NbtMapBuilder builder = NbtMap.builder();
        List<NbtMap> slots = new ArrayList<>();

        InventoryTranslator inventoryTranslator;
        if (entity instanceof LlamaEntity) {
            inventoryTranslator = new LlamaInventoryTranslator(packet.getNumberOfSlots());
            slots.add(CARPET_SLOT);
        } else if (entity instanceof ChestedHorseEntity) {
            inventoryTranslator = new DonkeyInventoryTranslator(packet.getNumberOfSlots());
            slots.add(SADDLE_SLOT);
        } else {
            inventoryTranslator = new HorseInventoryTranslator(packet.getNumberOfSlots());
            slots.add(SADDLE_SLOT);
            slots.add(ARMOR_SLOT);
        }

        // Build the NbtMap that sets the icons for Bedrock (e.g. sets the saddle outline on the saddle slot)
        builder.putList("slots", NbtType.COMPOUND, slots);

        updateEquipPacket.setTag(builder.build());
        session.sendUpstreamPacket(updateEquipPacket);

        session.setInventoryTranslator(inventoryTranslator);
        InventoryUtils.openInventory(session, new Container(entity.getMetadata().getString(EntityData.NAMETAG), packet.getWindowId(), packet.getNumberOfSlots(), null, session.getPlayerInventory()));
    }
//  [java]
	private void initializeVelocity() {
		if (velocityEngine == null) {
			velocityEngine = new VelocityEngine();
			
			Properties props = new Properties();
			props.setProperty(RuntimeConstants.RUNTIME_LOG, "startup_wizard_vel.log");
			// Linux requires setting logging properties to initialize Velocity Context.
			props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
			    "org.apache.velocity.runtime.log.CommonsLogLogChute");
			props.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME, "initial_wizard_velocity");
			
			// so the vm pages can import the header/footer
			props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
			props.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
			props.setProperty("class.resource.loader.class",
			    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
			
			try {
				velocityEngine.init(props);
			}
			catch (Exception e) {
				log.error("velocity init failed, because: {}", e, e);
			}
		}
	}
//  [java]
	private void initializeVelocity() {
		if (velocityEngine == null) {
			velocityEngine = new VelocityEngine();
			
			Properties props = new Properties();
			props.setProperty(RuntimeConstants.RUNTIME_LOG, "startup_wizard_vel.log");
			// Linux requires setting logging properties to initialize Velocity Context.
			props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
			    "org.apache.velocity.runtime.log.CommonsLogLogChute");
			props.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME, "initial_wizard_velocity");
			
			// so the vm pages can import the header/footer
			props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
			props.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
			props.setProperty("class.resource.loader.class",
			    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
			
			try {
				velocityEngine.init(props);
			}
			catch (Exception e) {
				log.error("velocity init failed, because: " + e);
			}
		}
	}
//  [java]
    static DataSource lookupDataSource(Hints hints) throws FactoryException {
        Object hint = hints.get(Hints.EPSG_DATA_SOURCE);
        if (hint instanceof DataSource) {
            return (DataSource) hint;
        } else if (hint instanceof String) {
            String name = (String) hint;
            try {
                return (DataSource) GeoTools.jndiLookup(name);
            } catch (Exception e) {
                throw new FactoryException("EPSG_DATA_SOURCE '" + name + "' not found:" + e, e);
            }
        }
        throw new FactoryException("EPSG_DATA_SOURCE must be provided");
    }
//  [java]
    static DataSource lookupDataSource(Hints hints) throws FactoryException {
        Object hint = hints.get(Hints.EPSG_DATA_SOURCE);
        if (hint instanceof DataSource) {
            return (DataSource) hint;
        } else if (hint instanceof String) {
            String name = (String) hint;
            InitialContext context;
            try {
                context = GeoTools.getInitialContext();
                // name = GeoTools.fixName( context, name );
                return (DataSource) context.lookup(name);
            } catch (Exception e) {
                throw new FactoryException("EPSG_DATA_SOURCE '" + name + "' not found:" + e, e);
            }
        }
        throw new FactoryException("EPSG_DATA_SOURCE must be provided");
    }
//  [java]
	public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	        throws IOException, ServletException {
		if (skipFilter((HttpServletRequest) request)) {
			chain.doFilter(request, response);
		} else {
			
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			
			String servletPath = httpRequest.getServletPath();
			// for all /images and /initfilter/scripts files, write the path
			// (the "/initfilter" part is needed so that the openmrs_static_context-servlet.xml file doesn't
			//  get instantiated early, before the locale messages are all set up)
			if (servletPath.startsWith("/images") || servletPath.startsWith("/initfilter/scripts")) {
				// strip out the /initfilter part
				servletPath = servletPath.replaceFirst("/initfilter", "/WEB-INF/view");
				// writes the actual image file path to the response
				Path filePath = Paths.get(filterConfig.getServletContext().getRealPath(servletPath)).normalize();
				Path fullFilePath = filePath;
				if (httpRequest.getPathInfo() != null) {
					fullFilePath = fullFilePath.resolve(httpRequest.getPathInfo());
					if (!(fullFilePath.normalize().startsWith(filePath))) {
						log.warn("Detected attempted directory traversal in request for {}", httpRequest.getPathInfo());
						return;
					}
				}
				
				try (InputStream imageFileInputStream = new FileInputStream(fullFilePath.normalize().toFile())) {
					OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());
				}
				catch (FileNotFoundException e) {
					log.error("Unable to find file: {}", filePath, e);
				}
				catch (IOException e) {
					log.warn("An error occurred while handling file {}", filePath, e);
				}
			} else if (servletPath.startsWith("/scripts")) {
				log.error(
				    "Calling /scripts during the initializationfilter pages will cause the openmrs_static_context-servlet.xml to initialize too early and cause errors after startup.  Use '/initfilter"
				            + servletPath + "' instead.");
			}
			// for anything but /initialsetup
			else if (!httpRequest.getServletPath().equals("/" + WebConstants.SETUP_PAGE_URL)
			        && !httpRequest.getServletPath().equals("/" + AUTO_RUN_OPENMRS)) {
				// send the user to the setup page
				httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL);
			} else {
				
				if ("GET".equals(httpRequest.getMethod())) {
					doGet(httpRequest, httpResponse);
				} else if ("POST".equals(httpRequest.getMethod())) {
					// only clear errors before POSTS so that redirects can show errors too.
					errors.clear();
					msgs.clear();
					doPost(httpRequest, httpResponse);
				}
			}
			// Don't continue down the filter chain otherwise Spring complains
			// that it hasn't been set up yet.
			// The jsp and servlet filter are also on this chain, so writing to
			// the response directly here is the only option
		}
	}
//  [java]
	public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	        throws IOException, ServletException {
		if (skipFilter((HttpServletRequest) request)) {
			chain.doFilter(request, response);
		} else {
			
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			
			String servletPath = httpRequest.getServletPath();
			// for all /images and /initfilter/scripts files, write the path
			// (the "/initfilter" part is needed so that the openmrs_static_context-servlet.xml file doesn't
			//  get instantiated early, before the locale messages are all set up)
			if (servletPath.startsWith("/images") || servletPath.startsWith("/initfilter/scripts")) {
				servletPath = servletPath.replaceFirst("/initfilter", "/WEB-INF/view"); // strip out the /initfilter part
				// writes the actual image file path to the response
				File file = new File(filterConfig.getServletContext().getRealPath(servletPath));
				if (httpRequest.getPathInfo() != null) {
					file = new File(file, httpRequest.getPathInfo());
				}
				
				InputStream imageFileInputStream = null;
				try {
					imageFileInputStream = new FileInputStream(file);
					OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());
				}
				catch (FileNotFoundException e) {
					log.error("Unable to find file: " + file.getAbsolutePath());
				}
				finally {
					if (imageFileInputStream != null) {
						try {
							imageFileInputStream.close();
						}
						catch (IOException io) {
							log.warn("Couldn't close imageFileInputStream: " + io);
						}
					}
				}
			} else if (servletPath.startsWith("/scripts")) {
				log.error(
				    "Calling /scripts during the initializationfilter pages will cause the openmrs_static_context-servlet.xml to initialize too early and cause errors after startup.  Use '/initfilter"
				            + servletPath + "' instead.");
			}
			// for anything but /initialsetup
			else if (!httpRequest.getServletPath().equals("/" + WebConstants.SETUP_PAGE_URL)
			        && !httpRequest.getServletPath().equals("/" + AUTO_RUN_OPENMRS)) {
				// send the user to the setup page
				httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL);
			} else {
				
				if ("GET".equals(httpRequest.getMethod())) {
					doGet(httpRequest, httpResponse);
				} else if ("POST".equals(httpRequest.getMethod())) {
					// only clear errors before POSTS so that redirects can show errors too.
					errors.clear();
					msgs.clear();
					doPost(httpRequest, httpResponse);
				}
			}
			// Don't continue down the filter chain otherwise Spring complains
			// that it hasn't been set up yet.
			// The jsp and servlet filter are also on this chain, so writing to
			// the response directly here is the only option
		}
	}
//  [java]
    public void checkConnection(UrlArgument repositoryURL) {
        CommandLine hg = createCommandLine("hg")
                .withArgs("id", "--id", "--")
                .withArg(repositoryURL)
                .withNonArgSecrets(secrets)
                .withEncoding("UTF-8");
        execute(hg, new NamedProcessTag(repositoryURL.forDisplay()));
    }
//  [java]
    public void checkConnection(UrlArgument repositoryURL) {
        execute(createCommandLine("hg").withArgs("id", "--id").withArg(repositoryURL).withNonArgSecrets(secrets).withEncoding("utf-8"), new NamedProcessTag(repositoryURL.forDisplay()));
    }
//  [java]
    public void testGetShellCommandLineBash_WithSingleQuotedArg()
        throws Exception
    {
        Commandline cmd = new Commandline( new BourneShell() );
        cmd.setExecutable( "/bin/echo" );
        cmd.addArguments( new String[] {
            "\'hello world\'"
        } );

        String[] shellCommandline = cmd.getShellCommandline();

        assertEquals( "Command line size", 3, shellCommandline.length );

        assertEquals( "/bin/sh", shellCommandline[0] );
        assertEquals( "-c", shellCommandline[1] );
        String expectedShellCmd = "'/bin/echo' ''\"'\"'hello world'\"'\"''";
        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            expectedShellCmd = "\\bin\\echo \'hello world\'";
        }
        assertEquals( expectedShellCmd, shellCommandline[2] );
    }
//  [java]
    public void testGetShellCommandLineBash_WithSingleQuotedArg()
        throws Exception
    {
        Commandline cmd = new Commandline( new BourneShell() );
        cmd.setExecutable( "/bin/echo" );
        cmd.addArguments( new String[] {
            "\'hello world\'"
        } );

        String[] shellCommandline = cmd.getShellCommandline();

        assertEquals( "Command line size", 3, shellCommandline.length );

        assertEquals( "/bin/sh", shellCommandline[0] );
        assertEquals( "-c", shellCommandline[1] );
        String expectedShellCmd = "/bin/echo \'hello world\'";
        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            expectedShellCmd = "\\bin\\echo \'hello world\'";
        }
        assertEquals( expectedShellCmd, shellCommandline[2] );
    }
//  [java]
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String encoding = request.getHeader("Accept-Encoding");
        boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
        SessionTerminal st = (SessionTerminal) request.getSession(true).getAttribute("terminal");
        if (st == null || st.isClosed()) {
            st = new SessionTerminal(getCommandProcessor(), getThreadIO());
            request.getSession().setAttribute("terminal", st);
        }
        String str = request.getParameter("k");
        String f = request.getParameter("f");
        String dump = st.handle(str, f != null && f.length() > 0);
        if (dump != null) {
            if (supportsGzip) {
                response.setHeader("Content-Encoding", "gzip");
                response.setHeader("Content-Type", "text/html");
                try {
                    GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
                    gzos.write(dump.getBytes());
                    gzos.close();
                } catch (IOException ie) {
                    LOG.info("Exception writing response: ", ie);
                }
            } else {
                response.getOutputStream().write(dump.getBytes());
            }
        }
    }
//  [java]
    private String templatePath() {
        if (templatePath == null) {
            String file = HgCommand.class.getResource("/hg.template").getFile();
            templatePath = URLDecoder.decode(new File(file).getAbsolutePath(), StandardCharsets.UTF_8);
        }
        return templatePath;
    }
//  [java]
    private String templatePath() {
        if (templatePath == null) {
            String file = HgCommand.class.getResource("/hg.template").getFile();
            try {
                templatePath = URLDecoder.decode(new File(file).getAbsolutePath(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                templatePath = URLDecoder.decode(new File(file).getAbsolutePath());
            }
        }
        return templatePath;
    }
//  [java]
    private List<Modification> findRecentModifications(int count) {
        // Currently impossible to check modifications on a remote repository.
        InMemoryStreamConsumer consumer = inMemoryConsumer();
        bombUnless(pull(consumer), "Failed to run hg pull command: " + consumer.getAllOutput());
        CommandLine hg = hg("log", "--limit", String.valueOf(count), branchArg(), "--style", templatePath());
        return new HgModificationSplitter(execute(hg)).modifications();
    }
//  [java]
    List<Modification> findRecentModifications(int count) {
        // Currently impossible to check modifications on a remote repository.
        InMemoryStreamConsumer consumer = inMemoryConsumer();
        bombUnless(pull(consumer), "Failed to run hg pull command: " + consumer.getAllOutput());
        CommandLine hg = hg("log", "--limit", String.valueOf(count), "-b", branch, "--style", templatePath());
        return new HgModificationSplitter(execute(hg)).modifications();
    }
//  [java]
    private boolean pull(ConsoleOutputStreamConsumer outputStreamConsumer) {
        CommandLine hg = hg("pull", branchArg(), "--config", String.format("paths.default=%s", url));
        return execute(hg, outputStreamConsumer) == 0;
    }
//  [java]
    private boolean pull(ConsoleOutputStreamConsumer outputStreamConsumer) {
        CommandLine hg = hg("pull", "-b", branch, "--config", String.format("paths.default=%s", url));
        return execute(hg, outputStreamConsumer) == 0;
    }
//  [java]
    public List<Modification> modificationsSince(Revision revision) {
        InMemoryStreamConsumer consumer = inMemoryConsumer();
        bombUnless(pull(consumer), "Failed to run hg pull command: " + consumer.getAllOutput());
        CommandLine hg = hg("log", "-r", "tip:" + revision.getRevision(), branchArg(), "--style", templatePath());
        return new HgModificationSplitter(execute(hg)).filterOutRevision(revision);
    }
//  [java]
    public List<Modification> modificationsSince(Revision revision) {
        InMemoryStreamConsumer consumer = inMemoryConsumer();
        bombUnless(pull(consumer), "Failed to run hg pull command: " + consumer.getAllOutput());
        CommandLine hg = hg("log",
                "-r", "tip:" + revision.getRevision(),
                "-b", branch,
                "--style", templatePath());
        return new HgModificationSplitter(execute(hg)).filterOutRevision(revision);
    }
//  [java]
    private void renderState(FacesContext context) throws IOException {
        // Get the view state and write it to the response..
        PartialViewContext pvc = context.getPartialViewContext();
        PartialResponseWriter writer = pvc.getPartialResponseWriter();
        String viewStateId = Util.getViewStateId(context);

        writer.startUpdate(viewStateId);
        String state = context.getApplication().getStateManager().getViewState(context);
        writer.write(state);
        writer.endUpdate();

        ClientWindow window = context.getExternalContext().getClientWindow();
        if (null != window) {
            String clientWindowId = Util.getClientWindowId(context);
            writer.startUpdate(clientWindowId);
            writer.writeText(window.getId(), null);
            writer.endUpdate();
        }
    }
//  [java]
    private void renderState(FacesContext context) throws IOException {
        // Get the view state and write it to the response..
        PartialViewContext pvc = context.getPartialViewContext();
        PartialResponseWriter writer = pvc.getPartialResponseWriter();
        String viewStateId = Util.getViewStateId(context);

        writer.startUpdate(viewStateId);
        String state = context.getApplication().getStateManager().getViewState(context);
        writer.write(state);
        writer.endUpdate();

        ClientWindow window = context.getExternalContext().getClientWindow();
        if (null != window) {
            String clientWindowId = Util.getClientWindowId(context);
            writer.startUpdate(clientWindowId);
            writer.write(window.getId());
            writer.endUpdate();
        }
    }
//  [java]
	public int decryptWithAd(byte[] ad, byte[] ciphertext,
			int ciphertextOffset, byte[] plaintext, int plaintextOffset,
			int length) throws ShortBufferException, BadPaddingException {
		int space;
		if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length)
			throw new IllegalArgumentException();
		else
			space = ciphertext.length - ciphertextOffset;
		if (length > space)
			throw new ShortBufferException();
		if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length)
			throw new IllegalArgumentException();
		space = plaintext.length - plaintextOffset;
		if (keySpec == null) {
			// The key is not set yet - return the ciphertext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
			return length;
		}
		if (length < 16)
			Noise.throwBadTagException();
		int dataLen = length - 16;
		if (dataLen > space)
			throw new ShortBufferException();
		try {
			setup(ad);
		} catch (InvalidKeyException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (InvalidAlgorithmParameterException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		}
		ghash.update(ciphertext, ciphertextOffset, dataLen);
		ghash.pad(ad != null ? ad.length : 0, dataLen);
		ghash.finish(iv, 0, 16);
		int temp = 0;
		for (int index = 0; index < 16; ++index)
			temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
		if ((temp & 0xFF) != 0)
			Noise.throwBadTagException();
		try {
			int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset);
			cipher.doFinal(plaintext, plaintextOffset + result);
		} catch (IllegalBlockSizeException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (BadPaddingException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		}
		return dataLen;
	}