jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    public Optional<InputStream> getResourceAsStream(String path) {
        URL url = classLoader.getResource(prefixPath(path));
        if (url != null) {
            try {
                URI uri = url.toURI();
                if (uri.getScheme().equals("jar")) {
                    synchronized (DefaultClassPathResourceLoader.class) {
                        FileSystem fileSystem = null;
                        try {
                            try {
                                fileSystem = FileSystems.getFileSystem(uri);
                            } catch (FileSystemNotFoundException e) {
                                //no-op
                            }
                            if (fileSystem == null || !fileSystem.isOpen()) {
                                try {
                                    fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap(), classLoader);
                                } catch (FileSystemAlreadyExistsException e) {
                                    fileSystem = FileSystems.getFileSystem(uri);
                                }
                            }
                            Path pathObject = fileSystem.getPath(path);
                            if (Files.isDirectory(pathObject)) {
                                return Optional.empty();
                            }
                            return Optional.of(new ByteArrayInputStream(Files.readAllBytes(pathObject)));
                        } finally {
                            if (fileSystem != null && fileSystem.isOpen()) {
                                try {
                                    fileSystem.close();
                                } catch (IOException e) {
                                    if (LOG.isDebugEnabled()) {
                                        LOG.debug("Error shutting down JAR file system [" + fileSystem + "]: " + e.getMessage(), e);
                                    }
                                }
                            }
                        }
                    }
                } else if (uri.getScheme().equals("file")) {
                    Path pathObject = Paths.get(uri);
                    if (Files.isDirectory(pathObject)) {
                        return Optional.empty();
                    }
                    return Optional.of(Files.newInputStream(pathObject));
                }
            } catch (URISyntaxException | IOException | ProviderNotFoundException e) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Error establishing whether path is a directory: " + e.getMessage(), e);
                }
            }
        }
        // fallback to less sophisticated approach
        if (path.indexOf('.') == -1) {
            return Optional.empty();
        }
        return Optional.ofNullable(classLoader.getResourceAsStream(prefixPath(path)));
    }
//  [java]
    public void translate(GeyserSession session, ServerSpawnPaintingPacket packet) {
        Vector3f position = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());

        PaintingEntity entity = new PaintingEntity(packet.getEntityId(),
                session.getEntityCache().getNextEntityId().incrementAndGet(),
                position, PaintingType.getByPaintingType(packet.getPaintingType()), packet.getDirection().ordinal());

        session.getEntityCache().spawnEntity(entity);
    }
//  [java]
    public void translate(ServerSpawnPaintingPacket packet, GeyserSession session) {
        Vector3f position = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());

        PaintingEntity entity = new PaintingEntity(packet.getEntityId(),
                session.getEntityCache().getNextEntityId().incrementAndGet(),
                position, PaintingType.getByPaintingType(packet.getPaintingType()), packet.getDirection().ordinal());

        session.getEntityCache().spawnEntity(entity);
    }
//  [java]
    public void translate(GeyserSession session, ServerUpdateTimePacket packet) {
        // Bedrock sends a GameRulesChangedPacket if there is no daylight cycle
        // Java just sends a negative long if there is no daylight cycle
        long time = packet.getTime();

        // https://minecraft.gamepedia.com/Day-night_cycle#24-hour_Minecraft_day
        SetTimePacket setTimePacket = new SetTimePacket();
        setTimePacket.setTime((int) Math.abs(time) % 24000);
        session.sendUpstreamPacket(setTimePacket);
        if (!session.isDaylightCycle() && time >= 0) {
            // Client thinks there is no daylight cycle but there is
            session.setDaylightCycle(true);
        } else if (session.isDaylightCycle() && time < 0) {
            // Client thinks there is daylight cycle but there isn't
            session.setDaylightCycle(false);
        }
    }
//  [java]
    public void translate(ServerUpdateTimePacket packet, GeyserSession session) {
        // Bedrock sends a GameRulesChangedPacket if there is no daylight cycle
        // Java just sends a negative long if there is no daylight cycle
        long time = packet.getTime();

        // https://minecraft.gamepedia.com/Day-night_cycle#24-hour_Minecraft_day
        SetTimePacket setTimePacket = new SetTimePacket();
        setTimePacket.setTime((int) Math.abs(time) % 24000);
        session.sendUpstreamPacket(setTimePacket);
        if (!session.isDaylightCycle() && time >= 0) {
            // Client thinks there is no daylight cycle but there is
            session.setDaylightCycle(true);
        } else if (session.isDaylightCycle() && time < 0) {
            // Client thinks there is daylight cycle but there isn't
            session.setDaylightCycle(false);
        }
    }
