jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
	public static String compileMustache(Map<String, Object> context, String template, boolean escapeHtml) {
		if (context == null || StringUtils.isBlank(template)) {
			return "";
		}
		Writer writer = new StringWriter();
		try {
			Mustache.compiler().escapeHTML(escapeHtml).emptyStringIsFalse(true).compile(template).execute(context, writer);
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				logger.error(null, e);
			}
		}
		return writer.toString();
	}
//  [java]
	public static String compileMustache(Map<String, Object> context, String template) {
		if (context == null || StringUtils.isBlank(template)) {
			return "";
		}
		Writer writer = new StringWriter();
		try {
			Mustache.compiler().escapeHTML(false).emptyStringIsFalse(true).compile(template).execute(context, writer);
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				logger.error(null, e);
			}
		}
		return writer.toString();
	}
//  [java]
    public void translate(GeyserSession session, CommandBlockUpdatePacket packet) {
        String command = packet.getCommand();
        boolean outputTracked = packet.isOutputTracked();
        if (packet.isBlock()) {
            CommandBlockMode mode;
            switch (packet.getMode()) {
                case CHAIN: // The green one
                    mode = CommandBlockMode.SEQUENCE;
                    break;
                case REPEATING: // The purple one
                    mode = CommandBlockMode.AUTO;
                    break;
                default: // NORMAL, the orange one
                    mode = CommandBlockMode.REDSTONE;
                    break;
            }
            boolean isConditional = packet.isConditional();
            boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java
            ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket(
                    new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),
                    command, mode, outputTracked, isConditional, automatic);
            session.sendDownstreamPacket(commandBlockPacket);
        } else {
            ClientUpdateCommandBlockMinecartPacket commandMinecartPacket = new ClientUpdateCommandBlockMinecartPacket(
                    (int) session.getEntityCache().getEntityByGeyserId(packet.getMinecartRuntimeEntityId()).getEntityId(),
                    command, outputTracked
            );
            session.sendDownstreamPacket(commandMinecartPacket);
        }
    }
//  [java]
    public void translate(CommandBlockUpdatePacket packet, GeyserSession session) {
        String command = packet.getCommand();
        boolean outputTracked = packet.isOutputTracked();
        if (packet.isBlock()) {
            CommandBlockMode mode;
            switch (packet.getMode()) {
                case CHAIN: // The green one
                    mode = CommandBlockMode.SEQUENCE;
                    break;
                case REPEATING: // The purple one
                    mode = CommandBlockMode.AUTO;
                    break;
                default: // NORMAL, the orange one
                    mode = CommandBlockMode.REDSTONE;
                    break;
            }
            boolean isConditional = packet.isConditional();
            boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java
            ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket(
                    new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),
                    command, mode, outputTracked, isConditional, automatic);
            session.sendDownstreamPacket(commandBlockPacket);
        } else {
            ClientUpdateCommandBlockMinecartPacket commandMinecartPacket = new ClientUpdateCommandBlockMinecartPacket(
                    (int) session.getEntityCache().getEntityByGeyserId(packet.getMinecartRuntimeEntityId()).getEntityId(),
                    command, outputTracked
            );
            session.sendDownstreamPacket(commandMinecartPacket);
        }
    }
//  [java]
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String path = httpRequest.getServletPath();
        LOG.debug("Handling request for path {}", path);

        if (configuration.getRealm() == null || configuration.getRealm().equals("") || !configuration.isEnabled()) {
            LOG.debug("No authentication needed for path {}", path);
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = httpRequest.getSession(false);
        if (session != null) {
            Subject subject = (Subject) session.getAttribute("subject");
            if (subject != null) {
                LOG.debug("Session subject {}", subject);
                executeAs(request, response, chain, subject);
                return;
            }
        }

        boolean doAuthenticate = true;

        if (doAuthenticate) {
            LOG.debug("Doing authentication and authorization for path {}", path);
            switch (Authenticator.authenticate(configuration.getRealm(), configuration.getRole(), configuration.getRolePrincipalClasses(),
                    configuration.getConfiguration(), httpRequest, new PrivilegedCallback() {
                public void execute(Subject subject) throws Exception {
                    executeAs(request, response, chain, subject);
                }
            })) {
                case AUTHORIZED:
                    // request was executed using the authenticated subject, nothing more to do
                    break;
                case NOT_AUTHORIZED:
                    Helpers.doForbidden((HttpServletResponse) response);
                    break;
                case NO_CREDENTIALS:
                    //doAuthPrompt((HttpServletResponse)response);
                    Helpers.doForbidden((HttpServletResponse) response);
                    break;
            }
        } else {
            LOG.warn("No authentication needed for path {}", path);
            chain.doFilter(request, response);
        }
    }
