jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    public ResponseEntity<Resource> fetch(@PathVariable String key) {
        LitemallStorage litemallStorage = litemallStorageService.findByKey(key);
        if (key == null) {
            ResponseEntity.notFound();
        }
        String type = litemallStorage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = storageService.loadAsResource(key);
        if (file == null) {
            ResponseEntity.notFound();
        }
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }
//  [java]
    public ResponseEntity<Resource> download(@PathVariable String key) {
        LitemallStorage litemallStorage = litemallStorageService.findByKey(key);
        if (key == null) {
            return ResponseEntity.notFound().build();
        }
        if(key.contains("../")){
            return ResponseEntity.badRequest().build();
        }

        String type = litemallStorage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = storageService.loadAsResource(key);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }
//  [java]
    public ResponseEntity<Resource> download(@PathVariable String key) {
        LitemallStorage litemallStorage = litemallStorageService.findByKey(key);
        if (key == null) {
            ResponseEntity.notFound();
        }
        String type = litemallStorage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = storageService.loadAsResource(key);
        if (file == null) {
            ResponseEntity.notFound();
        }
        return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }
//  [java]
    public void translate(GeyserSession session, ItemFrameDropItemPacket packet) {
        Entity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
        if (entity != null) {
            ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(),
                    InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking());
            session.sendDownstreamPacket(interactPacket);
        }
    }
//  [java]
    public void translate(ItemFrameDropItemPacket packet, GeyserSession session) {
        Entity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
        if (entity != null) {
            ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(),
                    InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking());
            session.sendDownstreamPacket(interactPacket);
        }
    }
//  [java]
	public static HColor noGradient(HColor color) {
		if (color instanceof HColorGradient)
			return ((HColorGradient) color).getColor1();

		return color;
	}
//  [java]
	public static HColor noGradient(HColor color) {
		if (color instanceof HColorGradient) {
			return ((HColorGradient) color).getColor1();
		}
		return color;
	}
//  [java]
	public static boolean isTransparent(HColor back) {
		if (back == TRANSPARENT)
			return true;

		if (back instanceof HColorBackground && ((HColorBackground) back).getBack() == TRANSPARENT)
			return true;

		if (back instanceof HColorSimple && ((HColorSimple) back).isTransparent())
			return true;

		return false;
	}
//  [java]
	public static boolean isTransparent(HColor back) {
		if (back == TRANSPARENT) {
			return true;
		}
		if (back instanceof HColorBackground && ((HColorBackground) back).getBack() == TRANSPARENT) {
			return true;
		}
		if (back instanceof HColorSimple && ((HColorSimple) back).isTransparent()) {
			return true;
		}
		return false;
	}
//  [java]
    public URL createURL(String spaces, String name, String queryString, String anchor, String wikiId,
        XWikiContext context, FilesystemExportContext exportContext) throws Exception
    {
        // Check if the current user has the right to view the SX file. We do this since this is what would happen
        // in XE when a SX action is called (check done in XWikiAction).
        // Note that we cannot just open an HTTP connection to the SX action here since we wouldn't be authenticated...
        // Thus we have to simulate the same behavior as the SX action...

        List<String> spaceNames = this.legacySpaceResolve.resolve(spaces);
        DocumentReference sxDocumentReference = new DocumentReference(wikiId, spaceNames, name);
        this.authorizationManager.checkAccess(Right.VIEW, sxDocumentReference);

        // Set the SX document as the current document in the XWiki Context since unfortunately the SxSource code
        // uses the current document in the context instead of accepting it as a parameter...
        XWikiDocument sxDocument = context.getWiki().getDocument(sxDocumentReference, context);

        Map<String, Object> backup = new HashMap<>();
        XWikiDocument.backupContext(backup, context);
        try {
            sxDocument.setAsContextDoc(context);
            return processSx(sxDocument.getId(), queryString, context, exportContext);
        } finally {
            XWikiDocument.restoreContext(backup, context);
        }
    }
//  [java]
    public URL createURL(String spaces, String name, String queryString, String anchor, String wikiId,
        XWikiContext context, FilesystemExportContext exportContext) throws Exception
    {
        // Check if the current user has the right to view the SX file. We do this since this is what would happen
        // in XE when a SX action is called (check done in XWikiAction).
        // Note that we cannot just open an HTTP connection to the SX action here since we wouldn't be authenticated...
        // Thus we have to simulate the same behavior as the SX action...

        List<String> spaceNames = this.legacySpaceResolve.resolve(spaces);
        DocumentReference sxDocumentReference = new DocumentReference(wikiId, spaceNames, name);
        this.authorizationManager.checkAccess(Right.VIEW, sxDocumentReference);

        // Set the SX document as the current document in the XWiki Context since unfortunately the SxSource code
        // uses the current document in the context instead of accepting it as a parameter...
        XWikiDocument sxDocument = context.getWiki().getDocument(sxDocumentReference, context);

        Map<String, Object> backup = new HashMap<>();
        XWikiDocument.backupContext(backup, context);
        try {
            sxDocument.setAsContextDoc(context);
            return processSx(spaceNames, name, queryString, context, exportContext);
        } finally {
            XWikiDocument.restoreContext(backup, context);
        }
    }
