jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,
        String parent) throws XWikiException
    {
        XWiki xwiki = context.getWiki();
        DocumentReferenceResolver<String> resolver = getCurrentMixedDocumentReferenceResolver();

        // 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.
        DocumentReference templateReference = resolver.resolve(template);
        newDocument.readFromTemplate(templateReference, context);

        // Set the parent field.
        if (!StringUtils.isEmpty(parent)) {
            DocumentReference parentReference = resolver.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 void translate(GeyserSession session, ServerMultiBlockChangePacket packet) {
        for (BlockChangeRecord record : packet.getRecords()) {
            ChunkUtils.updateBlock(session, record.getBlock(), record.getPosition());
        }
    }
//  [java]
    public void translate(ServerMultiBlockChangePacket packet, GeyserSession session) {
        for (BlockChangeRecord record : packet.getRecords()) {
            ChunkUtils.updateBlock(session, record.getBlock(), record.getPosition());
        }
    }
//  [java]
	public String render(TemplateEngineTypeEnum engineType, String templateContent, Map<String, Object> context)
			throws TemplateRenderException {
		if (StrUtil.isEmpty(templateContent)) {
			return StrUtil.EMPTY;
		}
		TemplateEngine templateEngine = templateEngineMap.get(engineType);
		Assert.notNull(templateEngine, "未找到对应的模板引擎：{}", engineType);
		return templateEngine.render(templateContent, context);
	}
//  [java]
	public String render(TemplateEngineTypeEnum engineType, String templateContent, Map<String, Object> context) {
		if (StrUtil.isEmpty(templateContent)) {
			return StrUtil.EMPTY;
		}
		TemplateEngine templateEngine = templateEngineMap.get(engineType);
		Assert.notNull(templateEngine, "未找到对应的模板引擎：{}", engineType);
		return templateEngine.render(templateContent, context);
	}
//  [java]
    public void translate(GeyserSession session, ServerUpdateTileEntityPacket packet) {
        String id = BlockEntityUtils.getBedrockBlockEntityId(packet.getType().name());
        if (packet.getNbt().isEmpty()) { // Fixes errors in servers sending empty NBT
            BlockEntityUtils.updateBlockEntity(session, NbtMap.EMPTY, packet.getPosition());
            return;
        }

        BlockEntityTranslator translator = BlockEntityUtils.getBlockEntityTranslator(id);
        // The Java block state is used in BlockEntityTranslator.translateTag() to make up for some inconsistencies
        // between Java block states and Bedrock block entity data
        int blockState;
        if (translator instanceof RequiresBlockState) {
            blockState = session.getConnector().getWorldManager().getBlockAt(session, packet.getPosition());
        } else {
            blockState = BlockStateValues.JAVA_AIR_ID;
        }
        BlockEntityUtils.updateBlockEntity(session, translator.getBlockEntityTag(id, packet.getNbt(), blockState), packet.getPosition());
        // Check for custom skulls.
        if (SkullBlockEntityTranslator.ALLOW_CUSTOM_SKULLS && packet.getNbt().contains("SkullOwner")) {
            SkullBlockEntityTranslator.spawnPlayer(session, packet.getNbt(), blockState);
        }

        // If block entity is command block, OP permission level is appropriate, player is in creative mode and the NBT is not empty
        if (packet.getType() == UpdatedTileType.COMMAND_BLOCK && session.getOpPermissionLevel() >= 2 &&
                session.getGameMode() == GameMode.CREATIVE && packet.getNbt().size() > 5) {
            ContainerOpenPacket openPacket = new ContainerOpenPacket();
            openPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));
            openPacket.setId((byte) 1);
            openPacket.setType(ContainerType.COMMAND_BLOCK);
            openPacket.setUniqueEntityId(-1);
            session.sendUpstreamPacket(openPacket);
        }
    }
//  [java]
    public void translate(ServerUpdateTileEntityPacket packet, GeyserSession session) {
        String id = BlockEntityUtils.getBedrockBlockEntityId(packet.getType().name());
        if (packet.getNbt().isEmpty()) { // Fixes errors in servers sending empty NBT
            BlockEntityUtils.updateBlockEntity(session, NbtMap.EMPTY, packet.getPosition());
            return;
        }

        BlockEntityTranslator translator = BlockEntityUtils.getBlockEntityTranslator(id);
        // The Java block state is used in BlockEntityTranslator.translateTag() to make up for some inconsistencies
        // between Java block states and Bedrock block entity data
        int blockState;
        if (translator instanceof RequiresBlockState) {
            blockState = session.getConnector().getWorldManager().getBlockAt(session, packet.getPosition());
        } else {
            blockState = BlockStateValues.JAVA_AIR_ID;
        }
        BlockEntityUtils.updateBlockEntity(session, translator.getBlockEntityTag(id, packet.getNbt(), blockState), packet.getPosition());
        // Check for custom skulls.
        if (SkullBlockEntityTranslator.ALLOW_CUSTOM_SKULLS && packet.getNbt().contains("SkullOwner")) {
            SkullBlockEntityTranslator.spawnPlayer(session, packet.getNbt(), blockState);
        }

        // If block entity is command block, OP permission level is appropriate, player is in creative mode and the NBT is not empty
        if (packet.getType() == UpdatedTileType.COMMAND_BLOCK && session.getOpPermissionLevel() >= 2 &&
                session.getGameMode() == GameMode.CREATIVE && packet.getNbt().size() > 5) {
            ContainerOpenPacket openPacket = new ContainerOpenPacket();
            openPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));
            openPacket.setId((byte) 1);
            openPacket.setType(ContainerType.COMMAND_BLOCK);
            openPacket.setUniqueEntityId(-1);
            session.sendUpstreamPacket(openPacket);
        }
    }
