jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    private String findPathConsideringContracts(LibraryInfo library,
                                     String resourceName,
                                     String localePrefix,
                                     ContractInfo [] outContract,
                                     FacesContext ctx) {
        UIViewRoot root = ctx.getViewRoot();
        List<String> contracts = null;

        if (library != null) {
            if(library.getContract() == null) {
                contracts = Collections.emptyList();
            } else {
                contracts = new ArrayList<String>(1);
                contracts.add(library.getContract());
            }
        } else if (root == null) {
            String contractName = ctx.getExternalContext().getRequestParameterMap()
                  .get("con");
            if (null != contractName && 0 < contractName.length()) {
                contracts = new ArrayList<>();
                contracts.add(contractName);
            } else {
                return null;
            }
        } else {
        	contracts = ctx.getResourceLibraryContracts();
        }

        String basePath = null;
        
        for (String curContract : contracts) {
        
            if (library != null) {
                // PENDING(fcaputo) no need to iterate over the contracts, if we have a library
                basePath = library.getPath(localePrefix) + '/' + resourceName;
            } else {
                if (localePrefix == null) {
                    basePath = getBaseContractsPath() + '/' + curContract + '/' + resourceName;
                } else {
                    basePath = getBaseContractsPath()
                            + '/' + curContract 
                            + '/'
                            + localePrefix
                            + '/'
                            + resourceName;
                }
            }
            
            try {
                if (ctx.getExternalContext().getResource(basePath) != null) {
                    outContract[0] = new ContractInfo(curContract);
                    break;
                } else {
                    basePath = null;
                }
            } catch (MalformedURLException e) {
                throw new FacesException(e);
            }
        }
            
        return basePath;
    }
//  [java]
    protected XWikiDocument prepareEditedDocument(XWikiContext context) throws XWikiException
    {
        // Determine the edited document (translation).
        XWikiDocument editedDocument = getEditedDocument(context);
        EditForm editForm = (EditForm) context.getForm();

        // Update the edited document based on the template specified on the request.
        readFromTemplate(editedDocument, editForm.getTemplate(), context);

        // The default values from the template can be overwritten by additional request parameters.
        updateDocumentTitleAndContentFromRequest(editedDocument, context);
        editedDocument.readObjectsFromForm(editForm, context);

        // Set the current user as creator, author and contentAuthor when the edited document is newly created to avoid
        // using XWikiGuest instead (because those fields were not previously initialized).
        if (editedDocument.isNew()) {
            editedDocument.setCreatorReference(context.getUserReference());
            editedDocument.setAuthorReference(context.getUserReference());
            editedDocument.setContentAuthorReference(context.getUserReference());
        }

        // Expose the edited document on the XWiki context and the Velocity context.
        putDocumentOnContext(editedDocument, context);

        return editedDocument;
    }
//  [java]
    protected XWikiDocument prepareEditedDocument(XWikiContext context) throws XWikiException
    {
        // Determine the edited document (translation).
        XWikiDocument editedDocument = getEditedDocument(context);
        EditForm editForm = (EditForm) context.getForm();

        // Update the edited document based on the template specified on the request.
        editedDocument.readFromTemplate(editForm, context);

        // The default values from the template can be overwritten by additional request parameters.
        updateDocumentTitleAndContentFromRequest(editedDocument, context);
        editedDocument.readObjectsFromForm(editForm, context);

        // Set the current user as creator, author and contentAuthor when the edited document is newly created to avoid
        // using XWikiGuest instead (because those fields were not previously initialized).
        if (editedDocument.isNew()) {
            editedDocument.setCreatorReference(context.getUserReference());
            editedDocument.setAuthorReference(context.getUserReference());
            editedDocument.setContentAuthorReference(context.getUserReference());
        }

        // Expose the edited document on the XWiki context and the Velocity context.
        putDocumentOnContext(editedDocument, context);

        return editedDocument;
    }
