jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    public static void fillArticleInfo(Log data, HttpServletRequest request, String suffix) {
        data.put("alias", data.get("alias") + suffix);
        data.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + data.get("alias"));
        data.put("noSchemeUrl", WebTools.getHomeUrlWithHost(request) + Constants.getArticleUri() + data.get("alias"));
        data.put("typeUrl", WebTools.getHomeUrl(request) + Constants.getArticleUri() + "sort/" + data.get("typeAlias") + suffix);
        Log lastLog = data.get("lastLog");
        Log nextLog = data.get("nextLog");
        nextLog.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + nextLog.get("alias") + suffix);
        lastLog.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + lastLog.get("alias") + suffix);
        //没有使用md的toc目录的文章才尝试使用系统提取的目录
        if (data.getStr("markdown") != null && !data.getStr("markdown").toLowerCase().contains("[toc]")
                && !data.getStr("markdown").toLowerCase().contains("[tocm]")) {
            //最基础的实现方式，若需要更强大的实现方式建议使用JavaScript完成（页面输入toc对象）
            OutlineVO outlineVO = OutlineUtil.extractOutline(data.getStr("content"));
            data.put("tocHtml", OutlineUtil.buildTocHtml(outlineVO, ""));
            data.put("toc", outlineVO);
        }
        if (!new CommentService().isAllowComment()) {
            data.set("canComment", false);
        }
    }
//  [java]
    private void onopen() {
        logger.fine("open");

        this.cleanup();

        this.readyState = ReadyState.OPEN;
        this.emit(EVENT_OPEN);

        final io.socket.engineio.client.Socket socket = this.engine;
        this.subs.add(On.on(socket, Engine.EVENT_DATA, new Listener() {
            @Override
            public void call(Object... objects) {
                Object data = objects[0];
                try {
                    if (data instanceof String) {
                        Manager.this.decoder.add((String) data);
                    } else if (data instanceof byte[]) {
                        Manager.this.decoder.add((byte[]) data);
                    }
                } catch (DecodingException e) {
                    logger.fine("error while decoding the packet: " + e.getMessage());
                }
            }
        }));
        this.subs.add(On.on(socket, Engine.EVENT_ERROR, new Listener() {
            @Override
            public void call(Object... objects) {
                Manager.this.onerror((Exception)objects[0]);
            }
        }));
        this.subs.add(On.on(socket, Engine.EVENT_CLOSE, new Listener() {
            @Override
            public void call(Object... objects) {
                Manager.this.onclose((String)objects[0]);
            }
        }));
        this.decoder.onDecoded(new Parser.Decoder.Callback() {
            @Override
            public void call (Packet packet) {
                Manager.this.ondecoded(packet);
            }
        });
    }
//  [java]
    private void onopen() {
        logger.fine("open");

        this.cleanup();

        this.readyState = ReadyState.OPEN;
        this.emit(EVENT_OPEN);

        final io.socket.engineio.client.Socket socket = this.engine;
        this.subs.add(On.on(socket, Engine.EVENT_DATA, new Listener() {
            @Override
            public void call(Object... objects) {
                Object data = objects[0];
                if (data instanceof String) {
                    Manager.this.ondata((String)data);
                } else if (data instanceof byte[]) {
                    Manager.this.ondata((byte[])data);
                }
            }
        }));
        this.subs.add(On.on(socket, Engine.EVENT_ERROR, new Listener() {
            @Override
            public void call(Object... objects) {
                Manager.this.onerror((Exception)objects[0]);
            }
        }));
        this.subs.add(On.on(socket, Engine.EVENT_CLOSE, new Listener() {
            @Override
            public void call(Object... objects) {
                Manager.this.onclose((String)objects[0]);
            }
        }));
        this.decoder.onDecoded(new Parser.Decoder.Callback() {
            @Override
            public void call (Packet packet) {
                Manager.this.ondecoded(packet);
            }
        });
    }
//  [java]
    public static synchronized InitialContext getInitialContext() throws NamingException {
        Logging.getLogger(GeoTools.class)
                .severe(
                        "Please don't use GeoTools.getInitialContext(), perform lookups using GeoTools.jndiLookup(s) instead.");
        return getJNDIContext();
    }
//  [java]
    public static synchronized InitialContext getInitialContext(final Hints hints)
            throws NamingException {

        return getInitialContext();
    }
//  [java]
    public void translate(GeyserSession session, ServerSpawnExpOrbPacket packet) {
        Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());

        Entity entity = new ExpOrbEntity(
                packet.getExp(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(),
                EntityType.EXPERIENCE_ORB, position, Vector3f.ZERO, Vector3f.ZERO
        );

        session.getEntityCache().spawnEntity(entity);
    }
//  [java]
    public void translate(ServerSpawnExpOrbPacket packet, GeyserSession session) {
        Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());

        Entity entity = new ExpOrbEntity(
                packet.getExp(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(),
                EntityType.EXPERIENCE_ORB, position, Vector3f.ZERO, Vector3f.ZERO
        );

        session.getEntityCache().spawnEntity(entity);
    }
//  [java]
    public void translate(GeyserSession session, ServerVehicleMovePacket packet) {
        Entity entity = session.getRidingVehicleEntity();
        if (entity == null) return;

        entity.moveAbsolute(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), false, true);
    }
//  [java]
    public void translate(ServerVehicleMovePacket packet, GeyserSession session) {
        Entity entity = session.getRidingVehicleEntity();
        if (entity == null) return;

        entity.moveAbsolute(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), false, true);
    }