//  [java]
    public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo)
        throws IOException
    {
        XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
        this.treeDigest = keyParams.getTreeDigest().getAlgorithm();

        XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());

        try
        {
            XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters
                .Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest)))
                .withIndex(xmssMtPrivateKey.getIndex())
                .withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed())
                .withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF())
                .withPublicSeed(xmssMtPrivateKey.getPublicSeed())
                .withRoot(xmssMtPrivateKey.getRoot());

            if (xmssMtPrivateKey.getBdsState() != null)
            {
                keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState(), BDSStateMap.class));
            }

            this.keyParams = keyBuilder.build();
        }
        catch (ClassNotFoundException e)
        {
            throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
        }
    }
//  [java]
    public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo)
        throws IOException
    {
        XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
        this.treeDigest = keyParams.getTreeDigest().getAlgorithm();

        XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());

        try
        {
            XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters
                .Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest)))
                .withIndex(xmssMtPrivateKey.getIndex())
                .withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed())
                .withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF())
                .withPublicSeed(xmssMtPrivateKey.getPublicSeed())
                .withRoot(xmssMtPrivateKey.getRoot());

            if (xmssMtPrivateKey.getBdsState() != null)
            {
                keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState()));
            }

            this.keyParams = keyBuilder.build();
        }
        catch (ClassNotFoundException e)
        {
            throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
        }
    }
//  [java]
	public XssHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);	
		
	}
//  [java]
	public XssHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
	}
//  [java]
    public void translate(GeyserSession session, ServerEntityEquipmentPacket packet) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }

        if (entity == null)
            return;

        if (!(entity instanceof LivingEntity)) {
            session.getConnector().getLogger().debug("Attempted to add armor to a non-living entity type (" +
                    entity.getEntityType().name() + ").");
            return;
        }

        boolean armorUpdated = false;
        boolean mainHandUpdated = false;
        boolean offHandUpdated = false;
        LivingEntity livingEntity = (LivingEntity) entity;
        for (Equipment equipment : packet.getEquipment()) {
            ItemData item = ItemTranslator.translateToBedrock(session, equipment.getItem());
            switch (equipment.getSlot()) {
                case HELMET:
                    livingEntity.setHelmet(item);
                    armorUpdated = true;
                    break;
                case CHESTPLATE:
                    livingEntity.setChestplate(item);
                    armorUpdated = true;
                    break;
                case LEGGINGS:
                    livingEntity.setLeggings(item);
                    armorUpdated = true;
                    break;
                case BOOTS:
                    livingEntity.setBoots(item);
                    armorUpdated = true;
                    break;
                case MAIN_HAND:
                    livingEntity.setHand(item);
                    mainHandUpdated = true;
                    break;
                case OFF_HAND:
                    livingEntity.setOffHand(item);
                    offHandUpdated = true;
                    break;
            }
        }

        if (armorUpdated) {
            livingEntity.updateArmor(session);
        }
        if (mainHandUpdated) {
            livingEntity.updateMainHand(session);
        }
        if (offHandUpdated) {
            livingEntity.updateOffHand(session);
        }
    }
//  [java]
    public void translate(ServerEntityEquipmentPacket packet, GeyserSession session) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }

        if (entity == null)
            return;

        if (!(entity instanceof LivingEntity)) {
            session.getConnector().getLogger().debug("Attempted to add armor to a non-living entity type (" +
                    entity.getEntityType().name() + ").");
            return;
        }

        boolean armorUpdated = false;
        boolean mainHandUpdated = false;
        boolean offHandUpdated = false;
        LivingEntity livingEntity = (LivingEntity) entity;
        for (Equipment equipment : packet.getEquipment()) {
            ItemData item = ItemTranslator.translateToBedrock(session, equipment.getItem());
            switch (equipment.getSlot()) {
                case HELMET:
                    livingEntity.setHelmet(item);
                    armorUpdated = true;
                    break;
                case CHESTPLATE:
                    livingEntity.setChestplate(item);
                    armorUpdated = true;
                    break;
                case LEGGINGS:
                    livingEntity.setLeggings(item);
                    armorUpdated = true;
                    break;
                case BOOTS:
                    livingEntity.setBoots(item);
                    armorUpdated = true;
                    break;
                case MAIN_HAND:
                    livingEntity.setHand(item);
                    mainHandUpdated = true;
                    break;
                case OFF_HAND:
                    livingEntity.setOffHand(item);
                    offHandUpdated = true;
                    break;
            }
        }

        if (armorUpdated) {
            livingEntity.updateArmor(session);
        }
        if (mainHandUpdated) {
            livingEntity.updateMainHand(session);
        }
        if (offHandUpdated) {
            livingEntity.updateOffHand(session);
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerEntityPositionPacket packet) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.moveRelative(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), entity.getRotation(), packet.isOnGround());
    }
//  [java]
    public void translate(ServerEntityPositionPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.moveRelative(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), entity.getRotation(), packet.isOnGround());
    }