//  [java]
    void arrive(Object payload, emissary.place.IServiceProviderPlace arrivalPlace, int mec, List<emissary.directory.DirectoryEntry> iq)
            throws Exception;

    /**
     * Retrieve the current move error count
     */
    int getMoveErrorCount();

    /**
     * Retreive the current list of stored itinerary steps
     * 
     * @return array of DirectoryEntry
     */
    emissary.directory.DirectoryEntry[] getItineraryQueueItems();

    /**
     * Return true if agent is working on a payload
     */
    boolean isInUse();

    /**
     * Get the payload as an object for serialization during transport.
     *
     */
    Object getPayloadForTransport();

    /**
     * Get the name of the current payload
     */
    String getName();

    /**
     * get the name of the last place processed.
     */
    String getLastPlaceProcessed();

    /**
     * Call this method to permanently stop the running thread when we finish what we are doing
     */
    void killAgent();

    /**
     * Call this method to permanently stop the running thread eventually Returns immediately
     */
    void killAgentAsync();

    /**
     * Determine if this agent is walking un-dead
     */
    boolean isZombie();

    /**
     * Interrupte the agent's thread
     */
    void interrupt();

    /**
     * Get the number of move errors
     */
    int getMaxMoveErrors();

    /**
     * Set the maximum number of move attempts that can error out before this instance will quit trying and set the workflow
     * to be an ERROR condition
     * 
     * @param value the maximum number of move failures
     */
    void setMaxMoveErrors(int value);

    /**
     * Get the maximum number of itinerary steps
     */
    int getMaxItinerarySteps();

    /**
     * Set the maximum number of itinerary steps before this instance will turn the workflow into an ERROR condition
     * 
     * @param value the new maximum number of steps
     */
    void setMaxItinerarySteps(int value);

    /**
     * Returns the current payload count of the agent.
     * 
     * @return default value of 1
     */
    default public int payloadCount() {
        return 1;
    }
//  [java]
    void arrive(Object payload, emissary.place.IServiceProviderPlace arrivalPlace, int mec, List<emissary.directory.DirectoryEntry> iq)
            throws Exception;

    /**
     * Retrieve the current move error count
     */
    int getMoveErrorCount();

    /**
     * Retreive the current list of stored itinerary steps
     * 
     * @return array of DirectoryEntry
     */
    emissary.directory.DirectoryEntry[] getItineraryQueueItems();

    /**
     * Return true if agent is working on a payload
     */
    boolean isInUse();

    /**
     * Get the payload as an object for serialization during transport Should only be called by the MoveToAdapter
     * 
     * @see MoveToAdapter
     */
    Object getPayloadForTransport();

    /**
     * Get the name of the current payload
     */
    String getName();

    /**
     * get the name of the last place processed.
     */
    String getLastPlaceProcessed();

    /**
     * Call this method to permanently stop the running thread when we finish what we are doing
     */
    void killAgent();

    /**
     * Call this method to permanently stop the running thread eventually Returns immediately
     */
    void killAgentAsync();

    /**
     * Determine if this agent is walking un-dead
     */
    boolean isZombie();

    /**
     * Interrupte the agent's thread
     */
    void interrupt();

    /**
     * Get the number of move errors
     */
    int getMaxMoveErrors();

    /**
     * Set the maximum number of move attempts that can error out before this instance will quit trying and set the workflow
     * to be an ERROR condition
     * 
     * @param value the maximum number of move failures
     */
    void setMaxMoveErrors(int value);

    /**
     * Get the maximum number of itinerary steps
     */
    int getMaxItinerarySteps();

    /**
     * Set the maximum number of itinerary steps before this instance will turn the workflow into an ERROR condition
     * 
     * @param value the new maximum number of steps
     */
    void setMaxItinerarySteps(int value);

    /**
     * Returns the current payload count of the agent.
     * 
     * @return default value of 1
     */
    default public int payloadCount() {
        return 1;
    }