//  [java]
    private URL processSx(long id, String queryString, XWikiContext context,
        FilesystemExportContext exportContext) throws Exception
    {
        SxSource sxSource = null;

        // Check if we have the JAR_RESOURCE_REQUEST_PARAMETER parameter in the query string
        List<NameValuePair> params = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
        for (NameValuePair param : params) {
            if (param.getName().equals(JAR_RESOURCE_REQUEST_PARAMETER)) {
                sxSource = new SxResourceSource(param.getValue());
                break;
            }
        }

        if (sxSource == null) {
            sxSource = new SxDocumentSource(context, getExtensionType());
        }

        String content = getContent(sxSource, exportContext);

        // Write the content to file
        // We need a unique name for that SSX content
        String targetPath = String.format("%s/%s", getSxPrefix(), id);
        File targetDirectory = new File(exportContext.getExportDir(), targetPath);
        if (!targetDirectory.exists()) {
            targetDirectory.mkdirs();
        }
        File targetLocation = File.createTempFile(getSxPrefix(), "." + getFileSuffix(), targetDirectory);
        FileUtils.writeStringToFile(targetLocation, content);

        // Rewrite the URL
        StringBuilder path = new StringBuilder("file://");

        // Adjust based on current document's location. We need to account for the fact that the current document
        // is stored in subdirectories inside the top level "pages" directory. Since the SX files are also in top
        // subdirectories, we need to compute the path to them.
        path.append(StringUtils.repeat("../", exportContext.getDocParentLevel()));

        path.append(getSxPrefix());
        path.append(URL_PATH_SEPARATOR);
        path.append(id);
        path.append(URL_PATH_SEPARATOR);
        path.append(encodeURLPart(targetLocation.getName()));

        return new URL(path.toString());
    }
//  [java]
    private URL processSx(List<String> spaceNames, String name, String queryString, XWikiContext context,
        FilesystemExportContext exportContext) throws Exception
    {
        SxSource sxSource = null;

        // Check if we have the JAR_RESOURCE_REQUEST_PARAMETER parameter in the query string
        List<NameValuePair> params = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
        for (NameValuePair param : params) {
            if (param.getName().equals(JAR_RESOURCE_REQUEST_PARAMETER)) {
                sxSource = new SxResourceSource(param.getValue());
                break;
            }
        }

        if (sxSource == null) {
            sxSource = new SxDocumentSource(context, getExtensionType());
        }

        String content = getContent(sxSource, exportContext);

        // Write the content to file
        // We need a unique name for that SSX content
        String targetPath = String.format("%s/%s/%s", getSxPrefix(), StringUtils.join(spaceNames, '/'), name);
        File targetDirectory = new File(exportContext.getExportDir(), targetPath);
        if (!targetDirectory.exists()) {
            targetDirectory.mkdirs();
        }
        File targetLocation = File.createTempFile(getSxPrefix(), "." + getFileSuffix(), targetDirectory);
        FileUtils.writeStringToFile(targetLocation, content);

        // Rewrite the URL
        StringBuilder path = new StringBuilder("file://");

        // Adjust based on current document's location. We need to account for the fact that the current document
        // is stored in subdirectories inside the top level "pages" directory. Since the SX files are also in top
        // subdirectories, we need to compute the path to them.
        path.append(StringUtils.repeat("../", exportContext.getDocParentLevel()));

        path.append(getSxPrefix());
        path.append(URL_PATH_SEPARATOR);
        for (String spaceName : spaceNames) {
            path.append(encodeURLPart(spaceName));
            path.append(URL_PATH_SEPARATOR);
        }
        path.append(encodeURLPart(name));
        path.append(URL_PATH_SEPARATOR);
        path.append(encodeURLPart(targetLocation.getName()));

        return new URL(path.toString());
    }
//  [java]
	public static HColor unlinear(HColor color1, HColor color2, int completion) {
		if (completion == 0)
			return color1;

		if (completion == 100)
			return color2;

		if (color1 instanceof HColorSimple && color2 instanceof HColorSimple)
			return HColorSimple.unlinear((HColorSimple) color1, (HColorSimple) color2, completion);

		return color1;
	}
//  [java]
	public static HColor unlinear(HColor color1, HColor color2, int completion) {
		if (completion == 0) {
			return color1;
		}
		if (completion == 100) {
			return color2;
		}
		if (color1 instanceof HColorSimple && color2 instanceof HColorSimple) {
			return HColorSimple.unlinear((HColorSimple) color1, (HColorSimple) color2, completion);
		}
		return color1;
	}
//  [java]
    protected String getContent(SxSource sxSource, FilesystemExportContext exportContext)
    {
        String content;

        // We know we're inside a SX file located at "<S|J>sx/<id>/<s|j>sx<NNN>.<css|js>". Inside this CSS
        // there can be URLs and we need to ensure that the prefix for these URLs lead to the root of the path, i.e.
        // 3 levels up ("../../").
        // To make this happen we reuse the Doc Parent Level from FileSystemExportContext to a fixed value of 3.
        // We also make sure to put back the original value
        int originalDocParentLevel = exportContext.getDocParentLevel();
        try {
            exportContext.setDocParentLevels(2);
            content = sxSource.getContent();
        } finally {
            exportContext.setDocParentLevels(originalDocParentLevel);
        }

        return content;
    }