//  [java]
	public final HColor getBackColor(ISkinParam skinParam, Style style) {
		if (colors == null || colors.getColor(ColorType.BACK) == null)
			return style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());

		return colors.getColor(ColorType.BACK);
	}
//  [java]
	public final HColor getBackColor(ISkinParam skinParam, Style style) {
		if (colors == null || colors.getColor(ColorType.BACK) == null) {
			if (UseStyle.useBetaStyle() == false)
				return HColorUtils.COL_D7E0F2;

			return style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());
		}
		return colors.getColor(ColorType.BACK);
	}
//  [java]
	private String clean(final String svg) {
		final String svg2 = svg.toLowerCase().replaceAll("\\s", "");
		if (svg2.contains("<script>"))
			return EMPTY_SVG;
		if (svg2.contains("</script>"))
			return EMPTY_SVG;
		if (svg2.contains("<foreignobject"))
			return EMPTY_SVG;
		if (svg2.contains("</foreignobject>"))
			return EMPTY_SVG;
		return svg;
	}
//  [java]
	private String clean(String svg) {
		svg = svg.toLowerCase().replaceAll("\\s", "");
		if (svg.contains("<script>"))
			return EMPTY_SVG;
		if (svg.contains("</script>"))
			return EMPTY_SVG;
		if (svg.contains("<foreignobject"))
			return EMPTY_SVG;
		if (svg.contains("</foreignobject>"))
			return EMPTY_SVG;
		return svg;
	}
//  [java]
    public void accessAllowed() {
        expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true);
        replay(backend);

        handler.checkAccess("localhost", "127.0.0.1",null);
    }
//  [java]
    public void accessAllowed() {
        expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true);
        replay(backend);

        handler.checkClientIPAccess("localhost","127.0.0.1");
    }
//  [java]
	public SymbolContext getContext(ISkinParam skinParam, Style style) {
		return new SymbolContext(getBackColor(skinParam, style), getLineColor(skinParam, style))
				.withStroke(getStroke(style));
	}
//  [java]
	public SymbolContext getContext(ISkinParam skinParam, Style style) {
		return new SymbolContext(getBackColor(skinParam, style), getLineColor(skinParam, style))
				.withStroke(new UStroke(1.5));
	}
//  [java]
	public ChangeState(TimeTick when, String comment, Colors colors, String... states) {
		if (states.length == 0)
			throw new IllegalArgumentException();

		this.when = when;
		this.states = states;
		this.comment = comment;
		this.colors = colors;
	}
//  [java]
	public ChangeState(TimeTick when, String comment, Colors colors, String... states) {
		if (states.length == 0) {
			throw new IllegalArgumentException();
		}
		this.when = when;
		this.states = states;
		this.comment = comment;
		this.colors = colors;
	}
//  [java]
    public void preflightCheckNegative() {
        String origin = "http://bla.com";
        String headers ="X-Data: Test";
        expect(backend.isOriginAllowed(origin,false)).andReturn(false);
        replay(backend);

        Map<String,String> ret =  handler.handleCorsPreflightRequest(origin, headers);
        assertNull(ret.get("Access-Control-Allow-Origin"));
    }
//  [java]
    public void preflightCheckNegative() {
        String origin = "http://bla.com";
        String headers ="X-Data: Test";
        expect(backend.isCorsAccessAllowed(origin)).andReturn(false);
        replay(backend);

        Map<String,String> ret =  handler.handleCorsPreflightRequest(origin, headers);
        assertNull(ret.get("Access-Control-Allow-Origin"));
    }
//  [java]
    public void accessDenied() {
        expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(false);
        replay(backend);

        handler.checkAccess("localhost", "127.0.0.1",null);
    }
//  [java]
    public void accessDenied() {
        expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(false);
        replay(backend);

        handler.checkClientIPAccess("localhost","127.0.0.1");
    }
//  [java]
	private final HColor getLineColor(ISkinParam skinParam, Style style) {
		if (colors == null || colors.getColor(ColorType.LINE) == null)
			return style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());

		return colors.getColor(ColorType.LINE);
	}
//  [java]
	private final HColor getLineColor(ISkinParam skinParam, Style style) {
		if (colors == null || colors.getColor(ColorType.LINE) == null) {
			if (UseStyle.useBetaStyle() == false)
				return HColorUtils.COL_038048;

			return style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());
		}
		return colors.getColor(ColorType.LINE);
	}
//  [java]
    public void preflightCheck() {
        String origin = "http://bla.com";
        String headers ="X-Data: Test";
        expect(backend.isOriginAllowed(origin,false)).andReturn(true);
        replay(backend);

        Map<String,String> ret =  handler.handleCorsPreflightRequest(origin, headers);
        assertEquals(ret.get("Access-Control-Allow-Origin"),origin);
    }
