jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
	public int decryptWithAd(byte[] ad, byte[] ciphertext,
			int ciphertextOffset, byte[] plaintext, int plaintextOffset,
			int length) throws ShortBufferException, BadPaddingException {
		int space;
		if (ciphertextOffset > ciphertext.length)
			space = 0;
		else
			space = ciphertext.length - ciphertextOffset;
		if (length > space)
			throw new ShortBufferException();
		if (plaintextOffset > plaintext.length)
			space = 0;
		else
			space = plaintext.length - plaintextOffset;
		if (keySpec == null) {
			// The key is not set yet - return the ciphertext as-is.
			if (length > space)
				throw new ShortBufferException();
			if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
				System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
			return length;
		}
		if (length < 16)
			Noise.throwBadTagException();
		int dataLen = length - 16;
		if (dataLen > space)
			throw new ShortBufferException();
		try {
			setup(ad);
		} catch (InvalidKeyException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (InvalidAlgorithmParameterException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		}
		ghash.update(ciphertext, ciphertextOffset, dataLen);
		ghash.pad(ad != null ? ad.length : 0, dataLen);
		ghash.finish(iv, 0, 16);
		int temp = 0;
		for (int index = 0; index < 16; ++index)
			temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
		if ((temp & 0xFF) != 0)
			Noise.throwBadTagException();
		try {
			int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset);
			cipher.doFinal(plaintext, plaintextOffset + result);
		} catch (IllegalBlockSizeException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		} catch (BadPaddingException e) {
			// Shouldn't happen.
			throw new IllegalStateException(e);
		}
		return dataLen;
	}
//  [java]
    public HgVersion version() {
        CommandLine hg = createCommandLine("hg").withArgs("version").withEncoding("UTF-8");
        String hgOut = execute(hg, new NamedProcessTag("hg version check")).outputAsString();
        return HgVersion.parse(hgOut);
    }
//  [java]
    public HgVersion version() {
        CommandLine hg = createCommandLine("hg").withArgs("version").withEncoding("utf-8");
        String hgOut = execute(hg, new NamedProcessTag("hg version check")).outputAsString();
        return HgVersion.parse(hgOut);
    }
//  [java]
	private void doRequest(String method, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		try
		{
			int serviceId = 0;
			String proxyPath = "";
			String queryString = "";
			
			try 
			{
				if (request.getQueryString() != null)
				{
					queryString = "?" + request.getQueryString(); 	
				}
				
				if (request.getPathInfo() != null) // /{serviceId}/*
				{
					String[] pathParts = request.getPathInfo().split("/");
	
					if (pathParts.length > 1)
					{
						serviceId = Integer.parseInt(pathParts[1]);
					}
					
					if (pathParts.length > 2)
					{
						proxyPath = String.join("/", Arrays.copyOfRange(pathParts, 2, pathParts.length));
					}
					
					if (serviceId < 0 || serviceId > supportedServices.length)
					{
						serviceId = 0;
					}
				}
			}
			catch (Exception e) 
			{
				// Ignore and use 0
				serviceId = 0;
			}
			
			String exportUrl = System.getenv(supportedServices[serviceId]);
			
			if (exportUrl == null || exportUrl.isEmpty())
			{
				throw new Exception(supportedServices[serviceId] + " not set");
			}
			
			URL url = new URL(exportUrl + proxyPath + queryString);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			
			con.setRequestMethod(method);
			
			//Copy request headers to export server
			Enumeration<String> headerNames = request.getHeaderNames();
			 
	        while (headerNames.hasMoreElements()) 
	        {
	            String headerName = headerNames.nextElement();
	            Enumeration<String> headers = request.getHeaders(headerName);
	            
	            while (headers.hasMoreElements()) 
	            {
	                String headerValue = headers.nextElement();
	                con.addRequestProperty(headerName, headerValue);
	            }
	        }
	        
	        if ("POST".equals(method))
	        {
				// Send post request
				con.setDoOutput(true);
				
				OutputStream params = con.getOutputStream();
				Utils.copy(request.getInputStream(), params);
				params.flush();
				params.close();
	        }
	        
	        int responseCode = con.getResponseCode();
			//Copy response code
			response.setStatus(responseCode);
			
			//Copy response headers
			Map<String, List<String>> map = con.getHeaderFields();
			
			for (Map.Entry<String, List<String>> entry : map.entrySet()) 
			{
				String key = entry.getKey();
				
				if (key != null)
				{
					for (String val : entry.getValue())
					{	
						
						response.addHeader(entry.getKey(), val);
					}
				}
			}
			
			//Copy response
			OutputStream out = response.getOutputStream();
			
			//Error
			if (responseCode >= 400)
			{
				Utils.copy(con.getErrorStream(), out);
			}
			else //Success
			{
				Utils.copy(con.getInputStream(), out);
			}
			
			out.flush();
			out.close();
		}
		catch (Exception e)
		{
			response.setStatus(
					HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			e.printStackTrace();
		}
	}
//  [java]
    private Template getClassloaderTemplate(ClassLoader classloader, String prefixPath, String templateName)
    {
        String templatePath = prefixPath + templateName;

        // Prevent access to resources from other directories
        Path normalizedResource = Paths.get(templatePath).normalize();
        // Protect against directory attacks.
        if (!normalizedResource.startsWith(prefixPath)) {
            this.logger.warn("Direct access to skin file [{}] refused. Possible break-in attempt!", normalizedResource);

            return null;
        }

        URL url = classloader.getResource(templatePath);

        return url != null ? new ClassloaderTemplate(new ClassloaderResource(url, templateName)) : null;
    }
//  [java]
    private Template getClassloaderTemplate(String suffixPath, String templateName)
    {
        return getClassloaderTemplate(Thread.currentThread().getContextClassLoader(), suffixPath, templateName);
    }
//  [java]
    public void getLogFile(@PathVariable("filename") String fileName, HttpServletResponse response) throws Exception {
        InputStream inputStream = null;
        try {
        	//Validate/Sanitize user input filename using a standard library, prevent from path traversal 
            String logFilePath = getFilePath() + File.separator;
            File fileToDownload = new File(logFilePath, fileName);                    
            String canonicalPath= fileToDownload.getCanonicalPath();
            
            if (canonicalPath.startsWith(logFilePath)) {
            	inputStream = new FileInputStream(fileToDownload);
                response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                IOUtils.copy(inputStream, response.getOutputStream());
                response.flushBuffer();
            }else {
            	throw new RuntimeException("Traversal attempt - file path not allowed " + fileName);
            }
            
        } catch (Exception e) {
            logger.debug("Request could not be completed at this moment. Please try again.");
            logger.debug(e.getStackTrace().toString());
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.debug(e.getStackTrace().toString());
                    throw e;
                }
            }
        }

    }