//  [java]
    public byte[] toByteArray()
    {
		/* index || secretKeySeed || secretKeyPRF || publicSeed || root */
        int n = params.getDigestSize();
        int indexSize = (params.getHeight() + 7) / 8;
        int secretKeySize = n;
        int secretKeyPRFSize = n;
        int publicSeedSize = n;
        int rootSize = n;
        int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize;
        byte[] out = new byte[totalSize];
        int position = 0;
		/* copy index */
        byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize);
        XMSSUtil.copyBytesAtOffset(out, indexBytes, position);
        position += indexSize;
		/* copy secretKeySeed */
        XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position);
        position += secretKeySize;
		/* copy secretKeyPRF */
        XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position);
        position += secretKeyPRFSize;
		/* copy publicSeed */
        XMSSUtil.copyBytesAtOffset(out, publicSeed, position);
        position += publicSeedSize;
		/* copy root */
        XMSSUtil.copyBytesAtOffset(out, root, position);
		/* concatenate bdsState */
        try
        {
            return Arrays.concatenate(out, XMSSUtil.serialize(bdsState));
        }
        catch (IOException e)
        {
            throw new IllegalStateException("error serializing bds state: " + e.getMessage(), e);
        }
    }
//  [java]
    public byte[] toByteArray()
    {
		/* index || secretKeySeed || secretKeyPRF || publicSeed || root */
        int n = params.getDigestSize();
        int indexSize = (params.getHeight() + 7) / 8;
        int secretKeySize = n;
        int secretKeyPRFSize = n;
        int publicSeedSize = n;
        int rootSize = n;
        int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize;
        byte[] out = new byte[totalSize];
        int position = 0;
		/* copy index */
        byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize);
        XMSSUtil.copyBytesAtOffset(out, indexBytes, position);
        position += indexSize;
		/* copy secretKeySeed */
        XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position);
        position += secretKeySize;
		/* copy secretKeyPRF */
        XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position);
        position += secretKeyPRFSize;
		/* copy publicSeed */
        XMSSUtil.copyBytesAtOffset(out, publicSeed, position);
        position += publicSeedSize;
		/* copy root */
        XMSSUtil.copyBytesAtOffset(out, root, position);
		/* concatenate bdsState */
        byte[] bdsStateOut = null;
        try
        {
            bdsStateOut = XMSSUtil.serialize(bdsState);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            throw new RuntimeException("error serializing bds state");
        }
        return Arrays.concatenate(out, bdsStateOut);
    }
//  [java]
    private String getLocalePrefix(FacesContext context) {

        String localePrefix = null;
        
        localePrefix = context.getExternalContext().getRequestParameterMap().get("loc");
        
        if(localePrefix != null && !nameContainsForbiddenSequence(localePrefix)){
            return localePrefix;
        }
        
        String appBundleName = context.getApplication().getMessageBundle();
        if (null != appBundleName) {
        	
            Locale locale = null;
            if (context.getViewRoot() != null) {
                locale = context.getViewRoot().getLocale();
            } else {
                locale = context.getApplication().getViewHandler().calculateLocale(context);
            }
            
                try {
                    ResourceBundle appBundle =
                          ResourceBundle.getBundle(appBundleName,
                                                   locale,
                                                   Util.getCurrentLoader(ResourceManager.class));
                    localePrefix =
                          appBundle
                                .getString(ResourceHandler.LOCALE_PREFIX);
                } catch (MissingResourceException mre) { 
                    if (LOGGER.isLoggable(Level.FINEST)) {
                        LOGGER.log(Level.FINEST, "Ignoring missing resource", mre);
                    }
                }
        }
        return localePrefix;

    }
//  [java]
    private String getLocalePrefix(FacesContext context) {

        String localePrefix = null;
        
        localePrefix = context.getExternalContext().getRequestParameterMap().get("loc");
        
        if(localePrefix != null){
            return localePrefix;
        }
        
        String appBundleName = context.getApplication().getMessageBundle();
        if (null != appBundleName) {
        	
            Locale locale = null;
            if (context.getViewRoot() != null) {
                locale = context.getViewRoot().getLocale();
            } else {
                locale = context.getApplication().getViewHandler().calculateLocale(context);
            }
            
                try {
                    ResourceBundle appBundle =
                          ResourceBundle.getBundle(appBundleName,
                                                   locale,
                                                   Util.getCurrentLoader(ResourceManager.class));
                    localePrefix =
                          appBundle
                                .getString(ResourceHandler.LOCALE_PREFIX);
                } catch (MissingResourceException mre) { 
                    if (LOGGER.isLoggable(Level.FINEST)) {
                        LOGGER.log(Level.FINEST, "Ignoring missing resource", mre);
                    }
                }
        }
        return localePrefix;

    }
//  [java]
    public void translate(GeyserSession session, ServerPlaySoundPacket packet) {
        String packetSound;
        if (packet.getSound() instanceof BuiltinSound) {
            packetSound = ((BuiltinSound) packet.getSound()).getName();
        } else if (packet.getSound() instanceof CustomSound) {
            packetSound = ((CustomSound) packet.getSound()).getName();
        } else {
            session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString());
            return;
        }

        SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", ""));
        String playsound;
        if (soundMapping == null || soundMapping.getPlaysound() == null) {
            // no mapping
            session.getConnector().getLogger()
                    .debug("[PlaySound] Defaulting to sound server gave us for " + packet.toString());
            playsound = packetSound.replace("minecraft:", "");
        } else {
            playsound = soundMapping.getPlaysound();
        }

        PlaySoundPacket playSoundPacket = new PlaySoundPacket();
        playSoundPacket.setSound(playsound);
        playSoundPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ()));
        playSoundPacket.setVolume(packet.getVolume());
        playSoundPacket.setPitch(packet.getPitch());

        session.sendUpstreamPacket(playSoundPacket);
    }
