jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
	public static void copyDb(
	    String jdbcDriverSource,
	    String usernameSource,
	    String passwordSource,
	    String jdbcUrlSource,
	    String jdbcDriverTarget,
	    String usernameTarget,
	    String passwordTarget,
	    String jdbcUrlTarget,
	    List<String> includeDbObjects,
	    List<String> excludeDbObjects,
	    List<String> valuePatterns,
	    List<String> valueReplacements,
	    PrintStream out
	) throws ServiceException {
		{
			DBOBJECTS.clear();
			List<String> tableNames = new ArrayList<String>();
			try {
				tableNames = DbSchemaUtils.getTableNames();
			} catch (Exception e) {
				new ServiceException(e).log();
			}
			for(String tableName : tableNames) {
				if(
					tableName.indexOf("_") > 0 &&
					tableName.indexOf("_TOBJ_") < 0 &&
					tableName.indexOf("_JOIN_") < 0 &&
					!tableName.endsWith("_")
				) {
					DBOBJECTS.add(tableName);
				}
			}		
		}
		try {
			// Source connection
			Class.forName(jdbcDriverSource);
			Properties props = new Properties();
			props.put("user", usernameSource);
			props.put("password", passwordSource);
			Connection connSource = DriverManager.getConnection(jdbcUrlSource, props);
			connSource.setAutoCommit(true);
			// Target connection
			Class.forName(jdbcDriverTarget);
			props = new Properties();
			props.put("user", usernameTarget);
			props.put("password", passwordTarget);
			Connection connTarget = DriverManager.getConnection(jdbcUrlTarget, props);
			connTarget.setAutoCommit(true);
			CopyDb.copyNamespace(
				connSource, 
				connTarget,
				filterDbObjects(
					DBOBJECTS, 
					includeDbObjects, 
					excludeDbObjects
				),
			    valuePatterns, 
			    valueReplacements, 
			    out
			);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
		out.println();
		out.println("!!! DONE !!!");
	}
//  [java]
		protected Class<?> getClassForNode(Node node) {
			if (node instanceof VersionedYamlDoc) {
				return super.getClassForNode(node);
			} else {
				Class<?> type = node.getType();
				if (type.getAnnotation(Editable.class) == null) {
					// Do not deserialize unknown classes to avoid security vulnerabilities
					throw new IllegalStateException(String.format("Unexpected yaml node (type: %s, tag: %s)", 
							type, node.getTag()));
				} else {
					if (!ClassUtils.isConcrete(type)) {
						ImplementationRegistry registry = OneDev.getInstance(ImplementationRegistry.class);
						for (Class<?> implementationClass: registry.getImplementations(node.getType())) {
							String implementationTag = new Tag("!" + implementationClass.getSimpleName()).getValue();
							if (implementationTag.equals(node.getTag().getValue()))
								return implementationClass;
						}
					}
					return super.getClassForNode(node);
				}
			}
		}
//  [java]
		protected Class<?> getClassForNode(Node node) {
			Class<?> type = node.getType();
			if (type.getAnnotation(Editable.class) != null && !ClassUtils.isConcrete(type)) {
				ImplementationRegistry registry = OneDev.getInstance(ImplementationRegistry.class);
				for (Class<?> implementationClass: registry.getImplementations(node.getType())) {
					String implementationTag = new Tag("!" + implementationClass.getSimpleName()).getValue();
					if (implementationTag.equals(node.getTag().getValue()))
						return implementationClass;
				}
			}
			
			return super.getClassForNode(node);
		}
//  [java]
    public void translate(GeyserSession session, ServerBlockBreakAnimPacket packet) {
        int state = session.getConnector().getWorldManager().getBlockAt(session, packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());
        int breakTime = (int) (65535 / Math.ceil(BlockUtils.getBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(state), ItemMapping.AIR, new CompoundTag(""), false) * 20));
        LevelEventPacket levelEventPacket = new LevelEventPacket();
        levelEventPacket.setPosition(Vector3f.from(
                packet.getPosition().getX(),
                packet.getPosition().getY(),
                packet.getPosition().getZ()
        ));
        levelEventPacket.setType(LevelEventType.BLOCK_START_BREAK);

        switch (packet.getStage()) {
            case STAGE_1:
                levelEventPacket.setData(breakTime);
                break;
            case STAGE_2:
                levelEventPacket.setData(breakTime * 2);
                break;
            case STAGE_3:
                levelEventPacket.setData(breakTime * 3);
                break;
            case STAGE_4:
                levelEventPacket.setData(breakTime * 4);
                break;
            case STAGE_5:
                levelEventPacket.setData(breakTime * 5);
                break;
            case STAGE_6:
                levelEventPacket.setData(breakTime * 6);
                break;
            case STAGE_7:
                levelEventPacket.setData(breakTime * 7);
                break;
            case STAGE_8:
                levelEventPacket.setData(breakTime * 8);
                break;
            case STAGE_9:
                levelEventPacket.setData(breakTime * 9);
                break;
            case STAGE_10:
                levelEventPacket.setData(breakTime * 10);
                break;
            case RESET:
                levelEventPacket.setType(LevelEventType.BLOCK_STOP_BREAK);
                levelEventPacket.setData(0);
                break;
        }
        session.sendUpstreamPacket(levelEventPacket);
    }