//  [java]
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        //便于Wappalyzer读取
        response.addHeader("X-ZrLog", BlogBuildInfoUtil.getVersion());
        boolean isPluginPath = false;
        for (String path : pluginHandlerPaths) {
            if (target.startsWith(path)) {
                isPluginPath = true;
            }
        }
        if (isPluginPath) {
            Map.Entry<AdminTokenVO, User> entry = null;
            try {
                entry = adminTokenService.getAdminTokenVOUserEntry(request);
                if (entry != null) {
                    adminTokenService.setAdminToken(entry.getValue(), entry.getKey().getSessionId(), entry.getKey().getProtocol(), request, response);
                }
                if (target.startsWith("/admin/plugins/")) {
                    try {
                        adminPermission(target, request, response);
                    } catch (IOException | InstantiationException e) {
                        LOGGER.error(e);
                    }
                } else if (target.startsWith("/plugin/") || target.startsWith("/p/")) {
                    try {
                        visitorPermission(target, request, response);
                    } catch (IOException | InstantiationException e) {
                        LOGGER.error(e);
                    }
                }
            } finally {
                isHandled[0] = true;
                if (entry != null) {
                    AdminTokenThreadLocal.remove();
                }
            }
        } else {
            this.next.handle(target, request, response, isHandled);
        }
    }
//  [java]
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        //便于Wappalyzer读取
        response.addHeader("X-ZrLog", BlogBuildInfoUtil.getVersion());
        boolean isPluginPath = false;
        for (String path : pluginHandlerPaths) {
            if (target.startsWith(path)) {
                isPluginPath = true;
            }
        }
        if (isPluginPath) {
            try {
                Map.Entry<AdminTokenVO, User> entry = adminTokenService.getAdminTokenVOUserEntry(request);
                if (entry != null) {
                    adminTokenService.setAdminToken(entry.getValue(), entry.getKey().getSessionId(), entry.getKey().getProtocol(), request, response);
                }
                if (target.startsWith("/admin/plugins/")) {
                    try {
                        adminPermission(target, request, response);
                    } catch (IOException | InstantiationException e) {
                        LOGGER.error(e);
                    }
                } else if (target.startsWith("/plugin/") || target.startsWith("/p/")) {
                    try {
                        visitorPermission(target, request, response);
                    } catch (IOException | InstantiationException e) {
                        LOGGER.error(e);
                    }
                }
            } finally {
                isHandled[0] = true;
            }
        } else {
            this.next.handle(target, request, response, isHandled);
        }
    }
//  [java]
    public void export(@PathVariable("modelId") @ApiParam("模型ID") String modelId,
                       @PathVariable("type") @ApiParam(value = "类型", allowableValues = "bpmn,json", example = "json")
                               ModelType type,
                       @ApiParam(hidden = true) HttpServletResponse response) {
        Model modelData = repositoryService.getModel(modelId);
        if (modelData == null) {
            throw new NotFoundException("模型不存在");
        }
        BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
        byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());

        JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
        BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

        // 处理异常
        if (bpmnModel.getMainProcess() == null) {
            throw new UnsupportedOperationException("无法导出模型文件:" + type);
        }

        String filename = "";
        byte[] exportBytes = null;

        String mainProcessId = bpmnModel.getMainProcess().getId();

        if (type == ModelType.bpmn) {
            BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
            exportBytes = xmlConverter.convertToXML(bpmnModel);
            filename = mainProcessId + ".bpmn20.xml";
        } else if (type == ModelType.json) {
            exportBytes = modelEditorSource;
            filename = mainProcessId + ".json";

        } else {
            throw new UnsupportedOperationException("不支持的格式:" + type);
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));

        /*创建输入流*/
        try (ByteArrayInputStream in = new ByteArrayInputStream(exportBytes)) {
            IOUtils.copy(in, response.getOutputStream());
            response.flushBuffer();
        }
    }
//  [java]
    public void export(@PathVariable("modelId") @ApiParam("模型ID") String modelId,
                       @PathVariable("type") @ApiParam(value = "类型", allowableValues = "bpmn,json", example = "json") String type,
                       @ApiParam(hidden = true) HttpServletResponse response) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());

            JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

            // 处理异常
            if (bpmnModel.getMainProcess() == null) {
                response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
                response.getOutputStream().println("no main process, can't export for dimension: " + type);
                response.flushBuffer();
                return;
            }

            String filename = "";
            byte[] exportBytes = null;

            String mainProcessId = bpmnModel.getMainProcess().getId();

            if ("bpmn".equals(type)) {

                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                exportBytes = xmlConverter.convertToXML(bpmnModel);

                filename = mainProcessId + ".bpmn20.xml";
            } else if ("json".equals(type)) {

                exportBytes = modelEditorSource;
                filename = mainProcessId + ".json";

            } else {
                throw new UnsupportedOperationException("不支持的格式:" + type);
            }

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));

            /*创建输入流*/
            try (ByteArrayInputStream in = new ByteArrayInputStream(exportBytes)) {
                IOUtils.copy(in, response.getOutputStream());
                response.flushBuffer();
                in.close();
            }

        } catch (Exception e) {
            log.error("导出model的xml文件失败：modelId={}, type={}", modelId, type, e);
        }
    }