//  [java]
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String path = httpRequest.getServletPath();
        LOG.debug("Handling request for path {}", path);

        if (configuration.getRealm() == null || configuration.getRealm().equals("") || !configuration.isEnabled()) {
            LOG.debug("No authentication needed for path {}", path);
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = httpRequest.getSession(false);
        if (session != null) {
            Subject subject = (Subject) session.getAttribute("subject");
            if (subject != null) {
                LOG.debug("Session subject {}", subject);
                executeAs(request, response, chain, subject);
                return;
            }
        }

        boolean doAuthenticate = path.startsWith("/auth") ||
                path.startsWith("/jolokia") ||
                path.startsWith("/upload");

        if (doAuthenticate) {
            LOG.debug("Doing authentication and authorization for path {}", path);
            switch (Authenticator.authenticate(configuration.getRealm(), configuration.getRole(), configuration.getRolePrincipalClasses(),
                    configuration.getConfiguration(), httpRequest, new PrivilegedCallback() {
                public void execute(Subject subject) throws Exception {
                    executeAs(request, response, chain, subject);
                }
            })) {
                case AUTHORIZED:
                    // request was executed using the authenticated subject, nothing more to do
                    break;
                case NOT_AUTHORIZED:
                    Helpers.doForbidden((HttpServletResponse) response);
                    break;
                case NO_CREDENTIALS:
                    //doAuthPrompt((HttpServletResponse)response);
                    Helpers.doForbidden((HttpServletResponse) response);
                    break;
            }
        } else {
            LOG.debug("No authentication needed for path {}", path);
            chain.doFilter(request, response);
        }
    }
//  [java]
    public JiffleRuntime getRuntimeInstance(Jiffle.RuntimeModel model) throws
            it.geosolutions.jaiext.jiffle.JiffleException {
        return createRuntimeInstance(model, getRuntimeBaseClass(model), includeScript);
    }
//  [java]
    public JiffleRuntime getRuntimeInstance(Jiffle.RuntimeModel model) throws
            it.geosolutions.jaiext.jiffle.JiffleException {
        return createRuntimeInstance(model, getRuntimeBaseClass(model), false);
    }
//  [java]
    public void translate(GeyserSession session, ServerSpawnPositionPacket packet) {
        SetSpawnPositionPacket spawnPositionPacket = new SetSpawnPositionPacket();
        spawnPositionPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));
        spawnPositionPacket.setSpawnForced(true);
        spawnPositionPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension()));
        spawnPositionPacket.setSpawnType(SetSpawnPositionPacket.Type.WORLD_SPAWN);
        session.sendUpstreamPacket(spawnPositionPacket);
    }
//  [java]
    public void translate(ServerSpawnPositionPacket packet, GeyserSession session) {
        SetSpawnPositionPacket spawnPositionPacket = new SetSpawnPositionPacket();
        spawnPositionPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));
        spawnPositionPacket.setSpawnForced(true);
        spawnPositionPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension()));
        spawnPositionPacket.setSpawnType(SetSpawnPositionPacket.Type.WORLD_SPAWN);
        session.sendUpstreamPacket(spawnPositionPacket);
    }
//  [java]
    public void corsEmpty() {
        InputStream is = getClass().getResourceAsStream("/allow-origin3.xml");
        PolicyRestrictor restrictor = new PolicyRestrictor(is);

        assertTrue(restrictor.isOriginAllowed("http://bla.com", false));
        assertTrue(restrictor.isOriginAllowed("http://www.jolokia.org", false));
        assertTrue(restrictor.isOriginAllowed("http://www.consol.de", false));
    }
//  [java]
    public void corsEmpty() {
        InputStream is = getClass().getResourceAsStream("/allow-origin3.xml");
        PolicyRestrictor restrictor = new PolicyRestrictor(is);

        assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
        assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
        assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de"));
    }
//  [java]
    public void translate(GeyserSession session, ContainerClosePacket packet) {
        byte windowId = packet.getId();

        //Client wants close confirmation
        session.sendUpstreamPacket(packet);
        session.setClosingInventory(false);

        if (windowId == -1 && session.getOpenInventory() instanceof MerchantContainer) {
            // 1.16.200 - window ID is always -1 sent from Bedrock
            windowId = (byte) session.getOpenInventory().getId();
        }

        Inventory openInventory = session.getOpenInventory();
        if (openInventory != null) {
            if (windowId == openInventory.getId()) {
                ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(windowId);
                session.sendDownstreamPacket(closeWindowPacket);
                InventoryUtils.closeInventory(session, windowId, false);
            } else if (openInventory.isPending()) {
                InventoryUtils.displayInventory(session, openInventory);
                openInventory.setPending(false);
            }
        }
    }
//  [java]
    public void translate(ContainerClosePacket packet, GeyserSession session) {
        byte windowId = packet.getId();

        //Client wants close confirmation
        session.sendUpstreamPacket(packet);
        session.setClosingInventory(false);

        if (windowId == -1 && session.getOpenInventory() instanceof MerchantContainer) {
            // 1.16.200 - window ID is always -1 sent from Bedrock
            windowId = (byte) session.getOpenInventory().getId();
        }

        Inventory openInventory = session.getOpenInventory();
        if (openInventory != null) {
            if (windowId == openInventory.getId()) {
                ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(windowId);
                session.sendDownstreamPacket(closeWindowPacket);
                InventoryUtils.closeInventory(session, windowId, false);
            } else if (openInventory.isPending()) {
                InventoryUtils.displayInventory(session, openInventory);
                openInventory.setPending(false);
            }
        }
    }