//  [java]
    public void getLogFile(@PathVariable("filename") String fileName, HttpServletResponse response) throws Exception {
        InputStream inputStream = null;
        try {
        	//Validate/Sanitize user input filename using a standard library, prevent from path traversal 
            String logFileName = getFilePath() + File.separator + FilenameUtils.getName(fileName);
            File fileToDownload = new File(logFileName);
            inputStream = new FileInputStream(fileToDownload);
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            logger.debug("Request could not be completed at this moment. Please try again.");
            logger.debug(e.getStackTrace().toString());
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.debug(e.getStackTrace().toString());
                    throw e;
                }
            }
        }

    }
//  [java]
		private void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) {
			final Point2D corner = getPosition(elkNode);
			final URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight());

			PackageStyle packageStyle = group.getPackageStyle();
			final ISkinParam skinParam = diagram.getSkinParam();
			if (packageStyle == null)
				packageStyle = skinParam.packageStyle();

			final UmlDiagramType umlDiagramType = diagram.getUmlDiagramType();

			final Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol())
					.getMergedStyle(skinParam.getCurrentStyleBuilder());
			final double shadowing = style.value(PName.Shadowing).asDouble();
			final UStroke stroke = Cluster.getStrokeInternal(group, style);

			HColor backColor = getBackColor(umlDiagramType);
			backColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(), umlDiagramType.getStyleName(),
					group.getUSymbol());

			final double roundCorner = group.getUSymbol() == null ? 0
					: group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype());

			final TextBlock ztitle = getTitleBlock(group);
			final TextBlock zstereo = TextBlockUtils.empty(0, 0);

			final ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle,
					zstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke);

			final HColor borderColor = HColorUtils.BLACK;
			decoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner,
					skinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null),
					skinParam.getStereotypeAlignment(), 0);

//			// Print a simple rectangle right now
//			ug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect);
		}
//  [java]
		private void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) {
			final Point2D corner = getPosition(elkNode);
			final URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight());

			PackageStyle packageStyle = group.getPackageStyle();
			final ISkinParam skinParam = diagram.getSkinParam();
			if (packageStyle == null)
				packageStyle = skinParam.packageStyle();

			final UmlDiagramType umlDiagramType = diagram.getUmlDiagramType();

			final Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol())
					.getMergedStyle(skinParam.getCurrentStyleBuilder());
			final double shadowing = style.value(PName.Shadowing).asDouble();
			final UStroke stroke = Cluster.getStrokeInternal(group, skinParam, style);

			HColor backColor = getBackColor(umlDiagramType);
			backColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(), umlDiagramType.getStyleName(),
					group.getUSymbol());

			final double roundCorner = group.getUSymbol() == null ? 0
					: group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype());

			final TextBlock ztitle = getTitleBlock(group);
			final TextBlock zstereo = TextBlockUtils.empty(0, 0);

			final ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle,
					zstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke);

			final HColor borderColor = HColorUtils.BLACK;
			decoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner,
					skinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null),
					skinParam.getStereotypeAlignment(), 0);

//			// Print a simple rectangle right now
//			ug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect);
		}