//  [java]
	protected int getExpectedErrors() {
		return 1;
	}
//  [java]
	protected int getExpectedErrors() {
		return hasJavaNetURLPermission ? 2 : 1; // Security error must be reported as an error. Java 8 reports two errors.
	}
//  [java]
    public static CloseResponseHandle getContext(String uri, String method, HttpServletRequest request, boolean disableRedirect) throws IOException, InstantiationException {
        String pluginServerHttp = Constants.pluginServer;
        CloseableHttpResponse httpResponse;
        CloseResponseHandle handle = new CloseResponseHandle();
        HttpUtil httpUtil = disableRedirect ? HttpUtil.getDisableRedirectInstance() : HttpUtil.getInstance();
        //GET请求不关心request.getInputStream() 的数据
        if (method.equals(request.getMethod()) && "GET".equalsIgnoreCase(method)) {
            httpResponse = httpUtil.sendGetRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request, AdminTokenThreadLocal.getUser())).getT();
        } else {
            //如果是表单数据提交不关心请求头，反之将所有请求头都发到插件服务
            if ("application/x-www-form-urlencoded".equals(request.getContentType())) {
                httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request, AdminTokenThreadLocal.getUser())).getT();
            } else {
                httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri + "?" + request.getQueryString(), IOUtil.getByteByInputStream(request.getInputStream()), handle, PluginHelper.genHeaderMapByRequest(request, AdminTokenThreadLocal.getUser())).getT();
            }
        }
        //添加插件服务的HTTP响应头到调用者响应头里面
        if (httpResponse != null) {
            Map<String, String> headerMap = new HashMap<>();
            Header[] headers = httpResponse.getAllHeaders();
            for (Header header : headers) {
                headerMap.put(header.getName(), header.getValue());
            }
            if (JFinal.me().getConstants().getDevMode()) {
                LOGGER.info(uri + " --------------------------------- response");
            }
            for (Map.Entry<String, String> t : headerMap.entrySet()) {
                if (JFinal.me().getConstants().getDevMode()) {
                    LOGGER.info("key " + t.getKey() + " value-> " + t.getValue());
                }
            }
        }
        return handle;
    }
//  [java]
    public static CloseResponseHandle getContext(String uri, String method, HttpServletRequest request, boolean disableRedirect) throws IOException, InstantiationException {
        String pluginServerHttp = Constants.pluginServer;
        CloseableHttpResponse httpResponse;
        CloseResponseHandle handle = new CloseResponseHandle();
        HttpUtil httpUtil = disableRedirect ? HttpUtil.getDisableRedirectInstance() : HttpUtil.getInstance();
        //GET请求不关心request.getInputStream() 的数据
        if (method.equals(request.getMethod()) && "GET".equalsIgnoreCase(method)) {
            httpResponse = httpUtil.sendGetRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request)).getT();
        } else {
            //如果是表单数据提交不关心请求头，反之将所有请求头都发到插件服务
            if ("application/x-www-form-urlencoded".equals(request.getContentType())) {
                httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request)).getT();
            } else {
                httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri + "?" + request.getQueryString(), IOUtil.getByteByInputStream(request.getInputStream()), handle, PluginHelper.genHeaderMapByRequest(request)).getT();
            }
        }
        //添加插件服务的HTTP响应头到调用者响应头里面
        if (httpResponse != null) {
            Map<String, String> headerMap = new HashMap<>();
            Header[] headers = httpResponse.getAllHeaders();
            for (Header header : headers) {
                headerMap.put(header.getName(), header.getValue());
            }
            if (JFinal.me().getConstants().getDevMode()) {
                LOGGER.info(uri + " --------------------------------- response");
            }
            for (Map.Entry<String, String> t : headerMap.entrySet()) {
                if (JFinal.me().getConstants().getDevMode()) {
                    LOGGER.info("key " + t.getKey() + " value-> " + t.getValue());
                }
            }
        }
        return handle;
    }