//  [java]
    public void translate(ServerBlockBreakAnimPacket packet, GeyserSession session) {
        int state = session.getConnector().getWorldManager().getBlockAt(session, packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());
        int breakTime = (int) (65535 / Math.ceil(BlockUtils.getBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(state), ItemMapping.AIR, new CompoundTag(""), false) * 20));
        LevelEventPacket levelEventPacket = new LevelEventPacket();
        levelEventPacket.setPosition(Vector3f.from(
                packet.getPosition().getX(),
                packet.getPosition().getY(),
                packet.getPosition().getZ()
        ));
        levelEventPacket.setType(LevelEventType.BLOCK_START_BREAK);

        switch (packet.getStage()) {
            case STAGE_1:
                levelEventPacket.setData(breakTime);
                break;
            case STAGE_2:
                levelEventPacket.setData(breakTime * 2);
                break;
            case STAGE_3:
                levelEventPacket.setData(breakTime * 3);
                break;
            case STAGE_4:
                levelEventPacket.setData(breakTime * 4);
                break;
            case STAGE_5:
                levelEventPacket.setData(breakTime * 5);
                break;
            case STAGE_6:
                levelEventPacket.setData(breakTime * 6);
                break;
            case STAGE_7:
                levelEventPacket.setData(breakTime * 7);
                break;
            case STAGE_8:
                levelEventPacket.setData(breakTime * 8);
                break;
            case STAGE_9:
                levelEventPacket.setData(breakTime * 9);
                break;
            case STAGE_10:
                levelEventPacket.setData(breakTime * 10);
                break;
            case RESET:
                levelEventPacket.setType(LevelEventType.BLOCK_STOP_BREAK);
                levelEventPacket.setData(0);
                break;
        }
        session.sendUpstreamPacket(levelEventPacket);
    }
//  [java]
    private static void handleResponse(HttpsURLConnection conn, String orgName, String moduleName, String version) {
        try {
            int statusCode = getStatusCode(conn);
            // 200 - Module pushed successfully
            // Other - Error occurred, json returned with the error message
            if (statusCode == HttpsURLConnection.HTTP_OK) {
                outStream.println(orgName + "/" + moduleName + ":" + version + " pushed to central successfully");
            } else if (statusCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {
                errStream.println("unauthorized access token for organization: " + orgName);
            } else if (statusCode == HttpsURLConnection.HTTP_BAD_REQUEST) {
                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());
                    String message = payload.getStringValue("message");
                    if (message.contains("module md file cannot be empty")) {
                        errStream.println(message);
                    } else {
                        throw ErrorUtil.createCommandException(message);
                    }
                } catch (IOException e) {
                    throw ErrorUtil.createCommandException(
                            "failed to push the module '" + orgName + "/" + moduleName + ":" + version
                                    + "' to the remote repository '" + conn.getURL() + "'");
                }
            } else {
                throw ErrorUtil.createCommandException(
                        "failed to push the module '" + orgName + "/" + moduleName + ":" + version
                                + "' to the remote repository '" + conn.getURL() + "'");
            }
        } finally {
            conn.disconnect();
        }
    }
//  [java]
    private static void handleResponse(HttpURLConnection conn, String orgName, String moduleName, String version) {
        try {
            int statusCode = getStatusCode(conn);
            // 200 - Module pushed successfully
            // Other - Error occurred, json returned with the error message
            if (statusCode == HttpURLConnection.HTTP_OK) {
                outStream.println(orgName + "/" + moduleName + ":" + version + " pushed to central successfully");
            } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                errStream.println("unauthorized access token for organization: " + orgName);
            } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
                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());
                    String message = payload.getStringValue("message");
                    if (message.contains("module md file cannot be empty")) {
                        errStream.println(message);
                    } else {
                        throw ErrorUtil.createCommandException(message);
                    }
                } catch (IOException e) {
                    throw ErrorUtil.createCommandException(
                            "failed to push the module '" + orgName + "/" + moduleName + ":" + version
                                    + "' to the remote repository '" + conn.getURL() + "'");
                }
            } else {
                throw ErrorUtil.createCommandException(
                        "failed to push the module '" + orgName + "/" + moduleName + ":" + version
                                + "' to the remote repository '" + conn.getURL() + "'");
            }
        } finally {
            conn.disconnect();
        }
    }
