jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    public void notExistingDocumentFromUIButSpaceTooLong() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(10);
        context.setDoc(document);

        when(mockRequest.getParameter("spaceReference")).thenReturn("1.3.5.7.9.11");
        when(mockRequest.getParameter("name")).thenReturn("Foo");

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify that the create template is rendered, so the UI is displayed for the user to see the error.
        assertEquals("create", result);

        // Check that the exception is properly set in the context for the UI to display.
        XWikiException exception = (XWikiException) this.oldcore.getScriptContext().getAttribute("createException");
        assertNotNull(exception);
        assertEquals(XWikiException.ERROR_XWIKI_APP_DOCUMENT_PATH_TOO_LONG, exception.getCode());

        // We should not get this far so no redirect should be done, just the template will be rendered.
        verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),
            any(), any(XWikiContext.class));
    }
//  [java]
    public void translate(GeyserSession session, EntityEventPacket packet) {
        switch (packet.getType()) {
            case EATING_ITEM:
                // Resend the packet so we get the eating sounds
                session.sendUpstreamPacket(packet);
                return;
            case COMPLETE_TRADE:
                ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData());
                session.sendDownstreamPacket(selectTradePacket);

                session.scheduleInEventLoop(() -> {
                    Entity villager = session.getPlayerEntity();
                    Inventory openInventory = session.getOpenInventory();
                    if (openInventory instanceof MerchantContainer) {
                        MerchantContainer merchantInventory = (MerchantContainer) openInventory;
                        VillagerTrade[] trades = merchantInventory.getVillagerTrades();
                        if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) {
                            VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()];
                            openInventory.setItem(2, GeyserItemStack.from(trade.getOutput()), session);
                            villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP));
                            villager.updateBedrockMetadata(session);
                        }
                    }
                }, 100, TimeUnit.MILLISECONDS);
                return;
        }
        session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + packet.toString());
    }
//  [java]
    public void translate(EntityEventPacket packet, GeyserSession session) {
        switch (packet.getType()) {
            case EATING_ITEM:
                // Resend the packet so we get the eating sounds
                session.sendUpstreamPacket(packet);
                return;
            case COMPLETE_TRADE:
                ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData());
                session.sendDownstreamPacket(selectTradePacket);

                session.scheduleInEventLoop(() -> {
                    Entity villager = session.getPlayerEntity();
                    Inventory openInventory = session.getOpenInventory();
                    if (openInventory instanceof MerchantContainer) {
                        MerchantContainer merchantInventory = (MerchantContainer) openInventory;
                        VillagerTrade[] trades = merchantInventory.getVillagerTrades();
                        if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) {
                            VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()];
                            openInventory.setItem(2, GeyserItemStack.from(trade.getOutput()), session);
                            villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP));
                            villager.updateBedrockMetadata(session);
                        }
                    }
                }, 100, TimeUnit.MILLISECONDS);
                return;
        }
        session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + packet.toString());
    }
//  [java]
	protected int getExpectedErrors() {
		return 2;
	}
//  [java]
	protected int getExpectedErrors() {
		return hasJavaNetURLPermission ? 3 : 2; // Security error must be reported as an error
	}
//  [java]
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession(false);
        String token = request.getHeader(LoginTokenServlet.LOGIN_TOKEN);

        if (token == null || session == null) {
            Helpers.doForbidden(response);
            return;
        }

        String sessionToken = (String) session.getAttribute(LoginTokenServlet.LOGIN_TOKEN);
        if (!token.equals(sessionToken)) {
            Helpers.doForbidden(response);
            return;
        }

        String encoding = request.getHeader("Accept-Encoding");
        boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
        SessionTerminal st = (SessionTerminal) session.getAttribute("terminal");
        if (st == null || st.isClosed()) {
            st = new SessionTerminal(getCommandProcessor(), getThreadIO());
            session.setAttribute("terminal", st);
        }
        String str = request.getParameter("k");
        String f = request.getParameter("f");
        String dump = st.handle(str, f != null && f.length() > 0);
        if (dump != null) {
            if (supportsGzip) {
                response.setHeader("Content-Encoding", "gzip");
                response.setHeader("Content-Type", "text/html");
                try {
                    GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
                    gzos.write(dump.getBytes());
                    gzos.close();
                } catch (IOException ie) {
                    LOG.info("Exception writing response: ", ie);
                }
            } else {
                response.getOutputStream().write(dump.getBytes());
            }
        }
    }
//  [java]
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession(false);
        if (session == null) {
          AccessControlContext acc = AccessController.getContext();
          Subject subject = Subject.getSubject(acc);
          if (subject == null) {
            Helpers.doForbidden(response);
            return;
          }
          session = request.getSession(true);
          session.setAttribute("subject", subject);
        } else {
          Subject subject = (Subject) session.getAttribute("subject");
          if (subject == null) {
            session.invalidate();
            Helpers.doForbidden(response);
            return;
          }
        }

        String encoding = request.getHeader("Accept-Encoding");
        boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
        SessionTerminal st = (SessionTerminal) session.getAttribute("terminal");
        if (st == null || st.isClosed()) {
            st = new SessionTerminal(getCommandProcessor(), getThreadIO());
            session.setAttribute("terminal", st);
        }
        String str = request.getParameter("k");
        String f = request.getParameter("f");
        String dump = st.handle(str, f != null && f.length() > 0);
        if (dump != null) {
            if (supportsGzip) {
                response.setHeader("Content-Encoding", "gzip");
                response.setHeader("Content-Type", "text/html");
                try {
                    GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
                    gzos.write(dump.getBytes());
                    gzos.close();
                } catch (IOException ie) {
                    LOG.info("Exception writing response: ", ie);
                }
            } else {
                response.getOutputStream().write(dump.getBytes());
            }
        }
    }