//  [java]
    public void corsNoTags() {
        InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
        PolicyRestrictor restrictor = new PolicyRestrictor(is);

        assertTrue(restrictor.isOriginAllowed("http://bla.com", false));
        assertTrue(restrictor.isOriginAllowed("http://www.jolokia.org", false));
        assertTrue(restrictor.isOriginAllowed("https://www.consol.de", false));
    }
//  [java]
    public void corsNoTags() {
        InputStream is = getClass().getResourceAsStream("/access-sample1.xml");
        PolicyRestrictor restrictor = new PolicyRestrictor(is);

        assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
        assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
        assertTrue(restrictor.isCorsAccessAllowed("https://www.consol.de"));
    }
//  [java]
	public static ResourceEvaluation evaluate(File file, String filename) {
		ResourceEvaluation eval = new ResourceEvaluation();
		try {
			ImsManifestFileFilter visitor = new ImsManifestFileFilter();
			Path fPath = PathUtils.visit(file, filename, visitor);
			if(visitor.isValid()) {
				Path realManifestPath = visitor.getManifestPath();
				Path manifestPath = fPath.resolve(realManifestPath);
				
				RootSearcher rootSearcher = new RootSearcher();
				Files.walkFileTree(fPath, EnumSet.noneOf(FileVisitOption.class), 16, rootSearcher);
				if(rootSearcher.foundRoot()) {
					manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);
				} else {
					manifestPath = fPath.resolve(IMS_MANIFEST);
				}
				
				Document doc = IMSLoader.loadIMSDocument(manifestPath);
				if(validateImsManifest(doc)) {
					eval.setValid(true);
				} else {
					eval.setValid(false);
				}
			} else {
				eval.setValid(false);
			}
			PathUtils.closeSubsequentFS(fPath);
		} catch (IOException | IllegalArgumentException e) {
			log.error("", e);
			eval.setValid(false);
		}
		return eval;
	}
//  [java]
	public static ResourceEvaluation evaluate(File file, String filename) {
		ResourceEvaluation eval = new ResourceEvaluation();
		try {
			ImsManifestFileFilter visitor = new ImsManifestFileFilter();
			Path fPath = PathUtils.visit(file, filename, visitor);
			if(visitor.isValid()) {
				Path realManifestPath = visitor.getManifestPath();
				Path manifestPath = fPath.resolve(realManifestPath);
				
				RootSearcher rootSearcher = new RootSearcher();
				Files.walkFileTree(fPath, rootSearcher);
				if(rootSearcher.foundRoot()) {
					manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);
				} else {
					manifestPath = fPath.resolve(IMS_MANIFEST);
				}
				
				Document doc = IMSLoader.loadIMSDocument(manifestPath);
				if(validateImsManifest(doc)) {
					eval.setValid(true);
				} else {
					eval.setValid(false);
				}
			} else {
				eval.setValid(false);
			}
			PathUtils.closeSubsequentFS(fPath);
		} catch (IOException | IllegalArgumentException e) {
			log.error("", e);
			eval.setValid(false);
		}
		return eval;
	}
//  [java]
    public void corsWildCard() {
        InputStream is = getClass().getResourceAsStream("/allow-origin2.xml");
        PolicyRestrictor restrictor = new PolicyRestrictor(is);

        assertTrue(restrictor.isOriginAllowed("http://bla.com", false));
        assertTrue(restrictor.isOriginAllowed("http://www.jolokia.org", false));
        assertTrue(restrictor.isOriginAllowed("http://www.consol.de", false));
    }
//  [java]
    public void corsWildCard() {
        InputStream is = getClass().getResourceAsStream("/allow-origin2.xml");
        PolicyRestrictor restrictor = new PolicyRestrictor(is);

        assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
        assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
        assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de"));
    }
//  [java]
    public void cors() {
        InputStream is = getClass().getResourceAsStream("/allow-origin4.xml");
        PolicyRestrictor restrictor = new PolicyRestrictor(is);

        for (boolean strict : new boolean[] {true, false}) {
            assertTrue(restrictor.isOriginAllowed("http://bla.com", strict));
            assertFalse(restrictor.isOriginAllowed("http://www.jolokia.org", strict));
            assertTrue(restrictor.isOriginAllowed("https://www.consol.de", strict));
        }
    }