//  [java]
    public static Map<String, String> genHeaderMapByRequest(HttpServletRequest request, AdminTokenVO adminTokenVO) {
        Map<String, String> map = new HashMap<>();
        if (adminTokenVO != null) {
            map.put("LoginUserId", adminTokenVO.getUserId() + "");
        }
        map.put("IsLogin", (adminTokenVO != null) + "");
        map.put("Current-Locale", I18nUtil.getCurrentLocale());
        map.put("Blog-Version", BlogBuildInfoUtil.getVersion());
        if (request != null) {
            String fullUrl = ZrLogUtil.getFullUrl(request);
            if (request.getQueryString() != null) {
                fullUrl = fullUrl + "?" + request.getQueryString();
            }
            if (adminTokenVO != null) {
                fullUrl = adminTokenVO.getProtocol() + ":" + fullUrl;
            }
            map.put("Cookie", request.getHeader("Cookie"));
            map.put("AccessUrl", "http://127.0.0.1:" + request.getServerPort() + request.getContextPath());
            if (request.getHeader("Content-Type") != null) {
                map.put("Content-Type", request.getHeader("Content-Type"));
            }
            map.put("Full-Url", fullUrl);
        }
        return map;
    }
//  [java]
    public static Map<String, String> genHeaderMapByRequest(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        AdminTokenVO adminTokenVO = AdminTokenThreadLocal.getUser();
        if (adminTokenVO != null) {
            User user = User.dao.findById(adminTokenVO.getUserId());
            map.put("LoginUserName", user.get("userName").toString());
            map.put("LoginUserId", adminTokenVO.getUserId() + "");
        }
        map.put("IsLogin", (adminTokenVO != null) + "");
        map.put("Current-Locale", I18nUtil.getCurrentLocale());
        map.put("Blog-Version", ((Map) JFinal.me().getServletContext().getAttribute("zrlog")).get("version").toString());
        if (request != null) {
            String fullUrl = ZrLogUtil.getFullUrl(request);
            if (request.getQueryString() != null) {
                fullUrl = fullUrl + "?" + request.getQueryString();
            }
            if (adminTokenVO != null) {
                fullUrl = adminTokenVO.getProtocol() + ":" + fullUrl;
            }
            map.put("Cookie", request.getHeader("Cookie"));
            map.put("AccessUrl", "http://127.0.0.1:" + request.getServerPort() + request.getContextPath());
            if (request.getHeader("Content-Type") != null) {
                map.put("Content-Type", request.getHeader("Content-Type"));
            }
            map.put("Full-Url", fullUrl);
        }
        return map;
    }
//  [java]
	protected StyleSignature getStyleSignature() {
		if (type == TimingStyle.CONCISE)
			return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.concise).withTOBECHANGED(stereotype);
		if (type == TimingStyle.ROBUST)
			return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.robust).withTOBECHANGED(stereotype);
		throw new IllegalStateException();
	}
//  [java]
	protected StyleSignatureBasic getStyleSignature() {
		if (type == TimingStyle.CONCISE)
			return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.concise);
		if (type == TimingStyle.ROBUST)
			return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.robust);
		throw new IllegalStateException();
	}
//  [java]
	public static List<String> checkLockedFileBeforeUnzipNonStrict(VFSLeaf zipLeaf, VFSContainer targetDir, Identity identity) {
		List<String> lockedFiles = new ArrayList<>();
		VFSLockManager vfsLockManager = CoreSpringFactory.getImpl(VFSLockManager.class);
		
		try(InputStream in = zipLeaf.getInputStream();
				net.sf.jazzlib.ZipInputStream oZip = new net.sf.jazzlib.ZipInputStream(in);) {
			// unzip files
			net.sf.jazzlib.ZipEntry oEntr = oZip.getNextEntry();
			while (oEntr != null) {
				if (oEntr.getName() != null && !oEntr.getName().startsWith(DIR_NAME__MACOSX)) {
					if (oEntr.isDirectory()) {
						// skip MacOSX specific metadata directory
						// directories aren't locked
						oZip.closeEntry();
						oEntr = oZip.getNextEntry();//TODO zip
						continue;
					} else {
						// search file
						VFSContainer createIn = targetDir;
						String name = oEntr.getName();
						// check if entry has directories which did not show up as
						// directories above
						int dirSepIndex = name.lastIndexOf('/');
						if (dirSepIndex == -1) {
							// try it windows style, backslash is also valid format
							dirSepIndex = name.lastIndexOf('\\');
						}
						if (dirSepIndex > 0) {
							// get subdirs
							createIn = getAllSubdirs(targetDir, name.substring(0, dirSepIndex), identity, false);
							if (createIn == null) {
								//sub directories don't exist, and aren't locked
								oZip.closeEntry();
								oEntr = oZip.getNextEntry();
								continue;
							}
							name = name.substring(dirSepIndex + 1);
						}
						
						VFSLeaf newEntry = (VFSLeaf)createIn.resolve(name);
						if(vfsLockManager.isLockedForMe(newEntry, identity, VFSLockApplicationType.vfs, null)) {
							lockedFiles.add(name);
						}
					}
				}
				oZip.closeEntry();
				oEntr = oZip.getNextEntry();
			}
		} catch (IOException e) {
			return null;
		}

		return lockedFiles;
	}