//  [java]
	private TextBlock getTitleBlock(IGroup g) {
		final Display label = g.getDisplay();
		if (label == null)
			return TextBlockUtils.empty(0, 0);

		final ISkinParam skinParam = dotData.getSkinParam();

		final SName sname = dotData.getUmlDiagramType().getStyleName();
		final StyleSignatureBasic signature;
		final USymbol uSymbol = g.getUSymbol();
		if (g.getGroupType() == GroupType.STATE)
			signature = StyleSignatureBasic.of(SName.root, SName.element, SName.stateDiagram, SName.state,
					SName.header);
		else if (uSymbol == USymbols.RECTANGLE)
			signature = StyleSignatureBasic.of(SName.root, SName.element, sname, uSymbol.getSName(), SName.title);
		else
			signature = StyleSignatureBasic.of(SName.root, SName.element, sname, SName.title);

		final Style style = signature //
				.withTOBECHANGED(g.getStereotype()) //
				.with(g.getStereostyles()) //
				.getMergedStyle(skinParam.getCurrentStyleBuilder());

		final FontConfiguration fontConfiguration = style.getFontConfiguration(skinParam.getThemeStyle(),
				skinParam.getIHtmlColorSet());

		final HorizontalAlignment alignment = HorizontalAlignment.CENTER;
		return label.create(fontConfiguration, alignment, dotData.getSkinParam());
	}
//  [java]
	private TextBlock getTitleBlock(IGroup g) {
		final Display label = g.getDisplay();
		if (label == null)
			return TextBlockUtils.empty(0, 0);

		final ISkinParam skinParam = dotData.getSkinParam();
		final FontConfiguration fontConfiguration;
		if (UseStyle.useBetaStyle()) {
			final SName sname = dotData.getUmlDiagramType().getStyleName();
			final StyleSignatureBasic signature;
			final USymbol uSymbol = g.getUSymbol();
			if (uSymbol == USymbols.RECTANGLE)
				signature = StyleSignatureBasic.of(SName.root, SName.element, sname, uSymbol.getSName(), SName.title);
			else
				signature = StyleSignatureBasic.of(SName.root, SName.element, sname, SName.title);

			final Style style = signature //
					.withTOBECHANGED(g.getStereotype()) //
					.with(g.getStereostyles()) //
					.getMergedStyle(skinParam.getCurrentStyleBuilder());

			fontConfiguration = style.getFontConfiguration(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());
		} else
			fontConfiguration = g.getFontConfigurationForTitle(skinParam);
		final HorizontalAlignment alignment = HorizontalAlignment.CENTER;
		return label.create(fontConfiguration, alignment, dotData.getSkinParam());
	}
//  [java]
	public UPathHand(UPath source, Random rnd) {

		final UPath result = new UPath();

		Point2D last = new Point2D.Double();

		for (USegment segment : source) {
			final USegmentType type = segment.getSegmentType();
			if (type == USegmentType.SEG_MOVETO) {
				final double x = segment.getCoord()[0];
				final double y = segment.getCoord()[1];
				result.moveTo(x, y);
				last = new Point2D.Double(x, y);
			} else if (type == USegmentType.SEG_CUBICTO) {
				final double x2 = segment.getCoord()[4];
				final double y2 = segment.getCoord()[5];
				final HandJiggle jiggle = HandJiggle.create(last, 2.0, rnd);

				final CubicCurve2D tmp = new CubicCurve2D.Double(last.getX(), last.getY(), segment.getCoord()[0],
						segment.getCoord()[1], segment.getCoord()[2], segment.getCoord()[3], x2, y2);
				jiggle.curveTo(tmp);
				jiggle.appendTo(result);
				last = new Point2D.Double(x2, y2);
			} else if (type == USegmentType.SEG_LINETO) {
				final double x = segment.getCoord()[0];
				final double y = segment.getCoord()[1];
				final HandJiggle jiggle = new HandJiggle(last.getX(), last.getY(), defaultVariation, rnd);
				jiggle.lineTo(x, y);
				for (USegment seg2 : jiggle.toUPath())
					if (seg2.getSegmentType() == USegmentType.SEG_LINETO)
						result.lineTo(seg2.getCoord()[0], seg2.getCoord()[1]);

				last = new Point2D.Double(x, y);
			} else if (type == USegmentType.SEG_ARCTO) {
				final double x = segment.getCoord()[5];
				final double y = segment.getCoord()[6];
				result.lineTo(x, y);
				last = new Point2D.Double(x, y);
			} else {
				this.path = source;
				return;
			}
		}
		this.path = result;
		this.path.setDeltaShadow(source.getDeltaShadow());
	}