//  [java]
    public void cors() {
        InputStream is = getClass().getResourceAsStream("/allow-origin1.xml");
        PolicyRestrictor restrictor = new PolicyRestrictor(is);

        assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
        assertFalse(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
        assertTrue(restrictor.isCorsAccessAllowed("https://www.consol.de"));
    }
//  [java]
    protected HtmlRenderable htmlBody() {
        return sequence(
                HtmlElement.div(cssClass("dir-container")).content(
                    HtmlElement.span(cssClass("directory")).content(
                        HtmlElement.a(onclick("BuildDetail.tree_navigator(this)"))
                                .safecontent(getFileName())
                    )
                ),
                HtmlElement.div(cssClass("subdir-container"), style("display:none"))
                        .content(subDirectory)
        );
    }
//  [java]
    protected HtmlRenderable htmlBody() {
        return sequence(
                HtmlElement.div(cssClass("dir-container")).content(
                    HtmlElement.span(cssClass("directory")).content(
                        HtmlElement.a(onclick("BuildDetail.tree_navigator(this)"))
                                .content(getFileName())
                    )
                ),
                HtmlElement.div(cssClass("subdir-container"), style("display:none"))
                        .content(subDirectory)
        );
    }
//  [java]
    public static String printFormattedMetadata(final IBaseDataObject payload) {
        final StringBuilder out = new StringBuilder();
        out.append(LS);
        for (final Map.Entry<String, Collection<Object>> entry : payload.getParameters().entrySet()) {
            out.append(entry.getKey()).append(SEP).append(entry.getValue()).append(LS);
        }
        return out.toString();
    }
//  [java]
    public static String printFormattedMetadata(final IBaseDataObject payload) {
        final StringBuilder out = new StringBuilder();
        out.append(LS);
        for (final Map.Entry<String, Collection<Object>> entry : payload.getParameters().entrySet()) {
            out.append(entry.getKey() + SEP + entry.getValue() + LS);
        }
        return out.toString();
    }
//  [java]
    public void testArgumentsWithsemicolon()
    {

        System.out.println( "---- semi colon tests ----" );

        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/bin" );
        sh.setExecutable( "chmod" );

        String[] args = { ";some&argwithunix$chars" };

        List shellCommandLine = sh.getShellCommandLine( args );

        String cli = StringUtils.join( shellCommandLine.iterator(), " " );
        System.out.println( cli );
        assertTrue( cli.endsWith( "\'" + args[0] + "\'" ) );

        Commandline commandline = new Commandline( newShell() );
        commandline.setExecutable( "chmod" );
        commandline.getShell().setQuotedArgumentsEnabled( true );
        commandline.createArg().setValue( "--password" );
        commandline.createArg().setValue( ";password" );

        String[] lines = commandline.getShellCommandline();
        System.out.println( Arrays.asList( lines ) );

        assertEquals( "/bin/sh", lines[0] );
        assertEquals( "-c", lines[1] );
        assertEquals( "'chmod' '--password' ';password'", lines[2] );

        commandline = new Commandline( newShell() );
        commandline.setExecutable( "chmod" );
        commandline.getShell().setQuotedArgumentsEnabled( true );
        commandline.createArg().setValue( "--password" );
        commandline.createArg().setValue( ";password" );
        lines = commandline.getShellCommandline();
        System.out.println( Arrays.asList( lines ) );

        assertEquals( "/bin/sh", lines[0] );
        assertEquals( "-c", lines[1] );
        assertEquals( "'chmod' '--password' ';password'", lines[2] );

        commandline = new Commandline( new CmdShell() );
        commandline.getShell().setQuotedArgumentsEnabled( true );
        commandline.createArg().setValue( "--password" );
        commandline.createArg().setValue( ";password" );
        lines = commandline.getShellCommandline();
        System.out.println( Arrays.asList( lines ) );

        assertEquals( "cmd.exe", lines[0] );
        assertEquals( "/X", lines[1] );
        assertEquals( "/C", lines[2] );
        assertEquals( "\"--password ;password\"", lines[3] );
    }
//  [java]
    public void testArgumentsWithsemicolon()
    {

        System.out.println( "---- semi colon tests ----" );

        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/bin" );
        sh.setExecutable( "chmod" );

        String[] args = { ";some&argwithunix$chars" };

        List shellCommandLine = sh.getShellCommandLine( args );

        String cli = StringUtils.join( shellCommandLine.iterator(), " " );
        System.out.println( cli );
        assertTrue( cli.endsWith( "\'" + args[0] + "\'" ) );

        Commandline commandline = new Commandline( newShell() );
        commandline.setExecutable( "chmod" );
        commandline.getShell().setQuotedArgumentsEnabled( true );
        commandline.createArg().setValue( "--password" );
        commandline.createArg().setValue( ";password" );

        String[] lines = commandline.getShellCommandline();
        System.out.println( Arrays.asList( lines ) );

        assertEquals( "/bin/sh", lines[0] );
        assertEquals( "-c", lines[1] );
        assertEquals( "chmod --password ';password'", lines[2] );

        commandline = new Commandline( newShell() );
        commandline.setExecutable( "chmod" );
        commandline.getShell().setQuotedArgumentsEnabled( true );
        commandline.createArg().setValue( "--password" );
        commandline.createArg().setValue( ";password" );
        lines = commandline.getShellCommandline();
        System.out.println( Arrays.asList( lines ) );

        assertEquals( "/bin/sh", lines[0] );
        assertEquals( "-c", lines[1] );
        assertEquals( "chmod --password ';password'", lines[2] );

        commandline = new Commandline( new CmdShell() );
        commandline.getShell().setQuotedArgumentsEnabled( true );
        commandline.createArg().setValue( "--password" );
        commandline.createArg().setValue( ";password" );
        lines = commandline.getShellCommandline();
        System.out.println( Arrays.asList( lines ) );

        assertEquals( "cmd.exe", lines[0] );
        assertEquals( "/X", lines[1] );
        assertEquals( "/C", lines[2] );
        assertEquals( "\"--password ;password\"", lines[3] );
    }
//  [java]
    public void testPreserveSingleQuotesOnArgument()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/bin" );
        sh.setExecutable( "chmod" );

        String[] args = { "\'some arg with spaces\'" };

        List shellCommandLine = sh.getShellCommandLine( args );

        String cli = StringUtils.join( shellCommandLine.iterator(), " " );
        System.out.println( cli );
        assertTrue( cli.endsWith("''\"'\"'some arg with spaces'\"'\"''"));
    }