//  [java]
    public void preflightCheck() {
        String origin = "http://bla.com";
        String headers ="X-Data: Test";
        expect(backend.isCorsAccessAllowed(origin)).andReturn(true);
        replay(backend);

        Map<String,String> ret =  handler.handleCorsPreflightRequest(origin, headers);
        assertEquals(ret.get("Access-Control-Allow-Origin"),origin);
    }
//  [java]
    public void translate(GeyserSession session, ServerEntityMetadataPacket packet) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null) return;

        for (EntityMetadata metadata : packet.getMetadata()) {
            try {
                entity.updateBedrockMetadata(metadata, session);
            } catch (ClassCastException e) {
                // Class cast exceptions are really the only ones we're going to get in normal gameplay
                // Because some entity rewriters forget about some values
                // Any other errors are actual bugs
                session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.network.translator.metadata.failed", metadata, entity.getEntityType()));
                session.getConnector().getLogger().debug("Entity Java ID: " + entity.getEntityId() + ", Geyser ID: " + entity.getGeyserId());
                if (session.getConnector().getConfig().isDebugMode()) {
                    e.printStackTrace();
                }
            }
        }

        entity.updateBedrockMetadata(session);

        // Update the interactive tag, if necessary
        if (session.getMouseoverEntity() != null && session.getMouseoverEntity().getEntityId() == entity.getEntityId()) {
            InteractiveTagManager.updateTag(session, entity);
        }
    }
//  [java]
    public void translate(ServerEntityMetadataPacket packet, GeyserSession session) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null) return;

        for (EntityMetadata metadata : packet.getMetadata()) {
            try {
                entity.updateBedrockMetadata(metadata, session);
            } catch (ClassCastException e) {
                // Class cast exceptions are really the only ones we're going to get in normal gameplay
                // Because some entity rewriters forget about some values
                // Any other errors are actual bugs
                session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.network.translator.metadata.failed", metadata, entity.getEntityType()));
                session.getConnector().getLogger().debug("Entity Java ID: " + entity.getEntityId() + ", Geyser ID: " + entity.getGeyserId());
                if (session.getConnector().getConfig().isDebugMode()) {
                    e.printStackTrace();
                }
            }
        }

        entity.updateBedrockMetadata(session);

        // Update the interactive tag, if necessary
        if (session.getMouseoverEntity() != null && session.getMouseoverEntity().getEntityId() == entity.getEntityId()) {
            InteractiveTagManager.updateTag(session, entity);
        }
    }
//  [java]
    public void translate(GeyserSession session, PacketViolationWarningPacket packet) {
        // Not translated since this is something that the developers need to know
        session.getConnector().getLogger().error("Packet violation warning sent from client! " + packet.toString());
    }
//  [java]
    public void translate(PacketViolationWarningPacket packet, GeyserSession session) {
        // Not translated since this is something that the developers need to know
        session.getConnector().getLogger().error("Packet violation warning sent from client! " + packet.toString());
    }