//  [java]
	public UPathHand(UPath source, Random rnd) {

		final UPath result = new UPath();

		Point2D last = new Point2D.Double();

		for (USegment segment : source) {
			final USegmentType type = segment.getSegmentType();
			if (type == USegmentType.SEG_MOVETO) {
				final double x = segment.getCoord()[0];
				final double y = segment.getCoord()[1];
				result.moveTo(x, y);
				last = new Point2D.Double(x, y);
			} else if (type == USegmentType.SEG_CUBICTO) {
				final double x2 = segment.getCoord()[4];
				final double y2 = segment.getCoord()[5];
				final HandJiggle jiggle = HandJiggle.create(last, 2.0, rnd);

				final CubicCurve2D tmp = new CubicCurve2D.Double(last.getX(), last.getY(), segment.getCoord()[0],
						segment.getCoord()[1], segment.getCoord()[2], segment.getCoord()[3], x2, y2);
				jiggle.curveTo(tmp);
				jiggle.appendTo(result);
				last = new Point2D.Double(x2, y2);
			} else if (type == USegmentType.SEG_LINETO) {
				final double x = segment.getCoord()[0];
				final double y = segment.getCoord()[1];
				final HandJiggle jiggle = new HandJiggle(last.getX(), last.getY(), defaultVariation, rnd);
				jiggle.lineTo(x, y);
				for (USegment seg2 : jiggle.toUPath()) {
					if (seg2.getSegmentType() == USegmentType.SEG_LINETO) {
						result.lineTo(seg2.getCoord()[0], seg2.getCoord()[1]);
					}
				}
				last = new Point2D.Double(x, y);
			} else {
				this.path = source;
				return;
			}
		}
		this.path = result;
		this.path.setDeltaShadow(source.getDeltaShadow());
	}
//  [java]
	public void onTurnEnded(TurnEndedEvent event) {
		super.onTurnEnded(event);

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

		if (out.contains("An error occurred during initialization")) {
			messagedInitialization = true;	
		}	

		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("An error occurred during initialization")) {
			messagedInitialization = true;	
		}	

		if (out.contains("access denied (java.net.SocketPermission")
				|| out.contains("access denied (\"java.net.SocketPermission\"")) {
			messagedAccessDenied = true;	
		}	
	}
//  [java]
    public void translate(GeyserSession session, ServerExplosionPacket packet) {
        for (ExplodedBlockRecord record : packet.getExploded()) {
            Vector3f pos = Vector3f.from(packet.getX() + record.getX(), packet.getY() + record.getY(), packet.getZ() + record.getZ());
            ChunkUtils.updateBlock(session, BlockStateValues.JAVA_AIR_ID, pos.toInt());
        }

        Vector3f pos = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
        // Since bedrock does not play an explosion sound and particles sound, we have to manually do so
        LevelEventPacket levelEventPacket = new LevelEventPacket();
        levelEventPacket.setType(packet.getRadius() >= 2.0f ? LevelEventType.PARTICLE_HUGE_EXPLODE : LevelEventType.PARTICLE_EXPLOSION);
        levelEventPacket.setData(0);
        levelEventPacket.setPosition(pos.toFloat());
        session.sendUpstreamPacket(levelEventPacket);

        LevelSoundEventPacket levelSoundEventPacket = new LevelSoundEventPacket();
        levelSoundEventPacket.setRelativeVolumeDisabled(false);
        levelSoundEventPacket.setBabySound(false);
        levelSoundEventPacket.setExtraData(-1);
        levelSoundEventPacket.setSound(SoundEvent.EXPLODE);
        levelSoundEventPacket.setIdentifier(":");
        levelSoundEventPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ()));
        session.sendUpstreamPacket(levelSoundEventPacket);

        if (packet.getPushX() > 0f || packet.getPushY() > 0f || packet.getPushZ() > 0f) {
            SetEntityMotionPacket motionPacket = new SetEntityMotionPacket();
            motionPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());
            motionPacket.setMotion(Vector3f.from(packet.getPushX(), packet.getPushY(), packet.getPushZ()));
            session.sendUpstreamPacket(motionPacket);
        }
    }
//  [java]
    public void translate(ServerExplosionPacket packet, GeyserSession session) {
        for (ExplodedBlockRecord record : packet.getExploded()) {
            Vector3f pos = Vector3f.from(packet.getX() + record.getX(), packet.getY() + record.getY(), packet.getZ() + record.getZ());
            ChunkUtils.updateBlock(session, BlockStateValues.JAVA_AIR_ID, pos.toInt());
        }

        Vector3f pos = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
        // Since bedrock does not play an explosion sound and particles sound, we have to manually do so
        LevelEventPacket levelEventPacket = new LevelEventPacket();
        levelEventPacket.setType(packet.getRadius() >= 2.0f ? LevelEventType.PARTICLE_HUGE_EXPLODE : LevelEventType.PARTICLE_EXPLOSION);
        levelEventPacket.setData(0);
        levelEventPacket.setPosition(pos.toFloat());
        session.sendUpstreamPacket(levelEventPacket);

        LevelSoundEventPacket levelSoundEventPacket = new LevelSoundEventPacket();
        levelSoundEventPacket.setRelativeVolumeDisabled(false);
        levelSoundEventPacket.setBabySound(false);
        levelSoundEventPacket.setExtraData(-1);
        levelSoundEventPacket.setSound(SoundEvent.EXPLODE);
        levelSoundEventPacket.setIdentifier(":");
        levelSoundEventPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ()));
        session.sendUpstreamPacket(levelSoundEventPacket);

        if (packet.getPushX() > 0f || packet.getPushY() > 0f || packet.getPushZ() > 0f) {
            SetEntityMotionPacket motionPacket = new SetEntityMotionPacket();
            motionPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());
            motionPacket.setMotion(Vector3f.from(packet.getPushX(), packet.getPushY(), packet.getPushZ()));
            session.sendUpstreamPacket(motionPacket);
        }
    }