//  [java]
    public void testPreserveSingleQuotesOnArgument()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/bin" );
        sh.setExecutable( "chmod" );

        String[] args = { "\'some arg with spaces\'" };

        List shellCommandLine = sh.getShellCommandLine( args );

        String cli = StringUtils.join( shellCommandLine.iterator(), " " );
        System.out.println( cli );
        assertTrue( cli.endsWith( args[0] ) );
    }
//  [java]
    public static Document toXml(final IBaseDataObject d) {
        final Element root = new Element("payload");
        root.addContent(JDOMUtil.protectedElement("name", d.getFilename()));
        final Element cf = new Element("current-forms");
        for (final String c : d.getAllCurrentForms()) {
            cf.addContent(JDOMUtil.simpleElement("current-form", c));
        }
        root.addContent(cf);
        root.addContent(JDOMUtil.simpleElement("encoding", d.getFontEncoding()));
        root.addContent(JDOMUtil.simpleElement("filetype", d.getFileType()));
        root.addContent(JDOMUtil.simpleElement("classification", d.getClassification()));
        final Element th = new Element("transform-history");
        for (final String s : d.transformHistory()) {
            th.addContent(JDOMUtil.simpleElement("itinerary-step", s));
        }
        root.addContent(th);
        if (d.getProcessingError() != null) {
            root.addContent(JDOMUtil.simpleElement("processing-error", d.getProcessingError()));
        }
        final Element meta = new Element("metadata");
        for (final String key : d.getParameters().keySet()) {
            final Element m = JDOMUtil.protectedElement("param", d.getStringParameter(key));
            m.setAttribute("name", key);
            meta.addContent(m);
        }
        root.addContent(meta);

        if (d.header() != null) {
            root.addContent(JDOMUtil.protectedElement("header", d.header()));
        }
        if (d.dataLength() > 0) {
            root.addContent(JDOMUtil.protectedElement("data", d.data()));
        }
        if (d.footer() != null) {
            root.addContent(JDOMUtil.protectedElement("footer", d.footer()));
        }

        // Alt views
        if (d.getNumAlternateViews() > 0) {
            final Element views = new Element("views");
            for (final String av : d.getAlternateViewNames()) {
                final Element v = JDOMUtil.protectedElement("view", d.getAlternateView(av));
                v.setAttribute("name", av);
                views.addContent(v);
            }
            root.addContent(views);
        }

        logger.debug("Produced xml document for " + d.shortName());
        return new Document(root);
    }
//  [java]
    public static Document toXml(final List<IBaseDataObject> list) {
        final Element root = new Element("payload-list");
        for (final IBaseDataObject d : list) {
            final Document doc = toXml(d);
            root.addContent(doc.detachRootElement());
            logger.debug("Adding xml content for " + d.shortName() + " to document");
        }
        final Document doc = new Document(root);
        return doc;
    }
//  [java]
    public void testQuoteWorkingDirectoryAndExecutable()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/local/bin" );
        sh.setExecutable( "chmod" );

        String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );

        assertEquals( "/bin/sh -c cd '/usr/local/bin' && 'chmod'", executable );
    }
//  [java]
    public void testQuoteWorkingDirectoryAndExecutable()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/local/bin" );
        sh.setExecutable( "chmod" );

        String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );

        assertEquals( "/bin/sh -c cd /usr/local/bin && chmod", executable );
    }
//  [java]
    public void testBourneShellQuotingCharacters()
        throws Exception
    {
        // { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')' };
        // test with values http://steve-parker.org/sh/bourne.shtml Appendix B - Meta-characters and Reserved Words
        Commandline commandline = new Commandline( newShell() );
        commandline.setExecutable( "chmod" );
        commandline.getShell().setQuotedArgumentsEnabled( true );
        commandline.createArg().setValue( " " );
        commandline.createArg().setValue( "|" );
        commandline.createArg().setValue( "&&" );
        commandline.createArg().setValue( "||" );
        commandline.createArg().setValue( ";" );
        commandline.createArg().setValue( ";;" );
        commandline.createArg().setValue( "&" );
        commandline.createArg().setValue( "()" );
        commandline.createArg().setValue( "<" );
        commandline.createArg().setValue( "<<" );
        commandline.createArg().setValue( ">" );
        commandline.createArg().setValue( ">>" );
        commandline.createArg().setValue( "*" );
        commandline.createArg().setValue( "?" );
        commandline.createArg().setValue( "[" );
        commandline.createArg().setValue( "]" );
        commandline.createArg().setValue( "{" );
        commandline.createArg().setValue( "}" );
        commandline.createArg().setValue( "`" );

        String[] lines = commandline.getShellCommandline();
        System.out.println( Arrays.asList( lines ) );

        assertEquals( "/bin/sh", lines[0] );
        assertEquals( "-c", lines[1] );
        assertEquals( "'chmod' ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'",
                      lines[2] );

    }