//  [java]
    public void translate(GeyserSession session, BlockPickRequestPacket packet) {
        Vector3i vector = packet.getBlockPosition();
        int blockToPick = session.getConnector().getWorldManager().getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());
        
        // Block is air - chunk caching is probably off
        if (blockToPick == BlockStateValues.JAVA_AIR_ID) {
            // Check for an item frame since the client thinks that's a block when it's an entity in Java
            ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
            if (entity != null) {
                // Check to see if the item frame has an item in it first
                if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {
                    // Grab the item in the frame
                    InventoryUtils.findOrCreateItem(session, entity.getHeldItem());
                } else {
                    // Grab the frame as the item
                    InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame");
                }
            }
            return;
        }

        InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());
    }
//  [java]
    public void translate(BlockPickRequestPacket packet, GeyserSession session) {
        Vector3i vector = packet.getBlockPosition();
        int blockToPick = session.getConnector().getWorldManager().getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());
        
        // Block is air - chunk caching is probably off
        if (blockToPick == BlockStateValues.JAVA_AIR_ID) {
            // Check for an item frame since the client thinks that's a block when it's an entity in Java
            ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
            if (entity != null) {
                // Check to see if the item frame has an item in it first
                if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {
                    // Grab the item in the frame
                    InventoryUtils.findOrCreateItem(session, entity.getHeldItem());
                } else {
                    // Grab the frame as the item
                    InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame");
                }
            }
            return;
        }

        InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());
    }
//  [java]
    public void translate(GeyserSession session, ItemStackRequestPacket packet) {
        Inventory inventory = session.getOpenInventory();
        if (inventory == null)
            return;

        InventoryTranslator translator = session.getInventoryTranslator();
        translator.translateRequests(session, inventory, packet.getRequests());
    }
//  [java]
    public void translate(ItemStackRequestPacket packet, GeyserSession session) {
        Inventory inventory = session.getOpenInventory();
        if (inventory == null)
            return;

        InventoryTranslator translator = session.getInventoryTranslator();
        translator.translateRequests(session, inventory, packet.getRequests());
    }
//  [java]
    public void translate(GeyserSession session, ServerMapDataPacket packet) {
        ClientboundMapItemDataPacket mapItemDataPacket = new ClientboundMapItemDataPacket();
        boolean shouldStore = false;

        mapItemDataPacket.setUniqueMapId(packet.getMapId());
        mapItemDataPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension()));
        mapItemDataPacket.setLocked(packet.isLocked());
        mapItemDataPacket.setScale(packet.getScale());

        MapData data = packet.getData();
        if (data != null) {
            mapItemDataPacket.setXOffset(data.getX());
            mapItemDataPacket.setYOffset(data.getY());
            mapItemDataPacket.setWidth(data.getColumns());
            mapItemDataPacket.setHeight(data.getRows());

            // We have a full map image, this usually only happens on spawn for the initial image
            if (mapItemDataPacket.getWidth() == 128 && mapItemDataPacket.getHeight() == 128) {
                shouldStore = true;
            }

            // Every int entry is an ABGR color
            int[] colors = new int[data.getData().length];

            int idx = 0;
            for (byte colorId : data.getData()) {
                colors[idx++] = MapColor.fromId(colorId & 0xFF).toABGR();
            }

            mapItemDataPacket.setColors(colors);
        }

        // Bedrock needs an entity id to display an icon
        int id = 0;
        for (MapIcon icon : packet.getIcons()) {
            BedrockMapIcon bedrockMapIcon = BedrockMapIcon.fromType(icon.getIconType());

            mapItemDataPacket.getTrackedObjects().add(new MapTrackedObject(id));
            mapItemDataPacket.getDecorations().add(new MapDecoration(bedrockMapIcon.getIconID(), icon.getIconRotation(), icon.getCenterX(), icon.getCenterZ(), "", bedrockMapIcon.toARGB()));
            id++;
        }

        // Store the map to send when the client requests it, as bedrock expects the data after a MapInfoRequestPacket
        if (shouldStore) {
            session.getStoredMaps().put(mapItemDataPacket.getUniqueMapId(), mapItemDataPacket);
        }

        // Send anyway just in case
        session.sendUpstreamPacket(mapItemDataPacket);
    }