//  [java]
    public void translate(ServerPlaySoundPacket packet, GeyserSession session) {
        String packetSound;
        if (packet.getSound() instanceof BuiltinSound) {
            packetSound = ((BuiltinSound) packet.getSound()).getName();
        } else if (packet.getSound() instanceof CustomSound) {
            packetSound = ((CustomSound) packet.getSound()).getName();
        } else {
            session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString());
            return;
        }

        SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", ""));
        String playsound;
        if (soundMapping == null || soundMapping.getPlaysound() == null) {
            // no mapping
            session.getConnector().getLogger()
                    .debug("[PlaySound] Defaulting to sound server gave us for " + packet.toString());
            playsound = packetSound.replace("minecraft:", "");
        } else {
            playsound = soundMapping.getPlaysound();
        }

        PlaySoundPacket playSoundPacket = new PlaySoundPacket();
        playSoundPacket.setSound(playsound);
        playSoundPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ()));
        playSoundPacket.setVolume(packet.getVolume());
        playSoundPacket.setPitch(packet.getPitch());

        session.sendUpstreamPacket(playSoundPacket);
    }
//  [java]
    private <P extends T> void translate0(GeyserSession session, PacketTranslator<P> translator, P packet) {
        if (session.isClosed()) {
            return;
        }

        try {
            translator.translate(session, packet);
        } catch (Throwable ex) {
            GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.network.translator.packet.failed", packet.getClass().getSimpleName()), ex);
            ex.printStackTrace();
        }
    }
//  [java]
    private <P extends T> void translate0(GeyserSession session, PacketTranslator<P> translator, P packet) {
        if (session.isClosed()) {
            return;
        }

        try {
            translator.translate(packet, session);
        } catch (Throwable ex) {
            GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.network.translator.packet.failed", packet.getClass().getSimpleName()), ex);
            ex.printStackTrace();
        }
    }
//  [java]
    public RainbowParameters(int[] vi)
    {
        this.vi = vi;

        checkParams();
    }