//  [java]
    public void testBourneShellQuotingCharacters()
        throws Exception
    {
        // { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')' };
        // test with values http://steve-parker.org/sh/bourne.shtml Appendix B - Meta-characters and Reserved Words
        Commandline commandline = new Commandline( newShell() );
        commandline.setExecutable( "chmod" );
        commandline.getShell().setQuotedArgumentsEnabled( true );
        commandline.createArg().setValue( " " );
        commandline.createArg().setValue( "|" );
        commandline.createArg().setValue( "&&" );
        commandline.createArg().setValue( "||" );
        commandline.createArg().setValue( ";" );
        commandline.createArg().setValue( ";;" );
        commandline.createArg().setValue( "&" );
        commandline.createArg().setValue( "()" );
        commandline.createArg().setValue( "<" );
        commandline.createArg().setValue( "<<" );
        commandline.createArg().setValue( ">" );
        commandline.createArg().setValue( ">>" );
        commandline.createArg().setValue( "*" );
        commandline.createArg().setValue( "?" );
        commandline.createArg().setValue( "[" );
        commandline.createArg().setValue( "]" );
        commandline.createArg().setValue( "{" );
        commandline.createArg().setValue( "}" );
        commandline.createArg().setValue( "`" );

        String[] lines = commandline.getShellCommandline();
        System.out.println( Arrays.asList( lines ) );

        assertEquals( "/bin/sh", lines[0] );
        assertEquals( "-c", lines[1] );
        assertEquals( "chmod ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'",
                      lines[2] );

    }
//  [java]
    public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/local/'something else'" );
        sh.setExecutable( "chmod" );

        String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );

        assertEquals( "/bin/sh -c cd '/usr/local/'\"'\"'something else'\"'\"'' && 'chmod'", executable );
    }
//  [java]
    public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/local/'something else'" );
        sh.setExecutable( "chmod" );

        String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );

        assertEquals( "/bin/sh -c cd \"/usr/local/\'something else\'\" && chmod", executable );
    }
//  [java]
    public void testEscapeSingleQuotesOnArgument()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/bin" );
        sh.setExecutable( "chmod" );

        String[] args = { "arg'withquote" };

        List shellCommandLine = sh.getShellCommandLine( args );

        String cli = StringUtils.join( shellCommandLine.iterator(), " " );
        System.out.println( cli );
        assertEquals("cd '/usr/bin' && 'chmod' 'arg'\"'\"'withquote'", shellCommandLine.get(shellCommandLine.size() - 1));
    }
//  [java]
    public void testEscapeSingleQuotesOnArgument()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "/usr/bin" );
        sh.setExecutable( "chmod" );

        String[] args = { "arg'withquote" };

        List shellCommandLine = sh.getShellCommandLine( args );

        String cli = StringUtils.join( shellCommandLine.iterator(), " " );
        System.out.println( cli );
        assertEquals("cd /usr/bin && chmod 'arg'\\''withquote'", shellCommandLine.get(shellCommandLine.size() - 1));
    }
//  [java]
	public Player(String title, ISkinParam skinParam, TimingRuler ruler, boolean compact, Stereotype stereotype) {
		this.stereotype = stereotype;
		this.skinParam = skinParam;
		this.compact = compact;
		this.ruler = ruler;
		this.title = Display.getWithNewlines(title);
	}
//  [java]
	public Player(String title, ISkinParam skinParam, TimingRuler ruler, boolean compact) {
		this.skinParam = skinParam;
		this.compact = compact;
		this.ruler = ruler;
		this.title = Display.getWithNewlines(title);
	}
//  [java]
    public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "\\usr\\local\\'something else'" );
        sh.setExecutable( "chmod" );

        String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );

        assertEquals( "/bin/sh -c cd '\\usr\\local\\\'\"'\"'something else'\"'\"'' && 'chmod'", executable );
    }
//  [java]
    public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep()
    {
        Shell sh = newShell();

        sh.setWorkingDirectory( "\\usr\\local\\'something else'" );
        sh.setExecutable( "chmod" );

        String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );

        assertEquals( "/bin/sh -c cd \"\\usr\\local\\\'something else\'\" && chmod", executable );
    }
//  [java]
    static boolean nameContainsForbiddenSequence(String name) {
        boolean result = false;
        if (name != null) {
            name = name.toLowerCase();
    
            result = name.startsWith(".") ||
                     name.contains("../") ||
                     name.contains("..\\") ||
                     name.startsWith("/") ||
                     name.startsWith("\\") ||
                     name.endsWith("/") ||
    
                     name.contains("..%2f") ||
                     name.contains("..%5c") ||
                     name.startsWith("%2f") ||
                     name.startsWith("%5c") ||
                     name.endsWith("%2f") ||
    
                     name.contains("..\\u002f") ||
                     name.contains("..\\u005c") ||
                     name.startsWith("\\u002f") ||
                     name.startsWith("\\u005c") ||
                     name.endsWith("\\u002f")
    
                    ;
        }
        
        return result;
    }