//  [java]
    public void setupRoutes() {
        path(controllerBasePath(), () -> {
            before("", mimeType, this::setContentType);
            before("/*", mimeType, this::setContentType);
            before("", mimeType, this::verifyContentType);
            before("/*", mimeType, this::verifyContentType);

            // change the line below to enable appropriate security
            before("", mimeType, this.apiAuthenticationHelper::checkAdminUserAnd403);

            get("", mimeType, this::show);

            post("", mimeType, this::createOrUpdate);
            put("", mimeType, this::createOrUpdate);

            delete("", mimeType, this::deleteBackupConfig);
        });
    }
//  [java]
    public void setupRoutes() {
        path(controllerBasePath(), () -> {
            before("", mimeType, this::setContentType);


            // change the line below to enable appropriate security
            before("", mimeType, this.apiAuthenticationHelper::checkAdminUserAnd403);

            get("", mimeType, this::show);

            post("", mimeType, this::createOrUpdate);
            put("", mimeType, this::createOrUpdate);

            delete("", mimeType, this::deleteBackupConfig);
        });
    }
//  [java]
	protected void runTeardown() {
		Assert.assertTrue("Error during initialization", messagedInitialization);
		Assert.assertTrue("Socket connection is not allowed", securityExceptionOccurred);
	}
//  [java]
	protected void runTeardown() {
		Assert.assertTrue("Error during initialization", messagedInitialization);
		Assert.assertTrue("HTTP connection is not allowed", messagedAccessDenied);
	}
//  [java]
    public Element handle(Element request, Map<String, Object> context) throws ServiceException {
        ZimbraSoapContext zsc = getZimbraSoapContext(context);
        Account account = getRequestedAccount(getZimbraSoapContext(context));

        if (!canAccessAccount(zsc, account))
            throw ServiceException.PERM_DENIED("can not access account");
        
        String name = request.getAttribute(AccountConstants.E_NAME);
        String typeStr = request.getAttribute(AccountConstants.A_TYPE, "account");
        GalSearchType type = GalSearchType.fromString(typeStr);

        boolean needCanExpand = request.getAttributeBool(AccountConstants.A_NEED_EXP, false);

        String galAcctId = request.getAttribute(AccountConstants.A_GAL_ACCOUNT_ID, null);
        
        GalSearchParams params = new GalSearchParams(account, zsc);
        params.setType(type);
        params.setRequest(request);
        params.setQuery(name);
        params.setLimit(account.getContactAutoCompleteMaxResults());
        params.setNeedCanExpand(needCanExpand);
        params.setResponseName(AccountConstants.AUTO_COMPLETE_GAL_RESPONSE);
        if (galAcctId != null) {
            Account galAccount = Provisioning.getInstance().getAccountById(galAcctId);
            if (galAccount != null && (!account.getDomainId().equals(galAccount.getDomainId()))) {
                throw ServiceException
                    .PERM_DENIED("can not access galsync account of different domain");
            }
            params.setGalSyncAccount(galAccount);
        }
        GalSearchControl gal = new GalSearchControl(params);
        gal.autocomplete();
        return params.getResultCallback().getResponse();
    }
//  [java]
    public Element handle(Element request, Map<String, Object> context) throws ServiceException {
        ZimbraSoapContext zsc = getZimbraSoapContext(context);
        Account account = getRequestedAccount(getZimbraSoapContext(context));

        if (!canAccessAccount(zsc, account))
            throw ServiceException.PERM_DENIED("can not access account");
        
        String name = request.getAttribute(AccountConstants.E_NAME);
        String typeStr = request.getAttribute(AccountConstants.A_TYPE, "account");
        GalSearchType type = GalSearchType.fromString(typeStr);

        boolean needCanExpand = request.getAttributeBool(AccountConstants.A_NEED_EXP, false);

        String galAcctId = request.getAttribute(AccountConstants.A_GAL_ACCOUNT_ID, null);
        
        GalSearchParams params = new GalSearchParams(account, zsc);
        params.setType(type);
        params.setRequest(request);
        params.setQuery(name);
        params.setLimit(account.getContactAutoCompleteMaxResults());
        params.setNeedCanExpand(needCanExpand);
        params.setResponseName(AccountConstants.AUTO_COMPLETE_GAL_RESPONSE);
        if (galAcctId != null)
            params.setGalSyncAccount(Provisioning.getInstance().getAccountById(galAcctId));
        GalSearchControl gal = new GalSearchControl(params);
        gal.autocomplete();
        return params.getResultCallback().getResponse();
    }