//  [java]
	public static List<String> checkLockedFileBeforeUnzipNonStrict(VFSLeaf zipLeaf, VFSContainer targetDir, Identity identity) {
		List<String> lockedFiles = new ArrayList<>();
		VFSLockManager vfsLockManager = CoreSpringFactory.getImpl(VFSLockManager.class);
		
		try(InputStream in = zipLeaf.getInputStream();
				net.sf.jazzlib.ZipInputStream oZip = new net.sf.jazzlib.ZipInputStream(in);) {
			// unzip files
			net.sf.jazzlib.ZipEntry oEntr = oZip.getNextEntry();
			while (oEntr != null) {
				if (oEntr.getName() != null && !oEntr.getName().startsWith(DIR_NAME__MACOSX)) {
					if (oEntr.isDirectory()) {
						// skip MacOSX specific metadata directory
						// directories aren't locked
						oZip.closeEntry();
						oEntr = oZip.getNextEntry();
						continue;
					} else {
						// search file
						VFSContainer createIn = targetDir;
						String name = oEntr.getName();
						// check if entry has directories which did not show up as
						// directories above
						int dirSepIndex = name.lastIndexOf('/');
						if (dirSepIndex == -1) {
							// try it windows style, backslash is also valid format
							dirSepIndex = name.lastIndexOf('\\');
						}
						if (dirSepIndex > 0) {
							// get subdirs
							createIn = getAllSubdirs(targetDir, name.substring(0, dirSepIndex), identity, false);
							if (createIn == null) {
								//sub directories don't exist, and aren't locked
								oZip.closeEntry();
								oEntr = oZip.getNextEntry();
								continue;
							}
							name = name.substring(dirSepIndex + 1);
						}
						
						VFSLeaf newEntry = (VFSLeaf)createIn.resolve(name);
						if(vfsLockManager.isLockedForMe(newEntry, identity, VFSLockApplicationType.vfs, null)) {
							lockedFiles.add(name);
						}
					}
				}
				oZip.closeEntry();
				oEntr = oZip.getNextEntry();
			}
		} catch (IOException e) {
			return null;
		}

		return lockedFiles;
	}
//  [java]
	private static boolean unzip(InputStream in, VFSContainer targetDir, Identity identity, boolean versioning) {
		
		VFSRepositoryService vfsRepositoryService = CoreSpringFactory.getImpl(VFSRepositoryService.class);

		try(ZipInputStream oZip = new ZipInputStream(in)) {
			// unzip files
			ZipEntry oEntr = oZip.getNextEntry();
			while (oEntr != null) {
				String name = oEntr.getName();
				if(!targetDir.isInPath(name)) {
					throw new IOException("Invalip ZIP");
				}

				if (name != null && !name.startsWith(DIR_NAME__MACOSX)) {
					if (oEntr.isDirectory()) {
						// skip MacOSX specific metadata directory
						// create directories
						getAllSubdirs(targetDir, name, identity, true);
					} else {
						// create file
						VFSContainer createIn = targetDir;
						// check if entry has directories which did not show up as
						// directories above
						int dirSepIndex = name.lastIndexOf('/');
						if (dirSepIndex == -1) {
							// try it windows style, backslash is also valid format
							dirSepIndex = name.lastIndexOf('\\');
						}
						if (dirSepIndex > 0) {
							// create subdirs
							createIn = getAllSubdirs(targetDir, name.substring(0, dirSepIndex), identity, true);
							if (createIn == null) {
								log.debug("Error creating directory structure for zip entry: {}", oEntr.getName());
								return false;
							}
							name = name.substring(dirSepIndex + 1);
						}
						
						if(versioning) {
							VFSLeaf newEntry = (VFSLeaf)createIn.resolve(name);
							if(newEntry == null) {
								newEntry = createIn.createChildLeaf(name);
								if (!copy(oZip, newEntry)) {
									return false;
								}
							} else if (newEntry.canVersion() == VFSConstants.YES) {
								vfsRepositoryService.addVersion(newEntry, identity, "", oZip);
							}
							if(newEntry != null && identity != null && newEntry.canMeta() == VFSConstants.YES) {
								VFSMetadata info = newEntry.getMetaInfo();
								if(info != null) {
									info.setAuthor(identity);
									vfsRepositoryService.updateMetadata(info);
								}
							}
							
						} else {
							VFSLeaf newEntry = createIn.createChildLeaf(name);
							if (newEntry != null) {
								if (!copy(oZip, newEntry)) {
									return false;
								}
					
								if(identity != null && newEntry.canMeta() == VFSConstants.YES) {
									VFSMetadata info = newEntry.getMetaInfo();
									if(info != null) {
										info.setAuthor(identity);
										vfsRepositoryService.updateMetadata(info);
									}
								}
							}
						}
					}
				}
				oZip.closeEntry();
				oEntr = oZip.getNextEntry();
			}
		} catch (IOException e) {
			return false;
		}
		return true;
	} // unzip