//  [java]
    public void translate(GeyserSession session, ServerChatPacket packet) {
        TextPacket textPacket = new TextPacket();
        textPacket.setPlatformChatId("");
        textPacket.setSourceName("");
        textPacket.setXuid(session.getAuthData().getXboxUUID());
        switch (packet.getType()) {
            case CHAT:
                textPacket.setType(TextPacket.Type.CHAT);
                break;
            case SYSTEM:
                textPacket.setType(TextPacket.Type.SYSTEM);
                break;
            case NOTIFICATION:
                textPacket.setType(TextPacket.Type.TIP);
                break;
            default:
                textPacket.setType(TextPacket.Type.RAW);
                break;
        }

        textPacket.setNeedsTranslation(false);
        textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale()));

        session.sendUpstreamPacket(textPacket);
    }
//  [java]
    public void translate(ServerChatPacket packet, GeyserSession session) {
        TextPacket textPacket = new TextPacket();
        textPacket.setPlatformChatId("");
        textPacket.setSourceName("");
        textPacket.setXuid(session.getAuthData().getXboxUUID());
        switch (packet.getType()) {
            case CHAT:
                textPacket.setType(TextPacket.Type.CHAT);
                break;
            case SYSTEM:
                textPacket.setType(TextPacket.Type.SYSTEM);
                break;
            case NOTIFICATION:
                textPacket.setType(TextPacket.Type.TIP);
                break;
            default:
                textPacket.setType(TextPacket.Type.RAW);
                break;
        }

        textPacket.setNeedsTranslation(false);
        textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale()));

        session.sendUpstreamPacket(textPacket);
    }
//  [java]
	private void parse(UserRequest ureq) {
		String[] sFiles = ureq.getHttpReq().getParameterValues(FORM_ID);
		if (sFiles == null || sFiles.length == 0) {
			return;
		}
		List<VFSItem> items = currentContainer.getItems();
		if(items != null && !items.isEmpty()) {
			Set<String> itemNames =  items.stream()
					.map(VFSItem::getName)
					.collect(Collectors.toSet());
			for(String sFile:sFiles) {
				if(itemNames.contains(sFile)) {
					files.add(sFile);
				}
			}
		}
	}
//  [java]
	private void parse(UserRequest ureq) {
		String[] sFiles = ureq.getHttpReq().getParameterValues(FORM_ID);
		if (sFiles == null || sFiles.length == 0) return;
		files = Arrays.asList(sFiles);
	}
//  [java]
    public void translate(GeyserSession session, ServerOpenWindowPacket packet) {
        if (packet.getWindowId() == 0) {
            return;
        }

        InventoryTranslator newTranslator = InventoryTranslator.INVENTORY_TRANSLATORS.get(packet.getType());
        Inventory openInventory = session.getOpenInventory();
        //No translator exists for this window type. Close all windows and return.
        if (newTranslator == null) {
            if (openInventory != null) {
                InventoryUtils.closeInventory(session, openInventory.getId(), true);
            }
            ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(packet.getWindowId());
            session.sendDownstreamPacket(closeWindowPacket);
            return;
        }

        String name = MessageTranslator.convertMessageLenient(packet.getName(), session.getLocale());
        name = LocaleUtils.getLocaleString(name, session.getLocale());

        Inventory newInventory = newTranslator.createInventory(name, packet.getWindowId(), packet.getType(), session.getPlayerInventory());
        if (openInventory != null) {
            // If the window type is the same, don't close.
            // In rare cases, inventories can do funny things where it keeps the same window type up but change the contents.
            if (openInventory.getWindowType() != packet.getType()) {
                // Sometimes the server can double-open an inventory with the same ID - don't confirm in that instance.
                InventoryUtils.closeInventory(session, openInventory.getId(), openInventory.getId() != packet.getWindowId());
            }
        }

        session.setInventoryTranslator(newTranslator);
        InventoryUtils.openInventory(session, newInventory);
    }
//  [java]
    public void translate(ServerOpenWindowPacket packet, GeyserSession session) {
        if (packet.getWindowId() == 0) {
            return;
        }

        InventoryTranslator newTranslator = InventoryTranslator.INVENTORY_TRANSLATORS.get(packet.getType());
        Inventory openInventory = session.getOpenInventory();
        //No translator exists for this window type. Close all windows and return.
        if (newTranslator == null) {
            if (openInventory != null) {
                InventoryUtils.closeInventory(session, openInventory.getId(), true);
            }
            ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(packet.getWindowId());
            session.sendDownstreamPacket(closeWindowPacket);
            return;
        }

        String name = MessageTranslator.convertMessageLenient(packet.getName(), session.getLocale());
        name = LocaleUtils.getLocaleString(name, session.getLocale());

        Inventory newInventory = newTranslator.createInventory(name, packet.getWindowId(), packet.getType(), session.getPlayerInventory());
        if (openInventory != null) {
            // If the window type is the same, don't close.
            // In rare cases, inventories can do funny things where it keeps the same window type up but change the contents.
            if (openInventory.getWindowType() != packet.getType()) {
                // Sometimes the server can double-open an inventory with the same ID - don't confirm in that instance.
                InventoryUtils.closeInventory(session, openInventory.getId(), openInventory.getId() != packet.getWindowId());
            }
        }

        session.setInventoryTranslator(newTranslator);
        InventoryUtils.openInventory(session, newInventory);
    }