//  [java]
	public static ResourceEvaluation evaluate(File file, String filename) {
		ResourceEvaluation eval = new ResourceEvaluation();
		try {
			ImsManifestFileFilter visitor = new ImsManifestFileFilter();
			Path fPath = PathUtils.visit(file, filename, visitor);
			if(visitor.hasManifest()) {
				Path realManifestPath = visitor.getManifestPath();
				Path manifestPath = fPath.resolve(realManifestPath);
				
				RootSearcher rootSearcher = new RootSearcher();
				Files.walkFileTree(fPath, EnumSet.noneOf(FileVisitOption.class), 16, rootSearcher);
				if(rootSearcher.foundRoot()) {
					manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);
				} else {
					manifestPath = fPath.resolve(IMS_MANIFEST);
				}

				Document doc = IMSLoader.loadIMSDocument(manifestPath);
				if(validateImsManifest(doc)) {
					if(visitor.hasEditorTreeModel()) {
						XMLScanner scanner = new XMLScanner();
						scanner.scan(visitor.getEditorTreeModelPath());
						eval.setValid(!scanner.hasEditorTreeModelMarkup());	
					} else {
						eval.setValid(true);
					}
				} else {
					eval.setValid(false);
				}
			} else {
				eval.setValid(false);
			}
			PathUtils.closeSubsequentFS(fPath);
		} catch (IOException | IllegalArgumentException e) {
			log.error("", e);
			eval.setValid(false);
		}
		return eval;
	}
//  [java]
	public static ResourceEvaluation evaluate(File file, String filename) {
		ResourceEvaluation eval = new ResourceEvaluation();
		try {
			ImsManifestFileFilter visitor = new ImsManifestFileFilter();
			Path fPath = PathUtils.visit(file, filename, visitor);
			if(visitor.hasManifest()) {
				Path realManifestPath = visitor.getManifestPath();
				Path manifestPath = fPath.resolve(realManifestPath);
				
				RootSearcher rootSearcher = new RootSearcher();
				Files.walkFileTree(fPath, rootSearcher);
				if(rootSearcher.foundRoot()) {
					manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);
				} else {
					manifestPath = fPath.resolve(IMS_MANIFEST);
				}

				Document doc = IMSLoader.loadIMSDocument(manifestPath);
				if(validateImsManifest(doc)) {
					if(visitor.hasEditorTreeModel()) {
						XMLScanner scanner = new XMLScanner();
						scanner.scan(visitor.getEditorTreeModelPath());
						eval.setValid(!scanner.hasEditorTreeModelMarkup());	
					} else {
						eval.setValid(true);
					}
				} else {
					eval.setValid(false);
				}
			} else {
				eval.setValid(false);
			}
			PathUtils.closeSubsequentFS(fPath);
		} catch (IOException | IllegalArgumentException e) {
			log.error("", e);
			eval.setValid(false);
		}
		return eval;
	}
//  [java]
    public void translate(GeyserSession session, RespawnPacket packet) {
        if (packet.getState() == RespawnPacket.State.CLIENT_READY) {
            // Previously we only sent the respawn packet before the server finished loading
            // The message included was 'Otherwise when immediate respawn is on the client never loads'
            // But I assume the new if statement below fixes that problem
            RespawnPacket respawnPacket = new RespawnPacket();
            respawnPacket.setRuntimeEntityId(0);
            respawnPacket.setPosition(Vector3f.ZERO);
            respawnPacket.setState(RespawnPacket.State.SERVER_READY);
            session.sendUpstreamPacket(respawnPacket);

            if (session.isSpawned()) {
                // Client might be stuck; resend spawn information
                PlayerEntity entity = session.getPlayerEntity();
                if (entity == null) return;
                SetEntityDataPacket entityDataPacket = new SetEntityDataPacket();
                entityDataPacket.setRuntimeEntityId(entity.getGeyserId());
                entityDataPacket.getMetadata().putAll(entity.getMetadata());
                session.sendUpstreamPacket(entityDataPacket);

                MovePlayerPacket movePlayerPacket = new MovePlayerPacket();
                movePlayerPacket.setRuntimeEntityId(entity.getGeyserId());
                movePlayerPacket.setPosition(entity.getPosition());
                movePlayerPacket.setRotation(entity.getBedrockRotation());
                movePlayerPacket.setMode(MovePlayerPacket.Mode.RESPAWN);
                session.sendUpstreamPacket(movePlayerPacket);
            }

            ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);
            session.sendDownstreamPacket(javaRespawnPacket);
        }
    }