//  [java]
	private static boolean unzip(InputStream in, VFSContainer targetDir, Identity identity, boolean versioning) {
		
		VFSRepositoryService vfsRepositoryService = CoreSpringFactory.getImpl(VFSRepositoryService.class);
		
		try(ZipInputStream oZip = new ZipInputStream(in)) {
			// unzip files
			ZipEntry oEntr = oZip.getNextEntry();
			while (oEntr != null) {
				if (oEntr.getName() != null && !oEntr.getName().startsWith(DIR_NAME__MACOSX)) {
					if (oEntr.isDirectory()) {
						// skip MacOSX specific metadata directory
						// create directories
						getAllSubdirs(targetDir, oEntr.getName(), identity, true);
					} else {
						// create file
						VFSContainer createIn = targetDir;
						String name = oEntr.getName();
						// check if entry has directories which did not show up as
						// directories above
						int dirSepIndex = name.lastIndexOf('/');
						if (dirSepIndex == -1) {
							// try it windows style, backslash is also valid format
							dirSepIndex = name.lastIndexOf('\\');
						}
						if (dirSepIndex > 0) {
							// create subdirs
							createIn = getAllSubdirs(targetDir, name.substring(0, dirSepIndex), identity, true);
							if (createIn == null) {
								log.debug("Error creating directory structure for zip entry: {}", oEntr.getName());
								return false;
							}
							name = name.substring(dirSepIndex + 1);
						}
						
						if(versioning) {
							VFSLeaf newEntry = (VFSLeaf)createIn.resolve(name);
							if(newEntry == null) {
								newEntry = createIn.createChildLeaf(name);
								if (!copy(oZip, newEntry)) {
									return false;
								}
							} else if (newEntry.canVersion() == VFSConstants.YES) {
								vfsRepositoryService.addVersion(newEntry, identity, "", oZip);
							}
							if(newEntry != null && identity != null && newEntry.canMeta() == VFSConstants.YES) {
								VFSMetadata info = newEntry.getMetaInfo();
								if(info != null) {
									info.setAuthor(identity);
									vfsRepositoryService.updateMetadata(info);
								}
							}
							
						} else {
							VFSLeaf newEntry = createIn.createChildLeaf(name);
							if (newEntry != null) {
								if (!copy(oZip, newEntry)) {
									return false;
								}
					
								if(identity != null && newEntry.canMeta() == VFSConstants.YES) {
									VFSMetadata info = newEntry.getMetaInfo();
									if(info != null) {
										info.setAuthor(identity);
										vfsRepositoryService.updateMetadata(info);
									}
								}
							}
						}
					}
				}
				oZip.closeEntry();
				oEntr = oZip.getNextEntry();
			}
		} catch (IOException e) {
			return false;
		}
		return true;
	} // unzip
//  [java]
	private static boolean unzipNonStrict(InputStream in, VFSContainer targetDir, Identity identity, boolean versioning) {
		try(net.sf.jazzlib.ZipInputStream oZip = new net.sf.jazzlib.ZipInputStream(in)) {
			VFSRepositoryService vfsRepositoryService = CoreSpringFactory.getImpl(VFSRepositoryService.class);
			
			// unzip files
			net.sf.jazzlib.ZipEntry oEntr = oZip.getNextEntry();//TODO zip
			
			VFSLeaf lastLeaf = null;
			while (oEntr != null) {
				if (oEntr.getName() != null && !oEntr.getName().startsWith(DIR_NAME__MACOSX)) {
					if (oEntr.isDirectory()) {
						// skip MacOSX specific metadata directory
						// create directories
						getAllSubdirs(targetDir, oEntr.getName(), identity, true);
					} else {
						// create file
						VFSContainer createIn = targetDir;
						String name = oEntr.getName();
						// check if entry has directories which did not show up as
						// directories above
						int dirSepIndex = name.lastIndexOf('/');
						if (dirSepIndex == -1) {
							// try it windows style, backslash is also valid format
							dirSepIndex = name.lastIndexOf('\\');
						}
						if (dirSepIndex > 0) {
							// create subdirs
							createIn = getAllSubdirs(targetDir, name.substring(0, dirSepIndex), identity, true);
							if (createIn == null) {
								log.debug("Error creating directory structure for zip entry: {}", oEntr.getName());
								return false;
							}
							name = name.substring(dirSepIndex + 1);
						}
						
						if(name != null && name.startsWith("._oo_meta_")) {
							if(lastLeaf != null && name.endsWith(lastLeaf.getName())) {
								unzipMetadata(oZip, lastLeaf);
							}
						} else if(versioning) {
							VFSLeaf newEntry = (VFSLeaf)createIn.resolve(name);
							if(newEntry == null) {
								newEntry = createIn.createChildLeaf(name);
								if (!copyShielded(oZip, newEntry)) {
									return false;
								}
							} else if (newEntry.canVersion() == VFSConstants.YES) {
								vfsRepositoryService.addVersion(newEntry, identity, "", oZip);
							}
							lastLeaf = newEntry;
							unzipMetadata(identity, newEntry);
						} else {
							VFSLeaf newEntry = createIn.createChildLeaf(name);
							if (newEntry != null) {
								if (!copyShielded(oZip, newEntry)) {
									return false;
								}
								lastLeaf = newEntry;
								unzipMetadata(identity, newEntry);
							}
						}
					}
				}
				oZip.closeEntry();
				oEntr = oZip.getNextEntry();
			}
		} catch (IOException e) {
			return false;
		}
		return true;
	} // unzip