//  [java]
    public RainbowParameters(int[] vi)
    {
        this.vi = vi;
        try
        {
            checkParams();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerCloseWindowPacket packet) {
        // Sometimes the server can request a window close of ID 0... when the window isn't even open
        // Don't confirm in this instance
        InventoryUtils.closeInventory(session, packet.getWindowId(), (session.getOpenInventory() != null && session.getOpenInventory().getId() == packet.getWindowId()));
    }
//  [java]
    public void translate(ServerCloseWindowPacket packet, GeyserSession session) {
        // Sometimes the server can request a window close of ID 0... when the window isn't even open
        // Don't confirm in this instance
        InventoryUtils.closeInventory(session, packet.getWindowId(), (session.getOpenInventory() != null && session.getOpenInventory().getId() == packet.getWindowId()));
    }
//  [java]
		public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
	    throws IOException {
			String filename = file.getFileName().toString();
			Path normalizedPath = file.normalize();
			if(!normalizedPath.startsWith(destDir)) {
				throw new IOException("Invalid ZIP");
			}
			
	        if(filename.endsWith(WikiManager.WIKI_PROPERTIES_SUFFIX)) {
	        	String f = convertAlternativeFilename(file.toString());
	        	final Path destFile = Paths.get(wikiDir.toString(), f);
	        	resetAndCopyProperties(file, destFile);
	        } else if (filename.endsWith(WIKI_FILE_SUFFIX)) {
	        	String f = convertAlternativeFilename(file.toString());
	        	final Path destFile = Paths.get(wikiDir.toString(), f);
	        	Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
			} else if (!filename.contains(WIKI_FILE_SUFFIX + "-")
					&& !filename.contains(WIKI_PROPERTIES_SUFFIX + "-")) {
				final Path destFile = Paths.get(mediaDir.toString(), file.toString());
				Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
			}
	        return FileVisitResult.CONTINUE;
		}
//  [java]
		public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
	    throws IOException {
	        String filename = file.getFileName().toString();
	        if(filename.endsWith(WikiManager.WIKI_PROPERTIES_SUFFIX)) {
	        		String f = convertAlternativeFilename(file.toString());
	        		final Path destFile = Paths.get(wikiDir.toString(), f);
	        		resetAndCopyProperties(file, destFile);
	        } else if (filename.endsWith(WIKI_FILE_SUFFIX)) {
        			String f = convertAlternativeFilename(file.toString());
	        		final Path destFile = Paths.get(wikiDir.toString(), f);
				Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
			} else if (!filename.contains(WIKI_FILE_SUFFIX + "-")
					&& !filename.contains(WIKI_PROPERTIES_SUFFIX + "-")) {
				final Path destFile = Paths.get(mediaDir.toString(), file.toString());
				Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
			}
	        return FileVisitResult.CONTINUE;
		}
//  [java]
    public void translate(GeyserSession session, ServerUpdateViewPositionPacket packet) {
        if (!session.isSpawned() && session.getLastChunkPosition() == null) {
            ChunkUtils.updateChunkPosition(session, Vector3i.from(packet.getChunkX() << 4, 64, packet.getChunkZ() << 4));
        }
    }
//  [java]
    public void translate(ServerUpdateViewPositionPacket packet, GeyserSession session) {
        if (!session.isSpawned() && session.getLastChunkPosition() == null) {
            ChunkUtils.updateChunkPosition(session, Vector3i.from(packet.getChunkX() << 4, 64, packet.getChunkZ() << 4));
        }
    }
//  [java]
    private void checkParams()
    {
        if (vi == null)
        {
            throw new IllegalArgumentException("no layers defined.");
        }
        if (vi.length > 1)
        {
            for (int i = 0; i < vi.length - 1; i++)
            {
                if (vi[i] >= vi[i + 1])
                {
                    throw new IllegalArgumentException(
                        "v[i] has to be smaller than v[i+1]");
                }
            }
        }
        else
        {
            throw new IllegalArgumentException(
                "Rainbow needs at least 1 layer, such that v1 < v2.");
        }
    }
//  [java]
    private void checkParams()
        throws Exception
    {
        if (vi == null)
        {
            throw new Exception("no layers defined.");
        }
        if (vi.length > 1)
        {
            for (int i = 0; i < vi.length - 1; i++)
            {
                if (vi[i] >= vi[i + 1])
                {
                    throw new Exception(
                        "v[i] has to be smaller than v[i+1]");
                }
            }
        }
        else
        {
            throw new Exception(
                "Rainbow needs at least 1 layer, such that v1 < v2.");
        }
    }
//  [java]
    public static void init(final InitialContext initialContext) {
        synchronized (GeoTools.class) {
            context = initialContext;
        }
        fireConfigurationChanged();
    }
//  [java]
    public static void init(final InitialContext applicationContext) {
        synchronized (GeoTools.class) {
            context = applicationContext;
        }
        fireConfigurationChanged();
    }
//  [java]
    public static void main(String[] args) {

        // Will serve all static file are under "/public" in classpath if the route isn't consumed by others routes.
        staticFiles.location("/public");

        get("/hello", (request, response) -> {
            return "Hello World!";
        });
    }
//  [java]
    public static void main(String[] args) {

        // Will serve all static file are under "/public" in classpath if the route isn't consumed by others routes.
        staticFileLocation("/public");

        get("/hello", (request, response) -> {
            return "Hello World!";
        });
    }
//  [java]
	public void reportJobCaches(String cacheInstancesString) {
		Collection<CacheInstance> cacheInstances = new ArrayList<>();
		for (String field: Splitter.on(';').omitEmptyStrings().split(cacheInstancesString))
			cacheInstances.add(CacheInstance.fromString(field));
		jobManager.reportJobCaches(getJobToken(), cacheInstances);
	}
//  [java]
	public void reportJobCaches(byte[] cacheInstanceBytes) {
		@SuppressWarnings("unchecked")
		Collection<CacheInstance> cacheInstances = (Collection<CacheInstance>) SerializationUtils
				.deserialize(cacheInstanceBytes);
		jobManager.reportJobCaches(getJobToken(), cacheInstances);
	}
//  [java]
  public synchronized MultiMap headers() {
    if (headers == null) {
      headers = new VertxHttpHeaders();
    }
    return headers;
  }
//  [java]
  public synchronized MultiMap headers() {
    if (headers == null) {
      headers = new CaseInsensitiveHeaders();
    }
    return headers;
  }
//  [java]
    public void translate(GeyserSession session, ServerUnloadChunkPacket packet) {
        session.getChunkCache().removeChunk(packet.getX(), packet.getZ());

        //Checks if a skull is in an unloaded chunk then removes it
        Iterator<Vector3i> iterator = session.getSkullCache().keySet().iterator();
        while (iterator.hasNext()) {
            Vector3i position = iterator.next();
            if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) {
                session.getSkullCache().get(position).despawnEntity(session);
                iterator.remove();
            }
        }

        // Do the same thing with lecterns
        iterator = session.getLecternCache().iterator();
        while (iterator.hasNext()) {
            Vector3i position = iterator.next();
            if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) {
                iterator.remove();
            }
        }
    }
//  [java]
    public void translate(ServerUnloadChunkPacket packet, GeyserSession session) {
        session.getChunkCache().removeChunk(packet.getX(), packet.getZ());

        //Checks if a skull is in an unloaded chunk then removes it
        Iterator<Vector3i> iterator = session.getSkullCache().keySet().iterator();
        while (iterator.hasNext()) {
            Vector3i position = iterator.next();
            if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) {
                session.getSkullCache().get(position).despawnEntity(session);
                iterator.remove();
            }
        }

        // Do the same thing with lecterns
        iterator = session.getLecternCache().iterator();
        while (iterator.hasNext()) {
            Vector3i position = iterator.next();
            if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) {
                iterator.remove();
            }
        }
    }
//  [java]
    public void deleteById(Integer id) {
        databaseTypeDao.selectOptionalById(id).ifPresent(data -> {
            if (DatabaseTypes.has(data.getDatabaseType())) {
                throw DomainErrors.MUST_NOT_MODIFY_SYSTEM_DEFAULT_DATABASE_TYPE.exception();
            }
            databaseTypeDao.deleteById(id);
            driverResources.deleteByDatabaseType(data.getDatabaseType());
        });
    }