//  [java]
    public Connection getConnection(Context context) throws SQLException {
        String databaseType = context.getDatabaseType();
        DatabaseTypePojo type = databaseTypeDao.selectByDatabaseType(databaseType);
        File driverFile = driverResources.loadOrDownloadByDatabaseType(databaseType, type.getJdbcDriverFileUrl());

        URLClassLoader loader = null;
        try {
            loader = new URLClassLoader(
                    new URL[]{
                            driverFile.toURI().toURL()
                    },
                    this.getClass().getClassLoader()
            );
        } catch (MalformedURLException e) {
            log.error("load driver error " + context, e);
            throw DomainErrors.CONNECT_DATABASE_FAILED.exception(e.getMessage());
        }
        // retrieve the driver class

        Class<?> clazz = null;
        Driver driver = null;
        try {
            clazz = Class.forName(type.getJdbcDriverClassName(), false, loader);
            driver = (Driver) clazz.getConstructor().newInstance();
        } catch (ClassNotFoundException e) {
            log.error("init driver error", e);
            throw DomainErrors.CONNECT_DATABASE_FAILED.exception("驱动初始化异常, 请检查驱动类名：" + e.getMessage());
        } catch (InvocationTargetException
                 | InstantiationException
                 | IllegalAccessException
                 | NoSuchMethodException e) {
            log.error("init driver error", e);
            throw DomainErrors.CONNECT_DATABASE_FAILED.exception("驱动初始化异常：" + e.getMessage());
        }

        String urlPattern = type.getUrlPattern();
        String jdbcUrl = urlPattern.replace("{{jdbc.protocol}}", type.getJdbcProtocol())
                .replace("{{db.url}}", context.getUrl())
                .replace("{{db.name}}", context.getDatabaseName())
                .replace("{{db.schema}}", context.getSchemaName());
        Properties info = new Properties();
        info.put("user", context.getUsername());
        info.put("password", context.getPassword());
        return driver.connect(jdbcUrl, info);
    }
//  [java]
    public Connection getConnection(Context context) throws SQLException {
        DatabaseTypePojo type = databaseTypeDao.selectByDatabaseType(context.getDatabaseType());
        File driverFile = driverResources.loadOrDownload(context.getDatabaseType(), type.getJdbcDriverFileUrl());
        URLClassLoader loader = null;
        try {
            loader = new URLClassLoader(
                    new URL[]{
                            driverFile.toURI().toURL()
                    },
                    this.getClass().getClassLoader()
            );
        } catch (MalformedURLException e) {
            log.error("load driver error " + context, e);
            throw DomainErrors.CONNECT_DATABASE_FAILED.exception(e.getMessage());
        }
        // retrieve the driver class

        Class<?> clazz = null;
        Driver driver = null;
        try {
            clazz = Class.forName(type.getJdbcDriverClassName(), true, loader);
            driver = (Driver) clazz.getConstructor().newInstance();
        } catch (ClassNotFoundException e) {
            log.error("init driver error", e);
            throw DomainErrors.CONNECT_DATABASE_FAILED.exception("驱动初始化异常, 请检查 Driver name：" + e.getMessage());
        } catch (InvocationTargetException
                 | InstantiationException
                 | IllegalAccessException
                 | NoSuchMethodException e) {
            log.error("init driver error", e);
            throw DomainErrors.CONNECT_DATABASE_FAILED.exception("驱动初始化异常：" + e.getMessage());
        }

        String urlPattern = type.getUrlPattern();
        String jdbcUrl = urlPattern.replace("{{jdbc.protocol}}", type.getJdbcProtocol())
                .replace("{{db.url}}", context.getUrl())
                .replace("{{db.name}}", context.getDatabaseName())
                .replace("{{db.schema}}", context.getSchemaName());
        Properties info = new Properties();
        info.put("user", context.getUsername());
        info.put("password", context.getPassword());
        return driver.connect(jdbcUrl, info);
    }
//  [java]
    private Job startCreateJob(EntityReference entityReference, EditForm editForm) throws XWikiException
    {
        DocumentReference templateReference = resolveTemplate(editForm.getTemplate());

        if (templateReference == null) {
            // No template specified, nothing more to do.
            return null;
        }

        // If a template is set in the request, then this is a create action which needs to be handled by a create job,
        // but skipping the target document, which is now already saved by the save action.

        RefactoringScriptService refactoring =
            (RefactoringScriptService) Utils.getComponent(ScriptService.class, "refactoring");

        CreateRequest request = refactoring.getRequestFactory().createCreateRequest(Arrays.asList(entityReference));
        request.setCheckAuthorRights(false);
        // Set the target document.
        request.setEntityReferences(Arrays.asList(entityReference));
        // Set the template to use.
        request.setTemplateReference(templateReference);
        // We`ve already created and populated the fields of the target document, focus only on the remaining children
        // specified in the template.
        request.setSkippedEntities(Arrays.asList(entityReference));

        Job createJob = refactoring.create(request);
        if (createJob != null) {
            return createJob;
        } else {
            throw new XWikiException(String.format("Failed to schedule the create job for [%s]", entityReference),
                refactoring.getLastError());
        }
    }