//  [java]
	private static boolean unzipNonStrict(InputStream in, VFSContainer targetDir, Identity identity, boolean versioning) {
		try(net.sf.jazzlib.ZipInputStream oZip = new net.sf.jazzlib.ZipInputStream(in)) {
			VFSRepositoryService vfsRepositoryService = CoreSpringFactory.getImpl(VFSRepositoryService.class);
			
			// unzip files
			net.sf.jazzlib.ZipEntry oEntr = oZip.getNextEntry();
			
			VFSLeaf lastLeaf = null;
			while (oEntr != null) {
				if (oEntr.getName() != null && !oEntr.getName().startsWith(DIR_NAME__MACOSX)) {
					if (oEntr.isDirectory()) {
						// skip MacOSX specific metadata directory
						// create directories
						getAllSubdirs(targetDir, oEntr.getName(), identity, true);
					} else {
						// create file
						VFSContainer createIn = targetDir;
						String name = oEntr.getName();
						// check if entry has directories which did not show up as
						// directories above
						int dirSepIndex = name.lastIndexOf('/');
						if (dirSepIndex == -1) {
							// try it windows style, backslash is also valid format
							dirSepIndex = name.lastIndexOf('\\');
						}
						if (dirSepIndex > 0) {
							// create subdirs
							createIn = getAllSubdirs(targetDir, name.substring(0, dirSepIndex), identity, true);
							if (createIn == null) {
								log.debug("Error creating directory structure for zip entry: {}", oEntr.getName());
								return false;
							}
							name = name.substring(dirSepIndex + 1);
						}
						
						if(name != null && name.startsWith("._oo_meta_")) {
							if(lastLeaf != null && name.endsWith(lastLeaf.getName())) {
								unzipMetadata(oZip, lastLeaf);
							}
						} else if(versioning) {
							VFSLeaf newEntry = (VFSLeaf)createIn.resolve(name);
							if(newEntry == null) {
								newEntry = createIn.createChildLeaf(name);
								if (!copyShielded(oZip, newEntry)) {
									return false;
								}
							} else if (newEntry.canVersion() == VFSConstants.YES) {
								vfsRepositoryService.addVersion(newEntry, identity, "", oZip);
							}
							lastLeaf = newEntry;
							unzipMetadata(identity, newEntry);
						} else {
							VFSLeaf newEntry = createIn.createChildLeaf(name);
							if (newEntry != null) {
								if (!copyShielded(oZip, newEntry)) {
									return false;
								}
								lastLeaf = newEntry;
								unzipMetadata(identity, newEntry);
							}
						}
					}
				}
				oZip.closeEntry();
				oEntr = oZip.getNextEntry();
			}
		} catch (IOException e) {
			return false;
		}
		return true;
	} // unzip
//  [java]
    public String list(Model model, // TODO model should no longer be injected
                       @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy,
                       @RequestParam(required = false, defaultValue = "false") boolean desc,
                       @RequestParam(required = false) String base) throws IOException, TemplateException {
        Path currentFolder = loggingPath(base);
        securityCheck(currentFolder, null);


        List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder);
        List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc);

        model.addAttribute("sortBy", sortBy);
        model.addAttribute("desc", desc);
        model.addAttribute("files", sortedFiles);
        model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString());
        model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : "");
        model.addAttribute("parent", getParent(currentFolder));
        model.addAttribute("stylesheets", stylesheets);

        return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model);
    }
//  [java]
    public String list(Model model, // TODO model should no longer be injected
                       @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy,
                       @RequestParam(required = false, defaultValue = "false") boolean desc,
                       @RequestParam(required = false) String base) throws IOException, TemplateException {
        securityCheck(base);

        Path currentFolder = loggingPath(base);

        List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder);
        List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc);

        model.addAttribute("sortBy", sortBy);
        model.addAttribute("desc", desc);
        model.addAttribute("files", sortedFiles);
        model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString());
        model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : "");
        model.addAttribute("parent", getParent(currentFolder));
        model.addAttribute("stylesheets", stylesheets);

        return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model);
    }