//  [java]
	public FileSelection(UserRequest ureq, VFSContainer currentContainer, String currentContainerRelPath) {
		if (currentContainerRelPath.equals("/")) currentContainerRelPath = "";
		this.currentContainerRelPath = currentContainerRelPath;
		this.currentContainer = currentContainer;
		parse(ureq);
	}
//  [java]
	public FileSelection(UserRequest ureq, String currentContainerRelPath) {
		if (currentContainerRelPath.equals("/")) currentContainerRelPath = "";
		this.currentContainerRelPath = currentContainerRelPath;
		parse(ureq);
	}
//  [java]
    public int clone(ConsoleOutputStreamConsumer outputStreamConsumer, UrlArgument repositoryUrl) {
        CommandLine hg = createCommandLine("hg")
                .withArgs("clone")
                .withArg(branchArg())
                .withArg("--")
                .withArg(repositoryUrl)
                .withArg(workingDir.getAbsolutePath())
                .withNonArgSecrets(secrets)
                .withEncoding("UTF-8");
        return execute(hg, outputStreamConsumer);
    }
//  [java]
    public int clone(ConsoleOutputStreamConsumer outputStreamConsumer, UrlArgument repositoryUrl) {
        CommandLine hg = createCommandLine("hg").withArgs("clone").withArg("-b").withArg(branch).withArg(repositoryUrl)
                .withArg(workingDir.getAbsolutePath()).withNonArgSecrets(secrets).withEncoding("utf-8");
        return execute(hg, outputStreamConsumer);
    }
//  [java]
    public void translate(GeyserSession session, ServerSetSlotPacket packet) {
        if (packet.getWindowId() == 255) { //cursor
            GeyserItemStack newItem = GeyserItemStack.from(packet.getItem());
            session.getPlayerInventory().setCursor(newItem, session);
            InventoryUtils.updateCursor(session);
            return;
        }

        //TODO: support window id -2, should update player inventory
        Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
        if (inventory == null)
            return;

        inventory.setStateId(packet.getStateId());

        InventoryTranslator translator = session.getInventoryTranslator();
        if (translator != null) {
            if (session.getCraftingGridFuture() != null) {
                session.getCraftingGridFuture().cancel(false);
            }
            session.setCraftingGridFuture(session.scheduleInEventLoop(() -> updateCraftingGrid(session, packet, inventory, translator), 150, TimeUnit.MILLISECONDS));

            GeyserItemStack newItem = GeyserItemStack.from(packet.getItem());
            if (packet.getWindowId() == 0 && !(translator instanceof PlayerInventoryTranslator)) {
                // In rare cases, the window ID can still be 0 but Java treats it as valid
                session.getPlayerInventory().setItem(packet.getSlot(), newItem, session);
                InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR.updateSlot(session, session.getPlayerInventory(), packet.getSlot());
            } else {
                inventory.setItem(packet.getSlot(), newItem, session);
                translator.updateSlot(session, inventory, packet.getSlot());
            }
        }
    }
//  [java]
    public void translate(ServerSetSlotPacket packet, GeyserSession session) {
        if (packet.getWindowId() == 255) { //cursor
            GeyserItemStack newItem = GeyserItemStack.from(packet.getItem());
            session.getPlayerInventory().setCursor(newItem, session);
            InventoryUtils.updateCursor(session);
            return;
        }

        //TODO: support window id -2, should update player inventory
        Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
        if (inventory == null)
            return;

        inventory.setStateId(packet.getStateId());

        InventoryTranslator translator = session.getInventoryTranslator();
        if (translator != null) {
            if (session.getCraftingGridFuture() != null) {
                session.getCraftingGridFuture().cancel(false);
            }
            session.setCraftingGridFuture(session.scheduleInEventLoop(() -> updateCraftingGrid(session, packet, inventory, translator), 150, TimeUnit.MILLISECONDS));

            GeyserItemStack newItem = GeyserItemStack.from(packet.getItem());
            if (packet.getWindowId() == 0 && !(translator instanceof PlayerInventoryTranslator)) {
                // In rare cases, the window ID can still be 0 but Java treats it as valid
                session.getPlayerInventory().setItem(packet.getSlot(), newItem, session);
                InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR.updateSlot(session, session.getPlayerInventory(), packet.getSlot());
            } else {
                inventory.setItem(packet.getSlot(), newItem, session);
                translator.updateSlot(session, inventory, packet.getSlot());
            }
        }
    }
//  [java]
    protected HtmlRenderable htmlBody() {
        return HtmlElement.li().content(
            HtmlElement.span(HtmlAttribute.cssClass("artifact")).content(
                HtmlElement.a(HtmlAttribute.href(getUrl()))
                        .safecontent(getFileName())
            )
        );

    }
//  [java]
    protected HtmlRenderable htmlBody() {
        return HtmlElement.li().content(
            HtmlElement.span(HtmlAttribute.cssClass("artifact")).content(
                HtmlElement.a(HtmlAttribute.href(getUrl()))
                        .content(getFileName())
            )
        );

    }