//  [java]
    public void handle(HttpExchange pExchange) throws IOException {
        if (requestHandler == null) {
            throw new IllegalStateException("Handler not yet started");
        }

        JSONAware json = null;
        URI uri = pExchange.getRequestURI();
        ParsedUri parsedUri = new ParsedUri(uri,context);
        try {
            // Check access policy
            InetSocketAddress address = pExchange.getRemoteAddress();
            requestHandler.checkAccess(address.getHostName(), address.getAddress().getHostAddress(),
                                       extractOriginOrReferer(pExchange));
            String method = pExchange.getRequestMethod();

            // Dispatch for the proper HTTP request method
            if ("GET".equalsIgnoreCase(method)) {
                setHeaders(pExchange);
                json = executeGetRequest(parsedUri);
            } else if ("POST".equalsIgnoreCase(method)) {
                setHeaders(pExchange);
                json = executePostRequest(pExchange, parsedUri);
            } else if ("OPTIONS".equalsIgnoreCase(method)) {
                performCorsPreflightCheck(pExchange);
            } else {
                throw new IllegalArgumentException("HTTP Method " + method + " is not supported.");
            }
        } catch (Throwable exp) {
            json = requestHandler.handleThrowable(
                    exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
        } finally {
            sendResponse(pExchange,parsedUri,json);
        }
    }
//  [java]
    public void handle(HttpExchange pExchange) throws IOException {
        if (requestHandler == null) {
            throw new IllegalStateException("Handler not yet started");
        }

        JSONAware json = null;
        URI uri = pExchange.getRequestURI();
        ParsedUri parsedUri = new ParsedUri(uri,context);
        try {
            // Check access policy
            InetSocketAddress address = pExchange.getRemoteAddress();
            requestHandler.checkClientIPAccess(address.getHostName(),address.getAddress().getHostAddress());
            String method = pExchange.getRequestMethod();

            // Dispatch for the proper HTTP request method
            if ("GET".equalsIgnoreCase(method)) {
                setHeaders(pExchange);
                json = executeGetRequest(parsedUri);
            } else if ("POST".equalsIgnoreCase(method)) {
                setHeaders(pExchange);
                json = executePostRequest(pExchange, parsedUri);
            } else if ("OPTIONS".equalsIgnoreCase(method)) {
                performCorsPreflightCheck(pExchange);
            } else {
                throw new IllegalArgumentException("HTTP Method " + method + " is not supported.");
            }
        } catch (Throwable exp) {
            json = requestHandler.handleThrowable(
                    exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
        } finally {
            sendResponse(pExchange,parsedUri,json);
        }
    }
//  [java]
    private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,
        String parent) throws XWikiException
    {
        XWiki xwiki = context.getWiki();

        // Set the locale and default locale, considering that we're creating the original version of the document
        // (not a translation).
        newDocument.setLocale(Locale.ROOT);
        if (newDocument.getDefaultLocale() == Locale.ROOT) {
            newDocument.setDefaultLocale(xwiki.getLocalePreference(context));
        }

        // Copy the template.
        readFromTemplate(newDocument, template, context);

        // Set the parent field.
        if (!StringUtils.isEmpty(parent)) {
            DocumentReference parentReference = getCurrentMixedDocumentReferenceResolver().resolve(parent);
            newDocument.setParentReference(parentReference);
        }

        // Set the document title
        if (title != null) {
            newDocument.setTitle(title);
        }

        // Set the author and creator.
        DocumentReference currentUserReference = context.getUserReference();
        newDocument.setAuthorReference(currentUserReference);
        newDocument.setCreatorReference(currentUserReference);

        // Make sure the user is allowed to make this modification
        xwiki.checkSavingDocument(currentUserReference, newDocument, context);

        xwiki.saveDocument(newDocument, context);
    }
//  [java]
	public PlayerAnalog(String code, ISkinParam skinParam, TimingRuler ruler, boolean compact) {
		super(code, skinParam, ruler, compact, null);
		this.suggestedHeight = 100;
	}
//  [java]
	public PlayerAnalog(String code, ISkinParam skinParam, TimingRuler ruler, boolean compact) {
		super(code, skinParam, ruler, compact);
		this.suggestedHeight = 100;
	}
//  [java]
  public ExitCode runWithoutHelp(CommandRunnerParams params)
      throws IOException, InterruptedException {

    if (saveFilename != null && loadFilename != null) {
      params.getConsole().printErrorText("Can't use both --load and --save");
      return ExitCode.COMMANDLINE_ERROR;
    }

    if (saveFilename != null) {
      invalidateChanges(params);
      RemoteDaemonicParserState state = params.getParser().storeParserState(params.getCell());
      try (FileOutputStream fos = new FileOutputStream(saveFilename);
          ZipOutputStream zipos = new ZipOutputStream(fos)) {
        zipos.putNextEntry(new ZipEntry("parser_data"));
        try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) {
          oos.writeObject(state);
        }
      }
    } else if (loadFilename != null) {
      try (FileInputStream fis = new FileInputStream(loadFilename);
          ZipInputStream zipis = new ZipInputStream(fis)) {
        ZipEntry entry = zipis.getNextEntry();
        Preconditions.checkState(entry.getName().equals("parser_data"));
        try (ObjectInputStream ois = new ParserStateObjectInputStream(zipis)) {
          RemoteDaemonicParserState state;
          try {
            state = (RemoteDaemonicParserState) ois.readObject();
          } catch (ClassNotFoundException e) {
            params.getConsole().printErrorText("Invalid file format");
            return ExitCode.COMMANDLINE_ERROR;
          }
          params.getParser().restoreParserState(state, params.getCell());
        }
      }
      invalidateChanges(params);

      ParserConfig configView = params.getBuckConfig().getView(ParserConfig.class);
      if (configView.isParserCacheMutationWarningEnabled()) {
        params
            .getConsole()
            .printErrorText(
                params
                    .getConsole()
                    .getAnsi()
                    .asWarningText(
                        "WARNING: Buck injected a parser state that may not match the local state."));
      }
    }

    return ExitCode.SUCCESS;
  }