//  [java]
    public void translate(ServerMapDataPacket packet, GeyserSession session) {
        ClientboundMapItemDataPacket mapItemDataPacket = new ClientboundMapItemDataPacket();
        boolean shouldStore = false;

        mapItemDataPacket.setUniqueMapId(packet.getMapId());
        mapItemDataPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension()));
        mapItemDataPacket.setLocked(packet.isLocked());
        mapItemDataPacket.setScale(packet.getScale());

        MapData data = packet.getData();
        if (data != null) {
            mapItemDataPacket.setXOffset(data.getX());
            mapItemDataPacket.setYOffset(data.getY());
            mapItemDataPacket.setWidth(data.getColumns());
            mapItemDataPacket.setHeight(data.getRows());

            // We have a full map image, this usually only happens on spawn for the initial image
            if (mapItemDataPacket.getWidth() == 128 && mapItemDataPacket.getHeight() == 128) {
                shouldStore = true;
            }

            // Every int entry is an ABGR color
            int[] colors = new int[data.getData().length];

            int idx = 0;
            for (byte colorId : data.getData()) {
                colors[idx++] = MapColor.fromId(colorId & 0xFF).toABGR();
            }

            mapItemDataPacket.setColors(colors);
        }

        // Bedrock needs an entity id to display an icon
        int id = 0;
        for (MapIcon icon : packet.getIcons()) {
            BedrockMapIcon bedrockMapIcon = BedrockMapIcon.fromType(icon.getIconType());

            mapItemDataPacket.getTrackedObjects().add(new MapTrackedObject(id));
            mapItemDataPacket.getDecorations().add(new MapDecoration(bedrockMapIcon.getIconID(), icon.getIconRotation(), icon.getCenterX(), icon.getCenterZ(), "", bedrockMapIcon.toARGB()));
            id++;
        }

        // Store the map to send when the client requests it, as bedrock expects the data after a MapInfoRequestPacket
        if (shouldStore) {
            session.getStoredMaps().put(mapItemDataPacket.getUniqueMapId(), mapItemDataPacket);
        }

        // Send anyway just in case
        session.sendUpstreamPacket(mapItemDataPacket);
    }
//  [java]
    public void translate(GeyserSession session, ServerRemoveEntitiesPacket packet) {
        for (int entityId : packet.getEntityIds()) {
            Entity entity = session.getEntityCache().getEntityByJavaId(entityId);
            if (entity != null) {
                session.getEntityCache().removeEntity(entity, false);
            }
        }
    }
//  [java]
    public void translate(ServerRemoveEntitiesPacket packet, GeyserSession session) {
        for (int entityId : packet.getEntityIds()) {
            Entity entity = session.getEntityCache().getEntityByJavaId(entityId);
            if (entity != null) {
                session.getEntityCache().removeEntity(entity, false);
            }
        }
    }
//  [java]
    protected BigDecimal bcdToBigDecimal() {
        if (usingBytes) {
            // Converting to a string here is faster than doing BigInteger/BigDecimal arithmetic.
            BigDecimal result = new BigDecimal(toNumberString());
            if (isNegative()) {
                result = result.negate();
            }
            return result;
        } else {
            long tempLong = 0L;
            for (int shift = (precision - 1); shift >= 0; shift--) {
                tempLong = tempLong * 10 + getDigitPos(shift);
            }
            BigDecimal result = BigDecimal.valueOf(tempLong);
            try {
                result = result.scaleByPowerOfTen(scale);
            } catch (ArithmeticException e) {
                if (e.getMessage().contains("Underflow")) {
                    result = BigDecimal.ZERO;
                } else {
                    throw e;
                }
            }
            if (isNegative())
                result = result.negate();
            return result;
        }
    }
//  [java]
    protected BigDecimal bcdToBigDecimal() {
        if (usingBytes) {
            // Converting to a string here is faster than doing BigInteger/BigDecimal arithmetic.
            BigDecimal result = new BigDecimal(toNumberString());
            if (isNegative()) {
                result = result.negate();
            }
            return result;
        } else {
            long tempLong = 0L;
            for (int shift = (precision - 1); shift >= 0; shift--) {
                tempLong = tempLong * 10 + getDigitPos(shift);
            }
            BigDecimal result = BigDecimal.valueOf(tempLong);
            result = result.scaleByPowerOfTen(scale);
            if (isNegative())
                result = result.negate();
            return result;
        }
    }
//  [java]
    private URL findPathConsideringContracts(ClassLoader loader, 
                                     LibraryInfo library,
                                     String resourceName,
                                     String localePrefix,
                                     ContractInfo [] outContract,
                                     String [] outBasePath,
                                     FacesContext ctx) {
        UIViewRoot root = ctx.getViewRoot();
        List<String> contracts = null;
        URL result = null;
        
        if (library != null) {
            if(library.getContract() == null) {
                contracts = Collections.emptyList();
            } else {
                contracts = new ArrayList<String>(1);
                contracts.add(library.getContract());
            }
        } else if (root == null) {
            String contractName = ctx.getExternalContext().getRequestParameterMap()
                  .get("con");
            if (null != contractName && 0 < contractName.length() && !ResourceManager.nameContainsForbiddenSequence(contractName)) {
                contracts = new ArrayList<>();
                contracts.add(contractName);
            } else {
                return null;
            }
        } else {
       		contracts = ctx.getResourceLibraryContracts();
        }

        String basePath = null;
        
        for (String curContract : contracts) {
        
            if (library != null) {
                // PENDING(fcaputo) no need to iterate over the contracts, if we have a library
                basePath = library.getPath(localePrefix) + '/' + resourceName;
            } else {
                if (localePrefix == null) {
                    basePath = getBaseContractsPath() + '/' + curContract + '/' + resourceName;
                } else {
                    basePath = getBaseContractsPath()
                            + '/' + curContract 
                            + '/'
                            + localePrefix
                            + '/'
                            + resourceName;
                }
            }
            
            if (null != (result = loader.getResource(basePath))) {
                outContract[0] = new ContractInfo(curContract);
                outBasePath[0] = basePath;
                break;
            } else {
                basePath = null;
            }
        }
            
        return result;
    }