//  [java]
    public static void main(String[] args) throws LifecycleException {
        String webappDirLocation;
        if (Constants.IN_JAR) {
            webappDirLocation = "webapp";
        } else {
            webappDirLocation = "src/main/webapp/";
        }

        Tomcat tomcat = new Tomcat();

        String webPort = System.getenv("PORT");
        if (webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }

        tomcat.setPort(Integer.parseInt(webPort));
        tomcat.getConnector();

        // Declare an alternative location for your "WEB-INF/classes" dir
        // Servlet 3.0 annotation will work
        File additionWebInfClasses;
        if (Constants.IN_JAR) {
            additionWebInfClasses = new File("");
        } else {
            additionWebInfClasses = new File("target/classes");
        }

        tomcat.setBaseDir(additionWebInfClasses.toString());
        //idea的路径eclipse启动的路径有区别
        if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) {
            webappDirLocation = "web/" + webappDirLocation;
        }
        tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
        tomcat.start();
        tomcat.getServer().await();
    }
//  [java]
    public static void main(String[] args) throws LifecycleException {
        String webappDirLocation;
        if (Constants.IN_JAR) {
            webappDirLocation = "webapp";
        } else {
            webappDirLocation = "src/main/webapp/";
        }

        Tomcat tomcat = new Tomcat();

        String webPort = System.getenv("PORT");
        if (webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }

        tomcat.setPort(Integer.valueOf(webPort));
        tomcat.getConnector();

        // Declare an alternative location for your "WEB-INF/classes" dir
        // Servlet 3.0 annotation will work
        File additionWebInfClasses;
        if (Constants.IN_JAR) {
            additionWebInfClasses = new File("");
        } else {
            additionWebInfClasses = new File("target/classes");
        }

        tomcat.setBaseDir(additionWebInfClasses.toString());
        //idea的路径eclipse启动的路径有区别
        if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) {
            webappDirLocation = "web/" + webappDirLocation;
        }
        tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
        tomcat.start();
        tomcat.getServer().await();
    }
//  [java]
    public void translate(GeyserSession session, ServerPlayerActionAckPacket packet) {
        ChunkUtils.updateBlock(session, packet.getNewState(), packet.getPosition());
        if (packet.getAction() == PlayerAction.START_DIGGING && !packet.isSuccessful()) {
            LevelEventPacket stopBreak = new LevelEventPacket();
            stopBreak.setType(LevelEventType.BLOCK_STOP_BREAK);
            stopBreak.setPosition(Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));
            stopBreak.setData(0);
            session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID);
            session.sendUpstreamPacket(stopBreak);
        }
    }
//  [java]
    public void translate(ServerPlayerActionAckPacket packet, GeyserSession session) {
        ChunkUtils.updateBlock(session, packet.getNewState(), packet.getPosition());
        if (packet.getAction() == PlayerAction.START_DIGGING && !packet.isSuccessful()) {
            LevelEventPacket stopBreak = new LevelEventPacket();
            stopBreak.setType(LevelEventType.BLOCK_STOP_BREAK);
            stopBreak.setPosition(Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));
            stopBreak.setData(0);
            session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID);
            session.sendUpstreamPacket(stopBreak);
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerStopSoundPacket packet) {
        // Runs if all sounds are stopped
        if (packet.getSound() == null) {
            StopSoundPacket stopPacket = new StopSoundPacket();
            stopPacket.setStoppingAllSound(true);
            stopPacket.setSoundName("");
            session.sendUpstreamPacket(stopPacket);
            return;
        }

        String packetSound;
        if (packet.getSound() instanceof BuiltinSound) {
            packetSound = ((BuiltinSound) packet.getSound()).getName();
        } else if (packet.getSound() instanceof CustomSound) {
            packetSound = ((CustomSound) packet.getSound()).getName();
        } else {
            session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString());
            return;
        }
        SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", ""));
        session.getConnector().getLogger()
                .debug("[StopSound] Sound mapping " + packetSound + " -> "
                        + soundMapping + (soundMapping == null ? "[not found]" : "")
                        + " - " + packet.toString());
        String playsound;
        if (soundMapping == null || soundMapping.getPlaysound() == null) {
            // no mapping
            session.getConnector().getLogger()
                    .debug("[StopSound] Defaulting to sound server gave us.");
            playsound = packetSound;
        } else {
            playsound = soundMapping.getPlaysound();
        }

        StopSoundPacket stopSoundPacket = new StopSoundPacket();
        stopSoundPacket.setSoundName(playsound);
        // packet not mapped in the library
        stopSoundPacket.setStoppingAllSound(false);

        session.sendUpstreamPacket(stopSoundPacket);
        session.getConnector().getLogger().debug("[StopSound] Packet sent - " + packet.toString() + " --> " + stopSoundPacket);
    }