//  [java]
    protected String getContent(SxSource sxSource, FilesystemExportContext exportContext)
    {
        String content;

        // We know we're inside a SX file located at "<S|J>sx/<Space>/<Page>/<s|j>sx<NNN>.<css|js>". Inside this CSS
        // there can be URLs and we need to ensure that the prefix for these URLs lead to the root of the path, i.e.
        // 3 levels up ("../../../").
        // To make this happen we reuse the Doc Parent Level from FileSystemExportContext to a fixed value of 3.
        // We also make sure to put back the original value
        int originalDocParentLevel = exportContext.getDocParentLevel();
        try {
            exportContext.setDocParentLevels(3);
            content = sxSource.getContent();
        } finally {
            exportContext.setDocParentLevels(originalDocParentLevel);
        }

        return content;
    }
//  [java]
    void setup(MockitoComponentManager componentManager) throws Exception
    {
        DocumentReferenceResolver<String> currentReferenceResolver =
            componentManager.getInstance(DocumentReferenceResolver.TYPE_STRING, "current");
        when(currentReferenceResolver.resolve(testSource)).thenReturn(documentReference);

        Execution execution = componentManager.getInstance(Execution.class);
        ExecutionContext executionContext = mock(ExecutionContext.class);
        when(execution.getContext()).thenReturn(executionContext);
        when(executionContext.getProperty("xwikicontext")).thenReturn(xWikiContext);

        when(xWikiContext.getWiki()).thenReturn(xwiki);
        when(xwiki.getDocument(documentReference, xWikiContext)).thenReturn(xWikiDocument);

        DocumentReferenceResolver<EntityReference> currentReferenceEntityResolver =
            componentManager.getInstance(DocumentReferenceResolver.TYPE_REFERENCE, "current");

        when(currentReferenceEntityResolver.resolve(DefaultGadgetSource.GADGET_CLASS)).thenReturn(gadgetClassReference);
        TransformationContext transformationContext = mock(TransformationContext.class);
        when(macroTransformationContext.getTransformationContext()).thenReturn(transformationContext);
        when(transformationContext.getId()).thenReturn(transformationId);

        VelocityManager velocityManager = componentManager.getInstance(VelocityManager.class);
        when(velocityManager.getVelocityEngine()).thenReturn(velocityEngine);

        when(authorExecutor.call(any(), eq(ownerAuthorReference), eq(ownerSourceReference))).then(invocationOnMock -> {
            Callable callable = (Callable) invocationOnMock.getArguments()[0];
            return callable.call();
        });

        this.contentExecutor =
            componentManager.getInstance(ContentExecutor.TYPE_MACRO_TRANSFORMATION);
        when(contentExecutor.execute(any(), any(), any(), any())).then((Answer<XDOM>) invocationOnMock -> {
            String content = invocationOnMock.getArgument(0);
            XDOM xdom = new XDOM(Collections.singletonList(new WordBlock(content)));
            return xdom;
        });
        when(ownerDocument.getAuthorReference()).thenReturn(ownerAuthorReference);
        when(ownerDocument.getDocumentReference()).thenReturn(ownerSourceReference);
    }
//  [java]
    void setup(MockitoComponentManager componentManager) throws Exception
    {
        DocumentReferenceResolver<String> currentReferenceResolver =
            componentManager.getInstance(DocumentReferenceResolver.TYPE_STRING, "current");
        when(currentReferenceResolver.resolve(testSource)).thenReturn(documentReference);

        Execution execution = componentManager.getInstance(Execution.class);
        ExecutionContext executionContext = mock(ExecutionContext.class);
        when(execution.getContext()).thenReturn(executionContext);
        when(executionContext.getProperty("xwikicontext")).thenReturn(xWikiContext);

        when(xWikiContext.getWiki()).thenReturn(xwiki);
        when(xwiki.getDocument(documentReference, xWikiContext)).thenReturn(xWikiDocument);

        DocumentReferenceResolver<EntityReference> currentReferenceEntityResolver =
            componentManager.getInstance(DocumentReferenceResolver.TYPE_REFERENCE, "current");

        when(currentReferenceEntityResolver.resolve(DefaultGadgetSource.GADGET_CLASS)).thenReturn(gadgetClassReference);
        TransformationContext transformationContext = mock(TransformationContext.class);
        when(macroTransformationContext.getTransformationContext()).thenReturn(transformationContext);
        when(transformationContext.getId()).thenReturn(transformationId);

        VelocityManager velocityManager = componentManager.getInstance(VelocityManager.class);
        VelocityEngine velocityEngine = mock(VelocityEngine.class);
        when(velocityManager.getVelocityEngine()).thenReturn(velocityEngine);
        when(velocityEngine.evaluate(any(), any(), any(), any(String.class))).then((Answer<Void>) invocation -> {
            Object[] args = invocation.getArguments();
            StringWriter stringWriter = (StringWriter) args[1];
            String title = (String) args[3];
            stringWriter.append(title);
            return null;
        });

        AuthorExecutor authorExecutor = componentManager.getInstance(AuthorExecutor.class);
        when(authorExecutor.call(any(), eq(ownerAuthorReference), eq(ownerSourceReference))).then(invocationOnMock -> {
            Callable callable = (Callable) invocationOnMock.getArguments()[0];
            return callable.call();
        });

        ContentExecutor<MacroTransformationContext> contentExecutor =
            componentManager.getInstance(ContentExecutor.TYPE_MACRO_TRANSFORMATION);
        when(contentExecutor.execute(any(), any(), any(), any())).then((Answer<XDOM>) invocationOnMock -> {
            String content = invocationOnMock.getArgument(0);
            XDOM xdom = new XDOM(Collections.singletonList(new WordBlock(content)));
            return xdom;
        });
        when(ownerDocument.getAuthorReference()).thenReturn(ownerAuthorReference);
        when(ownerDocument.getDocumentReference()).thenReturn(ownerSourceReference);
    }