//  [java]
  public ExitCode runWithoutHelp(CommandRunnerParams params)
      throws IOException, InterruptedException {

    if (saveFilename != null && loadFilename != null) {
      params.getConsole().printErrorText("Can't use both --load and --save");
      return ExitCode.COMMANDLINE_ERROR;
    }

    if (saveFilename != null) {
      invalidateChanges(params);
      RemoteDaemonicParserState state = params.getParser().storeParserState(params.getCell());
      try (FileOutputStream fos = new FileOutputStream(saveFilename);
          ZipOutputStream zipos = new ZipOutputStream(fos)) {
        zipos.putNextEntry(new ZipEntry("parser_data"));
        try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) {
          oos.writeObject(state);
        }
      }
    } else if (loadFilename != null) {
      try (FileInputStream fis = new FileInputStream(loadFilename);
          ZipInputStream zipis = new ZipInputStream(fis)) {
        ZipEntry entry = zipis.getNextEntry();
        Preconditions.checkState(entry.getName().equals("parser_data"));
        try (ObjectInputStream ois = new ObjectInputStream(zipis)) {
          RemoteDaemonicParserState state;
          try {
            state = (RemoteDaemonicParserState) ois.readObject();
          } catch (ClassNotFoundException e) {
            params.getConsole().printErrorText("Invalid file format");
            return ExitCode.COMMANDLINE_ERROR;
          }
          params.getParser().restoreParserState(state, params.getCell());
        }
      }
      invalidateChanges(params);

      ParserConfig configView = params.getBuckConfig().getView(ParserConfig.class);
      if (configView.isParserCacheMutationWarningEnabled()) {
        params
            .getConsole()
            .printErrorText(
                params
                    .getConsole()
                    .getAnsi()
                    .asWarningText(
                        "WARNING: Buck injected a parser state that may not match the local state."));
      }
    }

    return ExitCode.SUCCESS;
  }
//  [java]
    private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {
        JSONAware json = null;
        try {
            // Check access policy
            requestHandler.checkAccess(pReq.getRemoteHost(), pReq.getRemoteAddr(),
                                       getOriginOrReferer(pReq));

            // Remember the agent URL upon the first request. Needed for discovery
            updateAgentUrlIfNeeded(pReq);

            // Dispatch for the proper HTTP request method
            json = pReqHandler.handleRequest(pReq,pResp);
        } catch (Throwable exp) {
            json = requestHandler.handleThrowable(
                    exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
        } finally {
            setCorsHeader(pReq, pResp);

            String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());
            String answer = json != null ?
                    json.toJSONString() :
                    requestHandler.handleThrowable(new Exception("Internal error while handling an exception")).toJSONString();
            if (callback != null) {
                // Send a JSONP response
                sendResponse(pResp, "text/javascript", callback + "(" + answer + ");");
            } else {
                sendResponse(pResp, getMimeType(pReq),answer);
            }
        }
    }
//  [java]
    private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {
        JSONAware json = null;
        try {
            // Check access policy
            requestHandler.checkClientIPAccess(pReq.getRemoteHost(),pReq.getRemoteAddr());

            // Remember the agent URL upon the first request. Needed for discovery
            updateAgentUrlIfNeeded(pReq);

            // Dispatch for the proper HTTP request method
            json = pReqHandler.handleRequest(pReq,pResp);
        } catch (Throwable exp) {
            json = requestHandler.handleThrowable(
                    exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
        } finally {
            setCorsHeader(pReq, pResp);

            String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());
            String answer = json != null ?
                    json.toJSONString() :
                    requestHandler.handleThrowable(new Exception("Internal error while handling an exception")).toJSONString();
            if (callback != null) {
                // Send a JSONP response
                sendResponse(pResp, "text/javascript", callback + "(" + answer + ");");
            } else {
                sendResponse(pResp, getMimeType(pReq),answer);
            }
        }
    }
//  [java]
    public void parseURL(ApplContext ac, URL url, String title,
                         String kind, String media,
                         int origin) {
        boolean doneref = false;
        URL ref = ac.getReferrer();
        setWarningLevel(ac.getWarningLevel());
        if (Util.onDebug) {
            System.err.println("StyleSheet.parseURL(" + url + ", "
                    + title + ", "
                    + kind + ", " + media + ", "
                    + origin + ")");
        }
        if (kind != null) {
            kind = kind.trim().toLowerCase();
            if (!kind.equals("stylesheet") && !kind.equals("alternate stylesheet")) {
                return;
            }
        }
        try {
            ac.setOrigin(origin);
//	    if (cssFouffa == null) {
            cssFouffa = new CssFouffa(ac, url);
            cssFouffa.addListener(this);
//	    } else {
//		cssFouffa.ReInit(ac, url);
//	    }

            //	    cssFouffa.setResponse(res);

            // removed plh 2001-03-08
            // cssFouffa.setOrigin(origin);
            //	    cssFouffa.setDefaultMedium(defaultmedium);
            //	    cssFouffa.doConfig();
            if (media == null) {
                if (ac.getCssVersion() != CssVersion.CSS1) {
                    if (ac.getMedium() == null) {
                        media = "all";
                    } else {
                        media = ac.getMedium();
                    }
                }
            }
            AtRuleMedia m = AtRuleMedia.getInstance(ac.getCssVersion());
            try {
                if (media != null) {
                    addMedias(m, media, ac);
                }
                cssFouffa.setAtRule(m);
            } catch (org.w3c.css.util.InvalidParamException e) {
                Errors er = new Errors();
                er.addError(new org.w3c.css.parser.CssError(url.toString(),
                        -1, e));
                notifyErrors(er);
                return;
            }
            ac.setReferrer(url);
            doneref = true;
            cssFouffa.parseStyle();
        } catch (Exception e) {
            Errors er = new Errors();
            er.addError(new org.w3c.css.parser.CssError(Messages.escapeString(url.toString()),
                    -1, new Exception(Messages.escapeString(e.getMessage()))));
            notifyErrors(er);
        } finally {
            if (doneref) {
                ac.setReferrer(ref);
            }
        }
    }