//  [java]
    public void translate(ServerStopSoundPacket packet, GeyserSession session) {
        // Runs if all sounds are stopped
        if (packet.getSound() == null) {
            StopSoundPacket stopPacket = new StopSoundPacket();
            stopPacket.setStoppingAllSound(true);
            stopPacket.setSoundName("");
            session.sendUpstreamPacket(stopPacket);
            return;
        }

        String packetSound;
        if (packet.getSound() instanceof BuiltinSound) {
            packetSound = ((BuiltinSound) packet.getSound()).getName();
        } else if (packet.getSound() instanceof CustomSound) {
            packetSound = ((CustomSound) packet.getSound()).getName();
        } else {
            session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString());
            return;
        }
        SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", ""));
        session.getConnector().getLogger()
                .debug("[StopSound] Sound mapping " + packetSound + " -> "
                        + soundMapping + (soundMapping == null ? "[not found]" : "")
                        + " - " + packet.toString());
        String playsound;
        if (soundMapping == null || soundMapping.getPlaysound() == null) {
            // no mapping
            session.getConnector().getLogger()
                    .debug("[StopSound] Defaulting to sound server gave us.");
            playsound = packetSound;
        } else {
            playsound = soundMapping.getPlaysound();
        }

        StopSoundPacket stopSoundPacket = new StopSoundPacket();
        stopSoundPacket.setSoundName(playsound);
        // packet not mapped in the library
        stopSoundPacket.setStoppingAllSound(false);

        session.sendUpstreamPacket(stopSoundPacket);
        session.getConnector().getLogger().debug("[StopSound] Packet sent - " + packet.toString() + " --> " + stopSoundPacket);
    }
//  [java]
	public void checkAccess(Thread t) {
		if (RobocodeProperties.isSecurityOff()) {
			return;
		}

		Thread c = Thread.currentThread();
		if (isSafeThread(c)) {
			return;
		}
		super.checkAccess(t);

		// Threads belonging to other thread groups is not allowed to access threads belonging to other thread groups
		// Bug fix [3021140] Possible for robot to kill other robot threads.
		// In the following the thread group of the current thread must be in the thread group hierarchy of the
		// attacker thread; otherwise an AccessControlException must be thrown.

		boolean found = false;
		
		ThreadGroup cg = c.getThreadGroup();
		ThreadGroup tg = t.getThreadGroup();

		while (tg != null) {
			if (tg == cg) {
				found = true;
				break;
			}
			try {
				tg = tg.getParent();
			} catch (AccessControlException e) {
				// We expect an AccessControlException due to missing RuntimePermission modifyThreadGroup
				break;
			}
		}
		if (!found) {
			String message = "Preventing " + c.getName() + " from access to " + t.getName();
			IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);

			if (robotProxy != null) {
				robotProxy.punishSecurityViolation(message);
			}
			throw new SecurityException(message);
		}
	}
//  [java]
	public void checkAccess(Thread t) {
		if (RobocodeProperties.isSecurityOff()) {
			return;
		}

		Thread c = Thread.currentThread();

		if (isSafeThread(c)) {
			return;
		}
		super.checkAccess(t);

		// Threads belonging to other thread groups is not allowed to access threads belonging to other thread groups
		// Bug fix [3021140] Possible for robot to kill other robot threads.
		// In the following the thread group of the current thread must be in the thread group hierarchy of the
		// attacker thread; otherwise an AccessControlException must be thrown.

		boolean found = false;
		
		ThreadGroup cg = c.getThreadGroup();
		ThreadGroup tg = t.getThreadGroup();

		while (tg != null) {
			if (tg == cg) {
				found = true;
				break;
			}
			try {
				tg = tg.getParent();
			} catch (AccessControlException e) {
				// We expect an AccessControlException due to missing RuntimePermission modifyThreadGroup
				break;
			}
		}
		if (!found) {
			String message = "Preventing " + c.getName() + " from access to " + t.getName();
			IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);

			if (robotProxy != null) {
				robotProxy.punishSecurityViolation(message);
			}
			throw new AccessControlException(message);
		}
	}
//  [java]
    public void add(File fileToAdd) {
        String[] args = new String[]{"add", "--", fileToAdd.getName()};
        CommandLine gitAdd = gitWd().withArgs(args);
        runOrBomb(gitAdd);
    }
//  [java]
    public void add(File fileToAdd) {
        String[] args = new String[]{"add", fileToAdd.getName()};
        CommandLine gitAdd = gitWd().withArgs(args);
        runOrBomb(gitAdd);
    }
//  [java]
	public static int version() {
		return 1202205;
	}
//  [java]
	public static int version() {
		return 1202204;
	}
//  [java]
	public static long compileTime() {
		return 1651316152000L;
	}
//  [java]
	public static long compileTime() {
		return 1649510957985L;
	}
//  [java]
    public void checkConnection(UrlArgument repoUrl) {
        final String ref = fullUpstreamRef();
        final CommandLine commandLine = git().withArgs("ls-remote", "--").withArg(repoUrl).withArg(ref);
        final ConsoleResult result = commandLine.runOrBomb(new NamedProcessTag(repoUrl.forDisplay()));

        if (!hasExactlyOneMatchingBranch(result)) {
            throw new CommandLineException(format("The ref %s could not be found.", ref));
        }
    }