//  [java]
    public void deleteById(Integer id) {
        databaseTypeDao.selectOptionalById(id).ifPresent(data -> {
            if (DatabaseTypes.has(data.getDatabaseType())) {
                throw DomainErrors.MUST_NOT_MODIFY_SYSTEM_DEFAULT_DATABASE_TYPE.exception();
            }
            databaseTypeDao.deleteById(id);
            driverResources.delete(data.getDatabaseType());
        });
    }
//  [java]
    public byte[] allocateJobCaches(String cacheAllocationRequestString) {
		CacheAllocationRequest cacheAllocationRequest = CacheAllocationRequest.fromString(cacheAllocationRequestString);
		return SerializationUtils.serialize((Serializable) jobManager.allocateJobCaches(
				getJobToken(), cacheAllocationRequest.getCurrentTime(), cacheAllocationRequest.getInstances()));
    }
//  [java]
    public byte[] allocateJobCaches(byte[] cacheAllocationRequestBytes) {
		CacheAllocationRequest allocationRequest = (CacheAllocationRequest) SerializationUtils
				.deserialize(cacheAllocationRequestBytes);
		return SerializationUtils.serialize((Serializable) jobManager.allocateJobCaches(
				getJobToken(), allocationRequest.getCurrentTime(), allocationRequest.getInstances()));
    }
//  [java]
    public void validateConcreteScmMaterial(ValidationContext validationContext) {
        if (getView() == null || getView().trim().isEmpty()) {
            errors.add(VIEW, "P4 view cannot be empty.");
        }
        if (StringUtils.isBlank(getServerAndPort())) {
            errors.add(SERVER_AND_PORT, "P4 port cannot be empty.");
        }

        if (!new UrlArgument(getUrl()).isValidURLOrLocalPath()) {
            errors.add(SERVER_AND_PORT, "P4 port seems to be invalid.");
        }

        view.validate(validationContext);
    }
//  [java]
    public void validateConcreteScmMaterial(ValidationContext validationContext) {
        if (getView() == null || getView().trim().isEmpty()) {
            errors.add(VIEW, "P4 view cannot be empty.");
        }
        if (StringUtils.isBlank(getServerAndPort())) {
            errors.add(SERVER_AND_PORT, "P4 port cannot be empty.");
        }
        validateEncryptedPassword();
    }
//  [java]
	public void svgImage(UImageSvg image, double x, double y) {
		// https://developer.mozilla.org/fr/docs/Web/SVG/Element/image
		if (hidden == false) {
			final Element elt = (Element) document.createElement("image");
			elt.setAttribute("width", format(image.getWidth()));
			elt.setAttribute("height", format(image.getHeight()));
			elt.setAttribute("x", format(x));
			elt.setAttribute("y", format(y));

			String svg = manageScale(image);

			final String svgHeader;
			if (image.containsXlink())
				svgHeader = "<svg height=\"" + (int) (image.getHeight() * scale) + "\" width=\""
						+ (int) (image.getWidth() * scale)
						+ "\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://www.w3.org/2000/svg\" >";
			else
				svgHeader = "<svg height=\"" + (int) (image.getHeight() * scale) + "\" width=\""
						+ (int) (image.getWidth() * scale) + "\" xmlns=\"http://www.w3.org/2000/svg\" >";

			svg = svgHeader + svg.substring(5);

			final String s = toBase64(svg);
			elt.setAttribute("xlink:href", "data:image/svg+xml;base64," + s);

			getG().appendChild(elt);
		}
		ensureVisible(x, y);
		ensureVisible(x + image.getData("width"), y + image.getData("height"));
	}
//  [java]
	public void svgImage(UImageSvg image, double x, double y) {
		// https://developer.mozilla.org/fr/docs/Web/SVG/Element/image
		if (hidden == false) {
			final Element elt = (Element) document.createElement("image");
			elt.setAttribute("width", format(image.getWidth()));
			elt.setAttribute("height", format(image.getHeight()));
			elt.setAttribute("x", format(x));
			elt.setAttribute("y", format(y));

			String svg = manageScale(image);

			final String svgHeader = "<svg height=\"" + (int) (image.getHeight() * scale) + "\" width=\""
					+ (int) (image.getWidth() * scale) + "\" xmlns=\"http://www.w3.org/2000/svg\" >";

			svg = svgHeader + svg.substring(5);

			final String s = toBase64(svg);
			elt.setAttribute("xlink:href", "data:image/svg+xml;base64," + s);

			getG().appendChild(elt);
		}
		ensureVisible(x, y);
		ensureVisible(x + image.getData("width"), y + image.getData("height"));
	}
//  [java]
  public RechnungCostEditTablePanel(final String id)
  {
    super(id);
    feedbackPanel = new FeedbackPanel("feedback");
    ajaxComponents.register(feedbackPanel);
    add(feedbackPanel);
    this.form = new Form<AbstractRechnungsPositionDO>("form") {
      @Override
      protected void onSubmit()
      {
        super.onSubmit();
        csrfTokenHandler.onSubmit();
      }
    };
    add(form);
    csrfTokenHandler = new CsrfTokenHandler(form);
    rows = new RepeatingView("rows");
    form.add(rows);
  }
//  [java]
  public RechnungCostEditTablePanel(final String id)
  {
    super(id);
    feedbackPanel = new FeedbackPanel("feedback");
    ajaxComponents.register(feedbackPanel);
    add(feedbackPanel);
    this.form = new Form<AbstractRechnungsPositionDO>("form");
    add(form);
    rows = new RepeatingView("rows");
    form.add(rows);
  }