//  [java]
    public void translate(GeyserSession session, ServerUpdateScorePacket packet) {
        WorldCache worldCache = session.getWorldCache();
        Scoreboard scoreboard = worldCache.getScoreboard();
        int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();

        Objective objective = scoreboard.getObjective(packet.getObjective());
        if (objective == null && packet.getAction() != ScoreboardAction.REMOVE) {
            logger.info(LanguageUtils.getLocaleStringLog("geyser.network.translator.score.failed_objective", packet.getObjective()));
            return;
        }

        switch (packet.getAction()) {
            case ADD_OR_UPDATE:
                objective.setScore(packet.getEntry(), packet.getValue());
                break;
            case REMOVE:
                if (objective != null) {
                    objective.removeScore(packet.getEntry());
                } else {
                    for (Objective objective1 : scoreboard.getObjectives().values()) {
                        objective1.removeScore(packet.getEntry());
                    }
                }
                break;
        }

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

        Objective objective = scoreboard.getObjective(packet.getObjective());
        if (objective == null && packet.getAction() != ScoreboardAction.REMOVE) {
            logger.info(LanguageUtils.getLocaleStringLog("geyser.network.translator.score.failed_objective", packet.getObjective()));
            return;
        }

        switch (packet.getAction()) {
            case ADD_OR_UPDATE:
                objective.setScore(packet.getEntry(), packet.getValue());
                break;
            case REMOVE:
                if (objective != null) {
                    objective.removeScore(packet.getEntry());
                } else {
                    for (Objective objective1 : scoreboard.getObjectives().values()) {
                        objective1.removeScore(packet.getEntry());
                    }
                }
                break;
        }

        // ScoreboardUpdater will handle it for us if the packets per second
        // (for score and team packets) is higher then the first threshold
        if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) {
            scoreboard.onUpdate();
        }
    }
//  [java]
    void getGadgets() throws Exception
    {
        assertEquals(new ArrayList<>(), this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext));

        BaseObject gadgetObject1 = mock(BaseObject.class);
        when(xWikiDocument.getXObjects(gadgetClassReference)).thenReturn(Collections.singletonList(gadgetObject1));
        when(gadgetObject1.getOwnerDocument()).thenReturn(ownerDocument);
        when(gadgetObject1.getStringValue("title")).thenReturn("Gadget 1");
        when(gadgetObject1.getLargeStringValue("content")).thenReturn("Some content");
        when(gadgetObject1.getStringValue("position")).thenReturn("0");
        when(gadgetObject1.getNumber()).thenReturn(42);
        when(this.authorizationManager.hasAccess(Right.SCRIPT, ownerAuthorReference, ownerSourceReference)).thenReturn(true);
        when(this.velocityEngine.evaluate(any(), any(), any(), eq("Gadget 1"))).then((Answer<Void>) invocation -> {
            Object[] args = invocation.getArguments();
            StringWriter stringWriter = (StringWriter) args[1];
            String title = "Evaluated velocity version of gadget 1";
            stringWriter.append(title);
            return null;
        });

        List<Gadget> gadgets = this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext);
        assertEquals(1, gadgets.size());
        Gadget gadget = gadgets.get(0);
        assertEquals("Evaluated velocity version of gadget 1", gadget.getTitle().get(0).toString());
        assertEquals("Some content", gadget.getContent().get(0).toString());
        assertEquals("42", gadget.getId());
        verify(this.contentExecutor)
            .execute(eq("Evaluated velocity version of gadget 1"), any(), any(), any());
        verify(this.contentExecutor)
            .execute(eq("Some content"), any(), any(), any());
    }
//  [java]
    void getGadgets() throws Exception
    {
        assertEquals(new ArrayList<>(), this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext));

        BaseObject gadgetObject1 = mock(BaseObject.class);
        when(xWikiDocument.getXObjects(gadgetClassReference)).thenReturn(Collections.singletonList(gadgetObject1));
        when(gadgetObject1.getOwnerDocument()).thenReturn(ownerDocument);
        when(gadgetObject1.getStringValue("title")).thenReturn("Gadget 1");
        when(gadgetObject1.getLargeStringValue("content")).thenReturn("Some content");
        when(gadgetObject1.getStringValue("position")).thenReturn("0");
        when(gadgetObject1.getNumber()).thenReturn(42);

        List<Gadget> gadgets = this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext);
        assertEquals(1, gadgets.size());
        Gadget gadget = gadgets.get(0);
        assertEquals("Gadget 1", gadget.getTitle().get(0).toString());
        assertEquals("Some content", gadget.getContent().get(0).toString());
        assertEquals("42", gadget.getId());
    }