//  [java]
    private URL findPathConsideringContracts(ClassLoader loader, 
                                     LibraryInfo library,
                                     String resourceName,
                                     String localePrefix,
                                     ContractInfo [] outContract,
                                     String [] outBasePath,
                                     FacesContext ctx) {
        UIViewRoot root = ctx.getViewRoot();
        List<String> contracts = null;
        URL result = null;
        
        if (library != null) {
            if(library.getContract() == null) {
                contracts = Collections.emptyList();
            } else {
                contracts = new ArrayList<String>(1);
                contracts.add(library.getContract());
            }
        } else if (root == null) {
            String contractName = ctx.getExternalContext().getRequestParameterMap()
                  .get("con");
            if (null != contractName && 0 < contractName.length()) {
                contracts = new ArrayList<>();
                contracts.add(contractName);
            } else {
                return null;
            }
        } else {
       		contracts = ctx.getResourceLibraryContracts();
        }

        String basePath = null;
        
        for (String curContract : contracts) {
        
            if (library != null) {
                // PENDING(fcaputo) no need to iterate over the contracts, if we have a library
                basePath = library.getPath(localePrefix) + '/' + resourceName;
            } else {
                if (localePrefix == null) {
                    basePath = getBaseContractsPath() + '/' + curContract + '/' + resourceName;
                } else {
                    basePath = getBaseContractsPath()
                            + '/' + curContract 
                            + '/'
                            + localePrefix
                            + '/'
                            + resourceName;
                }
            }
            
            if (null != (result = loader.getResource(basePath))) {
                outContract[0] = new ContractInfo(curContract);
                outBasePath[0] = basePath;
                break;
            } else {
                basePath = null;
            }
        }
            
        return result;
    }
//  [java]
	private Response attachToPost(Long messageKey, String filename, InputStream file,  HttpServletRequest request) {
		//load message
		Message mess = fom.loadMessage(messageKey);
		if(mess == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		}
		if(!forum.equalsByPersistableKey(mess.getForum())) {
			return Response.serverError().status(Status.CONFLICT).build();
		}
		return attachToPost(mess, filename, file, request);
	}
//  [java]
	protected Response attachToPost(Long messageKey, String filename, InputStream file,  HttpServletRequest request) {
		//load message
		Message mess = fom.loadMessage(messageKey);
		if(mess == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		}
		if(!forum.equalsByPersistableKey(mess.getForum())) {
			return Response.serverError().status(Status.CONFLICT).build();
		}
		return attachToPost(mess, filename, file, request);
	}
//  [java]
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj instanceof ClassPathResource) {
            ClassPathResource otherRes = (ClassPathResource) obj;

            ClassLoader thisLoader = this.classLoader;
            ClassLoader otherLoader = otherRes.classLoader;

            return (this.path.equals(otherRes.path) &&
                    thisLoader.equals(otherLoader) &&
                    this.clazz.equals(otherRes.clazz));
        }
        return false;
    }
//  [java]
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj instanceof ClassPathResource) {
            ClassPathResource otherRes = (ClassPathResource) obj;

            ClassLoader thisLoader = this.classLoader;
            ClassLoader otherLoader = otherRes.classLoader;

            return (this.path.equals(otherRes.path) &&
                thisLoader.equals(otherLoader) &&
                this.clazz.equals(otherRes.clazz));
        }
        return false;
    }
//  [java]
    public void create() throws Exception {
        final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
        final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
        final Routes routes = mock(Routes.class);

        when(jettyServerFactory.create(100, 10, 10000)).thenReturn(new Server());

        final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory);
        embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);

        embeddedServer.ignite("localhost", 6757, null, 100, 10, 10000);

        verify(jettyServerFactory, times(1)).create(100, 10, 10000);
        verifyNoMoreInteractions(jettyServerFactory);
    }
//  [java]
    public void create() throws Exception {
        final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
        final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
        final Routes routes = mock(Routes.class);

        when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server());

        final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory);
        embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);

        embeddedServer.ignite("localhost", 8080, null, 100,10,10000);

        verify(jettyServerFactory, times(1)).create(100,10,10000);
        verifyNoMoreInteractions(jettyServerFactory);
    }