//  [java]
    public String resolveDriverClassName(DriverClassNameResolveRequest request) {
        return driverResources.resolveDriverClassName(request.getJdbcDriverFileUrl());
    }
//  [java]
    public String resolveDriverClassName(DriverClassNameResolveRequest request) {
        return driverResources.resolveSqlDriverNameFromJar(request.getJdbcDriverFileUrl());
    }
//  [java]
    public void update(DatabaseTypeUpdateRequest request) {
        databaseTypeDao.selectOptionalById(request.getId()).ifPresent(data -> {
            if (DatabaseTypes.has(data.getDatabaseType())) {
                throw DomainErrors.MUST_NOT_MODIFY_SYSTEM_DEFAULT_DATABASE_TYPE.exception();
            }
            driverResources.validateJar(request.getJdbcDriverFileUrl(), request.getJdbcDriverClassName());
            DatabaseTypePojo pojo = databaseTypePojoConverter.of(request);
            try {
                databaseTypeDao.updateById(pojo);
            } catch (DuplicateKeyException e) {
                throw DomainErrors.DATABASE_TYPE_NAME_DUPLICATE.exception();
            }

            // 名称修改，下载地址修改需要删除原有的 driver
            if (!Objects.equals(request.getDatabaseType(), data.getDatabaseType())
                    || !Objects.equals(request.getJdbcDriverFileUrl(), data.getJdbcDriverFileUrl())) {
                driverResources.deleteByDatabaseType(data.getDatabaseType());
            }
        });

    }
//  [java]
    public void update(DatabaseTypeUpdateRequest request) {
        databaseTypeDao.selectOptionalById(request.getId()).ifPresent(data -> {
            if (DatabaseTypes.has(data.getDatabaseType())) {
                throw DomainErrors.MUST_NOT_MODIFY_SYSTEM_DEFAULT_DATABASE_TYPE.exception();
            }

            DatabaseTypePojo pojo = databaseTypePojoConverter.of(request);
            try {
                databaseTypeDao.updateById(pojo);
            } catch (DuplicateKeyException e) {
                throw DomainErrors.DATABASE_TYPE_NAME_DUPLICATE.exception();
            }

            // 名称修改，下载地址修改需要删除原有的 driver
            if (!Objects.equals(request.getDatabaseType(), data.getDatabaseType())
                    || !Objects.equals(request.getJdbcDriverFileUrl(), data.getJdbcDriverFileUrl())) {
                driverResources.delete(data.getDatabaseType());
            }
        });

    }
//  [java]
    void validSaveNewTranslation() throws Exception
    {
        when(mockForm.getLanguage()).thenReturn("fr");
        when(mockClonedDocument.getTranslatedDocument("fr", this.context)).thenReturn(mockClonedDocument);
        when(mockClonedDocument.getDocumentReference()).thenReturn(new DocumentReference("xwiki", "My", "Page"));
        when(mockClonedDocument.getStore()).thenReturn(this.oldcore.getMockStore());
        when(xWiki.getStore()).thenReturn(this.oldcore.getMockStore());
        context.put("ajax", true);
        when(xWiki.isMultiLingual(this.context)).thenReturn(true);
        when(mockRequest.getParameter("previousVersion")).thenReturn("1.1");
        when(mockRequest.getParameter("isNew")).thenReturn("true");
        assertFalse(saveAction.save(this.context));
        assertEquals(new Version("1.1"), this.context.get("SaveAction.savedObjectVersion"));
        verify(this.xWiki).checkSavingDocument(eq(USER_REFERENCE), any(XWikiDocument.class), eq(""), eq(false),
            eq(this.context));
        verify(this.xWiki).saveDocument(any(XWikiDocument.class), eq(""), eq(false), eq(this.context));
    }
//  [java]
    void validSaveNewTranslation() throws Exception
    {
        when(mockForm.getLanguage()).thenReturn("fr");
        when(mockClonedDocument.getTranslatedDocument("fr", this.context)).thenReturn(mockClonedDocument);
        when(mockClonedDocument.getDocumentReference()).thenReturn(new DocumentReference("xwiki", "My", "Page"));
        when(mockClonedDocument.getStore()).thenReturn(this.oldcore.getMockStore());
        when(xWiki.getStore()).thenReturn(this.oldcore.getMockStore());
        context.put("ajax", true);
        when(xWiki.isMultiLingual(this.context)).thenReturn(true);
        when(mockRequest.getParameter("previousVersion")).thenReturn("1.1");
        when(mockRequest.getParameter("isNew")).thenReturn("true");
        assertFalse(saveAction.save(this.context));
        assertEquals(new Version("1.1"), this.context.get("SaveAction.savedObjectVersion"));
        verify(this.xWiki).checkSavingDocument(eq(USER_REFERENCE), any(XWikiDocument.class), eq(""),
            eq(false), eq(this.context));
        verify(this.xWiki).saveDocument(any(XWikiDocument.class), eq(""), eq(false), eq(this.context));
    }