//  [java]
    private Job startCreateJob(EntityReference entityReference, EditForm editForm) throws XWikiException
    {
        if (StringUtils.isBlank(editForm.getTemplate())) {
            // No template specified, nothing more to do.
            return null;
        }

        // If a template is set in the request, then this is a create action which needs to be handled by a create job,
        // but skipping the target document, which is now already saved by the save action.

        RefactoringScriptService refactoring =
            (RefactoringScriptService) Utils.getComponent(ScriptService.class, "refactoring");

        CreateRequest request = refactoring.getRequestFactory().createCreateRequest(Arrays.asList(entityReference));
        request.setCheckAuthorRights(false);
        // Set the target document.
        request.setEntityReferences(Arrays.asList(entityReference));
        // Set the template to use.
        DocumentReferenceResolver<String> resolver =
            Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, "currentmixed");
        EntityReference templateReference = resolver.resolve(editForm.getTemplate());
        request.setTemplateReference(templateReference);
        // We`ve already created and populated the fields of the target document, focus only on the remaining children
        // specified in the template.
        request.setSkippedEntities(Arrays.asList(entityReference));

        Job createJob = refactoring.create(request);
        if (createJob != null) {
            return createJob;
        } else {
            throw new XWikiException(String.format("Failed to schedule the create job for [%s]", entityReference),
                refactoring.getLastError());
        }
    }
//  [java]
    public void testGetShellCommandLineBash_WithWorkingDirectory()
        throws Exception
    {
        Commandline cmd = new Commandline( new BourneShell() );
        cmd.setExecutable( "/bin/echo" );
        cmd.addArguments( new String[] {
            "hello world"
        } );
        File root = File.listRoots()[0];
        File workingDirectory = new File( root, "path with spaces" );
        cmd.setWorkingDirectory( workingDirectory );

        String[] shellCommandline = cmd.getShellCommandline();

        assertEquals( "Command line size", 3, shellCommandline.length );

        assertEquals( "/bin/sh", shellCommandline[0] );
        assertEquals( "-c", shellCommandline[1] );
        String expectedShellCmd = "cd '" + root.getAbsolutePath()
                                  + "path with spaces' && '/bin/echo' 'hello world'";
        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            expectedShellCmd = "cd '" + root.getAbsolutePath()
                               + "path with spaces' && '\\bin\\echo' 'hello world'";
        }
        assertEquals( expectedShellCmd, shellCommandline[2] );
    }
//  [java]
    public void testGetShellCommandLineBash_WithWorkingDirectory()
        throws Exception
    {
        Commandline cmd = new Commandline( new BourneShell() );
        cmd.setExecutable( "/bin/echo" );
        cmd.addArguments( new String[] {
            "hello world"
        } );
        File root = File.listRoots()[0];
        File workingDirectory = new File( root, "path with spaces" );
        cmd.setWorkingDirectory( workingDirectory );

        String[] shellCommandline = cmd.getShellCommandline();

        assertEquals( "Command line size", 3, shellCommandline.length );

        assertEquals( "/bin/sh", shellCommandline[0] );
        assertEquals( "-c", shellCommandline[1] );
        String expectedShellCmd = "cd \"" + root.getAbsolutePath()
                                  + "path with spaces\" && /bin/echo \'hello world\'";
        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            expectedShellCmd = "cd \"" + root.getAbsolutePath()
                               + "path with spaces\" && \\bin\\echo \'hello world\'";
        }
        assertEquals( expectedShellCmd, shellCommandline[2] );
    }
//  [java]
    public void testGetShellCommandLineBash()
        throws Exception
    {
        Commandline cmd = new Commandline( new BourneShell() );
        cmd.setExecutable( "/bin/echo" );
        cmd.addArguments( new String[] {
            "hello world"
        } );

        String[] shellCommandline = cmd.getShellCommandline();

        assertEquals( "Command line size", 3, shellCommandline.length );

        assertEquals( "/bin/sh", shellCommandline[0] );
        assertEquals( "-c", shellCommandline[1] );
        String expectedShellCmd = "'/bin/echo' 'hello world'";
        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            expectedShellCmd = "\\bin\\echo \'hello world\'";
        }
        assertEquals( expectedShellCmd, shellCommandline[2] );
    }
//  [java]
    public void testGetShellCommandLineBash()
        throws Exception
    {
        Commandline cmd = new Commandline( new BourneShell() );
        cmd.setExecutable( "/bin/echo" );
        cmd.addArguments( new String[] {
            "hello world"
        } );

        String[] shellCommandline = cmd.getShellCommandline();

        assertEquals( "Command line size", 3, shellCommandline.length );

        assertEquals( "/bin/sh", shellCommandline[0] );
        assertEquals( "-c", shellCommandline[1] );
        String expectedShellCmd = "/bin/echo \'hello world\'";
        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            expectedShellCmd = "\\bin\\echo \'hello world\'";
        }
        assertEquals( expectedShellCmd, shellCommandline[2] );
    }
//  [java]
    public void testSetRequestMethod() {
        HttpsURLConnection conn = createHttpsUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
        Utils.setRequestMethod(conn, Utils.RequestMethod.POST);
        Assert.assertEquals(conn.getRequestMethod(), "POST");
    }
//  [java]
    public void testSetRequestMethod() {
        HttpURLConnection conn = createHttpUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
        Utils.setRequestMethod(conn, Utils.RequestMethod.POST);
        Assert.assertEquals(conn.getRequestMethod(), "POST");
    }
//  [java]
    public void testCreateHttpUrlConnection() {
        HttpsURLConnection conn;
        // Test without proxy
        conn = createHttpsUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
        Assert.assertNotNull(conn);
        // Test with the proxy
        conn = createHttpsUrlConnection(convertToUrl(TEST_URL), "http://localhost", 9090, "testUser", "testPassword");
        Assert.assertNotNull(conn);
    }