//  [java]
    private File extract(ArrayList<String> errors, URL source, String prefix, String suffix, File directory) {
        File target = null;
        try {
            FileOutputStream os = null;
            InputStream is = null;
            try {
                target = File.createTempFile(prefix, suffix, directory);
                is = source.openStream();
                if (is != null) {
                    byte[] buffer = new byte[4096];
                    os = new FileOutputStream(target);
                    int read;
                    while ((read = is.read(buffer)) != -1) {
                        os.write(buffer, 0, read);
                    }
                    chmod("755", target);
                }
                target.deleteOnExit();
                return target;
            } finally {
                close(os);
                close(is);
            }
        } catch (Throwable e) {
            if( target!=null ) {
                target.delete();
            }
            errors.add(e.getMessage());
        }
        return null;
    }
//  [java]
    private boolean extract(ArrayList<String> errors, URL source, File target) {
        FileOutputStream os = null;
        InputStream is = null;
        boolean extracting = false;
        try {
            if (!target.exists() || isStale(source, target) ) {
                is = source.openStream();
                if (is != null) {
                    byte[] buffer = new byte[4096];
                    os = new FileOutputStream(target);
                    extracting = true;
                    int read;
                    while ((read = is.read(buffer)) != -1) {
                        os.write(buffer, 0, read);
                    }
                    os.close();
                    is.close();
                    chmod("755", target);
                }
            }
        } catch (Throwable e) {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e1) {
            }
            try {
                if (is != null)
                    is.close();
            } catch (IOException e1) {
            }
            if (extracting && target.exists())
                target.delete();
            errors.add(e.getMessage());
            return false;
        }
        return true;
    }
//  [java]
    private String createRuntimeSource(RuntimeModel model, String baseClassName,
                                       boolean scriptInDocs) {
        SourceWriter writer = new SourceWriter(model);
        if (scriptInDocs) {
            writer.setScript(theScript);
        }
        writer.setBaseClassName(baseClassName);
        scriptModel.write(writer);
        return writer.getSource();
    }
//  [java]
    private String createRuntimeSource(RuntimeModel model, String baseClassName, boolean scriptInDocs) {
        if (scriptInDocs) {
            throw new RuntimeException("Do no know how to clean the block comments yet");
        }

        SourceWriter writer = new SourceWriter(model);
        writer.setScript(stripComments(theScript));
        writer.setBaseClassName(baseClassName);
        scriptModel.write(writer);
        return writer.getSource();
    }
//  [java]
    private JiffleRuntime createRuntimeInstance(RuntimeModel model, Class<? extends JiffleRuntime> runtimeClass, boolean scriptInDocs) throws
            
            it.geosolutions.jaiext.jiffle.JiffleException {
        if (!isCompiled()) {
            throw new it.geosolutions.jaiext.jiffle.JiffleException("The script has not been compiled");
        }

        String runtimeSource = createRuntimeSource(model, runtimeClass.getName(), scriptInDocs);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "Jiffle script compiled to:\n\n" + runtimeSource);    
        }
        try {
            SimpleCompiler compiler = new SimpleCompiler();
            compiler.cook(runtimeSource);

            StringBuilder sb = new StringBuilder();
            sb.append(it.geosolutions.jaiext.jiffle.JiffleProperties.get(
                    it.geosolutions.jaiext.jiffle.JiffleProperties.RUNTIME_PACKAGE_KEY)).append(".");

            switch (model) {
                case DIRECT:
                    sb.append(it.geosolutions.jaiext.jiffle.JiffleProperties.get(
                            it.geosolutions.jaiext.jiffle.JiffleProperties.DIRECT_CLASS_KEY));
                    break;

                case INDIRECT:
                    sb.append(it.geosolutions.jaiext.jiffle.JiffleProperties.get(
                            it.geosolutions.jaiext.jiffle.JiffleProperties.INDIRECT_CLASS_KEY));
                    break;

                default:
                    throw new IllegalArgumentException("Internal compiler error");
            }

            Class<?> clazz = compiler.getClassLoader().loadClass(sb.toString());
            JiffleRuntime runtime = (JiffleRuntime) clazz.newInstance();
            runtime.setImageParams(imageParams);
            if (runtime instanceof JiffleIndirectRuntime) {
                ((JiffleIndirectRuntime) runtime).setDestinationBands(destinationBands);
            }
            return runtime;

        } catch (Exception ex) {
            // do not display the source code in indirect runtime exception messages
            if (model == RuntimeModel.INDIRECT) {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine("Runtime source error for source: " + runtimeSource);
                }
                throw new JiffleException("Runtime source error", ex);
            }
            throw new JiffleException("Runtime source error for source: " + runtimeSource, ex);
        }
    }