//  [java]
    public void translate(RespawnPacket packet, GeyserSession session) {
        if (packet.getState() == RespawnPacket.State.CLIENT_READY) {
            // Previously we only sent the respawn packet before the server finished loading
            // The message included was 'Otherwise when immediate respawn is on the client never loads'
            // But I assume the new if statement below fixes that problem
            RespawnPacket respawnPacket = new RespawnPacket();
            respawnPacket.setRuntimeEntityId(0);
            respawnPacket.setPosition(Vector3f.ZERO);
            respawnPacket.setState(RespawnPacket.State.SERVER_READY);
            session.sendUpstreamPacket(respawnPacket);

            if (session.isSpawned()) {
                // Client might be stuck; resend spawn information
                PlayerEntity entity = session.getPlayerEntity();
                if (entity == null) return;
                SetEntityDataPacket entityDataPacket = new SetEntityDataPacket();
                entityDataPacket.setRuntimeEntityId(entity.getGeyserId());
                entityDataPacket.getMetadata().putAll(entity.getMetadata());
                session.sendUpstreamPacket(entityDataPacket);

                MovePlayerPacket movePlayerPacket = new MovePlayerPacket();
                movePlayerPacket.setRuntimeEntityId(entity.getGeyserId());
                movePlayerPacket.setPosition(entity.getPosition());
                movePlayerPacket.setRotation(entity.getBedrockRotation());
                movePlayerPacket.setMode(MovePlayerPacket.Mode.RESPAWN);
                session.sendUpstreamPacket(movePlayerPacket);
            }

            ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);
            session.sendDownstreamPacket(javaRespawnPacket);
        }
    }
//  [java]
	public void onTurnEnded(TurnEndedEvent event) {
		super.onTurnEnded(event);

		final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();

		if (out.contains("java.lang.SecurityException:")) {
			securityExceptionOccurred = true;	
		}	
	}
//  [java]
	public void onTurnEnded(TurnEndedEvent event) {
		super.onTurnEnded(event);

		final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();

		if (out.contains("access denied (java.net.SocketPermission")
				|| out.contains("access denied (\"java.net.SocketPermission\"")) {
			messagedAccessDenied = true;	
		}	
	}
//  [java]
    public static void execute(String url, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword,
            String accessToken, String orgName, String moduleName, String version, Path baloPath) {
        HttpsURLConnection conn = createHttpsUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
                                                           proxyPassword);
        conn.setInstanceFollowRedirects(false);
        setRequestMethod(conn, Utils.RequestMethod.POST);

        // Set headers
        conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        conn.setRequestProperty(PUSH_ORGANIZATION, orgName);
        conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);

        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(BUFFER_SIZE);

        try (DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream())) {
            // Send balo content by 1 kb chunks
            byte[] buffer = new byte[BUFFER_SIZE];
            int count;
            try (ProgressBar progressBar = new ProgressBar(
                    orgName + "/" + moduleName + ":" + version + " [project repo -> central]",
                    getTotalFileSizeInKB(baloPath), 1000, outStream, ProgressBarStyle.ASCII, " KB", 1);
                    FileInputStream fis = new FileInputStream(baloPath.toFile())) {
                while ((count = fis.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, count);
                    outputStream.flush();
                    progressBar.stepBy((long) NO_OF_BYTES);
                }
            }
        } catch (IOException e) {
            throw ErrorUtil.createCommandException("error occurred while uploading balo to central: " + e.getMessage());
        }

        handleResponse(conn, orgName, moduleName, version);
        Authenticator.setDefault(null);
    }
//  [java]
    public static void execute(String url, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword,
            String accessToken, String orgName, String moduleName, String version, Path baloPath) {
        initializeSsl();
        HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
                proxyPassword);
        conn.setInstanceFollowRedirects(false);
        setRequestMethod(conn, Utils.RequestMethod.POST);

        // Set headers
        conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        conn.setRequestProperty(PUSH_ORGANIZATION, orgName);
        conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);

        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(BUFFER_SIZE);

        try (DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream())) {
            // Send balo content by 1 kb chunks
            byte[] buffer = new byte[BUFFER_SIZE];
            int count;
            try (ProgressBar progressBar = new ProgressBar(
                    orgName + "/" + moduleName + ":" + version + " [project repo -> central]",
                    getTotalFileSizeInKB(baloPath), 1000, outStream, ProgressBarStyle.ASCII, " KB", 1);
                    FileInputStream fis = new FileInputStream(baloPath.toFile())) {
                while ((count = fis.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, count);
                    outputStream.flush();
                    progressBar.stepBy((long) NO_OF_BYTES);
                }
            }
        } catch (IOException e) {
            throw ErrorUtil.createCommandException("error occurred while uploading balo to central: " + e.getMessage());
        }

        handleResponse(conn, orgName, moduleName, version);
        Authenticator.setDefault(null);
    }