//  [java]
    public void checkConnection(UrlArgument repoUrl) {
        final String ref = fullUpstreamRef();
        final CommandLine commandLine = git().withArgs("ls-remote").withArg(repoUrl).withArg(ref);
        final ConsoleResult result = commandLine.runOrBomb(new NamedProcessTag(repoUrl.forDisplay()));

        if (!hasExactlyOneMatchingBranch(result)) {
            throw new CommandLineException(format("The ref %s could not be found.", ref));
        }
    }
//  [java]
    public void submoduleAdd(String repoUrl, String submoduleNameToPutInGitSubmodules, String folder) {
        String[] addSubmoduleWithSameNameArgs = new String[]{"submodule", "add", "--", repoUrl, folder};
        String[] changeSubmoduleNameInGitModules = new String[]{"config", "--file", ".gitmodules", "--rename-section", "submodule." + folder, "submodule." + submoduleNameToPutInGitSubmodules};
        String[] addGitModules = new String[]{"add", ".gitmodules"};

        runOrBomb(gitWd().withArgs(addSubmoduleWithSameNameArgs));
        runOrBomb(gitWd().withArgs(changeSubmoduleNameInGitModules));
        runOrBomb(gitWd().withArgs(addGitModules));
    }
//  [java]
    public void submoduleAdd(String repoUrl, String submoduleNameToPutInGitSubmodules, String folder) {
        String[] addSubmoduleWithSameNameArgs = new String[]{"submodule", "add", repoUrl, folder};
        String[] changeSubmoduleNameInGitModules = new String[]{"config", "--file", ".gitmodules", "--rename-section", "submodule." + folder, "submodule." + submoduleNameToPutInGitSubmodules};
        String[] addGitModules = new String[]{"add", ".gitmodules"};

        runOrBomb(gitWd().withArgs(addSubmoduleWithSameNameArgs));
        runOrBomb(gitWd().withArgs(changeSubmoduleNameInGitModules));
        runOrBomb(gitWd().withArgs(addGitModules));
    }
//  [java]
	public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
	throws IOException {
		Path relativeDir = source.relativize(dir);
		final Path dirToCreate = Paths.get(destDir.toString(), relativeDir.toString());
		checkPath(dirToCreate);
       
        if(!dirToCreate.toFile().exists()) {
        	Files.createDirectory(dirToCreate);
        }
        return FileVisitResult.CONTINUE;
	}
//  [java]
	public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
	throws IOException {
		Path relativeDir = source.relativize(dir);
        final Path dirToCreate = Paths.get(destDir.toString(), relativeDir.toString());
        if(!dirToCreate.toFile().exists()) {
        	Files.createDirectory(dirToCreate);
        }
        return FileVisitResult.CONTINUE;
	}