//  [java]
    private JiffleRuntime createRuntimeInstance(RuntimeModel model, Class<? extends JiffleRuntime> runtimeClass, boolean scriptInDocs) throws
            
            it.geosolutions.jaiext.jiffle.JiffleException {
        if (!isCompiled()) {
            throw new it.geosolutions.jaiext.jiffle.JiffleException("The script has not been compiled");
        }

        String runtimeSource = createRuntimeSource(model, runtimeClass.getName(), scriptInDocs);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "Jiffle script compiled to:\n\n" + runtimeSource);    
        }
        try {
            SimpleCompiler compiler = new SimpleCompiler();
            compiler.cook(runtimeSource);

            StringBuilder sb = new StringBuilder();
            sb.append(it.geosolutions.jaiext.jiffle.JiffleProperties.get(
                    it.geosolutions.jaiext.jiffle.JiffleProperties.RUNTIME_PACKAGE_KEY)).append(".");

            switch (model) {
                case DIRECT:
                    sb.append(it.geosolutions.jaiext.jiffle.JiffleProperties.get(
                            it.geosolutions.jaiext.jiffle.JiffleProperties.DIRECT_CLASS_KEY));
                    break;

                case INDIRECT:
                    sb.append(it.geosolutions.jaiext.jiffle.JiffleProperties.get(
                            it.geosolutions.jaiext.jiffle.JiffleProperties.INDIRECT_CLASS_KEY));
                    break;

                default:
                    throw new IllegalArgumentException("Internal compiler error");
            }

            Class<?> clazz = compiler.getClassLoader().loadClass(sb.toString());
            JiffleRuntime runtime = (JiffleRuntime) clazz.newInstance();
            runtime.setImageParams(imageParams);
            if (runtime instanceof JiffleIndirectRuntime) {
                ((JiffleIndirectRuntime) runtime).setDestinationBands(destinationBands);
            }
            return runtime;

        } catch (Exception ex) {
            throw new it.geosolutions.jaiext.jiffle.JiffleException("Runtime source error for source: " + runtimeSource, ex);
        }
    }
//  [java]
    private boolean exractAndLoad(ArrayList<String> errors, String version, String customPath, String resourcePath) {
        URL resource = classLoader.getResource(resourcePath);
        if( resource !=null ) {

            String libName = name + "-" + getBitModel();
            if( version !=null) {
                libName += "-" + version;
            }
            String []libNameParts = map(libName).split("\\.");
            String prefix = libNameParts[0]+"-";
            String suffix = "."+libNameParts[1];

            if( customPath!=null ) {
                // Try to extract it to the custom path...
                File target = extract(errors, resource, prefix, suffix, file(customPath));
                if( target!=null ) {
                    if( load(errors, target) ) {
                        return true;
                    }
                }
            }
            
            // Fall back to extracting to the tmp dir
            customPath = System.getProperty("java.io.tmpdir");
            File target = extract(errors, resource, prefix, suffix, file(customPath));
            if( target!=null ) {
                if( load(errors, target) ) {
                    return true;
                }
            }
        }
        return false;
    }
//  [java]
    private boolean exractAndLoad(ArrayList<String> errors, String version, String customPath, String resourcePath) {
        URL resource = classLoader.getResource(resourcePath);
        if( resource !=null ) {
            
            String libName = name + "-" + getBitModel();
            if( version !=null) {
                libName += "-" + version;
            }
            
            if( customPath!=null ) {
                // Try to extract it to the custom path...
                File target = file(customPath, map(libName));
                if( extract(errors, resource, target) ) {
                    if( load(errors, target) ) {
                        return true;
                    }
                }
            }
            
            // Fall back to extracting to the tmp dir
            customPath = System.getProperty("java.io.tmpdir");
            File target = file(customPath, map(libName));
            if( extract(errors, resource, target) ) {
                if( load(errors, target) ) {
                    return true;
                }
            }
        }
        return false;
    }
//  [java]
    public void toScientificString(StringBuilder result) {
        assert(!isApproximate);
        if (isNegative()) {
            result.append('-');
        }
        if (precision == 0) {
            result.append("0E+0");
            return;
        }
        // NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from
        // rOptPos (aka -maxFrac) due to overflow.
        int upperPos = Math.min(precision + scale, lOptPos) - scale - 1;
        int lowerPos = Math.max(scale, rOptPos) - scale;
        int p = upperPos;
        result.append((char) ('0' + getDigitPos(p)));
        if ((--p) >= lowerPos) {
            result.append('.');
            for (; p >= lowerPos; p--) {
                result.append((char) ('0' + getDigitPos(p)));
            }
        }
        result.append('E');
        int _scale = upperPos + scale;
        if (_scale == Integer.MIN_VALUE) {
            result.append("-2147483648");
            return;
        } else if (_scale < 0) {
            _scale *= -1;
            result.append('-');
        } else {
            result.append('+');
        }
        if (_scale == 0) {
            result.append('0');
        }
        int insertIndex = result.length();
        while (_scale > 0) {
            int quot = _scale / 10;
            int rem = _scale % 10;
            result.insert(insertIndex, (char) ('0' + rem));
            _scale = quot;
        }
    }