//  [java]
    public void testCreateHttpUrlConnection() {
        HttpURLConnection conn;
        // Test without proxy
        conn = createHttpUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
        Assert.assertNotNull(conn);
        // Test with the proxy
        conn = createHttpUrlConnection(convertToUrl(TEST_URL), "http://localhost", 9090, "testUser", "testPassword");
        Assert.assertNotNull(conn);
    }
//  [java]
    public void testGetShellCommandLineNonWindows()
        throws Exception
    {
        Commandline cmd = new Commandline( new BourneShell() );
        cmd.setExecutable( "/usr/bin" );
        cmd.addArguments( new String[] {
            "a",
            "b"
        } );
        String[] shellCommandline = cmd.getShellCommandline();

        assertEquals( "Command line size", 3, shellCommandline.length );

        assertEquals( "/bin/sh", shellCommandline[0] );
        assertEquals( "-c", shellCommandline[1] );

        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            assertEquals( "\\usr\\bin a b", shellCommandline[2] );
        }
        else
        {
            assertEquals( "'/usr/bin' 'a' 'b'", shellCommandline[2] );
        }
    }
//  [java]
    public void testGetShellCommandLineNonWindows()
        throws Exception
    {
        Commandline cmd = new Commandline( new BourneShell() );
        cmd.setExecutable( "/usr/bin" );
        cmd.addArguments( new String[] {
            "a",
            "b"
        } );
        String[] shellCommandline = cmd.getShellCommandline();

        assertEquals( "Command line size", 3, shellCommandline.length );

        assertEquals( "/bin/sh", shellCommandline[0] );
        assertEquals( "-c", shellCommandline[1] );

        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            assertEquals( "\\usr\\bin a b", shellCommandline[2] );
        }
        else
        {
            assertEquals( "/usr/bin a b", shellCommandline[2] );
        }
    }
//  [java]
    public void translate(GeyserSession session, AnimatePacket packet) {
        // Stop the player sending animations before they have fully spawned into the server
        if (!session.isSpawned()) {
            return;
        }

        switch (packet.getAction()) {
            case SWING_ARM:
                // Delay so entity damage can be processed first
                session.scheduleInEventLoop(() ->
                        session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)),
                        25,
                        TimeUnit.MILLISECONDS
                );
                break;
            // These two might need to be flipped, but my recommendation is getting moving working first
            case ROW_LEFT:
                // Packet value is a float of how long one has been rowing, so we convert that into a boolean
                session.setSteeringLeft(packet.getRowingTime() > 0.0);
                ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
                session.sendDownstreamPacket(steerLeftPacket);
                break;
            case ROW_RIGHT:
                session.setSteeringRight(packet.getRowingTime() > 0.0);
                ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
                session.sendDownstreamPacket(steerRightPacket);
                break;
        }
    }
//  [java]
    public void translate(AnimatePacket packet, GeyserSession session) {
        // Stop the player sending animations before they have fully spawned into the server
        if (!session.isSpawned()) {
            return;
        }

        switch (packet.getAction()) {
            case SWING_ARM:
                // Delay so entity damage can be processed first
                session.scheduleInEventLoop(() ->
                        session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)),
                        25,
                        TimeUnit.MILLISECONDS
                );
                break;
            // These two might need to be flipped, but my recommendation is getting moving working first
            case ROW_LEFT:
                // Packet value is a float of how long one has been rowing, so we convert that into a boolean
                session.setSteeringLeft(packet.getRowingTime() > 0.0);
                ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
                session.sendDownstreamPacket(steerLeftPacket);
                break;
            case ROW_RIGHT:
                session.setSteeringRight(packet.getRowingTime() > 0.0);
                ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
                session.sendDownstreamPacket(steerRightPacket);
                break;
        }
    }
//  [java]
    public void sendError(int sc, String msg) throws IOException {
        if (isIncluding()) {
            Logger.log(Logger.ERROR, Launcher.RESOURCES, "IncludeResponse.Error",
                    new String[] { "" + sc, msg });
            return;
        }
        
        Logger.log(Logger.DEBUG, Launcher.RESOURCES,
                "WinstoneResponse.SendingError", new String[] { "" + sc, msg });

        if ((this.webAppConfig != null) && (this.req != null)) {
            
            RequestDispatcher rd = this.webAppConfig
                    .getErrorDispatcherByCode(req.getRequestURI(), sc, msg, null);
            if (rd != null) {
                try {
                    rd.forward(this.req, this);
                    return;
                } catch (IllegalStateException err) {
                    throw err;
                } catch (IOException err) {
                    throw err;
                } catch (Throwable err) {
                    Logger.log(Logger.WARNING, Launcher.RESOURCES,
                            "WinstoneResponse.ErrorInErrorPage", new String[] {
                                    rd.getName(), sc + "" }, err);
                    return;
                }
            }
        }
        // If we are here there was no webapp and/or no request object, so 
        // show the default error page
        if (this.errorStatusCode == null) {
            this.statusCode = sc;
        }
        String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage",
                new String[] { sc + "", URIUtil.htmlEscape(msg == null ? "" : msg), "",
                        Launcher.RESOURCES.getString("ServerVersion"),
                        "" + new Date() });
        setContentLength(output.getBytes(getCharacterEncoding()).length);
        Writer out = getWriter();
        out.write(output);
        out.flush();
    }