//  [java]
    private static boolean nameContainsForbiddenSequence(String name) {
        boolean result = false;
        if (name != null) {
            name = name.toLowerCase();
    
            result = name.startsWith(".") ||
                     name.contains("../") ||
                     name.contains("..\\") ||
                     name.startsWith("/") ||
                     name.startsWith("\\") ||
                     name.endsWith("/") ||
    
                     name.contains("..%2f") ||
                     name.contains("..%5c") ||
                     name.startsWith("%2f") ||
                     name.startsWith("%5c") ||
                     name.endsWith("%2f") ||
    
                     name.contains("..\\u002f") ||
                     name.contains("..\\u005c") ||
                     name.startsWith("\\u002f") ||
                     name.startsWith("\\u005c") ||
                     name.endsWith("\\u002f")
    
                    ;
        }
        
        return result;
    }
//  [java]
    public String accessToken(String username) {
        Algorithm algorithm = Algorithm.HMAC256(tokenSecret);

        return JWT.create()
                .withExpiresAt(new Date(new Date().getTime() + ACCESS_EXPIRE_TIME))
                .withIssuer(ISSUER)
                .withClaim("username", username)
                .sign(algorithm);
    }
//  [java]
    public String accessToken(String username) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);

        return JWT.create()
                .withExpiresAt(new Date(new Date().getTime() + ACCESS_EXPIRE_TIME))
                .withIssuer(ISSUER)
                .withClaim("username", username)
                .sign(algorithm);
    }
//  [java]
    public static int getStatusCode(HttpsURLConnection conn) {
        try {
            return conn.getResponseCode();
        } catch (IOException e) {
            throw ErrorUtil
                    .createCommandException("connection to the remote repository host failed: " + e.getMessage());
        }
    }
//  [java]
    public static int getStatusCode(HttpURLConnection conn) {
        try {
            return conn.getResponseCode();
        } catch (IOException e) {
            throw ErrorUtil
                    .createCommandException("connection to the remote repository host failed: " + e.getMessage());
        }
    }
//  [java]
    public static void setRequestMethod(HttpsURLConnection conn, RequestMethod method) {
        try {
            conn.setRequestMethod(getRequestMethodAsString(method));
        } catch (ProtocolException e) {
            throw ErrorUtil.createCommandException(e.getMessage());
        }
    }
//  [java]
    public static void setRequestMethod(HttpURLConnection conn, RequestMethod method) {
        try {
            conn.setRequestMethod(getRequestMethodAsString(method));
        } catch (ProtocolException e) {
            throw ErrorUtil.createCommandException(e.getMessage());
        }
    }
//  [java]
    public boolean verify(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(tokenSecret))
                .withIssuer(ISSUER)
                .build();
        try {
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            log.warn("verify jwt token failed " + e.getMessage());
            return false;
        }
    }
//  [java]
    public boolean verify(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET))
                .withIssuer(ISSUER)
                .build();
        try {
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            log.warn("verify jwt token failed " + e.getMessage());
            return false;
        }
    }
//  [java]
    public void shouldNotAllowToListFileOutsideRoot() throws Exception {
        // given
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage(containsString("may not be located outside base path"));

        // when
        logViewEndpoint.view("../somefile", null, null, null);
    }
//  [java]
    public void shouldNotAllowToListFileOutsideRoot() throws Exception {
        // given
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage(containsString("this String argument must not contain the substring [..]"));

        // when
        logViewEndpoint.view("../somefile", null, null, null);
    }
//  [java]
    public boolean isAvailable() {
        return GeoTools.isJNDIAvailable();
    }
//  [java]
    public boolean isAvailable() {
        try {
            GeoTools.getInitialContext();
            return true;
        } catch (NamingException e) {
            return false;
        }
    }
//  [java]
	final protected FontConfiguration getFontConfiguration() {
		return FontConfiguration.create(skinParam, StyleSignatureBasic
				.of(SName.root, SName.element, SName.timingDiagram).getMergedStyle(skinParam.getCurrentStyleBuilder()));
	}
//  [java]
	final protected FontConfiguration getFontConfiguration() {
		if (UseStyle.useBetaStyle() == false)
			return FontConfiguration.create(skinParam, FontParam.TIMING, null);
		return FontConfiguration.create(skinParam, StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram)
				.getMergedStyle(skinParam.getCurrentStyleBuilder()));
	}
//  [java]
    public void translate(GeyserSession session, CommandRequestPacket packet) {
        String command = packet.getCommand().replace("/", "");
        CommandManager commandManager = GeyserConnector.getInstance().getCommandManager();
        if (session.getConnector().getPlatformType() == PlatformType.STANDALONE && command.trim().startsWith("geyser ") && commandManager.getCommands().containsKey(command.split(" ")[1])) {
            commandManager.runCommand(session, command);
        } else {
            String message = packet.getCommand().trim();

            if (MessageTranslator.isTooLong(message, session)) {
                return;
            }

            ClientChatPacket chatPacket = new ClientChatPacket(message);
            session.sendDownstreamPacket(chatPacket);
        }
    }