//  [java]
    private void securityCheck(Path base, String filename) {
        try {
            String canonicalLoggingPath = (filename != null ? new File(base.toFile().toString(), filename) : new File(base.toFile().toString())).getCanonicalPath();
            String baseCanonicalPath = new File(loggingPath).getCanonicalPath();
            String errorMessage = "File " + base.toString() + "/" + filename + " may not be located outside base path " + loggingPath;
            Assert.isTrue(canonicalLoggingPath.startsWith(baseCanonicalPath), errorMessage);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
//  [java]
    private void securityCheck(String filename) {
        Assert.doesNotContain(filename, "..");
    }
//  [java]
    void routingResult() throws URISyntaxException {
        final RoutingResultBuilder builder = RoutingResult.builder();
        final RoutingResult routingResult = builder.path("/foo")
                                                   .query("bar=baz")
                                                   .rawParam("qux", "quux")
                                                   .negotiatedResponseMediaType(MediaType.JSON_UTF_8)
                                                   .build();
        assertThat(routingResult.isPresent()).isTrue();
        assertThat(routingResult.path()).isEqualTo("/foo");
        assertThat(routingResult.query()).isEqualTo("bar=baz");
        assertThat(routingResult.pathParams()).containsOnly(Maps.immutableEntry("qux", "quux"));
        assertThat(routingResult.negotiatedResponseMediaType()).isSameAs(MediaType.JSON_UTF_8);
    }
//  [java]
    void routingResult() throws URISyntaxException {
        final RoutingResultBuilder builder = RoutingResult.builder();
        final RoutingResult routingResult = builder.path("/foo")
                                                   .query("bar=baz")
                                                   .rawParam("qux", "quux")
                                                   .negotiatedResponseMediaType(MediaType.JSON_UTF_8)
                                                   .build();
        assertThat(routingResult.isPresent()).isTrue();
        assertThat(routingResult.path()).isEqualTo("/foo");
        assertThat(routingResult.query()).isEqualTo("bar=baz");
        assertThat(routingResult.pathParams()).containsOnly(new SimpleEntry<>("qux", "quux"));
        assertThat(routingResult.negotiatedResponseMediaType()).isSameAs(MediaType.JSON_UTF_8);
    }
//  [java]
    public void translate(GeyserSession session, ServerKeepAlivePacket packet) {
        if (!session.getConnector().getConfig().isForwardPlayerPing()) {
            return;
        }
        NetworkStackLatencyPacket latencyPacket = new NetworkStackLatencyPacket();
        latencyPacket.setFromServer(true);
        latencyPacket.setTimestamp(packet.getPingId() * 1000);
        session.sendUpstreamPacket(latencyPacket);
    }
//  [java]
    public void translate(ServerKeepAlivePacket packet, GeyserSession session) {
        if (!session.getConnector().getConfig().isForwardPlayerPing()) {
            return;
        }
        NetworkStackLatencyPacket latencyPacket = new NetworkStackLatencyPacket();
        latencyPacket.setFromServer(true);
        latencyPacket.setTimestamp(packet.getPingId() * 1000);
        session.sendUpstreamPacket(latencyPacket);
    }
//  [java]
    public void view(@RequestParam String filename,
                     @RequestParam(required = false) String base,
                     @RequestParam(required = false) Integer tailLines,
                     HttpServletResponse response) throws IOException {

        Path path = loggingPath(base);
        securityCheck(path, filename);
        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
        FileProvider fileProvider = getFileProvider(path);
        if (tailLines != null) {
            fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines);
        }
        else {
            fileProvider.streamContent(path, filename, response.getOutputStream());
        }
    }
//  [java]
    public void view(@RequestParam String filename,
                     @RequestParam(required = false) String base,
                     @RequestParam(required = false) Integer tailLines,
                     HttpServletResponse response) throws IOException {
        securityCheck(filename);
        response.setContentType(MediaType.TEXT_PLAIN_VALUE);

        Path path = loggingPath(base);
        FileProvider fileProvider = getFileProvider(path);
        if (tailLines != null) {
            fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines);
        }
        else {
            fileProvider.streamContent(path, filename, response.getOutputStream());
        }
    }
//  [java]
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("application/json");
        final PrintWriter out = resp.getWriter();

        HttpSession session = req.getSession(false);

        if (session != null) {
            Subject subject = (Subject) session.getAttribute("subject");
            if (subject == null) {
                LOG.warn("No security subject stored in existing session, invalidating");
                session.invalidate();
                Helpers.doForbidden(resp);
                return;
            }
            sendResponse(session, subject, out);
            return;
        }

        AccessControlContext acc = AccessController.getContext();
        Subject subject = Subject.getSubject(acc);

        if (subject == null) {
            Helpers.doForbidden(resp);
            return;
        }
        Set<Principal> principals = subject.getPrincipals();

        String username = null;

        if (principals != null) {
            for (Principal principal : principals) {
                if (principal.getClass().getSimpleName().equals("UserPrincipal")) {
                    username = principal.getName();
                    LOG.debug("Authorizing user {}", username);
                }
            }
        }

        session = req.getSession(true);
        session.setAttribute("subject", subject);
        session.setAttribute("user", username);
        session.setAttribute("org.osgi.service.http.authentication.remote.user", username);
        session.setAttribute("org.osgi.service.http.authentication.type", HttpServletRequest.BASIC_AUTH);
        session.setAttribute("loginTime", GregorianCalendar.getInstance().getTimeInMillis());
        if (timeout != null) {
            session.setMaxInactiveInterval(timeout);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Http session timeout for user {} is {} sec.", username, session.getMaxInactiveInterval());
        }

        sendResponse(session, subject, out);
    }