//  [java]
    public void sendError(int sc, String msg) throws IOException {
        if (isIncluding()) {
            Logger.log(Logger.ERROR, Launcher.RESOURCES, "IncludeResponse.Error",
                    new String[] { "" + sc, msg });
            return;
        }
        
        Logger.log(Logger.DEBUG, Launcher.RESOURCES,
                "WinstoneResponse.SendingError", new String[] { "" + sc, msg });

        if ((this.webAppConfig != null) && (this.req != null)) {
            
            RequestDispatcher rd = this.webAppConfig
                    .getErrorDispatcherByCode(req.getRequestURI(), sc, msg, null);
            if (rd != null) {
                try {
                    rd.forward(this.req, this);
                    return;
                } catch (IllegalStateException err) {
                    throw err;
                } catch (IOException err) {
                    throw err;
                } catch (Throwable err) {
                    Logger.log(Logger.WARNING, Launcher.RESOURCES,
                            "WinstoneResponse.ErrorInErrorPage", new String[] {
                                    rd.getName(), sc + "" }, err);
                    return;
                }
            }
        }
        // If we are here there was no webapp and/or no request object, so 
        // show the default error page
        if (this.errorStatusCode == null) {
            this.statusCode = sc;
        }
        String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage",
                new String[] { sc + "", (msg == null ? "" : msg), "",
                        Launcher.RESOURCES.getString("ServerVersion"),
                        "" + new Date() });
        setContentLength(output.getBytes(getCharacterEncoding()).length);
        Writer out = getWriter();
        out.write(output);
        out.flush();
    }
//  [java]
    public static String getAttachedFilePath(String studyOid) throws Exception {    	
        String attachedFilePath = CoreResources.getField("attached_file_location");
        if (attachedFilePath == null || attachedFilePath.length() <= 0) {
            attachedFilePath = CoreResources.getField("filePath") + "attached_files" + File.separator;
        }
        File tempFile =  new File(attachedFilePath,studyOid);
        String canonicalPath= tempFile.getCanonicalPath();
        
        if (canonicalPath.startsWith(attachedFilePath)) {
        	if (attachedFilePath == null || attachedFilePath.length() <= 0) {
                attachedFilePath = CoreResources.getField("filePath") + "attached_files" + File.separator + studyOid + File.separator;
            } else {
                attachedFilePath += studyOid + File.separator;
            }
            return attachedFilePath;
        }else {
        	throw new RuntimeException("Traversal attempt - file path not allowed " + studyOid);
        }
        
    }
//  [java]
    public static String getAttachedFilePath(String inputStudyOid) {
    	// Using a standard library to validate/Sanitize user inputs which will be used in path expression to prevent from path traversal
    	String studyOid =  FilenameUtils.getName(inputStudyOid);
        String attachedFilePath = CoreResources.getField("attached_file_location");
        if (attachedFilePath == null || attachedFilePath.length() <= 0) {
            attachedFilePath = CoreResources.getField("filePath") + "attached_files" + File.separator + studyOid + File.separator;
        } else {
            attachedFilePath += studyOid + File.separator;
        }
        return attachedFilePath;
    }
//  [java]
    public void translate(GeyserSession session, ServerDifficultyPacket packet) {
        SetDifficultyPacket setDifficultyPacket = new SetDifficultyPacket();
        setDifficultyPacket.setDifficulty(packet.getDifficulty().ordinal());
        session.sendUpstreamPacket(setDifficultyPacket);

        session.getWorldCache().setDifficulty(packet.getDifficulty());
    }
//  [java]
    public void translate(ServerDifficultyPacket packet, GeyserSession session) {
        SetDifficultyPacket setDifficultyPacket = new SetDifficultyPacket();
        setDifficultyPacket.setDifficulty(packet.getDifficulty().ordinal());
        session.sendUpstreamPacket(setDifficultyPacket);

        session.getWorldCache().setDifficulty(packet.getDifficulty());
    }
//  [java]
    public void translate(GeyserSession session, ServerUpdateViewDistancePacket packet) {
        session.setRenderDistance(packet.getViewDistance());
    }
//  [java]
    public void translate(ServerUpdateViewDistancePacket packet, GeyserSession session) {
        session.setRenderDistance(packet.getViewDistance());
    }
//  [java]
	public CommandExecutionResult createBinary(String code, String full, boolean compact, Stereotype stereotype) {
		final Player player = new PlayerBinary(full, getSkinParam(), ruler, compactByDefault, stereotype);
		players.put(code, player);
		return CommandExecutionResult.ok();
	}
//  [java]
	public CommandExecutionResult createBinary(String code, String full, boolean compact) {
		final Player player = new PlayerBinary(full, getSkinParam(), ruler, compactByDefault);
		players.put(code, player);
		return CommandExecutionResult.ok();
	}
//  [java]
	public FromSkinparamToStyle(String key) {

		if (key.contains("<<")) {
			final StringTokenizer st = new StringTokenizer(key, "<>");
			this.key = st.nextToken();
			this.stereo = st.hasMoreTokens() ? st.nextToken().trim() : null;
		} else {
			this.key = key;
			this.stereo = null;
		}

	}