//  [java]
    public void toScientificString(StringBuilder result) {
        assert(!isApproximate);
        if (isNegative()) {
            result.append('-');
        }
        if (precision == 0) {
            result.append("0E+0");
            return;
        }
        // NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from
        // rOptPos (aka -maxFrac) due to overflow.
        int upperPos = Math.min(precision + scale, lOptPos) - scale - 1;
        int lowerPos = Math.max(scale, rOptPos) - scale;
        int p = upperPos;
        result.append((char) ('0' + getDigitPos(p)));
        if ((--p) >= lowerPos) {
            result.append('.');
            for (; p >= lowerPos; p--) {
                result.append((char) ('0' + getDigitPos(p)));
            }
        }
        result.append('E');
        int _scale = upperPos + scale;
        if (_scale < 0) {
            _scale *= -1;
            result.append('-');
        } else {
            result.append('+');
        }
        if (_scale == 0) {
            result.append('0');
        }
        int insertIndex = result.length();
        while (_scale > 0) {
            int quot = _scale / 10;
            int rem = _scale % 10;
            result.insert(insertIndex, (char) ('0' + rem));
            _scale = quot;
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerEntityCollectItemPacket packet) {
        // Collected entity is the other entity
        Entity collectedEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectedEntityId());
        if (collectedEntity == null) return;
        // Collector is the entity 'picking up' the item
        Entity collectorEntity;
        if (packet.getCollectorEntityId() == session.getPlayerEntity().getEntityId()) {
            collectorEntity = session.getPlayerEntity();
        } else {
            collectorEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectorEntityId());
        }
        if (collectorEntity == null) return;
        if (collectedEntity instanceof ExpOrbEntity) {
            // Player just picked up an experience orb
            LevelEventPacket xpPacket = new LevelEventPacket();
            xpPacket.setType(LevelEventType.SOUND_EXPERIENCE_ORB_PICKUP);
            xpPacket.setPosition(collectedEntity.getPosition());
            xpPacket.setData(0);
            session.sendUpstreamPacket(xpPacket);
        } else {
            // Item is being picked up (visual only)
            TakeItemEntityPacket takeItemEntityPacket = new TakeItemEntityPacket();
            takeItemEntityPacket.setRuntimeEntityId(collectorEntity.getGeyserId());
            takeItemEntityPacket.setItemRuntimeEntityId(collectedEntity.getGeyserId());
            session.sendUpstreamPacket(takeItemEntityPacket);
        }
    }
//  [java]
    public void translate(ServerEntityCollectItemPacket packet, GeyserSession session) {
        // Collected entity is the other entity
        Entity collectedEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectedEntityId());
        if (collectedEntity == null) return;
        // Collector is the entity 'picking up' the item
        Entity collectorEntity;
        if (packet.getCollectorEntityId() == session.getPlayerEntity().getEntityId()) {
            collectorEntity = session.getPlayerEntity();
        } else {
            collectorEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectorEntityId());
        }
        if (collectorEntity == null) return;
        if (collectedEntity instanceof ExpOrbEntity) {
            // Player just picked up an experience orb
            LevelEventPacket xpPacket = new LevelEventPacket();
            xpPacket.setType(LevelEventType.SOUND_EXPERIENCE_ORB_PICKUP);
            xpPacket.setPosition(collectedEntity.getPosition());
            xpPacket.setData(0);
            session.sendUpstreamPacket(xpPacket);
        } else {
            // Item is being picked up (visual only)
            TakeItemEntityPacket takeItemEntityPacket = new TakeItemEntityPacket();
            takeItemEntityPacket.setRuntimeEntityId(collectorEntity.getGeyserId());
            takeItemEntityPacket.setItemRuntimeEntityId(collectedEntity.getGeyserId());
            session.sendUpstreamPacket(takeItemEntityPacket);
        }
    }
//  [java]
    public AbstractEpsgFactory(final Hints userHints) throws FactoryException {
        super(MAXIMUM_PRIORITY - 20);
        // The following hints have no effect on this class behaviour,
        // but tell to the user what this factory do about axis order.
        hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);
        hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);
        hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);

        //
        // We need to obtain our DataSource
        if (userHints != null) {
            Object hint = userHints.get(Hints.EPSG_DATA_SOURCE);
            if (hint instanceof String) {
                String name = (String) hint;
                try {
                    dataSource = (DataSource) GeoTools.jndiLookup(name);
                } catch (NamingException e) {
                    throw new FactoryException("A EPSG_DATA_SOURCE hint is required:" + e);
                }
                hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
            } else if (hint instanceof DataSource) {
                dataSource = (DataSource) hint;
                hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
            } else {
                throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
            }
        } else {
            throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
        }
    }
//  [java]
    public AbstractEpsgFactory(final Hints userHints) throws FactoryException {
        super(MAXIMUM_PRIORITY - 20);
        // The following hints have no effect on this class behaviour,
        // but tell to the user what this factory do about axis order.
        hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);
        hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);
        hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);

        //
        // We need to obtain our DataSource
        if (userHints != null) {
            Object hint = userHints.get(Hints.EPSG_DATA_SOURCE);
            if (hint instanceof String) {
                String name = (String) hint;
                try {
                    dataSource = (DataSource) GeoTools.getInitialContext().lookup(name);
                } catch (NamingException e) {
                    throw new FactoryException("A EPSG_DATA_SOURCE hint is required:" + e);
                }
                hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
            } else if (hint instanceof DataSource) {
                dataSource = (DataSource) hint;
                hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
            } else {
                throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
            }
        } else {
            throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerUnlockRecipesPacket packet) {
        if (packet.getAction() == UnlockRecipesAction.REMOVE) {
            session.getUnlockedRecipes().removeAll(Arrays.asList(packet.getRecipes()));
        } else {
            session.getUnlockedRecipes().addAll(Arrays.asList(packet.getRecipes()));
        }
    }