//  [java]
    private AbstractAuthorityFactory createBackingStore0() throws FactoryException, SQLException {
        /*
         * We are locking on ReferencingFactoryFinder to avoid deadlocks.
         * @see DeferredAuthorityFactory#getBackingStore()
         */
        assert Thread.holdsLock(ReferencingFactoryFinder.class);
        final Hints sourceHints = new Hints(hints);
        sourceHints.putAll(factories.getImplementationHints());
        if (datasource != null) {
            return createBackingStore(sourceHints);
        }
        /*
         * Try to gets the DataSource from JNDI. In case of success, it will be tried
         * for a connection before any DataSource declared in META-INF/services/.
         */
        DataSource source = createDataSource();
        if (source == null) {
            throw new FactoryNotFoundException(Errors.format(ErrorKeys.NO_DATA_SOURCE));
        }
        final AbstractAuthorityFactory factory;
        try {
            datasource = source;
            factory = createBackingStore(sourceHints);
        } finally {
            datasource = null;
        }
        this.datasource = source; // Stores the data source only after success.
        return factory;
    }
//  [java]
    private AbstractAuthorityFactory createBackingStore0() throws FactoryException, SQLException {
        /*
         * We are locking on ReferencingFactoryFinder to avoid deadlocks.
         * @see DeferredAuthorityFactory#getBackingStore()
         */
        assert Thread.holdsLock(ReferencingFactoryFinder.class);
        final Hints sourceHints = new Hints(hints);
        sourceHints.putAll(factories.getImplementationHints());
        if (datasource != null) {
            return createBackingStore(sourceHints);
        }
        /*
         * Try to gets the DataSource from JNDI. In case of success, it will be tried
         * for a connection before any DataSource declared in META-INF/services/.
         */
        DataSource source;
        final InitialContext context;
        try {
            source = createDataSource();
            context = registerInto;
        } finally {
            registerInto = null;
        }
        if (source == null) {
            throw new FactoryNotFoundException(Errors.format(ErrorKeys.NO_DATA_SOURCE));
        }
        final AbstractAuthorityFactory factory;
        try {
            datasource = source;
            factory = createBackingStore(sourceHints);
        } finally {
            datasource = null;
        }
        /*
         * We now have a working connection. If a naming directory is running but didn't contains
         * the "jdbc/EPSG" entry, add it now. In such case, a message is prepared and logged.
         */
        LogRecord record;
        if (ALLOW_REGISTRATION && context != null) {
            try {
                context.bind(datasourceName, source);
                record =
                        Loggings.format(
                                Level.FINE,
                                LoggingKeys.CREATED_DATASOURCE_ENTRY_$1,
                                datasourceName);
            } catch (NamingException exception) {
                record =
                        Loggings.format(
                                Level.WARNING, LoggingKeys.CANT_BIND_DATASOURCE_$1, datasourceName);
                record.setThrown(exception);
            }
            log(record);
        }
        this.datasource = source; // Stores the data source only after success.
        return factory;
    }
//  [java]
    protected DataSource createDataSource() throws SQLException {
        DataSource source = null;
        try {
            source = (DataSource) GeoTools.jndiLookup(datasourceName);
        } catch (IllegalArgumentException | NamingException exception) {
            // Fall back on 'return null' below.
        }
        return source;
    }
//  [java]
    protected DataSource createDataSource() throws SQLException {
        InitialContext context = null;
        DataSource source = null;
        try {
            context = GeoTools.getInitialContext();
            source = (DataSource) context.lookup(datasourceName);
        } catch (IllegalArgumentException | NoInitialContextException exception) {
            // Fall back on 'return null' below.
        } catch (NamingException exception) {
            registerInto = context;
            // Fall back on 'return null' below.
        }
        return source;
    }
//  [java]
    void setup()
    {
        this.context = this.oldcore.getXWikiContext();

        this.xWiki = mock(XWiki.class);
        this.context.setWiki(this.xWiki);

        this.mockRequest = mock(XWikiRequest.class);
        this.context.setRequest(this.mockRequest);

        this.mockResponse = mock(XWikiResponse.class);
        this.context.setResponse(this.mockResponse);

        this.mockDocument = mock(XWikiDocument.class);
        this.context.setDoc(this.mockDocument);

        this.mockClonedDocument = mock(XWikiDocument.class);
        when(this.mockDocument.clone()).thenReturn(this.mockClonedDocument);

        this.mockForm = mock(EditForm.class);
        this.context.setForm(this.mockForm);
        when(this.entityNameValidationConfiguration.useValidation()).thenReturn(false);

        this.context.setUserReference(USER_REFERENCE);
    }
//  [java]
    void setup()
    {
        this.saveAction = new SaveAction();

        context = oldcore.getXWikiContext();

        xWiki = mock(XWiki.class);
        context.setWiki(this.xWiki);

        mockRequest = mock(XWikiRequest.class);
        context.setRequest(mockRequest);

        mockResponse = mock(XWikiResponse.class);
        context.setResponse(mockResponse);

        mockDocument = mock(XWikiDocument.class);
        context.setDoc(mockDocument);

        mockClonedDocument = mock(XWikiDocument.class);
        when(mockDocument.clone()).thenReturn(mockClonedDocument);

        mockForm = mock(EditForm.class);
        context.setForm(mockForm);
        when(this.entityNameValidationConfiguration.useValidation()).thenReturn(false);

        context.setUserReference(USER_REFERENCE);
    }
//  [java]
    void newDocumentInvalidName() throws Exception
    {
        when(mockDocument.isNew()).thenReturn(true);
        DocumentReference documentReference = new DocumentReference("XWiki", "Foo", "Bar");
        when(mockDocument.getDocumentReference()).thenReturn(documentReference);
        when(this.entityNameValidationConfiguration.useValidation()).thenReturn(true);
        EntityNameValidation entityNameValidation = mock(EntityNameValidation.class);
        when(this.entityNameValidationManager.getEntityReferenceNameStrategy()).thenReturn(entityNameValidation);
        when(entityNameValidation.isValid(documentReference)).thenReturn(false);

        assertTrue(saveAction.save(this.context));
        assertEquals("entitynamevalidation.create.invalidname", context.get("message"));
        assertArrayEquals(new Object[] {"Foo.Bar"}, (Object[]) context.get("messageParameters"));
    }