//  [java]
	protected void runTeardown() {
		Assert.assertTrue("Socket connection is not allowed", securityExceptionOccurred);
	}
//  [java]
	protected void runTeardown() {
		Assert.assertTrue("HTTP connection is not allowed", messagedAccessDenied);
	}
//  [java]
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        
        Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
        Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        if (err != null) {
            err.printStackTrace(pw);
        } else {
            pw.println("(none)");
        }
        pw.flush();
         
        // If we are here there was no error servlet, so show the default error page
        String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage",
                new String[] { sc + "", URIUtil.htmlEscape(msg == null ? "" : msg), URIUtil.htmlEscape(sw.toString()),
                Launcher.RESOURCES.getString("ServerVersion"),
                        "" + new Date() });
        response.setContentLength(output.getBytes(response.getCharacterEncoding()).length);
        Writer out = response.getWriter();
        out.write(output);
        out.flush();
    }
//  [java]
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        
        Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
        Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        if (err != null) {
            err.printStackTrace(pw);
        } else {
            pw.println("(none)");
        }
        pw.flush();
         
        // If we are here there was no error servlet, so show the default error page
        String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage",
                new String[] { sc + "", (msg == null ? "" : msg), sw.toString(),
                Launcher.RESOURCES.getString("ServerVersion"),
                        "" + new Date() });
        response.setContentLength(output.getBytes(response.getCharacterEncoding()).length);
        Writer out = response.getWriter();
        out.write(output);
        out.flush();
    }
//  [java]
    public void withRestrictor() throws InvalidSyntaxException, MalformedObjectNameException {
        setupRestrictor(new InnerRestrictor(true,false,true,false,true,false,true));
        assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.GET));
        assertFalse(restrictor.isTypeAllowed(RequestType.EXEC));
        assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
        assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
        assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Memory"), "gc"));
        assertFalse(restrictor.isRemoteAccessAllowed("localhost", "127.0.0.1"));
        assertTrue(restrictor.isOriginAllowed("http://bla.com", false));
    }
//  [java]
    public void withRestrictor() throws InvalidSyntaxException, MalformedObjectNameException {
        setupRestrictor(new InnerRestrictor(true,false,true,false,true,false,true));
        assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.GET));
        assertFalse(restrictor.isTypeAllowed(RequestType.EXEC));
        assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
        assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
        assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Memory"), "gc"));
        assertFalse(restrictor.isRemoteAccessAllowed("localhost", "127.0.0.1"));
        assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
    }
//  [java]
    public Response workspaceClientEnqueue(@FormParam(WorkSpaceAdapter.CLIENT_NAME) String clientName,
            @FormParam(WorkSpaceAdapter.WORK_BUNDLE_OBJ) String workBundleString) {
        logger.debug("TPWorker incoming execute! check prio={}", Thread.currentThread().getPriority());
        // TODO Doesn't look like anything is actually calling this, should we remove this?
        final boolean success;
        try {
            // Look up the place reference
            final String nsName = KeyManipulator.getServiceLocation(clientName);
            final IPickUpSpace place = (IPickUpSpace) Namespace.lookup(nsName);
            if (place == null) {
                throw new IllegalArgumentException("No client place found using name " + clientName);
            }

            final DataInputStream ois = new DataInputStream(new ByteArrayInputStream(workBundleString.getBytes("8859_1")));
            WorkBundle paths = WorkBundle.readFromStream(ois);
            success = place.enque(paths);
        } catch (Exception e) {
            logger.warn("WorkSpaceClientEnqueWorker exception", e);
            return Response.serverError().entity("WorkSpaceClientEnqueWorker exception:\n" + e.getMessage()).build();
        }

        if (success) {
            // old success from WorkSpaceClientEnqueWorker
            // return WORKER_SUCCESS;
            return Response.ok().entity("Successful add to the PickUpPlaceClient queue").build();
        } else {
            // old failure from WorkSpaceClientEnqueWorker
            // return new WorkerStatus(WorkerStatus.FAILURE, "WorkSpaceClientEnqueWorker failed, queue full");
            return Response.serverError().entity("WorkSpaceClientEnqueWorker failed, queue full").build();
        }
    }