//  [java]
    public void create_withThreadPool() throws Exception {
        final QueuedThreadPool threadPool = new QueuedThreadPool(100);
        final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
        final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
        final Routes routes = mock(Routes.class);

        when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool));

        final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool);
        embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);

        embeddedServer.ignite("localhost", 6758, null, 0, 0, 0);

        verify(jettyServerFactory, times(1)).create(threadPool);
        verifyNoMoreInteractions(jettyServerFactory);
    }
//  [java]
    public void create_withThreadPool() throws Exception {
        final QueuedThreadPool threadPool = new QueuedThreadPool(100);
        final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
        final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
        final Routes routes = mock(Routes.class);

        when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool));

        final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool);
        embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);

        embeddedServer.ignite("localhost", 8080, null, 0,0,0);

        verify(jettyServerFactory, times(1)).create(threadPool);
        verifyNoMoreInteractions(jettyServerFactory);
    }
//  [java]
    public void translate(GeyserSession session, ServerDeclareTagsPacket packet) {
        session.getTagCache().loadPacket(packet);
    }
//  [java]
    public void translate(ServerDeclareTagsPacket packet, GeyserSession session) {
        session.getTagCache().loadPacket(packet);
    }
//  [java]
    public void create_withNullThreadPool() throws Exception {
        final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
        final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
        final Routes routes = mock(Routes.class);

        when(jettyServerFactory.create(100, 10, 10000)).thenReturn(new Server());

        final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null);
        embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);

        embeddedServer.ignite("localhost", 6759, null, 100, 10, 10000);

        verify(jettyServerFactory, times(1)).create(100, 10, 10000);
        verifyNoMoreInteractions(jettyServerFactory);
    }
//  [java]
    public void create_withNullThreadPool() throws Exception {
        final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
        final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
        final Routes routes = mock(Routes.class);

        when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server());

        final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null);
        embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);

        embeddedServer.ignite("localhost", 8080, null, 100,10,10000);

        verify(jettyServerFactory, times(1)).create(100,10,10000);
        verifyNoMoreInteractions(jettyServerFactory);
    }
//  [java]
    public void tearDown() throws Exception {
        if (embeddedServer != null) {
            embeddedServer.extinguish();
        }
    }
//  [java]
    public void tearDown() throws Exception {
        if(embeddedServer != null) embeddedServer.extinguish();
    }
//  [java]
	public static void closeSubsequentFS(Path path) {
		if(path != null && FileSystems.getDefault() != path.getFileSystem()) {
			IOUtils.closeQuietly(path.getFileSystem(), null);
		}
	}
//  [java]
	public static void closeSubsequentFS(Path path) {
		if(path != null && FileSystems.getDefault() != path.getFileSystem()) {
			IOUtils.closeQuietly(path.getFileSystem());
		}
	}
//  [java]
    public void translate(GeyserSession session, PlayerInputPacket packet) {
        ClientSteerVehiclePacket clientSteerVehiclePacket = new ClientSteerVehiclePacket(
                packet.getInputMotion().getX(), packet.getInputMotion().getY(), packet.isJumping(), packet.isSneaking()
        );

        session.sendDownstreamPacket(clientSteerVehiclePacket);

        // Bedrock only sends movement vehicle packets while moving
        // This allows horses to take damage while standing on magma
        Entity vehicle = session.getRidingVehicleEntity();
        boolean sendMovement = false;
        if (vehicle instanceof AbstractHorseEntity && !(vehicle instanceof LlamaEntity)) {
            sendMovement = vehicle.isOnGround();
        } else if (vehicle instanceof BoatEntity) {
            if (vehicle.getPassengers().size() == 1) {
                // The player is the only rider
                sendMovement = true;
            } else {
                // Check if the player is the front rider
                Vector3f seatPos = session.getPlayerEntity().getMetadata().getVector3f(EntityData.RIDER_SEAT_POSITION, null);
                if (seatPos != null && seatPos.getX() > 0) {
                    sendMovement = true;
                }
            }
        }
        if (sendMovement) {
            long timeSinceVehicleMove = System.currentTimeMillis() - session.getLastVehicleMoveTimestamp();
            if (timeSinceVehicleMove >= 100) {
                Vector3f vehiclePosition = vehicle.getPosition();
                Vector3f vehicleRotation = vehicle.getRotation();

                if (vehicle instanceof BoatEntity) {
                    // Remove some Y position to prevents boats flying up
                    vehiclePosition = vehiclePosition.down(EntityType.BOAT.getOffset());
                }

                ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket(
                        vehiclePosition.getX(), vehiclePosition.getY(), vehiclePosition.getZ(),
                        vehicleRotation.getX() - 90, vehicleRotation.getY()
                );
                session.sendDownstreamPacket(clientVehicleMovePacket);
            }
        }
    }