//  [java]
    public void translate(ServerUnlockRecipesPacket packet, GeyserSession session) {
        if (packet.getAction() == UnlockRecipesAction.REMOVE) {
            session.getUnlockedRecipes().removeAll(Arrays.asList(packet.getRecipes()));
        } else {
            session.getUnlockedRecipes().addAll(Arrays.asList(packet.getRecipes()));
        }
    }
//  [java]
    void testDecodePath(boolean isPathParam) throws Exception {
        final Function<String, String> decodeFunc;
        if (isPathParam) {
            decodeFunc = ArmeriaHttpUtil::decodePathParam;
        } else {
            decodeFunc = ArmeriaHttpUtil::decodePath;
        }

        // Fast path
        final String pathThatDoesNotNeedDecode = "/foo_bar_baz";
        assertThat(decodeFunc.apply(pathThatDoesNotNeedDecode)).isSameAs(pathThatDoesNotNeedDecode);

        // Slow path
        assertThat(decodeFunc.apply("/foo%20bar\u007fbaz")).isEqualTo("/foo bar\u007fbaz");
        assertThat(decodeFunc.apply("/%C2%A2")).isEqualTo("/¢"); // Valid UTF-8 sequence
        assertThat(decodeFunc.apply("/%20\u0080")).isEqualTo("/ �"); // Unallowed character
        assertThat(decodeFunc.apply("/%")).isEqualTo("/�"); // No digit
        assertThat(decodeFunc.apply("/%1")).isEqualTo("/�"); // Only a single digit
        assertThat(decodeFunc.apply("/%G0")).isEqualTo("/�"); // First digit is not hex.
        assertThat(decodeFunc.apply("/%0G")).isEqualTo("/�"); // Second digit is not hex.
        assertThat(decodeFunc.apply("/%C3%28")).isEqualTo("/�("); // Invalid UTF-8 sequence

        // %2F (/) must be decoded only for path parameters.
        if (isPathParam) {
            assertThat(decodeFunc.apply("/%2F")).isEqualTo("//");
        } else {
            assertThat(decodeFunc.apply("/%2F")).isEqualTo("/%2F");
        }
    }
//  [java]
    void testDecodePath() throws Exception {
        // Fast path
        final String pathThatDoesNotNeedDecode = "/foo_bar_baz";
        assertThat(decodePath(pathThatDoesNotNeedDecode)).isSameAs(pathThatDoesNotNeedDecode);

        // Slow path
        assertThat(decodePath("/foo%20bar\u007fbaz")).isEqualTo("/foo bar\u007fbaz");
        assertThat(decodePath("/%C2%A2")).isEqualTo("/¢"); // Valid UTF-8 sequence
        assertThat(decodePath("/%20\u0080")).isEqualTo("/ �"); // Unallowed character
        assertThat(decodePath("/%")).isEqualTo("/�"); // No digit
        assertThat(decodePath("/%1")).isEqualTo("/�"); // Only a single digit
        assertThat(decodePath("/%G0")).isEqualTo("/�"); // First digit is not hex.
        assertThat(decodePath("/%0G")).isEqualTo("/�"); // Second digit is not hex.
        assertThat(decodePath("/%C3%28")).isEqualTo("/�("); // Invalid UTF-8 sequence
    }
//  [java]
  public AccessControlList getAccessControlList(String mediaPackageId) throws NotFoundException,
  SearchServiceDatabaseException {
    EntityManager em = null;
    try {
      em = emf.createEntityManager();
      SearchEntity entity = getSearchEntity(mediaPackageId, em);
      if (entity == null) {
        throw new NotFoundException("Could not found media package with ID " + mediaPackageId);
      }
      if (entity.getAccessControl() == null) {
        return null;
      } else {
        return AccessControlParser.parseAcl(entity.getAccessControl());
      }
    } catch (NotFoundException e) {
      throw e;
    } catch (Exception e) {
      logger.error("Could not retrieve ACL {}", mediaPackageId, e);
      throw new SearchServiceDatabaseException(e);
    } finally {
      em.close();
    }
  }
//  [java]
  public AccessControlList getAccessControlList(String mediaPackageId) throws NotFoundException,
  SearchServiceDatabaseException {
    EntityManager em = null;
    try {
      em = emf.createEntityManager();
      SearchEntity entity = getSearchEntity(mediaPackageId, em);
      if (entity == null) {
        throw new NotFoundException("Could not found media package with ID " + mediaPackageId);
      }
      if (entity.getAccessControl() == null) {
        return null;
      } else {
        return AccessControlParser.parseAcl(entity.getAccessControl());
      }
    } catch (NotFoundException e) {
      throw e;
    } catch (Exception e) {
      logger.error("Could not retrieve ACL {}: {}", mediaPackageId, e.getMessage());
      throw new SearchServiceDatabaseException(e);
    } finally {
      em.close();
    }
  }