//  [java]
    public Response workspaceClientEnqueue(@FormParam(WorkSpaceAdapter.CLIENT_NAME) String clientName,
            @FormParam(WorkSpaceAdapter.WORK_BUNDLE_OBJ) String workBundleString) {
        logger.debug("TPWorker incoming execute! check prio={}", Thread.currentThread().getPriority());
        // TODO Doesn't look like anything is actually calling this, should we remove this?
        final boolean success;
        try {
            // Look up the place reference
            final String nsName = KeyManipulator.getServiceLocation(clientName);
            final IPickUpSpace place = (IPickUpSpace) Namespace.lookup(nsName);
            if (place == null) {
                throw new IllegalArgumentException("No client place found using name " + clientName);
            }

            final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(workBundleString.getBytes("8859_1")));
            WorkBundle paths = (WorkBundle) ois.readObject();
            success = place.enque(paths);
        } catch (Exception e) {
            logger.warn("WorkSpaceClientEnqueWorker exception", e);
            return Response.serverError().entity("WorkSpaceClientEnqueWorker exception:\n" + e.getMessage()).build();
        }

        if (success) {
            // old success from WorkSpaceClientEnqueWorker
            // return WORKER_SUCCESS;
            return Response.ok().entity("Successful add to the PickUpPlaceClient queue").build();
        } else {
            // old failure from WorkSpaceClientEnqueWorker
            // return new WorkerStatus(WorkerStatus.FAILURE, "WorkSpaceClientEnqueWorker failed, queue full");
            return Response.serverError().entity("WorkSpaceClientEnqueWorker failed, queue full").build();
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerSpawnParticlePacket packet) {
        Function<Vector3f, BedrockPacket> particleCreateFunction = createParticle(session, packet.getParticle());
        if (particleCreateFunction != null) {
            if (packet.getAmount() == 0) {
                // 0 means don't apply the offset
                Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
                session.sendUpstreamPacket(particleCreateFunction.apply(position));
            } else {
                Random random = ThreadLocalRandom.current();
                for (int i = 0; i < packet.getAmount(); i++) {
                    double offsetX = random.nextGaussian() * (double) packet.getOffsetX();
                    double offsetY = random.nextGaussian() * (double) packet.getOffsetY();
                    double offsetZ = random.nextGaussian() * (double) packet.getOffsetZ();
                    Vector3f position = Vector3f.from(packet.getX() + offsetX, packet.getY() + offsetY, packet.getZ() + offsetZ);

                    session.sendUpstreamPacket(particleCreateFunction.apply(position));
                }
            }
        } else {
            // Null is only returned when no particle of this type is found
            session.getConnector().getLogger().debug("Unhandled particle packet: " + packet);
        }
    }
//  [java]
    public void translate(ServerSpawnParticlePacket packet, GeyserSession session) {
        Function<Vector3f, BedrockPacket> particleCreateFunction = createParticle(session, packet.getParticle());
        if (particleCreateFunction != null) {
            if (packet.getAmount() == 0) {
                // 0 means don't apply the offset
                Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
                session.sendUpstreamPacket(particleCreateFunction.apply(position));
            } else {
                Random random = ThreadLocalRandom.current();
                for (int i = 0; i < packet.getAmount(); i++) {
                    double offsetX = random.nextGaussian() * (double) packet.getOffsetX();
                    double offsetY = random.nextGaussian() * (double) packet.getOffsetY();
                    double offsetZ = random.nextGaussian() * (double) packet.getOffsetZ();
                    Vector3f position = Vector3f.from(packet.getX() + offsetX, packet.getY() + offsetY, packet.getZ() + offsetZ);

                    session.sendUpstreamPacket(particleCreateFunction.apply(position));
                }
            }
        } else {
            // Null is only returned when no particle of this type is found
            session.getConnector().getLogger().debug("Unhandled particle packet: " + packet);
        }
    }
//  [java]
    private String getMimeType(ParsedUri pParsedUri) {
        return MimeTypeUtil.getResponseMimeType(
            pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue()),
            configuration.get(ConfigKey.MIME_TYPE),
            pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()));
    }
//  [java]
    private String getMimeType(ParsedUri pParsedUri) {
        if (pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()) != null) {
            return "text/javascript";
        } else {
            String mimeType = pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue());
            if (mimeType != null) {
                return mimeType;
            }
            mimeType = configuration.get(ConfigKey.MIME_TYPE);
            return mimeType != null ? mimeType : ConfigKey.MIME_TYPE.getDefaultValue();
        }
    }