//  [java]
    public CorsChecker(Document pDoc) {
        NodeList corsNodes = pDoc.getElementsByTagName("cors");
        if (corsNodes.getLength() > 0) {
            patterns = new ArrayList<Pattern>();
            for (int i = 0; i < corsNodes.getLength(); i++) {
                Node corsNode = corsNodes.item(i);
                NodeList nodes = corsNode.getChildNodes();
                for (int j = 0;j <nodes.getLength();j++) {
                    Node node = nodes.item(j);
                    if (node.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    assertNodeName(node,"allow-origin","strict-checking");
                    if (node.getNodeName().equals("allow-origin")) {
                        String p = node.getTextContent().trim().toLowerCase();
                        p = Pattern.quote(p).replace("*", "\\E.*\\Q");
                        patterns.add(Pattern.compile("^" + p + "$"));
                    } else if (node.getNodeName().equals("strict-checking")) {
                        strictChecking = true;
                    }
                }
            }
        }
    }
//  [java]
    public CorsChecker(Document pDoc) {
        NodeList corsNodes = pDoc.getElementsByTagName("cors");
        if (corsNodes.getLength() > 0) {
            patterns = new ArrayList<Pattern>();
            for (int i = 0; i < corsNodes.getLength(); i++) {
                Node corsNode = corsNodes.item(i);
                NodeList nodes = corsNode.getChildNodes();
                for (int j = 0;j <nodes.getLength();j++) {
                    Node node = nodes.item(j);
                    if (node.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    assertNodeName(node,"allow-origin");
                    String p = node.getTextContent().trim().toLowerCase();
                    p = Pattern.quote(p).replace("*","\\E.*\\Q");
                    patterns.add(Pattern.compile("^" + p + "$"));
                }
            }
        }
    }
//  [java]
    public static String decodePath(String path) {
        if (path.indexOf('%') < 0) {
            // No need to decode because it's not percent-encoded
            return path;
        }

        // Decode percent-encoded characters, but don't decode %2F into /, so that a user can choose
        // to use it as a non-separator.
        //
        // For example, for the path pattern `/orgs/{org_name}/agents/{agent_name}`:
        // - orgs/mi6/agents/ethan-hunt
        //   - org_name: mi6
        //   - agent_name: ethan-hunt
        // - orgs/mi%2F6/agents/ethan-hunt
        //   - org_name: mi/6
        //   - agent_name: ethan-hunt
        return slowDecodePath(path, false);
    }
//  [java]
    public static String decodePath(String path) {
        if (path.indexOf('%') < 0) {
            // No need to decoded; not percent-encoded
            return path;
        }

        // Decode percent-encoded characters.
        // An invalid character is replaced with 0xFF, which will be replaced into '�' by UTF-8 decoder.
        final int len = path.length();
        try (TemporaryThreadLocals tempThreadLocals = TemporaryThreadLocals.acquire()) {
            final byte[] buf = tempThreadLocals.byteArray(len);
            int dstLen = 0;
            for (int i = 0; i < len; i++) {
                final char ch = path.charAt(i);
                if (ch != '%') {
                    buf[dstLen++] = (byte) ((ch & 0xFF80) == 0 ? ch : 0xFF);
                    continue;
                }

                // Decode a percent-encoded character.
                final int hexEnd = i + 3;
                if (hexEnd > len) {
                    // '%' or '%x' (must be followed by two hexadigits)
                    buf[dstLen++] = (byte) 0xFF;
                    break;
                }

                final int digit1 = decodeHexNibble(path.charAt(++i));
                final int digit2 = decodeHexNibble(path.charAt(++i));
                if (digit1 < 0 || digit2 < 0) {
                    // The first or second digit is not hexadecimal.
                    buf[dstLen++] = (byte) 0xFF;
                } else {
                    buf[dstLen++] = (byte) ((digit1 << 4) | digit2);
                }
            }

            return new String(buf, 0, dstLen, StandardCharsets.UTF_8);
        }
    }
//  [java]
    public void translate(GeyserSession session, FilterTextPacket packet) {
        if (session.getOpenInventory() instanceof CartographyContainer) {
            // We don't want to be able to rename in the cartography table
            return;
        }
        packet.setFromServer(true);
        session.sendUpstreamPacket(packet);

        if (session.getOpenInventory() instanceof AnvilContainer) {
            // Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now
            ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());
            session.sendDownstreamPacket(renameItemPacket);
        }
    }
//  [java]
    public void translate(FilterTextPacket packet, GeyserSession session) {
        if (session.getOpenInventory() instanceof CartographyContainer) {
            // We don't want to be able to rename in the cartography table
            return;
        }
        packet.setFromServer(true);
        session.sendUpstreamPacket(packet);

        if (session.getOpenInventory() instanceof AnvilContainer) {
            // Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now
            ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());
            session.sendDownstreamPacket(renameItemPacket);
        }
    }
//  [java]
    private static final RestrictorCheck CORS_CHECK = new RestrictorCheck() {
        /** {@inheritDoc} */
        public boolean check(Restrictor restrictor, Object... args) {
            return restrictor.isOriginAllowed((String) args[0], (Boolean) args[1]);
        }
    };
//  [java]
    private static final RestrictorCheck CORS_CHECK = new RestrictorCheck() {
        /** {@inheritDoc} */
        public boolean check(Restrictor restrictor, Object... args) {
            return restrictor.isCorsAccessAllowed((String) args[0]);
        }
    };
//  [java]
	public String render(String templateContent, Map<String, Object> context) throws TemplateRenderException {
		VelocityContext velocityContext = new VelocityContext(context);
		try (StringWriter sw = new StringWriter()) {
			Velocity.evaluate(velocityContext, sw, "velocityTemplateEngine", templateContent);
			return sw.toString();
		}
		catch (Exception ex) {
			throw new TemplateRenderException(ex);
		}
	}
//  [java]
	public String render(String templateContent, Map<String, Object> context) {
		VelocityContext velocityContext = new VelocityContext(context);
		try (StringWriter sw = new StringWriter()) {
			Velocity.evaluate(velocityContext, sw, "velocityTemplateEngine", templateContent);
			return sw.toString();
		}
		catch (Exception ex) {
			throw new TemplateRenderException(ex);
		}
	}
//  [java]
    public void translate(GeyserSession session, MobEquipmentPacket packet) {
        if (!session.isSpawned() || packet.getHotbarSlot() > 8 ||
                packet.getContainerId() != ContainerId.INVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) {
            // For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention
            return;
        }

        // Send book update before switching hotbar slot
        session.getBookEditCache().checkForSend();

        session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot());

        ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot());
        session.sendDownstreamPacket(changeHeldItemPacket);

        if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {
            // Activate shield since we are already sneaking
            // (No need to send a release item packet - Java doesn't do this when swapping items)
            // Required to do it a tick later or else it doesn't register
            session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)),
                    50, TimeUnit.MILLISECONDS);
        }

        // Java sends a cooldown indicator whenever you switch an item
        CooldownUtils.sendCooldown(session);

        // Update the interactive tag, if an entity is present
        if (session.getMouseoverEntity() != null) {
            InteractiveTagManager.updateTag(session, session.getMouseoverEntity());
        }
    }