//  [java]
    public void translate(PlayerInputPacket packet, GeyserSession session) {
        ClientSteerVehiclePacket clientSteerVehiclePacket = new ClientSteerVehiclePacket(
                packet.getInputMotion().getX(), packet.getInputMotion().getY(), packet.isJumping(), packet.isSneaking()
        );

        session.sendDownstreamPacket(clientSteerVehiclePacket);

        // Bedrock only sends movement vehicle packets while moving
        // This allows horses to take damage while standing on magma
        Entity vehicle = session.getRidingVehicleEntity();
        boolean sendMovement = false;
        if (vehicle instanceof AbstractHorseEntity && !(vehicle instanceof LlamaEntity)) {
            sendMovement = vehicle.isOnGround();
        } else if (vehicle instanceof BoatEntity) {
            if (vehicle.getPassengers().size() == 1) {
                // The player is the only rider
                sendMovement = true;
            } else {
                // Check if the player is the front rider
                Vector3f seatPos = session.getPlayerEntity().getMetadata().getVector3f(EntityData.RIDER_SEAT_POSITION, null);
                if (seatPos != null && seatPos.getX() > 0) {
                    sendMovement = true;
                }
            }
        }
        if (sendMovement) {
            long timeSinceVehicleMove = System.currentTimeMillis() - session.getLastVehicleMoveTimestamp();
            if (timeSinceVehicleMove >= 100) {
                Vector3f vehiclePosition = vehicle.getPosition();
                Vector3f vehicleRotation = vehicle.getRotation();

                if (vehicle instanceof BoatEntity) {
                    // Remove some Y position to prevents boats flying up
                    vehiclePosition = vehiclePosition.down(EntityType.BOAT.getOffset());
                }

                ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket(
                        vehiclePosition.getX(), vehiclePosition.getY(), vehiclePosition.getZ(),
                        vehicleRotation.getX() - 90, vehicleRotation.getY()
                );
                session.sendDownstreamPacket(clientVehicleMovePacket);
            }
        }
    }
//  [java]
	public static Path visit(File file, String filename, FileVisitor<Path> visitor) 
	throws IOException, IllegalArgumentException {
		if(!StringHelper.containsNonWhitespace(filename)) {
			filename = file.getName();
		}
		
		Path fPath = null;
		if(file.isDirectory()) {
			fPath = file.toPath();
		} else if(filename != null && filename.toLowerCase().endsWith(".zip")) {
			try {
				fPath = FileSystems.newFileSystem(file.toPath(), null).getPath("/");
			} catch (ProviderNotFoundException | ServiceConfigurationError e) {
				throw new IOException("Unreadable file with .zip extension: " + file, e);
			}
		} else {
			fPath = file.toPath();
		}
		if(fPath != null) {
		    Files.walkFileTree(fPath, EnumSet.noneOf(FileVisitOption.class), 32, visitor);
		}
		return fPath;
	}
//  [java]
	public static Path visit(File file, String filename, FileVisitor<Path> visitor) 
	throws IOException, IllegalArgumentException {
		if(!StringHelper.containsNonWhitespace(filename)) {
			filename = file.getName();
		}
		
		Path fPath = null;
		if(file.isDirectory()) {
			fPath = file.toPath();
		} else if(filename != null && filename.toLowerCase().endsWith(".zip")) {
			try {
				fPath = FileSystems.newFileSystem(file.toPath(), null).getPath("/");
			} catch (ProviderNotFoundException | ServiceConfigurationError e) {
				throw new IOException("Unreadable file with .zip extension: " + file, e);
			}
		} else {
			fPath = file.toPath();
		}
		if(fPath != null) {
		    Files.walkFileTree(fPath, visitor);
		}
		return fPath;
	}
//  [java]
    public static void execute(String url, String modulePathInBaloCache, String moduleNameWithOrg, String proxyHost,
            int proxyPort, String proxyUsername, String proxyPassword, String supportedVersionRange, boolean isBuild,
            boolean isNightlyBuild, String langSpecVersion, String platform) {
        if (isBuild) {
            logFormatter = new BuildLogFormatter();
        }

        HttpsURLConnection conn = null;
        try {
            conn = createHttpsUrlConnection(convertToUrl(url + supportedVersionRange), proxyHost, proxyPort,
                                            proxyUsername, proxyPassword);

            conn.setInstanceFollowRedirects(false);
            setRequestMethod(conn, Utils.RequestMethod.GET);

            // Set headers
            conn.setRequestProperty(BALLERINA_PLATFORM, platform);
            conn.setRequestProperty(BAL_LANG_SPEC_VERSION, langSpecVersion);
            conn.setRequestProperty(HttpHeaders.ACCEPT_ENCODING, IDENTITY);

            boolean redirect = false;
            // 302 - Module is found
            // Other - Error occurred, json returned with the error message
            if (getStatusCode(conn) == HttpsURLConnection.HTTP_MOVED_TEMP) {
                redirect = true;
            } else {
                handleErrorResponse(conn, url, moduleNameWithOrg);
            }

            if (redirect) {
                // get redirect url from "location" header field
                String newUrl = conn.getHeaderField(HttpHeaders.LOCATION);
                String contentDisposition = conn.getHeaderField(HttpHeaders.CONTENT_DISPOSITION);

                conn = createHttpsUrlConnection(convertToUrl(newUrl), proxyHost, proxyPort, proxyUsername,
                                                proxyPassword);
                conn.setRequestProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);

                createBaloInHomeRepo(conn, modulePathInBaloCache, moduleNameWithOrg, isNightlyBuild, newUrl,
                        contentDisposition);
            }
        } catch (Exception e) {
            throw ErrorUtil.createCommandException(e.getMessage());
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            Authenticator.setDefault(null);
        }
    }