//  [java]
    public void parseURL(ApplContext ac, URL url, String title,
                         String kind, String media,
                         int origin) {
        boolean doneref = false;
        URL ref = ac.getReferrer();
        setWarningLevel(ac.getWarningLevel());
        if (Util.onDebug) {
            System.err.println("StyleSheet.parseURL(" + url + ", "
                    + title + ", "
                    + kind + ", " + media + ", "
                    + origin + ")");
        }
        if (kind != null) {
            kind = kind.trim().toLowerCase();
            if (!kind.equals("stylesheet") && !kind.equals("alternate stylesheet")) {
                return;
            }
        }
        try {
            ac.setOrigin(origin);
//	    if (cssFouffa == null) {
            cssFouffa = new CssFouffa(ac, url);
            cssFouffa.addListener(this);
//	    } else {
//		cssFouffa.ReInit(ac, url);
//	    }

            //	    cssFouffa.setResponse(res);

            // removed plh 2001-03-08
            // cssFouffa.setOrigin(origin);
            //	    cssFouffa.setDefaultMedium(defaultmedium);
            //	    cssFouffa.doConfig();
            if (media == null) {
                if (ac.getCssVersion() != CssVersion.CSS1) {
                    if (ac.getMedium() == null) {
                        media = "all";
                    } else {
                        media = ac.getMedium();
                    }
                }
            }
            AtRuleMedia m = AtRuleMedia.getInstance(ac.getCssVersion());
            try {
                if (media != null) {
                    addMedias(m, media, ac);
                }
                cssFouffa.setAtRule(m);
            } catch (org.w3c.css.util.InvalidParamException e) {
                Errors er = new Errors();
                er.addError(new org.w3c.css.parser.CssError(url.toString(),
                        -1, e));
                notifyErrors(er);
                return;
            }
            ac.setReferrer(url);
            doneref = true;
            cssFouffa.parseStyle();
        } catch (Exception e) {
            Errors er = new Errors();
            er.addError(new org.w3c.css.parser.CssError(Messages.escapeString(url.toString()),
                    -1, e));
            notifyErrors(er);
        } finally {
            if (doneref) {
                ac.setReferrer(ref);
            }
        }
    }
//  [java]
    private boolean processStyleTag(Element ele, Node parentNode) {
        /*
         * Invoke the css parser on this element.
         */
        CssScanner styleScanner = new CssScanner(policy, messages, policy.isEmbedStyleSheets());

        try {
            if (ele.getChildNodes().getLength() > 0) {
                String toScan = "";

                for (int i = 0; i < ele.getChildNodes().getLength(); i++) {
                    Node childNode = ele.getChildNodes().item(i);
                    if (!toScan.isEmpty()){
                        toScan += "\n";
                    }
                    toScan += childNode.getTextContent();
                }

                CleanResults cr = styleScanner.scanStyleSheet(toScan, policy.getMaxInputSize());
                errorMessages.addAll(cr.getErrorMessages());

                /*
                 * If IE gets an empty style tag, i.e. <style/> it will
                 * break all CSS on the page. I wish I was kidding. So,
                 * if after validation no CSS properties are left, we
                 * would normally be left with an empty style tag and
                 * break all CSS. To prevent that, we have this check.
                 */

                String cleanHTML = cr.getCleanHTML();
                cleanHTML = cleanHTML == null || cleanHTML.equals("") ? "/* */" : cleanHTML;

                ele.getFirstChild().setNodeValue(cleanHTML);
                /*
                 * Remove every other node after cleaning CSS, there will
                 * be only one node in the end, as it always should have.
                 */
                for (int i = 1; i < ele.getChildNodes().getLength(); i++) {
                    Node childNode = ele.getChildNodes().item(i);
                    ele.removeChild(childNode);
                }
            }

        } catch (DOMException | ScanException | ParseException | NumberFormatException e) {

            /*
             * ParseException shouldn't be possible anymore, but we'll leave it
             * here because I (Arshan) am hilariously dumb sometimes.
             * Batik can throw NumberFormatExceptions (see bug #48).
             */

            addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(ele.getFirstChild().getNodeValue())});
            parentNode.removeChild(ele);
            return true;
        }
        return false;
    }