//  [java]
    public void translate(CommandRequestPacket packet, GeyserSession session) {
        String command = packet.getCommand().replace("/", "");
        CommandManager commandManager = GeyserConnector.getInstance().getCommandManager();
        if (session.getConnector().getPlatformType() == PlatformType.STANDALONE && command.trim().startsWith("geyser ") && commandManager.getCommands().containsKey(command.split(" ")[1])) {
            commandManager.runCommand(session, command);
        } else {
            String message = packet.getCommand().trim();

            if (MessageTranslator.isTooLong(message, session)) {
                return;
            }

            ClientChatPacket chatPacket = new ClientChatPacket(message);
            session.sendDownstreamPacket(chatPacket);
        }
    }
//  [java]
    public UploadFileResponse getCloudUrl(String contextPath, String uri, String finalFilePath, HttpServletRequest request) {
        UploadFileResponse uploadFileResponse = new UploadFileResponse();
        // try push to cloud
        Map<String, String[]> map = new HashMap<>();
        map.put("fileInfo", new String[]{finalFilePath + "," + uri});
        map.put("name", new String[]{"uploadService"});
        String url;
        try {
            List<Map> urls = HttpUtil.getInstance().sendGetRequest(Constants.pluginServer + "/service", map
                    , new HttpJsonArrayHandle<Map>(), PluginHelper.genHeaderMapByRequest(request, AdminTokenThreadLocal.getUser())).getT();
            if (urls != null && !urls.isEmpty()) {
                url = (String) urls.get(0).get("url");
                if (!url.startsWith("https://") && !url.startsWith("http://")) {
                    String tUrl = url;
                    if (!url.startsWith("/")) {
                        tUrl = "/" + url;
                    }
                    url = contextPath + tUrl;
                }
            } else {
                url = contextPath + uri;
            }
        } catch (Exception e) {
            url = contextPath + uri;
            LOGGER.error(e);
        }
        uploadFileResponse.setUrl(url);
        return uploadFileResponse;
    }
//  [java]
    public UploadFileResponse getCloudUrl(String contextPath, String uri, String finalFilePath, HttpServletRequest request) {
        UploadFileResponse uploadFileResponse = new UploadFileResponse();
        // try push to cloud
        Map<String, String[]> map = new HashMap<>();
        map.put("fileInfo", new String[]{finalFilePath + "," + uri});
        map.put("name", new String[]{"uploadService"});
        String url;
        try {
            List<Map> urls = HttpUtil.getInstance().sendGetRequest(Constants.pluginServer + "/service", map
                    , new HttpJsonArrayHandle<Map>(), PluginHelper.genHeaderMapByRequest(request)).getT();
            if (urls != null && !urls.isEmpty()) {
                url = (String) urls.get(0).get("url");
                if (!url.startsWith("https://") && !url.startsWith("http://")) {
                    String tUrl = url;
                    if (!url.startsWith("/")) {
                        tUrl = "/" + url;
                    }
                    url = contextPath + tUrl;
                }
            } else {
                url = contextPath + uri;
            }
        } catch (Exception e) {
            url = contextPath + uri;
            LOGGER.error(e);
        }
        uploadFileResponse.setUrl(url);
        return uploadFileResponse;
    }
//  [java]
    public void translate(GeyserSession session, EmoteListPacket packet) {
        if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
            return;
        }

        session.refreshEmotes(packet.getPieceIds());
    }
//  [java]
    public void translate(EmoteListPacket packet, GeyserSession session) {
        if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
            return;
        }

        session.refreshEmotes(packet.getPieceIds());
    }
//  [java]
    protected DataSource createDataSource(Map<String, ?> params, SQLDialect dialect)
            throws IOException {
        String jndiName = (String) JNDI_REFNAME.lookUp(params);
        if (jndiName == null) throw new IOException("Missing " + JNDI_REFNAME.description);

        DataSource ds = null;

        try {
            ds = (DataSource) GeoTools.jndiLookup(jndiName);
        } catch (NamingException e1) {
            // check if the user did not specify "java:comp/env"
            // and this code is running in a J2EE environment
            try {
                if (jndiName.startsWith(J2EERootContext) == false) {
                    ds = (DataSource) GeoTools.jndiLookup(J2EERootContext + jndiName);
                    // success --> issue a waring
                    Logger.getLogger(this.getClass().getName())
                            .log(
                                    Level.WARNING,
                                    "Using "
                                            + J2EERootContext
                                            + jndiName
                                            + " instead of "
                                            + jndiName
                                            + " would avoid an unnecessary JNDI lookup");
                }
            } catch (NamingException e2) {
                // do nothing, was only a try
            }
        }

        if (ds == null) throw new IOException("Cannot find JNDI data source: " + jndiName);
        else return ds;
    }