//  [java]
    public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)
        throws IOException
    {
        XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
        this.treeDigest = keyParams.getTreeDigest().getAlgorithm();

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

        try
        {
            XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
                .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))
                .withIndex(xmssPrivateKey.getIndex())
                .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())
                .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())
                .withPublicSeed(xmssPrivateKey.getPublicSeed())
                .withRoot(xmssPrivateKey.getRoot());

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

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

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

        try
        {
            XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
                .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))
                .withIndex(xmssPrivateKey.getIndex())
                .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())
                .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())
                .withPublicSeed(xmssPrivateKey.getPublicSeed())
                .withRoot(xmssPrivateKey.getRoot());

            if (xmssPrivateKey.getBdsState() != null)
            {
                keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));
            }

            this.keyParams = keyBuilder.build();
        }
        catch (ClassNotFoundException e)
        {
            throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
        }
    }
//  [java]
    private void sendAllJSON(HttpExchange pExchange, ParsedUri pParsedUri, JSONAware pJson) throws IOException {
        OutputStream out = null;
        try {
            Headers headers = pExchange.getResponseHeaders();
            if (pJson != null) {
                headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
                String json = pJson.toJSONString();
                String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
                String content = callback != null && MimeTypeUtil.isValidCallback(callback) ? callback + "(" + json + ");" : json;
                byte[] response = content.getBytes("UTF8");
                pExchange.sendResponseHeaders(200,response.length);
                out = pExchange.getResponseBody();
                out.write(response);
            } else {
                headers.set("Content-Type", "text/plain");
                pExchange.sendResponseHeaders(200,-1);
            }
        } finally {
            if (out != null) {
                // Always close in order to finish the request.
                // Otherwise the thread blocks.
                out.close();
            }
        }
    }
//  [java]
    private void sendAllJSON(HttpExchange pExchange, ParsedUri pParsedUri, JSONAware pJson) throws IOException {
        OutputStream out = null;
        try {
            Headers headers = pExchange.getResponseHeaders();
            if (pJson != null) {
                headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
                String json = pJson.toJSONString();
                String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
                String content = callback == null ? json : callback + "(" + json + ");";
                byte[] response = content.getBytes("UTF8");
                pExchange.sendResponseHeaders(200,response.length);
                out = pExchange.getResponseBody();
                out.write(response);
            } else {
                headers.set("Content-Type", "text/plain");
                pExchange.sendResponseHeaders(200,-1);
            }
        } finally {
            if (out != null) {
                // Always close in order to finish the request.
                // Otherwise the thread blocks.
                out.close();
            }
        }
    }
//  [java]
    private void sendStreamingResponse(HttpExchange pExchange, ParsedUri pParsedUri, JSONStreamAware pJson) throws IOException {
        Headers headers = pExchange.getResponseHeaders();
        if (pJson != null) {
            headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
            pExchange.sendResponseHeaders(200, 0);
            Writer writer = new OutputStreamWriter(pExchange.getResponseBody(), "UTF-8");

            String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
            IoUtil.streamResponseAndClose(writer, pJson, callback != null && MimeTypeUtil.isValidCallback(callback) ? callback : null);
        } else {
            headers.set("Content-Type", "text/plain");
            pExchange.sendResponseHeaders(200,-1);
        }
    }
//  [java]
    private void sendStreamingResponse(HttpExchange pExchange, ParsedUri pParsedUri, JSONStreamAware pJson) throws IOException {
        Headers headers = pExchange.getResponseHeaders();
        if (pJson != null) {
            headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
            String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
            pExchange.sendResponseHeaders(200, 0);
            Writer writer = new OutputStreamWriter(pExchange.getResponseBody(), "UTF-8");
            IoUtil.streamResponseAndClose(writer, pJson, callback);
        } else {
            headers.set("Content-Type", "text/plain");
            pExchange.sendResponseHeaders(200,-1);
        }
    }
//  [java]
	public PlayerRobustConcise(TimingStyle type, String full, ISkinParam skinParam, TimingRuler ruler, boolean compact,
			Stereotype stereotype) {
		super(full, skinParam, ruler, compact, stereotype);
		this.type = type;
		this.suggestedHeight = 0;
	}
//  [java]
	public PlayerRobustConcise(TimingStyle type, String full, ISkinParam skinParam, TimingRuler ruler,
			boolean compact) {
		super(full, skinParam, ruler, compact);
		this.type = type;
		this.suggestedHeight = 0;
	}
//  [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(false);
			// 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 !!!");
	}