//  [java]
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("application/json");
        final PrintWriter out = resp.getWriter();

        HttpSession session = req.getSession(false);

        if (session != null) {
            Subject subject = (Subject) session.getAttribute("subject");
            if (subject == null) {
                LOG.warn("No security subject stored in existing session, invalidating");
                session.invalidate();
                Helpers.doForbidden(resp);
            }
            returnPrincipals(subject, out);
            return;
        }

        AccessControlContext acc = AccessController.getContext();
        Subject subject = Subject.getSubject(acc);

        if (subject == null) {
            Helpers.doForbidden(resp);
            return;
        }
        Set<Principal> principals = subject.getPrincipals();

        String username = null;

        if (principals != null) {
            for (Principal principal : principals) {
                if (principal.getClass().getSimpleName().equals("UserPrincipal")) {
                    username = principal.getName();
                    LOG.debug("Authorizing user {}", username);
                }
            }
        }

        session = req.getSession(true);
        session.setAttribute("subject", subject);
        session.setAttribute("user", username);
        session.setAttribute("org.osgi.service.http.authentication.remote.user", username);
        session.setAttribute("org.osgi.service.http.authentication.type", HttpServletRequest.BASIC_AUTH);
        session.setAttribute("loginTime", GregorianCalendar.getInstance().getTimeInMillis());
        if (timeout != null) {
            session.setMaxInactiveInterval(timeout);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Http session timeout for user {} is {} sec.", username, session.getMaxInactiveInterval());
        }

        returnPrincipals(subject, out);
    }
//  [java]
    public void translate(GeyserSession session, ServerScoreboardObjectivePacket packet) {
        WorldCache worldCache = session.getWorldCache();
        Scoreboard scoreboard = worldCache.getScoreboard();
        Objective objective = scoreboard.getObjective(packet.getName());
        int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();

        if (objective == null && packet.getAction() != ObjectiveAction.REMOVE) {
            objective = scoreboard.registerNewObjective(packet.getName(), false);
        }

        switch (packet.getAction()) {
            case ADD:
            case UPDATE:
                objective.setDisplayName(MessageTranslator.convertMessage(packet.getDisplayName()))
                        .setType(packet.getType().ordinal());
                break;
            case REMOVE:
                scoreboard.unregisterObjective(packet.getName());
                break;
        }

        if (objective == null || !objective.isActive()) {
            return;
        }

        // ScoreboardUpdater will handle it for us if the packets per second
        // (for score and team packets) is higher then the first threshold
        if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) {
            scoreboard.onUpdate();
        }
    }
//  [java]
    public void translate(ServerScoreboardObjectivePacket packet, GeyserSession session) {
        WorldCache worldCache = session.getWorldCache();
        Scoreboard scoreboard = worldCache.getScoreboard();
        Objective objective = scoreboard.getObjective(packet.getName());
        int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();

        if (objective == null && packet.getAction() != ObjectiveAction.REMOVE) {
            objective = scoreboard.registerNewObjective(packet.getName(), false);
        }

        switch (packet.getAction()) {
            case ADD:
            case UPDATE:
                objective.setDisplayName(MessageTranslator.convertMessage(packet.getDisplayName()))
                        .setType(packet.getType().ordinal());
                break;
            case REMOVE:
                scoreboard.unregisterObjective(packet.getName());
                break;
        }

        if (objective == null || !objective.isActive()) {
            return;
        }

        // ScoreboardUpdater will handle it for us if the packets per second
        // (for score and team packets) is higher then the first threshold
        if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) {
            scoreboard.onUpdate();
        }
    }
//  [java]
  protected URI addContentToRepo(MediaPackage mp, String elementId, URI uri) throws IOException {
    InputStream in = null;
    HttpResponse response = null;
    CloseableHttpClient externalHttpClient = null;
    try {
      if (uri.toString().startsWith("http")) {
        HttpGet get = new HttpGet(uri);
        var clusterUrls = securityService.getOrganization().getServers().keySet();

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

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

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

      if (isBlank(FilenameUtils.getExtension(fileName)))
        throw new IOException("No filename extension found: " + fileName);
      return addContentToRepo(mp, elementId, fileName, in);
    } finally {
      if (in != null) {
        in.close();
      }
      if (externalHttpClient != null) {
        externalHttpClient.close();
      }
      httpClient.close(response);
    }
  }