//  [java]
    private boolean processStyleTag(Element ele, Node parentNode) {
        /*
         * Invoke the css parser on this element.
         */
        CssScanner styleScanner = new CssScanner(policy, messages, policy.isEmbedStyleSheets());

        try {
            Node firstChild = ele.getFirstChild();
            if (firstChild != null) {

                String toScan = firstChild.getNodeValue();
                CleanResults cr = styleScanner.scanStyleSheet(toScan, policy.getMaxInputSize());
                errorMessages.addAll(cr.getErrorMessages());

                /*
                 * If IE gets an empty style tag, i.e. <style/> it will
                 * break all CSS on the page. I wish I was kidding. So,
                 * if after validation no CSS properties are left, we
                 * would normally be left with an empty style tag and
                 * break all CSS. To prevent that, we have this check.
                 */

                final String cleanHTML = cr.getCleanHTML();

                if (cleanHTML == null || cleanHTML.equals("")) {
                    firstChild.setNodeValue("/* */");
                } else {
                    firstChild.setNodeValue(cleanHTML);
                }
            }

        } catch (DOMException | ScanException | ParseException | NumberFormatException e) {

            /*
             * ParseException shouldn't be possible anymore, but we'll leave it
             * here because I (Arshan) am hilariously dumb sometimes.
             * Batik can throw NumberFormatExceptions (see bug #48).
             */

            addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(ele.getFirstChild().getNodeValue())});
            parentNode.removeChild(ele);
            return true;
        }
        return false;
    }
//  [java]
    public DataSource createNewDataSource(Map<String, ?> params) throws IOException {
        String refName = (String) JNDI_REFNAME.lookUp(params);
        try {
            return (DataSource) GeoTools.jndiLookup(refName);
        } catch (Exception e) {
            throw new DataSourceException("Could not find the specified data source in JNDI", e);
        }
    }
//  [java]
    public DataSource createNewDataSource(Map<String, ?> params) throws IOException {
        String refName = (String) JNDI_REFNAME.lookUp(params);
        try {
            return (DataSource) GeoTools.getInitialContext().lookup(refName);
        } catch (Exception e) {
            throw new DataSourceException("Could not find the specified data source in JNDI", e);
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerPlayerChangeHeldItemPacket packet) {
        PlayerHotbarPacket hotbarPacket = new PlayerHotbarPacket();
        hotbarPacket.setContainerId(0);
        hotbarPacket.setSelectedHotbarSlot(packet.getSlot());
        hotbarPacket.setSelectHotbarSlot(true);
        session.sendUpstreamPacket(hotbarPacket);

        session.getPlayerInventory().setHeldItemSlot(packet.getSlot());
    }
//  [java]
    public void translate(ServerPlayerChangeHeldItemPacket packet, GeyserSession session) {
        PlayerHotbarPacket hotbarPacket = new PlayerHotbarPacket();
        hotbarPacket.setContainerId(0);
        hotbarPacket.setSelectedHotbarSlot(packet.getSlot());
        hotbarPacket.setSelectHotbarSlot(true);
        session.sendUpstreamPacket(hotbarPacket);

        session.getPlayerInventory().setHeldItemSlot(packet.getSlot());
    }
//  [java]
    public boolean isAvailable() {
        try {
            GeoTools.getInitialContext();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerPlayerHealthPacket packet) {
        SessionPlayerEntity entity = session.getPlayerEntity();

        int health = (int) Math.ceil(packet.getHealth());
        SetHealthPacket setHealthPacket = new SetHealthPacket();
        setHealthPacket.setHealth(health);
        session.sendUpstreamPacket(setHealthPacket);

        entity.setHealth(packet.getHealth());

        UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
        List<AttributeData> attributes = attributesPacket.getAttributes();

        AttributeData healthAttribute = entity.createHealthAttribute();
        entity.getAttributes().put(GeyserAttributeType.HEALTH, healthAttribute);
        attributes.add(healthAttribute);

        AttributeData hungerAttribute = GeyserAttributeType.HUNGER.getAttribute(packet.getFood());
        entity.getAttributes().put(GeyserAttributeType.HUNGER, hungerAttribute);
        attributes.add(hungerAttribute);

        AttributeData saturationAttribute = GeyserAttributeType.SATURATION.getAttribute(packet.getSaturation());
        entity.getAttributes().put(GeyserAttributeType.SATURATION, saturationAttribute);
        attributes.add(saturationAttribute);

        attributesPacket.setRuntimeEntityId(entity.getGeyserId());
        session.sendUpstreamPacket(attributesPacket);
    }