//  [java]
    public static void execute(String url, String modulePathInBaloCache, String moduleNameWithOrg, String proxyHost,
            int proxyPort, String proxyUsername, String proxyPassword, String supportedVersionRange, boolean isBuild,
            boolean isNightlyBuild, String langSpecVersion, String platform) {
        if (isBuild) {
            logFormatter = new BuildLogFormatter();
        }

        HttpURLConnection conn = null;
        try {
            initializeSsl();
            conn = createHttpUrlConnection(convertToUrl(url + supportedVersionRange), proxyHost, proxyPort,
                    proxyUsername, proxyPassword);

            conn.setInstanceFollowRedirects(false);
            setRequestMethod(conn, Utils.RequestMethod.GET);

            // Set headers
            conn.setRequestProperty(BALLERINA_PLATFORM, platform);
            conn.setRequestProperty(BAL_LANG_SPEC_VERSION, langSpecVersion);
            conn.setRequestProperty(HttpHeaders.ACCEPT_ENCODING, IDENTITY);

            boolean redirect = false;
            // 302 - Module is found
            // Other - Error occurred, json returned with the error message
            if (getStatusCode(conn) == HttpURLConnection.HTTP_MOVED_TEMP) {
                redirect = true;
            } else {
                handleErrorResponse(conn, url, moduleNameWithOrg);
            }

            if (redirect) {
                // get redirect url from "location" header field
                String newUrl = conn.getHeaderField(HttpHeaders.LOCATION);
                String contentDisposition = conn.getHeaderField(HttpHeaders.CONTENT_DISPOSITION);

                conn = createHttpUrlConnection(convertToUrl(newUrl), proxyHost, proxyPort, proxyUsername,
                        proxyPassword);
                conn.setRequestProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);

                createBaloInHomeRepo(conn, modulePathInBaloCache, moduleNameWithOrg, isNightlyBuild, newUrl,
                        contentDisposition);
            }
        } catch (Exception e) {
            throw ErrorUtil.createCommandException(e.getMessage());
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            Authenticator.setDefault(null);
        }
    }
//  [java]
    private static void handleErrorResponse(HttpsURLConnection conn, String url, String moduleFullName) {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) {
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            MapValue payload = (MapValue) JSONParser.parse(result.toString());
            createError("error: " + payload.getStringValue("message"));
        } catch (IOException e) {
            createError("failed to pull the module '" + moduleFullName + "' from the remote repository '" + url + "'");
        }
    }
//  [java]
    private static void handleErrorResponse(HttpURLConnection conn, String url, String moduleFullName) {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) {
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            MapValue payload = (MapValue) JSONParser.parse(result.toString());
            createError("error: " + payload.getStringValue("message"));
        } catch (IOException e) {
            createError("failed to pull the module '" + moduleFullName + "' from the remote repository '" + url + "'");
        }
    }
//  [java]
    private static void createBaloInHomeRepo(HttpsURLConnection conn, String modulePathInBaloCache,
            String moduleNameWithOrg, boolean isNightlyBuild, String newUrl, String contentDisposition) {
        long responseContentLength = conn.getContentLengthLong();
        if (responseContentLength <= 0) {
            createError("invalid response from the server, please try again");
        }
        String resolvedURI = conn.getHeaderField(RESOLVED_REQUESTED_URI);
        if (resolvedURI == null || resolvedURI.equals("")) {
            resolvedURI = newUrl;
        }
        String[] uriParts = resolvedURI.split("/");
        String moduleVersion = uriParts[uriParts.length - 3];

        validateModuleVersion(moduleVersion);
        String baloFile = getBaloFileName(contentDisposition, uriParts[uriParts.length - 1]);
        Path baloCacheWithModulePath = Paths.get(modulePathInBaloCache, moduleVersion);
        //<user.home>.ballerina/balo_cache/<org-name>/<module-name>/<module-version>

        Path baloPath = Paths.get(baloCacheWithModulePath.toString(), baloFile);
        if (baloPath.toFile().exists()) {
            createError("module already exists in the home repository: " + baloPath.toString());
        }

        createBaloFileDirectory(baloCacheWithModulePath);
        writeBaloFile(conn, baloPath, moduleNameWithOrg + ":" + moduleVersion, responseContentLength);
        handleNightlyBuild(isNightlyBuild, baloCacheWithModulePath);
    }