//  [java]
    void newDocumentInvalidName() throws Exception
    {
        when(mockDocument.isNew()).thenReturn(true);
        DocumentReference documentReference = new DocumentReference("XWiki", "Foo", "Bar");
        when(mockDocument.getDocumentReference()).thenReturn(documentReference);
        when(this.entityNameValidationConfiguration.useValidation()).thenReturn(true);
        EntityNameValidation entityNameValidation = mock(EntityNameValidation.class);
        when(this.entityNameValidationManager.getEntityReferenceNameStrategy()).thenReturn(entityNameValidation);
        when(entityNameValidation.isValid(documentReference)).thenReturn(false);

        assertTrue(saveAction.save(this.context));
        assertEquals("entitynamevalidation.create.invalidname", context.get("message"));
        assertArrayEquals(new Object[] { "Foo.Bar" }, (Object[]) context.get("messageParameters"));
    }
//  [java]
    void validSaveRequestImageUploadAndConflictCheck() throws Exception
    {
        when(mockDocument.getRCSVersion()).thenReturn(new Version("1.2"));
        when(mockClonedDocument.getRCSVersion()).thenReturn(new Version("1.2"));
        when(mockClonedDocument.getComment()).thenReturn("My Changes");
        when(mockClonedDocument.getLock(this.context)).thenReturn(mock(XWikiLock.class));
        when(mockForm.getTemplate()).thenReturn("");
        when(this.propertiesConf.getProperty("edit.conflictChecking.enabled")).thenReturn(true);
        when(mockRequest.getParameter("previousVersion")).thenReturn("1.1");
        context.put("ajax", true);
        when(mockRequest.getParameter("forceSave")).thenReturn("");
        when(mockRequest.getParameter("isNew")).thenReturn("true");

        when(mockDocument.getDate()).thenReturn(new Date(42));
        when(mockRequest.getParameter("editingVersionDate")).thenReturn("43");
        when(this.documentRevisionProvider.getRevision(mockDocument, "1.1")).thenReturn(mock(XWikiDocument.class));
        when(mockDocument.getContentDiff("1.1", "1.2", context)).thenReturn(Collections.emptyList());
        when(mockDocument.getMetaDataDiff("1.1", "1.2", context)).thenReturn(Collections.emptyList());
        when(mockDocument.getObjectDiff("1.1", "1.2", context)).thenReturn(Collections.emptyList());

        assertFalse(saveAction.save(this.context));
        assertEquals(new Version("1.2"), this.context.get("SaveAction.savedObjectVersion"));

        verify(mockClonedDocument).setAuthor("XWiki.FooBar");
        verify(mockClonedDocument).setMetaDataDirty(true);
        verify(this.xWiki).checkSavingDocument(USER_REFERENCE, mockClonedDocument, "My Changes", false, this.context);
        verify(this.xWiki).saveDocument(mockClonedDocument, "My Changes", false, this.context);
        verify(mockClonedDocument).removeLock(this.context);
    }
//  [java]
    void validSaveRequestImageUploadAndConflictCheck() throws Exception
    {
        when(mockDocument.getRCSVersion()).thenReturn(new Version("1.2"));
        when(mockClonedDocument.getRCSVersion()).thenReturn(new Version("1.2"));
        when(mockClonedDocument.getComment()).thenReturn("My Changes");
        when(mockClonedDocument.getLock(this.context)).thenReturn(mock(XWikiLock.class));
        when(mockForm.getTemplate()).thenReturn("");
        when(this.propertiesConf.getProperty("edit.conflictChecking.enabled")).thenReturn(true);
        when(mockRequest.getParameter("previousVersion")).thenReturn("1.1");
        context.put("ajax", true);
        when(mockRequest.getParameter("forceSave")).thenReturn("");
        when(mockRequest.getParameter("isNew")).thenReturn("true");

        when(mockDocument.getDate()).thenReturn(new Date(42));
        when(mockRequest.getParameter("editingVersionDate")).thenReturn("43");
        when(this.documentRevisionProvider.getRevision(mockDocument, "1.1")).thenReturn(mock(XWikiDocument.class));
        when(mockDocument.getContentDiff("1.1", "1.2", context)).thenReturn(Collections.emptyList());
        when(mockDocument.getMetaDataDiff("1.1", "1.2", context)).thenReturn(Collections.emptyList());
        when(mockDocument.getObjectDiff("1.1", "1.2", context)).thenReturn(Collections.emptyList());

        assertFalse(saveAction.save(this.context));
        assertEquals(new Version("1.2"), this.context.get("SaveAction.savedObjectVersion"));

        verify(mockClonedDocument).readFromTemplate("", this.context);
        verify(mockClonedDocument).setAuthor("XWiki.FooBar");
        verify(mockClonedDocument).setMetaDataDirty(true);
        verify(this.xWiki).checkSavingDocument(USER_REFERENCE, mockClonedDocument, "My Changes", false, this.context);
        verify(this.xWiki).saveDocument(mockClonedDocument, "My Changes", false, this.context);
        verify(mockClonedDocument).removeLock(this.context);

    }